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-conc-hashtable.h>
31 #include <mono/utils/lock-free-alloc.h>
32 #include <mono/utils/lock-free-queue.h>
40 #ifdef HAVE_SCHED_GETAFFINITY
45 #if defined(HOST_WIN32) || defined(DISABLE_SOCKETS)
46 #define DISABLE_HELPER_THREAD 1
55 #ifdef HAVE_EXECINFO_H
62 #ifndef DISABLE_HELPER_THREAD
63 #include <sys/types.h>
64 #include <sys/socket.h>
65 #include <netinet/in.h>
66 #include <sys/select.h>
75 #ifdef HAVE_SYS_STAT_H
82 #if defined (HAVE_SYS_ZLIB)
86 #if defined(__linux__)
89 #include <sys/syscall.h>
91 #ifdef ENABLE_PERF_EVENTS
92 #include <linux/perf_event.h>
94 #define USE_PERF_EVENTS 1
96 static int read_perf_mmap (MonoProfiler* prof, int cpu);
101 #define BUFFER_SIZE (4096 * 16)
103 /* Worst-case size in bytes of a 64-bit value encoded with LEB128. */
104 #define LEB128_SIZE 10
105 /* Size in bytes of the event ID prefix. */
108 static int nocalls = 0;
109 static int notraces = 0;
110 static int use_zip = 0;
111 static int do_report = 0;
112 static int do_heap_shot = 0;
113 static int max_call_depth = 100;
114 static volatile int runtime_inited = 0;
115 static int need_helper_thread = 0;
116 static int command_port = 0;
117 static int heapshot_requested = 0;
118 static int sample_type = 0;
119 static int sample_freq = 0;
120 static int do_mono_sample = 0;
121 static int in_shutdown = 0;
122 static int do_debug = 0;
123 static int do_counters = 0;
124 static int do_coverage = 0;
125 static gboolean debug_coverage = FALSE;
126 static MonoProfileSamplingMode sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
127 static int max_allocated_sample_hits;
129 static gint32 sample_hits;
130 static gint32 sample_flushes;
131 static gint32 sample_allocations;
132 static gint32 buffer_allocations;
133 static gint32 thread_starts;
134 static gint32 thread_ends;
135 static gint32 domain_loads;
136 static gint32 domain_unloads;
137 static gint32 context_loads;
138 static gint32 context_unloads;
139 static gint32 assembly_loads;
140 static gint32 assembly_unloads;
141 static gint32 image_loads;
142 static gint32 image_unloads;
143 static gint32 class_loads;
144 static gint32 class_unloads;
146 typedef struct _LogBuffer LogBuffer;
152 * The file is composed by a header followed by 0 or more buffers.
153 * Each buffer contains events that happened on a thread: for a given thread
154 * buffers that appear later in the file are guaranteed to contain events
155 * that happened later in time. Buffers from separate threads could be interleaved,
157 * Buffers are not required to be aligned.
160 * [id: 4 bytes] constant value: LOG_HEADER_ID
161 * [major: 1 byte] [minor: 1 byte] major and minor version of the log profiler
162 * [format: 1 byte] version of the data format for the rest of the file
163 * [ptrsize: 1 byte] size in bytes of a pointer in the profiled program
164 * [startup time: 8 bytes] time in milliseconds since the unix epoch when the program started
165 * [timer overhead: 4 bytes] approximate overhead in nanoseconds of the timer
166 * [flags: 4 bytes] file format flags, should be 0 for now
167 * [pid: 4 bytes] pid of the profiled process
168 * [port: 2 bytes] tcp port for server if != 0
169 * [sysid: 2 bytes] operating system and architecture identifier
171 * The multiple byte integers are in little-endian format.
174 * [buffer header] [event]*
175 * Buffers have a fixed-size header followed by 0 or more bytes of event data.
176 * Timing information and other values in the event data are usually stored
177 * as uleb128 or sleb128 integers. To save space, as noted for each item below,
178 * some data is represented as a difference between the actual value and
179 * either the last value of the same type (like for timing information) or
180 * as the difference from a value stored in a buffer header.
182 * For timing information the data is stored as uleb128, since timing
183 * increases in a monotonic way in each thread: the value is the number of
184 * nanoseconds to add to the last seen timing data in a buffer. The first value
185 * in a buffer will be calculated from the time_base field in the buffer head.
187 * Object or heap sizes are stored as uleb128.
188 * Pointer differences are stored as sleb128, instead.
190 * If an unexpected value is found, the rest of the buffer should be ignored,
191 * as generally the later values need the former to be interpreted correctly.
193 * buffer header format:
194 * [bufid: 4 bytes] constant value: BUF_ID
195 * [len: 4 bytes] size of the data following the buffer header
196 * [time_base: 8 bytes] time base in nanoseconds since an unspecified epoch
197 * [ptr_base: 8 bytes] base value for pointers
198 * [obj_base: 8 bytes] base value for object addresses
199 * [thread id: 8 bytes] system-specific thread ID (pthread_t for example)
200 * [method_base: 8 bytes] base value for MonoMethod pointers
203 * [extended info: upper 4 bits] [type: lower 4 bits] [data]*
204 * The data that follows depends on type and the extended info.
205 * Type is one of the enum values in proflog.h: TYPE_ALLOC, TYPE_GC,
206 * TYPE_METADATA, TYPE_METHOD, TYPE_EXCEPTION, TYPE_MONITOR, TYPE_HEAP.
207 * The extended info bits are interpreted based on type, see
208 * each individual event description below.
209 * strings are represented as a 0-terminated utf8 sequence.
212 * [flags: uleb128] must be 0
213 * [num: uleb128] number of frames following
214 * [frame: sleb128]* num MonoMethod pointers as differences from ptr_base
218 * exinfo: flags: TYPE_ALLOC_BT
219 * [time diff: uleb128] nanoseconds since last timing
220 * [ptr: sleb128] class as a byte difference from ptr_base
221 * [obj: sleb128] object address as a byte difference from obj_base
222 * [size: uleb128] size of the object in the heap
223 * If the TYPE_ALLOC_BT flag is set, a backtrace follows.
227 * exinfo: one of TYPE_GC_EVENT, TYPE_GC_RESIZE, TYPE_GC_MOVE, TYPE_GC_HANDLE_CREATED[_BT],
228 * TYPE_GC_HANDLE_DESTROYED[_BT]
229 * [time diff: uleb128] nanoseconds since last timing
230 * if exinfo == TYPE_GC_RESIZE
231 * [heap_size: uleb128] new heap size
232 * if exinfo == TYPE_GC_EVENT
233 * [event type: uleb128] GC event (MONO_GC_EVENT_* from profiler.h)
234 * [generation: uleb128] GC generation event refers to
235 * if exinfo == TYPE_GC_MOVE
236 * [num_objects: uleb128] number of object moves that follow
237 * [objaddr: sleb128]+ num_objects object pointer differences from obj_base
238 * num is always an even number: the even items are the old
239 * addresses, the odd numbers are the respective new object addresses
240 * if exinfo == TYPE_GC_HANDLE_CREATED[_BT]
241 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
242 * upper bits reserved as flags
243 * [handle: uleb128] GC handle value
244 * [objaddr: sleb128] object pointer differences from obj_base
245 * If exinfo == TYPE_GC_HANDLE_CREATED_BT, a backtrace follows.
246 * if exinfo == TYPE_GC_HANDLE_DESTROYED[_BT]
247 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
248 * upper bits reserved as flags
249 * [handle: uleb128] GC handle value
250 * If exinfo == TYPE_GC_HANDLE_DESTROYED_BT, a backtrace follows.
252 * type metadata format:
253 * type: TYPE_METADATA
254 * exinfo: one of: TYPE_END_LOAD, TYPE_END_UNLOAD (optional for TYPE_THREAD and TYPE_DOMAIN)
255 * [time diff: uleb128] nanoseconds since last timing
256 * [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
257 * TYPE_THREAD, TYPE_CONTEXT
258 * [pointer: sleb128] pointer of the metadata type depending on mtype
259 * if mtype == TYPE_CLASS
260 * [image: sleb128] MonoImage* as a pointer difference from ptr_base
261 * [flags: uleb128] must be 0
262 * [name: string] full class name
263 * if mtype == TYPE_IMAGE
264 * [flags: uleb128] must be 0
265 * [name: string] image file name
266 * if mtype == TYPE_ASSEMBLY
267 * [flags: uleb128] must be 0
268 * [name: string] assembly name
269 * if mtype == TYPE_DOMAIN
270 * [flags: uleb128] must be 0
271 * if mtype == TYPE_DOMAIN && exinfo == 0
272 * [name: string] domain friendly name
273 * if mtype == TYPE_CONTEXT
274 * [flags: uleb128] must be 0
275 * [domain: sleb128] domain id as pointer
276 * if mtype == TYPE_THREAD && (format_version < 11 || (format_version > 10 && exinfo == 0))
277 * [flags: uleb128] must be 0
278 * [name: string] thread name
280 * type method format:
282 * exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
283 * [time diff: uleb128] nanoseconds since last timing
284 * [method: sleb128] MonoMethod* as a pointer difference from the last such
285 * pointer or the buffer method_base
286 * if exinfo == TYPE_JIT
287 * [code address: sleb128] pointer to the native code as a diff from ptr_base
288 * [code size: uleb128] size of the generated code
289 * [name: string] full method name
291 * type runtime format:
293 * exinfo: one of: TYPE_JITHELPER
294 * [time diff: uleb128] nanoseconds since last timing
295 * if exinfo == TYPE_JITHELPER
296 * [type: uleb128] MonoProfilerCodeBufferType enum value
297 * [buffer address: sleb128] pointer to the native code as a diff from ptr_base
298 * [buffer size: uleb128] size of the generated code
299 * if type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE
300 * [name: string] buffer description name
302 * type monitor format:
304 * exinfo: TYPE_MONITOR_BT flag and one of: MONO_PROFILER_MONITOR_(CONTENTION|FAIL|DONE)
305 * [time diff: uleb128] nanoseconds since last timing
306 * [object: sleb128] the lock object as a difference from obj_base
307 * if exinfo.low3bits == MONO_PROFILER_MONITOR_CONTENTION
308 * If the TYPE_MONITOR_BT flag is set, a backtrace follows.
312 * exinfo: one of TYPE_HEAP_START, TYPE_HEAP_END, TYPE_HEAP_OBJECT, TYPE_HEAP_ROOT
313 * if exinfo == TYPE_HEAP_START
314 * [time diff: uleb128] nanoseconds since last timing
315 * if exinfo == TYPE_HEAP_END
316 * [time diff: uleb128] nanoseconds since last timing
317 * if exinfo == TYPE_HEAP_OBJECT
318 * [object: sleb128] the object as a difference from obj_base
319 * [class: sleb128] the object MonoClass* as a difference from ptr_base
320 * [size: uleb128] size of the object on the heap
321 * [num_refs: uleb128] number of object references
322 * if (format version > 1) each referenced objref is preceded by a
323 * uleb128 encoded offset: the first offset is from the object address
324 * and each next offset is relative to the previous one
325 * [objrefs: sleb128]+ object referenced as a difference from obj_base
326 * The same object can appear multiple times, but only the first time
327 * with size != 0: in the other cases this data will only be used to
328 * provide additional referenced objects.
329 * if exinfo == TYPE_HEAP_ROOT
330 * [num_roots: uleb128] number of root references
331 * [num_gc: uleb128] number of major gcs
332 * [object: sleb128] the object as a difference from obj_base
333 * [root_type: uleb128] the root_type: MonoProfileGCRootType (profiler.h)
334 * [extra_info: uleb128] the extra_info value
335 * object, root_type and extra_info are repeated num_roots times
339 * exinfo: one of TYPE_SAMPLE_HIT, TYPE_SAMPLE_USYM, TYPE_SAMPLE_UBIN, TYPE_SAMPLE_COUNTERS_DESC, TYPE_SAMPLE_COUNTERS
340 * if exinfo == TYPE_SAMPLE_HIT
341 * [sample_type: uleb128] type of sample (SAMPLE_*)
342 * [timestamp: uleb128] nanoseconds since startup (note: different from other timestamps!)
343 * if (format_version > 10)
344 * [thread: sleb128] thread id as difference from ptr_base
345 * [count: uleb128] number of following instruction addresses
346 * [ip: sleb128]* instruction pointer as difference from ptr_base
347 * if (format_version > 5)
348 * [mbt_count: uleb128] number of managed backtrace info triplets (method + IL offset + native offset)
349 * [method: sleb128]* MonoMethod* as a pointer difference from the last such
350 * pointer or the buffer method_base (the first such method can be also indentified by ip, but this is not neccessarily true)
351 * [il_offset: sleb128]* IL offset inside method where the hit occurred
352 * [native_offset: sleb128]* native offset inside method where the hit occurred
353 * if exinfo == TYPE_SAMPLE_USYM
354 * [address: sleb128] symbol address as a difference from ptr_base
355 * [size: uleb128] symbol size (may be 0 if unknown)
356 * [name: string] symbol name
357 * if exinfo == TYPE_SAMPLE_UBIN
358 * [time diff: uleb128] nanoseconds since last timing
359 * [address: sleb128] address where binary has been loaded
360 * [offset: uleb128] file offset of mapping (the same file can be mapped multiple times)
361 * [size: uleb128] memory size
362 * [name: string] binary name
363 * if exinfo == TYPE_SAMPLE_COUNTERS_DESC
364 * [len: uleb128] number of counters
366 * [section: uleb128] section of counter
367 * if section == MONO_COUNTER_PERFCOUNTERS:
368 * [section_name: string] section name of counter
369 * [name: string] name of counter
370 * [type: uleb128] type of counter
371 * [unit: uleb128] unit of counter
372 * [variance: uleb128] variance of counter
373 * [index: uleb128] unique index of counter
374 * if exinfo == TYPE_SAMPLE_COUNTERS
375 * [timestamp: uleb128] sampling timestamp
377 * [index: uleb128] unique index of counter
380 * [type: uleb128] type of counter value
383 * [0: uleb128] 0 -> value is null
385 * [1: uleb128] 1 -> value is not null
386 * [value: string] counter value
388 * [value: uleb128/sleb128/double] counter value, can be sleb128, uleb128 or double (determined by using type)
390 * type coverage format
391 * type: TYPE_COVERAGE
392 * exinfo: one of TYPE_COVERAGE_METHOD, TYPE_COVERAGE_STATEMENT, TYPE_COVERAGE_ASSEMBLY, TYPE_COVERAGE_CLASS
393 * if exinfo == TYPE_COVERAGE_METHOD
394 * [assembly: string] name of assembly
395 * [class: string] name of the class
396 * [name: string] name of the method
397 * [signature: string] the signature of the method
398 * [filename: string] the file path of the file that contains this method
399 * [token: uleb128] the method token
400 * [method_id: uleb128] an ID for this data to associate with the buffers of TYPE_COVERAGE_STATEMENTS
401 * [len: uleb128] the number of TYPE_COVERAGE_BUFFERS associated with this method
402 * if exinfo == TYPE_COVERAGE_STATEMENTS
403 * [method_id: uleb128] an the TYPE_COVERAGE_METHOD buffer to associate this with
404 * [offset: uleb128] the il offset relative to the previous offset
405 * [counter: uleb128] the counter for this instruction
406 * [line: uleb128] the line of filename containing this instruction
407 * [column: uleb128] the column containing this instruction
408 * if exinfo == TYPE_COVERAGE_ASSEMBLY
409 * [name: string] assembly name
410 * [guid: string] assembly GUID
411 * [filename: string] assembly filename
412 * [number_of_methods: uleb128] the number of methods in this assembly
413 * [fully_covered: uleb128] the number of fully covered methods
414 * [partially_covered: uleb128] the number of partially covered methods
415 * currently partially_covered will always be 0, and fully_covered is the
416 * number of methods that are fully and partially covered.
417 * if exinfo == TYPE_COVERAGE_CLASS
418 * [name: string] assembly name
419 * [class: string] class name
420 * [number_of_methods: uleb128] the number of methods in this class
421 * [fully_covered: uleb128] the number of fully covered methods
422 * [partially_covered: uleb128] the number of partially covered methods
423 * currently partially_covered will always be 0, and fully_covered is the
424 * number of methods that are fully and partially covered.
428 * Format oddities that we ought to fix:
430 * - Methods written in emit_bt () should be based on the buffer's base
431 * method instead of the base pointer.
432 * - The TYPE_SAMPLE_HIT event contains (currently) pointless data like
433 * always-one unmanaged frame count and always-zero IL offsets.
435 * These are mostly small things and are not worth a format change by
436 * themselves. They should be done when some other major change has to
437 * be done to the format.
440 // Pending data to be written to the log, for a single thread.
441 // Threads periodically flush their own LogBuffers by calling safe_send
443 // Next (older) LogBuffer in processing queue
449 uintptr_t method_base;
450 uintptr_t last_method;
456 // Bytes allocated for this LogBuffer
459 // Start of currently unused space in buffer
460 unsigned char* cursor;
462 // Pointer to start-of-structure-plus-size (for convenience)
463 unsigned char* buf_end;
465 // Start of data in buffer. Contents follow "buffer format" described above.
466 unsigned char buf [1];
470 ign_res (int G_GNUC_UNUSED unused, ...)
474 #define ENTER_LOG(lb,str) if ((lb)->locked) {ign_res (write(2, str, strlen(str))); ign_res (write(2, "\n", 1));return;} else {(lb)->locked++;}
475 #define EXIT_LOG(lb) (lb)->locked--;
477 typedef struct _BinaryObject BinaryObject;
479 struct _BinaryObject {
485 struct _MonoProfiler {
487 #if defined (HAVE_SYS_ZLIB)
490 uint64_t startup_time;
492 int last_gc_gen_started;
497 pthread_t helper_thread;
498 pthread_t writer_thread;
499 pthread_t dumper_thread;
501 volatile gint32 run_writer_thread;
502 MonoLockFreeQueue writer_queue;
503 MonoSemType writer_queue_sem;
504 MonoConcurrentHashTable *method_table;
505 mono_mutex_t method_table_mutex;
506 volatile gint32 run_dumper_thread;
507 MonoLockFreeQueue dumper_queue;
508 MonoSemType dumper_queue_sem;
509 MonoLockFreeAllocSizeClass sample_size_class;
510 MonoLockFreeAllocator sample_allocator;
511 MonoLockFreeQueue sample_reuse_queue;
512 BinaryObject *binary_objects;
513 GPtrArray *coverage_filters;
516 typedef struct _WriterQueueEntry WriterQueueEntry;
517 struct _WriterQueueEntry {
518 MonoLockFreeQueueNode node;
523 typedef struct _MethodInfo MethodInfo;
535 #define TLS_SET(x,y) (TlsSetValue (x, y))
536 #define TLS_GET(t,x) ((t *) TlsGetValue (x))
537 #define TLS_INIT(x) (x = TlsAlloc ())
538 static int tlsbuffer;
539 static int tlsmethodlist;
541 #define TLS_SET(x,y) (x = y)
542 #define TLS_GET(t,x) (x)
544 static __thread LogBuffer* tlsbuffer = NULL;
545 static __thread GPtrArray* tlsmethodlist = NULL;
547 #define TLS_SET(x,y) (pthread_setspecific (x, y))
548 #define TLS_GET(t,x) ((t *) pthread_getspecific (x))
549 #define TLS_INIT(x) (pthread_key_create (&x, NULL))
550 static pthread_key_t tlsbuffer;
551 static pthread_key_t tlsmethodlist;
554 static void safe_send (MonoProfiler *profiler, LogBuffer *logbuffer);
557 pstrdup (const char *s)
559 int len = strlen (s) + 1;
560 char *p = (char *)malloc (len);
568 LogBuffer* buf = (LogBuffer *)alloc_buffer (BUFFER_SIZE);
570 InterlockedIncrement (&buffer_allocations);
572 buf->size = BUFFER_SIZE;
573 buf->time_base = current_time ();
574 buf->last_time = buf->time_base;
575 buf->buf_end = (unsigned char*)buf + buf->size;
576 buf->cursor = buf->buf;
583 if (!TLS_GET (LogBuffer, tlsbuffer)) {
584 LogBuffer *logbuffer = create_buffer ();
585 TLS_SET (tlsbuffer, logbuffer);
586 logbuffer->thread_id = thread_id ();
588 if (!TLS_GET (GPtrArray, tlsmethodlist)) {
589 GPtrArray *methodlist = g_ptr_array_new ();
590 TLS_SET (tlsmethodlist, methodlist);
593 //printf ("thread %p at time %llu\n", (void*)logbuffer->thread_id, logbuffer->time_base);
597 ensure_logbuf_inner (LogBuffer *old, int bytes)
599 if (old && old->cursor + bytes + 100 < old->buf_end)
602 LogBuffer *new_ = (LogBuffer *)create_buffer ();
603 new_->thread_id = thread_id ();
607 new_->call_depth = old->call_depth;
613 ensure_logbuf (int bytes)
615 LogBuffer *old = TLS_GET (LogBuffer, tlsbuffer);
616 LogBuffer *new_ = ensure_logbuf_inner (old, bytes);
619 return old; // Still enough space.
621 TLS_SET (tlsbuffer, new_);
628 emit_byte (LogBuffer *logbuffer, int value)
630 logbuffer->cursor [0] = value;
632 assert (logbuffer->cursor <= logbuffer->buf_end);
636 emit_value (LogBuffer *logbuffer, int value)
638 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
639 assert (logbuffer->cursor <= logbuffer->buf_end);
643 emit_time (LogBuffer *logbuffer, uint64_t value)
645 uint64_t tdiff = value - logbuffer->last_time;
646 //if (value < logbuffer->last_time)
647 // printf ("time went backwards\n");
648 //if (tdiff > 1000000)
649 // printf ("large time offset: %llu\n", tdiff);
650 encode_uleb128 (tdiff, logbuffer->cursor, &logbuffer->cursor);
651 /*if (tdiff != decode_uleb128 (p, &p))
652 printf ("incorrect encoding: %llu\n", tdiff);*/
653 logbuffer->last_time = value;
654 assert (logbuffer->cursor <= logbuffer->buf_end);
658 emit_svalue (LogBuffer *logbuffer, int64_t value)
660 encode_sleb128 (value, logbuffer->cursor, &logbuffer->cursor);
661 assert (logbuffer->cursor <= logbuffer->buf_end);
665 emit_uvalue (LogBuffer *logbuffer, uint64_t value)
667 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
668 assert (logbuffer->cursor <= logbuffer->buf_end);
672 emit_ptr (LogBuffer *logbuffer, void *ptr)
674 if (!logbuffer->ptr_base)
675 logbuffer->ptr_base = (uintptr_t)ptr;
676 emit_svalue (logbuffer, (intptr_t)ptr - logbuffer->ptr_base);
677 assert (logbuffer->cursor <= logbuffer->buf_end);
681 emit_method_inner (LogBuffer *logbuffer, void *method)
683 if (!logbuffer->method_base) {
684 logbuffer->method_base = (intptr_t)method;
685 logbuffer->last_method = (intptr_t)method;
687 encode_sleb128 ((intptr_t)((char*)method - (char*)logbuffer->last_method), logbuffer->cursor, &logbuffer->cursor);
688 logbuffer->last_method = (intptr_t)method;
689 assert (logbuffer->cursor <= logbuffer->buf_end);
699 find_method (MonoDomain *domain, void *user_data)
701 MethodSearch *search = user_data;
706 MonoJitInfo *ji = mono_get_jit_info_from_method (domain, search->method);
708 // It could be AOT'd, so we need to get it from the AOT runtime's cache.
710 void *ip = mono_aot_get_method (domain, search->method);
712 // Avoid a slow path in mono_jit_info_table_find ().
714 ji = mono_jit_info_table_find (domain, ip);
723 register_method_local (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji)
725 if (!mono_conc_hashtable_lookup (prof->method_table, method)) {
727 * FIXME: In some cases, we crash while looking up JIT info for AOT'd methods.
728 * This usually happens for static constructors. This code is disabled for now
729 * as we don't need this info for anything critical.
731 * https://bugzilla.xamarin.com/show_bug.cgi?id=35171
735 MethodSearch search = { method, NULL };
737 mono_domain_foreach (find_method, &search);
744 * FIXME: We can't always find JIT info for a generic shared method, especially
745 * if we obtained the MonoMethod during an async stack walk. For now, we deal
746 * with this by giving the generic shared method name and dummy code start/size
747 * information (i.e. zeroes).
751 MethodInfo *info = (MethodInfo *)malloc (sizeof (MethodInfo));
753 info->method = method;
755 info->time = current_time ();
757 g_ptr_array_add (TLS_GET (GPtrArray, tlsmethodlist), info);
762 emit_method (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
764 register_method_local (prof, method, NULL);
765 emit_method_inner (logbuffer, method);
769 emit_method_as_ptr (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
771 register_method_local (prof, method, NULL);
772 emit_ptr (logbuffer, method);
776 emit_obj (LogBuffer *logbuffer, void *ptr)
778 if (!logbuffer->obj_base)
779 logbuffer->obj_base = (uintptr_t)ptr >> 3;
780 emit_svalue (logbuffer, ((uintptr_t)ptr >> 3) - logbuffer->obj_base);
781 assert (logbuffer->cursor <= logbuffer->buf_end);
785 emit_string (LogBuffer *logbuffer, const char *str, size_t size)
789 for (; i < size; i++) {
792 emit_byte (logbuffer, str [i]);
795 emit_byte (logbuffer, '\0');
799 emit_double (LogBuffer *logbuffer, double value)
802 unsigned char buffer[8];
803 memcpy (buffer, &value, 8);
804 #if G_BYTE_ORDER == G_BIG_ENDIAN
805 for (i = 7; i >= 0; i--)
807 for (i = 0; i < 8; i++)
809 emit_byte (logbuffer, buffer[i]);
813 write_int16 (char *buf, int32_t value)
816 for (i = 0; i < 2; ++i) {
824 write_int32 (char *buf, int32_t value)
827 for (i = 0; i < 4; ++i) {
835 write_int64 (char *buf, int64_t value)
838 for (i = 0; i < 8; ++i) {
846 dump_header (MonoProfiler *profiler)
850 p = write_int32 (p, LOG_HEADER_ID);
851 *p++ = LOG_VERSION_MAJOR;
852 *p++ = LOG_VERSION_MINOR;
853 *p++ = LOG_DATA_VERSION;
854 *p++ = sizeof (void*);
855 p = write_int64 (p, ((uint64_t)time (NULL)) * 1000); /* startup time */
856 p = write_int32 (p, get_timer_overhead ()); /* timer overhead */
857 p = write_int32 (p, 0); /* flags */
858 p = write_int32 (p, process_id ()); /* pid */
859 p = write_int16 (p, profiler->command_port); /* port */
860 p = write_int16 (p, 0); /* opsystem */
861 #if defined (HAVE_SYS_ZLIB)
862 if (profiler->gzfile) {
863 gzwrite (profiler->gzfile, hbuf, p - hbuf);
865 fwrite (hbuf, p - hbuf, 1, profiler->file);
868 fwrite (hbuf, p - hbuf, 1, profiler->file);
869 fflush (profiler->file);
874 send_buffer (MonoProfiler *prof, GPtrArray *methods, LogBuffer *buffer)
876 WriterQueueEntry *entry = (WriterQueueEntry *)calloc (1, sizeof (WriterQueueEntry));
877 mono_lock_free_queue_node_init (&entry->node, FALSE);
878 entry->methods = methods;
879 entry->buffer = buffer;
880 mono_lock_free_queue_enqueue (&prof->writer_queue, &entry->node);
881 mono_os_sem_post (&prof->writer_queue_sem);
885 dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
890 dump_buffer (profiler, buf->next);
891 p = write_int32 (p, BUF_ID);
892 p = write_int32 (p, buf->cursor - buf->buf);
893 p = write_int64 (p, buf->time_base);
894 p = write_int64 (p, buf->ptr_base);
895 p = write_int64 (p, buf->obj_base);
896 p = write_int64 (p, buf->thread_id);
897 p = write_int64 (p, buf->method_base);
898 #if defined (HAVE_SYS_ZLIB)
899 if (profiler->gzfile) {
900 gzwrite (profiler->gzfile, hbuf, p - hbuf);
901 gzwrite (profiler->gzfile, buf->buf, buf->cursor - buf->buf);
904 fwrite (hbuf, p - hbuf, 1, profiler->file);
905 fwrite (buf->buf, buf->cursor - buf->buf, 1, profiler->file);
906 fflush (profiler->file);
907 #if defined (HAVE_SYS_ZLIB)
910 free_buffer (buf, buf->size);
914 process_requests (MonoProfiler *profiler)
916 if (heapshot_requested)
917 mono_gc_collect (mono_gc_max_generation ());
920 static void counters_init (MonoProfiler *profiler);
921 static void counters_sample (MonoProfiler *profiler, uint64_t timestamp, gboolean threadless);
924 * Can be called only at safe callback locations.
927 safe_send (MonoProfiler *profiler, LogBuffer *logbuffer)
929 /* We need the runtime initialized so that we have threads and hazard
930 * pointers available. Otherwise, the lock free queue will not work and
931 * there won't be a thread to process the data.
933 * While the runtime isn't initialized, we just accumulate data in the
934 * thread local buffer list.
936 if (!InterlockedRead (&runtime_inited))
939 int cd = logbuffer->call_depth;
941 send_buffer (profiler, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
943 TLS_SET (tlsbuffer, NULL);
944 TLS_SET (tlsmethodlist, NULL);
948 TLS_GET (LogBuffer, tlsbuffer)->call_depth = cd;
952 safe_send_threadless (MonoProfiler *prof, LogBuffer *buf)
954 for (LogBuffer *iter = buf; iter; iter = iter->next)
957 safe_send (prof, buf);
961 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
964 uintptr_t last_offset = 0;
965 //const char *name = mono_class_get_name (klass);
966 LogBuffer *logbuffer = ensure_logbuf (
967 EVENT_SIZE /* event */ +
968 LEB128_SIZE /* obj */ +
969 LEB128_SIZE /* klass */ +
970 LEB128_SIZE /* size */ +
971 LEB128_SIZE /* num */ +
973 LEB128_SIZE /* offset */ +
974 LEB128_SIZE /* ref */
977 emit_byte (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
978 emit_obj (logbuffer, obj);
979 emit_ptr (logbuffer, klass);
980 /* account for object alignment in the heap */
983 emit_value (logbuffer, size);
984 emit_value (logbuffer, num);
985 for (i = 0; i < num; ++i) {
986 emit_value (logbuffer, offsets [i] - last_offset);
987 last_offset = offsets [i];
988 emit_obj (logbuffer, refs [i]);
991 // printf ("obj: %p, klass: %s, refs: %d, size: %d\n", obj, name, (int)num, (int)size);
995 static unsigned int hs_mode_ms = 0;
996 static unsigned int hs_mode_gc = 0;
997 static unsigned int hs_mode_ondemand = 0;
998 static unsigned int gc_count = 0;
999 static uint64_t last_hs_time = 0;
1002 heap_walk (MonoProfiler *profiler)
1006 LogBuffer *logbuffer;
1009 logbuffer = ensure_logbuf (
1010 EVENT_SIZE /* event */ +
1011 LEB128_SIZE /* time */
1013 now = current_time ();
1014 if (hs_mode_ms && (now - last_hs_time)/1000000 >= hs_mode_ms)
1016 else if (hs_mode_gc && (gc_count % hs_mode_gc) == 0)
1018 else if (hs_mode_ondemand)
1019 do_walk = heapshot_requested;
1020 else if (!hs_mode_ms && !hs_mode_gc && profiler->last_gc_gen_started == mono_gc_max_generation ())
1025 heapshot_requested = 0;
1026 emit_byte (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
1027 emit_time (logbuffer, now);
1028 mono_gc_walk_heap (0, gc_reference, NULL);
1029 logbuffer = ensure_logbuf (
1030 EVENT_SIZE /* event */ +
1031 LEB128_SIZE /* time */
1033 now = current_time ();
1034 emit_byte (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
1035 emit_time (logbuffer, now);
1040 gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation) {
1042 LogBuffer *logbuffer = ensure_logbuf (
1043 EVENT_SIZE /* event */ +
1044 LEB128_SIZE /* time */ +
1045 LEB128_SIZE /* gc event */ +
1046 LEB128_SIZE /* generation */
1048 now = current_time ();
1049 ENTER_LOG (logbuffer, "gcevent");
1050 emit_byte (logbuffer, TYPE_GC_EVENT | TYPE_GC);
1051 emit_time (logbuffer, now);
1052 emit_value (logbuffer, ev);
1053 emit_value (logbuffer, generation);
1054 /* to deal with nested gen1 after gen0 started */
1055 if (ev == MONO_GC_EVENT_START) {
1056 profiler->last_gc_gen_started = generation;
1057 if (generation == mono_gc_max_generation ())
1060 if (ev == MONO_GC_EVENT_PRE_START_WORLD)
1061 heap_walk (profiler);
1062 EXIT_LOG (logbuffer);
1063 if (ev == MONO_GC_EVENT_POST_START_WORLD)
1064 safe_send (profiler, logbuffer);
1065 //printf ("gc event %d for generation %d\n", ev, generation);
1069 gc_resize (MonoProfiler *profiler, int64_t new_size) {
1071 LogBuffer *logbuffer = ensure_logbuf (
1072 EVENT_SIZE /* event */ +
1073 LEB128_SIZE /* time */ +
1074 LEB128_SIZE /* new size */
1076 now = current_time ();
1077 ENTER_LOG (logbuffer, "gcresize");
1078 emit_byte (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
1079 emit_time (logbuffer, now);
1080 emit_value (logbuffer, new_size);
1081 //printf ("gc resized to %lld\n", new_size);
1082 EXIT_LOG (logbuffer);
1085 // If you alter MAX_FRAMES, you may need to alter SAMPLE_BLOCK_SIZE too.
1086 #define MAX_FRAMES 32
1090 MonoMethod* methods [MAX_FRAMES];
1091 int32_t il_offsets [MAX_FRAMES];
1092 int32_t native_offsets [MAX_FRAMES];
1095 static int num_frames = MAX_FRAMES;
1098 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
1100 FrameData *frame = (FrameData *)data;
1101 if (method && frame->count < num_frames) {
1102 frame->il_offsets [frame->count] = il_offset;
1103 frame->native_offsets [frame->count] = native_offset;
1104 frame->methods [frame->count++] = method;
1105 //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
1107 return frame->count == num_frames;
1111 * a note about stack walks: they can cause more profiler events to fire,
1112 * so we need to make sure they don't happen after we started emitting an
1113 * event, hence the collect_bt/emit_bt split.
1116 collect_bt (FrameData *data)
1119 mono_stack_walk_no_il (walk_stack, data);
1123 emit_bt (MonoProfiler *prof, LogBuffer *logbuffer, FrameData *data)
1125 /* FIXME: this is actually tons of data and we should
1126 * just output it the first time and use an id the next
1128 if (data->count > num_frames)
1129 printf ("bad num frames: %d\n", data->count);
1130 emit_value (logbuffer, 0); /* flags */
1131 emit_value (logbuffer, data->count);
1132 //if (*p != data.count) {
1133 // 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);}
1134 while (data->count) {
1135 emit_method_as_ptr (prof, logbuffer, data->methods [--data->count]);
1140 gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1144 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces)? TYPE_ALLOC_BT: 0;
1146 LogBuffer *logbuffer;
1147 len = mono_object_get_size (obj);
1148 /* account for object alignment in the heap */
1153 logbuffer = ensure_logbuf (
1154 EVENT_SIZE /* event */ +
1155 LEB128_SIZE /* time */ +
1156 LEB128_SIZE /* klass */ +
1157 LEB128_SIZE /* obj */ +
1158 LEB128_SIZE /* size */ +
1160 LEB128_SIZE /* flags */ +
1161 LEB128_SIZE /* count */ +
1163 LEB128_SIZE /* method */
1167 now = current_time ();
1168 ENTER_LOG (logbuffer, "gcalloc");
1169 emit_byte (logbuffer, do_bt | TYPE_ALLOC);
1170 emit_time (logbuffer, now);
1171 emit_ptr (logbuffer, klass);
1172 emit_obj (logbuffer, obj);
1173 emit_value (logbuffer, len);
1175 emit_bt (prof, logbuffer, &data);
1176 EXIT_LOG (logbuffer);
1177 if (logbuffer->next)
1178 safe_send (prof, logbuffer);
1179 process_requests (prof);
1180 //printf ("gc alloc %s at %p\n", mono_class_get_name (klass), obj);
1184 gc_moves (MonoProfiler *prof, void **objects, int num)
1188 LogBuffer *logbuffer = ensure_logbuf (
1189 EVENT_SIZE /* event */ +
1190 LEB128_SIZE /* time */ +
1191 LEB128_SIZE /* num */ +
1193 LEB128_SIZE /* object */
1196 now = current_time ();
1197 ENTER_LOG (logbuffer, "gcmove");
1198 emit_byte (logbuffer, TYPE_GC_MOVE | TYPE_GC);
1199 emit_time (logbuffer, now);
1200 emit_value (logbuffer, num);
1201 for (i = 0; i < num; ++i)
1202 emit_obj (logbuffer, objects [i]);
1203 //printf ("gc moved %d objects\n", num/2);
1204 EXIT_LOG (logbuffer);
1208 gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
1211 LogBuffer *logbuffer = ensure_logbuf (
1212 EVENT_SIZE /* event */ +
1213 LEB128_SIZE /* num */ +
1214 LEB128_SIZE /* collections */ +
1216 LEB128_SIZE /* object */ +
1217 LEB128_SIZE /* root type */ +
1218 LEB128_SIZE /* extra info */
1221 ENTER_LOG (logbuffer, "gcroots");
1222 emit_byte (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
1223 emit_value (logbuffer, num);
1224 emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
1225 for (i = 0; i < num; ++i) {
1226 emit_obj (logbuffer, objects [i]);
1227 emit_value (logbuffer, root_types [i]);
1228 emit_value (logbuffer, extra_info [i]);
1230 EXIT_LOG (logbuffer);
1234 gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
1236 int do_bt = nocalls && InterlockedRead (&runtime_inited) && !notraces;
1243 LogBuffer *logbuffer = ensure_logbuf (
1244 EVENT_SIZE /* event */ +
1245 LEB128_SIZE /* time */ +
1246 LEB128_SIZE /* type */ +
1247 LEB128_SIZE /* handle */ +
1248 (op == MONO_PROFILER_GC_HANDLE_CREATED ? (
1249 LEB128_SIZE /* obj */
1252 LEB128_SIZE /* flags */ +
1253 LEB128_SIZE /* count */ +
1255 LEB128_SIZE /* method */
1260 now = current_time ();
1261 ENTER_LOG (logbuffer, "gchandle");
1263 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1264 emit_byte (logbuffer, (do_bt ? TYPE_GC_HANDLE_CREATED_BT : TYPE_GC_HANDLE_CREATED) | TYPE_GC);
1265 else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
1266 emit_byte (logbuffer, (do_bt ? TYPE_GC_HANDLE_DESTROYED_BT : TYPE_GC_HANDLE_DESTROYED) | TYPE_GC);
1268 g_assert_not_reached ();
1270 emit_time (logbuffer, now);
1271 emit_value (logbuffer, type);
1272 emit_value (logbuffer, handle);
1274 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1275 emit_obj (logbuffer, obj);
1278 emit_bt (prof, logbuffer, &data);
1280 EXIT_LOG (logbuffer);
1281 process_requests (prof);
1285 push_nesting (char *p, MonoClass *klass)
1290 nesting = mono_class_get_nesting_type (klass);
1292 p = push_nesting (p, nesting);
1296 name = mono_class_get_name (klass);
1297 nspace = mono_class_get_namespace (klass);
1300 p += strlen (nspace);
1310 type_name (MonoClass *klass)
1314 push_nesting (buf, klass);
1315 p = (char *)malloc (strlen (buf) + 1);
1321 image_loaded (MonoProfiler *prof, MonoImage *image, int result)
1326 LogBuffer *logbuffer;
1327 if (result != MONO_PROFILE_OK)
1329 name = mono_image_get_filename (image);
1330 nlen = strlen (name) + 1;
1331 logbuffer = ensure_logbuf (
1332 EVENT_SIZE /* event */ +
1333 LEB128_SIZE /* time */ +
1334 EVENT_SIZE /* type */ +
1335 LEB128_SIZE /* image */ +
1336 LEB128_SIZE /* flags */ +
1339 now = current_time ();
1340 ENTER_LOG (logbuffer, "image");
1341 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1342 emit_time (logbuffer, now);
1343 emit_byte (logbuffer, TYPE_IMAGE);
1344 emit_ptr (logbuffer, image);
1345 emit_value (logbuffer, 0); /* flags */
1346 memcpy (logbuffer->cursor, name, nlen);
1347 logbuffer->cursor += nlen;
1348 //printf ("loaded image %p (%s)\n", image, name);
1349 EXIT_LOG (logbuffer);
1350 if (logbuffer->next)
1351 safe_send (prof, logbuffer);
1352 process_requests (prof);
1354 InterlockedIncrement (&image_loads);
1358 image_unloaded (MonoProfiler *prof, MonoImage *image)
1360 const char *name = mono_image_get_filename (image);
1361 int nlen = strlen (name) + 1;
1362 LogBuffer *logbuffer = ensure_logbuf (
1363 EVENT_SIZE /* event */ +
1364 LEB128_SIZE /* time */ +
1365 EVENT_SIZE /* type */ +
1366 LEB128_SIZE /* image */ +
1367 LEB128_SIZE /* flags */ +
1370 uint64_t now = current_time ();
1372 ENTER_LOG (logbuffer, "image-unload");
1373 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1374 emit_time (logbuffer, now);
1375 emit_byte (logbuffer, TYPE_IMAGE);
1376 emit_ptr (logbuffer, image);
1377 emit_value (logbuffer, 0); /* flags */
1378 memcpy (logbuffer->cursor, name, nlen);
1379 logbuffer->cursor += nlen;
1380 EXIT_LOG (logbuffer);
1382 if (logbuffer->next)
1383 safe_send (prof, logbuffer);
1385 process_requests (prof);
1387 InterlockedIncrement (&image_unloads);
1391 assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly, int result)
1393 if (result != MONO_PROFILE_OK)
1396 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1397 int nlen = strlen (name) + 1;
1398 LogBuffer *logbuffer = ensure_logbuf (
1399 EVENT_SIZE /* event */ +
1400 LEB128_SIZE /* time */ +
1401 EVENT_SIZE /* type */ +
1402 LEB128_SIZE /* assembly */ +
1403 LEB128_SIZE /* flags */ +
1406 uint64_t now = current_time ();
1408 ENTER_LOG (logbuffer, "assembly-load");
1409 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1410 emit_time (logbuffer, now);
1411 emit_byte (logbuffer, TYPE_ASSEMBLY);
1412 emit_ptr (logbuffer, assembly);
1413 emit_value (logbuffer, 0); /* flags */
1414 memcpy (logbuffer->cursor, name, nlen);
1415 logbuffer->cursor += nlen;
1416 EXIT_LOG (logbuffer);
1420 if (logbuffer->next)
1421 safe_send (prof, logbuffer);
1423 process_requests (prof);
1425 InterlockedIncrement (&assembly_loads);
1429 assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
1431 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1432 int nlen = strlen (name) + 1;
1433 LogBuffer *logbuffer = ensure_logbuf (
1434 EVENT_SIZE /* event */ +
1435 LEB128_SIZE /* time */ +
1436 EVENT_SIZE /* type */ +
1437 LEB128_SIZE /* assembly */ +
1438 LEB128_SIZE /* flags */ +
1441 uint64_t now = current_time ();
1443 ENTER_LOG (logbuffer, "assembly-unload");
1444 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1445 emit_time (logbuffer, now);
1446 emit_byte (logbuffer, TYPE_ASSEMBLY);
1447 emit_ptr (logbuffer, assembly);
1448 emit_value (logbuffer, 0); /* flags */
1449 memcpy (logbuffer->cursor, name, nlen);
1450 logbuffer->cursor += nlen;
1451 EXIT_LOG (logbuffer);
1455 if (logbuffer->next)
1456 safe_send (prof, logbuffer);
1458 process_requests (prof);
1460 InterlockedIncrement (&assembly_unloads);
1464 class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
1470 LogBuffer *logbuffer;
1471 if (result != MONO_PROFILE_OK)
1473 if (InterlockedRead (&runtime_inited))
1474 name = mono_type_get_name (mono_class_get_type (klass));
1476 name = type_name (klass);
1477 nlen = strlen (name) + 1;
1478 image = mono_class_get_image (klass);
1479 logbuffer = ensure_logbuf (
1480 EVENT_SIZE /* event */ +
1481 LEB128_SIZE /* time */ +
1482 EVENT_SIZE /* type */ +
1483 LEB128_SIZE /* klass */ +
1484 LEB128_SIZE /* image */ +
1485 LEB128_SIZE /* flags */ +
1488 now = current_time ();
1489 ENTER_LOG (logbuffer, "class");
1490 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1491 emit_time (logbuffer, now);
1492 emit_byte (logbuffer, TYPE_CLASS);
1493 emit_ptr (logbuffer, klass);
1494 emit_ptr (logbuffer, image);
1495 emit_value (logbuffer, 0); /* flags */
1496 memcpy (logbuffer->cursor, name, nlen);
1497 logbuffer->cursor += nlen;
1498 //printf ("loaded class %p (%s)\n", klass, name);
1503 EXIT_LOG (logbuffer);
1504 if (logbuffer->next)
1505 safe_send (prof, logbuffer);
1506 process_requests (prof);
1508 InterlockedIncrement (&class_loads);
1512 class_unloaded (MonoProfiler *prof, MonoClass *klass)
1516 if (InterlockedRead (&runtime_inited))
1517 name = mono_type_get_name (mono_class_get_type (klass));
1519 name = type_name (klass);
1521 int nlen = strlen (name) + 1;
1522 MonoImage *image = mono_class_get_image (klass);
1523 LogBuffer *logbuffer = ensure_logbuf (
1524 EVENT_SIZE /* event */ +
1525 LEB128_SIZE /* time */ +
1526 EVENT_SIZE /* type */ +
1527 LEB128_SIZE /* klass */ +
1528 LEB128_SIZE /* image */ +
1529 LEB128_SIZE /* flags */ +
1532 uint64_t now = current_time ();
1534 ENTER_LOG (logbuffer, "class-unload");
1535 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1536 emit_time (logbuffer, now);
1537 emit_byte (logbuffer, TYPE_CLASS);
1538 emit_ptr (logbuffer, klass);
1539 emit_ptr (logbuffer, image);
1540 emit_value (logbuffer, 0); /* flags */
1541 memcpy (logbuffer->cursor, name, nlen);
1542 logbuffer->cursor += nlen;
1543 EXIT_LOG (logbuffer);
1550 if (logbuffer->next)
1551 safe_send (prof, logbuffer);
1553 process_requests (prof);
1555 InterlockedIncrement (&class_unloads);
1558 #ifndef DISABLE_HELPER_THREAD
1559 static void process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method);
1560 #endif /* DISABLE_HELPER_THREAD */
1563 method_enter (MonoProfiler *prof, MonoMethod *method)
1565 uint64_t now = current_time ();
1567 #ifndef DISABLE_HELPER_THREAD
1568 process_method_enter_coverage (prof, method);
1569 #endif /* DISABLE_HELPER_THREAD */
1571 LogBuffer *logbuffer = ensure_logbuf (
1572 EVENT_SIZE /* event */ +
1573 LEB128_SIZE /* time */ +
1574 LEB128_SIZE /* method */
1576 if (logbuffer->call_depth++ > max_call_depth)
1578 ENTER_LOG (logbuffer, "enter");
1579 emit_byte (logbuffer, TYPE_ENTER | TYPE_METHOD);
1580 emit_time (logbuffer, now);
1581 emit_method (prof, logbuffer, method);
1582 EXIT_LOG (logbuffer);
1584 process_requests (prof);
1588 method_leave (MonoProfiler *prof, MonoMethod *method)
1591 LogBuffer *logbuffer = ensure_logbuf (
1592 EVENT_SIZE /* event */ +
1593 LEB128_SIZE /* time */ +
1594 LEB128_SIZE /* method */
1596 if (--logbuffer->call_depth > max_call_depth)
1598 now = current_time ();
1599 ENTER_LOG (logbuffer, "leave");
1600 emit_byte (logbuffer, TYPE_LEAVE | TYPE_METHOD);
1601 emit_time (logbuffer, now);
1602 emit_method (prof, logbuffer, method);
1603 EXIT_LOG (logbuffer);
1604 if (logbuffer->next)
1605 safe_send (prof, logbuffer);
1606 process_requests (prof);
1610 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
1613 LogBuffer *logbuffer;
1616 logbuffer = ensure_logbuf (
1617 EVENT_SIZE /* event */ +
1618 LEB128_SIZE /* time */ +
1619 LEB128_SIZE /* method */
1621 if (--logbuffer->call_depth > max_call_depth)
1623 now = current_time ();
1624 ENTER_LOG (logbuffer, "eleave");
1625 emit_byte (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
1626 emit_time (logbuffer, now);
1627 emit_method (prof, logbuffer, method);
1628 EXIT_LOG (logbuffer);
1629 process_requests (prof);
1633 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji, int result)
1635 if (result != MONO_PROFILE_OK)
1638 register_method_local (prof, method, ji);
1640 process_requests (prof);
1644 code_buffer_new (MonoProfiler *prof, void *buffer, int size, MonoProfilerCodeBufferType type, void *data)
1649 LogBuffer *logbuffer;
1650 if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
1651 name = (char *)data;
1652 nlen = strlen (name) + 1;
1657 logbuffer = ensure_logbuf (
1658 EVENT_SIZE /* event */ +
1659 LEB128_SIZE /* time */ +
1660 LEB128_SIZE /* type */ +
1661 LEB128_SIZE /* buffer */ +
1662 LEB128_SIZE /* size */ +
1667 now = current_time ();
1668 ENTER_LOG (logbuffer, "code buffer");
1669 emit_byte (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
1670 emit_time (logbuffer, now);
1671 emit_value (logbuffer, type);
1672 emit_ptr (logbuffer, buffer);
1673 emit_value (logbuffer, size);
1675 memcpy (logbuffer->cursor, name, nlen);
1676 logbuffer->cursor += nlen;
1678 EXIT_LOG (logbuffer);
1679 process_requests (prof);
1683 throw_exc (MonoProfiler *prof, MonoObject *object)
1685 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces)? TYPE_EXCEPTION_BT: 0;
1688 LogBuffer *logbuffer;
1691 logbuffer = ensure_logbuf (
1692 EVENT_SIZE /* event */ +
1693 LEB128_SIZE /* time */ +
1694 LEB128_SIZE /* object */ +
1696 LEB128_SIZE /* flags */ +
1697 LEB128_SIZE /* count */ +
1699 LEB128_SIZE /* method */
1703 now = current_time ();
1704 ENTER_LOG (logbuffer, "throw");
1705 emit_byte (logbuffer, do_bt | TYPE_EXCEPTION);
1706 emit_time (logbuffer, now);
1707 emit_obj (logbuffer, object);
1709 emit_bt (prof, logbuffer, &data);
1710 EXIT_LOG (logbuffer);
1711 process_requests (prof);
1715 clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
1718 LogBuffer *logbuffer = ensure_logbuf (
1719 EVENT_SIZE /* event */ +
1720 LEB128_SIZE /* time */ +
1721 LEB128_SIZE /* clause type */ +
1722 LEB128_SIZE /* clause num */ +
1723 LEB128_SIZE /* method */
1725 now = current_time ();
1726 ENTER_LOG (logbuffer, "clause");
1727 emit_byte (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
1728 emit_time (logbuffer, now);
1729 emit_value (logbuffer, clause_type);
1730 emit_value (logbuffer, clause_num);
1731 emit_method (prof, logbuffer, method);
1732 EXIT_LOG (logbuffer);
1734 process_requests (prof);
1738 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
1740 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION)? TYPE_MONITOR_BT: 0;
1743 LogBuffer *logbuffer;
1746 logbuffer = ensure_logbuf (
1747 EVENT_SIZE /* event */ +
1748 LEB128_SIZE /* time */ +
1749 LEB128_SIZE /* object */ +
1751 LEB128_SIZE /* flags */ +
1752 LEB128_SIZE /* count */ +
1754 LEB128_SIZE /* method */
1758 now = current_time ();
1759 ENTER_LOG (logbuffer, "monitor");
1760 emit_byte (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
1761 emit_time (logbuffer, now);
1762 emit_obj (logbuffer, object);
1764 emit_bt (profiler, logbuffer, &data);
1765 EXIT_LOG (logbuffer);
1766 process_requests (profiler);
1770 thread_start (MonoProfiler *prof, uintptr_t tid)
1772 //printf ("thread start %p\n", (void*)tid);
1775 LogBuffer *logbuffer = ensure_logbuf (
1776 EVENT_SIZE /* event */ +
1777 LEB128_SIZE /* time */ +
1778 EVENT_SIZE /* type */ +
1779 LEB128_SIZE /* tid */ +
1780 LEB128_SIZE /* flags */
1782 uint64_t now = current_time ();
1784 ENTER_LOG (logbuffer, "thread-start");
1785 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1786 emit_time (logbuffer, now);
1787 emit_byte (logbuffer, TYPE_THREAD);
1788 emit_ptr (logbuffer, (void*) tid);
1789 emit_value (logbuffer, 0); /* flags */
1790 EXIT_LOG (logbuffer);
1792 if (logbuffer->next)
1793 safe_send (prof, logbuffer);
1795 process_requests (prof);
1797 InterlockedIncrement (&thread_starts);
1801 thread_end (MonoProfiler *prof, uintptr_t tid)
1803 if (TLS_GET (LogBuffer, tlsbuffer)) {
1804 LogBuffer *logbuffer = ensure_logbuf (
1805 EVENT_SIZE /* event */ +
1806 LEB128_SIZE /* time */ +
1807 EVENT_SIZE /* type */ +
1808 LEB128_SIZE /* tid */ +
1809 LEB128_SIZE /* flags */
1811 uint64_t now = current_time ();
1813 ENTER_LOG (logbuffer, "thread-end");
1814 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1815 emit_time (logbuffer, now);
1816 emit_byte (logbuffer, TYPE_THREAD);
1817 emit_ptr (logbuffer, (void*) tid);
1818 emit_value (logbuffer, 0); /* flags */
1819 EXIT_LOG (logbuffer);
1821 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), logbuffer);
1823 /* Don't process requests as the thread is detached from the runtime. */
1826 TLS_SET (tlsbuffer, NULL);
1827 TLS_SET (tlsmethodlist, NULL);
1829 InterlockedIncrement (&thread_ends);
1833 domain_loaded (MonoProfiler *prof, MonoDomain *domain, int result)
1835 if (result != MONO_PROFILE_OK)
1838 LogBuffer *logbuffer = ensure_logbuf (
1839 EVENT_SIZE /* event */ +
1840 LEB128_SIZE /* time */ +
1841 EVENT_SIZE /* type */ +
1842 LEB128_SIZE /* domain id */ +
1843 LEB128_SIZE /* flags */
1845 uint64_t now = current_time ();
1847 ENTER_LOG (logbuffer, "domain-start");
1848 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1849 emit_time (logbuffer, now);
1850 emit_byte (logbuffer, TYPE_DOMAIN);
1851 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1852 emit_value (logbuffer, 0); /* flags */
1853 EXIT_LOG (logbuffer);
1855 if (logbuffer->next)
1856 safe_send (prof, logbuffer);
1858 process_requests (prof);
1860 InterlockedIncrement (&domain_loads);
1864 domain_unloaded (MonoProfiler *prof, MonoDomain *domain)
1866 LogBuffer *logbuffer = ensure_logbuf (
1867 EVENT_SIZE /* event */ +
1868 LEB128_SIZE /* time */ +
1869 EVENT_SIZE /* type */ +
1870 LEB128_SIZE /* domain id */ +
1871 LEB128_SIZE /* flags */
1873 uint64_t now = current_time ();
1875 ENTER_LOG (logbuffer, "domain-end");
1876 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1877 emit_time (logbuffer, now);
1878 emit_byte (logbuffer, TYPE_DOMAIN);
1879 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1880 emit_value (logbuffer, 0); /* flags */
1881 EXIT_LOG (logbuffer);
1883 if (logbuffer->next)
1884 safe_send (prof, logbuffer);
1886 process_requests (prof);
1888 InterlockedIncrement (&domain_unloads);
1892 domain_name (MonoProfiler *prof, MonoDomain *domain, const char *name)
1894 int nlen = strlen (name) + 1;
1895 LogBuffer *logbuffer = ensure_logbuf (
1896 EVENT_SIZE /* event */ +
1897 LEB128_SIZE /* time */ +
1898 EVENT_SIZE /* type */ +
1899 LEB128_SIZE /* domain id */ +
1900 LEB128_SIZE /* flags */ +
1903 uint64_t now = current_time ();
1905 ENTER_LOG (logbuffer, "domain-name");
1906 emit_byte (logbuffer, TYPE_METADATA);
1907 emit_time (logbuffer, now);
1908 emit_byte (logbuffer, TYPE_DOMAIN);
1909 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1910 emit_value (logbuffer, 0); /* flags */
1911 memcpy (logbuffer->cursor, name, nlen);
1912 logbuffer->cursor += nlen;
1913 EXIT_LOG (logbuffer);
1915 if (logbuffer->next)
1916 safe_send (prof, logbuffer);
1918 process_requests (prof);
1922 context_loaded (MonoProfiler *prof, MonoAppContext *context)
1924 LogBuffer *logbuffer = ensure_logbuf (
1925 EVENT_SIZE /* event */ +
1926 LEB128_SIZE /* time */ +
1927 EVENT_SIZE /* type */ +
1928 LEB128_SIZE /* context id */ +
1929 LEB128_SIZE /* flags */ +
1930 LEB128_SIZE /* domain id */
1932 uint64_t now = current_time ();
1934 ENTER_LOG (logbuffer, "context-start");
1935 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1936 emit_time (logbuffer, now);
1937 emit_byte (logbuffer, TYPE_CONTEXT);
1938 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
1939 emit_value (logbuffer, 0); /* flags */
1940 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
1941 EXIT_LOG (logbuffer);
1943 if (logbuffer->next)
1944 safe_send (prof, logbuffer);
1946 process_requests (prof);
1948 InterlockedIncrement (&context_loads);
1952 context_unloaded (MonoProfiler *prof, MonoAppContext *context)
1954 LogBuffer *logbuffer = ensure_logbuf (
1955 EVENT_SIZE /* event */ +
1956 LEB128_SIZE /* time */ +
1957 EVENT_SIZE /* type */ +
1958 LEB128_SIZE /* context id */ +
1959 LEB128_SIZE /* flags */ +
1960 LEB128_SIZE /* domain id */
1962 uint64_t now = current_time ();
1964 ENTER_LOG (logbuffer, "context-end");
1965 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1966 emit_time (logbuffer, now);
1967 emit_byte (logbuffer, TYPE_CONTEXT);
1968 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
1969 emit_value (logbuffer, 0); /* flags */
1970 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
1971 EXIT_LOG (logbuffer);
1973 if (logbuffer->next)
1974 safe_send (prof, logbuffer);
1976 process_requests (prof);
1978 InterlockedIncrement (&context_unloads);
1982 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
1984 int len = strlen (name) + 1;
1986 LogBuffer *logbuffer;
1987 logbuffer = ensure_logbuf (
1988 EVENT_SIZE /* event */ +
1989 LEB128_SIZE /* time */ +
1990 EVENT_SIZE /* type */ +
1991 LEB128_SIZE /* tid */ +
1992 LEB128_SIZE /* flags */ +
1995 now = current_time ();
1996 ENTER_LOG (logbuffer, "tname");
1997 emit_byte (logbuffer, TYPE_METADATA);
1998 emit_time (logbuffer, now);
1999 emit_byte (logbuffer, TYPE_THREAD);
2000 emit_ptr (logbuffer, (void*)tid);
2001 emit_value (logbuffer, 0); /* flags */
2002 memcpy (logbuffer->cursor, name, len);
2003 logbuffer->cursor += len;
2004 EXIT_LOG (logbuffer);
2006 if (logbuffer->next)
2007 safe_send (prof, logbuffer);
2009 process_requests (prof);
2020 MonoLockFreeQueueNode node;
2026 AsyncFrameInfo frames [MONO_ZERO_LEN_ARRAY];
2030 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
2032 SampleHit *sample = (SampleHit *) data;
2034 if (sample->count < num_frames) {
2035 int i = sample->count;
2037 sample->frames [i].method = method;
2038 sample->frames [i].domain = domain;
2039 sample->frames [i].base_address = base_address;
2040 sample->frames [i].offset = offset;
2045 return sample->count == num_frames;
2048 #define SAMPLE_SLOT_SIZE(FRAMES) (sizeof (SampleHit) + sizeof (AsyncFrameInfo) * (FRAMES - MONO_ZERO_LEN_ARRAY))
2049 #define SAMPLE_BLOCK_SIZE (mono_pagesize ())
2052 enqueue_sample_hit (gpointer p)
2054 SampleHit *sample = p;
2056 mono_lock_free_queue_node_unpoison (&sample->node);
2057 mono_lock_free_queue_enqueue (&sample->prof->dumper_queue, &sample->node);
2058 mono_os_sem_post (&sample->prof->dumper_queue_sem);
2060 InterlockedIncrement (&sample_flushes);
2064 mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
2067 * Please note: We rely on the runtime loading the profiler with
2068 * MONO_DL_EAGER (RTLD_NOW) so that references to runtime functions within
2069 * this function (and its siblings) are resolved when the profiler is
2070 * loaded. Otherwise, we would potentially invoke the dynamic linker when
2071 * invoking runtime functions, which is not async-signal-safe.
2077 InterlockedIncrement (&sample_hits);
2079 uint64_t now = current_time ();
2081 SampleHit *sample = (SampleHit *) mono_lock_free_queue_dequeue (&profiler->sample_reuse_queue);
2085 * If we're out of reusable sample events and we're not allowed to
2086 * allocate more, we have no choice but to drop the event.
2088 if (InterlockedRead (&sample_allocations) >= max_allocated_sample_hits)
2091 sample = mono_lock_free_alloc (&profiler->sample_allocator);
2092 sample->prof = profiler;
2093 mono_lock_free_queue_node_init (&sample->node, TRUE);
2095 InterlockedIncrement (&sample_allocations);
2099 mono_stack_walk_async_safe (&async_walk_stack, context, sample);
2101 uintptr_t elapsed = (now - profiler->startup_time) / 10000;
2103 sample->elapsed = elapsed;
2104 sample->tid = thread_id ();
2110 snprintf (buf, sizeof (buf), "hit at %p in thread %p after %llu ms\n", ip, (void *) thread_id (), (unsigned long long int) elapsed / 100);
2112 ign_res (write (2, buf, len));
2115 mono_thread_hazardous_try_free (sample, enqueue_sample_hit);
2118 static uintptr_t *code_pages = 0;
2119 static int num_code_pages = 0;
2120 static int size_code_pages = 0;
2121 #define CPAGE_SHIFT (9)
2122 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
2123 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
2124 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
2127 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
2130 uintptr_t start_pos;
2131 start_pos = (page >> CPAGE_SHIFT) % hsize;
2134 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
2136 } else if (!hash [i]) {
2143 } while (i != start_pos);
2144 /* should not happen */
2145 printf ("failed code page store\n");
2150 add_code_pointer (uintptr_t ip)
2153 if (num_code_pages * 2 >= size_code_pages) {
2155 uintptr_t old_size = size_code_pages;
2156 size_code_pages *= 2;
2157 if (size_code_pages == 0)
2158 size_code_pages = 16;
2159 n = (uintptr_t *)calloc (sizeof (uintptr_t) * size_code_pages, 1);
2160 for (i = 0; i < old_size; ++i) {
2162 add_code_page (n, size_code_pages, code_pages [i]);
2168 num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
2171 /* ELF code crashes on some systems. */
2172 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2175 dump_ubin (const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
2178 LogBuffer *logbuffer;
2180 len = strlen (filename) + 1;
2181 now = current_time ();
2182 logbuffer = ensure_logbuf (
2183 EVENT_SIZE /* event */ +
2184 LEB128_SIZE /* time */ +
2185 LEB128_SIZE /* load address */ +
2186 LEB128_SIZE /* offset */ +
2187 LEB128_SIZE /* size */ +
2188 nlen /* file name */
2190 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
2191 emit_time (logbuffer, now);
2192 emit_svalue (logbuffer, load_addr);
2193 emit_uvalue (logbuffer, offset);
2194 emit_uvalue (logbuffer, size);
2195 memcpy (logbuffer->cursor, filename, len);
2196 logbuffer->cursor += len;
2201 dump_usym (const char *name, uintptr_t value, uintptr_t size)
2203 LogBuffer *logbuffer;
2205 len = strlen (name) + 1;
2206 logbuffer = ensure_logbuf (
2207 EVENT_SIZE /* event */ +
2208 LEB128_SIZE /* value */ +
2209 LEB128_SIZE /* size */ +
2212 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
2213 emit_ptr (logbuffer, (void*)value);
2214 emit_value (logbuffer, size);
2215 memcpy (logbuffer->cursor, name, len);
2216 logbuffer->cursor += len;
2219 /* ELF code crashes on some systems. */
2220 //#if defined(ELFMAG0)
2223 #if SIZEOF_VOID_P == 4
2224 #define ELF_WSIZE 32
2226 #define ELF_WSIZE 64
2229 #define ElfW(type) _ElfW (Elf, ELF_WSIZE, type)
2230 #define _ElfW(e,w,t) _ElfW_1 (e, w, _##t)
2231 #define _ElfW_1(e,w,t) e##w##t
2235 dump_elf_symbols (ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
2238 for (i = 0; i < num_symbols; ++i) {
2240 sym = strtab + symbols [i].st_name;
2241 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
2243 //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
2244 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
2249 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
2256 ElfW(Shdr) *sheader;
2257 ElfW(Shdr) *shstrtabh;
2258 ElfW(Shdr) *symtabh = NULL;
2259 ElfW(Shdr) *strtabh = NULL;
2260 ElfW(Sym) *symbols = NULL;
2264 fd = open (filename, O_RDONLY);
2267 if (fstat (fd, &statb) != 0) {
2271 file_size = statb.st_size;
2272 data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
2274 if (data == MAP_FAILED)
2277 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2278 header->e_ident [EI_MAG1] != ELFMAG1 ||
2279 header->e_ident [EI_MAG2] != ELFMAG2 ||
2280 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2281 munmap (data, file_size);
2284 sheader = (void*)((char*)data + header->e_shoff);
2285 shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
2286 strtab = (const char*)data + shstrtabh->sh_offset;
2287 for (i = 0; i < header->e_shnum; ++i) {
2288 //printf ("section header: %d\n", sheader->sh_type);
2289 if (sheader->sh_type == SHT_SYMTAB) {
2291 strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
2292 /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
2295 sheader = (void*)((char*)sheader + header->e_shentsize);
2297 if (!symtabh || !strtabh) {
2298 munmap (data, file_size);
2301 strtab = (const char*)data + strtabh->sh_offset;
2302 num_symbols = symtabh->sh_size / symtabh->sh_entsize;
2303 symbols = (void*)((char*)data + symtabh->sh_offset);
2304 dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
2305 munmap (data, file_size);
2310 /* ELF code crashes on some systems. */
2311 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2314 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
2316 MonoProfiler *prof = data;
2318 const char *filename;
2320 char *a = (void*)info->dlpi_addr;
2322 ElfW(Dyn) *dyn = NULL;
2323 ElfW(Sym) *symtab = NULL;
2324 ElfW(Word) *hash_table = NULL;
2325 ElfW(Ehdr) *header = NULL;
2326 const char* strtab = NULL;
2327 for (obj = prof->binary_objects; obj; obj = obj->next) {
2331 filename = info->dlpi_name;
2334 if (!info->dlpi_addr && !filename [0]) {
2335 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
2341 obj = calloc (sizeof (BinaryObject), 1);
2342 obj->addr = (void*)info->dlpi_addr;
2343 obj->name = pstrdup (filename);
2344 obj->next = prof->binary_objects;
2345 prof->binary_objects = obj;
2346 //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
2348 for (i = 0; i < info->dlpi_phnum; ++i) {
2349 //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);
2350 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
2351 header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2352 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2353 header->e_ident [EI_MAG1] != ELFMAG1 ||
2354 header->e_ident [EI_MAG2] != ELFMAG2 ||
2355 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2358 dump_ubin (filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
2359 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
2360 dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2363 if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
2365 if (!info->dlpi_name || !info->dlpi_name[0])
2369 for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
2370 if (dyn [i].d_tag == DT_SYMTAB) {
2371 if (symtab && do_debug)
2372 printf ("multiple symtabs: %d\n", i);
2373 symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
2374 } else if (dyn [i].d_tag == DT_HASH) {
2375 hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
2376 } else if (dyn [i].d_tag == DT_STRTAB) {
2377 strtab = (const char*)(a + dyn [i].d_un.d_ptr);
2382 num_sym = hash_table [1];
2383 dump_elf_symbols (symtab, num_sym, strtab, (void*)info->dlpi_addr);
2388 load_binaries (MonoProfiler *prof)
2390 dl_iterate_phdr (elf_dl_callback, prof);
2395 load_binaries (MonoProfiler *prof)
2402 symbol_for (uintptr_t code)
2405 void *ip = (void*)code;
2407 if (dladdr (ip, &di)) {
2409 return di.dli_sname;
2412 names = backtrace_symbols (&ip, 1);
2414 const char* p = names [0];
2425 dump_unmanaged_coderefs (MonoProfiler *prof)
2428 const char* last_symbol;
2429 uintptr_t addr, page_end;
2431 if (load_binaries (prof))
2433 for (i = 0; i < size_code_pages; ++i) {
2435 if (!code_pages [i] || code_pages [i] & 1)
2438 addr = CPAGE_ADDR (code_pages [i]);
2439 page_end = addr + CPAGE_SIZE;
2440 code_pages [i] |= 1;
2441 /* we dump the symbols for the whole page */
2442 for (; addr < page_end; addr += 16) {
2443 sym = symbol_for (addr);
2444 if (sym && sym == last_symbol)
2449 dump_usym (sym, addr, 0); /* let's not guess the size */
2450 //printf ("found symbol at %p: %s\n", (void*)addr, sym);
2456 mono_cpu_count (void)
2458 #ifdef PLATFORM_ANDROID
2459 /* Android tries really hard to save power by powering off CPUs on SMP phones which
2460 * means the normal way to query cpu count returns a wrong value with userspace API.
2461 * Instead we use /sys entries to query the actual hardware CPU count.
2464 char buffer[8] = {'\0'};
2465 int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
2466 /* Format of the /sys entry is a cpulist of indexes which in the case
2467 * of present is always of the form "0-(n-1)" when there is more than
2468 * 1 core, n being the number of CPU cores in the system. Otherwise
2469 * the value is simply 0
2471 if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
2472 count = strtol (((char*)buffer) + 2, NULL, 10);
2479 #if defined(HOST_ARM) || defined (HOST_ARM64)
2481 /* ARM platforms tries really hard to save power by powering off CPUs on SMP phones which
2482 * means the normal way to query cpu count returns a wrong value with userspace API. */
2484 #ifdef _SC_NPROCESSORS_CONF
2486 int count = sysconf (_SC_NPROCESSORS_CONF);
2494 #ifdef HAVE_SCHED_GETAFFINITY
2497 if (sched_getaffinity (getpid (), sizeof (set), &set) == 0)
2498 return CPU_COUNT (&set);
2501 #ifdef _SC_NPROCESSORS_ONLN
2503 int count = sysconf (_SC_NPROCESSORS_ONLN);
2509 #endif /* defined(HOST_ARM) || defined (HOST_ARM64) */
2515 size_t len = sizeof (int);
2518 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
2525 GetSystemInfo (&info);
2526 return info.dwNumberOfProcessors;
2537 unsigned int prev_pos;
2539 struct perf_event_mmap_page *page_desc;
2542 static PerfData *perf_data = NULL;
2543 static int num_perf;
2544 #define PERF_PAGES_SHIFT 4
2545 static int num_pages = 1 << PERF_PAGES_SHIFT;
2546 static unsigned int mmap_mask;
2549 struct perf_event_header h;
2559 perf_event_syscall (struct perf_event_attr *attr, pid_t pid, int cpu, int group_fd, unsigned long flags)
2561 attr->size = PERF_ATTR_SIZE_VER0;
2562 //printf ("perf attr size: %d\n", attr->size);
2563 #if defined(__x86_64__)
2564 return syscall(/*__NR_perf_event_open*/ 298, attr, pid, cpu, group_fd, flags);
2565 #elif defined(__i386__)
2566 return syscall(/*__NR_perf_event_open*/ 336, attr, pid, cpu, group_fd, flags);
2567 #elif defined(__arm__) || defined (__aarch64__)
2568 return syscall(/*__NR_perf_event_open*/ 364, attr, pid, cpu, group_fd, flags);
2575 setup_perf_map (PerfData *perf)
2577 perf->mmap_base = mmap (NULL, (num_pages + 1) * getpagesize (), PROT_READ|PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
2578 if (perf->mmap_base == MAP_FAILED) {
2580 printf ("failed mmap\n");
2583 perf->page_desc = perf->mmap_base;
2585 printf ("mmap version: %d\n", perf->page_desc->version);
2590 dump_perf_hits (MonoProfiler *prof, void *buf, int size)
2592 LogBuffer *logbuffer;
2595 void *end = (char*)buf + size;
2597 int pid = getpid ();
2603 if (pid != s->pid) {
2605 printf ("event for different pid: %d\n", s->pid);
2606 buf = (char*)buf + s->h.size;
2609 /*ip = (void*)s->ip;
2610 printf ("sample: %d, size: %d, ip: %p (%s), timestamp: %llu, nframes: %llu\n",
2611 s->h.type, s->h.size, ip, symbol_for (ip), s->timestamp, s->nframes);*/
2612 logbuffer = ensure_logbuf (
2613 EVENT_SIZE /* event */ +
2614 LEB128_SIZE /* type */ +
2615 LEB128_SIZE /* time */ +
2616 LEB128_SIZE /* tid */ +
2617 LEB128_SIZE /* count */ +
2619 LEB128_SIZE /* ip */
2621 LEB128_SIZE /* managed count */ +
2623 LEB128_SIZE /* method */ +
2624 LEB128_SIZE /* il offset */ +
2625 LEB128_SIZE /* native offset */
2628 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
2629 emit_value (logbuffer, sample_type);
2630 emit_uvalue (logbuffer, s->timestamp - prof->startup_time);
2632 * No useful thread ID to write here, since throughout the
2633 * profiler we use pthread_self () but the ID we get from
2634 * perf is the kernel's thread ID.
2636 emit_ptr (logbuffer, 0);
2637 emit_value (logbuffer, count);
2638 emit_ptr (logbuffer, (void*)(uintptr_t)s->ip);
2639 add_code_pointer (s->ip);
2640 /* no support here yet for the managed backtrace */
2641 emit_uvalue (logbuffer, mbt_count);
2642 buf = (char*)buf + s->h.size;
2646 printf ("dumped %d samples\n", samples);
2647 dump_unmanaged_coderefs (prof);
2650 /* read events from the ring buffer */
2652 read_perf_mmap (MonoProfiler* prof, int cpu)
2654 PerfData *perf = perf_data + cpu;
2656 unsigned char *data = (unsigned char*)perf->mmap_base + getpagesize ();
2657 unsigned int head = perf->page_desc->data_head;
2661 mono_memory_read_barrier ();
2663 old = perf->prev_pos;
2667 printf ("lost mmap events: old: %d, head: %d\n", old, head);
2671 if ((old & mmap_mask) + size != (head & mmap_mask)) {
2672 buf = data + (old & mmap_mask);
2673 size = mmap_mask + 1 - (old & mmap_mask);
2675 /* size bytes at buf */
2677 printf ("found1 bytes of events: %d\n", size);
2678 dump_perf_hits (prof, buf, size);
2680 buf = data + (old & mmap_mask);
2682 /* size bytes at buf */
2684 printf ("found bytes of events: %d\n", size);
2685 dump_perf_hits (prof, buf, size);
2687 perf->prev_pos = old;
2688 perf->page_desc->data_tail = old;
2693 setup_perf_event_for_cpu (PerfData *perf, int cpu)
2695 struct perf_event_attr attr;
2696 memset (&attr, 0, sizeof (attr));
2697 attr.type = PERF_TYPE_HARDWARE;
2698 switch (sample_type) {
2699 case SAMPLE_CYCLES: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2700 case SAMPLE_INSTRUCTIONS: attr.config = PERF_COUNT_HW_INSTRUCTIONS; break;
2701 case SAMPLE_CACHE_MISSES: attr.config = PERF_COUNT_HW_CACHE_MISSES; break;
2702 case SAMPLE_CACHE_REFS: attr.config = PERF_COUNT_HW_CACHE_REFERENCES; break;
2703 case SAMPLE_BRANCHES: attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS; break;
2704 case SAMPLE_BRANCH_MISSES: attr.config = PERF_COUNT_HW_BRANCH_MISSES; break;
2705 default: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2707 attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD | PERF_SAMPLE_TIME;
2708 // attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
2709 attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING | PERF_FORMAT_ID;
2712 attr.sample_freq = sample_freq;
2714 perf->perf_fd = perf_event_syscall (&attr, getpid (), cpu, -1, 0);
2716 printf ("perf fd: %d, freq: %d, event: %llu\n", perf->perf_fd, sample_freq, attr.config);
2717 if (perf->perf_fd < 0) {
2718 if (perf->perf_fd == -EPERM) {
2719 fprintf (stderr, "Perf syscall denied, do \"echo 1 > /proc/sys/kernel/perf_event_paranoid\" as root to enable.\n");
2722 perror ("open perf event");
2726 if (!setup_perf_map (perf)) {
2727 close (perf->perf_fd);
2735 setup_perf_event (void)
2738 mmap_mask = num_pages * getpagesize () - 1;
2739 num_perf = mono_cpu_count ();
2740 perf_data = calloc (num_perf, sizeof (PerfData));
2741 for (i = 0; i < num_perf; ++i) {
2742 count += setup_perf_event_for_cpu (perf_data + i, i);
2751 #endif /* USE_PERF_EVENTS */
2753 #ifndef DISABLE_HELPER_THREAD
2755 typedef struct MonoCounterAgent {
2756 MonoCounter *counter;
2757 // MonoCounterAgent specific data :
2762 struct MonoCounterAgent *next;
2765 static MonoCounterAgent* counters;
2766 static gboolean counters_initialized = FALSE;
2767 static int counters_index = 1;
2768 static mono_mutex_t counters_mutex;
2771 counters_add_agent (MonoCounter *counter)
2773 MonoCounterAgent *agent, *item;
2775 if (!counters_initialized)
2778 mono_os_mutex_lock (&counters_mutex);
2780 for (agent = counters; agent; agent = agent->next) {
2781 if (agent->counter == counter) {
2782 agent->value_size = 0;
2784 free (agent->value);
2785 agent->value = NULL;
2787 mono_os_mutex_unlock (&counters_mutex);
2792 agent = (MonoCounterAgent *)malloc (sizeof (MonoCounterAgent));
2793 agent->counter = counter;
2794 agent->value = NULL;
2795 agent->value_size = 0;
2796 agent->index = counters_index++;
2809 mono_os_mutex_unlock (&counters_mutex);
2813 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
2815 counters_add_agent (counter);
2820 counters_init (MonoProfiler *profiler)
2822 assert (!counters_initialized);
2824 mono_os_mutex_init (&counters_mutex);
2826 counters_initialized = TRUE;
2828 mono_counters_on_register (&counters_add_agent);
2829 mono_counters_foreach (counters_init_foreach_callback, NULL);
2833 counters_emit (MonoProfiler *profiler, gboolean threadless)
2835 MonoCounterAgent *agent;
2836 LogBuffer *logbuffer;
2839 EVENT_SIZE /* event */ +
2840 LEB128_SIZE /* len */
2843 if (!counters_initialized)
2846 mono_os_mutex_lock (&counters_mutex);
2848 for (agent = counters; agent; agent = agent->next) {
2853 LEB128_SIZE /* section */ +
2854 strlen (mono_counter_get_name (agent->counter)) + 1 /* name */ +
2855 LEB128_SIZE /* type */ +
2856 LEB128_SIZE /* unit */ +
2857 LEB128_SIZE /* variance */ +
2858 LEB128_SIZE /* index */
2865 mono_os_mutex_unlock (&counters_mutex);
2869 logbuffer = ensure_logbuf (size);
2871 ENTER_LOG (logbuffer, "counters");
2872 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2873 emit_value (logbuffer, len);
2874 for (agent = counters; agent; agent = agent->next) {
2880 name = mono_counter_get_name (agent->counter);
2881 emit_value (logbuffer, mono_counter_get_section (agent->counter));
2882 emit_string (logbuffer, name, strlen (name) + 1);
2883 emit_value (logbuffer, mono_counter_get_type (agent->counter));
2884 emit_value (logbuffer, mono_counter_get_unit (agent->counter));
2885 emit_value (logbuffer, mono_counter_get_variance (agent->counter));
2886 emit_value (logbuffer, agent->index);
2890 EXIT_LOG (logbuffer);
2893 safe_send_threadless (profiler, logbuffer);
2895 safe_send (profiler, logbuffer);
2897 mono_os_mutex_unlock (&counters_mutex);
2901 counters_sample (MonoProfiler *profiler, uint64_t timestamp, gboolean threadless)
2903 MonoCounterAgent *agent;
2904 MonoCounter *counter;
2905 LogBuffer *logbuffer;
2911 if (!counters_initialized)
2914 counters_emit (profiler, threadless);
2917 buffer = calloc (1, buffer_size);
2919 mono_os_mutex_lock (&counters_mutex);
2922 EVENT_SIZE /* event */ +
2923 LEB128_SIZE /* time */
2926 for (agent = counters; agent; agent = agent->next) {
2928 LEB128_SIZE /* index */ +
2929 LEB128_SIZE /* type */ +
2930 mono_counter_get_size (agent->counter) /* value */
2935 LEB128_SIZE /* stop marker */
2938 logbuffer = ensure_logbuf (size);
2940 ENTER_LOG (logbuffer, "counters");
2941 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
2942 emit_uvalue (logbuffer, timestamp);
2943 for (agent = counters; agent; agent = agent->next) {
2946 counter = agent->counter;
2948 size = mono_counter_get_size (counter);
2950 continue; // FIXME error
2951 } else if (size > buffer_size) {
2953 buffer = realloc (buffer, buffer_size);
2956 memset (buffer, 0, buffer_size);
2958 if (mono_counters_sample (counter, buffer, size) < 0)
2959 continue; // FIXME error
2961 type = mono_counter_get_type (counter);
2963 if (!agent->value) {
2964 agent->value = calloc (1, size);
2965 agent->value_size = size;
2967 if (type == MONO_COUNTER_STRING) {
2968 if (strcmp (agent->value, buffer) == 0)
2971 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
2976 emit_uvalue (logbuffer, agent->index);
2977 emit_uvalue (logbuffer, type);
2979 case MONO_COUNTER_INT:
2980 #if SIZEOF_VOID_P == 4
2981 case MONO_COUNTER_WORD:
2983 emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
2985 case MONO_COUNTER_UINT:
2986 emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
2988 case MONO_COUNTER_TIME_INTERVAL:
2989 case MONO_COUNTER_LONG:
2990 #if SIZEOF_VOID_P == 8
2991 case MONO_COUNTER_WORD:
2993 emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
2995 case MONO_COUNTER_ULONG:
2996 emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
2998 case MONO_COUNTER_DOUBLE:
2999 emit_double (logbuffer, *(double*)buffer);
3001 case MONO_COUNTER_STRING:
3003 emit_byte (logbuffer, 0);
3005 emit_byte (logbuffer, 1);
3006 emit_string (logbuffer, (char*)buffer, size);
3013 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
3014 agent->value = realloc (agent->value, size);
3015 agent->value_size = size;
3019 memcpy (agent->value, buffer, size);
3023 emit_value (logbuffer, 0);
3024 EXIT_LOG (logbuffer);
3027 safe_send_threadless (profiler, logbuffer);
3029 safe_send (profiler, logbuffer);
3031 mono_os_mutex_unlock (&counters_mutex);
3034 typedef struct _PerfCounterAgent PerfCounterAgent;
3035 struct _PerfCounterAgent {
3036 PerfCounterAgent *next;
3038 char *category_name;
3047 static PerfCounterAgent *perfcounters = NULL;
3050 perfcounters_emit (MonoProfiler *profiler, gboolean threadless)
3052 PerfCounterAgent *pcagent;
3053 LogBuffer *logbuffer;
3056 EVENT_SIZE /* event */ +
3057 LEB128_SIZE /* len */
3060 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3061 if (pcagent->emitted)
3065 LEB128_SIZE /* section */ +
3066 strlen (pcagent->category_name) + 1 /* category name */ +
3067 strlen (pcagent->name) + 1 /* name */ +
3068 LEB128_SIZE /* type */ +
3069 LEB128_SIZE /* unit */ +
3070 LEB128_SIZE /* variance */ +
3071 LEB128_SIZE /* index */
3080 logbuffer = ensure_logbuf (size);
3082 ENTER_LOG (logbuffer, "perfcounters");
3083 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
3084 emit_value (logbuffer, len);
3085 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3086 if (pcagent->emitted)
3089 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
3090 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
3091 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
3092 emit_value (logbuffer, MONO_COUNTER_LONG);
3093 emit_value (logbuffer, MONO_COUNTER_RAW);
3094 emit_value (logbuffer, MONO_COUNTER_VARIABLE);
3095 emit_value (logbuffer, pcagent->index);
3097 pcagent->emitted = 1;
3099 EXIT_LOG (logbuffer);
3102 safe_send_threadless (profiler, logbuffer);
3104 safe_send (profiler, logbuffer);
3108 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
3110 PerfCounterAgent *pcagent;
3112 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3113 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
3115 if (pcagent->value == value)
3118 pcagent->value = value;
3119 pcagent->updated = 1;
3120 pcagent->deleted = 0;
3124 pcagent = g_new0 (PerfCounterAgent, 1);
3125 pcagent->next = perfcounters;
3126 pcagent->index = counters_index++;
3127 pcagent->category_name = g_strdup (category_name);
3128 pcagent->name = g_strdup (name);
3129 pcagent->type = (int) type;
3130 pcagent->value = value;
3131 pcagent->emitted = 0;
3132 pcagent->updated = 1;
3133 pcagent->deleted = 0;
3135 perfcounters = pcagent;
3141 perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp, gboolean threadless)
3143 PerfCounterAgent *pcagent;
3144 LogBuffer *logbuffer;
3147 if (!counters_initialized)
3150 mono_os_mutex_lock (&counters_mutex);
3152 /* mark all perfcounters as deleted, foreach will unmark them as necessary */
3153 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
3154 pcagent->deleted = 1;
3156 mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
3158 perfcounters_emit (profiler, threadless);
3161 EVENT_SIZE /* event */ +
3162 LEB128_SIZE /* time */
3165 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3166 if (pcagent->deleted || !pcagent->updated)
3170 LEB128_SIZE /* index */ +
3171 LEB128_SIZE /* type */ +
3172 LEB128_SIZE /* value */
3177 LEB128_SIZE /* stop marker */
3180 logbuffer = ensure_logbuf (size);
3182 ENTER_LOG (logbuffer, "perfcounters");
3183 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
3184 emit_uvalue (logbuffer, timestamp);
3185 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3186 if (pcagent->deleted || !pcagent->updated)
3188 emit_uvalue (logbuffer, pcagent->index);
3189 emit_uvalue (logbuffer, MONO_COUNTER_LONG);
3190 emit_svalue (logbuffer, pcagent->value);
3192 pcagent->updated = 0;
3195 emit_value (logbuffer, 0);
3196 EXIT_LOG (logbuffer);
3199 safe_send_threadless (profiler, logbuffer);
3201 safe_send (profiler, logbuffer);
3203 mono_os_mutex_unlock (&counters_mutex);
3207 counters_and_perfcounters_sample (MonoProfiler *prof, gboolean threadless)
3209 static uint64_t start = -1;
3213 start = current_time ();
3215 now = current_time ();
3216 counters_sample (prof, (now - start) / 1000/ 1000, threadless);
3217 perfcounters_sample (prof, (now - start) / 1000/ 1000, threadless);
3220 #define COVERAGE_DEBUG(x) if (debug_coverage) {x}
3221 static mono_mutex_t coverage_mutex;
3222 static MonoConcurrentHashTable *coverage_methods = NULL;
3223 static MonoConcurrentHashTable *coverage_assemblies = NULL;
3224 static MonoConcurrentHashTable *coverage_classes = NULL;
3226 static MonoConcurrentHashTable *filtered_classes = NULL;
3227 static MonoConcurrentHashTable *entered_methods = NULL;
3228 static MonoConcurrentHashTable *image_to_methods = NULL;
3229 static MonoConcurrentHashTable *suppressed_assemblies = NULL;
3230 static gboolean coverage_initialized = FALSE;
3232 static GPtrArray *coverage_data = NULL;
3233 static int previous_offset = 0;
3235 typedef struct _MethodNode MethodNode;
3236 struct _MethodNode {
3237 MonoLockFreeQueueNode node;
3241 typedef struct _CoverageEntry CoverageEntry;
3242 struct _CoverageEntry {
3251 free_coverage_entry (gpointer data, gpointer userdata)
3253 CoverageEntry *entry = (CoverageEntry *)data;
3254 g_free (entry->filename);
3259 obtain_coverage_for_method (MonoProfiler *prof, const MonoProfileCoverageEntry *entry)
3261 int offset = entry->iloffset - previous_offset;
3262 CoverageEntry *e = g_new (CoverageEntry, 1);
3264 previous_offset = entry->iloffset;
3267 e->counter = entry->counter;
3268 e->filename = g_strdup(entry->filename ? entry->filename : "");
3269 e->line = entry->line;
3270 e->column = entry->col;
3272 g_ptr_array_add (coverage_data, e);
3276 parse_generic_type_names(char *name)
3278 char *new_name, *ret;
3279 int within_generic_declaration = 0, generic_members = 1;
3281 if (name == NULL || *name == '\0')
3282 return g_strdup ("");
3284 if (!(ret = new_name = (char *)calloc (strlen (name) * 4 + 1, sizeof (char))))
3290 within_generic_declaration = 1;
3294 within_generic_declaration = 0;
3296 if (*(name - 1) != '<') {
3298 *new_name++ = '0' + generic_members;
3300 memcpy (new_name, "<>", 8);
3304 generic_members = 0;
3312 if (!within_generic_declaration)
3313 *new_name++ = *name;
3322 static int method_id;
3324 build_method_buffer (gpointer key, gpointer value, gpointer userdata)
3326 MonoMethod *method = (MonoMethod *)value;
3327 MonoProfiler *prof = (MonoProfiler *)userdata;
3331 const char *image_name, *method_name, *sig, *first_filename;
3332 LogBuffer *logbuffer;
3335 previous_offset = 0;
3336 coverage_data = g_ptr_array_new ();
3338 mono_profiler_coverage_get (prof, method, obtain_coverage_for_method);
3340 klass = mono_method_get_class (method);
3341 image = mono_class_get_image (klass);
3342 image_name = mono_image_get_name (image);
3344 sig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3345 class_name = parse_generic_type_names (mono_type_get_name (mono_class_get_type (klass)));
3346 method_name = mono_method_get_name (method);
3348 if (coverage_data->len != 0) {
3349 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[0];
3350 first_filename = entry->filename ? entry->filename : "";
3352 first_filename = "";
3354 image_name = image_name ? image_name : "";
3355 sig = sig ? sig : "";
3356 method_name = method_name ? method_name : "";
3358 logbuffer = ensure_logbuf (
3359 EVENT_SIZE /* event */ +
3360 strlen (image_name) + 1 /* image name */ +
3361 strlen (class_name) + 1 /* class name */ +
3362 strlen (method_name) + 1 /* method name */ +
3363 strlen (sig) + 1 /* signature */ +
3364 strlen (first_filename) + 1 /* first file name */ +
3365 LEB128_SIZE /* token */ +
3366 LEB128_SIZE /* method id */ +
3367 LEB128_SIZE /* entries */
3369 ENTER_LOG (logbuffer, "coverage-methods");
3371 emit_byte (logbuffer, TYPE_COVERAGE_METHOD | TYPE_COVERAGE);
3372 emit_string (logbuffer, image_name, strlen (image_name) + 1);
3373 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3374 emit_string (logbuffer, method_name, strlen (method_name) + 1);
3375 emit_string (logbuffer, sig, strlen (sig) + 1);
3376 emit_string (logbuffer, first_filename, strlen (first_filename) + 1);
3378 emit_uvalue (logbuffer, mono_method_get_token (method));
3379 emit_uvalue (logbuffer, method_id);
3380 emit_value (logbuffer, coverage_data->len);
3382 EXIT_LOG (logbuffer);
3383 safe_send (prof, logbuffer);
3385 for (i = 0; i < coverage_data->len; i++) {
3386 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[i];
3388 logbuffer = ensure_logbuf (
3389 EVENT_SIZE /* event */ +
3390 LEB128_SIZE /* method id */ +
3391 LEB128_SIZE /* offset */ +
3392 LEB128_SIZE /* counter */ +
3393 LEB128_SIZE /* line */ +
3394 LEB128_SIZE /* column */
3396 ENTER_LOG (logbuffer, "coverage-statement");
3398 emit_byte (logbuffer, TYPE_COVERAGE_STATEMENT | TYPE_COVERAGE);
3399 emit_uvalue (logbuffer, method_id);
3400 emit_uvalue (logbuffer, entry->offset);
3401 emit_uvalue (logbuffer, entry->counter);
3402 emit_uvalue (logbuffer, entry->line);
3403 emit_uvalue (logbuffer, entry->column);
3405 EXIT_LOG (logbuffer);
3406 safe_send (prof, logbuffer);
3411 g_free (class_name);
3413 g_ptr_array_foreach (coverage_data, free_coverage_entry, NULL);
3414 g_ptr_array_free (coverage_data, TRUE);
3415 coverage_data = NULL;
3418 /* This empties the queue */
3420 count_queue (MonoLockFreeQueue *queue)
3422 MonoLockFreeQueueNode *node;
3425 while ((node = mono_lock_free_queue_dequeue (queue))) {
3427 mono_thread_hazardous_try_free (node, free);
3434 build_class_buffer (gpointer key, gpointer value, gpointer userdata)
3436 MonoClass *klass = (MonoClass *)key;
3437 MonoLockFreeQueue *class_methods = (MonoLockFreeQueue *)value;
3438 MonoProfiler *prof = (MonoProfiler *)userdata;
3441 const char *assembly_name;
3442 int number_of_methods, partially_covered;
3443 guint fully_covered;
3444 LogBuffer *logbuffer;
3446 image = mono_class_get_image (klass);
3447 assembly_name = mono_image_get_name (image);
3448 class_name = mono_type_get_name (mono_class_get_type (klass));
3450 assembly_name = assembly_name ? assembly_name : "";
3451 number_of_methods = mono_class_num_methods (klass);
3452 fully_covered = count_queue (class_methods);
3453 /* We don't handle partial covered yet */
3454 partially_covered = 0;
3456 logbuffer = ensure_logbuf (
3457 EVENT_SIZE /* event */ +
3458 strlen (assembly_name) + 1 /* assembly name */ +
3459 strlen (class_name) + 1 /* class name */ +
3460 LEB128_SIZE /* no. methods */ +
3461 LEB128_SIZE /* fully covered */ +
3462 LEB128_SIZE /* partially covered */
3465 ENTER_LOG (logbuffer, "coverage-class");
3466 emit_byte (logbuffer, TYPE_COVERAGE_CLASS | TYPE_COVERAGE);
3467 emit_string (logbuffer, assembly_name, strlen (assembly_name) + 1);
3468 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3469 emit_uvalue (logbuffer, number_of_methods);
3470 emit_uvalue (logbuffer, fully_covered);
3471 emit_uvalue (logbuffer, partially_covered);
3472 EXIT_LOG (logbuffer);
3474 safe_send (prof, logbuffer);
3476 g_free (class_name);
3480 get_coverage_for_image (MonoImage *image, int *number_of_methods, guint *fully_covered, int *partially_covered)
3482 MonoLockFreeQueue *image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3484 *number_of_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
3486 *fully_covered = count_queue (image_methods);
3490 // FIXME: We don't handle partially covered yet.
3491 *partially_covered = 0;
3495 build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
3497 MonoAssembly *assembly = (MonoAssembly *)value;
3498 MonoProfiler *prof = (MonoProfiler *)userdata;
3499 MonoImage *image = mono_assembly_get_image (assembly);
3500 LogBuffer *logbuffer;
3501 const char *name, *guid, *filename;
3502 int number_of_methods = 0, partially_covered = 0;
3503 guint fully_covered = 0;
3505 name = mono_image_get_name (image);
3506 guid = mono_image_get_guid (image);
3507 filename = mono_image_get_filename (image);
3509 name = name ? name : "";
3510 guid = guid ? guid : "";
3511 filename = filename ? filename : "";
3513 get_coverage_for_image (image, &number_of_methods, &fully_covered, &partially_covered);
3515 logbuffer = ensure_logbuf (
3516 EVENT_SIZE /* event */ +
3517 strlen (name) + 1 /* name */ +
3518 strlen (guid) + 1 /* guid */ +
3519 strlen (filename) + 1 /* file name */ +
3520 LEB128_SIZE /* no. methods */ +
3521 LEB128_SIZE /* fully covered */ +
3522 LEB128_SIZE /* partially covered */
3525 ENTER_LOG (logbuffer, "coverage-assemblies");
3526 emit_byte (logbuffer, TYPE_COVERAGE_ASSEMBLY | TYPE_COVERAGE);
3527 emit_string (logbuffer, name, strlen (name) + 1);
3528 emit_string (logbuffer, guid, strlen (guid) + 1);
3529 emit_string (logbuffer, filename, strlen (filename) + 1);
3530 emit_uvalue (logbuffer, number_of_methods);
3531 emit_uvalue (logbuffer, fully_covered);
3532 emit_uvalue (logbuffer, partially_covered);
3533 EXIT_LOG (logbuffer);
3535 safe_send (prof, logbuffer);
3539 dump_coverage (MonoProfiler *prof)
3541 if (!coverage_initialized)
3544 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Started dump\n");)
3547 mono_os_mutex_lock (&coverage_mutex);
3548 mono_conc_hashtable_foreach (coverage_assemblies, build_assembly_buffer, prof);
3549 mono_conc_hashtable_foreach (coverage_classes, build_class_buffer, prof);
3550 mono_conc_hashtable_foreach (coverage_methods, build_method_buffer, prof);
3551 mono_os_mutex_unlock (&coverage_mutex);
3553 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Finished dump\n");)
3557 process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method)
3562 if (!coverage_initialized)
3565 klass = mono_method_get_class (method);
3566 image = mono_class_get_image (klass);
3568 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)))
3571 mono_os_mutex_lock (&coverage_mutex);
3572 mono_conc_hashtable_insert (entered_methods, method, method);
3573 mono_os_mutex_unlock (&coverage_mutex);
3576 static MonoLockFreeQueueNode *
3577 create_method_node (MonoMethod *method)
3579 MethodNode *node = (MethodNode *)g_malloc (sizeof (MethodNode));
3580 mono_lock_free_queue_node_init ((MonoLockFreeQueueNode *) node, FALSE);
3581 node->method = method;
3583 return (MonoLockFreeQueueNode *) node;
3587 coverage_filter (MonoProfiler *prof, MonoMethod *method)
3592 MonoAssembly *assembly;
3593 MonoMethodHeader *header;
3594 guint32 iflags, flags, code_size;
3595 char *fqn, *classname;
3596 gboolean has_positive, found;
3597 MonoLockFreeQueue *image_methods, *class_methods;
3598 MonoLockFreeQueueNode *node;
3600 if (!coverage_initialized)
3603 COVERAGE_DEBUG(fprintf (stderr, "Coverage filter for %s\n", mono_method_get_name (method));)
3605 flags = mono_method_get_flags (method, &iflags);
3606 if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
3607 (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/)) {
3608 COVERAGE_DEBUG(fprintf (stderr, " Internal call or pinvoke - ignoring\n");)
3612 // Don't need to do anything else if we're already tracking this method
3613 if (mono_conc_hashtable_lookup (coverage_methods, method)) {
3614 COVERAGE_DEBUG(fprintf (stderr, " Already tracking\n");)
3618 klass = mono_method_get_class (method);
3619 image = mono_class_get_image (klass);
3621 // Don't handle coverage for the core assemblies
3622 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)) != NULL)
3625 if (prof->coverage_filters) {
3626 /* Check already filtered classes first */
3627 if (mono_conc_hashtable_lookup (filtered_classes, klass)) {
3628 COVERAGE_DEBUG(fprintf (stderr, " Already filtered\n");)
3632 classname = mono_type_get_name (mono_class_get_type (klass));
3634 fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
3636 COVERAGE_DEBUG(fprintf (stderr, " Looking for %s in filter\n", fqn);)
3637 // Check positive filters first
3638 has_positive = FALSE;
3640 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3641 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3643 if (filter [0] == '+') {
3644 filter = &filter [1];
3646 COVERAGE_DEBUG(fprintf (stderr, " Checking against +%s ...", filter);)
3648 if (strstr (fqn, filter) != NULL) {
3649 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3652 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3654 has_positive = TRUE;
3658 if (has_positive && !found) {
3659 COVERAGE_DEBUG(fprintf (stderr, " Positive match was not found\n");)
3661 mono_os_mutex_lock (&coverage_mutex);
3662 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3663 mono_os_mutex_unlock (&coverage_mutex);
3670 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3671 // FIXME: Is substring search sufficient?
3672 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3673 if (filter [0] == '+')
3677 filter = &filter [1];
3678 COVERAGE_DEBUG(fprintf (stderr, " Checking against -%s ...", filter);)
3680 if (strstr (fqn, filter) != NULL) {
3681 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3683 mono_os_mutex_lock (&coverage_mutex);
3684 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3685 mono_os_mutex_unlock (&coverage_mutex);
3691 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3699 COVERAGE_DEBUG(fprintf (stderr, " Handling coverage for %s\n", mono_method_get_name (method));)
3700 header = mono_method_get_header_checked (method, &error);
3701 mono_error_cleanup (&error);
3703 mono_method_header_get_code (header, &code_size, NULL);
3705 assembly = mono_image_get_assembly (image);
3707 // Need to keep the assemblies around for as long as they are kept in the hashtable
3708 // Nunit, for example, has a habit of unloading them before the coverage statistics are
3709 // generated causing a crash. See https://bugzilla.xamarin.com/show_bug.cgi?id=39325
3710 mono_assembly_addref (assembly);
3712 mono_os_mutex_lock (&coverage_mutex);
3713 mono_conc_hashtable_insert (coverage_methods, method, method);
3714 mono_conc_hashtable_insert (coverage_assemblies, assembly, assembly);
3715 mono_os_mutex_unlock (&coverage_mutex);
3717 image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3719 if (image_methods == NULL) {
3720 image_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
3721 mono_lock_free_queue_init (image_methods);
3722 mono_os_mutex_lock (&coverage_mutex);
3723 mono_conc_hashtable_insert (image_to_methods, image, image_methods);
3724 mono_os_mutex_unlock (&coverage_mutex);
3727 node = create_method_node (method);
3728 mono_lock_free_queue_enqueue (image_methods, node);
3730 class_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (coverage_classes, klass);
3732 if (class_methods == NULL) {
3733 class_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
3734 mono_lock_free_queue_init (class_methods);
3735 mono_os_mutex_lock (&coverage_mutex);
3736 mono_conc_hashtable_insert (coverage_classes, klass, class_methods);
3737 mono_os_mutex_unlock (&coverage_mutex);
3740 node = create_method_node (method);
3741 mono_lock_free_queue_enqueue (class_methods, node);
3746 #define LINE_BUFFER_SIZE 4096
3747 /* Max file limit of 128KB */
3748 #define MAX_FILE_SIZE 128 * 1024
3750 get_file_content (FILE *stream)
3755 int res, offset = 0;
3757 res = fseek (stream, 0, SEEK_END);
3761 filesize = ftell (stream);
3765 res = fseek (stream, 0, SEEK_SET);
3769 if (filesize > MAX_FILE_SIZE)
3772 buffer = (char *)g_malloc ((filesize + 1) * sizeof (char));
3773 while ((bytes_read = fread (buffer + offset, 1, LINE_BUFFER_SIZE, stream)) > 0)
3774 offset += bytes_read;
3776 /* NULL terminate our buffer */
3777 buffer[filesize] = '\0';
3782 get_next_line (char *contents, char **next_start)
3786 if (p == NULL || *p == '\0') {
3791 while (*p != '\n' && *p != '\0')
3796 *next_start = p + 1;
3804 init_suppressed_assemblies (void)
3810 suppressed_assemblies = mono_conc_hashtable_new (g_str_hash, g_str_equal);
3811 sa_file = fopen (SUPPRESSION_DIR "/mono-profiler-log.suppression", "r");
3812 if (sa_file == NULL)
3815 /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
3816 content = get_file_content (sa_file);
3817 if (content == NULL) {
3818 g_error ("mono-profiler-log.suppression is greater than 128kb - aborting\n");
3821 while ((line = get_next_line (content, &content))) {
3822 line = g_strchomp (g_strchug (line));
3823 /* No locking needed as we're doing initialization */
3824 mono_conc_hashtable_insert (suppressed_assemblies, line, line);
3830 #endif /* DISABLE_HELPER_THREAD */
3833 coverage_init (MonoProfiler *prof)
3835 #ifndef DISABLE_HELPER_THREAD
3836 assert (!coverage_initialized);
3838 COVERAGE_DEBUG(fprintf (stderr, "Coverage initialized\n");)
3840 mono_os_mutex_init (&coverage_mutex);
3841 coverage_methods = mono_conc_hashtable_new (NULL, NULL);
3842 coverage_assemblies = mono_conc_hashtable_new (NULL, NULL);
3843 coverage_classes = mono_conc_hashtable_new (NULL, NULL);
3844 filtered_classes = mono_conc_hashtable_new (NULL, NULL);
3845 entered_methods = mono_conc_hashtable_new (NULL, NULL);
3846 image_to_methods = mono_conc_hashtable_new (NULL, NULL);
3847 init_suppressed_assemblies ();
3849 coverage_initialized = TRUE;
3850 #endif /* DISABLE_HELPER_THREAD */
3854 unref_coverage_assemblies (gpointer key, gpointer value, gpointer userdata)
3856 MonoAssembly *assembly = (MonoAssembly *)value;
3857 mono_assembly_close (assembly);
3861 free_sample_hit (gpointer p)
3863 mono_lock_free_free (p, SAMPLE_BLOCK_SIZE);
3867 cleanup_reusable_samples (MonoProfiler *prof)
3871 while ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&prof->sample_reuse_queue)))
3872 mono_thread_hazardous_try_free (sample, free_sample_hit);
3876 log_shutdown (MonoProfiler *prof)
3881 #ifndef DISABLE_HELPER_THREAD
3882 counters_and_perfcounters_sample (prof, FALSE);
3884 dump_coverage (prof);
3886 if (prof->command_port) {
3888 ign_res (write (prof->pipes [1], &c, 1));
3889 pthread_join (prof->helper_thread, &res);
3895 for (i = 0; i < num_perf; ++i)
3896 read_perf_mmap (prof, i);
3900 if (TLS_GET (LogBuffer, tlsbuffer))
3901 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
3903 TLS_SET (tlsbuffer, NULL);
3904 TLS_SET (tlsmethodlist, NULL);
3906 InterlockedWrite (&prof->run_dumper_thread, 0);
3907 mono_os_sem_post (&prof->dumper_queue_sem);
3908 pthread_join (prof->dumper_thread, &res);
3909 mono_os_sem_destroy (&prof->dumper_queue_sem);
3911 InterlockedWrite (&prof->run_writer_thread, 0);
3912 mono_os_sem_post (&prof->writer_queue_sem);
3913 pthread_join (prof->writer_thread, &res);
3914 mono_os_sem_destroy (&prof->writer_queue_sem);
3916 cleanup_reusable_samples (prof);
3918 #if defined (HAVE_SYS_ZLIB)
3920 gzclose (prof->gzfile);
3922 if (prof->pipe_output)
3923 pclose (prof->file);
3925 fclose (prof->file);
3927 mono_conc_hashtable_destroy (prof->method_table);
3928 mono_os_mutex_destroy (&prof->method_table_mutex);
3930 if (coverage_initialized) {
3931 mono_os_mutex_lock (&coverage_mutex);
3932 mono_conc_hashtable_foreach (coverage_assemblies, unref_coverage_assemblies, prof);
3933 mono_os_mutex_unlock (&coverage_mutex);
3935 mono_conc_hashtable_destroy (coverage_methods);
3936 mono_conc_hashtable_destroy (coverage_assemblies);
3937 mono_conc_hashtable_destroy (coverage_classes);
3938 mono_conc_hashtable_destroy (filtered_classes);
3940 mono_conc_hashtable_destroy (entered_methods);
3941 mono_conc_hashtable_destroy (image_to_methods);
3942 mono_conc_hashtable_destroy (suppressed_assemblies);
3943 mono_os_mutex_destroy (&coverage_mutex);
3950 new_filename (const char* filename)
3952 time_t t = time (NULL);
3953 int pid = process_id ();
3958 int count_dates = 0;
3962 for (p = filename; *p; p++) {
3973 if (!count_dates && !count_pids)
3974 return pstrdup (filename);
3975 snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
3977 snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
3978 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
3979 s_date = strlen (time_buf);
3980 s_pid = strlen (pid_buf);
3981 d = res = (char *)malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
3982 for (p = filename; *p; p++) {
3989 strcpy (d, time_buf);
3992 } else if (*p == 'p') {
3993 strcpy (d, pid_buf);
3996 } else if (*p == '%') {
4008 //this is exposed by the JIT, but it's not meant to be a supported API for now.
4009 extern void mono_threads_attach_tools_thread (void);
4011 #ifndef DISABLE_HELPER_THREAD
4014 helper_thread (void* arg)
4016 MonoProfiler* prof = (MonoProfiler *)arg;
4020 MonoThread *thread = NULL;
4022 mono_threads_attach_tools_thread ();
4023 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler helper");
4025 //fprintf (stderr, "Server listening\n");
4026 command_socket = -1;
4032 FD_SET (prof->server_socket, &rfds);
4033 max_fd = prof->server_socket;
4034 FD_SET (prof->pipes [0], &rfds);
4035 if (max_fd < prof->pipes [0])
4036 max_fd = prof->pipes [0];
4037 if (command_socket >= 0) {
4038 FD_SET (command_socket, &rfds);
4039 if (max_fd < command_socket)
4040 max_fd = command_socket;
4045 for ( i = 0; i < num_perf; ++i) {
4046 if (perf_data [i].perf_fd < 0)
4048 FD_SET (perf_data [i].perf_fd, &rfds);
4049 if (max_fd < perf_data [i].perf_fd)
4050 max_fd = perf_data [i].perf_fd;
4055 counters_and_perfcounters_sample (prof, TRUE);
4059 len = select (max_fd + 1, &rfds, NULL, NULL, &tv);
4065 g_warning ("Error in proflog server: %s", strerror (errno));
4069 if (FD_ISSET (prof->pipes [0], &rfds)) {
4071 read (prof->pipes [0], &c, 1);
4073 mono_thread_detach (thread);
4075 fprintf (stderr, "helper shutdown\n");
4079 for ( i = 0; i < num_perf; ++i) {
4080 if (perf_data [i].perf_fd < 0)
4082 if (FD_ISSET (perf_data [i].perf_fd, &rfds))
4083 read_perf_mmap (prof, i);
4087 safe_send_threadless (prof, ensure_logbuf (0));
4093 for ( i = 0; i < num_perf; ++i) {
4094 if (perf_data [i].perf_fd < 0)
4096 if (FD_ISSET (perf_data [i].perf_fd, &rfds)) {
4097 read_perf_mmap (prof, i);
4098 safe_send_threadless (prof, ensure_logbuf (0));
4103 if (command_socket >= 0 && FD_ISSET (command_socket, &rfds)) {
4104 len = read (command_socket, buf, sizeof (buf) - 1);
4108 close (command_socket);
4109 command_socket = -1;
4113 if (strcmp (buf, "heapshot\n") == 0) {
4114 heapshot_requested = 1;
4115 //fprintf (stderr, "perform heapshot\n");
4116 if (InterlockedRead (&runtime_inited) && !thread) {
4117 thread = mono_thread_attach (mono_get_root_domain ());
4118 /*fprintf (stderr, "attached\n");*/
4121 process_requests (prof);
4122 mono_thread_detach (thread);
4128 if (!FD_ISSET (prof->server_socket, &rfds)) {
4131 command_socket = accept (prof->server_socket, NULL, NULL);
4132 if (command_socket < 0)
4134 //fprintf (stderr, "Accepted connection\n");
4137 mono_thread_info_detach ();
4143 start_helper_thread (MonoProfiler* prof)
4145 struct sockaddr_in server_address;
4148 if (pipe (prof->pipes) < 0) {
4149 fprintf (stderr, "Cannot create pipe\n");
4152 prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
4153 if (prof->server_socket < 0) {
4154 fprintf (stderr, "Cannot create server socket\n");
4157 memset (&server_address, 0, sizeof (server_address));
4158 server_address.sin_family = AF_INET;
4159 server_address.sin_addr.s_addr = INADDR_ANY;
4160 server_address.sin_port = htons (prof->command_port);
4161 if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) < 0) {
4162 fprintf (stderr, "Cannot bind server socket, port: %d: %s\n", prof->command_port, strerror (errno));
4163 close (prof->server_socket);
4166 if (listen (prof->server_socket, 1) < 0) {
4167 fprintf (stderr, "Cannot listen server socket\n");
4168 close (prof->server_socket);
4171 slen = sizeof (server_address);
4172 if (getsockname (prof->server_socket, (struct sockaddr *)&server_address, &slen) == 0) {
4173 prof->command_port = ntohs (server_address.sin_port);
4174 /*fprintf (stderr, "Assigned server port: %d\n", prof->command_port);*/
4177 r = pthread_create (&prof->helper_thread, NULL, helper_thread, prof);
4179 close (prof->server_socket);
4187 handle_writer_queue_entry (MonoProfiler *prof)
4189 WriterQueueEntry *entry;
4191 if ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&prof->writer_queue))) {
4192 LogBuffer *method_buffer = NULL;
4193 gboolean new_methods = FALSE;
4195 if (entry->methods->len)
4196 method_buffer = create_buffer ();
4199 * Encode the method events in a temporary log buffer that we
4200 * flush to disk before the main buffer, ensuring that all
4201 * methods have metadata emitted before they're referenced.
4203 for (guint i = 0; i < entry->methods->len; i++) {
4204 MethodInfo *info = (MethodInfo *)g_ptr_array_index (entry->methods, i);
4206 if (mono_conc_hashtable_lookup (prof->method_table, info->method))
4212 * Other threads use this hash table to get a general
4213 * idea of whether a method has already been emitted to
4214 * the stream. Due to the way we add to this table, it
4215 * can easily happen that multiple threads queue up the
4216 * same methods, but that's OK since eventually all
4217 * methods will be in this table and the thread-local
4218 * method lists will just be empty for the rest of the
4221 mono_os_mutex_lock (&prof->method_table_mutex);
4222 mono_conc_hashtable_insert (prof->method_table, info->method, info->method);
4223 mono_os_mutex_unlock (&prof->method_table_mutex);
4225 char *name = mono_method_full_name (info->method, 1);
4226 int nlen = strlen (name) + 1;
4227 void *cstart = info->ji ? mono_jit_info_get_code_start (info->ji) : NULL;
4228 int csize = info->ji ? mono_jit_info_get_code_size (info->ji) : 0;
4230 method_buffer = ensure_logbuf_inner (method_buffer,
4231 EVENT_SIZE /* event */ +
4232 LEB128_SIZE /* time */ +
4233 LEB128_SIZE /* method */ +
4234 LEB128_SIZE /* start */ +
4235 LEB128_SIZE /* size */ +
4239 emit_byte (method_buffer, TYPE_JIT | TYPE_METHOD);
4240 emit_time (method_buffer, info->time);
4241 emit_method_inner (method_buffer, info->method);
4242 emit_ptr (method_buffer, cstart);
4243 emit_value (method_buffer, csize);
4245 memcpy (method_buffer->cursor, name, nlen);
4246 method_buffer->cursor += nlen;
4252 g_ptr_array_free (entry->methods, TRUE);
4255 for (LogBuffer *iter = method_buffer; iter; iter = iter->next)
4256 iter->thread_id = 0;
4258 dump_buffer (prof, method_buffer);
4259 } else if (method_buffer)
4260 free_buffer (method_buffer, method_buffer->size);
4262 dump_buffer (prof, entry->buffer);
4264 mono_thread_hazardous_try_free (entry, free);
4273 writer_thread (void *arg)
4275 MonoProfiler *prof = (MonoProfiler *)arg;
4277 mono_threads_attach_tools_thread ();
4278 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler writer");
4282 while (InterlockedRead (&prof->run_writer_thread)) {
4283 mono_os_sem_wait (&prof->writer_queue_sem, MONO_SEM_FLAGS_NONE);
4284 handle_writer_queue_entry (prof);
4287 /* Drain any remaining entries on shutdown. */
4288 while (handle_writer_queue_entry (prof));
4290 mono_thread_info_detach ();
4296 start_writer_thread (MonoProfiler* prof)
4298 InterlockedWrite (&prof->run_writer_thread, 1);
4300 return !pthread_create (&prof->writer_thread, NULL, writer_thread, prof);
4304 reuse_sample_hit (gpointer p)
4306 SampleHit *sample = p;
4308 mono_lock_free_queue_node_unpoison (&sample->node);
4309 mono_lock_free_queue_enqueue (&sample->prof->sample_reuse_queue, &sample->node);
4313 handle_dumper_queue_entry (MonoProfiler *prof)
4317 if ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&prof->dumper_queue))) {
4318 for (int i = 0; i < sample->count; ++i) {
4319 MonoMethod *method = sample->frames [i].method;
4320 MonoDomain *domain = sample->frames [i].domain;
4321 void *address = sample->frames [i].base_address;
4327 MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *) address);
4330 sample->frames [i].method = mono_jit_info_get_method (ji);
4334 LogBuffer *logbuffer = ensure_logbuf (
4335 EVENT_SIZE /* event */ +
4336 LEB128_SIZE /* type */ +
4337 LEB128_SIZE /* time */ +
4338 LEB128_SIZE /* tid */ +
4339 LEB128_SIZE /* count */ +
4341 LEB128_SIZE /* ip */
4343 LEB128_SIZE /* managed count */ +
4345 LEB128_SIZE /* method */ +
4346 LEB128_SIZE /* il offset */ +
4347 LEB128_SIZE /* native offset */
4351 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
4352 emit_value (logbuffer, sample_type);
4353 emit_uvalue (logbuffer, prof->startup_time + sample->elapsed * 10000);
4354 emit_ptr (logbuffer, (void *) sample->tid);
4355 emit_value (logbuffer, 1);
4357 // TODO: Actual native unwinding.
4358 for (int i = 0; i < 1; ++i) {
4359 emit_ptr (logbuffer, sample->ip);
4360 add_code_pointer ((uintptr_t) sample->ip);
4363 /* new in data version 6 */
4364 emit_uvalue (logbuffer, sample->count);
4366 for (int i = 0; i < sample->count; ++i) {
4367 emit_method (prof, logbuffer, sample->frames [i].method);
4368 emit_svalue (logbuffer, 0); /* il offset will always be 0 from now on */
4369 emit_svalue (logbuffer, sample->frames [i].offset);
4372 mono_thread_hazardous_try_free (sample, reuse_sample_hit);
4374 dump_unmanaged_coderefs (prof);
4376 if (logbuffer->next)
4377 safe_send_threadless (prof, logbuffer);
4384 dumper_thread (void *arg)
4386 MonoProfiler *prof = (MonoProfiler *)arg;
4388 mono_threads_attach_tools_thread ();
4389 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler dumper");
4391 while (InterlockedRead (&prof->run_dumper_thread)) {
4392 mono_os_sem_wait (&prof->dumper_queue_sem, MONO_SEM_FLAGS_NONE);
4393 handle_dumper_queue_entry (prof);
4396 /* Drain any remaining entries on shutdown. */
4397 while (handle_dumper_queue_entry (prof));
4399 safe_send_threadless (prof, ensure_logbuf (0));
4401 mono_thread_info_detach ();
4407 start_dumper_thread (MonoProfiler* prof)
4409 InterlockedWrite (&prof->run_dumper_thread, 1);
4411 return !pthread_create (&prof->dumper_thread, NULL, dumper_thread, prof);
4415 runtime_initialized (MonoProfiler *profiler)
4417 #ifndef DISABLE_HELPER_THREAD
4418 if (hs_mode_ondemand || need_helper_thread) {
4419 if (!start_helper_thread (profiler))
4420 profiler->command_port = 0;
4424 start_writer_thread (profiler);
4425 start_dumper_thread (profiler);
4427 InterlockedWrite (&runtime_inited, 1);
4428 #ifndef DISABLE_HELPER_THREAD
4429 counters_init (profiler);
4430 counters_sample (profiler, 0, FALSE);
4432 /* ensure the main thread data and startup are available soon */
4433 safe_send (profiler, ensure_logbuf (0));
4436 static MonoProfiler*
4437 create_profiler (const char *filename, GPtrArray *filters)
4441 int force_delete = 0;
4442 prof = (MonoProfiler *)calloc (1, sizeof (MonoProfiler));
4444 prof->command_port = command_port;
4445 if (filename && *filename == '-') {
4451 filename = "|mprof-report -";
4453 filename = "output.mlpd";
4454 nf = (char*)filename;
4456 nf = new_filename (filename);
4458 int s = strlen (nf) + 32;
4459 char *p = (char *)malloc (s);
4460 snprintf (p, s, "|mprof-report '--out=%s' -", nf);
4466 prof->file = popen (nf + 1, "w");
4467 prof->pipe_output = 1;
4468 } else if (*nf == '#') {
4469 int fd = strtol (nf + 1, NULL, 10);
4470 prof->file = fdopen (fd, "a");
4474 prof->file = fopen (nf, "wb");
4477 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
4480 #if defined (HAVE_SYS_ZLIB)
4482 prof->gzfile = gzdopen (fileno (prof->file), "wb");
4485 if (sample_type && !do_mono_sample)
4486 need_helper_thread = setup_perf_event ();
4488 /* FIXME: warn if different freq or sample type */
4492 if (do_mono_sample) {
4493 need_helper_thread = 1;
4495 if (do_counters && !need_helper_thread) {
4496 need_helper_thread = 1;
4500 * If you hit this assert while increasing MAX_FRAMES, you need to increase
4501 * SAMPLE_BLOCK_SIZE as well.
4503 g_assert (SAMPLE_SLOT_SIZE (MAX_FRAMES) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (SAMPLE_BLOCK_SIZE));
4505 // FIXME: We should free this stuff too.
4506 mono_lock_free_allocator_init_size_class (&prof->sample_size_class, SAMPLE_SLOT_SIZE (num_frames), SAMPLE_BLOCK_SIZE);
4507 mono_lock_free_allocator_init_allocator (&prof->sample_allocator, &prof->sample_size_class);
4509 mono_lock_free_queue_init (&prof->sample_reuse_queue);
4511 #ifdef DISABLE_HELPER_THREAD
4512 if (hs_mode_ondemand)
4513 fprintf (stderr, "Ondemand heapshot unavailable on this arch.\n");
4516 fprintf (stderr, "Coverage unavailable on this arch.\n");
4520 mono_lock_free_queue_init (&prof->writer_queue);
4521 mono_os_sem_init (&prof->writer_queue_sem, 0);
4523 mono_lock_free_queue_init (&prof->dumper_queue);
4524 mono_os_sem_init (&prof->dumper_queue_sem, 0);
4526 mono_os_mutex_init (&prof->method_table_mutex);
4527 prof->method_table = mono_conc_hashtable_new (NULL, NULL);
4530 coverage_init (prof);
4531 prof->coverage_filters = filters;
4533 prof->startup_time = current_time ();
4540 printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
4541 printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
4542 printf ("Options:\n");
4543 printf ("\thelp show this usage info\n");
4544 printf ("\t[no]alloc enable/disable recording allocation info\n");
4545 printf ("\t[no]calls enable/disable recording enter/leave method events\n");
4546 printf ("\theapshot[=MODE] record heap shot info (by default at each major collection)\n");
4547 printf ("\t MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
4548 printf ("\tcounters sample counters every 1s\n");
4549 printf ("\tsample[=TYPE] use statistical sampling mode (by default cycles/100)\n");
4550 printf ("\t TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
4551 printf ("\t TYPE can be followed by /FREQUENCY\n");
4552 printf ("\ttime=fast use a faster (but more inaccurate) timer\n");
4553 printf ("\tmaxframes=NUM collect up to NUM stack frames\n");
4554 printf ("\tcalldepth=NUM ignore method events for call chain depth bigger than NUM\n");
4555 printf ("\toutput=FILENAME write the data to file FILENAME (-FILENAME to overwrite)\n");
4556 printf ("\toutput=|PROGRAM write the data to the stdin of PROGRAM\n");
4557 printf ("\t %%t is subtituted with date and time, %%p with the pid\n");
4558 printf ("\treport create a report instead of writing the raw data to a file\n");
4559 printf ("\tzip compress the output data\n");
4560 printf ("\tport=PORTNUM use PORTNUM for the listening command server\n");
4561 printf ("\tcoverage enable collection of code coverage data\n");
4562 printf ("\tcovfilter=ASSEMBLY add an assembly to the code coverage filters\n");
4563 printf ("\t add a + to include the assembly or a - to exclude it\n");
4564 printf ("\t filter=-mscorlib\n");
4565 printf ("\tcovfilter-file=FILE use FILE to generate the list of assemblies to be filtered\n");
4571 match_option (const char* p, const char *opt, char **rval)
4573 int len = strlen (opt);
4574 if (strncmp (p, opt, len) == 0) {
4576 if (p [len] == '=' && p [len + 1]) {
4577 const char *opt = p + len + 1;
4578 const char *end = strchr (opt, ',');
4586 val = (char *)malloc (l + 1);
4587 memcpy (val, opt, l);
4592 if (p [len] == 0 || p [len] == ',') {
4594 return p + len + (p [len] == ',');
4612 static const SampleMode sample_modes [] = {
4613 {"cycles", SAMPLE_CYCLES},
4614 {"instr", SAMPLE_INSTRUCTIONS},
4615 {"cachemiss", SAMPLE_CACHE_MISSES},
4616 {"cacherefs", SAMPLE_CACHE_REFS},
4617 {"branches", SAMPLE_BRANCHES},
4618 {"branchmiss", SAMPLE_BRANCH_MISSES},
4623 set_sample_mode (char* val, int allow_empty)
4626 char *maybe_freq = NULL;
4628 const SampleMode *smode = sample_modes;
4629 #ifndef USE_PERF_EVENTS
4632 if (allow_empty && !val) {
4633 sample_type = SAMPLE_CYCLES;
4637 if (strcmp (val, "mono") == 0) {
4639 sample_type = SAMPLE_CYCLES;
4643 for (smode = sample_modes; smode->name; smode++) {
4644 int l = strlen (smode->name);
4645 if (strncmp (val, smode->name, l) == 0) {
4646 sample_type = smode->sample_mode;
4647 maybe_freq = val + l;
4653 if (*maybe_freq == '/') {
4654 count = strtoul (maybe_freq + 1, &end, 10);
4655 if (maybe_freq + 1 == end)
4657 sample_freq = count;
4658 } else if (*maybe_freq != 0) {
4667 set_hsmode (char* val, int allow_empty)
4671 if (allow_empty && !val)
4673 if (strcmp (val, "ondemand") == 0) {
4674 hs_mode_ondemand = 1;
4678 count = strtoul (val, &end, 10);
4681 if (strcmp (end, "ms") == 0)
4683 else if (strcmp (end, "gc") == 0)
4691 * declaration to silence the compiler: this is the entry point that
4692 * mono will load from the shared library and call.
4695 mono_profiler_startup (const char *desc);
4698 mono_profiler_startup_log (const char *desc);
4701 * this is the entry point that will be used when the profiler
4702 * is embedded inside the main executable.
4705 mono_profiler_startup_log (const char *desc)
4707 mono_profiler_startup (desc);
4711 mono_profiler_startup (const char *desc)
4714 GPtrArray *filters = NULL;
4715 char *filename = NULL;
4719 int calls_enabled = 0;
4720 int allocs_enabled = 0;
4721 int only_counters = 0;
4722 int only_coverage = 0;
4723 int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
4724 MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
4725 MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
4726 MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS|
4727 MONO_PROFILE_INS_COVERAGE|MONO_PROFILE_APPDOMAIN_EVENTS|MONO_PROFILE_CONTEXT_EVENTS|
4728 MONO_PROFILE_ASSEMBLY_EVENTS;
4730 max_allocated_sample_hits = mono_cpu_count () * 1000;
4732 mono_counters_register ("Sample hits", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &sample_hits);
4733 mono_counters_register ("Sample flushes", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &sample_flushes);
4734 mono_counters_register ("Sample events allocated", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &sample_allocations);
4735 mono_counters_register ("Log buffers allocated", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &buffer_allocations);
4736 mono_counters_register ("Thread start events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &thread_starts);
4737 mono_counters_register ("Thread stop events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &thread_ends);
4738 mono_counters_register ("Domain load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &domain_loads);
4739 mono_counters_register ("Domain unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &domain_unloads);
4740 mono_counters_register ("Context load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &context_loads);
4741 mono_counters_register ("Context unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &context_unloads);
4742 mono_counters_register ("Assembly load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &assembly_loads);
4743 mono_counters_register ("Assembly unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &assembly_unloads);
4744 mono_counters_register ("Image load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &image_loads);
4745 mono_counters_register ("Image unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &image_unloads);
4746 mono_counters_register ("Class load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &class_loads);
4747 mono_counters_register ("Class unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &class_unloads);
4750 if (strncmp (p, "log", 3))
4755 for (; *p; p = opt) {
4761 if ((opt = match_option (p, "help", NULL)) != p) {
4765 if ((opt = match_option (p, "calls", NULL)) != p) {
4769 if ((opt = match_option (p, "nocalls", NULL)) != p) {
4770 events &= ~MONO_PROFILE_ENTER_LEAVE;
4774 if ((opt = match_option (p, "alloc", NULL)) != p) {
4778 if ((opt = match_option (p, "noalloc", NULL)) != p) {
4779 events &= ~MONO_PROFILE_ALLOCATIONS;
4782 if ((opt = match_option (p, "time", &val)) != p) {
4783 if (strcmp (val, "fast") == 0)
4785 else if (strcmp (val, "null") == 0)
4792 if ((opt = match_option (p, "report", NULL)) != p) {
4796 if ((opt = match_option (p, "debug", NULL)) != p) {
4800 if ((opt = match_option (p, "sampling-real", NULL)) != p) {
4801 sampling_mode = MONO_PROFILER_STAT_MODE_REAL;
4804 if ((opt = match_option (p, "sampling-process", NULL)) != p) {
4805 sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
4808 if ((opt = match_option (p, "heapshot", &val)) != p) {
4809 events &= ~MONO_PROFILE_ALLOCATIONS;
4810 events &= ~MONO_PROFILE_ENTER_LEAVE;
4813 set_hsmode (val, 1);
4816 if ((opt = match_option (p, "sample", &val)) != p) {
4817 events &= ~MONO_PROFILE_ALLOCATIONS;
4818 events &= ~MONO_PROFILE_ENTER_LEAVE;
4820 set_sample_mode (val, 1);
4823 if ((opt = match_option (p, "hsmode", &val)) != p) {
4824 fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
4825 set_hsmode (val, 0);
4828 if ((opt = match_option (p, "zip", NULL)) != p) {
4832 if ((opt = match_option (p, "output", &val)) != p) {
4836 if ((opt = match_option (p, "port", &val)) != p) {
4838 command_port = strtoul (val, &end, 10);
4842 if ((opt = match_option (p, "maxframes", &val)) != p) {
4844 num_frames = strtoul (val, &end, 10);
4845 if (num_frames > MAX_FRAMES)
4846 num_frames = MAX_FRAMES;
4848 notraces = num_frames == 0;
4851 if ((opt = match_option (p, "maxsamples", &val)) != p) {
4853 max_allocated_sample_hits = strtoul (val, &end, 10);
4854 if (!max_allocated_sample_hits)
4855 max_allocated_sample_hits = G_MAXINT32;
4859 if ((opt = match_option (p, "calldepth", &val)) != p) {
4861 max_call_depth = strtoul (val, &end, 10);
4865 if ((opt = match_option (p, "counters", NULL)) != p) {
4869 if ((opt = match_option (p, "countersonly", NULL)) != p) {
4873 if ((opt = match_option (p, "coverage", NULL)) != p) {
4875 events |= MONO_PROFILE_ENTER_LEAVE;
4876 debug_coverage = (g_getenv ("MONO_PROFILER_DEBUG_COVERAGE") != NULL);
4879 if ((opt = match_option (p, "onlycoverage", NULL)) != p) {
4883 if ((opt = match_option (p, "covfilter-file", &val)) != p) {
4885 char *line, *content;
4887 if (filters == NULL)
4888 filters = g_ptr_array_new ();
4890 filter_file = fopen (val, "r");
4891 if (filter_file == NULL) {
4892 fprintf (stderr, "Unable to open %s\n", val);
4896 /* Don't need to free content as it is referred to by the lines stored in @filters */
4897 content = get_file_content (filter_file);
4898 if (content == NULL)
4899 fprintf (stderr, "WARNING: %s is greater than 128kb - ignoring\n", val);
4901 while ((line = get_next_line (content, &content)))
4902 g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
4904 fclose (filter_file);
4907 if ((opt = match_option (p, "covfilter", &val)) != p) {
4908 if (filters == NULL)
4909 filters = g_ptr_array_new ();
4911 g_ptr_array_add (filters, val);
4919 if (calls_enabled) {
4920 events |= MONO_PROFILE_ENTER_LEAVE;
4924 events |= MONO_PROFILE_ALLOCATIONS;
4928 events = MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_INS_COVERAGE;
4930 utils_init (fast_time);
4932 prof = create_profiler (filename, filters);
4938 mono_profiler_install (prof, log_shutdown);
4939 mono_profiler_install_gc (gc_event, gc_resize);
4940 mono_profiler_install_allocation (gc_alloc);
4941 mono_profiler_install_gc_moves (gc_moves);
4942 mono_profiler_install_gc_roots (gc_handle, gc_roots);
4943 mono_profiler_install_appdomain (NULL, domain_loaded, domain_unloaded, NULL);
4944 mono_profiler_install_appdomain_name (domain_name);
4945 mono_profiler_install_context (context_loaded, context_unloaded);
4946 mono_profiler_install_class (NULL, class_loaded, class_unloaded, NULL);
4947 mono_profiler_install_module (NULL, image_loaded, image_unloaded, NULL);
4948 mono_profiler_install_assembly (NULL, assembly_loaded, assembly_unloaded, NULL);
4949 mono_profiler_install_thread (thread_start, thread_end);
4950 mono_profiler_install_thread_name (thread_name);
4951 mono_profiler_install_enter_leave (method_enter, method_leave);
4952 mono_profiler_install_jit_end (method_jitted);
4953 mono_profiler_install_code_buffer_new (code_buffer_new);
4954 mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
4955 mono_profiler_install_monitor (monitor_event);
4956 mono_profiler_install_runtime_initialized (runtime_initialized);
4958 mono_profiler_install_coverage_filter (coverage_filter);
4960 if (do_mono_sample && sample_type == SAMPLE_CYCLES && !only_counters) {
4961 events |= MONO_PROFILE_STATISTICAL;
4962 mono_profiler_set_statistical_mode (sampling_mode, sample_freq);
4963 mono_profiler_install_statistical (mono_sample_hit);
4966 mono_profiler_set_events ((MonoProfileFlags)events);
4968 TLS_INIT (tlsbuffer);
4969 TLS_INIT (tlsmethodlist);