2 * proflog.c: mono log profiler
5 * Paolo Molaro (lupus@ximian.com)
6 * Alex Rønne Petersen (alexrp@xamarin.com)
8 * Copyright 2010 Novell, Inc (http://www.novell.com)
9 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
10 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
14 #include "../mini/jit.h"
15 #include "../metadata/metadata-internals.h"
16 #include <mono/metadata/profiler.h>
17 #include <mono/metadata/threads.h>
18 #include <mono/metadata/mono-gc.h>
19 #include <mono/metadata/debug-helpers.h>
20 #include <mono/metadata/mono-perfcounters.h>
21 #include <mono/metadata/appdomain.h>
22 #include <mono/metadata/assembly.h>
23 #include <mono/metadata/tokentype.h>
24 #include <mono/metadata/tabledefs.h>
25 #include <mono/utils/atomic.h>
26 #include <mono/utils/mono-membar.h>
27 #include <mono/utils/mono-mmap.h>
28 #include <mono/utils/mono-counters.h>
29 #include <mono/utils/mono-os-mutex.h>
30 #include <mono/utils/mono-os-semaphore.h>
31 #include <mono/utils/mono-conc-hashtable.h>
32 #include <mono/utils/mono-linked-list-set.h>
33 #include <mono/utils/lock-free-alloc.h>
34 #include <mono/utils/lock-free-queue.h>
35 #include <mono/utils/hazard-pointer.h>
36 #include <mono/utils/mono-threads.h>
37 #include <mono/utils/mono-threads-api.h>
45 #ifdef HAVE_SCHED_GETAFFINITY
50 #if defined(HOST_WIN32) || defined(DISABLE_SOCKETS)
51 #define DISABLE_HELPER_THREAD 1
60 #ifdef HAVE_EXECINFO_H
67 #ifndef DISABLE_HELPER_THREAD
68 #include <sys/types.h>
69 #include <sys/socket.h>
70 #include <netinet/in.h>
71 #include <sys/select.h>
80 #ifdef HAVE_SYS_STAT_H
87 #if defined (HAVE_SYS_ZLIB)
91 #if defined(__linux__)
94 #include <sys/syscall.h>
96 #ifdef ENABLE_PERF_EVENTS
97 #include <linux/perf_event.h>
99 #define USE_PERF_EVENTS 1
101 static int read_perf_mmap (MonoProfiler* prof, int cpu);
106 #define BUFFER_SIZE (4096 * 16)
108 /* Worst-case size in bytes of a 64-bit value encoded with LEB128. */
109 #define LEB128_SIZE 10
110 /* Size in bytes of the event ID prefix. */
113 static int nocalls = 0;
114 static int notraces = 0;
115 static int use_zip = 0;
116 static int do_report = 0;
117 static int do_heap_shot = 0;
118 static int max_call_depth = 100;
119 static volatile int runtime_inited = 0;
120 static int need_helper_thread = 0;
121 static int command_port = 0;
122 static int heapshot_requested = 0;
123 static int sample_type = 0;
124 static int sample_freq = 0;
125 static int do_mono_sample = 0;
126 static int in_shutdown = 0;
127 static int do_debug = 0;
128 static int do_counters = 0;
129 static int do_coverage = 0;
130 static gboolean debug_coverage = FALSE;
131 static MonoProfileSamplingMode sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
132 static int max_allocated_sample_hits;
134 static gint32 sample_hits;
135 static gint32 sample_flushes;
136 static gint32 sample_allocations;
137 static gint32 buffer_allocations;
138 static gint32 thread_starts;
139 static gint32 thread_ends;
140 static gint32 domain_loads;
141 static gint32 domain_unloads;
142 static gint32 context_loads;
143 static gint32 context_unloads;
144 static gint32 assembly_loads;
145 static gint32 assembly_unloads;
146 static gint32 image_loads;
147 static gint32 image_unloads;
148 static gint32 class_loads;
149 static gint32 class_unloads;
151 static MonoLinkedListSet profiler_thread_list;
157 * The file is composed by a header followed by 0 or more buffers.
158 * Each buffer contains events that happened on a thread: for a given thread
159 * buffers that appear later in the file are guaranteed to contain events
160 * that happened later in time. Buffers from separate threads could be interleaved,
162 * Buffers are not required to be aligned.
165 * [id: 4 bytes] constant value: LOG_HEADER_ID
166 * [major: 1 byte] [minor: 1 byte] major and minor version of the log profiler
167 * [format: 1 byte] version of the data format for the rest of the file
168 * [ptrsize: 1 byte] size in bytes of a pointer in the profiled program
169 * [startup time: 8 bytes] time in milliseconds since the unix epoch when the program started
170 * [timer overhead: 4 bytes] approximate overhead in nanoseconds of the timer
171 * [flags: 4 bytes] file format flags, should be 0 for now
172 * [pid: 4 bytes] pid of the profiled process
173 * [port: 2 bytes] tcp port for server if != 0
174 * [sysid: 2 bytes] operating system and architecture identifier
176 * The multiple byte integers are in little-endian format.
179 * [buffer header] [event]*
180 * Buffers have a fixed-size header followed by 0 or more bytes of event data.
181 * Timing information and other values in the event data are usually stored
182 * as uleb128 or sleb128 integers. To save space, as noted for each item below,
183 * some data is represented as a difference between the actual value and
184 * either the last value of the same type (like for timing information) or
185 * as the difference from a value stored in a buffer header.
187 * For timing information the data is stored as uleb128, since timing
188 * increases in a monotonic way in each thread: the value is the number of
189 * nanoseconds to add to the last seen timing data in a buffer. The first value
190 * in a buffer will be calculated from the time_base field in the buffer head.
192 * Object or heap sizes are stored as uleb128.
193 * Pointer differences are stored as sleb128, instead.
195 * If an unexpected value is found, the rest of the buffer should be ignored,
196 * as generally the later values need the former to be interpreted correctly.
198 * buffer header format:
199 * [bufid: 4 bytes] constant value: BUF_ID
200 * [len: 4 bytes] size of the data following the buffer header
201 * [time_base: 8 bytes] time base in nanoseconds since an unspecified epoch
202 * [ptr_base: 8 bytes] base value for pointers
203 * [obj_base: 8 bytes] base value for object addresses
204 * [thread id: 8 bytes] system-specific thread ID (pthread_t for example)
205 * [method_base: 8 bytes] base value for MonoMethod pointers
208 * [extended info: upper 4 bits] [type: lower 4 bits] [data]*
209 * The data that follows depends on type and the extended info.
210 * Type is one of the enum values in proflog.h: TYPE_ALLOC, TYPE_GC,
211 * TYPE_METADATA, TYPE_METHOD, TYPE_EXCEPTION, TYPE_MONITOR, TYPE_HEAP.
212 * The extended info bits are interpreted based on type, see
213 * each individual event description below.
214 * strings are represented as a 0-terminated utf8 sequence.
217 * [flags: uleb128] must be 0
218 * [num: uleb128] number of frames following
219 * [frame: sleb128]* num MonoMethod pointers as differences from ptr_base
223 * exinfo: flags: TYPE_ALLOC_BT
224 * [time diff: uleb128] nanoseconds since last timing
225 * [ptr: sleb128] class as a byte difference from ptr_base
226 * [obj: sleb128] object address as a byte difference from obj_base
227 * [size: uleb128] size of the object in the heap
228 * If the TYPE_ALLOC_BT flag is set, a backtrace follows.
232 * exinfo: one of TYPE_GC_EVENT, TYPE_GC_RESIZE, TYPE_GC_MOVE, TYPE_GC_HANDLE_CREATED[_BT],
233 * TYPE_GC_HANDLE_DESTROYED[_BT]
234 * [time diff: uleb128] nanoseconds since last timing
235 * if exinfo == TYPE_GC_RESIZE
236 * [heap_size: uleb128] new heap size
237 * if exinfo == TYPE_GC_EVENT
238 * [event type: uleb128] GC event (MONO_GC_EVENT_* from profiler.h)
239 * [generation: uleb128] GC generation event refers to
240 * if exinfo == TYPE_GC_MOVE
241 * [num_objects: uleb128] number of object moves that follow
242 * [objaddr: sleb128]+ num_objects object pointer differences from obj_base
243 * num is always an even number: the even items are the old
244 * addresses, the odd numbers are the respective new object addresses
245 * if exinfo == TYPE_GC_HANDLE_CREATED[_BT]
246 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
247 * upper bits reserved as flags
248 * [handle: uleb128] GC handle value
249 * [objaddr: sleb128] object pointer differences from obj_base
250 * If exinfo == TYPE_GC_HANDLE_CREATED_BT, a backtrace follows.
251 * if exinfo == TYPE_GC_HANDLE_DESTROYED[_BT]
252 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
253 * upper bits reserved as flags
254 * [handle: uleb128] GC handle value
255 * If exinfo == TYPE_GC_HANDLE_DESTROYED_BT, a backtrace follows.
257 * type metadata format:
258 * type: TYPE_METADATA
259 * exinfo: one of: TYPE_END_LOAD, TYPE_END_UNLOAD (optional for TYPE_THREAD and TYPE_DOMAIN)
260 * [time diff: uleb128] nanoseconds since last timing
261 * [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
262 * TYPE_THREAD, TYPE_CONTEXT
263 * [pointer: sleb128] pointer of the metadata type depending on mtype
264 * if mtype == TYPE_CLASS
265 * [image: sleb128] MonoImage* as a pointer difference from ptr_base
266 * [flags: uleb128] must be 0
267 * [name: string] full class name
268 * if mtype == TYPE_IMAGE
269 * [flags: uleb128] must be 0
270 * [name: string] image file name
271 * if mtype == TYPE_ASSEMBLY
272 * [flags: uleb128] must be 0
273 * [name: string] assembly name
274 * if mtype == TYPE_DOMAIN
275 * [flags: uleb128] must be 0
276 * if mtype == TYPE_DOMAIN && exinfo == 0
277 * [name: string] domain friendly name
278 * if mtype == TYPE_CONTEXT
279 * [flags: uleb128] must be 0
280 * [domain: sleb128] domain id as pointer
281 * if mtype == TYPE_THREAD && (format_version < 11 || (format_version > 10 && exinfo == 0))
282 * [flags: uleb128] must be 0
283 * [name: string] thread name
285 * type method format:
287 * exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
288 * [time diff: uleb128] nanoseconds since last timing
289 * [method: sleb128] MonoMethod* as a pointer difference from the last such
290 * pointer or the buffer method_base
291 * if exinfo == TYPE_JIT
292 * [code address: sleb128] pointer to the native code as a diff from ptr_base
293 * [code size: uleb128] size of the generated code
294 * [name: string] full method name
296 * type runtime format:
298 * exinfo: one of: TYPE_JITHELPER
299 * [time diff: uleb128] nanoseconds since last timing
300 * if exinfo == TYPE_JITHELPER
301 * [type: uleb128] MonoProfilerCodeBufferType enum value
302 * [buffer address: sleb128] pointer to the native code as a diff from ptr_base
303 * [buffer size: uleb128] size of the generated code
304 * if type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE
305 * [name: string] buffer description name
307 * type monitor format:
309 * exinfo: TYPE_MONITOR_BT flag and one of: MONO_PROFILER_MONITOR_(CONTENTION|FAIL|DONE)
310 * [time diff: uleb128] nanoseconds since last timing
311 * [object: sleb128] the lock object as a difference from obj_base
312 * if exinfo.low3bits == MONO_PROFILER_MONITOR_CONTENTION
313 * If the TYPE_MONITOR_BT flag is set, a backtrace follows.
317 * exinfo: one of TYPE_HEAP_START, TYPE_HEAP_END, TYPE_HEAP_OBJECT, TYPE_HEAP_ROOT
318 * if exinfo == TYPE_HEAP_START
319 * [time diff: uleb128] nanoseconds since last timing
320 * if exinfo == TYPE_HEAP_END
321 * [time diff: uleb128] nanoseconds since last timing
322 * if exinfo == TYPE_HEAP_OBJECT
323 * [object: sleb128] the object as a difference from obj_base
324 * [class: sleb128] the object MonoClass* as a difference from ptr_base
325 * [size: uleb128] size of the object on the heap
326 * [num_refs: uleb128] number of object references
327 * if (format version > 1) each referenced objref is preceded by a
328 * uleb128 encoded offset: the first offset is from the object address
329 * and each next offset is relative to the previous one
330 * [objrefs: sleb128]+ object referenced as a difference from obj_base
331 * The same object can appear multiple times, but only the first time
332 * with size != 0: in the other cases this data will only be used to
333 * provide additional referenced objects.
334 * if exinfo == TYPE_HEAP_ROOT
335 * [num_roots: uleb128] number of root references
336 * [num_gc: uleb128] number of major gcs
337 * [object: sleb128] the object as a difference from obj_base
338 * [root_type: uleb128] the root_type: MonoProfileGCRootType (profiler.h)
339 * [extra_info: uleb128] the extra_info value
340 * object, root_type and extra_info are repeated num_roots times
344 * exinfo: one of TYPE_SAMPLE_HIT, TYPE_SAMPLE_USYM, TYPE_SAMPLE_UBIN, TYPE_SAMPLE_COUNTERS_DESC, TYPE_SAMPLE_COUNTERS
345 * if exinfo == TYPE_SAMPLE_HIT
346 * [sample_type: uleb128] type of sample (SAMPLE_*)
347 * [timestamp: uleb128] nanoseconds since startup (note: different from other timestamps!)
348 * if (format_version > 10)
349 * [thread: sleb128] thread id as difference from ptr_base
350 * [count: uleb128] number of following instruction addresses
351 * [ip: sleb128]* instruction pointer as difference from ptr_base
352 * if (format_version > 5)
353 * [mbt_count: uleb128] number of managed backtrace info triplets (method + IL offset + native offset)
354 * [method: sleb128]* MonoMethod* as a pointer difference from the last such
355 * pointer or the buffer method_base (the first such method can be also indentified by ip, but this is not neccessarily true)
356 * [il_offset: sleb128]* IL offset inside method where the hit occurred
357 * [native_offset: sleb128]* native offset inside method where the hit occurred
358 * if exinfo == TYPE_SAMPLE_USYM
359 * [address: sleb128] symbol address as a difference from ptr_base
360 * [size: uleb128] symbol size (may be 0 if unknown)
361 * [name: string] symbol name
362 * if exinfo == TYPE_SAMPLE_UBIN
363 * [time diff: uleb128] nanoseconds since last timing
364 * [address: sleb128] address where binary has been loaded
365 * [offset: uleb128] file offset of mapping (the same file can be mapped multiple times)
366 * [size: uleb128] memory size
367 * [name: string] binary name
368 * if exinfo == TYPE_SAMPLE_COUNTERS_DESC
369 * [len: uleb128] number of counters
371 * [section: uleb128] section of counter
372 * if section == MONO_COUNTER_PERFCOUNTERS:
373 * [section_name: string] section name of counter
374 * [name: string] name of counter
375 * [type: uleb128] type of counter
376 * [unit: uleb128] unit of counter
377 * [variance: uleb128] variance of counter
378 * [index: uleb128] unique index of counter
379 * if exinfo == TYPE_SAMPLE_COUNTERS
380 * [timestamp: uleb128] sampling timestamp
382 * [index: uleb128] unique index of counter
385 * [type: uleb128] type of counter value
388 * [0: uleb128] 0 -> value is null
390 * [1: uleb128] 1 -> value is not null
391 * [value: string] counter value
393 * [value: uleb128/sleb128/double] counter value, can be sleb128, uleb128 or double (determined by using type)
395 * type coverage format
396 * type: TYPE_COVERAGE
397 * exinfo: one of TYPE_COVERAGE_METHOD, TYPE_COVERAGE_STATEMENT, TYPE_COVERAGE_ASSEMBLY, TYPE_COVERAGE_CLASS
398 * if exinfo == TYPE_COVERAGE_METHOD
399 * [assembly: string] name of assembly
400 * [class: string] name of the class
401 * [name: string] name of the method
402 * [signature: string] the signature of the method
403 * [filename: string] the file path of the file that contains this method
404 * [token: uleb128] the method token
405 * [method_id: uleb128] an ID for this data to associate with the buffers of TYPE_COVERAGE_STATEMENTS
406 * [len: uleb128] the number of TYPE_COVERAGE_BUFFERS associated with this method
407 * if exinfo == TYPE_COVERAGE_STATEMENTS
408 * [method_id: uleb128] an the TYPE_COVERAGE_METHOD buffer to associate this with
409 * [offset: uleb128] the il offset relative to the previous offset
410 * [counter: uleb128] the counter for this instruction
411 * [line: uleb128] the line of filename containing this instruction
412 * [column: uleb128] the column containing this instruction
413 * if exinfo == TYPE_COVERAGE_ASSEMBLY
414 * [name: string] assembly name
415 * [guid: string] assembly GUID
416 * [filename: string] assembly filename
417 * [number_of_methods: uleb128] the number of methods in this assembly
418 * [fully_covered: uleb128] the number of fully covered methods
419 * [partially_covered: uleb128] the number of partially covered methods
420 * currently partially_covered will always be 0, and fully_covered is the
421 * number of methods that are fully and partially covered.
422 * if exinfo == TYPE_COVERAGE_CLASS
423 * [name: string] assembly name
424 * [class: string] class name
425 * [number_of_methods: uleb128] the number of methods in this class
426 * [fully_covered: uleb128] the number of fully covered methods
427 * [partially_covered: uleb128] the number of partially covered methods
428 * currently partially_covered will always be 0, and fully_covered is the
429 * number of methods that are fully and partially covered.
433 * Format oddities that we ought to fix:
435 * - Methods written in emit_bt () should be based on the buffer's base
436 * method instead of the base pointer.
437 * - The TYPE_SAMPLE_HIT event contains (currently) pointless data like
438 * always-one unmanaged frame count and always-zero IL offsets.
440 * These are mostly small things and are not worth a format change by
441 * themselves. They should be done when some other major change has to
442 * be done to the format.
445 // Pending data to be written to the log, for a single thread.
446 // Threads periodically flush their own LogBuffers by calling safe_send
447 typedef struct _LogBuffer LogBuffer;
449 // Next (older) LogBuffer in processing queue
455 uintptr_t method_base;
456 uintptr_t last_method;
460 // Bytes allocated for this LogBuffer
463 // Start of currently unused space in buffer
464 unsigned char* cursor;
466 // Pointer to start-of-structure-plus-size (for convenience)
467 unsigned char* buf_end;
469 // Start of data in buffer. Contents follow "buffer format" described above.
470 unsigned char buf [1];
474 MonoLinkedListSetNode node;
476 // The current log buffer for this thread.
479 // Methods referenced by events in `buffer`, see `MethodInfo`.
482 // Current call depth for enter/leave events.
485 // Indicates whether this thread is currently writing to its `buffer`.
487 } MonoProfilerThread;
490 ign_res (int G_GNUC_UNUSED unused, ...)
495 * These macros create a scope to avoid leaking the buffer returned
496 * from ensure_logbuf () as it may have been invalidated by a GC
497 * thread during STW. If you called init_thread () with add_to_lls =
498 * FALSE, then don't use these macros.
504 g_assert (!PROF_TLS_GET ()->busy++ && "Why are we trying to write a new event while already writing one?")
507 PROF_TLS_GET ()->busy--; \
511 static volatile gint32 buffer_rwlock_count;
512 static volatile gpointer buffer_rwlock_exclusive;
514 // Can be used recursively.
519 * If the thread holding the exclusive lock tries to modify the
520 * reader count, just make it a no-op. This way, we also avoid
521 * invoking the GC safe point macros below, which could break if
522 * done from a thread that is currently the initiator of STW.
524 * In other words, we rely on the fact that the GC thread takes
525 * the exclusive lock in the gc_event () callback when the world
528 if (InterlockedReadPointer (&buffer_rwlock_exclusive) != (gpointer) thread_id ()) {
531 while (InterlockedReadPointer (&buffer_rwlock_exclusive))
532 mono_thread_info_yield ();
534 InterlockedIncrement (&buffer_rwlock_count);
539 mono_memory_barrier ();
545 mono_memory_barrier ();
547 // See the comment in buffer_lock ().
548 if (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id ())
551 g_assert (InterlockedRead (&buffer_rwlock_count) && "Why are we trying to decrement a zero reader count?");
553 InterlockedDecrement (&buffer_rwlock_count);
556 // Cannot be used recursively.
558 buffer_lock_excl (void)
560 gpointer tid = (gpointer) thread_id ();
562 g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) != tid && "Why are we taking the exclusive lock twice?");
566 while (InterlockedCompareExchangePointer (&buffer_rwlock_exclusive, tid, 0))
567 mono_thread_info_yield ();
569 while (InterlockedRead (&buffer_rwlock_count))
570 mono_thread_info_yield ();
574 mono_memory_barrier ();
578 buffer_unlock_excl (void)
580 mono_memory_barrier ();
582 g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) && "Why is the exclusive lock not held?");
583 g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id () && "Why does another thread hold the exclusive lock?");
584 g_assert (!InterlockedRead (&buffer_rwlock_count) && "Why are there readers when the exclusive lock is held?");
586 InterlockedWritePointer (&buffer_rwlock_exclusive, NULL);
589 typedef struct _BinaryObject BinaryObject;
590 struct _BinaryObject {
596 struct _MonoProfiler {
598 #if defined (HAVE_SYS_ZLIB)
601 uint64_t startup_time;
603 int last_gc_gen_started;
608 pthread_t helper_thread;
609 pthread_t writer_thread;
610 pthread_t dumper_thread;
612 volatile gint32 run_writer_thread;
613 MonoLockFreeAllocSizeClass writer_entry_size_class;
614 MonoLockFreeAllocator writer_entry_allocator;
615 MonoLockFreeQueue writer_queue;
616 MonoSemType writer_queue_sem;
617 MonoConcurrentHashTable *method_table;
618 mono_mutex_t method_table_mutex;
619 volatile gint32 run_dumper_thread;
620 MonoLockFreeQueue dumper_queue;
621 MonoSemType dumper_queue_sem;
622 MonoLockFreeAllocSizeClass sample_size_class;
623 MonoLockFreeAllocator sample_allocator;
624 MonoLockFreeQueue sample_reuse_queue;
625 BinaryObject *binary_objects;
626 GPtrArray *coverage_filters;
630 MonoLockFreeQueueNode node;
635 #define WRITER_ENTRY_BLOCK_SIZE (mono_pagesize ())
645 #define PROF_TLS_SET(VAL) (TlsSetValue (profiler_tls, (VAL)))
646 #define PROF_TLS_GET() ((MonoProfilerThread *) TlsGetValue (profiler_tls))
647 #define PROF_TLS_INIT() (profiler_tls = TlsAlloc ())
648 #define PROF_TLS_FREE() (TlsFree (profiler_tls))
650 static DWORD profiler_tls;
654 #define PROF_TLS_SET(VAL) (profiler_tls = (VAL))
655 #define PROF_TLS_GET() (profiler_tls)
656 #define PROF_TLS_INIT()
657 #define PROF_TLS_FREE()
659 static __thread MonoProfilerThread *profiler_tls;
663 #define PROF_TLS_SET(VAL) (pthread_setspecific (profiler_tls, (VAL)))
664 #define PROF_TLS_GET() ((MonoProfilerThread *) pthread_getspecific (profiler_tls))
665 #define PROF_TLS_INIT() (pthread_key_create (&profiler_tls, NULL))
666 #define PROF_TLS_FREE() (pthread_key_delete (&profiler_tls))
668 static pthread_key_t profiler_tls;
673 pstrdup (const char *s)
675 int len = strlen (s) + 1;
676 char *p = (char *)malloc (len);
684 LogBuffer* buf = (LogBuffer *)alloc_buffer (BUFFER_SIZE);
686 InterlockedIncrement (&buffer_allocations);
688 buf->size = BUFFER_SIZE;
689 buf->time_base = current_time ();
690 buf->last_time = buf->time_base;
691 buf->buf_end = (unsigned char*)buf + buf->size;
692 buf->cursor = buf->buf;
697 init_buffer_state (MonoProfilerThread *thread)
699 thread->buffer = create_buffer ();
700 thread->methods = NULL;
704 clear_hazard_pointers (MonoThreadHazardPointers *hp)
706 mono_hazard_pointer_clear (hp, 0);
707 mono_hazard_pointer_clear (hp, 1);
708 mono_hazard_pointer_clear (hp, 2);
711 static MonoProfilerThread *
712 init_thread (gboolean add_to_lls)
714 MonoProfilerThread *thread = PROF_TLS_GET ();
717 * Sometimes we may try to initialize a thread twice. One example is the
718 * main thread: We initialize it when setting up the profiler, but we will
719 * also get a thread_start () callback for it. Another example is when
720 * attaching new threads to the runtime: We may get a gc_alloc () callback
721 * for that thread's thread object (where we initialize it), soon followed
722 * by a thread_start () callback.
724 * These cases are harmless anyhow. Just return if we've already done the
725 * initialization work.
730 thread = malloc (sizeof (MonoProfilerThread));
731 thread->node.key = thread_id ();
732 thread->call_depth = 0;
735 init_buffer_state (thread);
738 * Some internal profiler threads don't need to be cleaned up
739 * by the main thread on shutdown.
742 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
743 g_assert (mono_lls_insert (&profiler_thread_list, hp, &thread->node) && "Why can't we insert the thread in the LLS?");
744 clear_hazard_pointers (hp);
747 PROF_TLS_SET (thread);
752 // Only valid if init_thread () was called with add_to_lls = FALSE.
754 deinit_thread (MonoProfilerThread *thread)
761 ensure_logbuf_inner (LogBuffer *old, int bytes)
763 if (old && old->cursor + bytes + 100 < old->buf_end)
766 LogBuffer *new_ = create_buffer ();
772 // Only valid if init_thread () was called with add_to_lls = FALSE.
774 ensure_logbuf_unsafe (int bytes)
776 MonoProfilerThread *thread = PROF_TLS_GET ();
777 LogBuffer *old = thread->buffer;
778 LogBuffer *new_ = ensure_logbuf_inner (old, bytes);
781 return old; // Still enough space.
783 thread->buffer = new_;
789 * Any calls to this function should be wrapped in the ENTER_LOG and
790 * EXIT_LOG macros to prevent the returned pointer from leaking
791 * outside of the critical region created by the calls to buffer_lock ()
792 * and buffer_unlock () that those macros insert. If the pointer leaks,
793 * it can and will lead to crashes as the GC or helper thread may
794 * invalidate the pointer at any time.
796 * Note: If you're calling from a thread that called init_thread () with
797 * add_to_lls = FALSE, you should use ensure_logbuf_unsafe () and omit
801 ensure_logbuf (int bytes)
803 g_assert (PROF_TLS_GET ()->busy && "Why are we trying to expand our buffer without the busy flag set?");
805 return ensure_logbuf_unsafe (bytes);
809 emit_byte (LogBuffer *logbuffer, int value)
811 logbuffer->cursor [0] = value;
813 assert (logbuffer->cursor <= logbuffer->buf_end);
817 emit_value (LogBuffer *logbuffer, int value)
819 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
820 assert (logbuffer->cursor <= logbuffer->buf_end);
824 emit_time (LogBuffer *logbuffer, uint64_t value)
826 uint64_t tdiff = value - logbuffer->last_time;
827 //if (value < logbuffer->last_time)
828 // printf ("time went backwards\n");
829 //if (tdiff > 1000000)
830 // printf ("large time offset: %llu\n", tdiff);
831 encode_uleb128 (tdiff, logbuffer->cursor, &logbuffer->cursor);
832 /*if (tdiff != decode_uleb128 (p, &p))
833 printf ("incorrect encoding: %llu\n", tdiff);*/
834 logbuffer->last_time = value;
835 assert (logbuffer->cursor <= logbuffer->buf_end);
839 emit_svalue (LogBuffer *logbuffer, int64_t value)
841 encode_sleb128 (value, logbuffer->cursor, &logbuffer->cursor);
842 assert (logbuffer->cursor <= logbuffer->buf_end);
846 emit_uvalue (LogBuffer *logbuffer, uint64_t value)
848 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
849 assert (logbuffer->cursor <= logbuffer->buf_end);
853 emit_ptr (LogBuffer *logbuffer, void *ptr)
855 if (!logbuffer->ptr_base)
856 logbuffer->ptr_base = (uintptr_t)ptr;
857 emit_svalue (logbuffer, (intptr_t)ptr - logbuffer->ptr_base);
858 assert (logbuffer->cursor <= logbuffer->buf_end);
862 emit_method_inner (LogBuffer *logbuffer, void *method)
864 if (!logbuffer->method_base) {
865 logbuffer->method_base = (intptr_t)method;
866 logbuffer->last_method = (intptr_t)method;
868 encode_sleb128 ((intptr_t)((char*)method - (char*)logbuffer->last_method), logbuffer->cursor, &logbuffer->cursor);
869 logbuffer->last_method = (intptr_t)method;
870 assert (logbuffer->cursor <= logbuffer->buf_end);
880 find_method (MonoDomain *domain, void *user_data)
882 MethodSearch *search = user_data;
887 MonoJitInfo *ji = mono_get_jit_info_from_method (domain, search->method);
889 // It could be AOT'd, so we need to get it from the AOT runtime's cache.
891 void *ip = mono_aot_get_method (domain, search->method);
893 // Avoid a slow path in mono_jit_info_table_find ().
895 ji = mono_jit_info_table_find (domain, ip);
904 register_method_local (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji)
906 if (!mono_conc_hashtable_lookup (prof->method_table, method)) {
908 * FIXME: In some cases, we crash while looking up JIT info for AOT'd methods.
909 * This usually happens for static constructors. This code is disabled for now
910 * as we don't need this info for anything critical.
912 * https://bugzilla.xamarin.com/show_bug.cgi?id=35171
916 MethodSearch search = { method, NULL };
918 mono_domain_foreach (find_method, &search);
925 * FIXME: We can't always find JIT info for a generic shared method, especially
926 * if we obtained the MonoMethod during an async stack walk. For now, we deal
927 * with this by giving the generic shared method name and dummy code start/size
928 * information (i.e. zeroes).
932 MethodInfo *info = (MethodInfo *) malloc (sizeof (MethodInfo));
934 info->method = method;
936 info->time = current_time ();
938 MonoProfilerThread *thread = PROF_TLS_GET ();
939 GPtrArray *arr = thread->methods ? thread->methods : (thread->methods = g_ptr_array_new ());
940 g_ptr_array_add (arr, info);
945 emit_method (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
947 register_method_local (prof, method, NULL);
948 emit_method_inner (logbuffer, method);
952 emit_method_as_ptr (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
954 register_method_local (prof, method, NULL);
955 emit_ptr (logbuffer, method);
959 emit_obj (LogBuffer *logbuffer, void *ptr)
961 if (!logbuffer->obj_base)
962 logbuffer->obj_base = (uintptr_t)ptr >> 3;
963 emit_svalue (logbuffer, ((uintptr_t)ptr >> 3) - logbuffer->obj_base);
964 assert (logbuffer->cursor <= logbuffer->buf_end);
968 emit_string (LogBuffer *logbuffer, const char *str, size_t size)
972 for (; i < size; i++) {
975 emit_byte (logbuffer, str [i]);
978 emit_byte (logbuffer, '\0');
982 emit_double (LogBuffer *logbuffer, double value)
985 unsigned char buffer[8];
986 memcpy (buffer, &value, 8);
987 #if G_BYTE_ORDER == G_BIG_ENDIAN
988 for (i = 7; i >= 0; i--)
990 for (i = 0; i < 8; i++)
992 emit_byte (logbuffer, buffer[i]);
996 write_int16 (char *buf, int32_t value)
999 for (i = 0; i < 2; ++i) {
1007 write_int32 (char *buf, int32_t value)
1010 for (i = 0; i < 4; ++i) {
1018 write_int64 (char *buf, int64_t value)
1021 for (i = 0; i < 8; ++i) {
1029 dump_header (MonoProfiler *profiler)
1033 p = write_int32 (p, LOG_HEADER_ID);
1034 *p++ = LOG_VERSION_MAJOR;
1035 *p++ = LOG_VERSION_MINOR;
1036 *p++ = LOG_DATA_VERSION;
1037 *p++ = sizeof (void*);
1038 p = write_int64 (p, ((uint64_t)time (NULL)) * 1000); /* startup time */
1039 p = write_int32 (p, get_timer_overhead ()); /* timer overhead */
1040 p = write_int32 (p, 0); /* flags */
1041 p = write_int32 (p, process_id ()); /* pid */
1042 p = write_int16 (p, profiler->command_port); /* port */
1043 p = write_int16 (p, 0); /* opsystem */
1044 #if defined (HAVE_SYS_ZLIB)
1045 if (profiler->gzfile) {
1046 gzwrite (profiler->gzfile, hbuf, p - hbuf);
1048 fwrite (hbuf, p - hbuf, 1, profiler->file);
1051 fwrite (hbuf, p - hbuf, 1, profiler->file);
1052 fflush (profiler->file);
1057 send_buffer (MonoProfiler *prof, MonoProfilerThread *thread)
1059 WriterQueueEntry *entry = mono_lock_free_alloc (&prof->writer_entry_allocator);
1060 entry->methods = thread->methods;
1061 entry->buffer = thread->buffer;
1063 mono_lock_free_queue_node_init (&entry->node, FALSE);
1065 mono_lock_free_queue_enqueue (&prof->writer_queue, &entry->node);
1066 mono_os_sem_post (&prof->writer_queue_sem);
1070 remove_thread (MonoProfiler *prof, MonoProfilerThread *thread, gboolean from_callback)
1072 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
1074 if (mono_lls_remove (&profiler_thread_list, hp, &thread->node)) {
1075 LogBuffer *buffer = thread->buffer;
1078 * No need to take the buffer lock here as no other threads can
1079 * be accessing this buffer anymore.
1082 if (!from_callback) {
1084 * The thread is being cleaned up by the main thread during
1085 * shutdown. This typically happens for internal runtime
1086 * threads. We need to synthesize a thread end event.
1089 buffer = ensure_logbuf_inner (buffer,
1090 EVENT_SIZE /* event */ +
1091 LEB128_SIZE /* time */ +
1092 EVENT_SIZE /* type */ +
1093 LEB128_SIZE /* tid */ +
1094 LEB128_SIZE /* flags */
1097 uint64_t now = current_time ();
1099 emit_byte (buffer, TYPE_END_UNLOAD | TYPE_METADATA);
1100 emit_time (buffer, now);
1101 emit_byte (buffer, TYPE_THREAD);
1102 emit_ptr (buffer, (void *) thread->node.key);
1103 emit_value (buffer, 0); /* flags */
1106 send_buffer (prof, thread);
1108 mono_thread_hazardous_try_free (thread, free);
1111 clear_hazard_pointers (hp);
1114 PROF_TLS_SET (NULL);
1118 dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
1123 dump_buffer (profiler, buf->next);
1124 p = write_int32 (p, BUF_ID);
1125 p = write_int32 (p, buf->cursor - buf->buf);
1126 p = write_int64 (p, buf->time_base);
1127 p = write_int64 (p, buf->ptr_base);
1128 p = write_int64 (p, buf->obj_base);
1129 p = write_int64 (p, buf->thread_id);
1130 p = write_int64 (p, buf->method_base);
1131 #if defined (HAVE_SYS_ZLIB)
1132 if (profiler->gzfile) {
1133 gzwrite (profiler->gzfile, hbuf, p - hbuf);
1134 gzwrite (profiler->gzfile, buf->buf, buf->cursor - buf->buf);
1137 fwrite (hbuf, p - hbuf, 1, profiler->file);
1138 fwrite (buf->buf, buf->cursor - buf->buf, 1, profiler->file);
1139 fflush (profiler->file);
1140 #if defined (HAVE_SYS_ZLIB)
1143 free_buffer (buf, buf->size);
1147 dump_buffer_threadless (MonoProfiler *profiler, LogBuffer *buf)
1149 for (LogBuffer *iter = buf; iter; iter = iter->next)
1150 iter->thread_id = 0;
1152 dump_buffer (profiler, buf);
1156 process_requests (MonoProfiler *profiler)
1158 if (heapshot_requested)
1159 mono_gc_collect (mono_gc_max_generation ());
1162 static void counters_init (MonoProfiler *profiler);
1163 static void counters_sample (MonoProfiler *profiler, uint64_t timestamp, gboolean threadless);
1166 safe_send (MonoProfiler *profiler)
1168 /* We need the runtime initialized so that we have threads and hazard
1169 * pointers available. Otherwise, the lock free queue will not work and
1170 * there won't be a thread to process the data.
1172 * While the runtime isn't initialized, we just accumulate data in the
1173 * thread local buffer list.
1175 if (!InterlockedRead (&runtime_inited))
1178 MonoProfilerThread *thread = PROF_TLS_GET ();
1182 send_buffer (profiler, thread);
1183 init_buffer_state (thread);
1189 send_if_needed (MonoProfiler *prof)
1191 if (PROF_TLS_GET ()->buffer->next)
1196 safe_send_threadless (MonoProfiler *prof)
1198 LogBuffer *buf = PROF_TLS_GET ()->buffer;
1200 for (LogBuffer *iter = buf; iter; iter = iter->next)
1201 iter->thread_id = 0;
1207 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
1209 /* account for object alignment in the heap */
1215 LogBuffer *logbuffer = ensure_logbuf (
1216 EVENT_SIZE /* event */ +
1217 LEB128_SIZE /* obj */ +
1218 LEB128_SIZE /* klass */ +
1219 LEB128_SIZE /* size */ +
1220 LEB128_SIZE /* num */ +
1222 LEB128_SIZE /* offset */ +
1223 LEB128_SIZE /* ref */
1227 emit_byte (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
1228 emit_obj (logbuffer, obj);
1229 emit_ptr (logbuffer, klass);
1230 emit_value (logbuffer, size);
1231 emit_value (logbuffer, num);
1233 uintptr_t last_offset = 0;
1235 for (int i = 0; i < num; ++i) {
1236 emit_value (logbuffer, offsets [i] - last_offset);
1237 last_offset = offsets [i];
1238 emit_obj (logbuffer, refs [i]);
1246 static unsigned int hs_mode_ms = 0;
1247 static unsigned int hs_mode_gc = 0;
1248 static unsigned int hs_mode_ondemand = 0;
1249 static unsigned int gc_count = 0;
1250 static uint64_t last_hs_time = 0;
1253 heap_walk (MonoProfiler *profiler)
1258 gboolean do_walk = 0;
1259 uint64_t now = current_time ();
1261 if (hs_mode_ms && (now - last_hs_time) / 1000000 >= hs_mode_ms)
1263 else if (hs_mode_gc && (gc_count % hs_mode_gc) == 0)
1265 else if (hs_mode_ondemand)
1266 do_walk = heapshot_requested;
1267 else if (!hs_mode_ms && !hs_mode_gc && profiler->last_gc_gen_started == mono_gc_max_generation ())
1273 heapshot_requested = 0;
1277 LogBuffer *logbuffer = ensure_logbuf (
1278 EVENT_SIZE /* event */ +
1279 LEB128_SIZE /* time */
1282 emit_byte (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
1283 emit_time (logbuffer, now);
1287 mono_gc_walk_heap (0, gc_reference, NULL);
1291 LogBuffer *logbuffer = ensure_logbuf (
1292 EVENT_SIZE /* event */ +
1293 LEB128_SIZE /* time */
1296 now = current_time ();
1298 emit_byte (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
1299 emit_time (logbuffer, now);
1307 gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation)
1311 LogBuffer *logbuffer = ensure_logbuf (
1312 EVENT_SIZE /* event */ +
1313 LEB128_SIZE /* time */ +
1314 LEB128_SIZE /* gc event */ +
1315 LEB128_SIZE /* generation */
1318 uint64_t now = current_time ();
1320 emit_byte (logbuffer, TYPE_GC_EVENT | TYPE_GC);
1321 emit_time (logbuffer, now);
1322 emit_value (logbuffer, ev);
1323 emit_value (logbuffer, generation);
1328 case MONO_GC_EVENT_START:
1329 /* to deal with nested gen1 after gen0 started */
1330 profiler->last_gc_gen_started = generation;
1332 if (generation == mono_gc_max_generation ())
1335 case MONO_GC_EVENT_PRE_STOP_WORLD:
1337 * Ensure that no thread can be in the middle of writing to
1338 * a buffer when the world stops...
1340 buffer_lock_excl ();
1342 case MONO_GC_EVENT_POST_STOP_WORLD:
1344 * ... So that we now have a consistent view of all buffers.
1345 * This allows us to flush them. We need to do this because
1346 * they may contain object allocation events that need to be
1347 * committed to the log file before any object move events
1348 * that will be produced during this GC.
1350 g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id () && "Why don't we hold the exclusive lock?");
1352 MONO_LLS_FOREACH_SAFE (&profiler_thread_list, MonoProfilerThread, thread) {
1353 send_buffer (profiler, thread);
1354 init_buffer_state (thread);
1355 } MONO_LLS_FOREACH_SAFE_END
1357 case MONO_GC_EVENT_PRE_START_WORLD:
1358 heap_walk (profiler);
1360 case MONO_GC_EVENT_POST_START_WORLD:
1362 * Similarly, we must now make sure that any object moves
1363 * written to the GC thread's buffer are flushed. Otherwise,
1364 * object allocation events for certain addresses could come
1365 * after the move events that made those addresses available.
1367 safe_send (profiler);
1370 * Finally, it is safe to allow other threads to write to
1371 * their buffers again.
1373 buffer_unlock_excl ();
1381 gc_resize (MonoProfiler *profiler, int64_t new_size)
1385 LogBuffer *logbuffer = ensure_logbuf (
1386 EVENT_SIZE /* event */ +
1387 LEB128_SIZE /* time */ +
1388 LEB128_SIZE /* new size */
1391 uint64_t now = current_time ();
1393 emit_byte (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
1394 emit_time (logbuffer, now);
1395 emit_value (logbuffer, new_size);
1400 // If you alter MAX_FRAMES, you may need to alter SAMPLE_BLOCK_SIZE too.
1401 #define MAX_FRAMES 32
1405 MonoMethod* methods [MAX_FRAMES];
1406 int32_t il_offsets [MAX_FRAMES];
1407 int32_t native_offsets [MAX_FRAMES];
1410 static int num_frames = MAX_FRAMES;
1413 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
1415 FrameData *frame = (FrameData *)data;
1416 if (method && frame->count < num_frames) {
1417 frame->il_offsets [frame->count] = il_offset;
1418 frame->native_offsets [frame->count] = native_offset;
1419 frame->methods [frame->count++] = method;
1420 //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
1422 return frame->count == num_frames;
1426 * a note about stack walks: they can cause more profiler events to fire,
1427 * so we need to make sure they don't happen after we started emitting an
1428 * event, hence the collect_bt/emit_bt split.
1431 collect_bt (FrameData *data)
1434 mono_stack_walk_no_il (walk_stack, data);
1438 emit_bt (MonoProfiler *prof, LogBuffer *logbuffer, FrameData *data)
1440 /* FIXME: this is actually tons of data and we should
1441 * just output it the first time and use an id the next
1443 if (data->count > num_frames)
1444 printf ("bad num frames: %d\n", data->count);
1445 emit_value (logbuffer, 0); /* flags */
1446 emit_value (logbuffer, data->count);
1447 //if (*p != data.count) {
1448 // 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);}
1449 while (data->count) {
1450 emit_method_as_ptr (prof, logbuffer, data->methods [--data->count]);
1455 gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1459 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces) ? TYPE_ALLOC_BT : 0;
1461 uintptr_t len = mono_object_get_size (obj);
1462 /* account for object alignment in the heap */
1471 LogBuffer *logbuffer = ensure_logbuf (
1472 EVENT_SIZE /* event */ +
1473 LEB128_SIZE /* time */ +
1474 LEB128_SIZE /* klass */ +
1475 LEB128_SIZE /* obj */ +
1476 LEB128_SIZE /* size */ +
1478 LEB128_SIZE /* flags */ +
1479 LEB128_SIZE /* count */ +
1481 LEB128_SIZE /* method */
1486 uint64_t now = current_time ();
1488 emit_byte (logbuffer, do_bt | TYPE_ALLOC);
1489 emit_time (logbuffer, now);
1490 emit_ptr (logbuffer, klass);
1491 emit_obj (logbuffer, obj);
1492 emit_value (logbuffer, len);
1495 emit_bt (prof, logbuffer, &data);
1499 send_if_needed (prof);
1501 process_requests (prof);
1505 gc_moves (MonoProfiler *prof, void **objects, int num)
1509 LogBuffer *logbuffer = ensure_logbuf (
1510 EVENT_SIZE /* event */ +
1511 LEB128_SIZE /* time */ +
1512 LEB128_SIZE /* num */ +
1514 LEB128_SIZE /* object */
1518 uint64_t now = current_time ();
1520 emit_byte (logbuffer, TYPE_GC_MOVE | TYPE_GC);
1521 emit_time (logbuffer, now);
1522 emit_value (logbuffer, num);
1524 for (int i = 0; i < num; ++i)
1525 emit_obj (logbuffer, objects [i]);
1531 gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
1535 LogBuffer *logbuffer = ensure_logbuf (
1536 EVENT_SIZE /* event */ +
1537 LEB128_SIZE /* num */ +
1538 LEB128_SIZE /* collections */ +
1540 LEB128_SIZE /* object */ +
1541 LEB128_SIZE /* root type */ +
1542 LEB128_SIZE /* extra info */
1546 emit_byte (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
1547 emit_value (logbuffer, num);
1548 emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
1550 for (int i = 0; i < num; ++i) {
1551 emit_obj (logbuffer, objects [i]);
1552 emit_value (logbuffer, root_types [i]);
1553 emit_value (logbuffer, extra_info [i]);
1560 gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
1562 int do_bt = nocalls && InterlockedRead (&runtime_inited) && !notraces;
1570 LogBuffer *logbuffer = ensure_logbuf (
1571 EVENT_SIZE /* event */ +
1572 LEB128_SIZE /* time */ +
1573 LEB128_SIZE /* type */ +
1574 LEB128_SIZE /* handle */ +
1575 (op == MONO_PROFILER_GC_HANDLE_CREATED ? (
1576 LEB128_SIZE /* obj */
1579 LEB128_SIZE /* flags */ +
1580 LEB128_SIZE /* count */ +
1582 LEB128_SIZE /* method */
1587 uint64_t now = current_time ();
1589 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1590 emit_byte (logbuffer, (do_bt ? TYPE_GC_HANDLE_CREATED_BT : TYPE_GC_HANDLE_CREATED) | TYPE_GC);
1591 else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
1592 emit_byte (logbuffer, (do_bt ? TYPE_GC_HANDLE_DESTROYED_BT : TYPE_GC_HANDLE_DESTROYED) | TYPE_GC);
1594 g_assert_not_reached ();
1596 emit_time (logbuffer, now);
1597 emit_value (logbuffer, type);
1598 emit_value (logbuffer, handle);
1600 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1601 emit_obj (logbuffer, obj);
1604 emit_bt (prof, logbuffer, &data);
1608 process_requests (prof);
1612 push_nesting (char *p, MonoClass *klass)
1617 nesting = mono_class_get_nesting_type (klass);
1619 p = push_nesting (p, nesting);
1623 name = mono_class_get_name (klass);
1624 nspace = mono_class_get_namespace (klass);
1627 p += strlen (nspace);
1637 type_name (MonoClass *klass)
1641 push_nesting (buf, klass);
1642 p = (char *)malloc (strlen (buf) + 1);
1648 image_loaded (MonoProfiler *prof, MonoImage *image, int result)
1650 if (result != MONO_PROFILE_OK)
1653 const char *name = mono_image_get_filename (image);
1654 int nlen = strlen (name) + 1;
1658 LogBuffer *logbuffer = ensure_logbuf (
1659 EVENT_SIZE /* event */ +
1660 LEB128_SIZE /* time */ +
1661 EVENT_SIZE /* type */ +
1662 LEB128_SIZE /* image */ +
1663 LEB128_SIZE /* flags */ +
1667 uint64_t now = current_time ();
1669 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1670 emit_time (logbuffer, now);
1671 emit_byte (logbuffer, TYPE_IMAGE);
1672 emit_ptr (logbuffer, image);
1673 emit_value (logbuffer, 0); /* flags */
1674 memcpy (logbuffer->cursor, name, nlen);
1675 logbuffer->cursor += nlen;
1679 send_if_needed (prof);
1681 process_requests (prof);
1683 InterlockedIncrement (&image_loads);
1687 image_unloaded (MonoProfiler *prof, MonoImage *image)
1689 const char *name = mono_image_get_filename (image);
1690 int nlen = strlen (name) + 1;
1694 LogBuffer *logbuffer = ensure_logbuf (
1695 EVENT_SIZE /* event */ +
1696 LEB128_SIZE /* time */ +
1697 EVENT_SIZE /* type */ +
1698 LEB128_SIZE /* image */ +
1699 LEB128_SIZE /* flags */ +
1703 uint64_t now = current_time ();
1705 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1706 emit_time (logbuffer, now);
1707 emit_byte (logbuffer, TYPE_IMAGE);
1708 emit_ptr (logbuffer, image);
1709 emit_value (logbuffer, 0); /* flags */
1710 memcpy (logbuffer->cursor, name, nlen);
1711 logbuffer->cursor += nlen;
1715 send_if_needed (prof);
1717 process_requests (prof);
1719 InterlockedIncrement (&image_unloads);
1723 assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly, int result)
1725 if (result != MONO_PROFILE_OK)
1728 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1729 int nlen = strlen (name) + 1;
1733 LogBuffer *logbuffer = ensure_logbuf (
1734 EVENT_SIZE /* event */ +
1735 LEB128_SIZE /* time */ +
1736 EVENT_SIZE /* type */ +
1737 LEB128_SIZE /* assembly */ +
1738 LEB128_SIZE /* flags */ +
1742 uint64_t now = current_time ();
1744 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1745 emit_time (logbuffer, now);
1746 emit_byte (logbuffer, TYPE_ASSEMBLY);
1747 emit_ptr (logbuffer, assembly);
1748 emit_value (logbuffer, 0); /* flags */
1749 memcpy (logbuffer->cursor, name, nlen);
1750 logbuffer->cursor += nlen;
1756 send_if_needed (prof);
1758 process_requests (prof);
1760 InterlockedIncrement (&assembly_loads);
1764 assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
1766 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1767 int nlen = strlen (name) + 1;
1771 LogBuffer *logbuffer = ensure_logbuf (
1772 EVENT_SIZE /* event */ +
1773 LEB128_SIZE /* time */ +
1774 EVENT_SIZE /* type */ +
1775 LEB128_SIZE /* assembly */ +
1776 LEB128_SIZE /* flags */ +
1780 uint64_t now = current_time ();
1782 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1783 emit_time (logbuffer, now);
1784 emit_byte (logbuffer, TYPE_ASSEMBLY);
1785 emit_ptr (logbuffer, assembly);
1786 emit_value (logbuffer, 0); /* flags */
1787 memcpy (logbuffer->cursor, name, nlen);
1788 logbuffer->cursor += nlen;
1794 send_if_needed (prof);
1796 process_requests (prof);
1798 InterlockedIncrement (&assembly_unloads);
1802 class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
1804 if (result != MONO_PROFILE_OK)
1809 if (InterlockedRead (&runtime_inited))
1810 name = mono_type_get_name (mono_class_get_type (klass));
1812 name = type_name (klass);
1814 int nlen = strlen (name) + 1;
1815 MonoImage *image = mono_class_get_image (klass);
1819 LogBuffer *logbuffer = ensure_logbuf (
1820 EVENT_SIZE /* event */ +
1821 LEB128_SIZE /* time */ +
1822 EVENT_SIZE /* type */ +
1823 LEB128_SIZE /* klass */ +
1824 LEB128_SIZE /* image */ +
1825 LEB128_SIZE /* flags */ +
1829 uint64_t now = current_time ();
1831 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1832 emit_time (logbuffer, now);
1833 emit_byte (logbuffer, TYPE_CLASS);
1834 emit_ptr (logbuffer, klass);
1835 emit_ptr (logbuffer, image);
1836 emit_value (logbuffer, 0); /* flags */
1837 memcpy (logbuffer->cursor, name, nlen);
1838 logbuffer->cursor += nlen;
1847 send_if_needed (prof);
1849 process_requests (prof);
1851 InterlockedIncrement (&class_loads);
1855 class_unloaded (MonoProfiler *prof, MonoClass *klass)
1859 if (InterlockedRead (&runtime_inited))
1860 name = mono_type_get_name (mono_class_get_type (klass));
1862 name = type_name (klass);
1864 int nlen = strlen (name) + 1;
1865 MonoImage *image = mono_class_get_image (klass);
1869 LogBuffer *logbuffer = ensure_logbuf (
1870 EVENT_SIZE /* event */ +
1871 LEB128_SIZE /* time */ +
1872 EVENT_SIZE /* type */ +
1873 LEB128_SIZE /* klass */ +
1874 LEB128_SIZE /* image */ +
1875 LEB128_SIZE /* flags */ +
1879 uint64_t now = current_time ();
1881 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1882 emit_time (logbuffer, now);
1883 emit_byte (logbuffer, TYPE_CLASS);
1884 emit_ptr (logbuffer, klass);
1885 emit_ptr (logbuffer, image);
1886 emit_value (logbuffer, 0); /* flags */
1887 memcpy (logbuffer->cursor, name, nlen);
1888 logbuffer->cursor += nlen;
1897 send_if_needed (prof);
1899 process_requests (prof);
1901 InterlockedIncrement (&class_unloads);
1904 #ifndef DISABLE_HELPER_THREAD
1905 static void process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method);
1906 #endif /* DISABLE_HELPER_THREAD */
1909 method_enter (MonoProfiler *prof, MonoMethod *method)
1911 uint64_t now = current_time ();
1913 #ifndef DISABLE_HELPER_THREAD
1914 process_method_enter_coverage (prof, method);
1915 #endif /* DISABLE_HELPER_THREAD */
1917 if (PROF_TLS_GET ()->call_depth++ > max_call_depth)
1922 LogBuffer *logbuffer = ensure_logbuf (
1923 EVENT_SIZE /* event */ +
1924 LEB128_SIZE /* time */ +
1925 LEB128_SIZE /* method */
1928 emit_byte (logbuffer, TYPE_ENTER | TYPE_METHOD);
1929 emit_time (logbuffer, now);
1930 emit_method (prof, logbuffer, method);
1934 process_requests (prof);
1938 method_leave (MonoProfiler *prof, MonoMethod *method)
1940 if (--PROF_TLS_GET ()->call_depth > max_call_depth)
1945 LogBuffer *logbuffer = ensure_logbuf (
1946 EVENT_SIZE /* event */ +
1947 LEB128_SIZE /* time */ +
1948 LEB128_SIZE /* method */
1951 uint64_t now = current_time ();
1953 emit_byte (logbuffer, TYPE_LEAVE | TYPE_METHOD);
1954 emit_time (logbuffer, now);
1955 emit_method (prof, logbuffer, method);
1959 send_if_needed (prof);
1961 process_requests (prof);
1965 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
1967 if (nocalls || --PROF_TLS_GET ()->call_depth > max_call_depth)
1972 LogBuffer *logbuffer = ensure_logbuf (
1973 EVENT_SIZE /* event */ +
1974 LEB128_SIZE /* time */ +
1975 LEB128_SIZE /* method */
1977 uint64_t now = current_time ();
1979 emit_byte (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
1980 emit_time (logbuffer, now);
1981 emit_method (prof, logbuffer, method);
1985 process_requests (prof);
1989 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji, int result)
1991 if (result != MONO_PROFILE_OK)
1994 register_method_local (prof, method, ji);
1996 process_requests (prof);
2000 code_buffer_new (MonoProfiler *prof, void *buffer, int size, MonoProfilerCodeBufferType type, void *data)
2005 if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
2006 name = (char *) data;
2007 nlen = strlen (name) + 1;
2015 LogBuffer *logbuffer = ensure_logbuf (
2016 EVENT_SIZE /* event */ +
2017 LEB128_SIZE /* time */ +
2018 LEB128_SIZE /* type */ +
2019 LEB128_SIZE /* buffer */ +
2020 LEB128_SIZE /* size */ +
2026 uint64_t now = current_time ();
2028 emit_byte (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
2029 emit_time (logbuffer, now);
2030 emit_value (logbuffer, type);
2031 emit_ptr (logbuffer, buffer);
2032 emit_value (logbuffer, size);
2035 memcpy (logbuffer->cursor, name, nlen);
2036 logbuffer->cursor += nlen;
2041 process_requests (prof);
2045 throw_exc (MonoProfiler *prof, MonoObject *object)
2047 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces) ? TYPE_EXCEPTION_BT : 0;
2055 LogBuffer *logbuffer = ensure_logbuf (
2056 EVENT_SIZE /* event */ +
2057 LEB128_SIZE /* time */ +
2058 LEB128_SIZE /* object */ +
2060 LEB128_SIZE /* flags */ +
2061 LEB128_SIZE /* count */ +
2063 LEB128_SIZE /* method */
2068 uint64_t now = current_time ();
2070 emit_byte (logbuffer, do_bt | TYPE_EXCEPTION);
2071 emit_time (logbuffer, now);
2072 emit_obj (logbuffer, object);
2075 emit_bt (prof, logbuffer, &data);
2079 process_requests (prof);
2083 clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
2087 LogBuffer *logbuffer = ensure_logbuf (
2088 EVENT_SIZE /* event */ +
2089 LEB128_SIZE /* time */ +
2090 LEB128_SIZE /* clause type */ +
2091 LEB128_SIZE /* clause num */ +
2092 LEB128_SIZE /* method */
2095 uint64_t now = current_time ();
2097 emit_byte (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
2098 emit_time (logbuffer, now);
2099 emit_value (logbuffer, clause_type);
2100 emit_value (logbuffer, clause_num);
2101 emit_method (prof, logbuffer, method);
2105 process_requests (prof);
2109 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
2111 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION) ? TYPE_MONITOR_BT : 0;
2119 LogBuffer *logbuffer = ensure_logbuf (
2120 EVENT_SIZE /* event */ +
2121 LEB128_SIZE /* time */ +
2122 LEB128_SIZE /* object */ +
2124 LEB128_SIZE /* flags */ +
2125 LEB128_SIZE /* count */ +
2127 LEB128_SIZE /* method */
2132 uint64_t now = current_time ();
2134 emit_byte (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
2135 emit_time (logbuffer, now);
2136 emit_obj (logbuffer, object);
2139 emit_bt (profiler, logbuffer, &data);
2143 process_requests (profiler);
2147 thread_start (MonoProfiler *prof, uintptr_t tid)
2153 LogBuffer *logbuffer = ensure_logbuf (
2154 EVENT_SIZE /* event */ +
2155 LEB128_SIZE /* time */ +
2156 EVENT_SIZE /* type */ +
2157 LEB128_SIZE /* tid */ +
2158 LEB128_SIZE /* flags */
2161 uint64_t now = current_time ();
2163 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2164 emit_time (logbuffer, now);
2165 emit_byte (logbuffer, TYPE_THREAD);
2166 emit_ptr (logbuffer, (void*) tid);
2167 emit_value (logbuffer, 0); /* flags */
2171 send_if_needed (prof);
2173 process_requests (prof);
2175 InterlockedIncrement (&thread_starts);
2179 thread_end (MonoProfiler *prof, uintptr_t tid)
2183 LogBuffer *logbuffer = ensure_logbuf (
2184 EVENT_SIZE /* event */ +
2185 LEB128_SIZE /* time */ +
2186 EVENT_SIZE /* type */ +
2187 LEB128_SIZE /* tid */ +
2188 LEB128_SIZE /* flags */
2191 uint64_t now = current_time ();
2193 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
2194 emit_time (logbuffer, now);
2195 emit_byte (logbuffer, TYPE_THREAD);
2196 emit_ptr (logbuffer, (void*) tid);
2197 emit_value (logbuffer, 0); /* flags */
2201 // Don't process requests as the thread is detached from the runtime.
2203 remove_thread (prof, PROF_TLS_GET (), TRUE);
2205 InterlockedIncrement (&thread_ends);
2209 domain_loaded (MonoProfiler *prof, MonoDomain *domain, int result)
2211 if (result != MONO_PROFILE_OK)
2216 LogBuffer *logbuffer = ensure_logbuf (
2217 EVENT_SIZE /* event */ +
2218 LEB128_SIZE /* time */ +
2219 EVENT_SIZE /* type */ +
2220 LEB128_SIZE /* domain id */ +
2221 LEB128_SIZE /* flags */
2224 uint64_t now = current_time ();
2226 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2227 emit_time (logbuffer, now);
2228 emit_byte (logbuffer, TYPE_DOMAIN);
2229 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2230 emit_value (logbuffer, 0); /* flags */
2234 send_if_needed (prof);
2236 process_requests (prof);
2238 InterlockedIncrement (&domain_loads);
2242 domain_unloaded (MonoProfiler *prof, MonoDomain *domain)
2246 LogBuffer *logbuffer = ensure_logbuf (
2247 EVENT_SIZE /* event */ +
2248 LEB128_SIZE /* time */ +
2249 EVENT_SIZE /* type */ +
2250 LEB128_SIZE /* domain id */ +
2251 LEB128_SIZE /* flags */
2254 uint64_t now = current_time ();
2256 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
2257 emit_time (logbuffer, now);
2258 emit_byte (logbuffer, TYPE_DOMAIN);
2259 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2260 emit_value (logbuffer, 0); /* flags */
2264 send_if_needed (prof);
2266 process_requests (prof);
2268 InterlockedIncrement (&domain_unloads);
2272 domain_name (MonoProfiler *prof, MonoDomain *domain, const char *name)
2274 int nlen = strlen (name) + 1;
2278 LogBuffer *logbuffer = ensure_logbuf (
2279 EVENT_SIZE /* event */ +
2280 LEB128_SIZE /* time */ +
2281 EVENT_SIZE /* type */ +
2282 LEB128_SIZE /* domain id */ +
2283 LEB128_SIZE /* flags */ +
2287 uint64_t now = current_time ();
2289 emit_byte (logbuffer, TYPE_METADATA);
2290 emit_time (logbuffer, now);
2291 emit_byte (logbuffer, TYPE_DOMAIN);
2292 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2293 emit_value (logbuffer, 0); /* flags */
2294 memcpy (logbuffer->cursor, name, nlen);
2295 logbuffer->cursor += nlen;
2299 send_if_needed (prof);
2301 process_requests (prof);
2305 context_loaded (MonoProfiler *prof, MonoAppContext *context)
2309 LogBuffer *logbuffer = ensure_logbuf (
2310 EVENT_SIZE /* event */ +
2311 LEB128_SIZE /* time */ +
2312 EVENT_SIZE /* type */ +
2313 LEB128_SIZE /* context id */ +
2314 LEB128_SIZE /* flags */ +
2315 LEB128_SIZE /* domain id */
2318 uint64_t now = current_time ();
2320 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2321 emit_time (logbuffer, now);
2322 emit_byte (logbuffer, TYPE_CONTEXT);
2323 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
2324 emit_value (logbuffer, 0); /* flags */
2325 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
2329 send_if_needed (prof);
2331 process_requests (prof);
2333 InterlockedIncrement (&context_loads);
2337 context_unloaded (MonoProfiler *prof, MonoAppContext *context)
2341 LogBuffer *logbuffer = ensure_logbuf (
2342 EVENT_SIZE /* event */ +
2343 LEB128_SIZE /* time */ +
2344 EVENT_SIZE /* type */ +
2345 LEB128_SIZE /* context id */ +
2346 LEB128_SIZE /* flags */ +
2347 LEB128_SIZE /* domain id */
2350 uint64_t now = current_time ();
2352 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
2353 emit_time (logbuffer, now);
2354 emit_byte (logbuffer, TYPE_CONTEXT);
2355 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
2356 emit_value (logbuffer, 0); /* flags */
2357 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
2361 send_if_needed (prof);
2363 process_requests (prof);
2365 InterlockedIncrement (&context_unloads);
2369 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
2371 int len = strlen (name) + 1;
2375 LogBuffer *logbuffer = ensure_logbuf (
2376 EVENT_SIZE /* event */ +
2377 LEB128_SIZE /* time */ +
2378 EVENT_SIZE /* type */ +
2379 LEB128_SIZE /* tid */ +
2380 LEB128_SIZE /* flags */ +
2384 uint64_t now = current_time ();
2386 emit_byte (logbuffer, TYPE_METADATA);
2387 emit_time (logbuffer, now);
2388 emit_byte (logbuffer, TYPE_THREAD);
2389 emit_ptr (logbuffer, (void*)tid);
2390 emit_value (logbuffer, 0); /* flags */
2391 memcpy (logbuffer->cursor, name, len);
2392 logbuffer->cursor += len;
2396 send_if_needed (prof);
2398 process_requests (prof);
2409 MonoLockFreeQueueNode node;
2415 AsyncFrameInfo frames [MONO_ZERO_LEN_ARRAY];
2419 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
2421 SampleHit *sample = (SampleHit *) data;
2423 if (sample->count < num_frames) {
2424 int i = sample->count;
2426 sample->frames [i].method = method;
2427 sample->frames [i].domain = domain;
2428 sample->frames [i].base_address = base_address;
2429 sample->frames [i].offset = offset;
2434 return sample->count == num_frames;
2437 #define SAMPLE_SLOT_SIZE(FRAMES) (sizeof (SampleHit) + sizeof (AsyncFrameInfo) * (FRAMES - MONO_ZERO_LEN_ARRAY))
2438 #define SAMPLE_BLOCK_SIZE (mono_pagesize ())
2441 enqueue_sample_hit (gpointer p)
2443 SampleHit *sample = p;
2445 mono_lock_free_queue_node_unpoison (&sample->node);
2446 mono_lock_free_queue_enqueue (&sample->prof->dumper_queue, &sample->node);
2447 mono_os_sem_post (&sample->prof->dumper_queue_sem);
2449 InterlockedIncrement (&sample_flushes);
2453 mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
2456 * Please note: We rely on the runtime loading the profiler with
2457 * MONO_DL_EAGER (RTLD_NOW) so that references to runtime functions within
2458 * this function (and its siblings) are resolved when the profiler is
2459 * loaded. Otherwise, we would potentially invoke the dynamic linker when
2460 * invoking runtime functions, which is not async-signal-safe.
2466 InterlockedIncrement (&sample_hits);
2468 uint64_t now = current_time ();
2470 SampleHit *sample = (SampleHit *) mono_lock_free_queue_dequeue (&profiler->sample_reuse_queue);
2474 * If we're out of reusable sample events and we're not allowed to
2475 * allocate more, we have no choice but to drop the event.
2477 if (InterlockedRead (&sample_allocations) >= max_allocated_sample_hits)
2480 sample = mono_lock_free_alloc (&profiler->sample_allocator);
2481 sample->prof = profiler;
2482 mono_lock_free_queue_node_init (&sample->node, TRUE);
2484 InterlockedIncrement (&sample_allocations);
2488 mono_stack_walk_async_safe (&async_walk_stack, context, sample);
2490 uintptr_t elapsed = (now - profiler->startup_time) / 10000;
2492 sample->elapsed = elapsed;
2493 sample->tid = thread_id ();
2499 snprintf (buf, sizeof (buf), "hit at %p in thread %p after %llu ms\n", ip, (void *) thread_id (), (unsigned long long int) elapsed / 100);
2501 ign_res (write (2, buf, len));
2504 mono_thread_hazardous_try_free (sample, enqueue_sample_hit);
2507 static uintptr_t *code_pages = 0;
2508 static int num_code_pages = 0;
2509 static int size_code_pages = 0;
2510 #define CPAGE_SHIFT (9)
2511 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
2512 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
2513 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
2516 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
2519 uintptr_t start_pos;
2520 start_pos = (page >> CPAGE_SHIFT) % hsize;
2523 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
2525 } else if (!hash [i]) {
2532 } while (i != start_pos);
2533 /* should not happen */
2534 printf ("failed code page store\n");
2539 add_code_pointer (uintptr_t ip)
2542 if (num_code_pages * 2 >= size_code_pages) {
2544 uintptr_t old_size = size_code_pages;
2545 size_code_pages *= 2;
2546 if (size_code_pages == 0)
2547 size_code_pages = 16;
2548 n = (uintptr_t *)calloc (sizeof (uintptr_t) * size_code_pages, 1);
2549 for (i = 0; i < old_size; ++i) {
2551 add_code_page (n, size_code_pages, code_pages [i]);
2557 num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
2560 /* ELF code crashes on some systems. */
2561 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2564 dump_ubin (const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
2566 int len = strlen (filename) + 1;
2570 LogBuffer *logbuffer = ensure_logbuf (
2571 EVENT_SIZE /* event */ +
2572 LEB128_SIZE /* time */ +
2573 LEB128_SIZE /* load address */ +
2574 LEB128_SIZE /* offset */ +
2575 LEB128_SIZE /* size */ +
2576 nlen /* file name */
2579 uint64_t now = current_time ();
2581 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
2582 emit_time (logbuffer, now);
2583 emit_svalue (logbuffer, load_addr);
2584 emit_uvalue (logbuffer, offset);
2585 emit_uvalue (logbuffer, size);
2586 memcpy (logbuffer->cursor, filename, len);
2587 logbuffer->cursor += len;
2594 dump_usym (const char *name, uintptr_t value, uintptr_t size)
2596 int len = strlen (name) + 1;
2600 LogBuffer *logbuffer = ensure_logbuf (
2601 EVENT_SIZE /* event */ +
2602 LEB128_SIZE /* value */ +
2603 LEB128_SIZE /* size */ +
2607 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
2608 emit_ptr (logbuffer, (void*)value);
2609 emit_value (logbuffer, size);
2610 memcpy (logbuffer->cursor, name, len);
2611 logbuffer->cursor += len;
2616 /* ELF code crashes on some systems. */
2617 //#if defined(ELFMAG0)
2620 #if SIZEOF_VOID_P == 4
2621 #define ELF_WSIZE 32
2623 #define ELF_WSIZE 64
2626 #define ElfW(type) _ElfW (Elf, ELF_WSIZE, type)
2627 #define _ElfW(e,w,t) _ElfW_1 (e, w, _##t)
2628 #define _ElfW_1(e,w,t) e##w##t
2632 dump_elf_symbols (ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
2635 for (i = 0; i < num_symbols; ++i) {
2637 sym = strtab + symbols [i].st_name;
2638 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
2640 //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
2641 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
2646 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
2653 ElfW(Shdr) *sheader;
2654 ElfW(Shdr) *shstrtabh;
2655 ElfW(Shdr) *symtabh = NULL;
2656 ElfW(Shdr) *strtabh = NULL;
2657 ElfW(Sym) *symbols = NULL;
2661 fd = open (filename, O_RDONLY);
2664 if (fstat (fd, &statb) != 0) {
2668 file_size = statb.st_size;
2669 data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
2671 if (data == MAP_FAILED)
2674 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2675 header->e_ident [EI_MAG1] != ELFMAG1 ||
2676 header->e_ident [EI_MAG2] != ELFMAG2 ||
2677 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2678 munmap (data, file_size);
2681 sheader = (void*)((char*)data + header->e_shoff);
2682 shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
2683 strtab = (const char*)data + shstrtabh->sh_offset;
2684 for (i = 0; i < header->e_shnum; ++i) {
2685 //printf ("section header: %d\n", sheader->sh_type);
2686 if (sheader->sh_type == SHT_SYMTAB) {
2688 strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
2689 /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
2692 sheader = (void*)((char*)sheader + header->e_shentsize);
2694 if (!symtabh || !strtabh) {
2695 munmap (data, file_size);
2698 strtab = (const char*)data + strtabh->sh_offset;
2699 num_symbols = symtabh->sh_size / symtabh->sh_entsize;
2700 symbols = (void*)((char*)data + symtabh->sh_offset);
2701 dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
2702 munmap (data, file_size);
2707 /* ELF code crashes on some systems. */
2708 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2711 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
2713 MonoProfiler *prof = data;
2715 const char *filename;
2717 char *a = (void*)info->dlpi_addr;
2719 ElfW(Dyn) *dyn = NULL;
2720 ElfW(Sym) *symtab = NULL;
2721 ElfW(Word) *hash_table = NULL;
2722 ElfW(Ehdr) *header = NULL;
2723 const char* strtab = NULL;
2724 for (obj = prof->binary_objects; obj; obj = obj->next) {
2728 filename = info->dlpi_name;
2731 if (!info->dlpi_addr && !filename [0]) {
2732 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
2738 obj = calloc (sizeof (BinaryObject), 1);
2739 obj->addr = (void*)info->dlpi_addr;
2740 obj->name = pstrdup (filename);
2741 obj->next = prof->binary_objects;
2742 prof->binary_objects = obj;
2743 //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
2745 for (i = 0; i < info->dlpi_phnum; ++i) {
2746 //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);
2747 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
2748 header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2749 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2750 header->e_ident [EI_MAG1] != ELFMAG1 ||
2751 header->e_ident [EI_MAG2] != ELFMAG2 ||
2752 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2755 dump_ubin (filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
2756 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
2757 dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2760 if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
2762 if (!info->dlpi_name || !info->dlpi_name[0])
2766 for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
2767 if (dyn [i].d_tag == DT_SYMTAB) {
2768 if (symtab && do_debug)
2769 printf ("multiple symtabs: %d\n", i);
2770 symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
2771 } else if (dyn [i].d_tag == DT_HASH) {
2772 hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
2773 } else if (dyn [i].d_tag == DT_STRTAB) {
2774 strtab = (const char*)(a + dyn [i].d_un.d_ptr);
2779 num_sym = hash_table [1];
2780 dump_elf_symbols (symtab, num_sym, strtab, (void*)info->dlpi_addr);
2785 load_binaries (MonoProfiler *prof)
2787 dl_iterate_phdr (elf_dl_callback, prof);
2792 load_binaries (MonoProfiler *prof)
2799 symbol_for (uintptr_t code)
2802 void *ip = (void*)code;
2804 if (dladdr (ip, &di)) {
2806 return di.dli_sname;
2809 names = backtrace_symbols (&ip, 1);
2811 const char* p = names [0];
2822 dump_unmanaged_coderefs (MonoProfiler *prof)
2825 const char* last_symbol;
2826 uintptr_t addr, page_end;
2828 if (load_binaries (prof))
2830 for (i = 0; i < size_code_pages; ++i) {
2832 if (!code_pages [i] || code_pages [i] & 1)
2835 addr = CPAGE_ADDR (code_pages [i]);
2836 page_end = addr + CPAGE_SIZE;
2837 code_pages [i] |= 1;
2838 /* we dump the symbols for the whole page */
2839 for (; addr < page_end; addr += 16) {
2840 sym = symbol_for (addr);
2841 if (sym && sym == last_symbol)
2846 dump_usym (sym, addr, 0); /* let's not guess the size */
2847 //printf ("found symbol at %p: %s\n", (void*)addr, sym);
2853 mono_cpu_count (void)
2855 #ifdef PLATFORM_ANDROID
2856 /* Android tries really hard to save power by powering off CPUs on SMP phones which
2857 * means the normal way to query cpu count returns a wrong value with userspace API.
2858 * Instead we use /sys entries to query the actual hardware CPU count.
2861 char buffer[8] = {'\0'};
2862 int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
2863 /* Format of the /sys entry is a cpulist of indexes which in the case
2864 * of present is always of the form "0-(n-1)" when there is more than
2865 * 1 core, n being the number of CPU cores in the system. Otherwise
2866 * the value is simply 0
2868 if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
2869 count = strtol (((char*)buffer) + 2, NULL, 10);
2876 #if defined(HOST_ARM) || defined (HOST_ARM64)
2878 /* ARM platforms tries really hard to save power by powering off CPUs on SMP phones which
2879 * means the normal way to query cpu count returns a wrong value with userspace API. */
2881 #ifdef _SC_NPROCESSORS_CONF
2883 int count = sysconf (_SC_NPROCESSORS_CONF);
2891 #ifdef HAVE_SCHED_GETAFFINITY
2894 if (sched_getaffinity (getpid (), sizeof (set), &set) == 0)
2895 return CPU_COUNT (&set);
2898 #ifdef _SC_NPROCESSORS_ONLN
2900 int count = sysconf (_SC_NPROCESSORS_ONLN);
2906 #endif /* defined(HOST_ARM) || defined (HOST_ARM64) */
2912 size_t len = sizeof (int);
2915 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
2922 GetSystemInfo (&info);
2923 return info.dwNumberOfProcessors;
2934 unsigned int prev_pos;
2936 struct perf_event_mmap_page *page_desc;
2939 static PerfData *perf_data = NULL;
2940 static int num_perf;
2941 #define PERF_PAGES_SHIFT 4
2942 static int num_pages = 1 << PERF_PAGES_SHIFT;
2943 static unsigned int mmap_mask;
2946 struct perf_event_header h;
2956 perf_event_syscall (struct perf_event_attr *attr, pid_t pid, int cpu, int group_fd, unsigned long flags)
2958 attr->size = PERF_ATTR_SIZE_VER0;
2959 //printf ("perf attr size: %d\n", attr->size);
2960 #if defined(__x86_64__)
2961 return syscall(/*__NR_perf_event_open*/ 298, attr, pid, cpu, group_fd, flags);
2962 #elif defined(__i386__)
2963 return syscall(/*__NR_perf_event_open*/ 336, attr, pid, cpu, group_fd, flags);
2964 #elif defined(__arm__) || defined (__aarch64__)
2965 return syscall(/*__NR_perf_event_open*/ 364, attr, pid, cpu, group_fd, flags);
2972 setup_perf_map (PerfData *perf)
2974 perf->mmap_base = mmap (NULL, (num_pages + 1) * getpagesize (), PROT_READ|PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
2975 if (perf->mmap_base == MAP_FAILED) {
2977 printf ("failed mmap\n");
2980 perf->page_desc = perf->mmap_base;
2982 printf ("mmap version: %d\n", perf->page_desc->version);
2987 dump_perf_hits (MonoProfiler *prof, void *buf, int size)
2991 void *end = (char*)buf + size;
2993 int pid = getpid ();
2999 if (pid != s->pid) {
3001 printf ("event for different pid: %d\n", s->pid);
3002 buf = (char*)buf + s->h.size;
3005 /*ip = (void*)s->ip;
3006 printf ("sample: %d, size: %d, ip: %p (%s), timestamp: %llu, nframes: %llu\n",
3007 s->h.type, s->h.size, ip, symbol_for (ip), s->timestamp, s->nframes);*/
3011 LogBuffer *logbuffer = ensure_logbuf (
3012 EVENT_SIZE /* event */ +
3013 LEB128_SIZE /* type */ +
3014 LEB128_SIZE /* time */ +
3015 LEB128_SIZE /* tid */ +
3016 LEB128_SIZE /* count */ +
3018 LEB128_SIZE /* ip */
3020 LEB128_SIZE /* managed count */ +
3022 LEB128_SIZE /* method */ +
3023 LEB128_SIZE /* il offset */ +
3024 LEB128_SIZE /* native offset */
3028 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
3029 emit_value (logbuffer, sample_type);
3030 emit_uvalue (logbuffer, s->timestamp - prof->startup_time);
3032 * No useful thread ID to write here, since throughout the
3033 * profiler we use pthread_self () but the ID we get from
3034 * perf is the kernel's thread ID.
3036 emit_ptr (logbuffer, 0);
3037 emit_value (logbuffer, count);
3038 emit_ptr (logbuffer, (void*)(uintptr_t)s->ip);
3039 /* no support here yet for the managed backtrace */
3040 emit_uvalue (logbuffer, mbt_count);
3044 add_code_pointer (s->ip);
3045 buf = (char*)buf + s->h.size;
3049 printf ("dumped %d samples\n", samples);
3050 dump_unmanaged_coderefs (prof);
3053 /* read events from the ring buffer */
3055 read_perf_mmap (MonoProfiler* prof, int cpu)
3057 PerfData *perf = perf_data + cpu;
3059 unsigned char *data = (unsigned char*)perf->mmap_base + getpagesize ();
3060 unsigned int head = perf->page_desc->data_head;
3064 mono_memory_read_barrier ();
3066 old = perf->prev_pos;
3070 printf ("lost mmap events: old: %d, head: %d\n", old, head);
3074 if ((old & mmap_mask) + size != (head & mmap_mask)) {
3075 buf = data + (old & mmap_mask);
3076 size = mmap_mask + 1 - (old & mmap_mask);
3078 /* size bytes at buf */
3080 printf ("found1 bytes of events: %d\n", size);
3081 dump_perf_hits (prof, buf, size);
3083 buf = data + (old & mmap_mask);
3085 /* size bytes at buf */
3087 printf ("found bytes of events: %d\n", size);
3088 dump_perf_hits (prof, buf, size);
3090 perf->prev_pos = old;
3091 perf->page_desc->data_tail = old;
3096 setup_perf_event_for_cpu (PerfData *perf, int cpu)
3098 struct perf_event_attr attr;
3099 memset (&attr, 0, sizeof (attr));
3100 attr.type = PERF_TYPE_HARDWARE;
3101 switch (sample_type) {
3102 case SAMPLE_CYCLES: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
3103 case SAMPLE_INSTRUCTIONS: attr.config = PERF_COUNT_HW_INSTRUCTIONS; break;
3104 case SAMPLE_CACHE_MISSES: attr.config = PERF_COUNT_HW_CACHE_MISSES; break;
3105 case SAMPLE_CACHE_REFS: attr.config = PERF_COUNT_HW_CACHE_REFERENCES; break;
3106 case SAMPLE_BRANCHES: attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS; break;
3107 case SAMPLE_BRANCH_MISSES: attr.config = PERF_COUNT_HW_BRANCH_MISSES; break;
3108 default: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
3110 attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD | PERF_SAMPLE_TIME;
3111 // attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
3112 attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING | PERF_FORMAT_ID;
3115 attr.sample_freq = sample_freq;
3117 perf->perf_fd = perf_event_syscall (&attr, getpid (), cpu, -1, 0);
3119 printf ("perf fd: %d, freq: %d, event: %llu\n", perf->perf_fd, sample_freq, attr.config);
3120 if (perf->perf_fd < 0) {
3121 if (perf->perf_fd == -EPERM) {
3122 fprintf (stderr, "Perf syscall denied, do \"echo 1 > /proc/sys/kernel/perf_event_paranoid\" as root to enable.\n");
3125 perror ("open perf event");
3129 if (!setup_perf_map (perf)) {
3130 close (perf->perf_fd);
3138 setup_perf_event (void)
3141 mmap_mask = num_pages * getpagesize () - 1;
3142 num_perf = mono_cpu_count ();
3143 perf_data = calloc (num_perf, sizeof (PerfData));
3144 for (i = 0; i < num_perf; ++i) {
3145 count += setup_perf_event_for_cpu (perf_data + i, i);
3154 #endif /* USE_PERF_EVENTS */
3156 #ifndef DISABLE_HELPER_THREAD
3158 typedef struct MonoCounterAgent {
3159 MonoCounter *counter;
3160 // MonoCounterAgent specific data :
3165 struct MonoCounterAgent *next;
3168 static MonoCounterAgent* counters;
3169 static gboolean counters_initialized = FALSE;
3170 static int counters_index = 1;
3171 static mono_mutex_t counters_mutex;
3174 counters_add_agent (MonoCounter *counter)
3176 MonoCounterAgent *agent, *item;
3178 if (!counters_initialized)
3181 mono_os_mutex_lock (&counters_mutex);
3183 for (agent = counters; agent; agent = agent->next) {
3184 if (agent->counter == counter) {
3185 agent->value_size = 0;
3187 free (agent->value);
3188 agent->value = NULL;
3190 mono_os_mutex_unlock (&counters_mutex);
3195 agent = (MonoCounterAgent *)malloc (sizeof (MonoCounterAgent));
3196 agent->counter = counter;
3197 agent->value = NULL;
3198 agent->value_size = 0;
3199 agent->index = counters_index++;
3212 mono_os_mutex_unlock (&counters_mutex);
3216 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
3218 counters_add_agent (counter);
3223 counters_init (MonoProfiler *profiler)
3225 assert (!counters_initialized);
3227 mono_os_mutex_init (&counters_mutex);
3229 counters_initialized = TRUE;
3231 mono_counters_on_register (&counters_add_agent);
3232 mono_counters_foreach (counters_init_foreach_callback, NULL);
3236 counters_emit (MonoProfiler *profiler, gboolean threadless)
3238 MonoCounterAgent *agent;
3241 EVENT_SIZE /* event */ +
3242 LEB128_SIZE /* len */
3245 if (!counters_initialized)
3248 mono_os_mutex_lock (&counters_mutex);
3250 for (agent = counters; agent; agent = agent->next) {
3255 LEB128_SIZE /* section */ +
3256 strlen (mono_counter_get_name (agent->counter)) + 1 /* name */ +
3257 LEB128_SIZE /* type */ +
3258 LEB128_SIZE /* unit */ +
3259 LEB128_SIZE /* variance */ +
3260 LEB128_SIZE /* index */
3267 mono_os_mutex_unlock (&counters_mutex);
3273 LogBuffer *logbuffer = ensure_logbuf (size);
3275 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
3276 emit_value (logbuffer, len);
3278 for (agent = counters; agent; agent = agent->next) {
3284 name = mono_counter_get_name (agent->counter);
3285 emit_value (logbuffer, mono_counter_get_section (agent->counter));
3286 emit_string (logbuffer, name, strlen (name) + 1);
3287 emit_value (logbuffer, mono_counter_get_type (agent->counter));
3288 emit_value (logbuffer, mono_counter_get_unit (agent->counter));
3289 emit_value (logbuffer, mono_counter_get_variance (agent->counter));
3290 emit_value (logbuffer, agent->index);
3298 safe_send_threadless (profiler);
3300 safe_send (profiler);
3302 mono_os_mutex_unlock (&counters_mutex);
3306 counters_sample (MonoProfiler *profiler, uint64_t timestamp, gboolean threadless)
3308 MonoCounterAgent *agent;
3309 MonoCounter *counter;
3315 if (!counters_initialized)
3318 counters_emit (profiler, threadless);
3321 buffer = calloc (1, buffer_size);
3323 mono_os_mutex_lock (&counters_mutex);
3326 EVENT_SIZE /* event */ +
3327 LEB128_SIZE /* time */
3330 for (agent = counters; agent; agent = agent->next) {
3332 LEB128_SIZE /* index */ +
3333 LEB128_SIZE /* type */ +
3334 mono_counter_get_size (agent->counter) /* value */
3339 LEB128_SIZE /* stop marker */
3344 LogBuffer *logbuffer = ensure_logbuf (size);
3346 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
3347 emit_uvalue (logbuffer, timestamp);
3349 for (agent = counters; agent; agent = agent->next) {
3352 counter = agent->counter;
3354 size = mono_counter_get_size (counter);
3356 continue; // FIXME error
3357 } else if (size > buffer_size) {
3359 buffer = realloc (buffer, buffer_size);
3362 memset (buffer, 0, buffer_size);
3364 if (mono_counters_sample (counter, buffer, size) < 0)
3365 continue; // FIXME error
3367 type = mono_counter_get_type (counter);
3369 if (!agent->value) {
3370 agent->value = calloc (1, size);
3371 agent->value_size = size;
3373 if (type == MONO_COUNTER_STRING) {
3374 if (strcmp (agent->value, buffer) == 0)
3377 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
3382 emit_uvalue (logbuffer, agent->index);
3383 emit_uvalue (logbuffer, type);
3385 case MONO_COUNTER_INT:
3386 #if SIZEOF_VOID_P == 4
3387 case MONO_COUNTER_WORD:
3389 emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
3391 case MONO_COUNTER_UINT:
3392 emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
3394 case MONO_COUNTER_TIME_INTERVAL:
3395 case MONO_COUNTER_LONG:
3396 #if SIZEOF_VOID_P == 8
3397 case MONO_COUNTER_WORD:
3399 emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
3401 case MONO_COUNTER_ULONG:
3402 emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
3404 case MONO_COUNTER_DOUBLE:
3405 emit_double (logbuffer, *(double*)buffer);
3407 case MONO_COUNTER_STRING:
3409 emit_byte (logbuffer, 0);
3411 emit_byte (logbuffer, 1);
3412 emit_string (logbuffer, (char*)buffer, size);
3419 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
3420 agent->value = realloc (agent->value, size);
3421 agent->value_size = size;
3425 memcpy (agent->value, buffer, size);
3429 emit_value (logbuffer, 0);
3434 safe_send_threadless (profiler);
3436 safe_send (profiler);
3438 mono_os_mutex_unlock (&counters_mutex);
3441 typedef struct _PerfCounterAgent PerfCounterAgent;
3442 struct _PerfCounterAgent {
3443 PerfCounterAgent *next;
3445 char *category_name;
3454 static PerfCounterAgent *perfcounters = NULL;
3457 perfcounters_emit (MonoProfiler *profiler, gboolean threadless)
3459 PerfCounterAgent *pcagent;
3462 EVENT_SIZE /* event */ +
3463 LEB128_SIZE /* len */
3466 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3467 if (pcagent->emitted)
3471 LEB128_SIZE /* section */ +
3472 strlen (pcagent->category_name) + 1 /* category name */ +
3473 strlen (pcagent->name) + 1 /* name */ +
3474 LEB128_SIZE /* type */ +
3475 LEB128_SIZE /* unit */ +
3476 LEB128_SIZE /* variance */ +
3477 LEB128_SIZE /* index */
3488 LogBuffer *logbuffer = ensure_logbuf (size);
3490 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
3491 emit_value (logbuffer, len);
3493 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3494 if (pcagent->emitted)
3497 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
3498 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
3499 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
3500 emit_value (logbuffer, MONO_COUNTER_LONG);
3501 emit_value (logbuffer, MONO_COUNTER_RAW);
3502 emit_value (logbuffer, MONO_COUNTER_VARIABLE);
3503 emit_value (logbuffer, pcagent->index);
3505 pcagent->emitted = 1;
3511 safe_send_threadless (profiler);
3513 safe_send (profiler);
3517 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
3519 PerfCounterAgent *pcagent;
3521 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3522 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
3524 if (pcagent->value == value)
3527 pcagent->value = value;
3528 pcagent->updated = 1;
3529 pcagent->deleted = 0;
3533 pcagent = g_new0 (PerfCounterAgent, 1);
3534 pcagent->next = perfcounters;
3535 pcagent->index = counters_index++;
3536 pcagent->category_name = g_strdup (category_name);
3537 pcagent->name = g_strdup (name);
3538 pcagent->type = (int) type;
3539 pcagent->value = value;
3540 pcagent->emitted = 0;
3541 pcagent->updated = 1;
3542 pcagent->deleted = 0;
3544 perfcounters = pcagent;
3550 perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp, gboolean threadless)
3552 PerfCounterAgent *pcagent;
3555 if (!counters_initialized)
3558 mono_os_mutex_lock (&counters_mutex);
3560 /* mark all perfcounters as deleted, foreach will unmark them as necessary */
3561 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
3562 pcagent->deleted = 1;
3564 mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
3566 perfcounters_emit (profiler, threadless);
3569 EVENT_SIZE /* event */ +
3570 LEB128_SIZE /* time */
3573 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3574 if (pcagent->deleted || !pcagent->updated)
3578 LEB128_SIZE /* index */ +
3579 LEB128_SIZE /* type */ +
3580 LEB128_SIZE /* value */
3585 LEB128_SIZE /* stop marker */
3590 LogBuffer *logbuffer = ensure_logbuf (size);
3592 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
3593 emit_uvalue (logbuffer, timestamp);
3595 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3596 if (pcagent->deleted || !pcagent->updated)
3598 emit_uvalue (logbuffer, pcagent->index);
3599 emit_uvalue (logbuffer, MONO_COUNTER_LONG);
3600 emit_svalue (logbuffer, pcagent->value);
3602 pcagent->updated = 0;
3605 emit_value (logbuffer, 0);
3610 safe_send_threadless (profiler);
3612 safe_send (profiler);
3614 mono_os_mutex_unlock (&counters_mutex);
3618 counters_and_perfcounters_sample (MonoProfiler *prof, gboolean threadless)
3620 static uint64_t start = -1;
3624 start = current_time ();
3626 now = current_time ();
3627 counters_sample (prof, (now - start) / 1000/ 1000, threadless);
3628 perfcounters_sample (prof, (now - start) / 1000/ 1000, threadless);
3631 #define COVERAGE_DEBUG(x) if (debug_coverage) {x}
3632 static mono_mutex_t coverage_mutex;
3633 static MonoConcurrentHashTable *coverage_methods = NULL;
3634 static MonoConcurrentHashTable *coverage_assemblies = NULL;
3635 static MonoConcurrentHashTable *coverage_classes = NULL;
3637 static MonoConcurrentHashTable *filtered_classes = NULL;
3638 static MonoConcurrentHashTable *entered_methods = NULL;
3639 static MonoConcurrentHashTable *image_to_methods = NULL;
3640 static MonoConcurrentHashTable *suppressed_assemblies = NULL;
3641 static gboolean coverage_initialized = FALSE;
3643 static GPtrArray *coverage_data = NULL;
3644 static int previous_offset = 0;
3647 MonoLockFreeQueueNode node;
3660 free_coverage_entry (gpointer data, gpointer userdata)
3662 CoverageEntry *entry = (CoverageEntry *)data;
3663 g_free (entry->filename);
3668 obtain_coverage_for_method (MonoProfiler *prof, const MonoProfileCoverageEntry *entry)
3670 int offset = entry->iloffset - previous_offset;
3671 CoverageEntry *e = g_new (CoverageEntry, 1);
3673 previous_offset = entry->iloffset;
3676 e->counter = entry->counter;
3677 e->filename = g_strdup(entry->filename ? entry->filename : "");
3678 e->line = entry->line;
3679 e->column = entry->col;
3681 g_ptr_array_add (coverage_data, e);
3685 parse_generic_type_names(char *name)
3687 char *new_name, *ret;
3688 int within_generic_declaration = 0, generic_members = 1;
3690 if (name == NULL || *name == '\0')
3691 return g_strdup ("");
3693 if (!(ret = new_name = (char *)calloc (strlen (name) * 4 + 1, sizeof (char))))
3699 within_generic_declaration = 1;
3703 within_generic_declaration = 0;
3705 if (*(name - 1) != '<') {
3707 *new_name++ = '0' + generic_members;
3709 memcpy (new_name, "<>", 8);
3713 generic_members = 0;
3721 if (!within_generic_declaration)
3722 *new_name++ = *name;
3731 static int method_id;
3733 build_method_buffer (gpointer key, gpointer value, gpointer userdata)
3735 MonoMethod *method = (MonoMethod *)value;
3736 MonoProfiler *prof = (MonoProfiler *)userdata;
3740 const char *image_name, *method_name, *sig, *first_filename;
3743 previous_offset = 0;
3744 coverage_data = g_ptr_array_new ();
3746 mono_profiler_coverage_get (prof, method, obtain_coverage_for_method);
3748 klass = mono_method_get_class (method);
3749 image = mono_class_get_image (klass);
3750 image_name = mono_image_get_name (image);
3752 sig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3753 class_name = parse_generic_type_names (mono_type_get_name (mono_class_get_type (klass)));
3754 method_name = mono_method_get_name (method);
3756 if (coverage_data->len != 0) {
3757 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[0];
3758 first_filename = entry->filename ? entry->filename : "";
3760 first_filename = "";
3762 image_name = image_name ? image_name : "";
3763 sig = sig ? sig : "";
3764 method_name = method_name ? method_name : "";
3768 LogBuffer *logbuffer = ensure_logbuf (
3769 EVENT_SIZE /* event */ +
3770 strlen (image_name) + 1 /* image name */ +
3771 strlen (class_name) + 1 /* class name */ +
3772 strlen (method_name) + 1 /* method name */ +
3773 strlen (sig) + 1 /* signature */ +
3774 strlen (first_filename) + 1 /* first file name */ +
3775 LEB128_SIZE /* token */ +
3776 LEB128_SIZE /* method id */ +
3777 LEB128_SIZE /* entries */
3780 emit_byte (logbuffer, TYPE_COVERAGE_METHOD | TYPE_COVERAGE);
3781 emit_string (logbuffer, image_name, strlen (image_name) + 1);
3782 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3783 emit_string (logbuffer, method_name, strlen (method_name) + 1);
3784 emit_string (logbuffer, sig, strlen (sig) + 1);
3785 emit_string (logbuffer, first_filename, strlen (first_filename) + 1);
3787 emit_uvalue (logbuffer, mono_method_get_token (method));
3788 emit_uvalue (logbuffer, method_id);
3789 emit_value (logbuffer, coverage_data->len);
3795 for (i = 0; i < coverage_data->len; i++) {
3796 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[i];
3800 LogBuffer *logbuffer = ensure_logbuf (
3801 EVENT_SIZE /* event */ +
3802 LEB128_SIZE /* method id */ +
3803 LEB128_SIZE /* offset */ +
3804 LEB128_SIZE /* counter */ +
3805 LEB128_SIZE /* line */ +
3806 LEB128_SIZE /* column */
3809 emit_byte (logbuffer, TYPE_COVERAGE_STATEMENT | TYPE_COVERAGE);
3810 emit_uvalue (logbuffer, method_id);
3811 emit_uvalue (logbuffer, entry->offset);
3812 emit_uvalue (logbuffer, entry->counter);
3813 emit_uvalue (logbuffer, entry->line);
3814 emit_uvalue (logbuffer, entry->column);
3823 g_free (class_name);
3825 g_ptr_array_foreach (coverage_data, free_coverage_entry, NULL);
3826 g_ptr_array_free (coverage_data, TRUE);
3827 coverage_data = NULL;
3830 /* This empties the queue */
3832 count_queue (MonoLockFreeQueue *queue)
3834 MonoLockFreeQueueNode *node;
3837 while ((node = mono_lock_free_queue_dequeue (queue))) {
3839 mono_thread_hazardous_try_free (node, free);
3846 build_class_buffer (gpointer key, gpointer value, gpointer userdata)
3848 MonoClass *klass = (MonoClass *)key;
3849 MonoLockFreeQueue *class_methods = (MonoLockFreeQueue *)value;
3850 MonoProfiler *prof = (MonoProfiler *)userdata;
3853 const char *assembly_name;
3854 int number_of_methods, partially_covered;
3855 guint fully_covered;
3857 image = mono_class_get_image (klass);
3858 assembly_name = mono_image_get_name (image);
3859 class_name = mono_type_get_name (mono_class_get_type (klass));
3861 assembly_name = assembly_name ? assembly_name : "";
3862 number_of_methods = mono_class_num_methods (klass);
3863 fully_covered = count_queue (class_methods);
3864 /* We don't handle partial covered yet */
3865 partially_covered = 0;
3869 LogBuffer *logbuffer = ensure_logbuf (
3870 EVENT_SIZE /* event */ +
3871 strlen (assembly_name) + 1 /* assembly name */ +
3872 strlen (class_name) + 1 /* class name */ +
3873 LEB128_SIZE /* no. methods */ +
3874 LEB128_SIZE /* fully covered */ +
3875 LEB128_SIZE /* partially covered */
3878 emit_byte (logbuffer, TYPE_COVERAGE_CLASS | TYPE_COVERAGE);
3879 emit_string (logbuffer, assembly_name, strlen (assembly_name) + 1);
3880 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3881 emit_uvalue (logbuffer, number_of_methods);
3882 emit_uvalue (logbuffer, fully_covered);
3883 emit_uvalue (logbuffer, partially_covered);
3889 g_free (class_name);
3893 get_coverage_for_image (MonoImage *image, int *number_of_methods, guint *fully_covered, int *partially_covered)
3895 MonoLockFreeQueue *image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3897 *number_of_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
3899 *fully_covered = count_queue (image_methods);
3903 // FIXME: We don't handle partially covered yet.
3904 *partially_covered = 0;
3908 build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
3910 MonoAssembly *assembly = (MonoAssembly *)value;
3911 MonoProfiler *prof = (MonoProfiler *)userdata;
3912 MonoImage *image = mono_assembly_get_image (assembly);
3913 const char *name, *guid, *filename;
3914 int number_of_methods = 0, partially_covered = 0;
3915 guint fully_covered = 0;
3917 name = mono_image_get_name (image);
3918 guid = mono_image_get_guid (image);
3919 filename = mono_image_get_filename (image);
3921 name = name ? name : "";
3922 guid = guid ? guid : "";
3923 filename = filename ? filename : "";
3925 get_coverage_for_image (image, &number_of_methods, &fully_covered, &partially_covered);
3929 LogBuffer *logbuffer = ensure_logbuf (
3930 EVENT_SIZE /* event */ +
3931 strlen (name) + 1 /* name */ +
3932 strlen (guid) + 1 /* guid */ +
3933 strlen (filename) + 1 /* file name */ +
3934 LEB128_SIZE /* no. methods */ +
3935 LEB128_SIZE /* fully covered */ +
3936 LEB128_SIZE /* partially covered */
3939 emit_byte (logbuffer, TYPE_COVERAGE_ASSEMBLY | TYPE_COVERAGE);
3940 emit_string (logbuffer, name, strlen (name) + 1);
3941 emit_string (logbuffer, guid, strlen (guid) + 1);
3942 emit_string (logbuffer, filename, strlen (filename) + 1);
3943 emit_uvalue (logbuffer, number_of_methods);
3944 emit_uvalue (logbuffer, fully_covered);
3945 emit_uvalue (logbuffer, partially_covered);
3953 dump_coverage (MonoProfiler *prof)
3955 if (!coverage_initialized)
3958 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Started dump\n");)
3961 mono_os_mutex_lock (&coverage_mutex);
3962 mono_conc_hashtable_foreach (coverage_assemblies, build_assembly_buffer, prof);
3963 mono_conc_hashtable_foreach (coverage_classes, build_class_buffer, prof);
3964 mono_conc_hashtable_foreach (coverage_methods, build_method_buffer, prof);
3965 mono_os_mutex_unlock (&coverage_mutex);
3967 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Finished dump\n");)
3971 process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method)
3976 if (!coverage_initialized)
3979 klass = mono_method_get_class (method);
3980 image = mono_class_get_image (klass);
3982 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)))
3985 mono_os_mutex_lock (&coverage_mutex);
3986 mono_conc_hashtable_insert (entered_methods, method, method);
3987 mono_os_mutex_unlock (&coverage_mutex);
3990 static MonoLockFreeQueueNode *
3991 create_method_node (MonoMethod *method)
3993 MethodNode *node = (MethodNode *)g_malloc (sizeof (MethodNode));
3994 mono_lock_free_queue_node_init ((MonoLockFreeQueueNode *) node, FALSE);
3995 node->method = method;
3997 return (MonoLockFreeQueueNode *) node;
4001 coverage_filter (MonoProfiler *prof, MonoMethod *method)
4006 MonoAssembly *assembly;
4007 MonoMethodHeader *header;
4008 guint32 iflags, flags, code_size;
4009 char *fqn, *classname;
4010 gboolean has_positive, found;
4011 MonoLockFreeQueue *image_methods, *class_methods;
4012 MonoLockFreeQueueNode *node;
4014 if (!coverage_initialized)
4017 COVERAGE_DEBUG(fprintf (stderr, "Coverage filter for %s\n", mono_method_get_name (method));)
4019 flags = mono_method_get_flags (method, &iflags);
4020 if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
4021 (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/)) {
4022 COVERAGE_DEBUG(fprintf (stderr, " Internal call or pinvoke - ignoring\n");)
4026 // Don't need to do anything else if we're already tracking this method
4027 if (mono_conc_hashtable_lookup (coverage_methods, method)) {
4028 COVERAGE_DEBUG(fprintf (stderr, " Already tracking\n");)
4032 klass = mono_method_get_class (method);
4033 image = mono_class_get_image (klass);
4035 // Don't handle coverage for the core assemblies
4036 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)) != NULL)
4039 if (prof->coverage_filters) {
4040 /* Check already filtered classes first */
4041 if (mono_conc_hashtable_lookup (filtered_classes, klass)) {
4042 COVERAGE_DEBUG(fprintf (stderr, " Already filtered\n");)
4046 classname = mono_type_get_name (mono_class_get_type (klass));
4048 fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
4050 COVERAGE_DEBUG(fprintf (stderr, " Looking for %s in filter\n", fqn);)
4051 // Check positive filters first
4052 has_positive = FALSE;
4054 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
4055 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
4057 if (filter [0] == '+') {
4058 filter = &filter [1];
4060 COVERAGE_DEBUG(fprintf (stderr, " Checking against +%s ...", filter);)
4062 if (strstr (fqn, filter) != NULL) {
4063 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
4066 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
4068 has_positive = TRUE;
4072 if (has_positive && !found) {
4073 COVERAGE_DEBUG(fprintf (stderr, " Positive match was not found\n");)
4075 mono_os_mutex_lock (&coverage_mutex);
4076 mono_conc_hashtable_insert (filtered_classes, klass, klass);
4077 mono_os_mutex_unlock (&coverage_mutex);
4084 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
4085 // FIXME: Is substring search sufficient?
4086 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
4087 if (filter [0] == '+')
4091 filter = &filter [1];
4092 COVERAGE_DEBUG(fprintf (stderr, " Checking against -%s ...", filter);)
4094 if (strstr (fqn, filter) != NULL) {
4095 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
4097 mono_os_mutex_lock (&coverage_mutex);
4098 mono_conc_hashtable_insert (filtered_classes, klass, klass);
4099 mono_os_mutex_unlock (&coverage_mutex);
4105 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
4113 COVERAGE_DEBUG(fprintf (stderr, " Handling coverage for %s\n", mono_method_get_name (method));)
4114 header = mono_method_get_header_checked (method, &error);
4115 mono_error_cleanup (&error);
4117 mono_method_header_get_code (header, &code_size, NULL);
4119 assembly = mono_image_get_assembly (image);
4121 // Need to keep the assemblies around for as long as they are kept in the hashtable
4122 // Nunit, for example, has a habit of unloading them before the coverage statistics are
4123 // generated causing a crash. See https://bugzilla.xamarin.com/show_bug.cgi?id=39325
4124 mono_assembly_addref (assembly);
4126 mono_os_mutex_lock (&coverage_mutex);
4127 mono_conc_hashtable_insert (coverage_methods, method, method);
4128 mono_conc_hashtable_insert (coverage_assemblies, assembly, assembly);
4129 mono_os_mutex_unlock (&coverage_mutex);
4131 image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
4133 if (image_methods == NULL) {
4134 image_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
4135 mono_lock_free_queue_init (image_methods);
4136 mono_os_mutex_lock (&coverage_mutex);
4137 mono_conc_hashtable_insert (image_to_methods, image, image_methods);
4138 mono_os_mutex_unlock (&coverage_mutex);
4141 node = create_method_node (method);
4142 mono_lock_free_queue_enqueue (image_methods, node);
4144 class_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (coverage_classes, klass);
4146 if (class_methods == NULL) {
4147 class_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
4148 mono_lock_free_queue_init (class_methods);
4149 mono_os_mutex_lock (&coverage_mutex);
4150 mono_conc_hashtable_insert (coverage_classes, klass, class_methods);
4151 mono_os_mutex_unlock (&coverage_mutex);
4154 node = create_method_node (method);
4155 mono_lock_free_queue_enqueue (class_methods, node);
4160 #define LINE_BUFFER_SIZE 4096
4161 /* Max file limit of 128KB */
4162 #define MAX_FILE_SIZE 128 * 1024
4164 get_file_content (FILE *stream)
4169 int res, offset = 0;
4171 res = fseek (stream, 0, SEEK_END);
4175 filesize = ftell (stream);
4179 res = fseek (stream, 0, SEEK_SET);
4183 if (filesize > MAX_FILE_SIZE)
4186 buffer = (char *)g_malloc ((filesize + 1) * sizeof (char));
4187 while ((bytes_read = fread (buffer + offset, 1, LINE_BUFFER_SIZE, stream)) > 0)
4188 offset += bytes_read;
4190 /* NULL terminate our buffer */
4191 buffer[filesize] = '\0';
4196 get_next_line (char *contents, char **next_start)
4200 if (p == NULL || *p == '\0') {
4205 while (*p != '\n' && *p != '\0')
4210 *next_start = p + 1;
4218 init_suppressed_assemblies (void)
4224 suppressed_assemblies = mono_conc_hashtable_new (g_str_hash, g_str_equal);
4225 sa_file = fopen (SUPPRESSION_DIR "/mono-profiler-log.suppression", "r");
4226 if (sa_file == NULL)
4229 /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
4230 content = get_file_content (sa_file);
4231 if (content == NULL) {
4232 g_error ("mono-profiler-log.suppression is greater than 128kb - aborting\n");
4235 while ((line = get_next_line (content, &content))) {
4236 line = g_strchomp (g_strchug (line));
4237 /* No locking needed as we're doing initialization */
4238 mono_conc_hashtable_insert (suppressed_assemblies, line, line);
4244 #endif /* DISABLE_HELPER_THREAD */
4247 coverage_init (MonoProfiler *prof)
4249 #ifndef DISABLE_HELPER_THREAD
4250 assert (!coverage_initialized);
4252 COVERAGE_DEBUG(fprintf (stderr, "Coverage initialized\n");)
4254 mono_os_mutex_init (&coverage_mutex);
4255 coverage_methods = mono_conc_hashtable_new (NULL, NULL);
4256 coverage_assemblies = mono_conc_hashtable_new (NULL, NULL);
4257 coverage_classes = mono_conc_hashtable_new (NULL, NULL);
4258 filtered_classes = mono_conc_hashtable_new (NULL, NULL);
4259 entered_methods = mono_conc_hashtable_new (NULL, NULL);
4260 image_to_methods = mono_conc_hashtable_new (NULL, NULL);
4261 init_suppressed_assemblies ();
4263 coverage_initialized = TRUE;
4264 #endif /* DISABLE_HELPER_THREAD */
4268 unref_coverage_assemblies (gpointer key, gpointer value, gpointer userdata)
4270 MonoAssembly *assembly = (MonoAssembly *)value;
4271 mono_assembly_close (assembly);
4275 free_sample_hit (gpointer p)
4277 mono_lock_free_free (p, SAMPLE_BLOCK_SIZE);
4281 cleanup_reusable_samples (MonoProfiler *prof)
4285 while ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&prof->sample_reuse_queue)))
4286 mono_thread_hazardous_try_free (sample, free_sample_hit);
4290 log_shutdown (MonoProfiler *prof)
4295 #ifndef DISABLE_HELPER_THREAD
4296 counters_and_perfcounters_sample (prof, FALSE);
4298 dump_coverage (prof);
4300 if (prof->command_port) {
4302 ign_res (write (prof->pipes [1], &c, 1));
4303 pthread_join (prof->helper_thread, &res);
4309 for (i = 0; i < num_perf; ++i)
4310 read_perf_mmap (prof, i);
4315 * Ensure that we empty the LLS completely, even if some nodes are
4316 * not immediately removed upon calling mono_lls_remove (), by
4317 * iterating until the head is NULL.
4319 while (profiler_thread_list.head) {
4320 MONO_LLS_FOREACH_SAFE (&profiler_thread_list, MonoProfilerThread, thread) {
4321 remove_thread (prof, thread, FALSE);
4322 } MONO_LLS_FOREACH_SAFE_END
4325 InterlockedWrite (&prof->run_dumper_thread, 0);
4326 mono_os_sem_post (&prof->dumper_queue_sem);
4327 pthread_join (prof->dumper_thread, &res);
4328 mono_os_sem_destroy (&prof->dumper_queue_sem);
4330 InterlockedWrite (&prof->run_writer_thread, 0);
4331 mono_os_sem_post (&prof->writer_queue_sem);
4332 pthread_join (prof->writer_thread, &res);
4333 mono_os_sem_destroy (&prof->writer_queue_sem);
4335 cleanup_reusable_samples (prof);
4337 g_assert (!InterlockedRead (&buffer_rwlock_count) && "Why is the reader count still non-zero?");
4338 g_assert (!InterlockedReadPointer (&buffer_rwlock_exclusive) && "Why does someone still hold the exclusive lock?");
4340 #if defined (HAVE_SYS_ZLIB)
4342 gzclose (prof->gzfile);
4344 if (prof->pipe_output)
4345 pclose (prof->file);
4347 fclose (prof->file);
4349 mono_conc_hashtable_destroy (prof->method_table);
4350 mono_os_mutex_destroy (&prof->method_table_mutex);
4352 if (coverage_initialized) {
4353 mono_os_mutex_lock (&coverage_mutex);
4354 mono_conc_hashtable_foreach (coverage_assemblies, unref_coverage_assemblies, prof);
4355 mono_os_mutex_unlock (&coverage_mutex);
4357 mono_conc_hashtable_destroy (coverage_methods);
4358 mono_conc_hashtable_destroy (coverage_assemblies);
4359 mono_conc_hashtable_destroy (coverage_classes);
4360 mono_conc_hashtable_destroy (filtered_classes);
4362 mono_conc_hashtable_destroy (entered_methods);
4363 mono_conc_hashtable_destroy (image_to_methods);
4364 mono_conc_hashtable_destroy (suppressed_assemblies);
4365 mono_os_mutex_destroy (&coverage_mutex);
4374 new_filename (const char* filename)
4376 time_t t = time (NULL);
4377 int pid = process_id ();
4382 int count_dates = 0;
4386 for (p = filename; *p; p++) {
4397 if (!count_dates && !count_pids)
4398 return pstrdup (filename);
4399 snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
4401 snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
4402 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
4403 s_date = strlen (time_buf);
4404 s_pid = strlen (pid_buf);
4405 d = res = (char *)malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
4406 for (p = filename; *p; p++) {
4413 strcpy (d, time_buf);
4416 } else if (*p == 'p') {
4417 strcpy (d, pid_buf);
4420 } else if (*p == '%') {
4432 //this is exposed by the JIT, but it's not meant to be a supported API for now.
4433 extern void mono_threads_attach_tools_thread (void);
4435 #ifndef DISABLE_HELPER_THREAD
4438 helper_thread (void* arg)
4440 MonoProfiler* prof = (MonoProfiler *)arg;
4444 MonoThread *thread = NULL;
4446 mono_threads_attach_tools_thread ();
4447 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler helper");
4449 init_thread (FALSE);
4451 //fprintf (stderr, "Server listening\n");
4452 command_socket = -1;
4458 FD_SET (prof->server_socket, &rfds);
4459 max_fd = prof->server_socket;
4460 FD_SET (prof->pipes [0], &rfds);
4461 if (max_fd < prof->pipes [0])
4462 max_fd = prof->pipes [0];
4463 if (command_socket >= 0) {
4464 FD_SET (command_socket, &rfds);
4465 if (max_fd < command_socket)
4466 max_fd = command_socket;
4471 for ( i = 0; i < num_perf; ++i) {
4472 if (perf_data [i].perf_fd < 0)
4474 FD_SET (perf_data [i].perf_fd, &rfds);
4475 if (max_fd < perf_data [i].perf_fd)
4476 max_fd = perf_data [i].perf_fd;
4481 counters_and_perfcounters_sample (prof, TRUE);
4483 buffer_lock_excl ();
4485 // Periodically flush all thread-local buffers.
4486 MONO_LLS_FOREACH_SAFE (&profiler_thread_list, MonoProfilerThread, thread) {
4487 send_buffer (prof, thread);
4488 init_buffer_state (thread);
4489 } MONO_LLS_FOREACH_SAFE_END
4491 buffer_unlock_excl ();
4495 len = select (max_fd + 1, &rfds, NULL, NULL, &tv);
4501 g_warning ("Error in proflog server: %s", strerror (errno));
4505 if (FD_ISSET (prof->pipes [0], &rfds)) {
4507 read (prof->pipes [0], &c, 1);
4509 mono_thread_detach (thread);
4511 fprintf (stderr, "helper shutdown\n");
4515 for ( i = 0; i < num_perf; ++i) {
4516 if (perf_data [i].perf_fd < 0)
4518 if (FD_ISSET (perf_data [i].perf_fd, &rfds))
4519 read_perf_mmap (prof, i);
4523 safe_send_threadless (prof);
4529 for ( i = 0; i < num_perf; ++i) {
4530 if (perf_data [i].perf_fd < 0)
4532 if (FD_ISSET (perf_data [i].perf_fd, &rfds)) {
4533 read_perf_mmap (prof, i);
4534 safe_send_threadless (prof);
4539 if (command_socket >= 0 && FD_ISSET (command_socket, &rfds)) {
4540 len = read (command_socket, buf, sizeof (buf) - 1);
4544 close (command_socket);
4545 command_socket = -1;
4549 if (strcmp (buf, "heapshot\n") == 0) {
4550 heapshot_requested = 1;
4551 //fprintf (stderr, "perform heapshot\n");
4552 if (InterlockedRead (&runtime_inited) && !thread) {
4553 thread = mono_thread_attach (mono_get_root_domain ());
4554 /*fprintf (stderr, "attached\n");*/
4557 process_requests (prof);
4558 mono_thread_detach (thread);
4564 if (!FD_ISSET (prof->server_socket, &rfds)) {
4567 command_socket = accept (prof->server_socket, NULL, NULL);
4568 if (command_socket < 0)
4570 //fprintf (stderr, "Accepted connection\n");
4573 mono_thread_info_detach ();
4579 start_helper_thread (MonoProfiler* prof)
4581 struct sockaddr_in server_address;
4584 if (pipe (prof->pipes) < 0) {
4585 fprintf (stderr, "Cannot create pipe\n");
4588 prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
4589 if (prof->server_socket < 0) {
4590 fprintf (stderr, "Cannot create server socket\n");
4593 memset (&server_address, 0, sizeof (server_address));
4594 server_address.sin_family = AF_INET;
4595 server_address.sin_addr.s_addr = INADDR_ANY;
4596 server_address.sin_port = htons (prof->command_port);
4597 if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) < 0) {
4598 fprintf (stderr, "Cannot bind server socket, port: %d: %s\n", prof->command_port, strerror (errno));
4599 close (prof->server_socket);
4602 if (listen (prof->server_socket, 1) < 0) {
4603 fprintf (stderr, "Cannot listen server socket\n");
4604 close (prof->server_socket);
4607 slen = sizeof (server_address);
4608 if (getsockname (prof->server_socket, (struct sockaddr *)&server_address, &slen) == 0) {
4609 prof->command_port = ntohs (server_address.sin_port);
4610 /*fprintf (stderr, "Assigned server port: %d\n", prof->command_port);*/
4613 r = pthread_create (&prof->helper_thread, NULL, helper_thread, prof);
4615 close (prof->server_socket);
4623 free_writer_entry (gpointer p)
4625 mono_lock_free_free (p, WRITER_ENTRY_BLOCK_SIZE);
4629 handle_writer_queue_entry (MonoProfiler *prof)
4631 WriterQueueEntry *entry;
4633 if ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&prof->writer_queue))) {
4634 if (!entry->methods)
4637 LogBuffer *buf = NULL;
4640 * Encode the method events in a temporary log buffer that we
4641 * flush to disk before the main buffer, ensuring that all
4642 * methods have metadata emitted before they're referenced.
4644 * We use a 'proper' thread-local buffer for this as opposed
4645 * to allocating and freeing a buffer by hand because the call
4646 * to mono_method_full_name () below may trigger class load
4647 * events when it retrieves the signature of the method. So a
4648 * thread-local buffer needs to exist when such events occur.
4650 for (guint i = 0; i < entry->methods->len; i++) {
4651 MethodInfo *info = (MethodInfo *) g_ptr_array_index (entry->methods, i);
4653 if (mono_conc_hashtable_lookup (prof->method_table, info->method))
4654 goto free_info; // This method already has metadata emitted.
4657 * Other threads use this hash table to get a general
4658 * idea of whether a method has already been emitted to
4659 * the stream. Due to the way we add to this table, it
4660 * can easily happen that multiple threads queue up the
4661 * same methods, but that's OK since eventually all
4662 * methods will be in this table and the thread-local
4663 * method lists will just be empty for the rest of the
4666 mono_os_mutex_lock (&prof->method_table_mutex);
4667 mono_conc_hashtable_insert (prof->method_table, info->method, info->method);
4668 mono_os_mutex_unlock (&prof->method_table_mutex);
4670 char *name = mono_method_full_name (info->method, 1);
4671 int nlen = strlen (name) + 1;
4672 void *cstart = info->ji ? mono_jit_info_get_code_start (info->ji) : NULL;
4673 int csize = info->ji ? mono_jit_info_get_code_size (info->ji) : 0;
4675 buf = ensure_logbuf_unsafe (
4676 EVENT_SIZE /* event */ +
4677 LEB128_SIZE /* time */ +
4678 LEB128_SIZE /* method */ +
4679 LEB128_SIZE /* start */ +
4680 LEB128_SIZE /* size */ +
4684 emit_byte (buf, TYPE_JIT | TYPE_METHOD);
4685 emit_time (buf, info->time);
4686 emit_method_inner (buf, info->method);
4687 emit_ptr (buf, cstart);
4688 emit_value (buf, csize);
4690 memcpy (buf->cursor, name, nlen);
4691 buf->cursor += nlen;
4699 g_ptr_array_free (entry->methods, TRUE);
4702 dump_buffer_threadless (prof, buf);
4703 init_buffer_state (PROF_TLS_GET ());
4707 dump_buffer (prof, entry->buffer);
4709 mono_thread_hazardous_try_free (entry, free_writer_entry);
4718 writer_thread (void *arg)
4720 MonoProfiler *prof = (MonoProfiler *)arg;
4722 mono_threads_attach_tools_thread ();
4723 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler writer");
4727 MonoProfilerThread *thread = init_thread (FALSE);
4729 while (InterlockedRead (&prof->run_writer_thread)) {
4730 mono_os_sem_wait (&prof->writer_queue_sem, MONO_SEM_FLAGS_NONE);
4731 handle_writer_queue_entry (prof);
4734 /* Drain any remaining entries on shutdown. */
4735 while (handle_writer_queue_entry (prof));
4737 free_buffer (thread->buffer, thread->buffer->size);
4738 deinit_thread (thread);
4740 mono_thread_info_detach ();
4746 start_writer_thread (MonoProfiler* prof)
4748 InterlockedWrite (&prof->run_writer_thread, 1);
4750 return !pthread_create (&prof->writer_thread, NULL, writer_thread, prof);
4754 reuse_sample_hit (gpointer p)
4756 SampleHit *sample = p;
4758 mono_lock_free_queue_node_unpoison (&sample->node);
4759 mono_lock_free_queue_enqueue (&sample->prof->sample_reuse_queue, &sample->node);
4763 handle_dumper_queue_entry (MonoProfiler *prof)
4767 if ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&prof->dumper_queue))) {
4768 for (int i = 0; i < sample->count; ++i) {
4769 MonoMethod *method = sample->frames [i].method;
4770 MonoDomain *domain = sample->frames [i].domain;
4771 void *address = sample->frames [i].base_address;
4774 g_assert (domain && "What happened to the domain pointer?");
4775 g_assert (address && "What happened to the instruction pointer?");
4777 MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *) address);
4780 sample->frames [i].method = mono_jit_info_get_method (ji);
4784 LogBuffer *logbuffer = ensure_logbuf_unsafe (
4785 EVENT_SIZE /* event */ +
4786 LEB128_SIZE /* type */ +
4787 LEB128_SIZE /* time */ +
4788 LEB128_SIZE /* tid */ +
4789 LEB128_SIZE /* count */ +
4791 LEB128_SIZE /* ip */
4793 LEB128_SIZE /* managed count */ +
4795 LEB128_SIZE /* method */ +
4796 LEB128_SIZE /* il offset */ +
4797 LEB128_SIZE /* native offset */
4801 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
4802 emit_value (logbuffer, sample_type);
4803 emit_uvalue (logbuffer, prof->startup_time + sample->elapsed * 10000);
4804 emit_ptr (logbuffer, (void *) sample->tid);
4805 emit_value (logbuffer, 1);
4807 // TODO: Actual native unwinding.
4808 for (int i = 0; i < 1; ++i) {
4809 emit_ptr (logbuffer, sample->ip);
4810 add_code_pointer ((uintptr_t) sample->ip);
4813 /* new in data version 6 */
4814 emit_uvalue (logbuffer, sample->count);
4816 for (int i = 0; i < sample->count; ++i) {
4817 emit_method (prof, logbuffer, sample->frames [i].method);
4818 emit_svalue (logbuffer, 0); /* il offset will always be 0 from now on */
4819 emit_svalue (logbuffer, sample->frames [i].offset);
4822 mono_thread_hazardous_try_free (sample, reuse_sample_hit);
4824 dump_unmanaged_coderefs (prof);
4826 if (logbuffer->next)
4827 safe_send_threadless (prof);
4834 dumper_thread (void *arg)
4836 MonoProfiler *prof = (MonoProfiler *)arg;
4838 mono_threads_attach_tools_thread ();
4839 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler dumper");
4841 MonoProfilerThread *thread = init_thread (FALSE);
4843 while (InterlockedRead (&prof->run_dumper_thread)) {
4844 mono_os_sem_wait (&prof->dumper_queue_sem, MONO_SEM_FLAGS_NONE);
4845 handle_dumper_queue_entry (prof);
4848 /* Drain any remaining entries on shutdown. */
4849 while (handle_dumper_queue_entry (prof));
4851 safe_send_threadless (prof);
4852 deinit_thread (thread);
4854 mono_thread_info_detach ();
4860 start_dumper_thread (MonoProfiler* prof)
4862 InterlockedWrite (&prof->run_dumper_thread, 1);
4864 return !pthread_create (&prof->dumper_thread, NULL, dumper_thread, prof);
4868 runtime_initialized (MonoProfiler *profiler)
4870 #ifndef DISABLE_HELPER_THREAD
4871 if (hs_mode_ondemand || need_helper_thread) {
4872 if (!start_helper_thread (profiler))
4873 profiler->command_port = 0;
4877 start_writer_thread (profiler);
4878 start_dumper_thread (profiler);
4880 InterlockedWrite (&runtime_inited, 1);
4881 #ifndef DISABLE_HELPER_THREAD
4882 counters_init (profiler);
4883 counters_sample (profiler, 0, FALSE);
4885 /* ensure the main thread data and startup are available soon */
4886 safe_send (profiler);
4889 static MonoProfiler*
4890 create_profiler (const char *filename, GPtrArray *filters)
4894 int force_delete = 0;
4895 prof = (MonoProfiler *)calloc (1, sizeof (MonoProfiler));
4897 prof->command_port = command_port;
4898 if (filename && *filename == '-') {
4904 filename = "|mprof-report -";
4906 filename = "output.mlpd";
4907 nf = (char*)filename;
4909 nf = new_filename (filename);
4911 int s = strlen (nf) + 32;
4912 char *p = (char *)malloc (s);
4913 snprintf (p, s, "|mprof-report '--out=%s' -", nf);
4919 prof->file = popen (nf + 1, "w");
4920 prof->pipe_output = 1;
4921 } else if (*nf == '#') {
4922 int fd = strtol (nf + 1, NULL, 10);
4923 prof->file = fdopen (fd, "a");
4927 prof->file = fopen (nf, "wb");
4930 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
4933 #if defined (HAVE_SYS_ZLIB)
4935 prof->gzfile = gzdopen (fileno (prof->file), "wb");
4938 if (sample_type && !do_mono_sample)
4939 need_helper_thread = setup_perf_event ();
4941 /* FIXME: warn if different freq or sample type */
4945 if (do_mono_sample) {
4946 need_helper_thread = 1;
4948 if (do_counters && !need_helper_thread) {
4949 need_helper_thread = 1;
4953 * If you hit this assert while increasing MAX_FRAMES, you need to increase
4954 * SAMPLE_BLOCK_SIZE as well.
4956 g_assert (SAMPLE_SLOT_SIZE (MAX_FRAMES) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (SAMPLE_BLOCK_SIZE));
4958 // FIXME: We should free this stuff too.
4959 mono_lock_free_allocator_init_size_class (&prof->sample_size_class, SAMPLE_SLOT_SIZE (num_frames), SAMPLE_BLOCK_SIZE);
4960 mono_lock_free_allocator_init_allocator (&prof->sample_allocator, &prof->sample_size_class);
4962 mono_lock_free_queue_init (&prof->sample_reuse_queue);
4964 #ifdef DISABLE_HELPER_THREAD
4965 if (hs_mode_ondemand)
4966 fprintf (stderr, "Ondemand heapshot unavailable on this arch.\n");
4969 fprintf (stderr, "Coverage unavailable on this arch.\n");
4973 g_assert (sizeof (WriterQueueEntry) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (WRITER_ENTRY_BLOCK_SIZE));
4975 // FIXME: We should free this stuff too.
4976 mono_lock_free_allocator_init_size_class (&prof->writer_entry_size_class, sizeof (WriterQueueEntry), WRITER_ENTRY_BLOCK_SIZE);
4977 mono_lock_free_allocator_init_allocator (&prof->writer_entry_allocator, &prof->writer_entry_size_class);
4979 mono_lock_free_queue_init (&prof->writer_queue);
4980 mono_os_sem_init (&prof->writer_queue_sem, 0);
4982 mono_lock_free_queue_init (&prof->dumper_queue);
4983 mono_os_sem_init (&prof->dumper_queue_sem, 0);
4985 mono_os_mutex_init (&prof->method_table_mutex);
4986 prof->method_table = mono_conc_hashtable_new (NULL, NULL);
4989 coverage_init (prof);
4990 prof->coverage_filters = filters;
4992 prof->startup_time = current_time ();
4999 printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
5000 printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
5001 printf ("Options:\n");
5002 printf ("\thelp show this usage info\n");
5003 printf ("\t[no]alloc enable/disable recording allocation info\n");
5004 printf ("\t[no]calls enable/disable recording enter/leave method events\n");
5005 printf ("\theapshot[=MODE] record heap shot info (by default at each major collection)\n");
5006 printf ("\t MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
5007 printf ("\tcounters sample counters every 1s\n");
5008 printf ("\tsample[=TYPE] use statistical sampling mode (by default cycles/100)\n");
5009 printf ("\t TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
5010 printf ("\t TYPE can be followed by /FREQUENCY\n");
5011 printf ("\ttime=fast use a faster (but more inaccurate) timer\n");
5012 printf ("\tmaxframes=NUM collect up to NUM stack frames\n");
5013 printf ("\tcalldepth=NUM ignore method events for call chain depth bigger than NUM\n");
5014 printf ("\toutput=FILENAME write the data to file FILENAME (-FILENAME to overwrite)\n");
5015 printf ("\toutput=|PROGRAM write the data to the stdin of PROGRAM\n");
5016 printf ("\t %%t is subtituted with date and time, %%p with the pid\n");
5017 printf ("\treport create a report instead of writing the raw data to a file\n");
5018 printf ("\tzip compress the output data\n");
5019 printf ("\tport=PORTNUM use PORTNUM for the listening command server\n");
5020 printf ("\tcoverage enable collection of code coverage data\n");
5021 printf ("\tcovfilter=ASSEMBLY add an assembly to the code coverage filters\n");
5022 printf ("\t add a + to include the assembly or a - to exclude it\n");
5023 printf ("\t filter=-mscorlib\n");
5024 printf ("\tcovfilter-file=FILE use FILE to generate the list of assemblies to be filtered\n");
5030 match_option (const char* p, const char *opt, char **rval)
5032 int len = strlen (opt);
5033 if (strncmp (p, opt, len) == 0) {
5035 if (p [len] == '=' && p [len + 1]) {
5036 const char *opt = p + len + 1;
5037 const char *end = strchr (opt, ',');
5045 val = (char *)malloc (l + 1);
5046 memcpy (val, opt, l);
5051 if (p [len] == 0 || p [len] == ',') {
5053 return p + len + (p [len] == ',');
5071 static const SampleMode sample_modes [] = {
5072 {"cycles", SAMPLE_CYCLES},
5073 {"instr", SAMPLE_INSTRUCTIONS},
5074 {"cachemiss", SAMPLE_CACHE_MISSES},
5075 {"cacherefs", SAMPLE_CACHE_REFS},
5076 {"branches", SAMPLE_BRANCHES},
5077 {"branchmiss", SAMPLE_BRANCH_MISSES},
5082 set_sample_mode (char* val, int allow_empty)
5085 char *maybe_freq = NULL;
5087 const SampleMode *smode = sample_modes;
5088 #ifndef USE_PERF_EVENTS
5091 if (allow_empty && !val) {
5092 sample_type = SAMPLE_CYCLES;
5096 if (strcmp (val, "mono") == 0) {
5098 sample_type = SAMPLE_CYCLES;
5102 for (smode = sample_modes; smode->name; smode++) {
5103 int l = strlen (smode->name);
5104 if (strncmp (val, smode->name, l) == 0) {
5105 sample_type = smode->sample_mode;
5106 maybe_freq = val + l;
5112 if (*maybe_freq == '/') {
5113 count = strtoul (maybe_freq + 1, &end, 10);
5114 if (maybe_freq + 1 == end)
5116 sample_freq = count;
5117 } else if (*maybe_freq != 0) {
5126 set_hsmode (char* val, int allow_empty)
5130 if (allow_empty && !val)
5132 if (strcmp (val, "ondemand") == 0) {
5133 hs_mode_ondemand = 1;
5137 count = strtoul (val, &end, 10);
5140 if (strcmp (end, "ms") == 0)
5142 else if (strcmp (end, "gc") == 0)
5150 * declaration to silence the compiler: this is the entry point that
5151 * mono will load from the shared library and call.
5154 mono_profiler_startup (const char *desc);
5157 mono_profiler_startup_log (const char *desc);
5160 * this is the entry point that will be used when the profiler
5161 * is embedded inside the main executable.
5164 mono_profiler_startup_log (const char *desc)
5166 mono_profiler_startup (desc);
5170 mono_profiler_startup (const char *desc)
5173 GPtrArray *filters = NULL;
5174 char *filename = NULL;
5178 int calls_enabled = 0;
5179 int allocs_enabled = 0;
5180 int only_counters = 0;
5181 int only_coverage = 0;
5182 int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
5183 MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
5184 MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
5185 MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS|
5186 MONO_PROFILE_INS_COVERAGE|MONO_PROFILE_APPDOMAIN_EVENTS|MONO_PROFILE_CONTEXT_EVENTS|
5187 MONO_PROFILE_ASSEMBLY_EVENTS;
5189 max_allocated_sample_hits = mono_cpu_count () * 1000;
5191 mono_counters_register ("Sample hits", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &sample_hits);
5192 mono_counters_register ("Sample flushes", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &sample_flushes);
5193 mono_counters_register ("Sample events allocated", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &sample_allocations);
5194 mono_counters_register ("Log buffers allocated", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &buffer_allocations);
5195 mono_counters_register ("Thread start events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &thread_starts);
5196 mono_counters_register ("Thread stop events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &thread_ends);
5197 mono_counters_register ("Domain load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &domain_loads);
5198 mono_counters_register ("Domain unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &domain_unloads);
5199 mono_counters_register ("Context load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &context_loads);
5200 mono_counters_register ("Context unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &context_unloads);
5201 mono_counters_register ("Assembly load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &assembly_loads);
5202 mono_counters_register ("Assembly unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &assembly_unloads);
5203 mono_counters_register ("Image load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &image_loads);
5204 mono_counters_register ("Image unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &image_unloads);
5205 mono_counters_register ("Class load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &class_loads);
5206 mono_counters_register ("Class unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &class_unloads);
5209 if (strncmp (p, "log", 3))
5214 for (; *p; p = opt) {
5220 if ((opt = match_option (p, "help", NULL)) != p) {
5224 if ((opt = match_option (p, "calls", NULL)) != p) {
5228 if ((opt = match_option (p, "nocalls", NULL)) != p) {
5229 events &= ~MONO_PROFILE_ENTER_LEAVE;
5233 if ((opt = match_option (p, "alloc", NULL)) != p) {
5237 if ((opt = match_option (p, "noalloc", NULL)) != p) {
5238 events &= ~MONO_PROFILE_ALLOCATIONS;
5241 if ((opt = match_option (p, "time", &val)) != p) {
5242 if (strcmp (val, "fast") == 0)
5244 else if (strcmp (val, "null") == 0)
5251 if ((opt = match_option (p, "report", NULL)) != p) {
5255 if ((opt = match_option (p, "debug", NULL)) != p) {
5259 if ((opt = match_option (p, "sampling-real", NULL)) != p) {
5260 sampling_mode = MONO_PROFILER_STAT_MODE_REAL;
5263 if ((opt = match_option (p, "sampling-process", NULL)) != p) {
5264 sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
5267 if ((opt = match_option (p, "heapshot", &val)) != p) {
5268 events &= ~MONO_PROFILE_ALLOCATIONS;
5269 events &= ~MONO_PROFILE_ENTER_LEAVE;
5272 set_hsmode (val, 1);
5275 if ((opt = match_option (p, "sample", &val)) != p) {
5276 events &= ~MONO_PROFILE_ALLOCATIONS;
5277 events &= ~MONO_PROFILE_ENTER_LEAVE;
5279 set_sample_mode (val, 1);
5282 if ((opt = match_option (p, "hsmode", &val)) != p) {
5283 fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
5284 set_hsmode (val, 0);
5287 if ((opt = match_option (p, "zip", NULL)) != p) {
5291 if ((opt = match_option (p, "output", &val)) != p) {
5295 if ((opt = match_option (p, "port", &val)) != p) {
5297 command_port = strtoul (val, &end, 10);
5301 if ((opt = match_option (p, "maxframes", &val)) != p) {
5303 num_frames = strtoul (val, &end, 10);
5304 if (num_frames > MAX_FRAMES)
5305 num_frames = MAX_FRAMES;
5307 notraces = num_frames == 0;
5310 if ((opt = match_option (p, "maxsamples", &val)) != p) {
5312 max_allocated_sample_hits = strtoul (val, &end, 10);
5313 if (!max_allocated_sample_hits)
5314 max_allocated_sample_hits = G_MAXINT32;
5318 if ((opt = match_option (p, "calldepth", &val)) != p) {
5320 max_call_depth = strtoul (val, &end, 10);
5324 if ((opt = match_option (p, "counters", NULL)) != p) {
5328 if ((opt = match_option (p, "countersonly", NULL)) != p) {
5332 if ((opt = match_option (p, "coverage", NULL)) != p) {
5334 events |= MONO_PROFILE_ENTER_LEAVE;
5335 debug_coverage = (g_getenv ("MONO_PROFILER_DEBUG_COVERAGE") != NULL);
5338 if ((opt = match_option (p, "onlycoverage", NULL)) != p) {
5342 if ((opt = match_option (p, "covfilter-file", &val)) != p) {
5344 char *line, *content;
5346 if (filters == NULL)
5347 filters = g_ptr_array_new ();
5349 filter_file = fopen (val, "r");
5350 if (filter_file == NULL) {
5351 fprintf (stderr, "Unable to open %s\n", val);
5355 /* Don't need to free content as it is referred to by the lines stored in @filters */
5356 content = get_file_content (filter_file);
5357 if (content == NULL)
5358 fprintf (stderr, "WARNING: %s is greater than 128kb - ignoring\n", val);
5360 while ((line = get_next_line (content, &content)))
5361 g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
5363 fclose (filter_file);
5366 if ((opt = match_option (p, "covfilter", &val)) != p) {
5367 if (filters == NULL)
5368 filters = g_ptr_array_new ();
5370 g_ptr_array_add (filters, val);
5378 if (calls_enabled) {
5379 events |= MONO_PROFILE_ENTER_LEAVE;
5383 events |= MONO_PROFILE_ALLOCATIONS;
5387 events = MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_INS_COVERAGE;
5389 utils_init (fast_time);
5393 prof = create_profiler (filename, filters);
5399 mono_lls_init (&profiler_thread_list, NULL);
5403 mono_profiler_install (prof, log_shutdown);
5404 mono_profiler_install_gc (gc_event, gc_resize);
5405 mono_profiler_install_allocation (gc_alloc);
5406 mono_profiler_install_gc_moves (gc_moves);
5407 mono_profiler_install_gc_roots (gc_handle, gc_roots);
5408 mono_profiler_install_appdomain (NULL, domain_loaded, domain_unloaded, NULL);
5409 mono_profiler_install_appdomain_name (domain_name);
5410 mono_profiler_install_context (context_loaded, context_unloaded);
5411 mono_profiler_install_class (NULL, class_loaded, class_unloaded, NULL);
5412 mono_profiler_install_module (NULL, image_loaded, image_unloaded, NULL);
5413 mono_profiler_install_assembly (NULL, assembly_loaded, assembly_unloaded, NULL);
5414 mono_profiler_install_thread (thread_start, thread_end);
5415 mono_profiler_install_thread_name (thread_name);
5416 mono_profiler_install_enter_leave (method_enter, method_leave);
5417 mono_profiler_install_jit_end (method_jitted);
5418 mono_profiler_install_code_buffer_new (code_buffer_new);
5419 mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
5420 mono_profiler_install_monitor (monitor_event);
5421 mono_profiler_install_runtime_initialized (runtime_initialized);
5423 mono_profiler_install_coverage_filter (coverage_filter);
5425 if (do_mono_sample && sample_type == SAMPLE_CYCLES && !only_counters) {
5426 events |= MONO_PROFILE_STATISTICAL;
5427 mono_profiler_set_statistical_mode (sampling_mode, sample_freq);
5428 mono_profiler_install_statistical (mono_sample_hit);
5431 mono_profiler_set_events ((MonoProfileFlags)events);