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 <mono/metadata/profiler.h>
16 #include <mono/metadata/threads.h>
17 #include <mono/metadata/mono-gc.h>
18 #include <mono/metadata/debug-helpers.h>
19 #include <mono/metadata/mono-perfcounters.h>
20 #include <mono/metadata/appdomain.h>
21 #include <mono/metadata/assembly.h>
22 #include <mono/metadata/tokentype.h>
23 #include <mono/metadata/tabledefs.h>
24 #include <mono/utils/atomic.h>
25 #include <mono/utils/mono-membar.h>
26 #include <mono/utils/mono-counters.h>
27 #include <mono/utils/mono-os-mutex.h>
28 #include <mono/utils/mono-conc-hashtable.h>
29 #include <mono/utils/lock-free-queue.h>
37 #ifdef HAVE_SCHED_GETAFFINITY
42 #if defined(HOST_WIN32) || defined(DISABLE_SOCKETS)
43 #define DISABLE_HELPER_THREAD 1
52 #ifdef HAVE_EXECINFO_H
59 #ifndef DISABLE_HELPER_THREAD
60 #include <sys/types.h>
61 #include <sys/socket.h>
62 #include <netinet/in.h>
63 #include <sys/select.h>
72 #ifdef HAVE_SYS_STAT_H
79 #if defined (HAVE_SYS_ZLIB)
83 #if defined(__linux__)
86 #include <sys/syscall.h>
88 #ifdef ENABLE_PERF_EVENTS
89 #include <linux/perf_event.h>
91 #define USE_PERF_EVENTS 1
93 static int read_perf_mmap (MonoProfiler* prof, int cpu);
98 #define BUFFER_SIZE (4096 * 16)
100 /* Worst-case size in bytes of a 64-bit value encoded with LEB128. */
101 #define LEB128_SIZE 10
102 /* Size in bytes of the event ID prefix. */
105 static int nocalls = 0;
106 static int notraces = 0;
107 static int use_zip = 0;
108 static int do_report = 0;
109 static int do_heap_shot = 0;
110 static int max_call_depth = 100;
111 static volatile int runtime_inited = 0;
112 static int need_helper_thread = 0;
113 static int command_port = 0;
114 static int heapshot_requested = 0;
115 static int sample_type = 0;
116 static int sample_freq = 0;
117 static int do_mono_sample = 0;
118 static int in_shutdown = 0;
119 static int do_debug = 0;
120 static int do_counters = 0;
121 static int do_coverage = 0;
122 static gboolean debug_coverage = FALSE;
123 static MonoProfileSamplingMode sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
125 typedef struct _LogBuffer LogBuffer;
131 * The file is composed by a header followed by 0 or more buffers.
132 * Each buffer contains events that happened on a thread: for a given thread
133 * buffers that appear later in the file are guaranteed to contain events
134 * that happened later in time. Buffers from separate threads could be interleaved,
136 * Buffers are not required to be aligned.
139 * [id: 4 bytes] constant value: LOG_HEADER_ID
140 * [major: 1 byte] [minor: 1 byte] major and minor version of the log profiler
141 * [format: 1 byte] version of the data format for the rest of the file
142 * [ptrsize: 1 byte] size in bytes of a pointer in the profiled program
143 * [startup time: 8 bytes] time in milliseconds since the unix epoch when the program started
144 * [timer overhead: 4 bytes] approximate overhead in nanoseconds of the timer
145 * [flags: 4 bytes] file format flags, should be 0 for now
146 * [pid: 4 bytes] pid of the profiled process
147 * [port: 2 bytes] tcp port for server if != 0
148 * [sysid: 2 bytes] operating system and architecture identifier
150 * The multiple byte integers are in little-endian format.
153 * [buffer header] [event]*
154 * Buffers have a fixed-size header followed by 0 or more bytes of event data.
155 * Timing information and other values in the event data are usually stored
156 * as uleb128 or sleb128 integers. To save space, as noted for each item below,
157 * some data is represented as a difference between the actual value and
158 * either the last value of the same type (like for timing information) or
159 * as the difference from a value stored in a buffer header.
161 * For timing information the data is stored as uleb128, since timing
162 * increases in a monotonic way in each thread: the value is the number of
163 * nanoseconds to add to the last seen timing data in a buffer. The first value
164 * in a buffer will be calculated from the time_base field in the buffer head.
166 * Object or heap sizes are stored as uleb128.
167 * Pointer differences are stored as sleb128, instead.
169 * If an unexpected value is found, the rest of the buffer should be ignored,
170 * as generally the later values need the former to be interpreted correctly.
172 * buffer header format:
173 * [bufid: 4 bytes] constant value: BUF_ID
174 * [len: 4 bytes] size of the data following the buffer header
175 * [time_base: 8 bytes] time base in nanoseconds since an unspecified epoch
176 * [ptr_base: 8 bytes] base value for pointers
177 * [obj_base: 8 bytes] base value for object addresses
178 * [thread id: 8 bytes] system-specific thread ID (pthread_t for example)
179 * [method_base: 8 bytes] base value for MonoMethod pointers
182 * [extended info: upper 4 bits] [type: lower 4 bits] [data]*
183 * The data that follows depends on type and the extended info.
184 * Type is one of the enum values in proflog.h: TYPE_ALLOC, TYPE_GC,
185 * TYPE_METADATA, TYPE_METHOD, TYPE_EXCEPTION, TYPE_MONITOR, TYPE_HEAP.
186 * The extended info bits are interpreted based on type, see
187 * each individual event description below.
188 * strings are represented as a 0-terminated utf8 sequence.
191 * [flags: uleb128] must be 0
192 * [num: uleb128] number of frames following
193 * [frame: sleb128]* num MonoMethod pointers as differences from ptr_base
197 * exinfo: flags: TYPE_ALLOC_BT
198 * [time diff: uleb128] nanoseconds since last timing
199 * [ptr: sleb128] class as a byte difference from ptr_base
200 * [obj: sleb128] object address as a byte difference from obj_base
201 * [size: uleb128] size of the object in the heap
202 * If the TYPE_ALLOC_BT flag is set, a backtrace follows.
206 * exinfo: one of TYPE_GC_EVENT, TYPE_GC_RESIZE, TYPE_GC_MOVE, TYPE_GC_HANDLE_CREATED[_BT],
207 * TYPE_GC_HANDLE_DESTROYED[_BT]
208 * [time diff: uleb128] nanoseconds since last timing
209 * if exinfo == TYPE_GC_RESIZE
210 * [heap_size: uleb128] new heap size
211 * if exinfo == TYPE_GC_EVENT
212 * [event type: uleb128] GC event (MONO_GC_EVENT_* from profiler.h)
213 * [generation: uleb128] GC generation event refers to
214 * if exinfo == TYPE_GC_MOVE
215 * [num_objects: uleb128] number of object moves that follow
216 * [objaddr: sleb128]+ num_objects object pointer differences from obj_base
217 * num is always an even number: the even items are the old
218 * addresses, the odd numbers are the respective new object addresses
219 * if exinfo == TYPE_GC_HANDLE_CREATED[_BT]
220 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
221 * upper bits reserved as flags
222 * [handle: uleb128] GC handle value
223 * [objaddr: sleb128] object pointer differences from obj_base
224 * If exinfo == TYPE_GC_HANDLE_CREATED_BT, a backtrace follows.
225 * if exinfo == TYPE_GC_HANDLE_DESTROYED[_BT]
226 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
227 * upper bits reserved as flags
228 * [handle: uleb128] GC handle value
229 * If exinfo == TYPE_GC_HANDLE_DESTROYED_BT, a backtrace follows.
231 * type metadata format:
232 * type: TYPE_METADATA
233 * exinfo: one of: TYPE_END_LOAD, TYPE_END_UNLOAD (optional for TYPE_THREAD and TYPE_DOMAIN)
234 * [time diff: uleb128] nanoseconds since last timing
235 * [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
236 * TYPE_THREAD, TYPE_CONTEXT
237 * [pointer: sleb128] pointer of the metadata type depending on mtype
238 * if mtype == TYPE_CLASS
239 * [image: sleb128] MonoImage* as a pointer difference from ptr_base
240 * [flags: uleb128] must be 0
241 * [name: string] full class name
242 * if mtype == TYPE_IMAGE
243 * [flags: uleb128] must be 0
244 * [name: string] image file name
245 * if mtype == TYPE_ASSEMBLY
246 * [flags: uleb128] must be 0
247 * [name: string] assembly name
248 * if mtype == TYPE_DOMAIN
249 * [flags: uleb128] must be 0
250 * if mtype == TYPE_DOMAIN && exinfo == 0
251 * [name: string] domain friendly name
252 * if mtype == TYPE_CONTEXT
253 * [flags: uleb128] must be 0
254 * [domain: sleb128] domain id as pointer
255 * if mtype == TYPE_THREAD && (format_version < 11 || (format_version > 10 && exinfo == 0))
256 * [flags: uleb128] must be 0
257 * [name: string] thread name
259 * type method format:
261 * exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
262 * [time diff: uleb128] nanoseconds since last timing
263 * [method: sleb128] MonoMethod* as a pointer difference from the last such
264 * pointer or the buffer method_base
265 * if exinfo == TYPE_JIT
266 * [code address: sleb128] pointer to the native code as a diff from ptr_base
267 * [code size: uleb128] size of the generated code
268 * [name: string] full method name
270 * type runtime format:
272 * exinfo: one of: TYPE_JITHELPER
273 * [time diff: uleb128] nanoseconds since last timing
274 * if exinfo == TYPE_JITHELPER
275 * [type: uleb128] MonoProfilerCodeBufferType enum value
276 * [buffer address: sleb128] pointer to the native code as a diff from ptr_base
277 * [buffer size: uleb128] size of the generated code
278 * if type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE
279 * [name: string] buffer description name
281 * type monitor format:
283 * exinfo: TYPE_MONITOR_BT flag and one of: MONO_PROFILER_MONITOR_(CONTENTION|FAIL|DONE)
284 * [time diff: uleb128] nanoseconds since last timing
285 * [object: sleb128] the lock object as a difference from obj_base
286 * if exinfo.low3bits == MONO_PROFILER_MONITOR_CONTENTION
287 * If the TYPE_MONITOR_BT flag is set, a backtrace follows.
291 * exinfo: one of TYPE_HEAP_START, TYPE_HEAP_END, TYPE_HEAP_OBJECT, TYPE_HEAP_ROOT
292 * if exinfo == TYPE_HEAP_START
293 * [time diff: uleb128] nanoseconds since last timing
294 * if exinfo == TYPE_HEAP_END
295 * [time diff: uleb128] nanoseconds since last timing
296 * if exinfo == TYPE_HEAP_OBJECT
297 * [object: sleb128] the object as a difference from obj_base
298 * [class: sleb128] the object MonoClass* as a difference from ptr_base
299 * [size: uleb128] size of the object on the heap
300 * [num_refs: uleb128] number of object references
301 * if (format version > 1) each referenced objref is preceded by a
302 * uleb128 encoded offset: the first offset is from the object address
303 * and each next offset is relative to the previous one
304 * [objrefs: sleb128]+ object referenced as a difference from obj_base
305 * The same object can appear multiple times, but only the first time
306 * with size != 0: in the other cases this data will only be used to
307 * provide additional referenced objects.
308 * if exinfo == TYPE_HEAP_ROOT
309 * [num_roots: uleb128] number of root references
310 * [num_gc: uleb128] number of major gcs
311 * [object: sleb128] the object as a difference from obj_base
312 * [root_type: uleb128] the root_type: MonoProfileGCRootType (profiler.h)
313 * [extra_info: uleb128] the extra_info value
314 * object, root_type and extra_info are repeated num_roots times
318 * exinfo: one of TYPE_SAMPLE_HIT, TYPE_SAMPLE_USYM, TYPE_SAMPLE_UBIN, TYPE_SAMPLE_COUNTERS_DESC, TYPE_SAMPLE_COUNTERS
319 * if exinfo == TYPE_SAMPLE_HIT
320 * [sample_type: uleb128] type of sample (SAMPLE_*)
321 * [timestamp: uleb128] nanoseconds since startup (note: different from other timestamps!)
322 * if (format_version > 10)
323 * [thread: sleb128] thread id as difference from ptr_base
324 * [count: uleb128] number of following instruction addresses
325 * [ip: sleb128]* instruction pointer as difference from ptr_base
326 * if (format_version > 5)
327 * [mbt_count: uleb128] number of managed backtrace info triplets (method + IL offset + native offset)
328 * [method: sleb128]* MonoMethod* as a pointer difference from the last such
329 * pointer or the buffer method_base (the first such method can be also indentified by ip, but this is not neccessarily true)
330 * [il_offset: sleb128]* IL offset inside method where the hit occurred
331 * [native_offset: sleb128]* native offset inside method where the hit occurred
332 * if exinfo == TYPE_SAMPLE_USYM
333 * [address: sleb128] symbol address as a difference from ptr_base
334 * [size: uleb128] symbol size (may be 0 if unknown)
335 * [name: string] symbol name
336 * if exinfo == TYPE_SAMPLE_UBIN
337 * [time diff: uleb128] nanoseconds since last timing
338 * [address: sleb128] address where binary has been loaded
339 * [offset: uleb128] file offset of mapping (the same file can be mapped multiple times)
340 * [size: uleb128] memory size
341 * [name: string] binary name
342 * if exinfo == TYPE_SAMPLE_COUNTERS_DESC
343 * [len: uleb128] number of counters
345 * [section: uleb128] section of counter
346 * if section == MONO_COUNTER_PERFCOUNTERS:
347 * [section_name: string] section name of counter
348 * [name: string] name of counter
349 * [type: uleb128] type of counter
350 * [unit: uleb128] unit of counter
351 * [variance: uleb128] variance of counter
352 * [index: uleb128] unique index of counter
353 * if exinfo == TYPE_SAMPLE_COUNTERS
354 * [timestamp: uleb128] sampling timestamp
356 * [index: uleb128] unique index of counter
359 * [type: uleb128] type of counter value
362 * [0: uleb128] 0 -> value is null
364 * [1: uleb128] 1 -> value is not null
365 * [value: string] counter value
367 * [value: uleb128/sleb128/double] counter value, can be sleb128, uleb128 or double (determined by using type)
369 * type coverage format
370 * type: TYPE_COVERAGE
371 * exinfo: one of TYPE_COVERAGE_METHOD, TYPE_COVERAGE_STATEMENT, TYPE_COVERAGE_ASSEMBLY, TYPE_COVERAGE_CLASS
372 * if exinfo == TYPE_COVERAGE_METHOD
373 * [assembly: string] name of assembly
374 * [class: string] name of the class
375 * [name: string] name of the method
376 * [signature: string] the signature of the method
377 * [filename: string] the file path of the file that contains this method
378 * [token: uleb128] the method token
379 * [method_id: uleb128] an ID for this data to associate with the buffers of TYPE_COVERAGE_STATEMENTS
380 * [len: uleb128] the number of TYPE_COVERAGE_BUFFERS associated with this method
381 * if exinfo == TYPE_COVERAGE_STATEMENTS
382 * [method_id: uleb128] an the TYPE_COVERAGE_METHOD buffer to associate this with
383 * [offset: uleb128] the il offset relative to the previous offset
384 * [counter: uleb128] the counter for this instruction
385 * [line: uleb128] the line of filename containing this instruction
386 * [column: uleb128] the column containing this instruction
387 * if exinfo == TYPE_COVERAGE_ASSEMBLY
388 * [name: string] assembly name
389 * [guid: string] assembly GUID
390 * [filename: string] assembly filename
391 * [number_of_methods: uleb128] the number of methods in this assembly
392 * [fully_covered: uleb128] the number of fully covered methods
393 * [partially_covered: uleb128] the number of partially covered methods
394 * currently partially_covered will always be 0, and fully_covered is the
395 * number of methods that are fully and partially covered.
396 * if exinfo == TYPE_COVERAGE_CLASS
397 * [name: string] assembly name
398 * [class: string] class name
399 * [number_of_methods: uleb128] the number of methods in this class
400 * [fully_covered: uleb128] the number of fully covered methods
401 * [partially_covered: uleb128] the number of partially covered methods
402 * currently partially_covered will always be 0, and fully_covered is the
403 * number of methods that are fully and partially covered.
407 * Format oddities that we ought to fix:
409 * - Methods written in emit_bt () should be based on the buffer's base
410 * method instead of the base pointer.
411 * - The TYPE_SAMPLE_HIT event contains (currently) pointless data like
412 * always-one unmanaged frame count and always-zero IL offsets.
414 * These are mostly small things and are not worth a format change by
415 * themselves. They should be done when some other major change has to
416 * be done to the format.
419 // Pending data to be written to the log, for a single thread.
420 // Threads periodically flush their own LogBuffers by calling safe_send
422 // Next (older) LogBuffer in processing queue
428 uintptr_t method_base;
429 uintptr_t last_method;
435 // Bytes allocated for this LogBuffer
438 // Start of currently unused space in buffer
439 unsigned char* cursor;
441 // Pointer to start-of-structure-plus-size (for convenience)
442 unsigned char* buf_end;
444 // Start of data in buffer. Contents follow "buffer format" described above.
445 unsigned char buf [1];
449 ign_res (int G_GNUC_UNUSED unused, ...)
453 #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++;}
454 #define EXIT_LOG(lb) (lb)->locked--;
456 // Shared queue of sample snapshots taken at signal time.
457 // The queue is written into by signal handlers for all threads;
458 // the helper thread later unqueues and writes into its own LogBuffer.
459 typedef struct _StatBuffer StatBuffer;
461 // Next (older) StatBuffer in processing queue
464 // Bytes allocated for this StatBuffer
467 // Start of currently unused space in buffer
470 // Pointer to start-of-structure-plus-size (for convenience)
473 // Start of data in buffer.
474 // Data consists of a series of sample packets consisting of:
475 // 1 ptrword: Metadata
476 // Low 8 bits: COUNT, the count of native stack frames in this sample (currently always 1)
477 // Next 8 bits: MBT_COUNT, the count of managed stacks in this sample
478 // Next 8 bits: TYPE. See "sampling sources" enum in proflog.h. Usually SAMPLE_CYCLES (1)
479 // 1 ptrword: Thread ID
480 // 1 ptrword: Timestamp
481 // COUNT ptrwords: Native stack frames
482 // Each word is an IP (first is IP where the signal did the interruption)
483 // MBT_COUNT * 4 ptrwords: Managed stack frames (AsyncFrameInfo, repacked)
484 // Word 1: MonoMethod ptr
485 // Word 2: MonoDomain ptr
486 // Word 3: Base address of method
487 // Word 4: Offset within method
491 typedef struct _BinaryObject BinaryObject;
493 struct _BinaryObject {
499 struct _MonoProfiler {
500 StatBuffer *stat_buffers;
502 #if defined (HAVE_SYS_ZLIB)
505 uint64_t startup_time;
507 int last_gc_gen_started;
512 pthread_t helper_thread;
513 pthread_t writer_thread;
515 volatile gint32 run_writer_thread;
516 MonoLockFreeQueue writer_queue;
517 MonoConcurrentHashTable *method_table;
518 mono_mutex_t method_table_mutex;
519 BinaryObject *binary_objects;
520 GPtrArray *coverage_filters;
521 GPtrArray *sorted_sample_events;
524 typedef struct _WriterQueueEntry WriterQueueEntry;
525 struct _WriterQueueEntry {
526 MonoLockFreeQueueNode node;
531 typedef struct _MethodInfo MethodInfo;
543 #define TLS_SET(x,y) (TlsSetValue (x, y))
544 #define TLS_GET(t,x) ((t *) TlsGetValue (x))
545 #define TLS_INIT(x) (x = TlsAlloc ())
546 static int tlsbuffer;
547 static int tlsmethodlist;
549 #define TLS_SET(x,y) (x = y)
550 #define TLS_GET(t,x) (x)
552 static __thread LogBuffer* tlsbuffer = NULL;
553 static __thread GPtrArray* tlsmethodlist = NULL;
555 #define TLS_SET(x,y) (pthread_setspecific (x, y))
556 #define TLS_GET(t,x) ((t *) pthread_getspecific (x))
557 #define TLS_INIT(x) (pthread_key_create (&x, NULL))
558 static pthread_key_t tlsbuffer;
559 static pthread_key_t tlsmethodlist;
562 static void safe_send (MonoProfiler *profiler, LogBuffer *logbuffer);
565 pstrdup (const char *s)
567 int len = strlen (s) + 1;
568 char *p = (char *)malloc (len);
574 create_stat_buffer (void)
576 StatBuffer* buf = (StatBuffer *)alloc_buffer (BUFFER_SIZE);
577 buf->size = BUFFER_SIZE;
578 buf->buf_end = (uintptr_t*)((unsigned char*)buf + buf->size);
579 buf->cursor = buf->buf;
586 LogBuffer* buf = (LogBuffer *)alloc_buffer (BUFFER_SIZE);
587 buf->size = BUFFER_SIZE;
588 buf->time_base = current_time ();
589 buf->last_time = buf->time_base;
590 buf->buf_end = (unsigned char*)buf + buf->size;
591 buf->cursor = buf->buf;
598 if (!TLS_GET (LogBuffer, tlsbuffer)) {
599 LogBuffer *logbuffer = create_buffer ();
600 TLS_SET (tlsbuffer, logbuffer);
601 logbuffer->thread_id = thread_id ();
603 if (!TLS_GET (GPtrArray, tlsmethodlist)) {
604 GPtrArray *methodlist = g_ptr_array_new ();
605 TLS_SET (tlsmethodlist, methodlist);
608 //printf ("thread %p at time %llu\n", (void*)logbuffer->thread_id, logbuffer->time_base);
612 ensure_logbuf_inner (LogBuffer *old, int bytes)
614 if (old && old->cursor + bytes + 100 < old->buf_end)
617 LogBuffer *new_ = (LogBuffer *)create_buffer ();
618 new_->thread_id = thread_id ();
622 new_->call_depth = old->call_depth;
628 ensure_logbuf (int bytes)
630 LogBuffer *old = TLS_GET (LogBuffer, tlsbuffer);
631 LogBuffer *new_ = ensure_logbuf_inner (old, bytes);
634 return old; // Still enough space.
636 TLS_SET (tlsbuffer, new_);
643 emit_byte (LogBuffer *logbuffer, int value)
645 logbuffer->cursor [0] = value;
647 assert (logbuffer->cursor <= logbuffer->buf_end);
651 emit_value (LogBuffer *logbuffer, int value)
653 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
654 assert (logbuffer->cursor <= logbuffer->buf_end);
658 emit_time (LogBuffer *logbuffer, uint64_t value)
660 uint64_t tdiff = value - logbuffer->last_time;
661 //if (value < logbuffer->last_time)
662 // printf ("time went backwards\n");
663 //if (tdiff > 1000000)
664 // printf ("large time offset: %llu\n", tdiff);
665 encode_uleb128 (tdiff, logbuffer->cursor, &logbuffer->cursor);
666 /*if (tdiff != decode_uleb128 (p, &p))
667 printf ("incorrect encoding: %llu\n", tdiff);*/
668 logbuffer->last_time = value;
669 assert (logbuffer->cursor <= logbuffer->buf_end);
673 emit_svalue (LogBuffer *logbuffer, int64_t value)
675 encode_sleb128 (value, logbuffer->cursor, &logbuffer->cursor);
676 assert (logbuffer->cursor <= logbuffer->buf_end);
680 emit_uvalue (LogBuffer *logbuffer, uint64_t value)
682 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
683 assert (logbuffer->cursor <= logbuffer->buf_end);
687 emit_ptr (LogBuffer *logbuffer, void *ptr)
689 if (!logbuffer->ptr_base)
690 logbuffer->ptr_base = (uintptr_t)ptr;
691 emit_svalue (logbuffer, (intptr_t)ptr - logbuffer->ptr_base);
692 assert (logbuffer->cursor <= logbuffer->buf_end);
696 emit_method_inner (LogBuffer *logbuffer, void *method)
698 if (!logbuffer->method_base) {
699 logbuffer->method_base = (intptr_t)method;
700 logbuffer->last_method = (intptr_t)method;
702 encode_sleb128 ((intptr_t)((char*)method - (char*)logbuffer->last_method), logbuffer->cursor, &logbuffer->cursor);
703 logbuffer->last_method = (intptr_t)method;
704 assert (logbuffer->cursor <= logbuffer->buf_end);
714 find_method (MonoDomain *domain, void *user_data)
716 MethodSearch *search = user_data;
721 MonoJitInfo *ji = mono_get_jit_info_from_method (domain, search->method);
723 // It could be AOT'd, so we need to get it from the AOT runtime's cache.
725 void *ip = mono_aot_get_method (domain, search->method);
727 // Avoid a slow path in mono_jit_info_table_find ().
729 ji = mono_jit_info_table_find (domain, ip);
738 register_method_local (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji)
740 if (!mono_conc_hashtable_lookup (prof->method_table, method)) {
742 * FIXME: In some cases, we crash while looking up JIT info for AOT'd methods.
743 * This usually happens for static constructors. This code is disabled for now
744 * as we don't need this info for anything critical.
746 * https://bugzilla.xamarin.com/show_bug.cgi?id=35171
750 MethodSearch search = { method, NULL };
752 mono_domain_foreach (find_method, &search);
759 * FIXME: We can't always find JIT info for a generic shared method, especially
760 * if we obtained the MonoMethod during an async stack walk. For now, we deal
761 * with this by giving the generic shared method name and dummy code start/size
762 * information (i.e. zeroes).
766 MethodInfo *info = (MethodInfo *)malloc (sizeof (MethodInfo));
768 info->method = method;
770 info->time = current_time ();
772 g_ptr_array_add (TLS_GET (GPtrArray, tlsmethodlist), info);
777 emit_method (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
779 register_method_local (prof, method, NULL);
780 emit_method_inner (logbuffer, method);
784 emit_method_as_ptr (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
786 register_method_local (prof, method, NULL);
787 emit_ptr (logbuffer, method);
791 emit_obj (LogBuffer *logbuffer, void *ptr)
793 if (!logbuffer->obj_base)
794 logbuffer->obj_base = (uintptr_t)ptr >> 3;
795 emit_svalue (logbuffer, ((uintptr_t)ptr >> 3) - logbuffer->obj_base);
796 assert (logbuffer->cursor <= logbuffer->buf_end);
800 emit_string (LogBuffer *logbuffer, const char *str, size_t size)
804 for (; i < size; i++) {
807 emit_byte (logbuffer, str [i]);
810 emit_byte (logbuffer, '\0');
814 emit_double (LogBuffer *logbuffer, double value)
817 unsigned char buffer[8];
818 memcpy (buffer, &value, 8);
819 #if G_BYTE_ORDER == G_BIG_ENDIAN
820 for (i = 7; i >= 0; i--)
822 for (i = 0; i < 8; i++)
824 emit_byte (logbuffer, buffer[i]);
828 write_int16 (char *buf, int32_t value)
831 for (i = 0; i < 2; ++i) {
839 write_int32 (char *buf, int32_t value)
842 for (i = 0; i < 4; ++i) {
850 write_int64 (char *buf, int64_t value)
853 for (i = 0; i < 8; ++i) {
861 dump_header (MonoProfiler *profiler)
865 p = write_int32 (p, LOG_HEADER_ID);
866 *p++ = LOG_VERSION_MAJOR;
867 *p++ = LOG_VERSION_MINOR;
868 *p++ = LOG_DATA_VERSION;
869 *p++ = sizeof (void*);
870 p = write_int64 (p, ((uint64_t)time (NULL)) * 1000); /* startup time */
871 p = write_int32 (p, get_timer_overhead ()); /* timer overhead */
872 p = write_int32 (p, 0); /* flags */
873 p = write_int32 (p, process_id ()); /* pid */
874 p = write_int16 (p, profiler->command_port); /* port */
875 p = write_int16 (p, 0); /* opsystem */
876 #if defined (HAVE_SYS_ZLIB)
877 if (profiler->gzfile) {
878 gzwrite (profiler->gzfile, hbuf, p - hbuf);
880 fwrite (hbuf, p - hbuf, 1, profiler->file);
883 fwrite (hbuf, p - hbuf, 1, profiler->file);
884 fflush (profiler->file);
889 send_buffer (MonoProfiler *prof, GPtrArray *methods, LogBuffer *buffer)
891 WriterQueueEntry *entry = (WriterQueueEntry *)calloc (1, sizeof (WriterQueueEntry));
892 mono_lock_free_queue_node_init (&entry->node, FALSE);
893 entry->methods = methods;
894 entry->buffer = buffer;
895 mono_lock_free_queue_enqueue (&prof->writer_queue, &entry->node);
899 dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
904 dump_buffer (profiler, buf->next);
905 p = write_int32 (p, BUF_ID);
906 p = write_int32 (p, buf->cursor - buf->buf);
907 p = write_int64 (p, buf->time_base);
908 p = write_int64 (p, buf->ptr_base);
909 p = write_int64 (p, buf->obj_base);
910 p = write_int64 (p, buf->thread_id);
911 p = write_int64 (p, buf->method_base);
912 #if defined (HAVE_SYS_ZLIB)
913 if (profiler->gzfile) {
914 gzwrite (profiler->gzfile, hbuf, p - hbuf);
915 gzwrite (profiler->gzfile, buf->buf, buf->cursor - buf->buf);
918 fwrite (hbuf, p - hbuf, 1, profiler->file);
919 fwrite (buf->buf, buf->cursor - buf->buf, 1, profiler->file);
920 fflush (profiler->file);
921 #if defined (HAVE_SYS_ZLIB)
924 free_buffer (buf, buf->size);
928 process_requests (MonoProfiler *profiler)
930 if (heapshot_requested)
931 mono_gc_collect (mono_gc_max_generation ());
934 static void counters_init (MonoProfiler *profiler);
935 static void counters_sample (MonoProfiler *profiler, uint64_t timestamp);
938 * Can be called only at safe callback locations.
941 safe_send (MonoProfiler *profiler, LogBuffer *logbuffer)
943 /* We need the runtime initialized so that we have threads and hazard
944 * pointers available. Otherwise, the lock free queue will not work and
945 * there won't be a thread to process the data.
947 * While the runtime isn't initialized, we just accumulate data in the
948 * thread local buffer list.
950 if (!InterlockedRead (&runtime_inited))
953 int cd = logbuffer->call_depth;
955 send_buffer (profiler, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
957 TLS_SET (tlsbuffer, NULL);
958 TLS_SET (tlsmethodlist, NULL);
962 TLS_GET (LogBuffer, tlsbuffer)->call_depth = cd;
966 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
969 uintptr_t last_offset = 0;
970 //const char *name = mono_class_get_name (klass);
971 LogBuffer *logbuffer = ensure_logbuf (
972 EVENT_SIZE /* event */ +
973 LEB128_SIZE /* obj */ +
974 LEB128_SIZE /* klass */ +
975 LEB128_SIZE /* size */ +
976 LEB128_SIZE /* num */ +
978 LEB128_SIZE /* offset */ +
979 LEB128_SIZE /* ref */
982 emit_byte (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
983 emit_obj (logbuffer, obj);
984 emit_ptr (logbuffer, klass);
985 /* account for object alignment in the heap */
988 emit_value (logbuffer, size);
989 emit_value (logbuffer, num);
990 for (i = 0; i < num; ++i) {
991 emit_value (logbuffer, offsets [i] - last_offset);
992 last_offset = offsets [i];
993 emit_obj (logbuffer, refs [i]);
996 // printf ("obj: %p, klass: %s, refs: %d, size: %d\n", obj, name, (int)num, (int)size);
1000 static unsigned int hs_mode_ms = 0;
1001 static unsigned int hs_mode_gc = 0;
1002 static unsigned int hs_mode_ondemand = 0;
1003 static unsigned int gc_count = 0;
1004 static uint64_t last_hs_time = 0;
1007 heap_walk (MonoProfiler *profiler)
1011 LogBuffer *logbuffer;
1014 logbuffer = ensure_logbuf (
1015 EVENT_SIZE /* event */ +
1016 LEB128_SIZE /* time */
1018 now = current_time ();
1019 if (hs_mode_ms && (now - last_hs_time)/1000000 >= hs_mode_ms)
1021 else if (hs_mode_gc && (gc_count % hs_mode_gc) == 0)
1023 else if (hs_mode_ondemand)
1024 do_walk = heapshot_requested;
1025 else if (!hs_mode_ms && !hs_mode_gc && profiler->last_gc_gen_started == mono_gc_max_generation ())
1030 heapshot_requested = 0;
1031 emit_byte (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
1032 emit_time (logbuffer, now);
1033 mono_gc_walk_heap (0, gc_reference, NULL);
1034 logbuffer = ensure_logbuf (
1035 EVENT_SIZE /* event */ +
1036 LEB128_SIZE /* time */
1038 now = current_time ();
1039 emit_byte (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
1040 emit_time (logbuffer, now);
1045 gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation) {
1047 LogBuffer *logbuffer = ensure_logbuf (
1048 EVENT_SIZE /* event */ +
1049 LEB128_SIZE /* time */ +
1050 LEB128_SIZE /* gc event */ +
1051 LEB128_SIZE /* generation */
1053 now = current_time ();
1054 ENTER_LOG (logbuffer, "gcevent");
1055 emit_byte (logbuffer, TYPE_GC_EVENT | TYPE_GC);
1056 emit_time (logbuffer, now);
1057 emit_value (logbuffer, ev);
1058 emit_value (logbuffer, generation);
1059 /* to deal with nested gen1 after gen0 started */
1060 if (ev == MONO_GC_EVENT_START) {
1061 profiler->last_gc_gen_started = generation;
1062 if (generation == mono_gc_max_generation ())
1065 if (ev == MONO_GC_EVENT_PRE_START_WORLD)
1066 heap_walk (profiler);
1067 EXIT_LOG (logbuffer);
1068 if (ev == MONO_GC_EVENT_POST_START_WORLD)
1069 safe_send (profiler, logbuffer);
1070 //printf ("gc event %d for generation %d\n", ev, generation);
1074 gc_resize (MonoProfiler *profiler, int64_t new_size) {
1076 LogBuffer *logbuffer = ensure_logbuf (
1077 EVENT_SIZE /* event */ +
1078 LEB128_SIZE /* time */ +
1079 LEB128_SIZE /* new size */
1081 now = current_time ();
1082 ENTER_LOG (logbuffer, "gcresize");
1083 emit_byte (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
1084 emit_time (logbuffer, now);
1085 emit_value (logbuffer, new_size);
1086 //printf ("gc resized to %lld\n", new_size);
1087 EXIT_LOG (logbuffer);
1090 #define MAX_FRAMES 32
1093 MonoMethod* methods [MAX_FRAMES];
1094 int32_t il_offsets [MAX_FRAMES];
1095 int32_t native_offsets [MAX_FRAMES];
1097 static int num_frames = MAX_FRAMES;
1100 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
1102 FrameData *frame = (FrameData *)data;
1103 if (method && frame->count < num_frames) {
1104 frame->il_offsets [frame->count] = il_offset;
1105 frame->native_offsets [frame->count] = native_offset;
1106 frame->methods [frame->count++] = method;
1107 //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
1109 return frame->count == num_frames;
1113 * a note about stack walks: they can cause more profiler events to fire,
1114 * so we need to make sure they don't happen after we started emitting an
1115 * event, hence the collect_bt/emit_bt split.
1118 collect_bt (FrameData *data)
1121 mono_stack_walk_no_il (walk_stack, data);
1125 emit_bt (MonoProfiler *prof, LogBuffer *logbuffer, FrameData *data)
1127 /* FIXME: this is actually tons of data and we should
1128 * just output it the first time and use an id the next
1130 if (data->count > num_frames)
1131 printf ("bad num frames: %d\n", data->count);
1132 emit_value (logbuffer, 0); /* flags */
1133 emit_value (logbuffer, data->count);
1134 //if (*p != data.count) {
1135 // 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);}
1136 while (data->count) {
1137 emit_method_as_ptr (prof, logbuffer, data->methods [--data->count]);
1142 gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1146 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces)? TYPE_ALLOC_BT: 0;
1148 LogBuffer *logbuffer;
1149 len = mono_object_get_size (obj);
1150 /* account for object alignment in the heap */
1155 logbuffer = ensure_logbuf (
1156 EVENT_SIZE /* event */ +
1157 LEB128_SIZE /* time */ +
1158 LEB128_SIZE /* klass */ +
1159 LEB128_SIZE /* obj */ +
1160 LEB128_SIZE /* size */ +
1162 LEB128_SIZE /* flags */ +
1163 LEB128_SIZE /* count */ +
1165 LEB128_SIZE /* method */
1169 now = current_time ();
1170 ENTER_LOG (logbuffer, "gcalloc");
1171 emit_byte (logbuffer, do_bt | TYPE_ALLOC);
1172 emit_time (logbuffer, now);
1173 emit_ptr (logbuffer, klass);
1174 emit_obj (logbuffer, obj);
1175 emit_value (logbuffer, len);
1177 emit_bt (prof, logbuffer, &data);
1178 EXIT_LOG (logbuffer);
1179 if (logbuffer->next)
1180 safe_send (prof, logbuffer);
1181 process_requests (prof);
1182 //printf ("gc alloc %s at %p\n", mono_class_get_name (klass), obj);
1186 gc_moves (MonoProfiler *prof, void **objects, int num)
1190 LogBuffer *logbuffer = ensure_logbuf (
1191 EVENT_SIZE /* event */ +
1192 LEB128_SIZE /* time */ +
1193 LEB128_SIZE /* num */ +
1195 LEB128_SIZE /* object */
1198 now = current_time ();
1199 ENTER_LOG (logbuffer, "gcmove");
1200 emit_byte (logbuffer, TYPE_GC_MOVE | TYPE_GC);
1201 emit_time (logbuffer, now);
1202 emit_value (logbuffer, num);
1203 for (i = 0; i < num; ++i)
1204 emit_obj (logbuffer, objects [i]);
1205 //printf ("gc moved %d objects\n", num/2);
1206 EXIT_LOG (logbuffer);
1210 gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
1213 LogBuffer *logbuffer = ensure_logbuf (
1214 EVENT_SIZE /* event */ +
1215 LEB128_SIZE /* num */ +
1216 LEB128_SIZE /* collections */ +
1218 LEB128_SIZE /* object */ +
1219 LEB128_SIZE /* root type */ +
1220 LEB128_SIZE /* extra info */
1223 ENTER_LOG (logbuffer, "gcroots");
1224 emit_byte (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
1225 emit_value (logbuffer, num);
1226 emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
1227 for (i = 0; i < num; ++i) {
1228 emit_obj (logbuffer, objects [i]);
1229 emit_value (logbuffer, root_types [i]);
1230 emit_value (logbuffer, extra_info [i]);
1232 EXIT_LOG (logbuffer);
1236 gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
1238 int do_bt = nocalls && InterlockedRead (&runtime_inited) && !notraces;
1245 LogBuffer *logbuffer = ensure_logbuf (
1246 EVENT_SIZE /* event */ +
1247 LEB128_SIZE /* time */ +
1248 LEB128_SIZE /* type */ +
1249 LEB128_SIZE /* handle */ +
1250 (op == MONO_PROFILER_GC_HANDLE_CREATED ? (
1251 LEB128_SIZE /* obj */
1254 LEB128_SIZE /* flags */ +
1255 LEB128_SIZE /* count */ +
1257 LEB128_SIZE /* method */
1262 now = current_time ();
1263 ENTER_LOG (logbuffer, "gchandle");
1265 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1266 emit_byte (logbuffer, (do_bt ? TYPE_GC_HANDLE_CREATED_BT : TYPE_GC_HANDLE_CREATED) | TYPE_GC);
1267 else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
1268 emit_byte (logbuffer, (do_bt ? TYPE_GC_HANDLE_DESTROYED_BT : TYPE_GC_HANDLE_DESTROYED) | TYPE_GC);
1270 g_assert_not_reached ();
1272 emit_time (logbuffer, now);
1273 emit_value (logbuffer, type);
1274 emit_value (logbuffer, handle);
1276 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1277 emit_obj (logbuffer, obj);
1280 emit_bt (prof, logbuffer, &data);
1282 EXIT_LOG (logbuffer);
1283 process_requests (prof);
1287 push_nesting (char *p, MonoClass *klass)
1292 nesting = mono_class_get_nesting_type (klass);
1294 p = push_nesting (p, nesting);
1298 name = mono_class_get_name (klass);
1299 nspace = mono_class_get_namespace (klass);
1302 p += strlen (nspace);
1312 type_name (MonoClass *klass)
1316 push_nesting (buf, klass);
1317 p = (char *)malloc (strlen (buf) + 1);
1323 image_loaded (MonoProfiler *prof, MonoImage *image, int result)
1328 LogBuffer *logbuffer;
1329 if (result != MONO_PROFILE_OK)
1331 name = mono_image_get_filename (image);
1332 nlen = strlen (name) + 1;
1333 logbuffer = ensure_logbuf (
1334 EVENT_SIZE /* event */ +
1335 LEB128_SIZE /* time */ +
1336 EVENT_SIZE /* type */ +
1337 LEB128_SIZE /* image */ +
1338 LEB128_SIZE /* flags */ +
1341 now = current_time ();
1342 ENTER_LOG (logbuffer, "image");
1343 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1344 emit_time (logbuffer, now);
1345 emit_byte (logbuffer, TYPE_IMAGE);
1346 emit_ptr (logbuffer, image);
1347 emit_value (logbuffer, 0); /* flags */
1348 memcpy (logbuffer->cursor, name, nlen);
1349 logbuffer->cursor += nlen;
1350 //printf ("loaded image %p (%s)\n", image, name);
1351 EXIT_LOG (logbuffer);
1352 if (logbuffer->next)
1353 safe_send (prof, logbuffer);
1354 process_requests (prof);
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);
1389 assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly, int result)
1391 if (result != MONO_PROFILE_OK)
1394 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1395 int nlen = strlen (name) + 1;
1396 LogBuffer *logbuffer = ensure_logbuf (
1397 EVENT_SIZE /* event */ +
1398 LEB128_SIZE /* time */ +
1399 EVENT_SIZE /* type */ +
1400 LEB128_SIZE /* assembly */ +
1401 LEB128_SIZE /* flags */ +
1404 uint64_t now = current_time ();
1406 ENTER_LOG (logbuffer, "assembly-load");
1407 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1408 emit_time (logbuffer, now);
1409 emit_byte (logbuffer, TYPE_ASSEMBLY);
1410 emit_ptr (logbuffer, assembly);
1411 emit_value (logbuffer, 0); /* flags */
1412 memcpy (logbuffer->cursor, name, nlen);
1413 logbuffer->cursor += nlen;
1414 EXIT_LOG (logbuffer);
1418 if (logbuffer->next)
1419 safe_send (prof, logbuffer);
1421 process_requests (prof);
1425 assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
1427 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1428 int nlen = strlen (name) + 1;
1429 LogBuffer *logbuffer = ensure_logbuf (
1430 EVENT_SIZE /* event */ +
1431 LEB128_SIZE /* time */ +
1432 EVENT_SIZE /* type */ +
1433 LEB128_SIZE /* assembly */ +
1434 LEB128_SIZE /* flags */ +
1437 uint64_t now = current_time ();
1439 ENTER_LOG (logbuffer, "assembly-unload");
1440 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1441 emit_time (logbuffer, now);
1442 emit_byte (logbuffer, TYPE_ASSEMBLY);
1443 emit_ptr (logbuffer, assembly);
1444 emit_value (logbuffer, 0); /* flags */
1445 memcpy (logbuffer->cursor, name, nlen);
1446 logbuffer->cursor += nlen;
1447 EXIT_LOG (logbuffer);
1451 if (logbuffer->next)
1452 safe_send (prof, logbuffer);
1454 process_requests (prof);
1458 class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
1464 LogBuffer *logbuffer;
1465 if (result != MONO_PROFILE_OK)
1467 if (InterlockedRead (&runtime_inited))
1468 name = mono_type_get_name (mono_class_get_type (klass));
1470 name = type_name (klass);
1471 nlen = strlen (name) + 1;
1472 image = mono_class_get_image (klass);
1473 logbuffer = ensure_logbuf (
1474 EVENT_SIZE /* event */ +
1475 LEB128_SIZE /* time */ +
1476 EVENT_SIZE /* type */ +
1477 LEB128_SIZE /* klass */ +
1478 LEB128_SIZE /* image */ +
1479 LEB128_SIZE /* flags */ +
1482 now = current_time ();
1483 ENTER_LOG (logbuffer, "class");
1484 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1485 emit_time (logbuffer, now);
1486 emit_byte (logbuffer, TYPE_CLASS);
1487 emit_ptr (logbuffer, klass);
1488 emit_ptr (logbuffer, image);
1489 emit_value (logbuffer, 0); /* flags */
1490 memcpy (logbuffer->cursor, name, nlen);
1491 logbuffer->cursor += nlen;
1492 //printf ("loaded class %p (%s)\n", klass, name);
1497 EXIT_LOG (logbuffer);
1498 if (logbuffer->next)
1499 safe_send (prof, logbuffer);
1500 process_requests (prof);
1504 class_unloaded (MonoProfiler *prof, MonoClass *klass)
1508 if (InterlockedRead (&runtime_inited))
1509 name = mono_type_get_name (mono_class_get_type (klass));
1511 name = type_name (klass);
1513 int nlen = strlen (name) + 1;
1514 MonoImage *image = mono_class_get_image (klass);
1515 LogBuffer *logbuffer = ensure_logbuf (
1516 EVENT_SIZE /* event */ +
1517 LEB128_SIZE /* time */ +
1518 EVENT_SIZE /* type */ +
1519 LEB128_SIZE /* klass */ +
1520 LEB128_SIZE /* image */ +
1521 LEB128_SIZE /* flags */ +
1524 uint64_t now = current_time ();
1526 ENTER_LOG (logbuffer, "class-unload");
1527 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1528 emit_time (logbuffer, now);
1529 emit_byte (logbuffer, TYPE_CLASS);
1530 emit_ptr (logbuffer, klass);
1531 emit_ptr (logbuffer, image);
1532 emit_value (logbuffer, 0); /* flags */
1533 memcpy (logbuffer->cursor, name, nlen);
1534 logbuffer->cursor += nlen;
1535 EXIT_LOG (logbuffer);
1542 if (logbuffer->next)
1543 safe_send (prof, logbuffer);
1545 process_requests (prof);
1548 #ifndef DISABLE_HELPER_THREAD
1549 static void process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method);
1550 #endif /* DISABLE_HELPER_THREAD */
1553 method_enter (MonoProfiler *prof, MonoMethod *method)
1555 uint64_t now = current_time ();
1557 #ifndef DISABLE_HELPER_THREAD
1558 process_method_enter_coverage (prof, method);
1559 #endif /* DISABLE_HELPER_THREAD */
1561 LogBuffer *logbuffer = ensure_logbuf (
1562 EVENT_SIZE /* event */ +
1563 LEB128_SIZE /* time */ +
1564 LEB128_SIZE /* method */
1566 if (logbuffer->call_depth++ > max_call_depth)
1568 ENTER_LOG (logbuffer, "enter");
1569 emit_byte (logbuffer, TYPE_ENTER | TYPE_METHOD);
1570 emit_time (logbuffer, now);
1571 emit_method (prof, logbuffer, method);
1572 EXIT_LOG (logbuffer);
1574 process_requests (prof);
1578 method_leave (MonoProfiler *prof, MonoMethod *method)
1581 LogBuffer *logbuffer = ensure_logbuf (
1582 EVENT_SIZE /* event */ +
1583 LEB128_SIZE /* time */ +
1584 LEB128_SIZE /* method */
1586 if (--logbuffer->call_depth > max_call_depth)
1588 now = current_time ();
1589 ENTER_LOG (logbuffer, "leave");
1590 emit_byte (logbuffer, TYPE_LEAVE | TYPE_METHOD);
1591 emit_time (logbuffer, now);
1592 emit_method (prof, logbuffer, method);
1593 EXIT_LOG (logbuffer);
1594 if (logbuffer->next)
1595 safe_send (prof, logbuffer);
1596 process_requests (prof);
1600 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
1603 LogBuffer *logbuffer;
1606 logbuffer = ensure_logbuf (
1607 EVENT_SIZE /* event */ +
1608 LEB128_SIZE /* time */ +
1609 LEB128_SIZE /* method */
1611 if (--logbuffer->call_depth > max_call_depth)
1613 now = current_time ();
1614 ENTER_LOG (logbuffer, "eleave");
1615 emit_byte (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
1616 emit_time (logbuffer, now);
1617 emit_method (prof, logbuffer, method);
1618 EXIT_LOG (logbuffer);
1619 process_requests (prof);
1623 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji, int result)
1625 if (result != MONO_PROFILE_OK)
1628 register_method_local (prof, method, ji);
1630 process_requests (prof);
1634 code_buffer_new (MonoProfiler *prof, void *buffer, int size, MonoProfilerCodeBufferType type, void *data)
1639 LogBuffer *logbuffer;
1640 if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
1641 name = (char *)data;
1642 nlen = strlen (name) + 1;
1647 logbuffer = ensure_logbuf (
1648 EVENT_SIZE /* event */ +
1649 LEB128_SIZE /* time */ +
1650 LEB128_SIZE /* type */ +
1651 LEB128_SIZE /* buffer */ +
1652 LEB128_SIZE /* size */ +
1657 now = current_time ();
1658 ENTER_LOG (logbuffer, "code buffer");
1659 emit_byte (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
1660 emit_time (logbuffer, now);
1661 emit_value (logbuffer, type);
1662 emit_ptr (logbuffer, buffer);
1663 emit_value (logbuffer, size);
1665 memcpy (logbuffer->cursor, name, nlen);
1666 logbuffer->cursor += nlen;
1668 EXIT_LOG (logbuffer);
1669 process_requests (prof);
1673 throw_exc (MonoProfiler *prof, MonoObject *object)
1675 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces)? TYPE_EXCEPTION_BT: 0;
1678 LogBuffer *logbuffer;
1681 logbuffer = ensure_logbuf (
1682 EVENT_SIZE /* event */ +
1683 LEB128_SIZE /* time */ +
1684 LEB128_SIZE /* object */ +
1686 LEB128_SIZE /* flags */ +
1687 LEB128_SIZE /* count */ +
1689 LEB128_SIZE /* method */
1693 now = current_time ();
1694 ENTER_LOG (logbuffer, "throw");
1695 emit_byte (logbuffer, do_bt | TYPE_EXCEPTION);
1696 emit_time (logbuffer, now);
1697 emit_obj (logbuffer, object);
1699 emit_bt (prof, logbuffer, &data);
1700 EXIT_LOG (logbuffer);
1701 process_requests (prof);
1705 clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
1708 LogBuffer *logbuffer = ensure_logbuf (
1709 EVENT_SIZE /* event */ +
1710 LEB128_SIZE /* time */ +
1711 LEB128_SIZE /* clause type */ +
1712 LEB128_SIZE /* clause num */ +
1713 LEB128_SIZE /* method */
1715 now = current_time ();
1716 ENTER_LOG (logbuffer, "clause");
1717 emit_byte (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
1718 emit_time (logbuffer, now);
1719 emit_value (logbuffer, clause_type);
1720 emit_value (logbuffer, clause_num);
1721 emit_method (prof, logbuffer, method);
1722 EXIT_LOG (logbuffer);
1724 process_requests (prof);
1728 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
1730 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION)? TYPE_MONITOR_BT: 0;
1733 LogBuffer *logbuffer;
1736 logbuffer = ensure_logbuf (
1737 EVENT_SIZE /* event */ +
1738 LEB128_SIZE /* time */ +
1739 LEB128_SIZE /* object */ +
1741 LEB128_SIZE /* flags */ +
1742 LEB128_SIZE /* count */ +
1744 LEB128_SIZE /* method */
1748 now = current_time ();
1749 ENTER_LOG (logbuffer, "monitor");
1750 emit_byte (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
1751 emit_time (logbuffer, now);
1752 emit_obj (logbuffer, object);
1754 emit_bt (profiler, logbuffer, &data);
1755 EXIT_LOG (logbuffer);
1756 process_requests (profiler);
1760 thread_start (MonoProfiler *prof, uintptr_t tid)
1762 //printf ("thread start %p\n", (void*)tid);
1765 LogBuffer *logbuffer = ensure_logbuf (
1766 EVENT_SIZE /* event */ +
1767 LEB128_SIZE /* time */ +
1768 EVENT_SIZE /* type */ +
1769 LEB128_SIZE /* tid */ +
1770 LEB128_SIZE /* flags */
1772 uint64_t now = current_time ();
1774 ENTER_LOG (logbuffer, "thread-start");
1775 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1776 emit_time (logbuffer, now);
1777 emit_byte (logbuffer, TYPE_THREAD);
1778 emit_ptr (logbuffer, (void*) tid);
1779 emit_value (logbuffer, 0); /* flags */
1780 EXIT_LOG (logbuffer);
1782 if (logbuffer->next)
1783 safe_send (prof, logbuffer);
1785 process_requests (prof);
1789 thread_end (MonoProfiler *prof, uintptr_t tid)
1791 if (TLS_GET (LogBuffer, tlsbuffer)) {
1792 LogBuffer *logbuffer = ensure_logbuf (
1793 EVENT_SIZE /* event */ +
1794 LEB128_SIZE /* time */ +
1795 EVENT_SIZE /* type */ +
1796 LEB128_SIZE /* tid */ +
1797 LEB128_SIZE /* flags */
1799 uint64_t now = current_time ();
1801 ENTER_LOG (logbuffer, "thread-end");
1802 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1803 emit_time (logbuffer, now);
1804 emit_byte (logbuffer, TYPE_THREAD);
1805 emit_ptr (logbuffer, (void*) tid);
1806 emit_value (logbuffer, 0); /* flags */
1807 EXIT_LOG (logbuffer);
1809 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), logbuffer);
1811 /* Don't process requests as the thread is detached from the runtime. */
1814 TLS_SET (tlsbuffer, NULL);
1815 TLS_SET (tlsmethodlist, NULL);
1819 domain_loaded (MonoProfiler *prof, MonoDomain *domain, int result)
1821 if (result != MONO_PROFILE_OK)
1824 LogBuffer *logbuffer = ensure_logbuf (
1825 EVENT_SIZE /* event */ +
1826 LEB128_SIZE /* time */ +
1827 EVENT_SIZE /* type */ +
1828 LEB128_SIZE /* domain id */ +
1829 LEB128_SIZE /* flags */
1831 uint64_t now = current_time ();
1833 ENTER_LOG (logbuffer, "domain-start");
1834 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1835 emit_time (logbuffer, now);
1836 emit_byte (logbuffer, TYPE_DOMAIN);
1837 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1838 emit_value (logbuffer, 0); /* flags */
1839 EXIT_LOG (logbuffer);
1841 if (logbuffer->next)
1842 safe_send (prof, logbuffer);
1844 process_requests (prof);
1848 domain_unloaded (MonoProfiler *prof, MonoDomain *domain)
1850 LogBuffer *logbuffer = ensure_logbuf (
1851 EVENT_SIZE /* event */ +
1852 LEB128_SIZE /* time */ +
1853 EVENT_SIZE /* type */ +
1854 LEB128_SIZE /* domain id */ +
1855 LEB128_SIZE /* flags */
1857 uint64_t now = current_time ();
1859 ENTER_LOG (logbuffer, "domain-end");
1860 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1861 emit_time (logbuffer, now);
1862 emit_byte (logbuffer, TYPE_DOMAIN);
1863 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1864 emit_value (logbuffer, 0); /* flags */
1865 EXIT_LOG (logbuffer);
1867 if (logbuffer->next)
1868 safe_send (prof, logbuffer);
1870 process_requests (prof);
1874 domain_name (MonoProfiler *prof, MonoDomain *domain, const char *name)
1876 int nlen = strlen (name) + 1;
1877 LogBuffer *logbuffer = ensure_logbuf (
1878 EVENT_SIZE /* event */ +
1879 LEB128_SIZE /* time */ +
1880 EVENT_SIZE /* type */ +
1881 LEB128_SIZE /* domain id */ +
1882 LEB128_SIZE /* flags */ +
1885 uint64_t now = current_time ();
1887 ENTER_LOG (logbuffer, "domain-name");
1888 emit_byte (logbuffer, TYPE_METADATA);
1889 emit_time (logbuffer, now);
1890 emit_byte (logbuffer, TYPE_DOMAIN);
1891 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1892 emit_value (logbuffer, 0); /* flags */
1893 memcpy (logbuffer->cursor, name, nlen);
1894 logbuffer->cursor += nlen;
1895 EXIT_LOG (logbuffer);
1897 if (logbuffer->next)
1898 safe_send (prof, logbuffer);
1900 process_requests (prof);
1904 context_loaded (MonoProfiler *prof, MonoAppContext *context)
1906 LogBuffer *logbuffer = ensure_logbuf (
1907 EVENT_SIZE /* event */ +
1908 LEB128_SIZE /* time */ +
1909 EVENT_SIZE /* type */ +
1910 LEB128_SIZE /* context id */ +
1911 LEB128_SIZE /* flags */ +
1912 LEB128_SIZE /* domain id */
1914 uint64_t now = current_time ();
1916 ENTER_LOG (logbuffer, "context-start");
1917 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1918 emit_time (logbuffer, now);
1919 emit_byte (logbuffer, TYPE_CONTEXT);
1920 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
1921 emit_value (logbuffer, 0); /* flags */
1922 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
1923 EXIT_LOG (logbuffer);
1925 if (logbuffer->next)
1926 safe_send (prof, logbuffer);
1928 process_requests (prof);
1932 context_unloaded (MonoProfiler *prof, MonoAppContext *context)
1934 LogBuffer *logbuffer = ensure_logbuf (
1935 EVENT_SIZE /* event */ +
1936 LEB128_SIZE /* time */ +
1937 EVENT_SIZE /* type */ +
1938 LEB128_SIZE /* context id */ +
1939 LEB128_SIZE /* flags */ +
1940 LEB128_SIZE /* domain id */
1942 uint64_t now = current_time ();
1944 ENTER_LOG (logbuffer, "context-end");
1945 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1946 emit_time (logbuffer, now);
1947 emit_byte (logbuffer, TYPE_CONTEXT);
1948 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
1949 emit_value (logbuffer, 0); /* flags */
1950 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
1951 EXIT_LOG (logbuffer);
1953 if (logbuffer->next)
1954 safe_send (prof, logbuffer);
1956 process_requests (prof);
1960 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
1962 int len = strlen (name) + 1;
1964 LogBuffer *logbuffer;
1965 logbuffer = ensure_logbuf (
1966 EVENT_SIZE /* event */ +
1967 LEB128_SIZE /* time */ +
1968 EVENT_SIZE /* type */ +
1969 LEB128_SIZE /* tid */ +
1970 LEB128_SIZE /* flags */ +
1973 now = current_time ();
1974 ENTER_LOG (logbuffer, "tname");
1975 emit_byte (logbuffer, TYPE_METADATA);
1976 emit_time (logbuffer, now);
1977 emit_byte (logbuffer, TYPE_THREAD);
1978 emit_ptr (logbuffer, (void*)tid);
1979 emit_value (logbuffer, 0); /* flags */
1980 memcpy (logbuffer->cursor, name, len);
1981 logbuffer->cursor += len;
1982 EXIT_LOG (logbuffer);
1984 if (logbuffer->next)
1985 safe_send (prof, logbuffer);
1987 process_requests (prof);
1999 AsyncFrameInfo *data;
2003 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
2005 AsyncFrameData *frame = (AsyncFrameData *)data;
2006 if (frame->count < num_frames) {
2007 frame->data [frame->count].method = method;
2008 frame->data [frame->count].domain = domain;
2009 frame->data [frame->count].base_address = base_address;
2010 frame->data [frame->count].offset = offset;
2011 // printf ("In %d at %p (dom %p) (native: %p)\n", frame->count, method, domain, base_address);
2014 return frame->count == num_frames;
2018 (type | frame count), tid, time, ip, [method, domain, base address, offset] * frames
2020 #define SAMPLE_EVENT_SIZE_IN_SLOTS(FRAMES) (4 + (FRAMES) * 4)
2023 mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
2026 AsyncFrameInfo frames [num_frames];
2027 AsyncFrameData bt_data = { 0, &frames [0]};
2029 uintptr_t *data, *new_data, *old_data;
2035 now = current_time ();
2037 mono_stack_walk_async_safe (&async_walk_stack, context, &bt_data);
2039 elapsed = (now - profiler->startup_time) / 10000;
2043 snprintf (buf, sizeof (buf), "hit at %p in thread %p after %llu ms\n", ip, (void*)thread_id (), (unsigned long long int)elapsed/100);
2045 ign_res (write (2, buf, len));
2047 sbuf = profiler->stat_buffers;
2050 /* flush the buffer at 1 second intervals */
2051 if (sbuf->cursor > sbuf->buf && (elapsed - sbuf->buf [2]) > 100000) {
2054 /* overflow: 400 slots is a big enough number to reduce the chance of losing this event if many
2055 * threads hit this same spot at the same time
2057 if (timedout || (sbuf->cursor + 400 >= sbuf->buf_end)) {
2058 StatBuffer *oldsb, *foundsb;
2059 sbuf = create_stat_buffer ();
2061 oldsb = profiler->stat_buffers;
2063 foundsb = (StatBuffer *)InterlockedCompareExchangePointer ((void * volatile*)&profiler->stat_buffers, sbuf, oldsb);
2064 } while (foundsb != oldsb);
2066 ign_res (write (2, "overflow\n", 9));
2067 /* notify the helper thread */
2068 if (sbuf->next->next) {
2070 ign_res (write (profiler->pipes [1], &c, 1));
2072 ign_res (write (2, "notify\n", 7));
2076 old_data = sbuf->cursor;
2077 new_data = old_data + SAMPLE_EVENT_SIZE_IN_SLOTS (bt_data.count);
2078 if (new_data > sbuf->buf_end)
2079 return; /* Not enough room in buf to hold this event-- lost event */
2080 data = (uintptr_t *)InterlockedCompareExchangePointer ((void * volatile*)&sbuf->cursor, new_data, old_data);
2081 } while (data != old_data);
2083 old_data [0] = 1 | (sample_type << 16) | (bt_data.count << 8);
2084 old_data [1] = thread_id ();
2085 old_data [2] = elapsed;
2086 old_data [3] = (uintptr_t)ip;
2087 for (i = 0; i < bt_data.count; ++i) {
2088 old_data [4 + 4 * i + 0] = (uintptr_t)frames [i].method;
2089 old_data [4 + 4 * i + 1] = (uintptr_t)frames [i].domain;
2090 old_data [4 + 4 * i + 2] = (uintptr_t)frames [i].base_address;
2091 old_data [4 + 4 * i + 3] = (uintptr_t)frames [i].offset;
2095 static uintptr_t *code_pages = 0;
2096 static int num_code_pages = 0;
2097 static int size_code_pages = 0;
2098 #define CPAGE_SHIFT (9)
2099 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
2100 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
2101 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
2104 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
2107 uintptr_t start_pos;
2108 start_pos = (page >> CPAGE_SHIFT) % hsize;
2111 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
2113 } else if (!hash [i]) {
2120 } while (i != start_pos);
2121 /* should not happen */
2122 printf ("failed code page store\n");
2127 add_code_pointer (uintptr_t ip)
2130 if (num_code_pages * 2 >= size_code_pages) {
2132 uintptr_t old_size = size_code_pages;
2133 size_code_pages *= 2;
2134 if (size_code_pages == 0)
2135 size_code_pages = 16;
2136 n = (uintptr_t *)calloc (sizeof (uintptr_t) * size_code_pages, 1);
2137 for (i = 0; i < old_size; ++i) {
2139 add_code_page (n, size_code_pages, code_pages [i]);
2145 num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
2148 /* ELF code crashes on some systems. */
2149 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2152 dump_ubin (const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
2155 LogBuffer *logbuffer;
2157 len = strlen (filename) + 1;
2158 now = current_time ();
2159 logbuffer = ensure_logbuf (
2160 EVENT_SIZE /* event */ +
2161 LEB128_SIZE /* time */ +
2162 LEB128_SIZE /* load address */ +
2163 LEB128_SIZE /* offset */ +
2164 LEB128_SIZE /* size */ +
2165 nlen /* file name */
2167 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
2168 emit_time (logbuffer, now);
2169 emit_svalue (logbuffer, load_addr);
2170 emit_uvalue (logbuffer, offset);
2171 emit_uvalue (logbuffer, size);
2172 memcpy (logbuffer->cursor, filename, len);
2173 logbuffer->cursor += len;
2178 dump_usym (const char *name, uintptr_t value, uintptr_t size)
2180 LogBuffer *logbuffer;
2182 len = strlen (name) + 1;
2183 logbuffer = ensure_logbuf (
2184 EVENT_SIZE /* event */ +
2185 LEB128_SIZE /* value */ +
2186 LEB128_SIZE /* size */ +
2189 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
2190 emit_ptr (logbuffer, (void*)value);
2191 emit_value (logbuffer, size);
2192 memcpy (logbuffer->cursor, name, len);
2193 logbuffer->cursor += len;
2196 /* ELF code crashes on some systems. */
2197 //#if defined(ELFMAG0)
2200 #if SIZEOF_VOID_P == 4
2201 #define ELF_WSIZE 32
2203 #define ELF_WSIZE 64
2206 #define ElfW(type) _ElfW (Elf, ELF_WSIZE, type)
2207 #define _ElfW(e,w,t) _ElfW_1 (e, w, _##t)
2208 #define _ElfW_1(e,w,t) e##w##t
2212 dump_elf_symbols (ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
2215 for (i = 0; i < num_symbols; ++i) {
2217 sym = strtab + symbols [i].st_name;
2218 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
2220 //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
2221 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
2226 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
2233 ElfW(Shdr) *sheader;
2234 ElfW(Shdr) *shstrtabh;
2235 ElfW(Shdr) *symtabh = NULL;
2236 ElfW(Shdr) *strtabh = NULL;
2237 ElfW(Sym) *symbols = NULL;
2241 fd = open (filename, O_RDONLY);
2244 if (fstat (fd, &statb) != 0) {
2248 file_size = statb.st_size;
2249 data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
2251 if (data == MAP_FAILED)
2254 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2255 header->e_ident [EI_MAG1] != ELFMAG1 ||
2256 header->e_ident [EI_MAG2] != ELFMAG2 ||
2257 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2258 munmap (data, file_size);
2261 sheader = (void*)((char*)data + header->e_shoff);
2262 shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
2263 strtab = (const char*)data + shstrtabh->sh_offset;
2264 for (i = 0; i < header->e_shnum; ++i) {
2265 //printf ("section header: %d\n", sheader->sh_type);
2266 if (sheader->sh_type == SHT_SYMTAB) {
2268 strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
2269 /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
2272 sheader = (void*)((char*)sheader + header->e_shentsize);
2274 if (!symtabh || !strtabh) {
2275 munmap (data, file_size);
2278 strtab = (const char*)data + strtabh->sh_offset;
2279 num_symbols = symtabh->sh_size / symtabh->sh_entsize;
2280 symbols = (void*)((char*)data + symtabh->sh_offset);
2281 dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
2282 munmap (data, file_size);
2287 /* ELF code crashes on some systems. */
2288 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2291 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
2293 MonoProfiler *prof = data;
2295 const char *filename;
2297 char *a = (void*)info->dlpi_addr;
2299 ElfW(Dyn) *dyn = NULL;
2300 ElfW(Sym) *symtab = NULL;
2301 ElfW(Word) *hash_table = NULL;
2302 ElfW(Ehdr) *header = NULL;
2303 const char* strtab = NULL;
2304 for (obj = prof->binary_objects; obj; obj = obj->next) {
2308 filename = info->dlpi_name;
2311 if (!info->dlpi_addr && !filename [0]) {
2312 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
2318 obj = calloc (sizeof (BinaryObject), 1);
2319 obj->addr = (void*)info->dlpi_addr;
2320 obj->name = pstrdup (filename);
2321 obj->next = prof->binary_objects;
2322 prof->binary_objects = obj;
2323 //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
2325 for (i = 0; i < info->dlpi_phnum; ++i) {
2326 //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);
2327 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
2328 header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2329 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2330 header->e_ident [EI_MAG1] != ELFMAG1 ||
2331 header->e_ident [EI_MAG2] != ELFMAG2 ||
2332 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2335 dump_ubin (filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
2336 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
2337 dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2340 if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
2342 if (!info->dlpi_name || !info->dlpi_name[0])
2346 for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
2347 if (dyn [i].d_tag == DT_SYMTAB) {
2348 if (symtab && do_debug)
2349 printf ("multiple symtabs: %d\n", i);
2350 symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
2351 } else if (dyn [i].d_tag == DT_HASH) {
2352 hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
2353 } else if (dyn [i].d_tag == DT_STRTAB) {
2354 strtab = (const char*)(a + dyn [i].d_un.d_ptr);
2359 num_sym = hash_table [1];
2360 dump_elf_symbols (symtab, num_sym, strtab, (void*)info->dlpi_addr);
2365 load_binaries (MonoProfiler *prof)
2367 dl_iterate_phdr (elf_dl_callback, prof);
2372 load_binaries (MonoProfiler *prof)
2379 symbol_for (uintptr_t code)
2382 void *ip = (void*)code;
2384 if (dladdr (ip, &di)) {
2386 return di.dli_sname;
2389 names = backtrace_symbols (&ip, 1);
2391 const char* p = names [0];
2402 dump_unmanaged_coderefs (MonoProfiler *prof)
2405 const char* last_symbol;
2406 uintptr_t addr, page_end;
2408 if (load_binaries (prof))
2410 for (i = 0; i < size_code_pages; ++i) {
2412 if (!code_pages [i] || code_pages [i] & 1)
2415 addr = CPAGE_ADDR (code_pages [i]);
2416 page_end = addr + CPAGE_SIZE;
2417 code_pages [i] |= 1;
2418 /* we dump the symbols for the whole page */
2419 for (; addr < page_end; addr += 16) {
2420 sym = symbol_for (addr);
2421 if (sym && sym == last_symbol)
2426 dump_usym (sym, addr, 0); /* let's not guess the size */
2427 //printf ("found symbol at %p: %s\n", (void*)addr, sym);
2433 compare_sample_events (gconstpointer a, gconstpointer b)
2435 uintptr_t tid1 = (*(uintptr_t **) a) [1];
2436 uintptr_t tid2 = (*(uintptr_t **) b) [1];
2438 return tid1 > tid2 ? 1 :
2444 dump_sample_hits (MonoProfiler *prof, StatBuffer *sbuf)
2446 LogBuffer *logbuffer;
2450 dump_sample_hits (prof, sbuf->next);
2451 free_buffer (sbuf->next, sbuf->next->size);
2455 g_ptr_array_set_size (prof->sorted_sample_events, 0);
2457 for (uintptr_t *sample = sbuf->buf; sample < sbuf->cursor;) {
2458 int count = sample [0] & 0xff;
2459 int mbt_count = (sample [0] & 0xff00) >> 8;
2461 if (sample + SAMPLE_EVENT_SIZE_IN_SLOTS (mbt_count) > sbuf->cursor)
2464 g_ptr_array_add (prof->sorted_sample_events, sample);
2466 sample += count + 3 + 4 * mbt_count;
2469 g_ptr_array_sort (prof->sorted_sample_events, compare_sample_events);
2471 for (guint sidx = 0; sidx < prof->sorted_sample_events->len; sidx++) {
2472 uintptr_t *sample = (uintptr_t *)g_ptr_array_index (prof->sorted_sample_events, sidx);
2473 int count = sample [0] & 0xff;
2474 int mbt_count = (sample [0] & 0xff00) >> 8;
2475 int type = sample [0] >> 16;
2476 uintptr_t *managed_sample_base = sample + count + 3;
2477 uintptr_t thread_id = sample [1];
2479 for (int i = 0; i < mbt_count; ++i) {
2480 MonoMethod *method = (MonoMethod*)managed_sample_base [i * 4 + 0];
2481 MonoDomain *domain = (MonoDomain*)managed_sample_base [i * 4 + 1];
2482 void *address = (void*)managed_sample_base [i * 4 + 2];
2486 MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *)address);
2489 managed_sample_base [i * 4 + 0] = (uintptr_t)mono_jit_info_get_method (ji);
2493 logbuffer = ensure_logbuf (
2494 EVENT_SIZE /* event */ +
2495 LEB128_SIZE /* type */ +
2496 LEB128_SIZE /* time */ +
2497 LEB128_SIZE /* tid */ +
2498 LEB128_SIZE /* count */ +
2500 LEB128_SIZE /* ip */
2502 LEB128_SIZE /* managed count */ +
2504 LEB128_SIZE /* method */ +
2505 LEB128_SIZE /* il offset */ +
2506 LEB128_SIZE /* native offset */
2509 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
2510 emit_value (logbuffer, type);
2511 emit_uvalue (logbuffer, prof->startup_time + (uint64_t)sample [2] * (uint64_t)10000);
2512 emit_ptr (logbuffer, (void *) thread_id);
2513 emit_value (logbuffer, count);
2514 for (int i = 0; i < count; ++i) {
2515 emit_ptr (logbuffer, (void*)sample [i + 3]);
2516 add_code_pointer (sample [i + 3]);
2519 sample += count + 3;
2520 /* new in data version 6 */
2521 emit_uvalue (logbuffer, mbt_count);
2522 for (int i = 0; i < mbt_count; ++i) {
2523 MonoMethod *method = (MonoMethod *) sample [i * 4 + 0];
2524 uintptr_t native_offset = sample [i * 4 + 3];
2526 emit_method (prof, logbuffer, method);
2527 emit_svalue (logbuffer, 0); /* il offset will always be 0 from now on */
2528 emit_svalue (logbuffer, native_offset);
2532 dump_unmanaged_coderefs (prof);
2538 mono_cpu_count (void)
2540 #ifdef PLATFORM_ANDROID
2541 /* Android tries really hard to save power by powering off CPUs on SMP phones which
2542 * means the normal way to query cpu count returns a wrong value with userspace API.
2543 * Instead we use /sys entries to query the actual hardware CPU count.
2546 char buffer[8] = {'\0'};
2547 int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
2548 /* Format of the /sys entry is a cpulist of indexes which in the case
2549 * of present is always of the form "0-(n-1)" when there is more than
2550 * 1 core, n being the number of CPU cores in the system. Otherwise
2551 * the value is simply 0
2553 if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
2554 count = strtol (((char*)buffer) + 2, NULL, 10);
2561 #if defined(HOST_ARM) || defined (HOST_ARM64)
2563 /* ARM platforms tries really hard to save power by powering off CPUs on SMP phones which
2564 * means the normal way to query cpu count returns a wrong value with userspace API. */
2566 #ifdef _SC_NPROCESSORS_CONF
2568 int count = sysconf (_SC_NPROCESSORS_CONF);
2576 #ifdef HAVE_SCHED_GETAFFINITY
2579 if (sched_getaffinity (getpid (), sizeof (set), &set) == 0)
2580 return CPU_COUNT (&set);
2583 #ifdef _SC_NPROCESSORS_ONLN
2585 int count = sysconf (_SC_NPROCESSORS_ONLN);
2591 #endif /* defined(HOST_ARM) || defined (HOST_ARM64) */
2597 size_t len = sizeof (int);
2600 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
2607 GetSystemInfo (&info);
2608 return info.dwNumberOfProcessors;
2617 unsigned int prev_pos;
2619 struct perf_event_mmap_page *page_desc;
2622 static PerfData *perf_data = NULL;
2623 static int num_perf;
2624 #define PERF_PAGES_SHIFT 4
2625 static int num_pages = 1 << PERF_PAGES_SHIFT;
2626 static unsigned int mmap_mask;
2629 struct perf_event_header h;
2639 perf_event_syscall (struct perf_event_attr *attr, pid_t pid, int cpu, int group_fd, unsigned long flags)
2641 attr->size = PERF_ATTR_SIZE_VER0;
2642 //printf ("perf attr size: %d\n", attr->size);
2643 #if defined(__x86_64__)
2644 return syscall(/*__NR_perf_event_open*/ 298, attr, pid, cpu, group_fd, flags);
2645 #elif defined(__i386__)
2646 return syscall(/*__NR_perf_event_open*/ 336, attr, pid, cpu, group_fd, flags);
2647 #elif defined(__arm__) || defined (__aarch64__)
2648 return syscall(/*__NR_perf_event_open*/ 364, attr, pid, cpu, group_fd, flags);
2655 setup_perf_map (PerfData *perf)
2657 perf->mmap_base = mmap (NULL, (num_pages + 1) * getpagesize (), PROT_READ|PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
2658 if (perf->mmap_base == MAP_FAILED) {
2660 printf ("failed mmap\n");
2663 perf->page_desc = perf->mmap_base;
2665 printf ("mmap version: %d\n", perf->page_desc->version);
2670 dump_perf_hits (MonoProfiler *prof, void *buf, int size)
2672 LogBuffer *logbuffer;
2675 void *end = (char*)buf + size;
2677 int pid = getpid ();
2683 if (pid != s->pid) {
2685 printf ("event for different pid: %d\n", s->pid);
2686 buf = (char*)buf + s->h.size;
2689 /*ip = (void*)s->ip;
2690 printf ("sample: %d, size: %d, ip: %p (%s), timestamp: %llu, nframes: %llu\n",
2691 s->h.type, s->h.size, ip, symbol_for (ip), s->timestamp, s->nframes);*/
2692 logbuffer = ensure_logbuf (
2693 EVENT_SIZE /* event */ +
2694 LEB128_SIZE /* type */ +
2695 LEB128_SIZE /* time */ +
2696 LEB128_SIZE /* tid */ +
2697 LEB128_SIZE /* count */ +
2699 LEB128_SIZE /* ip */
2701 LEB128_SIZE /* managed count */ +
2703 LEB128_SIZE /* method */ +
2704 LEB128_SIZE /* il offset */ +
2705 LEB128_SIZE /* native offset */
2708 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
2709 emit_value (logbuffer, sample_type);
2710 emit_uvalue (logbuffer, s->timestamp - prof->startup_time);
2712 * No useful thread ID to write here, since throughout the
2713 * profiler we use pthread_self () but the ID we get from
2714 * perf is the kernel's thread ID.
2716 emit_ptr (logbuffer, 0);
2717 emit_value (logbuffer, count);
2718 emit_ptr (logbuffer, (void*)(uintptr_t)s->ip);
2719 add_code_pointer (s->ip);
2720 /* no support here yet for the managed backtrace */
2721 emit_uvalue (logbuffer, mbt_count);
2722 buf = (char*)buf + s->h.size;
2726 printf ("dumped %d samples\n", samples);
2727 dump_unmanaged_coderefs (prof);
2730 /* read events from the ring buffer */
2732 read_perf_mmap (MonoProfiler* prof, int cpu)
2734 PerfData *perf = perf_data + cpu;
2736 unsigned char *data = (unsigned char*)perf->mmap_base + getpagesize ();
2737 unsigned int head = perf->page_desc->data_head;
2741 mono_memory_read_barrier ();
2743 old = perf->prev_pos;
2747 printf ("lost mmap events: old: %d, head: %d\n", old, head);
2751 if ((old & mmap_mask) + size != (head & mmap_mask)) {
2752 buf = data + (old & mmap_mask);
2753 size = mmap_mask + 1 - (old & mmap_mask);
2755 /* size bytes at buf */
2757 printf ("found1 bytes of events: %d\n", size);
2758 dump_perf_hits (prof, buf, size);
2760 buf = data + (old & mmap_mask);
2762 /* size bytes at buf */
2764 printf ("found bytes of events: %d\n", size);
2765 dump_perf_hits (prof, buf, size);
2767 perf->prev_pos = old;
2768 perf->page_desc->data_tail = old;
2773 setup_perf_event_for_cpu (PerfData *perf, int cpu)
2775 struct perf_event_attr attr;
2776 memset (&attr, 0, sizeof (attr));
2777 attr.type = PERF_TYPE_HARDWARE;
2778 switch (sample_type) {
2779 case SAMPLE_CYCLES: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2780 case SAMPLE_INSTRUCTIONS: attr.config = PERF_COUNT_HW_INSTRUCTIONS; break;
2781 case SAMPLE_CACHE_MISSES: attr.config = PERF_COUNT_HW_CACHE_MISSES; break;
2782 case SAMPLE_CACHE_REFS: attr.config = PERF_COUNT_HW_CACHE_REFERENCES; break;
2783 case SAMPLE_BRANCHES: attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS; break;
2784 case SAMPLE_BRANCH_MISSES: attr.config = PERF_COUNT_HW_BRANCH_MISSES; break;
2785 default: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2787 attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD | PERF_SAMPLE_TIME;
2788 // attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
2789 attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING | PERF_FORMAT_ID;
2792 attr.sample_freq = sample_freq;
2794 perf->perf_fd = perf_event_syscall (&attr, getpid (), cpu, -1, 0);
2796 printf ("perf fd: %d, freq: %d, event: %llu\n", perf->perf_fd, sample_freq, attr.config);
2797 if (perf->perf_fd < 0) {
2798 if (perf->perf_fd == -EPERM) {
2799 fprintf (stderr, "Perf syscall denied, do \"echo 1 > /proc/sys/kernel/perf_event_paranoid\" as root to enable.\n");
2802 perror ("open perf event");
2806 if (!setup_perf_map (perf)) {
2807 close (perf->perf_fd);
2815 setup_perf_event (void)
2818 mmap_mask = num_pages * getpagesize () - 1;
2819 num_perf = mono_cpu_count ();
2820 perf_data = calloc (num_perf, sizeof (PerfData));
2821 for (i = 0; i < num_perf; ++i) {
2822 count += setup_perf_event_for_cpu (perf_data + i, i);
2831 #endif /* USE_PERF_EVENTS */
2833 #ifndef DISABLE_HELPER_THREAD
2835 typedef struct MonoCounterAgent {
2836 MonoCounter *counter;
2837 // MonoCounterAgent specific data :
2842 struct MonoCounterAgent *next;
2845 static MonoCounterAgent* counters;
2846 static gboolean counters_initialized = FALSE;
2847 static int counters_index = 1;
2848 static mono_mutex_t counters_mutex;
2851 counters_add_agent (MonoCounter *counter)
2853 MonoCounterAgent *agent, *item;
2855 if (!counters_initialized)
2858 mono_os_mutex_lock (&counters_mutex);
2860 for (agent = counters; agent; agent = agent->next) {
2861 if (agent->counter == counter) {
2862 agent->value_size = 0;
2864 free (agent->value);
2865 agent->value = NULL;
2867 mono_os_mutex_unlock (&counters_mutex);
2872 agent = (MonoCounterAgent *)malloc (sizeof (MonoCounterAgent));
2873 agent->counter = counter;
2874 agent->value = NULL;
2875 agent->value_size = 0;
2876 agent->index = counters_index++;
2889 mono_os_mutex_unlock (&counters_mutex);
2893 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
2895 counters_add_agent (counter);
2900 counters_init (MonoProfiler *profiler)
2902 assert (!counters_initialized);
2904 mono_os_mutex_init (&counters_mutex);
2906 counters_initialized = TRUE;
2908 mono_counters_on_register (&counters_add_agent);
2909 mono_counters_foreach (counters_init_foreach_callback, NULL);
2913 counters_emit (MonoProfiler *profiler)
2915 MonoCounterAgent *agent;
2916 LogBuffer *logbuffer;
2919 EVENT_SIZE /* event */ +
2920 LEB128_SIZE /* len */
2923 if (!counters_initialized)
2926 mono_os_mutex_lock (&counters_mutex);
2928 for (agent = counters; agent; agent = agent->next) {
2933 LEB128_SIZE /* section */ +
2934 strlen (mono_counter_get_name (agent->counter)) + 1 /* name */ +
2935 LEB128_SIZE /* type */ +
2936 LEB128_SIZE /* unit */ +
2937 LEB128_SIZE /* variance */ +
2938 LEB128_SIZE /* index */
2945 mono_os_mutex_unlock (&counters_mutex);
2949 logbuffer = ensure_logbuf (size);
2951 ENTER_LOG (logbuffer, "counters");
2952 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2953 emit_value (logbuffer, len);
2954 for (agent = counters; agent; agent = agent->next) {
2960 name = mono_counter_get_name (agent->counter);
2961 emit_value (logbuffer, mono_counter_get_section (agent->counter));
2962 emit_string (logbuffer, name, strlen (name) + 1);
2963 emit_value (logbuffer, mono_counter_get_type (agent->counter));
2964 emit_value (logbuffer, mono_counter_get_unit (agent->counter));
2965 emit_value (logbuffer, mono_counter_get_variance (agent->counter));
2966 emit_value (logbuffer, agent->index);
2970 EXIT_LOG (logbuffer);
2972 safe_send (profiler, logbuffer);
2974 mono_os_mutex_unlock (&counters_mutex);
2978 counters_sample (MonoProfiler *profiler, uint64_t timestamp)
2980 MonoCounterAgent *agent;
2981 MonoCounter *counter;
2982 LogBuffer *logbuffer;
2988 if (!counters_initialized)
2991 counters_emit (profiler);
2994 buffer = calloc (1, buffer_size);
2996 mono_os_mutex_lock (&counters_mutex);
2999 EVENT_SIZE /* event */ +
3000 LEB128_SIZE /* time */
3003 for (agent = counters; agent; agent = agent->next) {
3005 LEB128_SIZE /* index */ +
3006 LEB128_SIZE /* type */ +
3007 mono_counter_get_size (agent->counter) /* value */
3012 LEB128_SIZE /* stop marker */
3015 logbuffer = ensure_logbuf (size);
3017 ENTER_LOG (logbuffer, "counters");
3018 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
3019 emit_uvalue (logbuffer, timestamp);
3020 for (agent = counters; agent; agent = agent->next) {
3023 counter = agent->counter;
3025 size = mono_counter_get_size (counter);
3027 continue; // FIXME error
3028 } else if (size > buffer_size) {
3030 buffer = realloc (buffer, buffer_size);
3033 memset (buffer, 0, buffer_size);
3035 if (mono_counters_sample (counter, buffer, size) < 0)
3036 continue; // FIXME error
3038 type = mono_counter_get_type (counter);
3040 if (!agent->value) {
3041 agent->value = calloc (1, size);
3042 agent->value_size = size;
3044 if (type == MONO_COUNTER_STRING) {
3045 if (strcmp (agent->value, buffer) == 0)
3048 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
3053 emit_uvalue (logbuffer, agent->index);
3054 emit_uvalue (logbuffer, type);
3056 case MONO_COUNTER_INT:
3057 #if SIZEOF_VOID_P == 4
3058 case MONO_COUNTER_WORD:
3060 emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
3062 case MONO_COUNTER_UINT:
3063 emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
3065 case MONO_COUNTER_TIME_INTERVAL:
3066 case MONO_COUNTER_LONG:
3067 #if SIZEOF_VOID_P == 8
3068 case MONO_COUNTER_WORD:
3070 emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
3072 case MONO_COUNTER_ULONG:
3073 emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
3075 case MONO_COUNTER_DOUBLE:
3076 emit_double (logbuffer, *(double*)buffer);
3078 case MONO_COUNTER_STRING:
3080 emit_byte (logbuffer, 0);
3082 emit_byte (logbuffer, 1);
3083 emit_string (logbuffer, (char*)buffer, size);
3090 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
3091 agent->value = realloc (agent->value, size);
3092 agent->value_size = size;
3096 memcpy (agent->value, buffer, size);
3100 emit_value (logbuffer, 0);
3101 EXIT_LOG (logbuffer);
3103 safe_send (profiler, logbuffer);
3105 mono_os_mutex_unlock (&counters_mutex);
3108 typedef struct _PerfCounterAgent PerfCounterAgent;
3109 struct _PerfCounterAgent {
3110 PerfCounterAgent *next;
3112 char *category_name;
3121 static PerfCounterAgent *perfcounters = NULL;
3124 perfcounters_emit (MonoProfiler *profiler)
3126 PerfCounterAgent *pcagent;
3127 LogBuffer *logbuffer;
3130 EVENT_SIZE /* event */ +
3131 LEB128_SIZE /* len */
3134 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3135 if (pcagent->emitted)
3139 LEB128_SIZE /* section */ +
3140 strlen (pcagent->category_name) + 1 /* category name */ +
3141 strlen (pcagent->name) + 1 /* name */ +
3142 LEB128_SIZE /* type */ +
3143 LEB128_SIZE /* unit */ +
3144 LEB128_SIZE /* variance */ +
3145 LEB128_SIZE /* index */
3154 logbuffer = ensure_logbuf (size);
3156 ENTER_LOG (logbuffer, "perfcounters");
3157 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
3158 emit_value (logbuffer, len);
3159 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3160 if (pcagent->emitted)
3163 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
3164 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
3165 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
3166 emit_value (logbuffer, MONO_COUNTER_LONG);
3167 emit_value (logbuffer, MONO_COUNTER_RAW);
3168 emit_value (logbuffer, MONO_COUNTER_VARIABLE);
3169 emit_value (logbuffer, pcagent->index);
3171 pcagent->emitted = 1;
3173 EXIT_LOG (logbuffer);
3175 safe_send (profiler, logbuffer);
3179 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
3181 PerfCounterAgent *pcagent;
3183 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3184 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
3186 if (pcagent->value == value)
3189 pcagent->value = value;
3190 pcagent->updated = 1;
3191 pcagent->deleted = 0;
3195 pcagent = g_new0 (PerfCounterAgent, 1);
3196 pcagent->next = perfcounters;
3197 pcagent->index = counters_index++;
3198 pcagent->category_name = g_strdup (category_name);
3199 pcagent->name = g_strdup (name);
3200 pcagent->type = (int) type;
3201 pcagent->value = value;
3202 pcagent->emitted = 0;
3203 pcagent->updated = 1;
3204 pcagent->deleted = 0;
3206 perfcounters = pcagent;
3212 perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp)
3214 PerfCounterAgent *pcagent;
3215 LogBuffer *logbuffer;
3218 if (!counters_initialized)
3221 mono_os_mutex_lock (&counters_mutex);
3223 /* mark all perfcounters as deleted, foreach will unmark them as necessary */
3224 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
3225 pcagent->deleted = 1;
3227 mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
3229 perfcounters_emit (profiler);
3232 EVENT_SIZE /* event */ +
3233 LEB128_SIZE /* time */
3236 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3237 if (pcagent->deleted || !pcagent->updated)
3241 LEB128_SIZE /* index */ +
3242 LEB128_SIZE /* type */ +
3243 LEB128_SIZE /* value */
3248 LEB128_SIZE /* stop marker */
3251 logbuffer = ensure_logbuf (size);
3253 ENTER_LOG (logbuffer, "perfcounters");
3254 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
3255 emit_uvalue (logbuffer, timestamp);
3256 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3257 if (pcagent->deleted || !pcagent->updated)
3259 emit_uvalue (logbuffer, pcagent->index);
3260 emit_uvalue (logbuffer, MONO_COUNTER_LONG);
3261 emit_svalue (logbuffer, pcagent->value);
3263 pcagent->updated = 0;
3266 emit_value (logbuffer, 0);
3267 EXIT_LOG (logbuffer);
3269 safe_send (profiler, logbuffer);
3271 mono_os_mutex_unlock (&counters_mutex);
3275 counters_and_perfcounters_sample (MonoProfiler *prof)
3277 static uint64_t start = -1;
3281 start = current_time ();
3283 now = current_time ();
3284 counters_sample (prof, (now - start) / 1000/ 1000);
3285 perfcounters_sample (prof, (now - start) / 1000/ 1000);
3288 #define COVERAGE_DEBUG(x) if (debug_coverage) {x}
3289 static mono_mutex_t coverage_mutex;
3290 static MonoConcurrentHashTable *coverage_methods = NULL;
3291 static MonoConcurrentHashTable *coverage_assemblies = NULL;
3292 static MonoConcurrentHashTable *coverage_classes = NULL;
3294 static MonoConcurrentHashTable *filtered_classes = NULL;
3295 static MonoConcurrentHashTable *entered_methods = NULL;
3296 static MonoConcurrentHashTable *image_to_methods = NULL;
3297 static MonoConcurrentHashTable *suppressed_assemblies = NULL;
3298 static gboolean coverage_initialized = FALSE;
3300 static GPtrArray *coverage_data = NULL;
3301 static int previous_offset = 0;
3303 typedef struct _MethodNode MethodNode;
3304 struct _MethodNode {
3305 MonoLockFreeQueueNode node;
3309 typedef struct _CoverageEntry CoverageEntry;
3310 struct _CoverageEntry {
3319 free_coverage_entry (gpointer data, gpointer userdata)
3321 CoverageEntry *entry = (CoverageEntry *)data;
3322 g_free (entry->filename);
3327 obtain_coverage_for_method (MonoProfiler *prof, const MonoProfileCoverageEntry *entry)
3329 int offset = entry->iloffset - previous_offset;
3330 CoverageEntry *e = g_new (CoverageEntry, 1);
3332 previous_offset = entry->iloffset;
3335 e->counter = entry->counter;
3336 e->filename = g_strdup(entry->filename ? entry->filename : "");
3337 e->line = entry->line;
3338 e->column = entry->col;
3340 g_ptr_array_add (coverage_data, e);
3344 parse_generic_type_names(char *name)
3346 char *new_name, *ret;
3347 int within_generic_declaration = 0, generic_members = 1;
3349 if (name == NULL || *name == '\0')
3350 return g_strdup ("");
3352 if (!(ret = new_name = (char *)calloc (strlen (name) * 4 + 1, sizeof (char))))
3358 within_generic_declaration = 1;
3362 within_generic_declaration = 0;
3364 if (*(name - 1) != '<') {
3366 *new_name++ = '0' + generic_members;
3368 memcpy (new_name, "<>", 8);
3372 generic_members = 0;
3380 if (!within_generic_declaration)
3381 *new_name++ = *name;
3390 static int method_id;
3392 build_method_buffer (gpointer key, gpointer value, gpointer userdata)
3394 MonoMethod *method = (MonoMethod *)value;
3395 MonoProfiler *prof = (MonoProfiler *)userdata;
3399 const char *image_name, *method_name, *sig, *first_filename;
3400 LogBuffer *logbuffer;
3403 previous_offset = 0;
3404 coverage_data = g_ptr_array_new ();
3406 mono_profiler_coverage_get (prof, method, obtain_coverage_for_method);
3408 klass = mono_method_get_class (method);
3409 image = mono_class_get_image (klass);
3410 image_name = mono_image_get_name (image);
3412 sig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3413 class_name = parse_generic_type_names (mono_type_get_name (mono_class_get_type (klass)));
3414 method_name = mono_method_get_name (method);
3416 if (coverage_data->len != 0) {
3417 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[0];
3418 first_filename = entry->filename ? entry->filename : "";
3420 first_filename = "";
3422 image_name = image_name ? image_name : "";
3423 sig = sig ? sig : "";
3424 method_name = method_name ? method_name : "";
3426 logbuffer = ensure_logbuf (
3427 EVENT_SIZE /* event */ +
3428 strlen (image_name) + 1 /* image name */ +
3429 strlen (class_name) + 1 /* class name */ +
3430 strlen (method_name) + 1 /* method name */ +
3431 strlen (sig) + 1 /* signature */ +
3432 strlen (first_filename) + 1 /* first file name */ +
3433 LEB128_SIZE /* token */ +
3434 LEB128_SIZE /* method id */ +
3435 LEB128_SIZE /* entries */
3437 ENTER_LOG (logbuffer, "coverage-methods");
3439 emit_byte (logbuffer, TYPE_COVERAGE_METHOD | TYPE_COVERAGE);
3440 emit_string (logbuffer, image_name, strlen (image_name) + 1);
3441 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3442 emit_string (logbuffer, method_name, strlen (method_name) + 1);
3443 emit_string (logbuffer, sig, strlen (sig) + 1);
3444 emit_string (logbuffer, first_filename, strlen (first_filename) + 1);
3446 emit_uvalue (logbuffer, mono_method_get_token (method));
3447 emit_uvalue (logbuffer, method_id);
3448 emit_value (logbuffer, coverage_data->len);
3450 EXIT_LOG (logbuffer);
3451 safe_send (prof, logbuffer);
3453 for (i = 0; i < coverage_data->len; i++) {
3454 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[i];
3456 logbuffer = ensure_logbuf (
3457 EVENT_SIZE /* event */ +
3458 LEB128_SIZE /* method id */ +
3459 LEB128_SIZE /* offset */ +
3460 LEB128_SIZE /* counter */ +
3461 LEB128_SIZE /* line */ +
3462 LEB128_SIZE /* column */
3464 ENTER_LOG (logbuffer, "coverage-statement");
3466 emit_byte (logbuffer, TYPE_COVERAGE_STATEMENT | TYPE_COVERAGE);
3467 emit_uvalue (logbuffer, method_id);
3468 emit_uvalue (logbuffer, entry->offset);
3469 emit_uvalue (logbuffer, entry->counter);
3470 emit_uvalue (logbuffer, entry->line);
3471 emit_uvalue (logbuffer, entry->column);
3473 EXIT_LOG (logbuffer);
3474 safe_send (prof, logbuffer);
3479 g_free (class_name);
3481 g_ptr_array_foreach (coverage_data, free_coverage_entry, NULL);
3482 g_ptr_array_free (coverage_data, TRUE);
3483 coverage_data = NULL;
3486 /* This empties the queue */
3488 count_queue (MonoLockFreeQueue *queue)
3490 MonoLockFreeQueueNode *node;
3493 while ((node = mono_lock_free_queue_dequeue (queue))) {
3495 mono_lock_free_queue_node_free (node);
3502 build_class_buffer (gpointer key, gpointer value, gpointer userdata)
3504 MonoClass *klass = (MonoClass *)key;
3505 MonoLockFreeQueue *class_methods = (MonoLockFreeQueue *)value;
3506 MonoProfiler *prof = (MonoProfiler *)userdata;
3509 const char *assembly_name;
3510 int number_of_methods, partially_covered;
3511 guint fully_covered;
3512 LogBuffer *logbuffer;
3514 image = mono_class_get_image (klass);
3515 assembly_name = mono_image_get_name (image);
3516 class_name = mono_type_get_name (mono_class_get_type (klass));
3518 assembly_name = assembly_name ? assembly_name : "";
3519 number_of_methods = mono_class_num_methods (klass);
3520 fully_covered = count_queue (class_methods);
3521 /* We don't handle partial covered yet */
3522 partially_covered = 0;
3524 logbuffer = ensure_logbuf (
3525 EVENT_SIZE /* event */ +
3526 strlen (assembly_name) + 1 /* assembly name */ +
3527 strlen (class_name) + 1 /* class name */ +
3528 LEB128_SIZE /* no. methods */ +
3529 LEB128_SIZE /* fully covered */ +
3530 LEB128_SIZE /* partially covered */
3533 ENTER_LOG (logbuffer, "coverage-class");
3534 emit_byte (logbuffer, TYPE_COVERAGE_CLASS | TYPE_COVERAGE);
3535 emit_string (logbuffer, assembly_name, strlen (assembly_name) + 1);
3536 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3537 emit_uvalue (logbuffer, number_of_methods);
3538 emit_uvalue (logbuffer, fully_covered);
3539 emit_uvalue (logbuffer, partially_covered);
3540 EXIT_LOG (logbuffer);
3542 safe_send (prof, logbuffer);
3544 g_free (class_name);
3548 get_coverage_for_image (MonoImage *image, int *number_of_methods, guint *fully_covered, int *partially_covered)
3550 MonoLockFreeQueue *image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3552 *number_of_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
3554 *fully_covered = count_queue (image_methods);
3558 // FIXME: We don't handle partially covered yet.
3559 *partially_covered = 0;
3563 build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
3565 MonoAssembly *assembly = (MonoAssembly *)value;
3566 MonoProfiler *prof = (MonoProfiler *)userdata;
3567 MonoImage *image = mono_assembly_get_image (assembly);
3568 LogBuffer *logbuffer;
3569 const char *name, *guid, *filename;
3570 int number_of_methods = 0, partially_covered = 0;
3571 guint fully_covered = 0;
3573 name = mono_image_get_name (image);
3574 guid = mono_image_get_guid (image);
3575 filename = mono_image_get_filename (image);
3577 name = name ? name : "";
3578 guid = guid ? guid : "";
3579 filename = filename ? filename : "";
3581 get_coverage_for_image (image, &number_of_methods, &fully_covered, &partially_covered);
3583 logbuffer = ensure_logbuf (
3584 EVENT_SIZE /* event */ +
3585 strlen (name) + 1 /* name */ +
3586 strlen (guid) + 1 /* guid */ +
3587 strlen (filename) + 1 /* file name */ +
3588 LEB128_SIZE /* no. methods */ +
3589 LEB128_SIZE /* fully covered */ +
3590 LEB128_SIZE /* partially covered */
3593 ENTER_LOG (logbuffer, "coverage-assemblies");
3594 emit_byte (logbuffer, TYPE_COVERAGE_ASSEMBLY | TYPE_COVERAGE);
3595 emit_string (logbuffer, name, strlen (name) + 1);
3596 emit_string (logbuffer, guid, strlen (guid) + 1);
3597 emit_string (logbuffer, filename, strlen (filename) + 1);
3598 emit_uvalue (logbuffer, number_of_methods);
3599 emit_uvalue (logbuffer, fully_covered);
3600 emit_uvalue (logbuffer, partially_covered);
3601 EXIT_LOG (logbuffer);
3603 safe_send (prof, logbuffer);
3607 dump_coverage (MonoProfiler *prof)
3609 if (!coverage_initialized)
3612 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Started dump\n");)
3615 mono_os_mutex_lock (&coverage_mutex);
3616 mono_conc_hashtable_foreach (coverage_assemblies, build_assembly_buffer, prof);
3617 mono_conc_hashtable_foreach (coverage_classes, build_class_buffer, prof);
3618 mono_conc_hashtable_foreach (coverage_methods, build_method_buffer, prof);
3619 mono_os_mutex_unlock (&coverage_mutex);
3621 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Finished dump\n");)
3625 process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method)
3630 if (!coverage_initialized)
3633 klass = mono_method_get_class (method);
3634 image = mono_class_get_image (klass);
3636 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)))
3639 mono_os_mutex_lock (&coverage_mutex);
3640 mono_conc_hashtable_insert (entered_methods, method, method);
3641 mono_os_mutex_unlock (&coverage_mutex);
3644 static MonoLockFreeQueueNode *
3645 create_method_node (MonoMethod *method)
3647 MethodNode *node = (MethodNode *)g_malloc (sizeof (MethodNode));
3648 mono_lock_free_queue_node_init ((MonoLockFreeQueueNode *) node, FALSE);
3649 node->method = method;
3651 return (MonoLockFreeQueueNode *) node;
3655 coverage_filter (MonoProfiler *prof, MonoMethod *method)
3660 MonoAssembly *assembly;
3661 MonoMethodHeader *header;
3662 guint32 iflags, flags, code_size;
3663 char *fqn, *classname;
3664 gboolean has_positive, found;
3665 MonoLockFreeQueue *image_methods, *class_methods;
3666 MonoLockFreeQueueNode *node;
3668 if (!coverage_initialized)
3671 COVERAGE_DEBUG(fprintf (stderr, "Coverage filter for %s\n", mono_method_get_name (method));)
3673 flags = mono_method_get_flags (method, &iflags);
3674 if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
3675 (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/)) {
3676 COVERAGE_DEBUG(fprintf (stderr, " Internal call or pinvoke - ignoring\n");)
3680 // Don't need to do anything else if we're already tracking this method
3681 if (mono_conc_hashtable_lookup (coverage_methods, method)) {
3682 COVERAGE_DEBUG(fprintf (stderr, " Already tracking\n");)
3686 klass = mono_method_get_class (method);
3687 image = mono_class_get_image (klass);
3689 // Don't handle coverage for the core assemblies
3690 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)) != NULL)
3693 if (prof->coverage_filters) {
3694 /* Check already filtered classes first */
3695 if (mono_conc_hashtable_lookup (filtered_classes, klass)) {
3696 COVERAGE_DEBUG(fprintf (stderr, " Already filtered\n");)
3700 classname = mono_type_get_name (mono_class_get_type (klass));
3702 fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
3704 COVERAGE_DEBUG(fprintf (stderr, " Looking for %s in filter\n", fqn);)
3705 // Check positive filters first
3706 has_positive = FALSE;
3708 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3709 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3711 if (filter [0] == '+') {
3712 filter = &filter [1];
3714 COVERAGE_DEBUG(fprintf (stderr, " Checking against +%s ...", filter);)
3716 if (strstr (fqn, filter) != NULL) {
3717 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3720 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3722 has_positive = TRUE;
3726 if (has_positive && !found) {
3727 COVERAGE_DEBUG(fprintf (stderr, " Positive match was not found\n");)
3729 mono_os_mutex_lock (&coverage_mutex);
3730 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3731 mono_os_mutex_unlock (&coverage_mutex);
3738 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3739 // FIXME: Is substring search sufficient?
3740 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3741 if (filter [0] == '+')
3745 filter = &filter [1];
3746 COVERAGE_DEBUG(fprintf (stderr, " Checking against -%s ...", filter);)
3748 if (strstr (fqn, filter) != NULL) {
3749 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3751 mono_os_mutex_lock (&coverage_mutex);
3752 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3753 mono_os_mutex_unlock (&coverage_mutex);
3759 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3767 COVERAGE_DEBUG(fprintf (stderr, " Handling coverage for %s\n", mono_method_get_name (method));)
3768 header = mono_method_get_header_checked (method, &error);
3769 mono_error_cleanup (&error);
3771 mono_method_header_get_code (header, &code_size, NULL);
3773 assembly = mono_image_get_assembly (image);
3775 mono_os_mutex_lock (&coverage_mutex);
3776 mono_conc_hashtable_insert (coverage_methods, method, method);
3777 mono_conc_hashtable_insert (coverage_assemblies, assembly, assembly);
3778 mono_os_mutex_unlock (&coverage_mutex);
3780 image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3782 if (image_methods == NULL) {
3783 image_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
3784 mono_lock_free_queue_init (image_methods);
3785 mono_os_mutex_lock (&coverage_mutex);
3786 mono_conc_hashtable_insert (image_to_methods, image, image_methods);
3787 mono_os_mutex_unlock (&coverage_mutex);
3790 node = create_method_node (method);
3791 mono_lock_free_queue_enqueue (image_methods, node);
3793 class_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (coverage_classes, klass);
3795 if (class_methods == NULL) {
3796 class_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
3797 mono_lock_free_queue_init (class_methods);
3798 mono_os_mutex_lock (&coverage_mutex);
3799 mono_conc_hashtable_insert (coverage_classes, klass, class_methods);
3800 mono_os_mutex_unlock (&coverage_mutex);
3803 node = create_method_node (method);
3804 mono_lock_free_queue_enqueue (class_methods, node);
3809 #define LINE_BUFFER_SIZE 4096
3810 /* Max file limit of 128KB */
3811 #define MAX_FILE_SIZE 128 * 1024
3813 get_file_content (FILE *stream)
3818 int res, offset = 0;
3820 res = fseek (stream, 0, SEEK_END);
3824 filesize = ftell (stream);
3828 res = fseek (stream, 0, SEEK_SET);
3832 if (filesize > MAX_FILE_SIZE)
3835 buffer = (char *)g_malloc ((filesize + 1) * sizeof (char));
3836 while ((bytes_read = fread (buffer + offset, 1, LINE_BUFFER_SIZE, stream)) > 0)
3837 offset += bytes_read;
3839 /* NULL terminate our buffer */
3840 buffer[filesize] = '\0';
3845 get_next_line (char *contents, char **next_start)
3849 if (p == NULL || *p == '\0') {
3854 while (*p != '\n' && *p != '\0')
3859 *next_start = p + 1;
3867 init_suppressed_assemblies (void)
3873 suppressed_assemblies = mono_conc_hashtable_new (g_str_hash, g_str_equal);
3874 sa_file = fopen (SUPPRESSION_DIR "/mono-profiler-log.suppression", "r");
3875 if (sa_file == NULL)
3878 /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
3879 content = get_file_content (sa_file);
3880 if (content == NULL) {
3881 g_error ("mono-profiler-log.suppression is greater than 128kb - aborting\n");
3884 while ((line = get_next_line (content, &content))) {
3885 line = g_strchomp (g_strchug (line));
3886 /* No locking needed as we're doing initialization */
3887 mono_conc_hashtable_insert (suppressed_assemblies, line, line);
3893 #endif /* DISABLE_HELPER_THREAD */
3896 coverage_init (MonoProfiler *prof)
3898 #ifndef DISABLE_HELPER_THREAD
3899 assert (!coverage_initialized);
3901 COVERAGE_DEBUG(fprintf (stderr, "Coverage initialized\n");)
3903 mono_os_mutex_init (&coverage_mutex);
3904 coverage_methods = mono_conc_hashtable_new (NULL, NULL);
3905 coverage_assemblies = mono_conc_hashtable_new (NULL, NULL);
3906 coverage_classes = mono_conc_hashtable_new (NULL, NULL);
3907 filtered_classes = mono_conc_hashtable_new (NULL, NULL);
3908 entered_methods = mono_conc_hashtable_new (NULL, NULL);
3909 image_to_methods = mono_conc_hashtable_new (NULL, NULL);
3910 init_suppressed_assemblies ();
3912 coverage_initialized = TRUE;
3913 #endif /* DISABLE_HELPER_THREAD */
3917 log_shutdown (MonoProfiler *prof)
3922 #ifndef DISABLE_HELPER_THREAD
3923 counters_and_perfcounters_sample (prof);
3925 dump_coverage (prof);
3927 if (prof->command_port) {
3929 ign_res (write (prof->pipes [1], &c, 1));
3930 pthread_join (prof->helper_thread, &res);
3936 for (i = 0; i < num_perf; ++i)
3937 read_perf_mmap (prof, i);
3941 g_ptr_array_free (prof->sorted_sample_events, TRUE);
3943 if (TLS_GET (LogBuffer, tlsbuffer))
3944 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
3946 TLS_SET (tlsbuffer, NULL);
3947 TLS_SET (tlsmethodlist, NULL);
3949 InterlockedWrite (&prof->run_writer_thread, 0);
3950 pthread_join (prof->writer_thread, &res);
3952 #if defined (HAVE_SYS_ZLIB)
3954 gzclose (prof->gzfile);
3956 if (prof->pipe_output)
3957 pclose (prof->file);
3959 fclose (prof->file);
3961 mono_conc_hashtable_destroy (prof->method_table);
3962 mono_os_mutex_destroy (&prof->method_table_mutex);
3964 if (coverage_initialized) {
3965 mono_conc_hashtable_destroy (coverage_methods);
3966 mono_conc_hashtable_destroy (coverage_assemblies);
3967 mono_conc_hashtable_destroy (coverage_classes);
3968 mono_conc_hashtable_destroy (filtered_classes);
3970 mono_conc_hashtable_destroy (entered_methods);
3971 mono_conc_hashtable_destroy (image_to_methods);
3972 mono_conc_hashtable_destroy (suppressed_assemblies);
3973 mono_os_mutex_destroy (&coverage_mutex);
3980 new_filename (const char* filename)
3982 time_t t = time (NULL);
3983 int pid = process_id ();
3988 int count_dates = 0;
3992 for (p = filename; *p; p++) {
4003 if (!count_dates && !count_pids)
4004 return pstrdup (filename);
4005 snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
4007 snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
4008 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
4009 s_date = strlen (time_buf);
4010 s_pid = strlen (pid_buf);
4011 d = res = (char *)malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
4012 for (p = filename; *p; p++) {
4019 strcpy (d, time_buf);
4022 } else if (*p == 'p') {
4023 strcpy (d, pid_buf);
4026 } else if (*p == '%') {
4038 //this is exposed by the JIT, but it's not meant to be a supported API for now.
4039 extern void mono_threads_attach_tools_thread (void);
4041 #ifndef DISABLE_HELPER_THREAD
4044 helper_thread (void* arg)
4046 MonoProfiler* prof = (MonoProfiler *)arg;
4050 MonoThread *thread = NULL;
4052 mono_threads_attach_tools_thread ();
4053 //fprintf (stderr, "Server listening\n");
4054 command_socket = -1;
4060 FD_SET (prof->server_socket, &rfds);
4061 max_fd = prof->server_socket;
4062 FD_SET (prof->pipes [0], &rfds);
4063 if (max_fd < prof->pipes [0])
4064 max_fd = prof->pipes [0];
4065 if (command_socket >= 0) {
4066 FD_SET (command_socket, &rfds);
4067 if (max_fd < command_socket)
4068 max_fd = command_socket;
4073 for ( i = 0; i < num_perf; ++i) {
4074 if (perf_data [i].perf_fd < 0)
4076 FD_SET (perf_data [i].perf_fd, &rfds);
4077 if (max_fd < perf_data [i].perf_fd)
4078 max_fd = perf_data [i].perf_fd;
4083 counters_and_perfcounters_sample (prof);
4087 len = select (max_fd + 1, &rfds, NULL, NULL, &tv);
4093 g_warning ("Error in proflog server: %s", strerror (errno));
4097 if (FD_ISSET (prof->pipes [0], &rfds)) {
4099 int r = read (prof->pipes [0], &c, 1);
4100 if (r == 1 && c == 0) {
4101 StatBuffer *sbufbase = prof->stat_buffers;
4103 if (!sbufbase->next)
4105 sbuf = sbufbase->next->next;
4106 sbufbase->next->next = NULL;
4108 fprintf (stderr, "stat buffer dump\n");
4110 dump_sample_hits (prof, sbuf);
4111 free_buffer (sbuf, sbuf->size);
4112 safe_send (prof, ensure_logbuf (0));
4116 /* time to shut down */
4117 dump_sample_hits (prof, prof->stat_buffers);
4119 mono_thread_detach (thread);
4121 fprintf (stderr, "helper shutdown\n");
4125 for ( i = 0; i < num_perf; ++i) {
4126 if (perf_data [i].perf_fd < 0)
4128 if (FD_ISSET (perf_data [i].perf_fd, &rfds))
4129 read_perf_mmap (prof, i);
4133 safe_send (prof, ensure_logbuf (0));
4139 for ( i = 0; i < num_perf; ++i) {
4140 if (perf_data [i].perf_fd < 0)
4142 if (FD_ISSET (perf_data [i].perf_fd, &rfds)) {
4143 read_perf_mmap (prof, i);
4144 safe_send (prof, ensure_logbuf (0));
4149 if (command_socket >= 0 && FD_ISSET (command_socket, &rfds)) {
4150 len = read (command_socket, buf, sizeof (buf) - 1);
4154 close (command_socket);
4155 command_socket = -1;
4159 if (strcmp (buf, "heapshot\n") == 0) {
4160 heapshot_requested = 1;
4161 //fprintf (stderr, "perform heapshot\n");
4162 if (InterlockedRead (&runtime_inited) && !thread) {
4163 thread = mono_thread_attach (mono_get_root_domain ());
4164 /*fprintf (stderr, "attached\n");*/
4167 process_requests (prof);
4168 mono_thread_detach (thread);
4174 if (!FD_ISSET (prof->server_socket, &rfds)) {
4177 command_socket = accept (prof->server_socket, NULL, NULL);
4178 if (command_socket < 0)
4180 //fprintf (stderr, "Accepted connection\n");
4186 start_helper_thread (MonoProfiler* prof)
4188 struct sockaddr_in server_address;
4191 if (pipe (prof->pipes) < 0) {
4192 fprintf (stderr, "Cannot create pipe\n");
4195 prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
4196 if (prof->server_socket < 0) {
4197 fprintf (stderr, "Cannot create server socket\n");
4200 memset (&server_address, 0, sizeof (server_address));
4201 server_address.sin_family = AF_INET;
4202 server_address.sin_addr.s_addr = INADDR_ANY;
4203 server_address.sin_port = htons (prof->command_port);
4204 if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) < 0) {
4205 fprintf (stderr, "Cannot bind server socket, port: %d: %s\n", prof->command_port, strerror (errno));
4206 close (prof->server_socket);
4209 if (listen (prof->server_socket, 1) < 0) {
4210 fprintf (stderr, "Cannot listen server socket\n");
4211 close (prof->server_socket);
4214 slen = sizeof (server_address);
4215 if (getsockname (prof->server_socket, (struct sockaddr *)&server_address, &slen) == 0) {
4216 prof->command_port = ntohs (server_address.sin_port);
4217 /*fprintf (stderr, "Assigned server port: %d\n", prof->command_port);*/
4220 r = pthread_create (&prof->helper_thread, NULL, helper_thread, prof);
4222 close (prof->server_socket);
4230 writer_thread (void *arg)
4232 MonoProfiler *prof = (MonoProfiler *)arg;
4234 mono_threads_attach_tools_thread ();
4238 while (InterlockedRead (&prof->run_writer_thread)) {
4239 WriterQueueEntry *entry;
4241 while ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&prof->writer_queue))) {
4242 LogBuffer *method_buffer = NULL;
4243 gboolean new_methods = FALSE;
4245 if (entry->methods->len)
4246 method_buffer = create_buffer ();
4249 * Encode the method events in a temporary log buffer that we
4250 * flush to disk before the main buffer, ensuring that all
4251 * methods have metadata emitted before they're referenced.
4253 for (guint i = 0; i < entry->methods->len; i++) {
4254 MethodInfo *info = (MethodInfo *)g_ptr_array_index (entry->methods, i);
4256 if (mono_conc_hashtable_lookup (prof->method_table, info->method))
4262 * Other threads use this hash table to get a general
4263 * idea of whether a method has already been emitted to
4264 * the stream. Due to the way we add to this table, it
4265 * can easily happen that multiple threads queue up the
4266 * same methods, but that's OK since eventually all
4267 * methods will be in this table and the thread-local
4268 * method lists will just be empty for the rest of the
4271 mono_os_mutex_lock (&prof->method_table_mutex);
4272 mono_conc_hashtable_insert (prof->method_table, info->method, info->method);
4273 mono_os_mutex_unlock (&prof->method_table_mutex);
4275 char *name = mono_method_full_name (info->method, 1);
4276 int nlen = strlen (name) + 1;
4277 void *cstart = info->ji ? mono_jit_info_get_code_start (info->ji) : NULL;
4278 int csize = info->ji ? mono_jit_info_get_code_size (info->ji) : 0;
4280 method_buffer = ensure_logbuf_inner (method_buffer,
4281 EVENT_SIZE /* event */ +
4282 LEB128_SIZE /* time */ +
4283 LEB128_SIZE /* method */ +
4284 LEB128_SIZE /* start */ +
4285 LEB128_SIZE /* size */ +
4289 emit_byte (method_buffer, TYPE_JIT | TYPE_METHOD);
4290 emit_time (method_buffer, info->time);
4291 emit_method_inner (method_buffer, info->method);
4292 emit_ptr (method_buffer, cstart);
4293 emit_value (method_buffer, csize);
4295 memcpy (method_buffer->cursor, name, nlen);
4296 method_buffer->cursor += nlen;
4302 g_ptr_array_free (entry->methods, TRUE);
4305 dump_buffer (prof, method_buffer);
4306 else if (method_buffer)
4307 free_buffer (method_buffer, method_buffer->size);
4309 dump_buffer (prof, entry->buffer);
4319 start_writer_thread (MonoProfiler* prof)
4321 InterlockedWrite (&prof->run_writer_thread, 1);
4323 return !pthread_create (&prof->writer_thread, NULL, writer_thread, prof);
4327 runtime_initialized (MonoProfiler *profiler)
4329 #ifndef DISABLE_HELPER_THREAD
4330 if (hs_mode_ondemand || need_helper_thread) {
4331 if (!start_helper_thread (profiler))
4332 profiler->command_port = 0;
4336 start_writer_thread (profiler);
4338 InterlockedWrite (&runtime_inited, 1);
4339 #ifndef DISABLE_HELPER_THREAD
4340 counters_init (profiler);
4341 counters_sample (profiler, 0);
4343 /* ensure the main thread data and startup are available soon */
4344 safe_send (profiler, ensure_logbuf (0));
4347 static MonoProfiler*
4348 create_profiler (const char *filename, GPtrArray *filters)
4352 int force_delete = 0;
4353 prof = (MonoProfiler *)calloc (1, sizeof (MonoProfiler));
4355 prof->command_port = command_port;
4356 if (filename && *filename == '-') {
4362 filename = "|mprof-report -";
4364 filename = "output.mlpd";
4365 nf = (char*)filename;
4367 nf = new_filename (filename);
4369 int s = strlen (nf) + 32;
4370 char *p = (char *)malloc (s);
4371 snprintf (p, s, "|mprof-report '--out=%s' -", nf);
4377 prof->file = popen (nf + 1, "w");
4378 prof->pipe_output = 1;
4379 } else if (*nf == '#') {
4380 int fd = strtol (nf + 1, NULL, 10);
4381 prof->file = fdopen (fd, "a");
4385 prof->file = fopen (nf, "wb");
4388 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
4391 #if defined (HAVE_SYS_ZLIB)
4393 prof->gzfile = gzdopen (fileno (prof->file), "wb");
4396 if (sample_type && !do_mono_sample)
4397 need_helper_thread = setup_perf_event ();
4399 /* FIXME: warn if different freq or sample type */
4403 if (do_mono_sample) {
4404 prof->stat_buffers = create_stat_buffer ();
4405 need_helper_thread = 1;
4407 if (do_counters && !need_helper_thread) {
4408 need_helper_thread = 1;
4411 prof->sorted_sample_events = g_ptr_array_sized_new (BUFFER_SIZE / SAMPLE_EVENT_SIZE_IN_SLOTS (0));
4413 #ifdef DISABLE_HELPER_THREAD
4414 if (hs_mode_ondemand)
4415 fprintf (stderr, "Ondemand heapshot unavailable on this arch.\n");
4418 fprintf (stderr, "Coverage unavailable on this arch.\n");
4422 mono_lock_free_queue_init (&prof->writer_queue);
4423 mono_os_mutex_init (&prof->method_table_mutex);
4424 prof->method_table = mono_conc_hashtable_new (NULL, NULL);
4427 coverage_init (prof);
4428 prof->coverage_filters = filters;
4430 prof->startup_time = current_time ();
4437 printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
4438 printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
4439 printf ("Options:\n");
4440 printf ("\thelp show this usage info\n");
4441 printf ("\t[no]alloc enable/disable recording allocation info\n");
4442 printf ("\t[no]calls enable/disable recording enter/leave method events\n");
4443 printf ("\theapshot[=MODE] record heap shot info (by default at each major collection)\n");
4444 printf ("\t MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
4445 printf ("\tcounters sample counters every 1s\n");
4446 printf ("\tsample[=TYPE] use statistical sampling mode (by default cycles/1000)\n");
4447 printf ("\t TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
4448 printf ("\t TYPE can be followed by /FREQUENCY\n");
4449 printf ("\ttime=fast use a faster (but more inaccurate) timer\n");
4450 printf ("\tmaxframes=NUM collect up to NUM stack frames\n");
4451 printf ("\tcalldepth=NUM ignore method events for call chain depth bigger than NUM\n");
4452 printf ("\toutput=FILENAME write the data to file FILENAME (-FILENAME to overwrite)\n");
4453 printf ("\toutput=|PROGRAM write the data to the stdin of PROGRAM\n");
4454 printf ("\t %%t is subtituted with date and time, %%p with the pid\n");
4455 printf ("\treport create a report instead of writing the raw data to a file\n");
4456 printf ("\tzip compress the output data\n");
4457 printf ("\tport=PORTNUM use PORTNUM for the listening command server\n");
4458 printf ("\tcoverage enable collection of code coverage data\n");
4459 printf ("\tcovfilter=ASSEMBLY add an assembly to the code coverage filters\n");
4460 printf ("\t add a + to include the assembly or a - to exclude it\n");
4461 printf ("\t filter=-mscorlib\n");
4462 printf ("\tcovfilter-file=FILE use FILE to generate the list of assemblies to be filtered\n");
4468 match_option (const char* p, const char *opt, char **rval)
4470 int len = strlen (opt);
4471 if (strncmp (p, opt, len) == 0) {
4473 if (p [len] == '=' && p [len + 1]) {
4474 const char *opt = p + len + 1;
4475 const char *end = strchr (opt, ',');
4483 val = (char *)malloc (l + 1);
4484 memcpy (val, opt, l);
4489 if (p [len] == 0 || p [len] == ',') {
4491 return p + len + (p [len] == ',');
4509 static const SampleMode sample_modes [] = {
4510 {"cycles", SAMPLE_CYCLES},
4511 {"instr", SAMPLE_INSTRUCTIONS},
4512 {"cachemiss", SAMPLE_CACHE_MISSES},
4513 {"cacherefs", SAMPLE_CACHE_REFS},
4514 {"branches", SAMPLE_BRANCHES},
4515 {"branchmiss", SAMPLE_BRANCH_MISSES},
4520 set_sample_mode (char* val, int allow_empty)
4523 char *maybe_freq = NULL;
4525 const SampleMode *smode = sample_modes;
4526 #ifndef USE_PERF_EVENTS
4529 if (allow_empty && !val) {
4530 sample_type = SAMPLE_CYCLES;
4534 if (strcmp (val, "mono") == 0) {
4536 sample_type = SAMPLE_CYCLES;
4540 for (smode = sample_modes; smode->name; smode++) {
4541 int l = strlen (smode->name);
4542 if (strncmp (val, smode->name, l) == 0) {
4543 sample_type = smode->sample_mode;
4544 maybe_freq = val + l;
4550 if (*maybe_freq == '/') {
4551 count = strtoul (maybe_freq + 1, &end, 10);
4552 if (maybe_freq + 1 == end)
4554 sample_freq = count;
4555 } else if (*maybe_freq != 0) {
4564 set_hsmode (char* val, int allow_empty)
4568 if (allow_empty && !val)
4570 if (strcmp (val, "ondemand") == 0) {
4571 hs_mode_ondemand = 1;
4575 count = strtoul (val, &end, 10);
4578 if (strcmp (end, "ms") == 0)
4580 else if (strcmp (end, "gc") == 0)
4588 * declaration to silence the compiler: this is the entry point that
4589 * mono will load from the shared library and call.
4592 mono_profiler_startup (const char *desc);
4595 mono_profiler_startup_log (const char *desc);
4598 * this is the entry point that will be used when the profiler
4599 * is embedded inside the main executable.
4602 mono_profiler_startup_log (const char *desc)
4604 mono_profiler_startup (desc);
4608 mono_profiler_startup (const char *desc)
4611 GPtrArray *filters = NULL;
4612 char *filename = NULL;
4616 int calls_enabled = 0;
4617 int allocs_enabled = 0;
4618 int only_counters = 0;
4619 int only_coverage = 0;
4620 int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
4621 MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
4622 MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
4623 MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS|
4624 MONO_PROFILE_INS_COVERAGE|MONO_PROFILE_APPDOMAIN_EVENTS|MONO_PROFILE_CONTEXT_EVENTS|
4625 MONO_PROFILE_ASSEMBLY_EVENTS;
4628 if (strncmp (p, "log", 3))
4633 for (; *p; p = opt) {
4639 if ((opt = match_option (p, "help", NULL)) != p) {
4643 if ((opt = match_option (p, "calls", NULL)) != p) {
4647 if ((opt = match_option (p, "nocalls", NULL)) != p) {
4648 events &= ~MONO_PROFILE_ENTER_LEAVE;
4652 if ((opt = match_option (p, "alloc", NULL)) != p) {
4656 if ((opt = match_option (p, "noalloc", NULL)) != p) {
4657 events &= ~MONO_PROFILE_ALLOCATIONS;
4660 if ((opt = match_option (p, "time", &val)) != p) {
4661 if (strcmp (val, "fast") == 0)
4663 else if (strcmp (val, "null") == 0)
4670 if ((opt = match_option (p, "report", NULL)) != p) {
4674 if ((opt = match_option (p, "debug", NULL)) != p) {
4678 if ((opt = match_option (p, "sampling-real", NULL)) != p) {
4679 sampling_mode = MONO_PROFILER_STAT_MODE_REAL;
4682 if ((opt = match_option (p, "sampling-process", NULL)) != p) {
4683 sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
4686 if ((opt = match_option (p, "heapshot", &val)) != p) {
4687 events &= ~MONO_PROFILE_ALLOCATIONS;
4688 events &= ~MONO_PROFILE_ENTER_LEAVE;
4691 set_hsmode (val, 1);
4694 if ((opt = match_option (p, "sample", &val)) != p) {
4695 events &= ~MONO_PROFILE_ALLOCATIONS;
4696 events &= ~MONO_PROFILE_ENTER_LEAVE;
4698 set_sample_mode (val, 1);
4701 if ((opt = match_option (p, "hsmode", &val)) != p) {
4702 fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
4703 set_hsmode (val, 0);
4706 if ((opt = match_option (p, "zip", NULL)) != p) {
4710 if ((opt = match_option (p, "output", &val)) != p) {
4714 if ((opt = match_option (p, "port", &val)) != p) {
4716 command_port = strtoul (val, &end, 10);
4720 if ((opt = match_option (p, "maxframes", &val)) != p) {
4722 num_frames = strtoul (val, &end, 10);
4723 if (num_frames > MAX_FRAMES)
4724 num_frames = MAX_FRAMES;
4726 notraces = num_frames == 0;
4729 if ((opt = match_option (p, "calldepth", &val)) != p) {
4731 max_call_depth = strtoul (val, &end, 10);
4735 if ((opt = match_option (p, "counters", NULL)) != p) {
4739 if ((opt = match_option (p, "countersonly", NULL)) != p) {
4743 if ((opt = match_option (p, "coverage", NULL)) != p) {
4745 events |= MONO_PROFILE_ENTER_LEAVE;
4746 debug_coverage = (g_getenv ("MONO_PROFILER_DEBUG_COVERAGE") != NULL);
4749 if ((opt = match_option (p, "onlycoverage", NULL)) != p) {
4753 if ((opt = match_option (p, "covfilter-file", &val)) != p) {
4755 char *line, *content;
4757 if (filters == NULL)
4758 filters = g_ptr_array_new ();
4760 filter_file = fopen (val, "r");
4761 if (filter_file == NULL) {
4762 fprintf (stderr, "Unable to open %s\n", val);
4766 /* Don't need to free content as it is referred to by the lines stored in @filters */
4767 content = get_file_content (filter_file);
4768 if (content == NULL)
4769 fprintf (stderr, "WARNING: %s is greater than 128kb - ignoring\n", val);
4771 while ((line = get_next_line (content, &content)))
4772 g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
4774 fclose (filter_file);
4777 if ((opt = match_option (p, "covfilter", &val)) != p) {
4778 if (filters == NULL)
4779 filters = g_ptr_array_new ();
4781 g_ptr_array_add (filters, val);
4789 if (calls_enabled) {
4790 events |= MONO_PROFILE_ENTER_LEAVE;
4794 events |= MONO_PROFILE_ALLOCATIONS;
4798 events = MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_INS_COVERAGE;
4800 utils_init (fast_time);
4802 prof = create_profiler (filename, filters);
4807 mono_profiler_install (prof, log_shutdown);
4808 mono_profiler_install_gc (gc_event, gc_resize);
4809 mono_profiler_install_allocation (gc_alloc);
4810 mono_profiler_install_gc_moves (gc_moves);
4811 mono_profiler_install_gc_roots (gc_handle, gc_roots);
4812 mono_profiler_install_appdomain (NULL, domain_loaded, NULL, domain_unloaded);
4813 mono_profiler_install_appdomain_name (domain_name);
4814 mono_profiler_install_context (context_loaded, context_unloaded);
4815 mono_profiler_install_class (NULL, class_loaded, NULL, class_unloaded);
4816 mono_profiler_install_module (NULL, image_loaded, NULL, image_unloaded);
4817 mono_profiler_install_assembly (NULL, assembly_loaded, assembly_unloaded, NULL);
4818 mono_profiler_install_thread (thread_start, thread_end);
4819 mono_profiler_install_thread_name (thread_name);
4820 mono_profiler_install_enter_leave (method_enter, method_leave);
4821 mono_profiler_install_jit_end (method_jitted);
4822 mono_profiler_install_code_buffer_new (code_buffer_new);
4823 mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
4824 mono_profiler_install_monitor (monitor_event);
4825 mono_profiler_install_runtime_initialized (runtime_initialized);
4827 mono_profiler_install_coverage_filter (coverage_filter);
4829 if (do_mono_sample && sample_type == SAMPLE_CYCLES && !only_counters) {
4830 events |= MONO_PROFILE_STATISTICAL;
4831 mono_profiler_set_statistical_mode (sampling_mode, 1000000 / sample_freq);
4832 mono_profiler_install_statistical (mono_sample_hit);
4835 mono_profiler_set_events ((MonoProfileFlags)events);
4837 TLS_INIT (tlsbuffer);
4838 TLS_INIT (tlsmethodlist);