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)
13 #include "../mini/jit.h"
14 #include <mono/metadata/profiler.h>
15 #include <mono/metadata/threads.h>
16 #include <mono/metadata/mono-gc.h>
17 #include <mono/metadata/debug-helpers.h>
18 #include <mono/metadata/mono-perfcounters.h>
19 #include <mono/metadata/appdomain.h>
20 #include <mono/metadata/assembly.h>
21 #include <mono/metadata/tokentype.h>
22 #include <mono/metadata/tabledefs.h>
23 #include <mono/utils/atomic.h>
24 #include <mono/utils/mono-membar.h>
25 #include <mono/utils/mono-counters.h>
26 #include <mono/utils/mono-os-mutex.h>
27 #include <mono/utils/mono-conc-hashtable.h>
28 #include <mono/utils/lock-free-queue.h>
36 #ifdef HAVE_SCHED_GETAFFINITY
41 #if defined(HOST_WIN32) || defined(DISABLE_SOCKETS)
42 #define DISABLE_HELPER_THREAD 1
51 #ifdef HAVE_EXECINFO_H
58 #ifndef DISABLE_HELPER_THREAD
59 #include <sys/types.h>
60 #include <sys/socket.h>
61 #include <netinet/in.h>
62 #include <sys/select.h>
71 #ifdef HAVE_SYS_STAT_H
78 #if defined (HAVE_SYS_ZLIB)
82 #if defined(__linux__)
85 #include <sys/syscall.h>
87 #ifdef ENABLE_PERF_EVENTS
88 #include <linux/perf_event.h>
90 #define USE_PERF_EVENTS 1
92 static int read_perf_mmap (MonoProfiler* prof, int cpu);
97 #define BUFFER_SIZE (4096 * 16)
99 /* Worst-case size in bytes of a 64-bit value encoded with LEB128. */
100 #define LEB128_SIZE 10
101 /* Size in bytes of the event ID prefix. */
104 static int nocalls = 0;
105 static int notraces = 0;
106 static int use_zip = 0;
107 static int do_report = 0;
108 static int do_heap_shot = 0;
109 static int max_call_depth = 100;
110 static volatile int runtime_inited = 0;
111 static int need_helper_thread = 0;
112 static int command_port = 0;
113 static int heapshot_requested = 0;
114 static int sample_type = 0;
115 static int sample_freq = 0;
116 static int do_mono_sample = 0;
117 static int in_shutdown = 0;
118 static int do_debug = 0;
119 static int do_counters = 0;
120 static int do_coverage = 0;
121 static gboolean debug_coverage = FALSE;
122 static MonoProfileSamplingMode sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
124 typedef struct _LogBuffer LogBuffer;
130 * The file is composed by a header followed by 0 or more buffers.
131 * Each buffer contains events that happened on a thread: for a given thread
132 * buffers that appear later in the file are guaranteed to contain events
133 * that happened later in time. Buffers from separate threads could be interleaved,
135 * Buffers are not required to be aligned.
138 * [id: 4 bytes] constant value: LOG_HEADER_ID
139 * [major: 1 byte] [minor: 1 byte] major and minor version of the log profiler
140 * [format: 1 byte] version of the data format for the rest of the file
141 * [ptrsize: 1 byte] size in bytes of a pointer in the profiled program
142 * [startup time: 8 bytes] time in milliseconds since the unix epoch when the program started
143 * [timer overhead: 4 bytes] approximate overhead in nanoseconds of the timer
144 * [flags: 4 bytes] file format flags, should be 0 for now
145 * [pid: 4 bytes] pid of the profiled process
146 * [port: 2 bytes] tcp port for server if != 0
147 * [sysid: 2 bytes] operating system and architecture identifier
149 * The multiple byte integers are in little-endian format.
152 * [buffer header] [event]*
153 * Buffers have a fixed-size header followed by 0 or more bytes of event data.
154 * Timing information and other values in the event data are usually stored
155 * as uleb128 or sleb128 integers. To save space, as noted for each item below,
156 * some data is represented as a difference between the actual value and
157 * either the last value of the same type (like for timing information) or
158 * as the difference from a value stored in a buffer header.
160 * For timing information the data is stored as uleb128, since timing
161 * increases in a monotonic way in each thread: the value is the number of
162 * nanoseconds to add to the last seen timing data in a buffer. The first value
163 * in a buffer will be calculated from the time_base field in the buffer head.
165 * Object or heap sizes are stored as uleb128.
166 * Pointer differences are stored as sleb128, instead.
168 * If an unexpected value is found, the rest of the buffer should be ignored,
169 * as generally the later values need the former to be interpreted correctly.
171 * buffer header format:
172 * [bufid: 4 bytes] constant value: BUF_ID
173 * [len: 4 bytes] size of the data following the buffer header
174 * [time_base: 8 bytes] time base in nanoseconds since an unspecified epoch
175 * [ptr_base: 8 bytes] base value for pointers
176 * [obj_base: 8 bytes] base value for object addresses
177 * [thread id: 8 bytes] system-specific thread ID (pthread_t for example)
178 * [method_base: 8 bytes] base value for MonoMethod pointers
181 * [extended info: upper 4 bits] [type: lower 4 bits] [data]*
182 * The data that follows depends on type and the extended info.
183 * Type is one of the enum values in proflog.h: TYPE_ALLOC, TYPE_GC,
184 * TYPE_METADATA, TYPE_METHOD, TYPE_EXCEPTION, TYPE_MONITOR, TYPE_HEAP.
185 * The extended info bits are interpreted based on type, see
186 * each individual event description below.
187 * strings are represented as a 0-terminated utf8 sequence.
190 * [flags: uleb128] must be 0
191 * [num: uleb128] number of frames following
192 * [frame: sleb128]* num MonoMethod pointers as differences from ptr_base
196 * exinfo: flags: TYPE_ALLOC_BT
197 * [time diff: uleb128] nanoseconds since last timing
198 * [ptr: sleb128] class as a byte difference from ptr_base
199 * [obj: sleb128] object address as a byte difference from obj_base
200 * [size: uleb128] size of the object in the heap
201 * If the TYPE_ALLOC_BT flag is set, a backtrace follows.
205 * exinfo: one of TYPE_GC_EVENT, TYPE_GC_RESIZE, TYPE_GC_MOVE, TYPE_GC_HANDLE_CREATED[_BT],
206 * TYPE_GC_HANDLE_DESTROYED[_BT]
207 * [time diff: uleb128] nanoseconds since last timing
208 * if exinfo == TYPE_GC_RESIZE
209 * [heap_size: uleb128] new heap size
210 * if exinfo == TYPE_GC_EVENT
211 * [event type: uleb128] GC event (MONO_GC_EVENT_* from profiler.h)
212 * [generation: uleb128] GC generation event refers to
213 * if exinfo == TYPE_GC_MOVE
214 * [num_objects: uleb128] number of object moves that follow
215 * [objaddr: sleb128]+ num_objects object pointer differences from obj_base
216 * num is always an even number: the even items are the old
217 * addresses, the odd numbers are the respective new object addresses
218 * if exinfo == TYPE_GC_HANDLE_CREATED[_BT]
219 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
220 * upper bits reserved as flags
221 * [handle: uleb128] GC handle value
222 * [objaddr: sleb128] object pointer differences from obj_base
223 * If exinfo == TYPE_GC_HANDLE_CREATED_BT, a backtrace follows.
224 * if exinfo == TYPE_GC_HANDLE_DESTROYED[_BT]
225 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
226 * upper bits reserved as flags
227 * [handle: uleb128] GC handle value
228 * If exinfo == TYPE_GC_HANDLE_DESTROYED_BT, a backtrace follows.
230 * type metadata format:
231 * type: TYPE_METADATA
232 * exinfo: one of: TYPE_END_LOAD, TYPE_END_UNLOAD (optional for TYPE_THREAD and TYPE_DOMAIN)
233 * [time diff: uleb128] nanoseconds since last timing
234 * [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
235 * TYPE_THREAD, TYPE_CONTEXT
236 * [pointer: sleb128] pointer of the metadata type depending on mtype
237 * if mtype == TYPE_CLASS
238 * [image: sleb128] MonoImage* as a pointer difference from ptr_base
239 * [flags: uleb128] must be 0
240 * [name: string] full class name
241 * if mtype == TYPE_IMAGE
242 * [flags: uleb128] must be 0
243 * [name: string] image file name
244 * if mtype == TYPE_ASSEMBLY
245 * [flags: uleb128] must be 0
246 * [name: string] assembly name
247 * if mtype == TYPE_DOMAIN
248 * [flags: uleb128] must be 0
249 * if mtype == TYPE_DOMAIN && exinfo == 0
250 * [name: string] domain friendly name
251 * if mtype == TYPE_CONTEXT
252 * [flags: uleb128] must be 0
253 * [domain: sleb128] domain id as pointer
254 * if mtype == TYPE_THREAD && (format_version < 11 || (format_version > 10 && exinfo == 0))
255 * [flags: uleb128] must be 0
256 * [name: string] thread name
258 * type method format:
260 * exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
261 * [time diff: uleb128] nanoseconds since last timing
262 * [method: sleb128] MonoMethod* as a pointer difference from the last such
263 * pointer or the buffer method_base
264 * if exinfo == TYPE_JIT
265 * [code address: sleb128] pointer to the native code as a diff from ptr_base
266 * [code size: uleb128] size of the generated code
267 * [name: string] full method name
269 * type runtime format:
271 * exinfo: one of: TYPE_JITHELPER
272 * [time diff: uleb128] nanoseconds since last timing
273 * if exinfo == TYPE_JITHELPER
274 * [type: uleb128] MonoProfilerCodeBufferType enum value
275 * [buffer address: sleb128] pointer to the native code as a diff from ptr_base
276 * [buffer size: uleb128] size of the generated code
277 * if type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE
278 * [name: string] buffer description name
280 * type monitor format:
282 * exinfo: TYPE_MONITOR_BT flag and one of: MONO_PROFILER_MONITOR_(CONTENTION|FAIL|DONE)
283 * [time diff: uleb128] nanoseconds since last timing
284 * [object: sleb128] the lock object as a difference from obj_base
285 * if exinfo.low3bits == MONO_PROFILER_MONITOR_CONTENTION
286 * If the TYPE_MONITOR_BT flag is set, a backtrace follows.
290 * exinfo: one of TYPE_HEAP_START, TYPE_HEAP_END, TYPE_HEAP_OBJECT, TYPE_HEAP_ROOT
291 * if exinfo == TYPE_HEAP_START
292 * [time diff: uleb128] nanoseconds since last timing
293 * if exinfo == TYPE_HEAP_END
294 * [time diff: uleb128] nanoseconds since last timing
295 * if exinfo == TYPE_HEAP_OBJECT
296 * [object: sleb128] the object as a difference from obj_base
297 * [class: sleb128] the object MonoClass* as a difference from ptr_base
298 * [size: uleb128] size of the object on the heap
299 * [num_refs: uleb128] number of object references
300 * if (format version > 1) each referenced objref is preceded by a
301 * uleb128 encoded offset: the first offset is from the object address
302 * and each next offset is relative to the previous one
303 * [objrefs: sleb128]+ object referenced as a difference from obj_base
304 * The same object can appear multiple times, but only the first time
305 * with size != 0: in the other cases this data will only be used to
306 * provide additional referenced objects.
307 * if exinfo == TYPE_HEAP_ROOT
308 * [num_roots: uleb128] number of root references
309 * [num_gc: uleb128] number of major gcs
310 * [object: sleb128] the object as a difference from obj_base
311 * [root_type: uleb128] the root_type: MonoProfileGCRootType (profiler.h)
312 * [extra_info: uleb128] the extra_info value
313 * object, root_type and extra_info are repeated num_roots times
317 * exinfo: one of TYPE_SAMPLE_HIT, TYPE_SAMPLE_USYM, TYPE_SAMPLE_UBIN, TYPE_SAMPLE_COUNTERS_DESC, TYPE_SAMPLE_COUNTERS
318 * if exinfo == TYPE_SAMPLE_HIT
319 * [sample_type: uleb128] type of sample (SAMPLE_*)
320 * [timestamp: uleb128] nanoseconds since startup (note: different from other timestamps!)
321 * if (format_version > 10)
322 * [thread: sleb128] thread id as difference from ptr_base
323 * [count: uleb128] number of following instruction addresses
324 * [ip: sleb128]* instruction pointer as difference from ptr_base
325 * if (format_version > 5)
326 * [mbt_count: uleb128] number of managed backtrace info triplets (method + IL offset + native offset)
327 * [method: sleb128]* MonoMethod* as a pointer difference from the last such
328 * pointer or the buffer method_base (the first such method can be also indentified by ip, but this is not neccessarily true)
329 * [il_offset: sleb128]* IL offset inside method where the hit occurred
330 * [native_offset: sleb128]* native offset inside method where the hit occurred
331 * if exinfo == TYPE_SAMPLE_USYM
332 * [address: sleb128] symbol address as a difference from ptr_base
333 * [size: uleb128] symbol size (may be 0 if unknown)
334 * [name: string] symbol name
335 * if exinfo == TYPE_SAMPLE_UBIN
336 * [time diff: uleb128] nanoseconds since last timing
337 * [address: sleb128] address where binary has been loaded
338 * [offset: uleb128] file offset of mapping (the same file can be mapped multiple times)
339 * [size: uleb128] memory size
340 * [name: string] binary name
341 * if exinfo == TYPE_SAMPLE_COUNTERS_DESC
342 * [len: uleb128] number of counters
344 * [section: uleb128] section of counter
345 * if section == MONO_COUNTER_PERFCOUNTERS:
346 * [section_name: string] section name of counter
347 * [name: string] name of counter
348 * [type: uleb128] type of counter
349 * [unit: uleb128] unit of counter
350 * [variance: uleb128] variance of counter
351 * [index: uleb128] unique index of counter
352 * if exinfo == TYPE_SAMPLE_COUNTERS
353 * [timestamp: uleb128] sampling timestamp
355 * [index: uleb128] unique index of counter
358 * [type: uleb128] type of counter value
361 * [0: uleb128] 0 -> value is null
363 * [1: uleb128] 1 -> value is not null
364 * [value: string] counter value
366 * [value: uleb128/sleb128/double] counter value, can be sleb128, uleb128 or double (determined by using type)
368 * type coverage format
369 * type: TYPE_COVERAGE
370 * exinfo: one of TYPE_COVERAGE_METHOD, TYPE_COVERAGE_STATEMENT, TYPE_COVERAGE_ASSEMBLY, TYPE_COVERAGE_CLASS
371 * if exinfo == TYPE_COVERAGE_METHOD
372 * [assembly: string] name of assembly
373 * [class: string] name of the class
374 * [name: string] name of the method
375 * [signature: string] the signature of the method
376 * [filename: string] the file path of the file that contains this method
377 * [token: uleb128] the method token
378 * [method_id: uleb128] an ID for this data to associate with the buffers of TYPE_COVERAGE_STATEMENTS
379 * [len: uleb128] the number of TYPE_COVERAGE_BUFFERS associated with this method
380 * if exinfo == TYPE_COVERAGE_STATEMENTS
381 * [method_id: uleb128] an the TYPE_COVERAGE_METHOD buffer to associate this with
382 * [offset: uleb128] the il offset relative to the previous offset
383 * [counter: uleb128] the counter for this instruction
384 * [line: uleb128] the line of filename containing this instruction
385 * [column: uleb128] the column containing this instruction
386 * if exinfo == TYPE_COVERAGE_ASSEMBLY
387 * [name: string] assembly name
388 * [guid: string] assembly GUID
389 * [filename: string] assembly filename
390 * [number_of_methods: uleb128] the number of methods in this assembly
391 * [fully_covered: uleb128] the number of fully covered methods
392 * [partially_covered: uleb128] the number of partially covered methods
393 * currently partially_covered will always be 0, and fully_covered is the
394 * number of methods that are fully and partially covered.
395 * if exinfo == TYPE_COVERAGE_CLASS
396 * [name: string] assembly name
397 * [class: string] class name
398 * [number_of_methods: uleb128] the number of methods in this class
399 * [fully_covered: uleb128] the number of fully covered methods
400 * [partially_covered: uleb128] the number of partially covered methods
401 * currently partially_covered will always be 0, and fully_covered is the
402 * number of methods that are fully and partially covered.
406 * Format oddities that we ought to fix:
408 * - Methods written in emit_bt () should be based on the buffer's base
409 * method instead of the base pointer.
410 * - The TYPE_SAMPLE_HIT event contains (currently) pointless data like
411 * always-one unmanaged frame count and always-zero IL offsets.
413 * These are mostly small things and are not worth a format change by
414 * themselves. They should be done when some other major change has to
415 * be done to the format.
418 // Pending data to be written to the log, for a single thread.
419 // Threads periodically flush their own LogBuffers by calling safe_send
421 // Next (older) LogBuffer in processing queue
427 uintptr_t method_base;
428 uintptr_t last_method;
434 // Bytes allocated for this LogBuffer
437 // Start of currently unused space in buffer
438 unsigned char* cursor;
440 // Pointer to start-of-structure-plus-size (for convenience)
441 unsigned char* buf_end;
443 // Start of data in buffer. Contents follow "buffer format" described above.
444 unsigned char buf [1];
448 ign_res (int G_GNUC_UNUSED unused, ...)
452 #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++;}
453 #define EXIT_LOG(lb) (lb)->locked--;
455 // Shared queue of sample snapshots taken at signal time.
456 // The queue is written into by signal handlers for all threads;
457 // the helper thread later unqueues and writes into its own LogBuffer.
458 typedef struct _StatBuffer StatBuffer;
460 // Next (older) StatBuffer in processing queue
463 // Bytes allocated for this StatBuffer
466 // Start of currently unused space in buffer
469 // Pointer to start-of-structure-plus-size (for convenience)
472 // Start of data in buffer.
473 // Data consists of a series of sample packets consisting of:
474 // 1 ptrword: Metadata
475 // Low 8 bits: COUNT, the count of native stack frames in this sample (currently always 1)
476 // Next 8 bits: MBT_COUNT, the count of managed stacks in this sample
477 // Next 8 bits: TYPE. See "sampling sources" enum in proflog.h. Usually SAMPLE_CYCLES (1)
478 // 1 ptrword: Thread ID
479 // 1 ptrword: Timestamp
480 // COUNT ptrwords: Native stack frames
481 // Each word is an IP (first is IP where the signal did the interruption)
482 // MBT_COUNT * 4 ptrwords: Managed stack frames (AsyncFrameInfo, repacked)
483 // Word 1: MonoMethod ptr
484 // Word 2: MonoDomain ptr
485 // Word 3: Base address of method
486 // Word 4: Offset within method
490 typedef struct _BinaryObject BinaryObject;
492 struct _BinaryObject {
498 struct _MonoProfiler {
499 StatBuffer *stat_buffers;
501 #if defined (HAVE_SYS_ZLIB)
504 uint64_t startup_time;
506 int last_gc_gen_started;
511 pthread_t helper_thread;
512 pthread_t writer_thread;
514 volatile gint32 run_writer_thread;
515 MonoLockFreeQueue writer_queue;
516 MonoConcurrentHashTable *method_table;
517 mono_mutex_t method_table_mutex;
518 BinaryObject *binary_objects;
519 GPtrArray *coverage_filters;
520 GPtrArray *sorted_sample_events;
523 typedef struct _WriterQueueEntry WriterQueueEntry;
524 struct _WriterQueueEntry {
525 MonoLockFreeQueueNode node;
530 typedef struct _MethodInfo MethodInfo;
542 #define TLS_SET(x,y) (TlsSetValue (x, y))
543 #define TLS_GET(t,x) ((t *) TlsGetValue (x))
544 #define TLS_INIT(x) (x = TlsAlloc ())
545 static int tlsbuffer;
546 static int tlsmethodlist;
548 #define TLS_SET(x,y) (x = y)
549 #define TLS_GET(t,x) (x)
551 static __thread LogBuffer* tlsbuffer = NULL;
552 static __thread GPtrArray* tlsmethodlist = NULL;
554 #define TLS_SET(x,y) (pthread_setspecific (x, y))
555 #define TLS_GET(t,x) ((t *) pthread_getspecific (x))
556 #define TLS_INIT(x) (pthread_key_create (&x, NULL))
557 static pthread_key_t tlsbuffer;
558 static pthread_key_t tlsmethodlist;
561 static void safe_send (MonoProfiler *profiler, LogBuffer *logbuffer);
564 pstrdup (const char *s)
566 int len = strlen (s) + 1;
567 char *p = (char *)malloc (len);
573 create_stat_buffer (void)
575 StatBuffer* buf = (StatBuffer *)alloc_buffer (BUFFER_SIZE);
576 buf->size = BUFFER_SIZE;
577 buf->buf_end = (uintptr_t*)((unsigned char*)buf + buf->size);
578 buf->cursor = buf->buf;
585 LogBuffer* buf = (LogBuffer *)alloc_buffer (BUFFER_SIZE);
586 buf->size = BUFFER_SIZE;
587 buf->time_base = current_time ();
588 buf->last_time = buf->time_base;
589 buf->buf_end = (unsigned char*)buf + buf->size;
590 buf->cursor = buf->buf;
597 if (!TLS_GET (LogBuffer, tlsbuffer)) {
598 LogBuffer *logbuffer = create_buffer ();
599 TLS_SET (tlsbuffer, logbuffer);
600 logbuffer->thread_id = thread_id ();
602 if (!TLS_GET (GPtrArray, tlsmethodlist)) {
603 GPtrArray *methodlist = g_ptr_array_new ();
604 TLS_SET (tlsmethodlist, methodlist);
607 //printf ("thread %p at time %llu\n", (void*)logbuffer->thread_id, logbuffer->time_base);
611 ensure_logbuf_inner (LogBuffer *old, int bytes)
613 if (old && old->cursor + bytes + 100 < old->buf_end)
616 LogBuffer *new_ = (LogBuffer *)create_buffer ();
617 new_->thread_id = thread_id ();
621 new_->call_depth = old->call_depth;
627 ensure_logbuf (int bytes)
629 LogBuffer *old = TLS_GET (LogBuffer, tlsbuffer);
630 LogBuffer *new_ = ensure_logbuf_inner (old, bytes);
633 return old; // Still enough space.
635 TLS_SET (tlsbuffer, new_);
642 emit_byte (LogBuffer *logbuffer, int value)
644 logbuffer->cursor [0] = value;
646 assert (logbuffer->cursor <= logbuffer->buf_end);
650 emit_value (LogBuffer *logbuffer, int value)
652 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
653 assert (logbuffer->cursor <= logbuffer->buf_end);
657 emit_time (LogBuffer *logbuffer, uint64_t value)
659 uint64_t tdiff = value - logbuffer->last_time;
660 //if (value < logbuffer->last_time)
661 // printf ("time went backwards\n");
662 //if (tdiff > 1000000)
663 // printf ("large time offset: %llu\n", tdiff);
664 encode_uleb128 (tdiff, logbuffer->cursor, &logbuffer->cursor);
665 /*if (tdiff != decode_uleb128 (p, &p))
666 printf ("incorrect encoding: %llu\n", tdiff);*/
667 logbuffer->last_time = value;
668 assert (logbuffer->cursor <= logbuffer->buf_end);
672 emit_svalue (LogBuffer *logbuffer, int64_t value)
674 encode_sleb128 (value, logbuffer->cursor, &logbuffer->cursor);
675 assert (logbuffer->cursor <= logbuffer->buf_end);
679 emit_uvalue (LogBuffer *logbuffer, uint64_t value)
681 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
682 assert (logbuffer->cursor <= logbuffer->buf_end);
686 emit_ptr (LogBuffer *logbuffer, void *ptr)
688 if (!logbuffer->ptr_base)
689 logbuffer->ptr_base = (uintptr_t)ptr;
690 emit_svalue (logbuffer, (intptr_t)ptr - logbuffer->ptr_base);
691 assert (logbuffer->cursor <= logbuffer->buf_end);
695 emit_method_inner (LogBuffer *logbuffer, void *method)
697 if (!logbuffer->method_base) {
698 logbuffer->method_base = (intptr_t)method;
699 logbuffer->last_method = (intptr_t)method;
701 encode_sleb128 ((intptr_t)((char*)method - (char*)logbuffer->last_method), logbuffer->cursor, &logbuffer->cursor);
702 logbuffer->last_method = (intptr_t)method;
703 assert (logbuffer->cursor <= logbuffer->buf_end);
713 find_method (MonoDomain *domain, void *user_data)
715 MethodSearch *search = user_data;
720 MonoJitInfo *ji = mono_get_jit_info_from_method (domain, search->method);
722 // It could be AOT'd, so we need to get it from the AOT runtime's cache.
724 void *ip = mono_aot_get_method (domain, search->method);
726 // Avoid a slow path in mono_jit_info_table_find ().
728 ji = mono_jit_info_table_find (domain, ip);
737 register_method_local (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji)
739 if (!mono_conc_hashtable_lookup (prof->method_table, method)) {
741 * FIXME: In some cases, we crash while looking up JIT info for AOT'd methods.
742 * This usually happens for static constructors. This code is disabled for now
743 * as we don't need this info for anything critical.
745 * https://bugzilla.xamarin.com/show_bug.cgi?id=35171
749 MethodSearch search = { method, NULL };
751 mono_domain_foreach (find_method, &search);
758 * FIXME: We can't always find JIT info for a generic shared method, especially
759 * if we obtained the MonoMethod during an async stack walk. For now, we deal
760 * with this by giving the generic shared method name and dummy code start/size
761 * information (i.e. zeroes).
765 MethodInfo *info = (MethodInfo *)malloc (sizeof (MethodInfo));
767 info->method = method;
769 info->time = current_time ();
771 g_ptr_array_add (TLS_GET (GPtrArray, tlsmethodlist), info);
776 emit_method (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
778 register_method_local (prof, method, NULL);
779 emit_method_inner (logbuffer, method);
783 emit_method_as_ptr (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
785 register_method_local (prof, method, NULL);
786 emit_ptr (logbuffer, method);
790 emit_obj (LogBuffer *logbuffer, void *ptr)
792 if (!logbuffer->obj_base)
793 logbuffer->obj_base = (uintptr_t)ptr >> 3;
794 emit_svalue (logbuffer, ((uintptr_t)ptr >> 3) - logbuffer->obj_base);
795 assert (logbuffer->cursor <= logbuffer->buf_end);
799 emit_string (LogBuffer *logbuffer, const char *str, size_t size)
803 for (; i < size; i++) {
806 emit_byte (logbuffer, str [i]);
809 emit_byte (logbuffer, '\0');
813 emit_double (LogBuffer *logbuffer, double value)
816 unsigned char buffer[8];
817 memcpy (buffer, &value, 8);
818 #if G_BYTE_ORDER == G_BIG_ENDIAN
819 for (i = 7; i >= 0; i--)
821 for (i = 0; i < 8; i++)
823 emit_byte (logbuffer, buffer[i]);
827 write_int16 (char *buf, int32_t value)
830 for (i = 0; i < 2; ++i) {
838 write_int32 (char *buf, int32_t value)
841 for (i = 0; i < 4; ++i) {
849 write_int64 (char *buf, int64_t value)
852 for (i = 0; i < 8; ++i) {
860 dump_header (MonoProfiler *profiler)
864 p = write_int32 (p, LOG_HEADER_ID);
865 *p++ = LOG_VERSION_MAJOR;
866 *p++ = LOG_VERSION_MINOR;
867 *p++ = LOG_DATA_VERSION;
868 *p++ = sizeof (void*);
869 p = write_int64 (p, ((uint64_t)time (NULL)) * 1000); /* startup time */
870 p = write_int32 (p, get_timer_overhead ()); /* timer overhead */
871 p = write_int32 (p, 0); /* flags */
872 p = write_int32 (p, process_id ()); /* pid */
873 p = write_int16 (p, profiler->command_port); /* port */
874 p = write_int16 (p, 0); /* opsystem */
875 #if defined (HAVE_SYS_ZLIB)
876 if (profiler->gzfile) {
877 gzwrite (profiler->gzfile, hbuf, p - hbuf);
879 fwrite (hbuf, p - hbuf, 1, profiler->file);
882 fwrite (hbuf, p - hbuf, 1, profiler->file);
883 fflush (profiler->file);
888 send_buffer (MonoProfiler *prof, GPtrArray *methods, LogBuffer *buffer)
890 WriterQueueEntry *entry = (WriterQueueEntry *)calloc (1, sizeof (WriterQueueEntry));
891 mono_lock_free_queue_node_init (&entry->node, FALSE);
892 entry->methods = methods;
893 entry->buffer = buffer;
894 mono_lock_free_queue_enqueue (&prof->writer_queue, &entry->node);
898 dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
903 dump_buffer (profiler, buf->next);
904 p = write_int32 (p, BUF_ID);
905 p = write_int32 (p, buf->cursor - buf->buf);
906 p = write_int64 (p, buf->time_base);
907 p = write_int64 (p, buf->ptr_base);
908 p = write_int64 (p, buf->obj_base);
909 p = write_int64 (p, buf->thread_id);
910 p = write_int64 (p, buf->method_base);
911 #if defined (HAVE_SYS_ZLIB)
912 if (profiler->gzfile) {
913 gzwrite (profiler->gzfile, hbuf, p - hbuf);
914 gzwrite (profiler->gzfile, buf->buf, buf->cursor - buf->buf);
917 fwrite (hbuf, p - hbuf, 1, profiler->file);
918 fwrite (buf->buf, buf->cursor - buf->buf, 1, profiler->file);
919 fflush (profiler->file);
920 #if defined (HAVE_SYS_ZLIB)
923 free_buffer (buf, buf->size);
927 process_requests (MonoProfiler *profiler)
929 if (heapshot_requested)
930 mono_gc_collect (mono_gc_max_generation ());
933 static void counters_init (MonoProfiler *profiler);
934 static void counters_sample (MonoProfiler *profiler, uint64_t timestamp);
937 * Can be called only at safe callback locations.
940 safe_send (MonoProfiler *profiler, LogBuffer *logbuffer)
942 /* We need the runtime initialized so that we have threads and hazard
943 * pointers available. Otherwise, the lock free queue will not work and
944 * there won't be a thread to process the data.
946 * While the runtime isn't initialized, we just accumulate data in the
947 * thread local buffer list.
949 if (!InterlockedRead (&runtime_inited))
952 int cd = logbuffer->call_depth;
954 send_buffer (profiler, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
956 TLS_SET (tlsbuffer, NULL);
957 TLS_SET (tlsmethodlist, NULL);
961 TLS_GET (LogBuffer, tlsbuffer)->call_depth = cd;
965 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
968 uintptr_t last_offset = 0;
969 //const char *name = mono_class_get_name (klass);
970 LogBuffer *logbuffer = ensure_logbuf (
971 EVENT_SIZE /* event */ +
972 LEB128_SIZE /* obj */ +
973 LEB128_SIZE /* klass */ +
974 LEB128_SIZE /* size */ +
975 LEB128_SIZE /* num */ +
977 LEB128_SIZE /* offset */ +
978 LEB128_SIZE /* ref */
981 emit_byte (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
982 emit_obj (logbuffer, obj);
983 emit_ptr (logbuffer, klass);
984 /* account for object alignment in the heap */
987 emit_value (logbuffer, size);
988 emit_value (logbuffer, num);
989 for (i = 0; i < num; ++i) {
990 emit_value (logbuffer, offsets [i] - last_offset);
991 last_offset = offsets [i];
992 emit_obj (logbuffer, refs [i]);
995 // printf ("obj: %p, klass: %s, refs: %d, size: %d\n", obj, name, (int)num, (int)size);
999 static unsigned int hs_mode_ms = 0;
1000 static unsigned int hs_mode_gc = 0;
1001 static unsigned int hs_mode_ondemand = 0;
1002 static unsigned int gc_count = 0;
1003 static uint64_t last_hs_time = 0;
1006 heap_walk (MonoProfiler *profiler)
1010 LogBuffer *logbuffer;
1013 logbuffer = ensure_logbuf (
1014 EVENT_SIZE /* event */ +
1015 LEB128_SIZE /* time */
1017 now = current_time ();
1018 if (hs_mode_ms && (now - last_hs_time)/1000000 >= hs_mode_ms)
1020 else if (hs_mode_gc && (gc_count % hs_mode_gc) == 0)
1022 else if (hs_mode_ondemand)
1023 do_walk = heapshot_requested;
1024 else if (!hs_mode_ms && !hs_mode_gc && profiler->last_gc_gen_started == mono_gc_max_generation ())
1029 heapshot_requested = 0;
1030 emit_byte (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
1031 emit_time (logbuffer, now);
1032 mono_gc_walk_heap (0, gc_reference, NULL);
1033 logbuffer = ensure_logbuf (
1034 EVENT_SIZE /* event */ +
1035 LEB128_SIZE /* time */
1037 now = current_time ();
1038 emit_byte (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
1039 emit_time (logbuffer, now);
1044 gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation) {
1046 LogBuffer *logbuffer = ensure_logbuf (
1047 EVENT_SIZE /* event */ +
1048 LEB128_SIZE /* time */ +
1049 LEB128_SIZE /* gc event */ +
1050 LEB128_SIZE /* generation */
1052 now = current_time ();
1053 ENTER_LOG (logbuffer, "gcevent");
1054 emit_byte (logbuffer, TYPE_GC_EVENT | TYPE_GC);
1055 emit_time (logbuffer, now);
1056 emit_value (logbuffer, ev);
1057 emit_value (logbuffer, generation);
1058 /* to deal with nested gen1 after gen0 started */
1059 if (ev == MONO_GC_EVENT_START) {
1060 profiler->last_gc_gen_started = generation;
1061 if (generation == mono_gc_max_generation ())
1064 if (ev == MONO_GC_EVENT_PRE_START_WORLD)
1065 heap_walk (profiler);
1066 EXIT_LOG (logbuffer);
1067 if (ev == MONO_GC_EVENT_POST_START_WORLD)
1068 safe_send (profiler, logbuffer);
1069 //printf ("gc event %d for generation %d\n", ev, generation);
1073 gc_resize (MonoProfiler *profiler, int64_t new_size) {
1075 LogBuffer *logbuffer = ensure_logbuf (
1076 EVENT_SIZE /* event */ +
1077 LEB128_SIZE /* time */ +
1078 LEB128_SIZE /* new size */
1080 now = current_time ();
1081 ENTER_LOG (logbuffer, "gcresize");
1082 emit_byte (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
1083 emit_time (logbuffer, now);
1084 emit_value (logbuffer, new_size);
1085 //printf ("gc resized to %lld\n", new_size);
1086 EXIT_LOG (logbuffer);
1089 #define MAX_FRAMES 32
1092 MonoMethod* methods [MAX_FRAMES];
1093 int32_t il_offsets [MAX_FRAMES];
1094 int32_t native_offsets [MAX_FRAMES];
1096 static int num_frames = MAX_FRAMES;
1099 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
1101 FrameData *frame = (FrameData *)data;
1102 if (method && frame->count < num_frames) {
1103 frame->il_offsets [frame->count] = il_offset;
1104 frame->native_offsets [frame->count] = native_offset;
1105 frame->methods [frame->count++] = method;
1106 //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
1108 return frame->count == num_frames;
1112 * a note about stack walks: they can cause more profiler events to fire,
1113 * so we need to make sure they don't happen after we started emitting an
1114 * event, hence the collect_bt/emit_bt split.
1117 collect_bt (FrameData *data)
1120 mono_stack_walk_no_il (walk_stack, data);
1124 emit_bt (MonoProfiler *prof, LogBuffer *logbuffer, FrameData *data)
1126 /* FIXME: this is actually tons of data and we should
1127 * just output it the first time and use an id the next
1129 if (data->count > num_frames)
1130 printf ("bad num frames: %d\n", data->count);
1131 emit_value (logbuffer, 0); /* flags */
1132 emit_value (logbuffer, data->count);
1133 //if (*p != data.count) {
1134 // 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);}
1135 while (data->count) {
1136 emit_method_as_ptr (prof, logbuffer, data->methods [--data->count]);
1141 gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1145 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces)? TYPE_ALLOC_BT: 0;
1147 LogBuffer *logbuffer;
1148 len = mono_object_get_size (obj);
1149 /* account for object alignment in the heap */
1154 logbuffer = ensure_logbuf (
1155 EVENT_SIZE /* event */ +
1156 LEB128_SIZE /* time */ +
1157 LEB128_SIZE /* klass */ +
1158 LEB128_SIZE /* obj */ +
1159 LEB128_SIZE /* size */ +
1161 LEB128_SIZE /* flags */ +
1162 LEB128_SIZE /* count */ +
1164 LEB128_SIZE /* method */
1168 now = current_time ();
1169 ENTER_LOG (logbuffer, "gcalloc");
1170 emit_byte (logbuffer, do_bt | TYPE_ALLOC);
1171 emit_time (logbuffer, now);
1172 emit_ptr (logbuffer, klass);
1173 emit_obj (logbuffer, obj);
1174 emit_value (logbuffer, len);
1176 emit_bt (prof, logbuffer, &data);
1177 EXIT_LOG (logbuffer);
1178 if (logbuffer->next)
1179 safe_send (prof, logbuffer);
1180 process_requests (prof);
1181 //printf ("gc alloc %s at %p\n", mono_class_get_name (klass), obj);
1185 gc_moves (MonoProfiler *prof, void **objects, int num)
1189 LogBuffer *logbuffer = ensure_logbuf (
1190 EVENT_SIZE /* event */ +
1191 LEB128_SIZE /* time */ +
1192 LEB128_SIZE /* num */ +
1194 LEB128_SIZE /* object */
1197 now = current_time ();
1198 ENTER_LOG (logbuffer, "gcmove");
1199 emit_byte (logbuffer, TYPE_GC_MOVE | TYPE_GC);
1200 emit_time (logbuffer, now);
1201 emit_value (logbuffer, num);
1202 for (i = 0; i < num; ++i)
1203 emit_obj (logbuffer, objects [i]);
1204 //printf ("gc moved %d objects\n", num/2);
1205 EXIT_LOG (logbuffer);
1209 gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
1212 LogBuffer *logbuffer = ensure_logbuf (
1213 EVENT_SIZE /* event */ +
1214 LEB128_SIZE /* num */ +
1215 LEB128_SIZE /* collections */ +
1217 LEB128_SIZE /* object */ +
1218 LEB128_SIZE /* root type */ +
1219 LEB128_SIZE /* extra info */
1222 ENTER_LOG (logbuffer, "gcroots");
1223 emit_byte (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
1224 emit_value (logbuffer, num);
1225 emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
1226 for (i = 0; i < num; ++i) {
1227 emit_obj (logbuffer, objects [i]);
1228 emit_value (logbuffer, root_types [i]);
1229 emit_value (logbuffer, extra_info [i]);
1231 EXIT_LOG (logbuffer);
1235 gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
1237 int do_bt = nocalls && InterlockedRead (&runtime_inited) && !notraces;
1244 LogBuffer *logbuffer = ensure_logbuf (
1245 EVENT_SIZE /* event */ +
1246 LEB128_SIZE /* time */ +
1247 LEB128_SIZE /* type */ +
1248 LEB128_SIZE /* handle */ +
1249 (op == MONO_PROFILER_GC_HANDLE_CREATED ? (
1250 LEB128_SIZE /* obj */
1253 LEB128_SIZE /* flags */ +
1254 LEB128_SIZE /* count */ +
1256 LEB128_SIZE /* method */
1261 now = current_time ();
1262 ENTER_LOG (logbuffer, "gchandle");
1264 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1265 emit_byte (logbuffer, (do_bt ? TYPE_GC_HANDLE_CREATED_BT : TYPE_GC_HANDLE_CREATED) | TYPE_GC);
1266 else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
1267 emit_byte (logbuffer, (do_bt ? TYPE_GC_HANDLE_DESTROYED_BT : TYPE_GC_HANDLE_DESTROYED) | TYPE_GC);
1269 g_assert_not_reached ();
1271 emit_time (logbuffer, now);
1272 emit_value (logbuffer, type);
1273 emit_value (logbuffer, handle);
1275 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1276 emit_obj (logbuffer, obj);
1279 emit_bt (prof, logbuffer, &data);
1281 EXIT_LOG (logbuffer);
1282 process_requests (prof);
1286 push_nesting (char *p, MonoClass *klass)
1291 nesting = mono_class_get_nesting_type (klass);
1293 p = push_nesting (p, nesting);
1297 name = mono_class_get_name (klass);
1298 nspace = mono_class_get_namespace (klass);
1301 p += strlen (nspace);
1311 type_name (MonoClass *klass)
1315 push_nesting (buf, klass);
1316 p = (char *)malloc (strlen (buf) + 1);
1322 image_loaded (MonoProfiler *prof, MonoImage *image, int result)
1327 LogBuffer *logbuffer;
1328 if (result != MONO_PROFILE_OK)
1330 name = mono_image_get_filename (image);
1331 nlen = strlen (name) + 1;
1332 logbuffer = ensure_logbuf (
1333 EVENT_SIZE /* event */ +
1334 LEB128_SIZE /* time */ +
1335 EVENT_SIZE /* type */ +
1336 LEB128_SIZE /* image */ +
1337 LEB128_SIZE /* flags */ +
1340 now = current_time ();
1341 ENTER_LOG (logbuffer, "image");
1342 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1343 emit_time (logbuffer, now);
1344 emit_byte (logbuffer, TYPE_IMAGE);
1345 emit_ptr (logbuffer, image);
1346 emit_value (logbuffer, 0); /* flags */
1347 memcpy (logbuffer->cursor, name, nlen);
1348 logbuffer->cursor += nlen;
1349 //printf ("loaded image %p (%s)\n", image, name);
1350 EXIT_LOG (logbuffer);
1351 if (logbuffer->next)
1352 safe_send (prof, logbuffer);
1353 process_requests (prof);
1357 image_unloaded (MonoProfiler *prof, MonoImage *image)
1359 const char *name = mono_image_get_filename (image);
1360 int nlen = strlen (name) + 1;
1361 LogBuffer *logbuffer = ensure_logbuf (
1362 EVENT_SIZE /* event */ +
1363 LEB128_SIZE /* time */ +
1364 EVENT_SIZE /* type */ +
1365 LEB128_SIZE /* image */ +
1366 LEB128_SIZE /* flags */ +
1369 uint64_t now = current_time ();
1371 ENTER_LOG (logbuffer, "image-unload");
1372 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1373 emit_time (logbuffer, now);
1374 emit_byte (logbuffer, TYPE_IMAGE);
1375 emit_ptr (logbuffer, image);
1376 emit_value (logbuffer, 0); /* flags */
1377 memcpy (logbuffer->cursor, name, nlen);
1378 logbuffer->cursor += nlen;
1379 EXIT_LOG (logbuffer);
1381 if (logbuffer->next)
1382 safe_send (prof, logbuffer);
1384 process_requests (prof);
1388 assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly, int result)
1390 if (result != MONO_PROFILE_OK)
1393 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1394 int nlen = strlen (name) + 1;
1395 LogBuffer *logbuffer = ensure_logbuf (
1396 EVENT_SIZE /* event */ +
1397 LEB128_SIZE /* time */ +
1398 EVENT_SIZE /* type */ +
1399 LEB128_SIZE /* assembly */ +
1400 LEB128_SIZE /* flags */ +
1403 uint64_t now = current_time ();
1405 ENTER_LOG (logbuffer, "assembly-load");
1406 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1407 emit_time (logbuffer, now);
1408 emit_byte (logbuffer, TYPE_ASSEMBLY);
1409 emit_ptr (logbuffer, assembly);
1410 emit_value (logbuffer, 0); /* flags */
1411 memcpy (logbuffer->cursor, name, nlen);
1412 logbuffer->cursor += nlen;
1413 EXIT_LOG (logbuffer);
1417 if (logbuffer->next)
1418 safe_send (prof, logbuffer);
1420 process_requests (prof);
1424 assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
1426 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1427 int nlen = strlen (name) + 1;
1428 LogBuffer *logbuffer = ensure_logbuf (
1429 EVENT_SIZE /* event */ +
1430 LEB128_SIZE /* time */ +
1431 EVENT_SIZE /* type */ +
1432 LEB128_SIZE /* assembly */ +
1433 LEB128_SIZE /* flags */ +
1436 uint64_t now = current_time ();
1438 ENTER_LOG (logbuffer, "assembly-unload");
1439 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1440 emit_time (logbuffer, now);
1441 emit_byte (logbuffer, TYPE_ASSEMBLY);
1442 emit_ptr (logbuffer, assembly);
1443 emit_value (logbuffer, 0); /* flags */
1444 memcpy (logbuffer->cursor, name, nlen);
1445 logbuffer->cursor += nlen;
1446 EXIT_LOG (logbuffer);
1450 if (logbuffer->next)
1451 safe_send (prof, logbuffer);
1453 process_requests (prof);
1457 class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
1463 LogBuffer *logbuffer;
1464 if (result != MONO_PROFILE_OK)
1466 if (InterlockedRead (&runtime_inited))
1467 name = mono_type_get_name (mono_class_get_type (klass));
1469 name = type_name (klass);
1470 nlen = strlen (name) + 1;
1471 image = mono_class_get_image (klass);
1472 logbuffer = ensure_logbuf (
1473 EVENT_SIZE /* event */ +
1474 LEB128_SIZE /* time */ +
1475 EVENT_SIZE /* type */ +
1476 LEB128_SIZE /* klass */ +
1477 LEB128_SIZE /* image */ +
1478 LEB128_SIZE /* flags */ +
1481 now = current_time ();
1482 ENTER_LOG (logbuffer, "class");
1483 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1484 emit_time (logbuffer, now);
1485 emit_byte (logbuffer, TYPE_CLASS);
1486 emit_ptr (logbuffer, klass);
1487 emit_ptr (logbuffer, image);
1488 emit_value (logbuffer, 0); /* flags */
1489 memcpy (logbuffer->cursor, name, nlen);
1490 logbuffer->cursor += nlen;
1491 //printf ("loaded class %p (%s)\n", klass, name);
1496 EXIT_LOG (logbuffer);
1497 if (logbuffer->next)
1498 safe_send (prof, logbuffer);
1499 process_requests (prof);
1503 class_unloaded (MonoProfiler *prof, MonoClass *klass)
1507 if (InterlockedRead (&runtime_inited))
1508 name = mono_type_get_name (mono_class_get_type (klass));
1510 name = type_name (klass);
1512 int nlen = strlen (name) + 1;
1513 MonoImage *image = mono_class_get_image (klass);
1514 LogBuffer *logbuffer = ensure_logbuf (
1515 EVENT_SIZE /* event */ +
1516 LEB128_SIZE /* time */ +
1517 EVENT_SIZE /* type */ +
1518 LEB128_SIZE /* klass */ +
1519 LEB128_SIZE /* image */ +
1520 LEB128_SIZE /* flags */ +
1523 uint64_t now = current_time ();
1525 ENTER_LOG (logbuffer, "class-unload");
1526 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1527 emit_time (logbuffer, now);
1528 emit_byte (logbuffer, TYPE_CLASS);
1529 emit_ptr (logbuffer, klass);
1530 emit_ptr (logbuffer, image);
1531 emit_value (logbuffer, 0); /* flags */
1532 memcpy (logbuffer->cursor, name, nlen);
1533 logbuffer->cursor += nlen;
1534 EXIT_LOG (logbuffer);
1541 if (logbuffer->next)
1542 safe_send (prof, logbuffer);
1544 process_requests (prof);
1547 #ifndef DISABLE_HELPER_THREAD
1548 static void process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method);
1549 #endif /* DISABLE_HELPER_THREAD */
1552 method_enter (MonoProfiler *prof, MonoMethod *method)
1554 uint64_t now = current_time ();
1556 #ifndef DISABLE_HELPER_THREAD
1557 process_method_enter_coverage (prof, method);
1558 #endif /* DISABLE_HELPER_THREAD */
1560 LogBuffer *logbuffer = ensure_logbuf (
1561 EVENT_SIZE /* event */ +
1562 LEB128_SIZE /* time */ +
1563 LEB128_SIZE /* method */
1565 if (logbuffer->call_depth++ > max_call_depth)
1567 ENTER_LOG (logbuffer, "enter");
1568 emit_byte (logbuffer, TYPE_ENTER | TYPE_METHOD);
1569 emit_time (logbuffer, now);
1570 emit_method (prof, logbuffer, method);
1571 EXIT_LOG (logbuffer);
1573 process_requests (prof);
1577 method_leave (MonoProfiler *prof, MonoMethod *method)
1580 LogBuffer *logbuffer = ensure_logbuf (
1581 EVENT_SIZE /* event */ +
1582 LEB128_SIZE /* time */ +
1583 LEB128_SIZE /* method */
1585 if (--logbuffer->call_depth > max_call_depth)
1587 now = current_time ();
1588 ENTER_LOG (logbuffer, "leave");
1589 emit_byte (logbuffer, TYPE_LEAVE | TYPE_METHOD);
1590 emit_time (logbuffer, now);
1591 emit_method (prof, logbuffer, method);
1592 EXIT_LOG (logbuffer);
1593 if (logbuffer->next)
1594 safe_send (prof, logbuffer);
1595 process_requests (prof);
1599 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
1602 LogBuffer *logbuffer;
1605 logbuffer = ensure_logbuf (
1606 EVENT_SIZE /* event */ +
1607 LEB128_SIZE /* time */ +
1608 LEB128_SIZE /* method */
1610 if (--logbuffer->call_depth > max_call_depth)
1612 now = current_time ();
1613 ENTER_LOG (logbuffer, "eleave");
1614 emit_byte (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
1615 emit_time (logbuffer, now);
1616 emit_method (prof, logbuffer, method);
1617 EXIT_LOG (logbuffer);
1618 process_requests (prof);
1622 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji, int result)
1624 if (result != MONO_PROFILE_OK)
1627 register_method_local (prof, method, ji);
1629 process_requests (prof);
1633 code_buffer_new (MonoProfiler *prof, void *buffer, int size, MonoProfilerCodeBufferType type, void *data)
1638 LogBuffer *logbuffer;
1639 if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
1640 name = (char *)data;
1641 nlen = strlen (name) + 1;
1646 logbuffer = ensure_logbuf (
1647 EVENT_SIZE /* event */ +
1648 LEB128_SIZE /* time */ +
1649 LEB128_SIZE /* type */ +
1650 LEB128_SIZE /* buffer */ +
1651 LEB128_SIZE /* size */ +
1656 now = current_time ();
1657 ENTER_LOG (logbuffer, "code buffer");
1658 emit_byte (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
1659 emit_time (logbuffer, now);
1660 emit_value (logbuffer, type);
1661 emit_ptr (logbuffer, buffer);
1662 emit_value (logbuffer, size);
1664 memcpy (logbuffer->cursor, name, nlen);
1665 logbuffer->cursor += nlen;
1667 EXIT_LOG (logbuffer);
1668 process_requests (prof);
1672 throw_exc (MonoProfiler *prof, MonoObject *object)
1674 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces)? TYPE_EXCEPTION_BT: 0;
1677 LogBuffer *logbuffer;
1680 logbuffer = ensure_logbuf (
1681 EVENT_SIZE /* event */ +
1682 LEB128_SIZE /* time */ +
1683 LEB128_SIZE /* object */ +
1685 LEB128_SIZE /* flags */ +
1686 LEB128_SIZE /* count */ +
1688 LEB128_SIZE /* method */
1692 now = current_time ();
1693 ENTER_LOG (logbuffer, "throw");
1694 emit_byte (logbuffer, do_bt | TYPE_EXCEPTION);
1695 emit_time (logbuffer, now);
1696 emit_obj (logbuffer, object);
1698 emit_bt (prof, logbuffer, &data);
1699 EXIT_LOG (logbuffer);
1700 process_requests (prof);
1704 clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
1707 LogBuffer *logbuffer = ensure_logbuf (
1708 EVENT_SIZE /* event */ +
1709 LEB128_SIZE /* time */ +
1710 LEB128_SIZE /* clause type */ +
1711 LEB128_SIZE /* clause num */ +
1712 LEB128_SIZE /* method */
1714 now = current_time ();
1715 ENTER_LOG (logbuffer, "clause");
1716 emit_byte (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
1717 emit_time (logbuffer, now);
1718 emit_value (logbuffer, clause_type);
1719 emit_value (logbuffer, clause_num);
1720 emit_method (prof, logbuffer, method);
1721 EXIT_LOG (logbuffer);
1723 process_requests (prof);
1727 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
1729 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION)? TYPE_MONITOR_BT: 0;
1732 LogBuffer *logbuffer;
1735 logbuffer = ensure_logbuf (
1736 EVENT_SIZE /* event */ +
1737 LEB128_SIZE /* time */ +
1738 LEB128_SIZE /* object */ +
1740 LEB128_SIZE /* flags */ +
1741 LEB128_SIZE /* count */ +
1743 LEB128_SIZE /* method */
1747 now = current_time ();
1748 ENTER_LOG (logbuffer, "monitor");
1749 emit_byte (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
1750 emit_time (logbuffer, now);
1751 emit_obj (logbuffer, object);
1753 emit_bt (profiler, logbuffer, &data);
1754 EXIT_LOG (logbuffer);
1755 process_requests (profiler);
1759 thread_start (MonoProfiler *prof, uintptr_t tid)
1761 //printf ("thread start %p\n", (void*)tid);
1764 LogBuffer *logbuffer = ensure_logbuf (
1765 EVENT_SIZE /* event */ +
1766 LEB128_SIZE /* time */ +
1767 EVENT_SIZE /* type */ +
1768 LEB128_SIZE /* tid */ +
1769 LEB128_SIZE /* flags */
1771 uint64_t now = current_time ();
1773 ENTER_LOG (logbuffer, "thread-start");
1774 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1775 emit_time (logbuffer, now);
1776 emit_byte (logbuffer, TYPE_THREAD);
1777 emit_ptr (logbuffer, (void*) tid);
1778 emit_value (logbuffer, 0); /* flags */
1779 EXIT_LOG (logbuffer);
1781 if (logbuffer->next)
1782 safe_send (prof, logbuffer);
1784 process_requests (prof);
1788 thread_end (MonoProfiler *prof, uintptr_t tid)
1790 if (TLS_GET (LogBuffer, tlsbuffer)) {
1791 LogBuffer *logbuffer = ensure_logbuf (
1792 EVENT_SIZE /* event */ +
1793 LEB128_SIZE /* time */ +
1794 EVENT_SIZE /* type */ +
1795 LEB128_SIZE /* tid */ +
1796 LEB128_SIZE /* flags */
1798 uint64_t now = current_time ();
1800 ENTER_LOG (logbuffer, "thread-end");
1801 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1802 emit_time (logbuffer, now);
1803 emit_byte (logbuffer, TYPE_THREAD);
1804 emit_ptr (logbuffer, (void*) tid);
1805 emit_value (logbuffer, 0); /* flags */
1806 EXIT_LOG (logbuffer);
1808 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), logbuffer);
1810 /* Don't process requests as the thread is detached from the runtime. */
1813 TLS_SET (tlsbuffer, NULL);
1814 TLS_SET (tlsmethodlist, NULL);
1818 domain_loaded (MonoProfiler *prof, MonoDomain *domain, int result)
1820 if (result != MONO_PROFILE_OK)
1823 LogBuffer *logbuffer = ensure_logbuf (
1824 EVENT_SIZE /* event */ +
1825 LEB128_SIZE /* time */ +
1826 EVENT_SIZE /* type */ +
1827 LEB128_SIZE /* domain id */ +
1828 LEB128_SIZE /* flags */
1830 uint64_t now = current_time ();
1832 ENTER_LOG (logbuffer, "domain-start");
1833 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1834 emit_time (logbuffer, now);
1835 emit_byte (logbuffer, TYPE_DOMAIN);
1836 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1837 emit_value (logbuffer, 0); /* flags */
1838 EXIT_LOG (logbuffer);
1840 if (logbuffer->next)
1841 safe_send (prof, logbuffer);
1843 process_requests (prof);
1847 domain_unloaded (MonoProfiler *prof, MonoDomain *domain)
1849 LogBuffer *logbuffer = ensure_logbuf (
1850 EVENT_SIZE /* event */ +
1851 LEB128_SIZE /* time */ +
1852 EVENT_SIZE /* type */ +
1853 LEB128_SIZE /* domain id */ +
1854 LEB128_SIZE /* flags */
1856 uint64_t now = current_time ();
1858 ENTER_LOG (logbuffer, "domain-end");
1859 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1860 emit_time (logbuffer, now);
1861 emit_byte (logbuffer, TYPE_DOMAIN);
1862 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1863 emit_value (logbuffer, 0); /* flags */
1864 EXIT_LOG (logbuffer);
1866 if (logbuffer->next)
1867 safe_send (prof, logbuffer);
1869 process_requests (prof);
1873 domain_name (MonoProfiler *prof, MonoDomain *domain, const char *name)
1875 int nlen = strlen (name) + 1;
1876 LogBuffer *logbuffer = ensure_logbuf (
1877 EVENT_SIZE /* event */ +
1878 LEB128_SIZE /* time */ +
1879 EVENT_SIZE /* type */ +
1880 LEB128_SIZE /* domain id */ +
1881 LEB128_SIZE /* flags */ +
1884 uint64_t now = current_time ();
1886 ENTER_LOG (logbuffer, "domain-name");
1887 emit_byte (logbuffer, TYPE_METADATA);
1888 emit_time (logbuffer, now);
1889 emit_byte (logbuffer, TYPE_DOMAIN);
1890 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1891 emit_value (logbuffer, 0); /* flags */
1892 memcpy (logbuffer->cursor, name, nlen);
1893 logbuffer->cursor += nlen;
1894 EXIT_LOG (logbuffer);
1896 if (logbuffer->next)
1897 safe_send (prof, logbuffer);
1899 process_requests (prof);
1903 context_loaded (MonoProfiler *prof, MonoAppContext *context)
1905 LogBuffer *logbuffer = ensure_logbuf (
1906 EVENT_SIZE /* event */ +
1907 LEB128_SIZE /* time */ +
1908 EVENT_SIZE /* type */ +
1909 LEB128_SIZE /* context id */ +
1910 LEB128_SIZE /* flags */ +
1911 LEB128_SIZE /* domain id */
1913 uint64_t now = current_time ();
1915 ENTER_LOG (logbuffer, "context-start");
1916 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1917 emit_time (logbuffer, now);
1918 emit_byte (logbuffer, TYPE_CONTEXT);
1919 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
1920 emit_value (logbuffer, 0); /* flags */
1921 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
1922 EXIT_LOG (logbuffer);
1924 if (logbuffer->next)
1925 safe_send (prof, logbuffer);
1927 process_requests (prof);
1931 context_unloaded (MonoProfiler *prof, MonoAppContext *context)
1933 LogBuffer *logbuffer = ensure_logbuf (
1934 EVENT_SIZE /* event */ +
1935 LEB128_SIZE /* time */ +
1936 EVENT_SIZE /* type */ +
1937 LEB128_SIZE /* context id */ +
1938 LEB128_SIZE /* flags */ +
1939 LEB128_SIZE /* domain id */
1941 uint64_t now = current_time ();
1943 ENTER_LOG (logbuffer, "context-end");
1944 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1945 emit_time (logbuffer, now);
1946 emit_byte (logbuffer, TYPE_CONTEXT);
1947 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
1948 emit_value (logbuffer, 0); /* flags */
1949 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
1950 EXIT_LOG (logbuffer);
1952 if (logbuffer->next)
1953 safe_send (prof, logbuffer);
1955 process_requests (prof);
1959 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
1961 int len = strlen (name) + 1;
1963 LogBuffer *logbuffer;
1964 logbuffer = ensure_logbuf (
1965 EVENT_SIZE /* event */ +
1966 LEB128_SIZE /* time */ +
1967 EVENT_SIZE /* type */ +
1968 LEB128_SIZE /* tid */ +
1969 LEB128_SIZE /* flags */ +
1972 now = current_time ();
1973 ENTER_LOG (logbuffer, "tname");
1974 emit_byte (logbuffer, TYPE_METADATA);
1975 emit_time (logbuffer, now);
1976 emit_byte (logbuffer, TYPE_THREAD);
1977 emit_ptr (logbuffer, (void*)tid);
1978 emit_value (logbuffer, 0); /* flags */
1979 memcpy (logbuffer->cursor, name, len);
1980 logbuffer->cursor += len;
1981 EXIT_LOG (logbuffer);
1983 if (logbuffer->next)
1984 safe_send (prof, logbuffer);
1986 process_requests (prof);
1998 AsyncFrameInfo *data;
2002 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
2004 AsyncFrameData *frame = (AsyncFrameData *)data;
2005 if (frame->count < num_frames) {
2006 frame->data [frame->count].method = method;
2007 frame->data [frame->count].domain = domain;
2008 frame->data [frame->count].base_address = base_address;
2009 frame->data [frame->count].offset = offset;
2010 // printf ("In %d at %p (dom %p) (native: %p)\n", frame->count, method, domain, base_address);
2013 return frame->count == num_frames;
2017 (type | frame count), tid, time, ip, [method, domain, base address, offset] * frames
2019 #define SAMPLE_EVENT_SIZE_IN_SLOTS(FRAMES) (4 + (FRAMES) * 4)
2022 mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
2025 AsyncFrameInfo frames [num_frames];
2026 AsyncFrameData bt_data = { 0, &frames [0]};
2028 uintptr_t *data, *new_data, *old_data;
2034 now = current_time ();
2036 mono_stack_walk_async_safe (&async_walk_stack, context, &bt_data);
2038 elapsed = (now - profiler->startup_time) / 10000;
2042 snprintf (buf, sizeof (buf), "hit at %p in thread %p after %llu ms\n", ip, (void*)thread_id (), (unsigned long long int)elapsed/100);
2044 ign_res (write (2, buf, len));
2046 sbuf = profiler->stat_buffers;
2049 /* flush the buffer at 1 second intervals */
2050 if (sbuf->cursor > sbuf->buf && (elapsed - sbuf->buf [2]) > 100000) {
2053 /* overflow: 400 slots is a big enough number to reduce the chance of losing this event if many
2054 * threads hit this same spot at the same time
2056 if (timedout || (sbuf->cursor + 400 >= sbuf->buf_end)) {
2057 StatBuffer *oldsb, *foundsb;
2058 sbuf = create_stat_buffer ();
2060 oldsb = profiler->stat_buffers;
2062 foundsb = (StatBuffer *)InterlockedCompareExchangePointer ((void * volatile*)&profiler->stat_buffers, sbuf, oldsb);
2063 } while (foundsb != oldsb);
2065 ign_res (write (2, "overflow\n", 9));
2066 /* notify the helper thread */
2067 if (sbuf->next->next) {
2069 ign_res (write (profiler->pipes [1], &c, 1));
2071 ign_res (write (2, "notify\n", 7));
2075 old_data = sbuf->cursor;
2076 new_data = old_data + SAMPLE_EVENT_SIZE_IN_SLOTS (bt_data.count);
2077 if (new_data > sbuf->buf_end)
2078 return; /* Not enough room in buf to hold this event-- lost event */
2079 data = (uintptr_t *)InterlockedCompareExchangePointer ((void * volatile*)&sbuf->cursor, new_data, old_data);
2080 } while (data != old_data);
2082 old_data [0] = 1 | (sample_type << 16) | (bt_data.count << 8);
2083 old_data [1] = thread_id ();
2084 old_data [2] = elapsed;
2085 old_data [3] = (uintptr_t)ip;
2086 for (i = 0; i < bt_data.count; ++i) {
2087 old_data [4 + 4 * i + 0] = (uintptr_t)frames [i].method;
2088 old_data [4 + 4 * i + 1] = (uintptr_t)frames [i].domain;
2089 old_data [4 + 4 * i + 2] = (uintptr_t)frames [i].base_address;
2090 old_data [4 + 4 * i + 3] = (uintptr_t)frames [i].offset;
2094 static uintptr_t *code_pages = 0;
2095 static int num_code_pages = 0;
2096 static int size_code_pages = 0;
2097 #define CPAGE_SHIFT (9)
2098 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
2099 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
2100 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
2103 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
2106 uintptr_t start_pos;
2107 start_pos = (page >> CPAGE_SHIFT) % hsize;
2110 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
2112 } else if (!hash [i]) {
2119 } while (i != start_pos);
2120 /* should not happen */
2121 printf ("failed code page store\n");
2126 add_code_pointer (uintptr_t ip)
2129 if (num_code_pages * 2 >= size_code_pages) {
2131 uintptr_t old_size = size_code_pages;
2132 size_code_pages *= 2;
2133 if (size_code_pages == 0)
2134 size_code_pages = 16;
2135 n = (uintptr_t *)calloc (sizeof (uintptr_t) * size_code_pages, 1);
2136 for (i = 0; i < old_size; ++i) {
2138 add_code_page (n, size_code_pages, code_pages [i]);
2144 num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
2147 /* ELF code crashes on some systems. */
2148 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2151 dump_ubin (const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
2154 LogBuffer *logbuffer;
2156 len = strlen (filename) + 1;
2157 now = current_time ();
2158 logbuffer = ensure_logbuf (
2159 EVENT_SIZE /* event */ +
2160 LEB128_SIZE /* time */ +
2161 LEB128_SIZE /* load address */ +
2162 LEB128_SIZE /* offset */ +
2163 LEB128_SIZE /* size */ +
2164 nlen /* file name */
2166 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
2167 emit_time (logbuffer, now);
2168 emit_svalue (logbuffer, load_addr);
2169 emit_uvalue (logbuffer, offset);
2170 emit_uvalue (logbuffer, size);
2171 memcpy (logbuffer->cursor, filename, len);
2172 logbuffer->cursor += len;
2177 dump_usym (const char *name, uintptr_t value, uintptr_t size)
2179 LogBuffer *logbuffer;
2181 len = strlen (name) + 1;
2182 logbuffer = ensure_logbuf (
2183 EVENT_SIZE /* event */ +
2184 LEB128_SIZE /* value */ +
2185 LEB128_SIZE /* size */ +
2188 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
2189 emit_ptr (logbuffer, (void*)value);
2190 emit_value (logbuffer, size);
2191 memcpy (logbuffer->cursor, name, len);
2192 logbuffer->cursor += len;
2195 /* ELF code crashes on some systems. */
2196 //#if defined(ELFMAG0)
2199 #if SIZEOF_VOID_P == 4
2200 #define ELF_WSIZE 32
2202 #define ELF_WSIZE 64
2205 #define ElfW(type) _ElfW (Elf, ELF_WSIZE, type)
2206 #define _ElfW(e,w,t) _ElfW_1 (e, w, _##t)
2207 #define _ElfW_1(e,w,t) e##w##t
2211 dump_elf_symbols (ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
2214 for (i = 0; i < num_symbols; ++i) {
2216 sym = strtab + symbols [i].st_name;
2217 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
2219 //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
2220 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
2225 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
2232 ElfW(Shdr) *sheader;
2233 ElfW(Shdr) *shstrtabh;
2234 ElfW(Shdr) *symtabh = NULL;
2235 ElfW(Shdr) *strtabh = NULL;
2236 ElfW(Sym) *symbols = NULL;
2240 fd = open (filename, O_RDONLY);
2243 if (fstat (fd, &statb) != 0) {
2247 file_size = statb.st_size;
2248 data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
2250 if (data == MAP_FAILED)
2253 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2254 header->e_ident [EI_MAG1] != ELFMAG1 ||
2255 header->e_ident [EI_MAG2] != ELFMAG2 ||
2256 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2257 munmap (data, file_size);
2260 sheader = (void*)((char*)data + header->e_shoff);
2261 shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
2262 strtab = (const char*)data + shstrtabh->sh_offset;
2263 for (i = 0; i < header->e_shnum; ++i) {
2264 //printf ("section header: %d\n", sheader->sh_type);
2265 if (sheader->sh_type == SHT_SYMTAB) {
2267 strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
2268 /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
2271 sheader = (void*)((char*)sheader + header->e_shentsize);
2273 if (!symtabh || !strtabh) {
2274 munmap (data, file_size);
2277 strtab = (const char*)data + strtabh->sh_offset;
2278 num_symbols = symtabh->sh_size / symtabh->sh_entsize;
2279 symbols = (void*)((char*)data + symtabh->sh_offset);
2280 dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
2281 munmap (data, file_size);
2286 /* ELF code crashes on some systems. */
2287 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2290 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
2292 MonoProfiler *prof = data;
2294 const char *filename;
2296 char *a = (void*)info->dlpi_addr;
2298 ElfW(Dyn) *dyn = NULL;
2299 ElfW(Sym) *symtab = NULL;
2300 ElfW(Word) *hash_table = NULL;
2301 ElfW(Ehdr) *header = NULL;
2302 const char* strtab = NULL;
2303 for (obj = prof->binary_objects; obj; obj = obj->next) {
2307 filename = info->dlpi_name;
2310 if (!info->dlpi_addr && !filename [0]) {
2311 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
2317 obj = calloc (sizeof (BinaryObject), 1);
2318 obj->addr = (void*)info->dlpi_addr;
2319 obj->name = pstrdup (filename);
2320 obj->next = prof->binary_objects;
2321 prof->binary_objects = obj;
2322 //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
2324 for (i = 0; i < info->dlpi_phnum; ++i) {
2325 //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);
2326 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
2327 header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2328 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2329 header->e_ident [EI_MAG1] != ELFMAG1 ||
2330 header->e_ident [EI_MAG2] != ELFMAG2 ||
2331 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2334 dump_ubin (filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
2335 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
2336 dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2339 if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
2341 if (!info->dlpi_name || !info->dlpi_name[0])
2345 for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
2346 if (dyn [i].d_tag == DT_SYMTAB) {
2347 if (symtab && do_debug)
2348 printf ("multiple symtabs: %d\n", i);
2349 symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
2350 } else if (dyn [i].d_tag == DT_HASH) {
2351 hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
2352 } else if (dyn [i].d_tag == DT_STRTAB) {
2353 strtab = (const char*)(a + dyn [i].d_un.d_ptr);
2358 num_sym = hash_table [1];
2359 dump_elf_symbols (symtab, num_sym, strtab, (void*)info->dlpi_addr);
2364 load_binaries (MonoProfiler *prof)
2366 dl_iterate_phdr (elf_dl_callback, prof);
2371 load_binaries (MonoProfiler *prof)
2378 symbol_for (uintptr_t code)
2381 void *ip = (void*)code;
2383 if (dladdr (ip, &di)) {
2385 return di.dli_sname;
2388 names = backtrace_symbols (&ip, 1);
2390 const char* p = names [0];
2401 dump_unmanaged_coderefs (MonoProfiler *prof)
2404 const char* last_symbol;
2405 uintptr_t addr, page_end;
2407 if (load_binaries (prof))
2409 for (i = 0; i < size_code_pages; ++i) {
2411 if (!code_pages [i] || code_pages [i] & 1)
2414 addr = CPAGE_ADDR (code_pages [i]);
2415 page_end = addr + CPAGE_SIZE;
2416 code_pages [i] |= 1;
2417 /* we dump the symbols for the whole page */
2418 for (; addr < page_end; addr += 16) {
2419 sym = symbol_for (addr);
2420 if (sym && sym == last_symbol)
2425 dump_usym (sym, addr, 0); /* let's not guess the size */
2426 //printf ("found symbol at %p: %s\n", (void*)addr, sym);
2432 compare_sample_events (gconstpointer a, gconstpointer b)
2434 uintptr_t tid1 = (*(uintptr_t **) a) [1];
2435 uintptr_t tid2 = (*(uintptr_t **) b) [1];
2437 return tid1 > tid2 ? 1 :
2443 dump_sample_hits (MonoProfiler *prof, StatBuffer *sbuf)
2445 LogBuffer *logbuffer;
2449 dump_sample_hits (prof, sbuf->next);
2450 free_buffer (sbuf->next, sbuf->next->size);
2454 g_ptr_array_set_size (prof->sorted_sample_events, 0);
2456 for (uintptr_t *sample = sbuf->buf; sample < sbuf->cursor;) {
2457 int count = sample [0] & 0xff;
2458 int mbt_count = (sample [0] & 0xff00) >> 8;
2460 if (sample + SAMPLE_EVENT_SIZE_IN_SLOTS (mbt_count) > sbuf->cursor)
2463 g_ptr_array_add (prof->sorted_sample_events, sample);
2465 sample += count + 3 + 4 * mbt_count;
2468 g_ptr_array_sort (prof->sorted_sample_events, compare_sample_events);
2470 for (guint sidx = 0; sidx < prof->sorted_sample_events->len; sidx++) {
2471 uintptr_t *sample = (uintptr_t *)g_ptr_array_index (prof->sorted_sample_events, sidx);
2472 int count = sample [0] & 0xff;
2473 int mbt_count = (sample [0] & 0xff00) >> 8;
2474 int type = sample [0] >> 16;
2475 uintptr_t *managed_sample_base = sample + count + 3;
2476 uintptr_t thread_id = sample [1];
2478 for (int i = 0; i < mbt_count; ++i) {
2479 MonoMethod *method = (MonoMethod*)managed_sample_base [i * 4 + 0];
2480 MonoDomain *domain = (MonoDomain*)managed_sample_base [i * 4 + 1];
2481 void *address = (void*)managed_sample_base [i * 4 + 2];
2485 MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *)address);
2488 managed_sample_base [i * 4 + 0] = (uintptr_t)mono_jit_info_get_method (ji);
2492 logbuffer = ensure_logbuf (
2493 EVENT_SIZE /* event */ +
2494 LEB128_SIZE /* type */ +
2495 LEB128_SIZE /* time */ +
2496 LEB128_SIZE /* tid */ +
2497 LEB128_SIZE /* count */ +
2499 LEB128_SIZE /* ip */
2501 LEB128_SIZE /* managed count */ +
2503 LEB128_SIZE /* method */ +
2504 LEB128_SIZE /* il offset */ +
2505 LEB128_SIZE /* native offset */
2508 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
2509 emit_value (logbuffer, type);
2510 emit_uvalue (logbuffer, prof->startup_time + (uint64_t)sample [2] * (uint64_t)10000);
2511 emit_ptr (logbuffer, (void *) thread_id);
2512 emit_value (logbuffer, count);
2513 for (int i = 0; i < count; ++i) {
2514 emit_ptr (logbuffer, (void*)sample [i + 3]);
2515 add_code_pointer (sample [i + 3]);
2518 sample += count + 3;
2519 /* new in data version 6 */
2520 emit_uvalue (logbuffer, mbt_count);
2521 for (int i = 0; i < mbt_count; ++i) {
2522 MonoMethod *method = (MonoMethod *) sample [i * 4 + 0];
2523 uintptr_t native_offset = sample [i * 4 + 3];
2525 emit_method (prof, logbuffer, method);
2526 emit_svalue (logbuffer, 0); /* il offset will always be 0 from now on */
2527 emit_svalue (logbuffer, native_offset);
2531 dump_unmanaged_coderefs (prof);
2537 mono_cpu_count (void)
2539 #ifdef PLATFORM_ANDROID
2540 /* Android tries really hard to save power by powering off CPUs on SMP phones which
2541 * means the normal way to query cpu count returns a wrong value with userspace API.
2542 * Instead we use /sys entries to query the actual hardware CPU count.
2545 char buffer[8] = {'\0'};
2546 int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
2547 /* Format of the /sys entry is a cpulist of indexes which in the case
2548 * of present is always of the form "0-(n-1)" when there is more than
2549 * 1 core, n being the number of CPU cores in the system. Otherwise
2550 * the value is simply 0
2552 if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
2553 count = strtol (((char*)buffer) + 2, NULL, 10);
2560 #if defined(HOST_ARM) || defined (HOST_ARM64)
2562 /* ARM platforms tries really hard to save power by powering off CPUs on SMP phones which
2563 * means the normal way to query cpu count returns a wrong value with userspace API. */
2565 #ifdef _SC_NPROCESSORS_CONF
2567 int count = sysconf (_SC_NPROCESSORS_CONF);
2575 #ifdef HAVE_SCHED_GETAFFINITY
2578 if (sched_getaffinity (getpid (), sizeof (set), &set) == 0)
2579 return CPU_COUNT (&set);
2582 #ifdef _SC_NPROCESSORS_ONLN
2584 int count = sysconf (_SC_NPROCESSORS_ONLN);
2590 #endif /* defined(HOST_ARM) || defined (HOST_ARM64) */
2596 size_t len = sizeof (int);
2599 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
2606 GetSystemInfo (&info);
2607 return info.dwNumberOfProcessors;
2616 unsigned int prev_pos;
2618 struct perf_event_mmap_page *page_desc;
2621 static PerfData *perf_data = NULL;
2622 static int num_perf;
2623 #define PERF_PAGES_SHIFT 4
2624 static int num_pages = 1 << PERF_PAGES_SHIFT;
2625 static unsigned int mmap_mask;
2628 struct perf_event_header h;
2638 perf_event_syscall (struct perf_event_attr *attr, pid_t pid, int cpu, int group_fd, unsigned long flags)
2640 attr->size = PERF_ATTR_SIZE_VER0;
2641 //printf ("perf attr size: %d\n", attr->size);
2642 #if defined(__x86_64__)
2643 return syscall(/*__NR_perf_event_open*/ 298, attr, pid, cpu, group_fd, flags);
2644 #elif defined(__i386__)
2645 return syscall(/*__NR_perf_event_open*/ 336, attr, pid, cpu, group_fd, flags);
2646 #elif defined(__arm__) || defined (__aarch64__)
2647 return syscall(/*__NR_perf_event_open*/ 364, attr, pid, cpu, group_fd, flags);
2654 setup_perf_map (PerfData *perf)
2656 perf->mmap_base = mmap (NULL, (num_pages + 1) * getpagesize (), PROT_READ|PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
2657 if (perf->mmap_base == MAP_FAILED) {
2659 printf ("failed mmap\n");
2662 perf->page_desc = perf->mmap_base;
2664 printf ("mmap version: %d\n", perf->page_desc->version);
2669 dump_perf_hits (MonoProfiler *prof, void *buf, int size)
2671 LogBuffer *logbuffer;
2674 void *end = (char*)buf + size;
2676 int pid = getpid ();
2682 if (pid != s->pid) {
2684 printf ("event for different pid: %d\n", s->pid);
2685 buf = (char*)buf + s->h.size;
2688 /*ip = (void*)s->ip;
2689 printf ("sample: %d, size: %d, ip: %p (%s), timestamp: %llu, nframes: %llu\n",
2690 s->h.type, s->h.size, ip, symbol_for (ip), s->timestamp, s->nframes);*/
2691 logbuffer = ensure_logbuf (
2692 EVENT_SIZE /* event */ +
2693 LEB128_SIZE /* type */ +
2694 LEB128_SIZE /* time */ +
2695 LEB128_SIZE /* tid */ +
2696 LEB128_SIZE /* count */ +
2698 LEB128_SIZE /* ip */
2700 LEB128_SIZE /* managed count */ +
2702 LEB128_SIZE /* method */ +
2703 LEB128_SIZE /* il offset */ +
2704 LEB128_SIZE /* native offset */
2707 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
2708 emit_value (logbuffer, sample_type);
2709 emit_uvalue (logbuffer, s->timestamp - prof->startup_time);
2711 * No useful thread ID to write here, since throughout the
2712 * profiler we use pthread_self () but the ID we get from
2713 * perf is the kernel's thread ID.
2715 emit_ptr (logbuffer, 0);
2716 emit_value (logbuffer, count);
2717 emit_ptr (logbuffer, (void*)(uintptr_t)s->ip);
2718 add_code_pointer (s->ip);
2719 /* no support here yet for the managed backtrace */
2720 emit_uvalue (logbuffer, mbt_count);
2721 buf = (char*)buf + s->h.size;
2725 printf ("dumped %d samples\n", samples);
2726 dump_unmanaged_coderefs (prof);
2729 /* read events from the ring buffer */
2731 read_perf_mmap (MonoProfiler* prof, int cpu)
2733 PerfData *perf = perf_data + cpu;
2735 unsigned char *data = (unsigned char*)perf->mmap_base + getpagesize ();
2736 unsigned int head = perf->page_desc->data_head;
2740 mono_memory_read_barrier ();
2742 old = perf->prev_pos;
2746 printf ("lost mmap events: old: %d, head: %d\n", old, head);
2750 if ((old & mmap_mask) + size != (head & mmap_mask)) {
2751 buf = data + (old & mmap_mask);
2752 size = mmap_mask + 1 - (old & mmap_mask);
2754 /* size bytes at buf */
2756 printf ("found1 bytes of events: %d\n", size);
2757 dump_perf_hits (prof, buf, size);
2759 buf = data + (old & mmap_mask);
2761 /* size bytes at buf */
2763 printf ("found bytes of events: %d\n", size);
2764 dump_perf_hits (prof, buf, size);
2766 perf->prev_pos = old;
2767 perf->page_desc->data_tail = old;
2772 setup_perf_event_for_cpu (PerfData *perf, int cpu)
2774 struct perf_event_attr attr;
2775 memset (&attr, 0, sizeof (attr));
2776 attr.type = PERF_TYPE_HARDWARE;
2777 switch (sample_type) {
2778 case SAMPLE_CYCLES: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2779 case SAMPLE_INSTRUCTIONS: attr.config = PERF_COUNT_HW_INSTRUCTIONS; break;
2780 case SAMPLE_CACHE_MISSES: attr.config = PERF_COUNT_HW_CACHE_MISSES; break;
2781 case SAMPLE_CACHE_REFS: attr.config = PERF_COUNT_HW_CACHE_REFERENCES; break;
2782 case SAMPLE_BRANCHES: attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS; break;
2783 case SAMPLE_BRANCH_MISSES: attr.config = PERF_COUNT_HW_BRANCH_MISSES; break;
2784 default: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2786 attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD | PERF_SAMPLE_TIME;
2787 // attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
2788 attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING | PERF_FORMAT_ID;
2791 attr.sample_freq = sample_freq;
2793 perf->perf_fd = perf_event_syscall (&attr, getpid (), cpu, -1, 0);
2795 printf ("perf fd: %d, freq: %d, event: %llu\n", perf->perf_fd, sample_freq, attr.config);
2796 if (perf->perf_fd < 0) {
2797 if (perf->perf_fd == -EPERM) {
2798 fprintf (stderr, "Perf syscall denied, do \"echo 1 > /proc/sys/kernel/perf_event_paranoid\" as root to enable.\n");
2801 perror ("open perf event");
2805 if (!setup_perf_map (perf)) {
2806 close (perf->perf_fd);
2814 setup_perf_event (void)
2817 mmap_mask = num_pages * getpagesize () - 1;
2818 num_perf = mono_cpu_count ();
2819 perf_data = calloc (num_perf, sizeof (PerfData));
2820 for (i = 0; i < num_perf; ++i) {
2821 count += setup_perf_event_for_cpu (perf_data + i, i);
2830 #endif /* USE_PERF_EVENTS */
2832 #ifndef DISABLE_HELPER_THREAD
2834 typedef struct MonoCounterAgent {
2835 MonoCounter *counter;
2836 // MonoCounterAgent specific data :
2841 struct MonoCounterAgent *next;
2844 static MonoCounterAgent* counters;
2845 static gboolean counters_initialized = FALSE;
2846 static int counters_index = 1;
2847 static mono_mutex_t counters_mutex;
2850 counters_add_agent (MonoCounter *counter)
2852 MonoCounterAgent *agent, *item;
2854 if (!counters_initialized)
2857 mono_os_mutex_lock (&counters_mutex);
2859 for (agent = counters; agent; agent = agent->next) {
2860 if (agent->counter == counter) {
2861 agent->value_size = 0;
2863 free (agent->value);
2864 agent->value = NULL;
2866 mono_os_mutex_unlock (&counters_mutex);
2871 agent = (MonoCounterAgent *)malloc (sizeof (MonoCounterAgent));
2872 agent->counter = counter;
2873 agent->value = NULL;
2874 agent->value_size = 0;
2875 agent->index = counters_index++;
2888 mono_os_mutex_unlock (&counters_mutex);
2892 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
2894 counters_add_agent (counter);
2899 counters_init (MonoProfiler *profiler)
2901 assert (!counters_initialized);
2903 mono_os_mutex_init (&counters_mutex);
2905 counters_initialized = TRUE;
2907 mono_counters_on_register (&counters_add_agent);
2908 mono_counters_foreach (counters_init_foreach_callback, NULL);
2912 counters_emit (MonoProfiler *profiler)
2914 MonoCounterAgent *agent;
2915 LogBuffer *logbuffer;
2918 EVENT_SIZE /* event */ +
2919 LEB128_SIZE /* len */
2922 if (!counters_initialized)
2925 mono_os_mutex_lock (&counters_mutex);
2927 for (agent = counters; agent; agent = agent->next) {
2932 LEB128_SIZE /* section */ +
2933 strlen (mono_counter_get_name (agent->counter)) + 1 /* name */ +
2934 LEB128_SIZE /* type */ +
2935 LEB128_SIZE /* unit */ +
2936 LEB128_SIZE /* variance */ +
2937 LEB128_SIZE /* index */
2944 mono_os_mutex_unlock (&counters_mutex);
2948 logbuffer = ensure_logbuf (size);
2950 ENTER_LOG (logbuffer, "counters");
2951 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2952 emit_value (logbuffer, len);
2953 for (agent = counters; agent; agent = agent->next) {
2959 name = mono_counter_get_name (agent->counter);
2960 emit_value (logbuffer, mono_counter_get_section (agent->counter));
2961 emit_string (logbuffer, name, strlen (name) + 1);
2962 emit_value (logbuffer, mono_counter_get_type (agent->counter));
2963 emit_value (logbuffer, mono_counter_get_unit (agent->counter));
2964 emit_value (logbuffer, mono_counter_get_variance (agent->counter));
2965 emit_value (logbuffer, agent->index);
2969 EXIT_LOG (logbuffer);
2971 safe_send (profiler, logbuffer);
2973 mono_os_mutex_unlock (&counters_mutex);
2977 counters_sample (MonoProfiler *profiler, uint64_t timestamp)
2979 MonoCounterAgent *agent;
2980 MonoCounter *counter;
2981 LogBuffer *logbuffer;
2987 if (!counters_initialized)
2990 counters_emit (profiler);
2993 buffer = calloc (1, buffer_size);
2995 mono_os_mutex_lock (&counters_mutex);
2998 EVENT_SIZE /* event */ +
2999 LEB128_SIZE /* time */
3002 for (agent = counters; agent; agent = agent->next) {
3004 LEB128_SIZE /* index */ +
3005 LEB128_SIZE /* type */ +
3006 mono_counter_get_size (agent->counter) /* value */
3011 LEB128_SIZE /* stop marker */
3014 logbuffer = ensure_logbuf (size);
3016 ENTER_LOG (logbuffer, "counters");
3017 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
3018 emit_uvalue (logbuffer, timestamp);
3019 for (agent = counters; agent; agent = agent->next) {
3022 counter = agent->counter;
3024 size = mono_counter_get_size (counter);
3026 continue; // FIXME error
3027 } else if (size > buffer_size) {
3029 buffer = realloc (buffer, buffer_size);
3032 memset (buffer, 0, buffer_size);
3034 if (mono_counters_sample (counter, buffer, size) < 0)
3035 continue; // FIXME error
3037 type = mono_counter_get_type (counter);
3039 if (!agent->value) {
3040 agent->value = calloc (1, size);
3041 agent->value_size = size;
3043 if (type == MONO_COUNTER_STRING) {
3044 if (strcmp (agent->value, buffer) == 0)
3047 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
3052 emit_uvalue (logbuffer, agent->index);
3053 emit_uvalue (logbuffer, type);
3055 case MONO_COUNTER_INT:
3056 #if SIZEOF_VOID_P == 4
3057 case MONO_COUNTER_WORD:
3059 emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
3061 case MONO_COUNTER_UINT:
3062 emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
3064 case MONO_COUNTER_TIME_INTERVAL:
3065 case MONO_COUNTER_LONG:
3066 #if SIZEOF_VOID_P == 8
3067 case MONO_COUNTER_WORD:
3069 emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
3071 case MONO_COUNTER_ULONG:
3072 emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
3074 case MONO_COUNTER_DOUBLE:
3075 emit_double (logbuffer, *(double*)buffer);
3077 case MONO_COUNTER_STRING:
3079 emit_byte (logbuffer, 0);
3081 emit_byte (logbuffer, 1);
3082 emit_string (logbuffer, (char*)buffer, size);
3089 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
3090 agent->value = realloc (agent->value, size);
3091 agent->value_size = size;
3095 memcpy (agent->value, buffer, size);
3099 emit_value (logbuffer, 0);
3100 EXIT_LOG (logbuffer);
3102 safe_send (profiler, logbuffer);
3104 mono_os_mutex_unlock (&counters_mutex);
3107 typedef struct _PerfCounterAgent PerfCounterAgent;
3108 struct _PerfCounterAgent {
3109 PerfCounterAgent *next;
3111 char *category_name;
3120 static PerfCounterAgent *perfcounters = NULL;
3123 perfcounters_emit (MonoProfiler *profiler)
3125 PerfCounterAgent *pcagent;
3126 LogBuffer *logbuffer;
3129 EVENT_SIZE /* event */ +
3130 LEB128_SIZE /* len */
3133 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3134 if (pcagent->emitted)
3138 LEB128_SIZE /* section */ +
3139 strlen (pcagent->category_name) + 1 /* category name */ +
3140 strlen (pcagent->name) + 1 /* name */ +
3141 LEB128_SIZE /* type */ +
3142 LEB128_SIZE /* unit */ +
3143 LEB128_SIZE /* variance */ +
3144 LEB128_SIZE /* index */
3153 logbuffer = ensure_logbuf (size);
3155 ENTER_LOG (logbuffer, "perfcounters");
3156 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
3157 emit_value (logbuffer, len);
3158 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3159 if (pcagent->emitted)
3162 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
3163 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
3164 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
3165 emit_value (logbuffer, MONO_COUNTER_LONG);
3166 emit_value (logbuffer, MONO_COUNTER_RAW);
3167 emit_value (logbuffer, MONO_COUNTER_VARIABLE);
3168 emit_value (logbuffer, pcagent->index);
3170 pcagent->emitted = 1;
3172 EXIT_LOG (logbuffer);
3174 safe_send (profiler, logbuffer);
3178 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
3180 PerfCounterAgent *pcagent;
3182 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3183 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
3185 if (pcagent->value == value)
3188 pcagent->value = value;
3189 pcagent->updated = 1;
3190 pcagent->deleted = 0;
3194 pcagent = g_new0 (PerfCounterAgent, 1);
3195 pcagent->next = perfcounters;
3196 pcagent->index = counters_index++;
3197 pcagent->category_name = g_strdup (category_name);
3198 pcagent->name = g_strdup (name);
3199 pcagent->type = (int) type;
3200 pcagent->value = value;
3201 pcagent->emitted = 0;
3202 pcagent->updated = 1;
3203 pcagent->deleted = 0;
3205 perfcounters = pcagent;
3211 perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp)
3213 PerfCounterAgent *pcagent;
3214 LogBuffer *logbuffer;
3217 if (!counters_initialized)
3220 mono_os_mutex_lock (&counters_mutex);
3222 /* mark all perfcounters as deleted, foreach will unmark them as necessary */
3223 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
3224 pcagent->deleted = 1;
3226 mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
3228 perfcounters_emit (profiler);
3231 EVENT_SIZE /* event */ +
3232 LEB128_SIZE /* time */
3235 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3236 if (pcagent->deleted || !pcagent->updated)
3240 LEB128_SIZE /* index */ +
3241 LEB128_SIZE /* type */ +
3242 LEB128_SIZE /* value */
3247 LEB128_SIZE /* stop marker */
3250 logbuffer = ensure_logbuf (size);
3252 ENTER_LOG (logbuffer, "perfcounters");
3253 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
3254 emit_uvalue (logbuffer, timestamp);
3255 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3256 if (pcagent->deleted || !pcagent->updated)
3258 emit_uvalue (logbuffer, pcagent->index);
3259 emit_uvalue (logbuffer, MONO_COUNTER_LONG);
3260 emit_svalue (logbuffer, pcagent->value);
3262 pcagent->updated = 0;
3265 emit_value (logbuffer, 0);
3266 EXIT_LOG (logbuffer);
3268 safe_send (profiler, logbuffer);
3270 mono_os_mutex_unlock (&counters_mutex);
3274 counters_and_perfcounters_sample (MonoProfiler *prof)
3276 static uint64_t start = -1;
3280 start = current_time ();
3282 now = current_time ();
3283 counters_sample (prof, (now - start) / 1000/ 1000);
3284 perfcounters_sample (prof, (now - start) / 1000/ 1000);
3287 #define COVERAGE_DEBUG(x) if (debug_coverage) {x}
3288 static mono_mutex_t coverage_mutex;
3289 static MonoConcurrentHashTable *coverage_methods = NULL;
3290 static MonoConcurrentHashTable *coverage_assemblies = NULL;
3291 static MonoConcurrentHashTable *coverage_classes = NULL;
3293 static MonoConcurrentHashTable *filtered_classes = NULL;
3294 static MonoConcurrentHashTable *entered_methods = NULL;
3295 static MonoConcurrentHashTable *image_to_methods = NULL;
3296 static MonoConcurrentHashTable *suppressed_assemblies = NULL;
3297 static gboolean coverage_initialized = FALSE;
3299 static GPtrArray *coverage_data = NULL;
3300 static int previous_offset = 0;
3302 typedef struct _MethodNode MethodNode;
3303 struct _MethodNode {
3304 MonoLockFreeQueueNode node;
3308 typedef struct _CoverageEntry CoverageEntry;
3309 struct _CoverageEntry {
3318 free_coverage_entry (gpointer data, gpointer userdata)
3320 CoverageEntry *entry = (CoverageEntry *)data;
3321 g_free (entry->filename);
3326 obtain_coverage_for_method (MonoProfiler *prof, const MonoProfileCoverageEntry *entry)
3328 int offset = entry->iloffset - previous_offset;
3329 CoverageEntry *e = g_new (CoverageEntry, 1);
3331 previous_offset = entry->iloffset;
3334 e->counter = entry->counter;
3335 e->filename = g_strdup(entry->filename ? entry->filename : "");
3336 e->line = entry->line;
3337 e->column = entry->col;
3339 g_ptr_array_add (coverage_data, e);
3343 parse_generic_type_names(char *name)
3345 char *new_name, *ret;
3346 int within_generic_declaration = 0, generic_members = 1;
3348 if (name == NULL || *name == '\0')
3349 return g_strdup ("");
3351 if (!(ret = new_name = (char *)calloc (strlen (name) * 4 + 1, sizeof (char))))
3357 within_generic_declaration = 1;
3361 within_generic_declaration = 0;
3363 if (*(name - 1) != '<') {
3365 *new_name++ = '0' + generic_members;
3367 memcpy (new_name, "<>", 8);
3371 generic_members = 0;
3379 if (!within_generic_declaration)
3380 *new_name++ = *name;
3389 static int method_id;
3391 build_method_buffer (gpointer key, gpointer value, gpointer userdata)
3393 MonoMethod *method = (MonoMethod *)value;
3394 MonoProfiler *prof = (MonoProfiler *)userdata;
3398 const char *image_name, *method_name, *sig, *first_filename;
3399 LogBuffer *logbuffer;
3402 previous_offset = 0;
3403 coverage_data = g_ptr_array_new ();
3405 mono_profiler_coverage_get (prof, method, obtain_coverage_for_method);
3407 klass = mono_method_get_class (method);
3408 image = mono_class_get_image (klass);
3409 image_name = mono_image_get_name (image);
3411 sig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3412 class_name = parse_generic_type_names (mono_type_get_name (mono_class_get_type (klass)));
3413 method_name = mono_method_get_name (method);
3415 if (coverage_data->len != 0) {
3416 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[0];
3417 first_filename = entry->filename ? entry->filename : "";
3419 first_filename = "";
3421 image_name = image_name ? image_name : "";
3422 sig = sig ? sig : "";
3423 method_name = method_name ? method_name : "";
3425 logbuffer = ensure_logbuf (
3426 EVENT_SIZE /* event */ +
3427 strlen (image_name) + 1 /* image name */ +
3428 strlen (class_name) + 1 /* class name */ +
3429 strlen (method_name) + 1 /* method name */ +
3430 strlen (sig) + 1 /* signature */ +
3431 strlen (first_filename) + 1 /* first file name */ +
3432 LEB128_SIZE /* token */ +
3433 LEB128_SIZE /* method id */ +
3434 LEB128_SIZE /* entries */
3436 ENTER_LOG (logbuffer, "coverage-methods");
3438 emit_byte (logbuffer, TYPE_COVERAGE_METHOD | TYPE_COVERAGE);
3439 emit_string (logbuffer, image_name, strlen (image_name) + 1);
3440 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3441 emit_string (logbuffer, method_name, strlen (method_name) + 1);
3442 emit_string (logbuffer, sig, strlen (sig) + 1);
3443 emit_string (logbuffer, first_filename, strlen (first_filename) + 1);
3445 emit_uvalue (logbuffer, mono_method_get_token (method));
3446 emit_uvalue (logbuffer, method_id);
3447 emit_value (logbuffer, coverage_data->len);
3449 EXIT_LOG (logbuffer);
3450 safe_send (prof, logbuffer);
3452 for (i = 0; i < coverage_data->len; i++) {
3453 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[i];
3455 logbuffer = ensure_logbuf (
3456 EVENT_SIZE /* event */ +
3457 LEB128_SIZE /* method id */ +
3458 LEB128_SIZE /* offset */ +
3459 LEB128_SIZE /* counter */ +
3460 LEB128_SIZE /* line */ +
3461 LEB128_SIZE /* column */
3463 ENTER_LOG (logbuffer, "coverage-statement");
3465 emit_byte (logbuffer, TYPE_COVERAGE_STATEMENT | TYPE_COVERAGE);
3466 emit_uvalue (logbuffer, method_id);
3467 emit_uvalue (logbuffer, entry->offset);
3468 emit_uvalue (logbuffer, entry->counter);
3469 emit_uvalue (logbuffer, entry->line);
3470 emit_uvalue (logbuffer, entry->column);
3472 EXIT_LOG (logbuffer);
3473 safe_send (prof, logbuffer);
3478 g_free (class_name);
3480 g_ptr_array_foreach (coverage_data, free_coverage_entry, NULL);
3481 g_ptr_array_free (coverage_data, TRUE);
3482 coverage_data = NULL;
3485 /* This empties the queue */
3487 count_queue (MonoLockFreeQueue *queue)
3489 MonoLockFreeQueueNode *node;
3492 while ((node = mono_lock_free_queue_dequeue (queue))) {
3494 mono_lock_free_queue_node_free (node);
3501 build_class_buffer (gpointer key, gpointer value, gpointer userdata)
3503 MonoClass *klass = (MonoClass *)key;
3504 MonoLockFreeQueue *class_methods = (MonoLockFreeQueue *)value;
3505 MonoProfiler *prof = (MonoProfiler *)userdata;
3508 const char *assembly_name;
3509 int number_of_methods, partially_covered;
3510 guint fully_covered;
3511 LogBuffer *logbuffer;
3513 image = mono_class_get_image (klass);
3514 assembly_name = mono_image_get_name (image);
3515 class_name = mono_type_get_name (mono_class_get_type (klass));
3517 assembly_name = assembly_name ? assembly_name : "";
3518 number_of_methods = mono_class_num_methods (klass);
3519 fully_covered = count_queue (class_methods);
3520 /* We don't handle partial covered yet */
3521 partially_covered = 0;
3523 logbuffer = ensure_logbuf (
3524 EVENT_SIZE /* event */ +
3525 strlen (assembly_name) + 1 /* assembly name */ +
3526 strlen (class_name) + 1 /* class name */ +
3527 LEB128_SIZE /* no. methods */ +
3528 LEB128_SIZE /* fully covered */ +
3529 LEB128_SIZE /* partially covered */
3532 ENTER_LOG (logbuffer, "coverage-class");
3533 emit_byte (logbuffer, TYPE_COVERAGE_CLASS | TYPE_COVERAGE);
3534 emit_string (logbuffer, assembly_name, strlen (assembly_name) + 1);
3535 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3536 emit_uvalue (logbuffer, number_of_methods);
3537 emit_uvalue (logbuffer, fully_covered);
3538 emit_uvalue (logbuffer, partially_covered);
3539 EXIT_LOG (logbuffer);
3541 safe_send (prof, logbuffer);
3543 g_free (class_name);
3547 get_coverage_for_image (MonoImage *image, int *number_of_methods, guint *fully_covered, int *partially_covered)
3549 MonoLockFreeQueue *image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3551 *number_of_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
3553 *fully_covered = count_queue (image_methods);
3557 // FIXME: We don't handle partially covered yet.
3558 *partially_covered = 0;
3562 build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
3564 MonoAssembly *assembly = (MonoAssembly *)value;
3565 MonoProfiler *prof = (MonoProfiler *)userdata;
3566 MonoImage *image = mono_assembly_get_image (assembly);
3567 LogBuffer *logbuffer;
3568 const char *name, *guid, *filename;
3569 int number_of_methods = 0, partially_covered = 0;
3570 guint fully_covered = 0;
3572 name = mono_image_get_name (image);
3573 guid = mono_image_get_guid (image);
3574 filename = mono_image_get_filename (image);
3576 name = name ? name : "";
3577 guid = guid ? guid : "";
3578 filename = filename ? filename : "";
3580 get_coverage_for_image (image, &number_of_methods, &fully_covered, &partially_covered);
3582 logbuffer = ensure_logbuf (
3583 EVENT_SIZE /* event */ +
3584 strlen (name) + 1 /* name */ +
3585 strlen (guid) + 1 /* guid */ +
3586 strlen (filename) + 1 /* file name */ +
3587 LEB128_SIZE /* no. methods */ +
3588 LEB128_SIZE /* fully covered */ +
3589 LEB128_SIZE /* partially covered */
3592 ENTER_LOG (logbuffer, "coverage-assemblies");
3593 emit_byte (logbuffer, TYPE_COVERAGE_ASSEMBLY | TYPE_COVERAGE);
3594 emit_string (logbuffer, name, strlen (name) + 1);
3595 emit_string (logbuffer, guid, strlen (guid) + 1);
3596 emit_string (logbuffer, filename, strlen (filename) + 1);
3597 emit_uvalue (logbuffer, number_of_methods);
3598 emit_uvalue (logbuffer, fully_covered);
3599 emit_uvalue (logbuffer, partially_covered);
3600 EXIT_LOG (logbuffer);
3602 safe_send (prof, logbuffer);
3606 dump_coverage (MonoProfiler *prof)
3608 if (!coverage_initialized)
3611 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Started dump\n");)
3614 mono_os_mutex_lock (&coverage_mutex);
3615 mono_conc_hashtable_foreach (coverage_assemblies, build_assembly_buffer, prof);
3616 mono_conc_hashtable_foreach (coverage_classes, build_class_buffer, prof);
3617 mono_conc_hashtable_foreach (coverage_methods, build_method_buffer, prof);
3618 mono_os_mutex_unlock (&coverage_mutex);
3620 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Finished dump\n");)
3624 process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method)
3629 if (!coverage_initialized)
3632 klass = mono_method_get_class (method);
3633 image = mono_class_get_image (klass);
3635 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)))
3638 mono_os_mutex_lock (&coverage_mutex);
3639 mono_conc_hashtable_insert (entered_methods, method, method);
3640 mono_os_mutex_unlock (&coverage_mutex);
3643 static MonoLockFreeQueueNode *
3644 create_method_node (MonoMethod *method)
3646 MethodNode *node = (MethodNode *)g_malloc (sizeof (MethodNode));
3647 mono_lock_free_queue_node_init ((MonoLockFreeQueueNode *) node, FALSE);
3648 node->method = method;
3650 return (MonoLockFreeQueueNode *) node;
3654 coverage_filter (MonoProfiler *prof, MonoMethod *method)
3659 MonoAssembly *assembly;
3660 MonoMethodHeader *header;
3661 guint32 iflags, flags, code_size;
3662 char *fqn, *classname;
3663 gboolean has_positive, found;
3664 MonoLockFreeQueue *image_methods, *class_methods;
3665 MonoLockFreeQueueNode *node;
3667 if (!coverage_initialized)
3670 COVERAGE_DEBUG(fprintf (stderr, "Coverage filter for %s\n", mono_method_get_name (method));)
3672 flags = mono_method_get_flags (method, &iflags);
3673 if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
3674 (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/)) {
3675 COVERAGE_DEBUG(fprintf (stderr, " Internal call or pinvoke - ignoring\n");)
3679 // Don't need to do anything else if we're already tracking this method
3680 if (mono_conc_hashtable_lookup (coverage_methods, method)) {
3681 COVERAGE_DEBUG(fprintf (stderr, " Already tracking\n");)
3685 klass = mono_method_get_class (method);
3686 image = mono_class_get_image (klass);
3688 // Don't handle coverage for the core assemblies
3689 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)) != NULL)
3692 if (prof->coverage_filters) {
3693 /* Check already filtered classes first */
3694 if (mono_conc_hashtable_lookup (filtered_classes, klass)) {
3695 COVERAGE_DEBUG(fprintf (stderr, " Already filtered\n");)
3699 classname = mono_type_get_name (mono_class_get_type (klass));
3701 fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
3703 COVERAGE_DEBUG(fprintf (stderr, " Looking for %s in filter\n", fqn);)
3704 // Check positive filters first
3705 has_positive = FALSE;
3707 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3708 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3710 if (filter [0] == '+') {
3711 filter = &filter [1];
3713 COVERAGE_DEBUG(fprintf (stderr, " Checking against +%s ...", filter);)
3715 if (strstr (fqn, filter) != NULL) {
3716 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3719 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3721 has_positive = TRUE;
3725 if (has_positive && !found) {
3726 COVERAGE_DEBUG(fprintf (stderr, " Positive match was not found\n");)
3728 mono_os_mutex_lock (&coverage_mutex);
3729 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3730 mono_os_mutex_unlock (&coverage_mutex);
3737 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3738 // FIXME: Is substring search sufficient?
3739 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3740 if (filter [0] == '+')
3744 filter = &filter [1];
3745 COVERAGE_DEBUG(fprintf (stderr, " Checking against -%s ...", filter);)
3747 if (strstr (fqn, filter) != NULL) {
3748 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3750 mono_os_mutex_lock (&coverage_mutex);
3751 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3752 mono_os_mutex_unlock (&coverage_mutex);
3758 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3766 COVERAGE_DEBUG(fprintf (stderr, " Handling coverage for %s\n", mono_method_get_name (method));)
3767 header = mono_method_get_header_checked (method, &error);
3768 mono_error_cleanup (&error);
3770 mono_method_header_get_code (header, &code_size, NULL);
3772 assembly = mono_image_get_assembly (image);
3774 mono_os_mutex_lock (&coverage_mutex);
3775 mono_conc_hashtable_insert (coverage_methods, method, method);
3776 mono_conc_hashtable_insert (coverage_assemblies, assembly, assembly);
3777 mono_os_mutex_unlock (&coverage_mutex);
3779 image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3781 if (image_methods == NULL) {
3782 image_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
3783 mono_lock_free_queue_init (image_methods);
3784 mono_os_mutex_lock (&coverage_mutex);
3785 mono_conc_hashtable_insert (image_to_methods, image, image_methods);
3786 mono_os_mutex_unlock (&coverage_mutex);
3789 node = create_method_node (method);
3790 mono_lock_free_queue_enqueue (image_methods, node);
3792 class_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (coverage_classes, klass);
3794 if (class_methods == NULL) {
3795 class_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
3796 mono_lock_free_queue_init (class_methods);
3797 mono_os_mutex_lock (&coverage_mutex);
3798 mono_conc_hashtable_insert (coverage_classes, klass, class_methods);
3799 mono_os_mutex_unlock (&coverage_mutex);
3802 node = create_method_node (method);
3803 mono_lock_free_queue_enqueue (class_methods, node);
3808 #define LINE_BUFFER_SIZE 4096
3809 /* Max file limit of 128KB */
3810 #define MAX_FILE_SIZE 128 * 1024
3812 get_file_content (FILE *stream)
3817 int res, offset = 0;
3819 res = fseek (stream, 0, SEEK_END);
3823 filesize = ftell (stream);
3827 res = fseek (stream, 0, SEEK_SET);
3831 if (filesize > MAX_FILE_SIZE)
3834 buffer = (char *)g_malloc ((filesize + 1) * sizeof (char));
3835 while ((bytes_read = fread (buffer + offset, 1, LINE_BUFFER_SIZE, stream)) > 0)
3836 offset += bytes_read;
3838 /* NULL terminate our buffer */
3839 buffer[filesize] = '\0';
3844 get_next_line (char *contents, char **next_start)
3848 if (p == NULL || *p == '\0') {
3853 while (*p != '\n' && *p != '\0')
3858 *next_start = p + 1;
3866 init_suppressed_assemblies (void)
3872 suppressed_assemblies = mono_conc_hashtable_new (g_str_hash, g_str_equal);
3873 sa_file = fopen (SUPPRESSION_DIR "/mono-profiler-log.suppression", "r");
3874 if (sa_file == NULL)
3877 /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
3878 content = get_file_content (sa_file);
3879 if (content == NULL) {
3880 g_error ("mono-profiler-log.suppression is greater than 128kb - aborting\n");
3883 while ((line = get_next_line (content, &content))) {
3884 line = g_strchomp (g_strchug (line));
3885 /* No locking needed as we're doing initialization */
3886 mono_conc_hashtable_insert (suppressed_assemblies, line, line);
3892 #endif /* DISABLE_HELPER_THREAD */
3895 coverage_init (MonoProfiler *prof)
3897 #ifndef DISABLE_HELPER_THREAD
3898 assert (!coverage_initialized);
3900 COVERAGE_DEBUG(fprintf (stderr, "Coverage initialized\n");)
3902 mono_os_mutex_init (&coverage_mutex);
3903 coverage_methods = mono_conc_hashtable_new (NULL, NULL);
3904 coverage_assemblies = mono_conc_hashtable_new (NULL, NULL);
3905 coverage_classes = mono_conc_hashtable_new (NULL, NULL);
3906 filtered_classes = mono_conc_hashtable_new (NULL, NULL);
3907 entered_methods = mono_conc_hashtable_new (NULL, NULL);
3908 image_to_methods = mono_conc_hashtable_new (NULL, NULL);
3909 init_suppressed_assemblies ();
3911 coverage_initialized = TRUE;
3912 #endif /* DISABLE_HELPER_THREAD */
3916 log_shutdown (MonoProfiler *prof)
3921 #ifndef DISABLE_HELPER_THREAD
3922 counters_and_perfcounters_sample (prof);
3924 dump_coverage (prof);
3926 if (prof->command_port) {
3928 ign_res (write (prof->pipes [1], &c, 1));
3929 pthread_join (prof->helper_thread, &res);
3935 for (i = 0; i < num_perf; ++i)
3936 read_perf_mmap (prof, i);
3940 g_ptr_array_free (prof->sorted_sample_events, TRUE);
3942 if (TLS_GET (LogBuffer, tlsbuffer))
3943 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
3945 TLS_SET (tlsbuffer, NULL);
3946 TLS_SET (tlsmethodlist, NULL);
3948 InterlockedWrite (&prof->run_writer_thread, 0);
3949 pthread_join (prof->writer_thread, &res);
3951 #if defined (HAVE_SYS_ZLIB)
3953 gzclose (prof->gzfile);
3955 if (prof->pipe_output)
3956 pclose (prof->file);
3958 fclose (prof->file);
3960 mono_conc_hashtable_destroy (prof->method_table);
3961 mono_os_mutex_destroy (&prof->method_table_mutex);
3963 if (coverage_initialized) {
3964 mono_conc_hashtable_destroy (coverage_methods);
3965 mono_conc_hashtable_destroy (coverage_assemblies);
3966 mono_conc_hashtable_destroy (coverage_classes);
3967 mono_conc_hashtable_destroy (filtered_classes);
3969 mono_conc_hashtable_destroy (entered_methods);
3970 mono_conc_hashtable_destroy (image_to_methods);
3971 mono_conc_hashtable_destroy (suppressed_assemblies);
3972 mono_os_mutex_destroy (&coverage_mutex);
3979 new_filename (const char* filename)
3981 time_t t = time (NULL);
3982 int pid = process_id ();
3987 int count_dates = 0;
3991 for (p = filename; *p; p++) {
4002 if (!count_dates && !count_pids)
4003 return pstrdup (filename);
4004 snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
4006 snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
4007 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
4008 s_date = strlen (time_buf);
4009 s_pid = strlen (pid_buf);
4010 d = res = (char *)malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
4011 for (p = filename; *p; p++) {
4018 strcpy (d, time_buf);
4021 } else if (*p == 'p') {
4022 strcpy (d, pid_buf);
4025 } else if (*p == '%') {
4037 //this is exposed by the JIT, but it's not meant to be a supported API for now.
4038 extern void mono_threads_attach_tools_thread (void);
4040 #ifndef DISABLE_HELPER_THREAD
4043 helper_thread (void* arg)
4045 MonoProfiler* prof = (MonoProfiler *)arg;
4049 MonoThread *thread = NULL;
4051 mono_threads_attach_tools_thread ();
4052 //fprintf (stderr, "Server listening\n");
4053 command_socket = -1;
4059 FD_SET (prof->server_socket, &rfds);
4060 max_fd = prof->server_socket;
4061 FD_SET (prof->pipes [0], &rfds);
4062 if (max_fd < prof->pipes [0])
4063 max_fd = prof->pipes [0];
4064 if (command_socket >= 0) {
4065 FD_SET (command_socket, &rfds);
4066 if (max_fd < command_socket)
4067 max_fd = command_socket;
4072 for ( i = 0; i < num_perf; ++i) {
4073 if (perf_data [i].perf_fd < 0)
4075 FD_SET (perf_data [i].perf_fd, &rfds);
4076 if (max_fd < perf_data [i].perf_fd)
4077 max_fd = perf_data [i].perf_fd;
4082 counters_and_perfcounters_sample (prof);
4086 len = select (max_fd + 1, &rfds, NULL, NULL, &tv);
4092 g_warning ("Error in proflog server: %s", strerror (errno));
4096 if (FD_ISSET (prof->pipes [0], &rfds)) {
4098 int r = read (prof->pipes [0], &c, 1);
4099 if (r == 1 && c == 0) {
4100 StatBuffer *sbufbase = prof->stat_buffers;
4102 if (!sbufbase->next)
4104 sbuf = sbufbase->next->next;
4105 sbufbase->next->next = NULL;
4107 fprintf (stderr, "stat buffer dump\n");
4109 dump_sample_hits (prof, sbuf);
4110 free_buffer (sbuf, sbuf->size);
4111 safe_send (prof, ensure_logbuf (0));
4115 /* time to shut down */
4116 dump_sample_hits (prof, prof->stat_buffers);
4118 mono_thread_detach (thread);
4120 fprintf (stderr, "helper shutdown\n");
4124 for ( i = 0; i < num_perf; ++i) {
4125 if (perf_data [i].perf_fd < 0)
4127 if (FD_ISSET (perf_data [i].perf_fd, &rfds))
4128 read_perf_mmap (prof, i);
4132 safe_send (prof, ensure_logbuf (0));
4138 for ( i = 0; i < num_perf; ++i) {
4139 if (perf_data [i].perf_fd < 0)
4141 if (FD_ISSET (perf_data [i].perf_fd, &rfds)) {
4142 read_perf_mmap (prof, i);
4143 safe_send (prof, ensure_logbuf (0));
4148 if (command_socket >= 0 && FD_ISSET (command_socket, &rfds)) {
4149 len = read (command_socket, buf, sizeof (buf) - 1);
4153 close (command_socket);
4154 command_socket = -1;
4158 if (strcmp (buf, "heapshot\n") == 0) {
4159 heapshot_requested = 1;
4160 //fprintf (stderr, "perform heapshot\n");
4161 if (InterlockedRead (&runtime_inited) && !thread) {
4162 thread = mono_thread_attach (mono_get_root_domain ());
4163 /*fprintf (stderr, "attached\n");*/
4166 process_requests (prof);
4167 mono_thread_detach (thread);
4173 if (!FD_ISSET (prof->server_socket, &rfds)) {
4176 command_socket = accept (prof->server_socket, NULL, NULL);
4177 if (command_socket < 0)
4179 //fprintf (stderr, "Accepted connection\n");
4185 start_helper_thread (MonoProfiler* prof)
4187 struct sockaddr_in server_address;
4190 if (pipe (prof->pipes) < 0) {
4191 fprintf (stderr, "Cannot create pipe\n");
4194 prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
4195 if (prof->server_socket < 0) {
4196 fprintf (stderr, "Cannot create server socket\n");
4199 memset (&server_address, 0, sizeof (server_address));
4200 server_address.sin_family = AF_INET;
4201 server_address.sin_addr.s_addr = INADDR_ANY;
4202 server_address.sin_port = htons (prof->command_port);
4203 if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) < 0) {
4204 fprintf (stderr, "Cannot bind server socket, port: %d: %s\n", prof->command_port, strerror (errno));
4205 close (prof->server_socket);
4208 if (listen (prof->server_socket, 1) < 0) {
4209 fprintf (stderr, "Cannot listen server socket\n");
4210 close (prof->server_socket);
4213 slen = sizeof (server_address);
4214 if (getsockname (prof->server_socket, (struct sockaddr *)&server_address, &slen) == 0) {
4215 prof->command_port = ntohs (server_address.sin_port);
4216 /*fprintf (stderr, "Assigned server port: %d\n", prof->command_port);*/
4219 r = pthread_create (&prof->helper_thread, NULL, helper_thread, prof);
4221 close (prof->server_socket);
4229 writer_thread (void *arg)
4231 MonoProfiler *prof = (MonoProfiler *)arg;
4233 mono_threads_attach_tools_thread ();
4237 while (InterlockedRead (&prof->run_writer_thread)) {
4238 WriterQueueEntry *entry;
4240 while ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&prof->writer_queue))) {
4241 LogBuffer *method_buffer = NULL;
4242 gboolean new_methods = FALSE;
4244 if (entry->methods->len)
4245 method_buffer = create_buffer ();
4248 * Encode the method events in a temporary log buffer that we
4249 * flush to disk before the main buffer, ensuring that all
4250 * methods have metadata emitted before they're referenced.
4252 for (guint i = 0; i < entry->methods->len; i++) {
4253 MethodInfo *info = (MethodInfo *)g_ptr_array_index (entry->methods, i);
4255 if (mono_conc_hashtable_lookup (prof->method_table, info->method))
4261 * Other threads use this hash table to get a general
4262 * idea of whether a method has already been emitted to
4263 * the stream. Due to the way we add to this table, it
4264 * can easily happen that multiple threads queue up the
4265 * same methods, but that's OK since eventually all
4266 * methods will be in this table and the thread-local
4267 * method lists will just be empty for the rest of the
4270 mono_os_mutex_lock (&prof->method_table_mutex);
4271 mono_conc_hashtable_insert (prof->method_table, info->method, info->method);
4272 mono_os_mutex_unlock (&prof->method_table_mutex);
4274 char *name = mono_method_full_name (info->method, 1);
4275 int nlen = strlen (name) + 1;
4276 void *cstart = info->ji ? mono_jit_info_get_code_start (info->ji) : NULL;
4277 int csize = info->ji ? mono_jit_info_get_code_size (info->ji) : 0;
4279 method_buffer = ensure_logbuf_inner (method_buffer,
4280 EVENT_SIZE /* event */ +
4281 LEB128_SIZE /* time */ +
4282 LEB128_SIZE /* method */ +
4283 LEB128_SIZE /* start */ +
4284 LEB128_SIZE /* size */ +
4288 emit_byte (method_buffer, TYPE_JIT | TYPE_METHOD);
4289 emit_time (method_buffer, info->time);
4290 emit_method_inner (method_buffer, info->method);
4291 emit_ptr (method_buffer, cstart);
4292 emit_value (method_buffer, csize);
4294 memcpy (method_buffer->cursor, name, nlen);
4295 method_buffer->cursor += nlen;
4301 g_ptr_array_free (entry->methods, TRUE);
4304 dump_buffer (prof, method_buffer);
4305 else if (method_buffer)
4306 free_buffer (method_buffer, method_buffer->size);
4308 dump_buffer (prof, entry->buffer);
4318 start_writer_thread (MonoProfiler* prof)
4320 InterlockedWrite (&prof->run_writer_thread, 1);
4322 return !pthread_create (&prof->writer_thread, NULL, writer_thread, prof);
4326 runtime_initialized (MonoProfiler *profiler)
4328 #ifndef DISABLE_HELPER_THREAD
4329 if (hs_mode_ondemand || need_helper_thread) {
4330 if (!start_helper_thread (profiler))
4331 profiler->command_port = 0;
4335 start_writer_thread (profiler);
4337 InterlockedWrite (&runtime_inited, 1);
4338 #ifndef DISABLE_HELPER_THREAD
4339 counters_init (profiler);
4340 counters_sample (profiler, 0);
4342 /* ensure the main thread data and startup are available soon */
4343 safe_send (profiler, ensure_logbuf (0));
4346 static MonoProfiler*
4347 create_profiler (const char *filename, GPtrArray *filters)
4351 int force_delete = 0;
4352 prof = (MonoProfiler *)calloc (1, sizeof (MonoProfiler));
4354 prof->command_port = command_port;
4355 if (filename && *filename == '-') {
4361 filename = "|mprof-report -";
4363 filename = "output.mlpd";
4364 nf = (char*)filename;
4366 nf = new_filename (filename);
4368 int s = strlen (nf) + 32;
4369 char *p = (char *)malloc (s);
4370 snprintf (p, s, "|mprof-report '--out=%s' -", nf);
4376 prof->file = popen (nf + 1, "w");
4377 prof->pipe_output = 1;
4378 } else if (*nf == '#') {
4379 int fd = strtol (nf + 1, NULL, 10);
4380 prof->file = fdopen (fd, "a");
4384 prof->file = fopen (nf, "wb");
4387 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
4390 #if defined (HAVE_SYS_ZLIB)
4392 prof->gzfile = gzdopen (fileno (prof->file), "wb");
4395 if (sample_type && !do_mono_sample)
4396 need_helper_thread = setup_perf_event ();
4398 /* FIXME: warn if different freq or sample type */
4402 if (do_mono_sample) {
4403 prof->stat_buffers = create_stat_buffer ();
4404 need_helper_thread = 1;
4406 if (do_counters && !need_helper_thread) {
4407 need_helper_thread = 1;
4410 prof->sorted_sample_events = g_ptr_array_sized_new (BUFFER_SIZE / SAMPLE_EVENT_SIZE_IN_SLOTS (0));
4412 #ifdef DISABLE_HELPER_THREAD
4413 if (hs_mode_ondemand)
4414 fprintf (stderr, "Ondemand heapshot unavailable on this arch.\n");
4417 fprintf (stderr, "Coverage unavailable on this arch.\n");
4421 mono_lock_free_queue_init (&prof->writer_queue);
4422 mono_os_mutex_init (&prof->method_table_mutex);
4423 prof->method_table = mono_conc_hashtable_new (NULL, NULL);
4426 coverage_init (prof);
4427 prof->coverage_filters = filters;
4429 prof->startup_time = current_time ();
4436 printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
4437 printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
4438 printf ("Options:\n");
4439 printf ("\thelp show this usage info\n");
4440 printf ("\t[no]alloc enable/disable recording allocation info\n");
4441 printf ("\t[no]calls enable/disable recording enter/leave method events\n");
4442 printf ("\theapshot[=MODE] record heap shot info (by default at each major collection)\n");
4443 printf ("\t MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
4444 printf ("\tcounters sample counters every 1s\n");
4445 printf ("\tsample[=TYPE] use statistical sampling mode (by default cycles/1000)\n");
4446 printf ("\t TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
4447 printf ("\t TYPE can be followed by /FREQUENCY\n");
4448 printf ("\ttime=fast use a faster (but more inaccurate) timer\n");
4449 printf ("\tmaxframes=NUM collect up to NUM stack frames\n");
4450 printf ("\tcalldepth=NUM ignore method events for call chain depth bigger than NUM\n");
4451 printf ("\toutput=FILENAME write the data to file FILENAME (-FILENAME to overwrite)\n");
4452 printf ("\toutput=|PROGRAM write the data to the stdin of PROGRAM\n");
4453 printf ("\t %%t is subtituted with date and time, %%p with the pid\n");
4454 printf ("\treport create a report instead of writing the raw data to a file\n");
4455 printf ("\tzip compress the output data\n");
4456 printf ("\tport=PORTNUM use PORTNUM for the listening command server\n");
4457 printf ("\tcoverage enable collection of code coverage data\n");
4458 printf ("\tcovfilter=ASSEMBLY add an assembly to the code coverage filters\n");
4459 printf ("\t add a + to include the assembly or a - to exclude it\n");
4460 printf ("\t filter=-mscorlib\n");
4461 printf ("\tcovfilter-file=FILE use FILE to generate the list of assemblies to be filtered\n");
4467 match_option (const char* p, const char *opt, char **rval)
4469 int len = strlen (opt);
4470 if (strncmp (p, opt, len) == 0) {
4472 if (p [len] == '=' && p [len + 1]) {
4473 const char *opt = p + len + 1;
4474 const char *end = strchr (opt, ',');
4482 val = (char *)malloc (l + 1);
4483 memcpy (val, opt, l);
4488 if (p [len] == 0 || p [len] == ',') {
4490 return p + len + (p [len] == ',');
4508 static const SampleMode sample_modes [] = {
4509 {"cycles", SAMPLE_CYCLES},
4510 {"instr", SAMPLE_INSTRUCTIONS},
4511 {"cachemiss", SAMPLE_CACHE_MISSES},
4512 {"cacherefs", SAMPLE_CACHE_REFS},
4513 {"branches", SAMPLE_BRANCHES},
4514 {"branchmiss", SAMPLE_BRANCH_MISSES},
4519 set_sample_mode (char* val, int allow_empty)
4522 char *maybe_freq = NULL;
4524 const SampleMode *smode = sample_modes;
4525 #ifndef USE_PERF_EVENTS
4528 if (allow_empty && !val) {
4529 sample_type = SAMPLE_CYCLES;
4533 if (strcmp (val, "mono") == 0) {
4535 sample_type = SAMPLE_CYCLES;
4539 for (smode = sample_modes; smode->name; smode++) {
4540 int l = strlen (smode->name);
4541 if (strncmp (val, smode->name, l) == 0) {
4542 sample_type = smode->sample_mode;
4543 maybe_freq = val + l;
4549 if (*maybe_freq == '/') {
4550 count = strtoul (maybe_freq + 1, &end, 10);
4551 if (maybe_freq + 1 == end)
4553 sample_freq = count;
4554 } else if (*maybe_freq != 0) {
4563 set_hsmode (char* val, int allow_empty)
4567 if (allow_empty && !val)
4569 if (strcmp (val, "ondemand") == 0) {
4570 hs_mode_ondemand = 1;
4574 count = strtoul (val, &end, 10);
4577 if (strcmp (end, "ms") == 0)
4579 else if (strcmp (end, "gc") == 0)
4587 * declaration to silence the compiler: this is the entry point that
4588 * mono will load from the shared library and call.
4591 mono_profiler_startup (const char *desc);
4594 mono_profiler_startup_log (const char *desc);
4597 * this is the entry point that will be used when the profiler
4598 * is embedded inside the main executable.
4601 mono_profiler_startup_log (const char *desc)
4603 mono_profiler_startup (desc);
4607 mono_profiler_startup (const char *desc)
4610 GPtrArray *filters = NULL;
4611 char *filename = NULL;
4615 int calls_enabled = 0;
4616 int allocs_enabled = 0;
4617 int only_counters = 0;
4618 int only_coverage = 0;
4619 int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
4620 MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
4621 MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
4622 MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS|
4623 MONO_PROFILE_INS_COVERAGE|MONO_PROFILE_APPDOMAIN_EVENTS|MONO_PROFILE_CONTEXT_EVENTS|
4624 MONO_PROFILE_ASSEMBLY_EVENTS;
4627 if (strncmp (p, "log", 3))
4632 for (; *p; p = opt) {
4638 if ((opt = match_option (p, "help", NULL)) != p) {
4642 if ((opt = match_option (p, "calls", NULL)) != p) {
4646 if ((opt = match_option (p, "nocalls", NULL)) != p) {
4647 events &= ~MONO_PROFILE_ENTER_LEAVE;
4651 if ((opt = match_option (p, "alloc", NULL)) != p) {
4655 if ((opt = match_option (p, "noalloc", NULL)) != p) {
4656 events &= ~MONO_PROFILE_ALLOCATIONS;
4659 if ((opt = match_option (p, "time", &val)) != p) {
4660 if (strcmp (val, "fast") == 0)
4662 else if (strcmp (val, "null") == 0)
4669 if ((opt = match_option (p, "report", NULL)) != p) {
4673 if ((opt = match_option (p, "debug", NULL)) != p) {
4677 if ((opt = match_option (p, "sampling-real", NULL)) != p) {
4678 sampling_mode = MONO_PROFILER_STAT_MODE_REAL;
4681 if ((opt = match_option (p, "sampling-process", NULL)) != p) {
4682 sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
4685 if ((opt = match_option (p, "heapshot", &val)) != p) {
4686 events &= ~MONO_PROFILE_ALLOCATIONS;
4687 events &= ~MONO_PROFILE_ENTER_LEAVE;
4690 set_hsmode (val, 1);
4693 if ((opt = match_option (p, "sample", &val)) != p) {
4694 events &= ~MONO_PROFILE_ALLOCATIONS;
4695 events &= ~MONO_PROFILE_ENTER_LEAVE;
4697 set_sample_mode (val, 1);
4700 if ((opt = match_option (p, "hsmode", &val)) != p) {
4701 fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
4702 set_hsmode (val, 0);
4705 if ((opt = match_option (p, "zip", NULL)) != p) {
4709 if ((opt = match_option (p, "output", &val)) != p) {
4713 if ((opt = match_option (p, "port", &val)) != p) {
4715 command_port = strtoul (val, &end, 10);
4719 if ((opt = match_option (p, "maxframes", &val)) != p) {
4721 num_frames = strtoul (val, &end, 10);
4722 if (num_frames > MAX_FRAMES)
4723 num_frames = MAX_FRAMES;
4725 notraces = num_frames == 0;
4728 if ((opt = match_option (p, "calldepth", &val)) != p) {
4730 max_call_depth = strtoul (val, &end, 10);
4734 if ((opt = match_option (p, "counters", NULL)) != p) {
4738 if ((opt = match_option (p, "countersonly", NULL)) != p) {
4742 if ((opt = match_option (p, "coverage", NULL)) != p) {
4744 events |= MONO_PROFILE_ENTER_LEAVE;
4745 debug_coverage = (g_getenv ("MONO_PROFILER_DEBUG_COVERAGE") != NULL);
4748 if ((opt = match_option (p, "onlycoverage", NULL)) != p) {
4752 if ((opt = match_option (p, "covfilter-file", &val)) != p) {
4754 char *line, *content;
4756 if (filters == NULL)
4757 filters = g_ptr_array_new ();
4759 filter_file = fopen (val, "r");
4760 if (filter_file == NULL) {
4761 fprintf (stderr, "Unable to open %s\n", val);
4765 /* Don't need to free content as it is referred to by the lines stored in @filters */
4766 content = get_file_content (filter_file);
4767 if (content == NULL)
4768 fprintf (stderr, "WARNING: %s is greater than 128kb - ignoring\n", val);
4770 while ((line = get_next_line (content, &content)))
4771 g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
4773 fclose (filter_file);
4776 if ((opt = match_option (p, "covfilter", &val)) != p) {
4777 if (filters == NULL)
4778 filters = g_ptr_array_new ();
4780 g_ptr_array_add (filters, val);
4788 if (calls_enabled) {
4789 events |= MONO_PROFILE_ENTER_LEAVE;
4793 events |= MONO_PROFILE_ALLOCATIONS;
4797 events = MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_INS_COVERAGE;
4799 utils_init (fast_time);
4801 prof = create_profiler (filename, filters);
4806 mono_profiler_install (prof, log_shutdown);
4807 mono_profiler_install_gc (gc_event, gc_resize);
4808 mono_profiler_install_allocation (gc_alloc);
4809 mono_profiler_install_gc_moves (gc_moves);
4810 mono_profiler_install_gc_roots (gc_handle, gc_roots);
4811 mono_profiler_install_appdomain (NULL, domain_loaded, NULL, domain_unloaded);
4812 mono_profiler_install_appdomain_name (domain_name);
4813 mono_profiler_install_context (context_loaded, context_unloaded);
4814 mono_profiler_install_class (NULL, class_loaded, NULL, class_unloaded);
4815 mono_profiler_install_module (NULL, image_loaded, NULL, image_unloaded);
4816 mono_profiler_install_assembly (NULL, assembly_loaded, assembly_unloaded, NULL);
4817 mono_profiler_install_thread (thread_start, thread_end);
4818 mono_profiler_install_thread_name (thread_name);
4819 mono_profiler_install_enter_leave (method_enter, method_leave);
4820 mono_profiler_install_jit_end (method_jitted);
4821 mono_profiler_install_code_buffer_new (code_buffer_new);
4822 mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
4823 mono_profiler_install_monitor (monitor_event);
4824 mono_profiler_install_runtime_initialized (runtime_initialized);
4826 mono_profiler_install_coverage_filter (coverage_filter);
4828 if (do_mono_sample && sample_type == SAMPLE_CYCLES && !only_counters) {
4829 events |= MONO_PROFILE_STATISTICAL;
4830 mono_profiler_set_statistical_mode (sampling_mode, 1000000 / sample_freq);
4831 mono_profiler_install_statistical (mono_sample_hit);
4834 mono_profiler_set_events ((MonoProfileFlags)events);
4836 TLS_INIT (tlsbuffer);
4837 TLS_INIT (tlsmethodlist);