2 * proflog.c: mono log profiler
5 * Paolo Molaro (lupus@ximian.com)
6 * Alex Rønne Petersen (alexrp@xamarin.com)
8 * Copyright 2010 Novell, Inc (http://www.novell.com)
9 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
10 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
14 #include "../mini/jit.h"
15 #include "../metadata/metadata-internals.h"
16 #include <mono/metadata/profiler.h>
17 #include <mono/metadata/threads.h>
18 #include <mono/metadata/mono-gc.h>
19 #include <mono/metadata/debug-helpers.h>
20 #include <mono/metadata/mono-perfcounters.h>
21 #include <mono/metadata/appdomain.h>
22 #include <mono/metadata/assembly.h>
23 #include <mono/metadata/tokentype.h>
24 #include <mono/metadata/tabledefs.h>
25 #include <mono/utils/atomic.h>
26 #include <mono/utils/mono-membar.h>
27 #include <mono/utils/mono-counters.h>
28 #include <mono/utils/mono-os-mutex.h>
29 #include <mono/utils/mono-conc-hashtable.h>
30 #include <mono/utils/lock-free-queue.h>
38 #ifdef HAVE_SCHED_GETAFFINITY
43 #if defined(HOST_WIN32) || defined(DISABLE_SOCKETS)
44 #define DISABLE_HELPER_THREAD 1
53 #ifdef HAVE_EXECINFO_H
60 #ifndef DISABLE_HELPER_THREAD
61 #include <sys/types.h>
62 #include <sys/socket.h>
63 #include <netinet/in.h>
64 #include <sys/select.h>
73 #ifdef HAVE_SYS_STAT_H
80 #if defined (HAVE_SYS_ZLIB)
84 #if defined(__linux__)
87 #include <sys/syscall.h>
89 #ifdef ENABLE_PERF_EVENTS
90 #include <linux/perf_event.h>
92 #define USE_PERF_EVENTS 1
94 static int read_perf_mmap (MonoProfiler* prof, int cpu);
99 #define BUFFER_SIZE (4096 * 16)
101 /* Worst-case size in bytes of a 64-bit value encoded with LEB128. */
102 #define LEB128_SIZE 10
103 /* Size in bytes of the event ID prefix. */
106 static int nocalls = 0;
107 static int notraces = 0;
108 static int use_zip = 0;
109 static int do_report = 0;
110 static int do_heap_shot = 0;
111 static int max_call_depth = 100;
112 static volatile int runtime_inited = 0;
113 static int need_helper_thread = 0;
114 static int command_port = 0;
115 static int heapshot_requested = 0;
116 static int sample_type = 0;
117 static int sample_freq = 0;
118 static int do_mono_sample = 0;
119 static int in_shutdown = 0;
120 static int do_debug = 0;
121 static int do_counters = 0;
122 static int do_coverage = 0;
123 static gboolean debug_coverage = FALSE;
124 static MonoProfileSamplingMode sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
126 typedef struct _LogBuffer LogBuffer;
132 * The file is composed by a header followed by 0 or more buffers.
133 * Each buffer contains events that happened on a thread: for a given thread
134 * buffers that appear later in the file are guaranteed to contain events
135 * that happened later in time. Buffers from separate threads could be interleaved,
137 * Buffers are not required to be aligned.
140 * [id: 4 bytes] constant value: LOG_HEADER_ID
141 * [major: 1 byte] [minor: 1 byte] major and minor version of the log profiler
142 * [format: 1 byte] version of the data format for the rest of the file
143 * [ptrsize: 1 byte] size in bytes of a pointer in the profiled program
144 * [startup time: 8 bytes] time in milliseconds since the unix epoch when the program started
145 * [timer overhead: 4 bytes] approximate overhead in nanoseconds of the timer
146 * [flags: 4 bytes] file format flags, should be 0 for now
147 * [pid: 4 bytes] pid of the profiled process
148 * [port: 2 bytes] tcp port for server if != 0
149 * [sysid: 2 bytes] operating system and architecture identifier
151 * The multiple byte integers are in little-endian format.
154 * [buffer header] [event]*
155 * Buffers have a fixed-size header followed by 0 or more bytes of event data.
156 * Timing information and other values in the event data are usually stored
157 * as uleb128 or sleb128 integers. To save space, as noted for each item below,
158 * some data is represented as a difference between the actual value and
159 * either the last value of the same type (like for timing information) or
160 * as the difference from a value stored in a buffer header.
162 * For timing information the data is stored as uleb128, since timing
163 * increases in a monotonic way in each thread: the value is the number of
164 * nanoseconds to add to the last seen timing data in a buffer. The first value
165 * in a buffer will be calculated from the time_base field in the buffer head.
167 * Object or heap sizes are stored as uleb128.
168 * Pointer differences are stored as sleb128, instead.
170 * If an unexpected value is found, the rest of the buffer should be ignored,
171 * as generally the later values need the former to be interpreted correctly.
173 * buffer header format:
174 * [bufid: 4 bytes] constant value: BUF_ID
175 * [len: 4 bytes] size of the data following the buffer header
176 * [time_base: 8 bytes] time base in nanoseconds since an unspecified epoch
177 * [ptr_base: 8 bytes] base value for pointers
178 * [obj_base: 8 bytes] base value for object addresses
179 * [thread id: 8 bytes] system-specific thread ID (pthread_t for example)
180 * [method_base: 8 bytes] base value for MonoMethod pointers
183 * [extended info: upper 4 bits] [type: lower 4 bits] [data]*
184 * The data that follows depends on type and the extended info.
185 * Type is one of the enum values in proflog.h: TYPE_ALLOC, TYPE_GC,
186 * TYPE_METADATA, TYPE_METHOD, TYPE_EXCEPTION, TYPE_MONITOR, TYPE_HEAP.
187 * The extended info bits are interpreted based on type, see
188 * each individual event description below.
189 * strings are represented as a 0-terminated utf8 sequence.
192 * [flags: uleb128] must be 0
193 * [num: uleb128] number of frames following
194 * [frame: sleb128]* num MonoMethod pointers as differences from ptr_base
198 * exinfo: flags: TYPE_ALLOC_BT
199 * [time diff: uleb128] nanoseconds since last timing
200 * [ptr: sleb128] class as a byte difference from ptr_base
201 * [obj: sleb128] object address as a byte difference from obj_base
202 * [size: uleb128] size of the object in the heap
203 * If the TYPE_ALLOC_BT flag is set, a backtrace follows.
207 * exinfo: one of TYPE_GC_EVENT, TYPE_GC_RESIZE, TYPE_GC_MOVE, TYPE_GC_HANDLE_CREATED[_BT],
208 * TYPE_GC_HANDLE_DESTROYED[_BT]
209 * [time diff: uleb128] nanoseconds since last timing
210 * if exinfo == TYPE_GC_RESIZE
211 * [heap_size: uleb128] new heap size
212 * if exinfo == TYPE_GC_EVENT
213 * [event type: uleb128] GC event (MONO_GC_EVENT_* from profiler.h)
214 * [generation: uleb128] GC generation event refers to
215 * if exinfo == TYPE_GC_MOVE
216 * [num_objects: uleb128] number of object moves that follow
217 * [objaddr: sleb128]+ num_objects object pointer differences from obj_base
218 * num is always an even number: the even items are the old
219 * addresses, the odd numbers are the respective new object addresses
220 * if exinfo == TYPE_GC_HANDLE_CREATED[_BT]
221 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
222 * upper bits reserved as flags
223 * [handle: uleb128] GC handle value
224 * [objaddr: sleb128] object pointer differences from obj_base
225 * If exinfo == TYPE_GC_HANDLE_CREATED_BT, a backtrace follows.
226 * if exinfo == TYPE_GC_HANDLE_DESTROYED[_BT]
227 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
228 * upper bits reserved as flags
229 * [handle: uleb128] GC handle value
230 * If exinfo == TYPE_GC_HANDLE_DESTROYED_BT, a backtrace follows.
232 * type metadata format:
233 * type: TYPE_METADATA
234 * exinfo: one of: TYPE_END_LOAD, TYPE_END_UNLOAD (optional for TYPE_THREAD and TYPE_DOMAIN)
235 * [time diff: uleb128] nanoseconds since last timing
236 * [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
237 * TYPE_THREAD, TYPE_CONTEXT
238 * [pointer: sleb128] pointer of the metadata type depending on mtype
239 * if mtype == TYPE_CLASS
240 * [image: sleb128] MonoImage* as a pointer difference from ptr_base
241 * [flags: uleb128] must be 0
242 * [name: string] full class name
243 * if mtype == TYPE_IMAGE
244 * [flags: uleb128] must be 0
245 * [name: string] image file name
246 * if mtype == TYPE_ASSEMBLY
247 * [flags: uleb128] must be 0
248 * [name: string] assembly name
249 * if mtype == TYPE_DOMAIN
250 * [flags: uleb128] must be 0
251 * if mtype == TYPE_DOMAIN && exinfo == 0
252 * [name: string] domain friendly name
253 * if mtype == TYPE_CONTEXT
254 * [flags: uleb128] must be 0
255 * [domain: sleb128] domain id as pointer
256 * if mtype == TYPE_THREAD && (format_version < 11 || (format_version > 10 && exinfo == 0))
257 * [flags: uleb128] must be 0
258 * [name: string] thread name
260 * type method format:
262 * exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
263 * [time diff: uleb128] nanoseconds since last timing
264 * [method: sleb128] MonoMethod* as a pointer difference from the last such
265 * pointer or the buffer method_base
266 * if exinfo == TYPE_JIT
267 * [code address: sleb128] pointer to the native code as a diff from ptr_base
268 * [code size: uleb128] size of the generated code
269 * [name: string] full method name
271 * type runtime format:
273 * exinfo: one of: TYPE_JITHELPER
274 * [time diff: uleb128] nanoseconds since last timing
275 * if exinfo == TYPE_JITHELPER
276 * [type: uleb128] MonoProfilerCodeBufferType enum value
277 * [buffer address: sleb128] pointer to the native code as a diff from ptr_base
278 * [buffer size: uleb128] size of the generated code
279 * if type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE
280 * [name: string] buffer description name
282 * type monitor format:
284 * exinfo: TYPE_MONITOR_BT flag and one of: MONO_PROFILER_MONITOR_(CONTENTION|FAIL|DONE)
285 * [time diff: uleb128] nanoseconds since last timing
286 * [object: sleb128] the lock object as a difference from obj_base
287 * if exinfo.low3bits == MONO_PROFILER_MONITOR_CONTENTION
288 * If the TYPE_MONITOR_BT flag is set, a backtrace follows.
292 * exinfo: one of TYPE_HEAP_START, TYPE_HEAP_END, TYPE_HEAP_OBJECT, TYPE_HEAP_ROOT
293 * if exinfo == TYPE_HEAP_START
294 * [time diff: uleb128] nanoseconds since last timing
295 * if exinfo == TYPE_HEAP_END
296 * [time diff: uleb128] nanoseconds since last timing
297 * if exinfo == TYPE_HEAP_OBJECT
298 * [object: sleb128] the object as a difference from obj_base
299 * [class: sleb128] the object MonoClass* as a difference from ptr_base
300 * [size: uleb128] size of the object on the heap
301 * [num_refs: uleb128] number of object references
302 * if (format version > 1) each referenced objref is preceded by a
303 * uleb128 encoded offset: the first offset is from the object address
304 * and each next offset is relative to the previous one
305 * [objrefs: sleb128]+ object referenced as a difference from obj_base
306 * The same object can appear multiple times, but only the first time
307 * with size != 0: in the other cases this data will only be used to
308 * provide additional referenced objects.
309 * if exinfo == TYPE_HEAP_ROOT
310 * [num_roots: uleb128] number of root references
311 * [num_gc: uleb128] number of major gcs
312 * [object: sleb128] the object as a difference from obj_base
313 * [root_type: uleb128] the root_type: MonoProfileGCRootType (profiler.h)
314 * [extra_info: uleb128] the extra_info value
315 * object, root_type and extra_info are repeated num_roots times
319 * exinfo: one of TYPE_SAMPLE_HIT, TYPE_SAMPLE_USYM, TYPE_SAMPLE_UBIN, TYPE_SAMPLE_COUNTERS_DESC, TYPE_SAMPLE_COUNTERS
320 * if exinfo == TYPE_SAMPLE_HIT
321 * [sample_type: uleb128] type of sample (SAMPLE_*)
322 * [timestamp: uleb128] nanoseconds since startup (note: different from other timestamps!)
323 * if (format_version > 10)
324 * [thread: sleb128] thread id as difference from ptr_base
325 * [count: uleb128] number of following instruction addresses
326 * [ip: sleb128]* instruction pointer as difference from ptr_base
327 * if (format_version > 5)
328 * [mbt_count: uleb128] number of managed backtrace info triplets (method + IL offset + native offset)
329 * [method: sleb128]* MonoMethod* as a pointer difference from the last such
330 * pointer or the buffer method_base (the first such method can be also indentified by ip, but this is not neccessarily true)
331 * [il_offset: sleb128]* IL offset inside method where the hit occurred
332 * [native_offset: sleb128]* native offset inside method where the hit occurred
333 * if exinfo == TYPE_SAMPLE_USYM
334 * [address: sleb128] symbol address as a difference from ptr_base
335 * [size: uleb128] symbol size (may be 0 if unknown)
336 * [name: string] symbol name
337 * if exinfo == TYPE_SAMPLE_UBIN
338 * [time diff: uleb128] nanoseconds since last timing
339 * [address: sleb128] address where binary has been loaded
340 * [offset: uleb128] file offset of mapping (the same file can be mapped multiple times)
341 * [size: uleb128] memory size
342 * [name: string] binary name
343 * if exinfo == TYPE_SAMPLE_COUNTERS_DESC
344 * [len: uleb128] number of counters
346 * [section: uleb128] section of counter
347 * if section == MONO_COUNTER_PERFCOUNTERS:
348 * [section_name: string] section name of counter
349 * [name: string] name of counter
350 * [type: uleb128] type of counter
351 * [unit: uleb128] unit of counter
352 * [variance: uleb128] variance of counter
353 * [index: uleb128] unique index of counter
354 * if exinfo == TYPE_SAMPLE_COUNTERS
355 * [timestamp: uleb128] sampling timestamp
357 * [index: uleb128] unique index of counter
360 * [type: uleb128] type of counter value
363 * [0: uleb128] 0 -> value is null
365 * [1: uleb128] 1 -> value is not null
366 * [value: string] counter value
368 * [value: uleb128/sleb128/double] counter value, can be sleb128, uleb128 or double (determined by using type)
370 * type coverage format
371 * type: TYPE_COVERAGE
372 * exinfo: one of TYPE_COVERAGE_METHOD, TYPE_COVERAGE_STATEMENT, TYPE_COVERAGE_ASSEMBLY, TYPE_COVERAGE_CLASS
373 * if exinfo == TYPE_COVERAGE_METHOD
374 * [assembly: string] name of assembly
375 * [class: string] name of the class
376 * [name: string] name of the method
377 * [signature: string] the signature of the method
378 * [filename: string] the file path of the file that contains this method
379 * [token: uleb128] the method token
380 * [method_id: uleb128] an ID for this data to associate with the buffers of TYPE_COVERAGE_STATEMENTS
381 * [len: uleb128] the number of TYPE_COVERAGE_BUFFERS associated with this method
382 * if exinfo == TYPE_COVERAGE_STATEMENTS
383 * [method_id: uleb128] an the TYPE_COVERAGE_METHOD buffer to associate this with
384 * [offset: uleb128] the il offset relative to the previous offset
385 * [counter: uleb128] the counter for this instruction
386 * [line: uleb128] the line of filename containing this instruction
387 * [column: uleb128] the column containing this instruction
388 * if exinfo == TYPE_COVERAGE_ASSEMBLY
389 * [name: string] assembly name
390 * [guid: string] assembly GUID
391 * [filename: string] assembly filename
392 * [number_of_methods: uleb128] the number of methods in this assembly
393 * [fully_covered: uleb128] the number of fully covered methods
394 * [partially_covered: uleb128] the number of partially covered methods
395 * currently partially_covered will always be 0, and fully_covered is the
396 * number of methods that are fully and partially covered.
397 * if exinfo == TYPE_COVERAGE_CLASS
398 * [name: string] assembly name
399 * [class: string] class name
400 * [number_of_methods: uleb128] the number of methods in this class
401 * [fully_covered: uleb128] the number of fully covered methods
402 * [partially_covered: uleb128] the number of partially covered methods
403 * currently partially_covered will always be 0, and fully_covered is the
404 * number of methods that are fully and partially covered.
408 * Format oddities that we ought to fix:
410 * - Methods written in emit_bt () should be based on the buffer's base
411 * method instead of the base pointer.
412 * - The TYPE_SAMPLE_HIT event contains (currently) pointless data like
413 * always-one unmanaged frame count and always-zero IL offsets.
415 * These are mostly small things and are not worth a format change by
416 * themselves. They should be done when some other major change has to
417 * be done to the format.
420 // Pending data to be written to the log, for a single thread.
421 // Threads periodically flush their own LogBuffers by calling safe_send
423 // Next (older) LogBuffer in processing queue
429 uintptr_t method_base;
430 uintptr_t last_method;
436 // Bytes allocated for this LogBuffer
439 // Start of currently unused space in buffer
440 unsigned char* cursor;
442 // Pointer to start-of-structure-plus-size (for convenience)
443 unsigned char* buf_end;
445 // Start of data in buffer. Contents follow "buffer format" described above.
446 unsigned char buf [1];
450 ign_res (int G_GNUC_UNUSED unused, ...)
454 #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++;}
455 #define EXIT_LOG(lb) (lb)->locked--;
457 // Shared queue of sample snapshots taken at signal time.
458 // The queue is written into by signal handlers for all threads;
459 // the helper thread later unqueues and writes into its own LogBuffer.
460 typedef struct _StatBuffer StatBuffer;
462 // Next (older) StatBuffer in processing queue
465 // Bytes allocated for this StatBuffer
468 // Start of currently unused space in buffer
471 // Pointer to start-of-structure-plus-size (for convenience)
474 // Start of data in buffer.
475 // Data consists of a series of sample packets consisting of:
476 // 1 ptrword: Metadata
477 // Low 8 bits: COUNT, the count of native stack frames in this sample (currently always 1)
478 // Next 8 bits: MBT_COUNT, the count of managed stacks in this sample
479 // Next 8 bits: TYPE. See "sampling sources" enum in proflog.h. Usually SAMPLE_CYCLES (1)
480 // 1 ptrword: Thread ID
481 // 1 ptrword: Timestamp
482 // COUNT ptrwords: Native stack frames
483 // Each word is an IP (first is IP where the signal did the interruption)
484 // MBT_COUNT * 4 ptrwords: Managed stack frames (AsyncFrameInfo, repacked)
485 // Word 1: MonoMethod ptr
486 // Word 2: MonoDomain ptr
487 // Word 3: Base address of method
488 // Word 4: Offset within method
492 typedef struct _BinaryObject BinaryObject;
494 struct _BinaryObject {
500 struct _MonoProfiler {
501 StatBuffer *stat_buffers;
503 #if defined (HAVE_SYS_ZLIB)
506 uint64_t startup_time;
508 int last_gc_gen_started;
513 pthread_t helper_thread;
514 pthread_t writer_thread;
516 volatile gint32 run_writer_thread;
517 MonoLockFreeQueue writer_queue;
518 MonoConcurrentHashTable *method_table;
519 mono_mutex_t method_table_mutex;
520 BinaryObject *binary_objects;
521 GPtrArray *coverage_filters;
522 GPtrArray *sorted_sample_events;
525 typedef struct _WriterQueueEntry WriterQueueEntry;
526 struct _WriterQueueEntry {
527 MonoLockFreeQueueNode node;
532 typedef struct _MethodInfo MethodInfo;
544 #define TLS_SET(x,y) (TlsSetValue (x, y))
545 #define TLS_GET(t,x) ((t *) TlsGetValue (x))
546 #define TLS_INIT(x) (x = TlsAlloc ())
547 static int tlsbuffer;
548 static int tlsmethodlist;
550 #define TLS_SET(x,y) (x = y)
551 #define TLS_GET(t,x) (x)
553 static __thread LogBuffer* tlsbuffer = NULL;
554 static __thread GPtrArray* tlsmethodlist = NULL;
556 #define TLS_SET(x,y) (pthread_setspecific (x, y))
557 #define TLS_GET(t,x) ((t *) pthread_getspecific (x))
558 #define TLS_INIT(x) (pthread_key_create (&x, NULL))
559 static pthread_key_t tlsbuffer;
560 static pthread_key_t tlsmethodlist;
563 static void safe_send (MonoProfiler *profiler, LogBuffer *logbuffer);
566 pstrdup (const char *s)
568 int len = strlen (s) + 1;
569 char *p = (char *)malloc (len);
575 create_stat_buffer (void)
577 StatBuffer* buf = (StatBuffer *)alloc_buffer (BUFFER_SIZE);
578 buf->size = BUFFER_SIZE;
579 buf->buf_end = (uintptr_t*)((unsigned char*)buf + buf->size);
580 buf->cursor = buf->buf;
587 LogBuffer* buf = (LogBuffer *)alloc_buffer (BUFFER_SIZE);
588 buf->size = BUFFER_SIZE;
589 buf->time_base = current_time ();
590 buf->last_time = buf->time_base;
591 buf->buf_end = (unsigned char*)buf + buf->size;
592 buf->cursor = buf->buf;
599 if (!TLS_GET (LogBuffer, tlsbuffer)) {
600 LogBuffer *logbuffer = create_buffer ();
601 TLS_SET (tlsbuffer, logbuffer);
602 logbuffer->thread_id = thread_id ();
604 if (!TLS_GET (GPtrArray, tlsmethodlist)) {
605 GPtrArray *methodlist = g_ptr_array_new ();
606 TLS_SET (tlsmethodlist, methodlist);
609 //printf ("thread %p at time %llu\n", (void*)logbuffer->thread_id, logbuffer->time_base);
613 ensure_logbuf_inner (LogBuffer *old, int bytes)
615 if (old && old->cursor + bytes + 100 < old->buf_end)
618 LogBuffer *new_ = (LogBuffer *)create_buffer ();
619 new_->thread_id = thread_id ();
623 new_->call_depth = old->call_depth;
629 ensure_logbuf (int bytes)
631 LogBuffer *old = TLS_GET (LogBuffer, tlsbuffer);
632 LogBuffer *new_ = ensure_logbuf_inner (old, bytes);
635 return old; // Still enough space.
637 TLS_SET (tlsbuffer, new_);
644 emit_byte (LogBuffer *logbuffer, int value)
646 logbuffer->cursor [0] = value;
648 assert (logbuffer->cursor <= logbuffer->buf_end);
652 emit_value (LogBuffer *logbuffer, int value)
654 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
655 assert (logbuffer->cursor <= logbuffer->buf_end);
659 emit_time (LogBuffer *logbuffer, uint64_t value)
661 uint64_t tdiff = value - logbuffer->last_time;
662 //if (value < logbuffer->last_time)
663 // printf ("time went backwards\n");
664 //if (tdiff > 1000000)
665 // printf ("large time offset: %llu\n", tdiff);
666 encode_uleb128 (tdiff, logbuffer->cursor, &logbuffer->cursor);
667 /*if (tdiff != decode_uleb128 (p, &p))
668 printf ("incorrect encoding: %llu\n", tdiff);*/
669 logbuffer->last_time = value;
670 assert (logbuffer->cursor <= logbuffer->buf_end);
674 emit_svalue (LogBuffer *logbuffer, int64_t value)
676 encode_sleb128 (value, logbuffer->cursor, &logbuffer->cursor);
677 assert (logbuffer->cursor <= logbuffer->buf_end);
681 emit_uvalue (LogBuffer *logbuffer, uint64_t value)
683 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
684 assert (logbuffer->cursor <= logbuffer->buf_end);
688 emit_ptr (LogBuffer *logbuffer, void *ptr)
690 if (!logbuffer->ptr_base)
691 logbuffer->ptr_base = (uintptr_t)ptr;
692 emit_svalue (logbuffer, (intptr_t)ptr - logbuffer->ptr_base);
693 assert (logbuffer->cursor <= logbuffer->buf_end);
697 emit_method_inner (LogBuffer *logbuffer, void *method)
699 if (!logbuffer->method_base) {
700 logbuffer->method_base = (intptr_t)method;
701 logbuffer->last_method = (intptr_t)method;
703 encode_sleb128 ((intptr_t)((char*)method - (char*)logbuffer->last_method), logbuffer->cursor, &logbuffer->cursor);
704 logbuffer->last_method = (intptr_t)method;
705 assert (logbuffer->cursor <= logbuffer->buf_end);
715 find_method (MonoDomain *domain, void *user_data)
717 MethodSearch *search = user_data;
722 MonoJitInfo *ji = mono_get_jit_info_from_method (domain, search->method);
724 // It could be AOT'd, so we need to get it from the AOT runtime's cache.
726 void *ip = mono_aot_get_method (domain, search->method);
728 // Avoid a slow path in mono_jit_info_table_find ().
730 ji = mono_jit_info_table_find (domain, ip);
739 register_method_local (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji)
741 if (!mono_conc_hashtable_lookup (prof->method_table, method)) {
743 * FIXME: In some cases, we crash while looking up JIT info for AOT'd methods.
744 * This usually happens for static constructors. This code is disabled for now
745 * as we don't need this info for anything critical.
747 * https://bugzilla.xamarin.com/show_bug.cgi?id=35171
751 MethodSearch search = { method, NULL };
753 mono_domain_foreach (find_method, &search);
760 * FIXME: We can't always find JIT info for a generic shared method, especially
761 * if we obtained the MonoMethod during an async stack walk. For now, we deal
762 * with this by giving the generic shared method name and dummy code start/size
763 * information (i.e. zeroes).
767 MethodInfo *info = (MethodInfo *)malloc (sizeof (MethodInfo));
769 info->method = method;
771 info->time = current_time ();
773 g_ptr_array_add (TLS_GET (GPtrArray, tlsmethodlist), info);
778 emit_method (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
780 register_method_local (prof, method, NULL);
781 emit_method_inner (logbuffer, method);
785 emit_method_as_ptr (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
787 register_method_local (prof, method, NULL);
788 emit_ptr (logbuffer, method);
792 emit_obj (LogBuffer *logbuffer, void *ptr)
794 if (!logbuffer->obj_base)
795 logbuffer->obj_base = (uintptr_t)ptr >> 3;
796 emit_svalue (logbuffer, ((uintptr_t)ptr >> 3) - logbuffer->obj_base);
797 assert (logbuffer->cursor <= logbuffer->buf_end);
801 emit_string (LogBuffer *logbuffer, const char *str, size_t size)
805 for (; i < size; i++) {
808 emit_byte (logbuffer, str [i]);
811 emit_byte (logbuffer, '\0');
815 emit_double (LogBuffer *logbuffer, double value)
818 unsigned char buffer[8];
819 memcpy (buffer, &value, 8);
820 #if G_BYTE_ORDER == G_BIG_ENDIAN
821 for (i = 7; i >= 0; i--)
823 for (i = 0; i < 8; i++)
825 emit_byte (logbuffer, buffer[i]);
829 write_int16 (char *buf, int32_t value)
832 for (i = 0; i < 2; ++i) {
840 write_int32 (char *buf, int32_t value)
843 for (i = 0; i < 4; ++i) {
851 write_int64 (char *buf, int64_t value)
854 for (i = 0; i < 8; ++i) {
862 dump_header (MonoProfiler *profiler)
866 p = write_int32 (p, LOG_HEADER_ID);
867 *p++ = LOG_VERSION_MAJOR;
868 *p++ = LOG_VERSION_MINOR;
869 *p++ = LOG_DATA_VERSION;
870 *p++ = sizeof (void*);
871 p = write_int64 (p, ((uint64_t)time (NULL)) * 1000); /* startup time */
872 p = write_int32 (p, get_timer_overhead ()); /* timer overhead */
873 p = write_int32 (p, 0); /* flags */
874 p = write_int32 (p, process_id ()); /* pid */
875 p = write_int16 (p, profiler->command_port); /* port */
876 p = write_int16 (p, 0); /* opsystem */
877 #if defined (HAVE_SYS_ZLIB)
878 if (profiler->gzfile) {
879 gzwrite (profiler->gzfile, hbuf, p - hbuf);
881 fwrite (hbuf, p - hbuf, 1, profiler->file);
884 fwrite (hbuf, p - hbuf, 1, profiler->file);
885 fflush (profiler->file);
890 send_buffer (MonoProfiler *prof, GPtrArray *methods, LogBuffer *buffer)
892 WriterQueueEntry *entry = (WriterQueueEntry *)calloc (1, sizeof (WriterQueueEntry));
893 mono_lock_free_queue_node_init (&entry->node, FALSE);
894 entry->methods = methods;
895 entry->buffer = buffer;
896 mono_lock_free_queue_enqueue (&prof->writer_queue, &entry->node);
900 dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
905 dump_buffer (profiler, buf->next);
906 p = write_int32 (p, BUF_ID);
907 p = write_int32 (p, buf->cursor - buf->buf);
908 p = write_int64 (p, buf->time_base);
909 p = write_int64 (p, buf->ptr_base);
910 p = write_int64 (p, buf->obj_base);
911 p = write_int64 (p, buf->thread_id);
912 p = write_int64 (p, buf->method_base);
913 #if defined (HAVE_SYS_ZLIB)
914 if (profiler->gzfile) {
915 gzwrite (profiler->gzfile, hbuf, p - hbuf);
916 gzwrite (profiler->gzfile, buf->buf, buf->cursor - buf->buf);
919 fwrite (hbuf, p - hbuf, 1, profiler->file);
920 fwrite (buf->buf, buf->cursor - buf->buf, 1, profiler->file);
921 fflush (profiler->file);
922 #if defined (HAVE_SYS_ZLIB)
925 free_buffer (buf, buf->size);
929 process_requests (MonoProfiler *profiler)
931 if (heapshot_requested)
932 mono_gc_collect (mono_gc_max_generation ());
935 static void counters_init (MonoProfiler *profiler);
936 static void counters_sample (MonoProfiler *profiler, uint64_t timestamp);
939 * Can be called only at safe callback locations.
942 safe_send (MonoProfiler *profiler, LogBuffer *logbuffer)
944 /* We need the runtime initialized so that we have threads and hazard
945 * pointers available. Otherwise, the lock free queue will not work and
946 * there won't be a thread to process the data.
948 * While the runtime isn't initialized, we just accumulate data in the
949 * thread local buffer list.
951 if (!InterlockedRead (&runtime_inited))
954 int cd = logbuffer->call_depth;
956 send_buffer (profiler, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
958 TLS_SET (tlsbuffer, NULL);
959 TLS_SET (tlsmethodlist, NULL);
963 TLS_GET (LogBuffer, tlsbuffer)->call_depth = cd;
967 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
970 uintptr_t last_offset = 0;
971 //const char *name = mono_class_get_name (klass);
972 LogBuffer *logbuffer = ensure_logbuf (
973 EVENT_SIZE /* event */ +
974 LEB128_SIZE /* obj */ +
975 LEB128_SIZE /* klass */ +
976 LEB128_SIZE /* size */ +
977 LEB128_SIZE /* num */ +
979 LEB128_SIZE /* offset */ +
980 LEB128_SIZE /* ref */
983 emit_byte (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
984 emit_obj (logbuffer, obj);
985 emit_ptr (logbuffer, klass);
986 /* account for object alignment in the heap */
989 emit_value (logbuffer, size);
990 emit_value (logbuffer, num);
991 for (i = 0; i < num; ++i) {
992 emit_value (logbuffer, offsets [i] - last_offset);
993 last_offset = offsets [i];
994 emit_obj (logbuffer, refs [i]);
997 // printf ("obj: %p, klass: %s, refs: %d, size: %d\n", obj, name, (int)num, (int)size);
1001 static unsigned int hs_mode_ms = 0;
1002 static unsigned int hs_mode_gc = 0;
1003 static unsigned int hs_mode_ondemand = 0;
1004 static unsigned int gc_count = 0;
1005 static uint64_t last_hs_time = 0;
1008 heap_walk (MonoProfiler *profiler)
1012 LogBuffer *logbuffer;
1015 logbuffer = ensure_logbuf (
1016 EVENT_SIZE /* event */ +
1017 LEB128_SIZE /* time */
1019 now = current_time ();
1020 if (hs_mode_ms && (now - last_hs_time)/1000000 >= hs_mode_ms)
1022 else if (hs_mode_gc && (gc_count % hs_mode_gc) == 0)
1024 else if (hs_mode_ondemand)
1025 do_walk = heapshot_requested;
1026 else if (!hs_mode_ms && !hs_mode_gc && profiler->last_gc_gen_started == mono_gc_max_generation ())
1031 heapshot_requested = 0;
1032 emit_byte (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
1033 emit_time (logbuffer, now);
1034 mono_gc_walk_heap (0, gc_reference, NULL);
1035 logbuffer = ensure_logbuf (
1036 EVENT_SIZE /* event */ +
1037 LEB128_SIZE /* time */
1039 now = current_time ();
1040 emit_byte (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
1041 emit_time (logbuffer, now);
1046 gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation) {
1048 LogBuffer *logbuffer = ensure_logbuf (
1049 EVENT_SIZE /* event */ +
1050 LEB128_SIZE /* time */ +
1051 LEB128_SIZE /* gc event */ +
1052 LEB128_SIZE /* generation */
1054 now = current_time ();
1055 ENTER_LOG (logbuffer, "gcevent");
1056 emit_byte (logbuffer, TYPE_GC_EVENT | TYPE_GC);
1057 emit_time (logbuffer, now);
1058 emit_value (logbuffer, ev);
1059 emit_value (logbuffer, generation);
1060 /* to deal with nested gen1 after gen0 started */
1061 if (ev == MONO_GC_EVENT_START) {
1062 profiler->last_gc_gen_started = generation;
1063 if (generation == mono_gc_max_generation ())
1066 if (ev == MONO_GC_EVENT_PRE_START_WORLD)
1067 heap_walk (profiler);
1068 EXIT_LOG (logbuffer);
1069 if (ev == MONO_GC_EVENT_POST_START_WORLD)
1070 safe_send (profiler, logbuffer);
1071 //printf ("gc event %d for generation %d\n", ev, generation);
1075 gc_resize (MonoProfiler *profiler, int64_t new_size) {
1077 LogBuffer *logbuffer = ensure_logbuf (
1078 EVENT_SIZE /* event */ +
1079 LEB128_SIZE /* time */ +
1080 LEB128_SIZE /* new size */
1082 now = current_time ();
1083 ENTER_LOG (logbuffer, "gcresize");
1084 emit_byte (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
1085 emit_time (logbuffer, now);
1086 emit_value (logbuffer, new_size);
1087 //printf ("gc resized to %lld\n", new_size);
1088 EXIT_LOG (logbuffer);
1091 #define MAX_FRAMES 32
1094 MonoMethod* methods [MAX_FRAMES];
1095 int32_t il_offsets [MAX_FRAMES];
1096 int32_t native_offsets [MAX_FRAMES];
1098 static int num_frames = MAX_FRAMES;
1101 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
1103 FrameData *frame = (FrameData *)data;
1104 if (method && frame->count < num_frames) {
1105 frame->il_offsets [frame->count] = il_offset;
1106 frame->native_offsets [frame->count] = native_offset;
1107 frame->methods [frame->count++] = method;
1108 //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
1110 return frame->count == num_frames;
1114 * a note about stack walks: they can cause more profiler events to fire,
1115 * so we need to make sure they don't happen after we started emitting an
1116 * event, hence the collect_bt/emit_bt split.
1119 collect_bt (FrameData *data)
1122 mono_stack_walk_no_il (walk_stack, data);
1126 emit_bt (MonoProfiler *prof, LogBuffer *logbuffer, FrameData *data)
1128 /* FIXME: this is actually tons of data and we should
1129 * just output it the first time and use an id the next
1131 if (data->count > num_frames)
1132 printf ("bad num frames: %d\n", data->count);
1133 emit_value (logbuffer, 0); /* flags */
1134 emit_value (logbuffer, data->count);
1135 //if (*p != data.count) {
1136 // 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);}
1137 while (data->count) {
1138 emit_method_as_ptr (prof, logbuffer, data->methods [--data->count]);
1143 gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1147 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces)? TYPE_ALLOC_BT: 0;
1149 LogBuffer *logbuffer;
1150 len = mono_object_get_size (obj);
1151 /* account for object alignment in the heap */
1156 logbuffer = ensure_logbuf (
1157 EVENT_SIZE /* event */ +
1158 LEB128_SIZE /* time */ +
1159 LEB128_SIZE /* klass */ +
1160 LEB128_SIZE /* obj */ +
1161 LEB128_SIZE /* size */ +
1163 LEB128_SIZE /* flags */ +
1164 LEB128_SIZE /* count */ +
1166 LEB128_SIZE /* method */
1170 now = current_time ();
1171 ENTER_LOG (logbuffer, "gcalloc");
1172 emit_byte (logbuffer, do_bt | TYPE_ALLOC);
1173 emit_time (logbuffer, now);
1174 emit_ptr (logbuffer, klass);
1175 emit_obj (logbuffer, obj);
1176 emit_value (logbuffer, len);
1178 emit_bt (prof, logbuffer, &data);
1179 EXIT_LOG (logbuffer);
1180 if (logbuffer->next)
1181 safe_send (prof, logbuffer);
1182 process_requests (prof);
1183 //printf ("gc alloc %s at %p\n", mono_class_get_name (klass), obj);
1187 gc_moves (MonoProfiler *prof, void **objects, int num)
1191 LogBuffer *logbuffer = ensure_logbuf (
1192 EVENT_SIZE /* event */ +
1193 LEB128_SIZE /* time */ +
1194 LEB128_SIZE /* num */ +
1196 LEB128_SIZE /* object */
1199 now = current_time ();
1200 ENTER_LOG (logbuffer, "gcmove");
1201 emit_byte (logbuffer, TYPE_GC_MOVE | TYPE_GC);
1202 emit_time (logbuffer, now);
1203 emit_value (logbuffer, num);
1204 for (i = 0; i < num; ++i)
1205 emit_obj (logbuffer, objects [i]);
1206 //printf ("gc moved %d objects\n", num/2);
1207 EXIT_LOG (logbuffer);
1211 gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
1214 LogBuffer *logbuffer = ensure_logbuf (
1215 EVENT_SIZE /* event */ +
1216 LEB128_SIZE /* num */ +
1217 LEB128_SIZE /* collections */ +
1219 LEB128_SIZE /* object */ +
1220 LEB128_SIZE /* root type */ +
1221 LEB128_SIZE /* extra info */
1224 ENTER_LOG (logbuffer, "gcroots");
1225 emit_byte (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
1226 emit_value (logbuffer, num);
1227 emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
1228 for (i = 0; i < num; ++i) {
1229 emit_obj (logbuffer, objects [i]);
1230 emit_value (logbuffer, root_types [i]);
1231 emit_value (logbuffer, extra_info [i]);
1233 EXIT_LOG (logbuffer);
1237 gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
1239 int do_bt = nocalls && InterlockedRead (&runtime_inited) && !notraces;
1246 LogBuffer *logbuffer = ensure_logbuf (
1247 EVENT_SIZE /* event */ +
1248 LEB128_SIZE /* time */ +
1249 LEB128_SIZE /* type */ +
1250 LEB128_SIZE /* handle */ +
1251 (op == MONO_PROFILER_GC_HANDLE_CREATED ? (
1252 LEB128_SIZE /* obj */
1255 LEB128_SIZE /* flags */ +
1256 LEB128_SIZE /* count */ +
1258 LEB128_SIZE /* method */
1263 now = current_time ();
1264 ENTER_LOG (logbuffer, "gchandle");
1266 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1267 emit_byte (logbuffer, (do_bt ? TYPE_GC_HANDLE_CREATED_BT : TYPE_GC_HANDLE_CREATED) | TYPE_GC);
1268 else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
1269 emit_byte (logbuffer, (do_bt ? TYPE_GC_HANDLE_DESTROYED_BT : TYPE_GC_HANDLE_DESTROYED) | TYPE_GC);
1271 g_assert_not_reached ();
1273 emit_time (logbuffer, now);
1274 emit_value (logbuffer, type);
1275 emit_value (logbuffer, handle);
1277 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1278 emit_obj (logbuffer, obj);
1281 emit_bt (prof, logbuffer, &data);
1283 EXIT_LOG (logbuffer);
1284 process_requests (prof);
1288 push_nesting (char *p, MonoClass *klass)
1293 nesting = mono_class_get_nesting_type (klass);
1295 p = push_nesting (p, nesting);
1299 name = mono_class_get_name (klass);
1300 nspace = mono_class_get_namespace (klass);
1303 p += strlen (nspace);
1313 type_name (MonoClass *klass)
1317 push_nesting (buf, klass);
1318 p = (char *)malloc (strlen (buf) + 1);
1324 image_loaded (MonoProfiler *prof, MonoImage *image, int result)
1329 LogBuffer *logbuffer;
1330 if (result != MONO_PROFILE_OK)
1332 name = mono_image_get_filename (image);
1333 nlen = strlen (name) + 1;
1334 logbuffer = ensure_logbuf (
1335 EVENT_SIZE /* event */ +
1336 LEB128_SIZE /* time */ +
1337 EVENT_SIZE /* type */ +
1338 LEB128_SIZE /* image */ +
1339 LEB128_SIZE /* flags */ +
1342 now = current_time ();
1343 ENTER_LOG (logbuffer, "image");
1344 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1345 emit_time (logbuffer, now);
1346 emit_byte (logbuffer, TYPE_IMAGE);
1347 emit_ptr (logbuffer, image);
1348 emit_value (logbuffer, 0); /* flags */
1349 memcpy (logbuffer->cursor, name, nlen);
1350 logbuffer->cursor += nlen;
1351 //printf ("loaded image %p (%s)\n", image, name);
1352 EXIT_LOG (logbuffer);
1353 if (logbuffer->next)
1354 safe_send (prof, logbuffer);
1355 process_requests (prof);
1359 image_unloaded (MonoProfiler *prof, MonoImage *image)
1361 const char *name = mono_image_get_filename (image);
1362 int nlen = strlen (name) + 1;
1363 LogBuffer *logbuffer = ensure_logbuf (
1364 EVENT_SIZE /* event */ +
1365 LEB128_SIZE /* time */ +
1366 EVENT_SIZE /* type */ +
1367 LEB128_SIZE /* image */ +
1368 LEB128_SIZE /* flags */ +
1371 uint64_t now = current_time ();
1373 ENTER_LOG (logbuffer, "image-unload");
1374 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1375 emit_time (logbuffer, now);
1376 emit_byte (logbuffer, TYPE_IMAGE);
1377 emit_ptr (logbuffer, image);
1378 emit_value (logbuffer, 0); /* flags */
1379 memcpy (logbuffer->cursor, name, nlen);
1380 logbuffer->cursor += nlen;
1381 EXIT_LOG (logbuffer);
1383 if (logbuffer->next)
1384 safe_send (prof, logbuffer);
1386 process_requests (prof);
1390 assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly, int result)
1392 if (result != MONO_PROFILE_OK)
1395 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1396 int nlen = strlen (name) + 1;
1397 LogBuffer *logbuffer = ensure_logbuf (
1398 EVENT_SIZE /* event */ +
1399 LEB128_SIZE /* time */ +
1400 EVENT_SIZE /* type */ +
1401 LEB128_SIZE /* assembly */ +
1402 LEB128_SIZE /* flags */ +
1405 uint64_t now = current_time ();
1407 ENTER_LOG (logbuffer, "assembly-load");
1408 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1409 emit_time (logbuffer, now);
1410 emit_byte (logbuffer, TYPE_ASSEMBLY);
1411 emit_ptr (logbuffer, assembly);
1412 emit_value (logbuffer, 0); /* flags */
1413 memcpy (logbuffer->cursor, name, nlen);
1414 logbuffer->cursor += nlen;
1415 EXIT_LOG (logbuffer);
1419 if (logbuffer->next)
1420 safe_send (prof, logbuffer);
1422 process_requests (prof);
1426 assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
1428 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1429 int nlen = strlen (name) + 1;
1430 LogBuffer *logbuffer = ensure_logbuf (
1431 EVENT_SIZE /* event */ +
1432 LEB128_SIZE /* time */ +
1433 EVENT_SIZE /* type */ +
1434 LEB128_SIZE /* assembly */ +
1435 LEB128_SIZE /* flags */ +
1438 uint64_t now = current_time ();
1440 ENTER_LOG (logbuffer, "assembly-unload");
1441 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1442 emit_time (logbuffer, now);
1443 emit_byte (logbuffer, TYPE_ASSEMBLY);
1444 emit_ptr (logbuffer, assembly);
1445 emit_value (logbuffer, 0); /* flags */
1446 memcpy (logbuffer->cursor, name, nlen);
1447 logbuffer->cursor += nlen;
1448 EXIT_LOG (logbuffer);
1452 if (logbuffer->next)
1453 safe_send (prof, logbuffer);
1455 process_requests (prof);
1459 class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
1465 LogBuffer *logbuffer;
1466 if (result != MONO_PROFILE_OK)
1468 if (InterlockedRead (&runtime_inited))
1469 name = mono_type_get_name (mono_class_get_type (klass));
1471 name = type_name (klass);
1472 nlen = strlen (name) + 1;
1473 image = mono_class_get_image (klass);
1474 logbuffer = ensure_logbuf (
1475 EVENT_SIZE /* event */ +
1476 LEB128_SIZE /* time */ +
1477 EVENT_SIZE /* type */ +
1478 LEB128_SIZE /* klass */ +
1479 LEB128_SIZE /* image */ +
1480 LEB128_SIZE /* flags */ +
1483 now = current_time ();
1484 ENTER_LOG (logbuffer, "class");
1485 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1486 emit_time (logbuffer, now);
1487 emit_byte (logbuffer, TYPE_CLASS);
1488 emit_ptr (logbuffer, klass);
1489 emit_ptr (logbuffer, image);
1490 emit_value (logbuffer, 0); /* flags */
1491 memcpy (logbuffer->cursor, name, nlen);
1492 logbuffer->cursor += nlen;
1493 //printf ("loaded class %p (%s)\n", klass, name);
1498 EXIT_LOG (logbuffer);
1499 if (logbuffer->next)
1500 safe_send (prof, logbuffer);
1501 process_requests (prof);
1505 class_unloaded (MonoProfiler *prof, MonoClass *klass)
1509 if (InterlockedRead (&runtime_inited))
1510 name = mono_type_get_name (mono_class_get_type (klass));
1512 name = type_name (klass);
1514 int nlen = strlen (name) + 1;
1515 MonoImage *image = mono_class_get_image (klass);
1516 LogBuffer *logbuffer = ensure_logbuf (
1517 EVENT_SIZE /* event */ +
1518 LEB128_SIZE /* time */ +
1519 EVENT_SIZE /* type */ +
1520 LEB128_SIZE /* klass */ +
1521 LEB128_SIZE /* image */ +
1522 LEB128_SIZE /* flags */ +
1525 uint64_t now = current_time ();
1527 ENTER_LOG (logbuffer, "class-unload");
1528 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1529 emit_time (logbuffer, now);
1530 emit_byte (logbuffer, TYPE_CLASS);
1531 emit_ptr (logbuffer, klass);
1532 emit_ptr (logbuffer, image);
1533 emit_value (logbuffer, 0); /* flags */
1534 memcpy (logbuffer->cursor, name, nlen);
1535 logbuffer->cursor += nlen;
1536 EXIT_LOG (logbuffer);
1543 if (logbuffer->next)
1544 safe_send (prof, logbuffer);
1546 process_requests (prof);
1549 #ifndef DISABLE_HELPER_THREAD
1550 static void process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method);
1551 #endif /* DISABLE_HELPER_THREAD */
1554 method_enter (MonoProfiler *prof, MonoMethod *method)
1556 uint64_t now = current_time ();
1558 #ifndef DISABLE_HELPER_THREAD
1559 process_method_enter_coverage (prof, method);
1560 #endif /* DISABLE_HELPER_THREAD */
1562 LogBuffer *logbuffer = ensure_logbuf (
1563 EVENT_SIZE /* event */ +
1564 LEB128_SIZE /* time */ +
1565 LEB128_SIZE /* method */
1567 if (logbuffer->call_depth++ > max_call_depth)
1569 ENTER_LOG (logbuffer, "enter");
1570 emit_byte (logbuffer, TYPE_ENTER | TYPE_METHOD);
1571 emit_time (logbuffer, now);
1572 emit_method (prof, logbuffer, method);
1573 EXIT_LOG (logbuffer);
1575 process_requests (prof);
1579 method_leave (MonoProfiler *prof, MonoMethod *method)
1582 LogBuffer *logbuffer = ensure_logbuf (
1583 EVENT_SIZE /* event */ +
1584 LEB128_SIZE /* time */ +
1585 LEB128_SIZE /* method */
1587 if (--logbuffer->call_depth > max_call_depth)
1589 now = current_time ();
1590 ENTER_LOG (logbuffer, "leave");
1591 emit_byte (logbuffer, TYPE_LEAVE | TYPE_METHOD);
1592 emit_time (logbuffer, now);
1593 emit_method (prof, logbuffer, method);
1594 EXIT_LOG (logbuffer);
1595 if (logbuffer->next)
1596 safe_send (prof, logbuffer);
1597 process_requests (prof);
1601 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
1604 LogBuffer *logbuffer;
1607 logbuffer = ensure_logbuf (
1608 EVENT_SIZE /* event */ +
1609 LEB128_SIZE /* time */ +
1610 LEB128_SIZE /* method */
1612 if (--logbuffer->call_depth > max_call_depth)
1614 now = current_time ();
1615 ENTER_LOG (logbuffer, "eleave");
1616 emit_byte (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
1617 emit_time (logbuffer, now);
1618 emit_method (prof, logbuffer, method);
1619 EXIT_LOG (logbuffer);
1620 process_requests (prof);
1624 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji, int result)
1626 if (result != MONO_PROFILE_OK)
1629 register_method_local (prof, method, ji);
1631 process_requests (prof);
1635 code_buffer_new (MonoProfiler *prof, void *buffer, int size, MonoProfilerCodeBufferType type, void *data)
1640 LogBuffer *logbuffer;
1641 if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
1642 name = (char *)data;
1643 nlen = strlen (name) + 1;
1648 logbuffer = ensure_logbuf (
1649 EVENT_SIZE /* event */ +
1650 LEB128_SIZE /* time */ +
1651 LEB128_SIZE /* type */ +
1652 LEB128_SIZE /* buffer */ +
1653 LEB128_SIZE /* size */ +
1658 now = current_time ();
1659 ENTER_LOG (logbuffer, "code buffer");
1660 emit_byte (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
1661 emit_time (logbuffer, now);
1662 emit_value (logbuffer, type);
1663 emit_ptr (logbuffer, buffer);
1664 emit_value (logbuffer, size);
1666 memcpy (logbuffer->cursor, name, nlen);
1667 logbuffer->cursor += nlen;
1669 EXIT_LOG (logbuffer);
1670 process_requests (prof);
1674 throw_exc (MonoProfiler *prof, MonoObject *object)
1676 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces)? TYPE_EXCEPTION_BT: 0;
1679 LogBuffer *logbuffer;
1682 logbuffer = ensure_logbuf (
1683 EVENT_SIZE /* event */ +
1684 LEB128_SIZE /* time */ +
1685 LEB128_SIZE /* object */ +
1687 LEB128_SIZE /* flags */ +
1688 LEB128_SIZE /* count */ +
1690 LEB128_SIZE /* method */
1694 now = current_time ();
1695 ENTER_LOG (logbuffer, "throw");
1696 emit_byte (logbuffer, do_bt | TYPE_EXCEPTION);
1697 emit_time (logbuffer, now);
1698 emit_obj (logbuffer, object);
1700 emit_bt (prof, logbuffer, &data);
1701 EXIT_LOG (logbuffer);
1702 process_requests (prof);
1706 clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
1709 LogBuffer *logbuffer = ensure_logbuf (
1710 EVENT_SIZE /* event */ +
1711 LEB128_SIZE /* time */ +
1712 LEB128_SIZE /* clause type */ +
1713 LEB128_SIZE /* clause num */ +
1714 LEB128_SIZE /* method */
1716 now = current_time ();
1717 ENTER_LOG (logbuffer, "clause");
1718 emit_byte (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
1719 emit_time (logbuffer, now);
1720 emit_value (logbuffer, clause_type);
1721 emit_value (logbuffer, clause_num);
1722 emit_method (prof, logbuffer, method);
1723 EXIT_LOG (logbuffer);
1725 process_requests (prof);
1729 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
1731 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION)? TYPE_MONITOR_BT: 0;
1734 LogBuffer *logbuffer;
1737 logbuffer = ensure_logbuf (
1738 EVENT_SIZE /* event */ +
1739 LEB128_SIZE /* time */ +
1740 LEB128_SIZE /* object */ +
1742 LEB128_SIZE /* flags */ +
1743 LEB128_SIZE /* count */ +
1745 LEB128_SIZE /* method */
1749 now = current_time ();
1750 ENTER_LOG (logbuffer, "monitor");
1751 emit_byte (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
1752 emit_time (logbuffer, now);
1753 emit_obj (logbuffer, object);
1755 emit_bt (profiler, logbuffer, &data);
1756 EXIT_LOG (logbuffer);
1757 process_requests (profiler);
1761 thread_start (MonoProfiler *prof, uintptr_t tid)
1763 //printf ("thread start %p\n", (void*)tid);
1766 LogBuffer *logbuffer = ensure_logbuf (
1767 EVENT_SIZE /* event */ +
1768 LEB128_SIZE /* time */ +
1769 EVENT_SIZE /* type */ +
1770 LEB128_SIZE /* tid */ +
1771 LEB128_SIZE /* flags */
1773 uint64_t now = current_time ();
1775 ENTER_LOG (logbuffer, "thread-start");
1776 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1777 emit_time (logbuffer, now);
1778 emit_byte (logbuffer, TYPE_THREAD);
1779 emit_ptr (logbuffer, (void*) tid);
1780 emit_value (logbuffer, 0); /* flags */
1781 EXIT_LOG (logbuffer);
1783 if (logbuffer->next)
1784 safe_send (prof, logbuffer);
1786 process_requests (prof);
1790 thread_end (MonoProfiler *prof, uintptr_t tid)
1792 if (TLS_GET (LogBuffer, tlsbuffer)) {
1793 LogBuffer *logbuffer = ensure_logbuf (
1794 EVENT_SIZE /* event */ +
1795 LEB128_SIZE /* time */ +
1796 EVENT_SIZE /* type */ +
1797 LEB128_SIZE /* tid */ +
1798 LEB128_SIZE /* flags */
1800 uint64_t now = current_time ();
1802 ENTER_LOG (logbuffer, "thread-end");
1803 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1804 emit_time (logbuffer, now);
1805 emit_byte (logbuffer, TYPE_THREAD);
1806 emit_ptr (logbuffer, (void*) tid);
1807 emit_value (logbuffer, 0); /* flags */
1808 EXIT_LOG (logbuffer);
1810 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), logbuffer);
1812 /* Don't process requests as the thread is detached from the runtime. */
1815 TLS_SET (tlsbuffer, NULL);
1816 TLS_SET (tlsmethodlist, NULL);
1820 domain_loaded (MonoProfiler *prof, MonoDomain *domain, int result)
1822 if (result != MONO_PROFILE_OK)
1825 LogBuffer *logbuffer = ensure_logbuf (
1826 EVENT_SIZE /* event */ +
1827 LEB128_SIZE /* time */ +
1828 EVENT_SIZE /* type */ +
1829 LEB128_SIZE /* domain id */ +
1830 LEB128_SIZE /* flags */
1832 uint64_t now = current_time ();
1834 ENTER_LOG (logbuffer, "domain-start");
1835 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1836 emit_time (logbuffer, now);
1837 emit_byte (logbuffer, TYPE_DOMAIN);
1838 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1839 emit_value (logbuffer, 0); /* flags */
1840 EXIT_LOG (logbuffer);
1842 if (logbuffer->next)
1843 safe_send (prof, logbuffer);
1845 process_requests (prof);
1849 domain_unloaded (MonoProfiler *prof, MonoDomain *domain)
1851 LogBuffer *logbuffer = ensure_logbuf (
1852 EVENT_SIZE /* event */ +
1853 LEB128_SIZE /* time */ +
1854 EVENT_SIZE /* type */ +
1855 LEB128_SIZE /* domain id */ +
1856 LEB128_SIZE /* flags */
1858 uint64_t now = current_time ();
1860 ENTER_LOG (logbuffer, "domain-end");
1861 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1862 emit_time (logbuffer, now);
1863 emit_byte (logbuffer, TYPE_DOMAIN);
1864 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1865 emit_value (logbuffer, 0); /* flags */
1866 EXIT_LOG (logbuffer);
1868 if (logbuffer->next)
1869 safe_send (prof, logbuffer);
1871 process_requests (prof);
1875 domain_name (MonoProfiler *prof, MonoDomain *domain, const char *name)
1877 int nlen = strlen (name) + 1;
1878 LogBuffer *logbuffer = ensure_logbuf (
1879 EVENT_SIZE /* event */ +
1880 LEB128_SIZE /* time */ +
1881 EVENT_SIZE /* type */ +
1882 LEB128_SIZE /* domain id */ +
1883 LEB128_SIZE /* flags */ +
1886 uint64_t now = current_time ();
1888 ENTER_LOG (logbuffer, "domain-name");
1889 emit_byte (logbuffer, TYPE_METADATA);
1890 emit_time (logbuffer, now);
1891 emit_byte (logbuffer, TYPE_DOMAIN);
1892 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1893 emit_value (logbuffer, 0); /* flags */
1894 memcpy (logbuffer->cursor, name, nlen);
1895 logbuffer->cursor += nlen;
1896 EXIT_LOG (logbuffer);
1898 if (logbuffer->next)
1899 safe_send (prof, logbuffer);
1901 process_requests (prof);
1905 context_loaded (MonoProfiler *prof, MonoAppContext *context)
1907 LogBuffer *logbuffer = ensure_logbuf (
1908 EVENT_SIZE /* event */ +
1909 LEB128_SIZE /* time */ +
1910 EVENT_SIZE /* type */ +
1911 LEB128_SIZE /* context id */ +
1912 LEB128_SIZE /* flags */ +
1913 LEB128_SIZE /* domain id */
1915 uint64_t now = current_time ();
1917 ENTER_LOG (logbuffer, "context-start");
1918 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1919 emit_time (logbuffer, now);
1920 emit_byte (logbuffer, TYPE_CONTEXT);
1921 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
1922 emit_value (logbuffer, 0); /* flags */
1923 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
1924 EXIT_LOG (logbuffer);
1926 if (logbuffer->next)
1927 safe_send (prof, logbuffer);
1929 process_requests (prof);
1933 context_unloaded (MonoProfiler *prof, MonoAppContext *context)
1935 LogBuffer *logbuffer = ensure_logbuf (
1936 EVENT_SIZE /* event */ +
1937 LEB128_SIZE /* time */ +
1938 EVENT_SIZE /* type */ +
1939 LEB128_SIZE /* context id */ +
1940 LEB128_SIZE /* flags */ +
1941 LEB128_SIZE /* domain id */
1943 uint64_t now = current_time ();
1945 ENTER_LOG (logbuffer, "context-end");
1946 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1947 emit_time (logbuffer, now);
1948 emit_byte (logbuffer, TYPE_CONTEXT);
1949 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
1950 emit_value (logbuffer, 0); /* flags */
1951 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
1952 EXIT_LOG (logbuffer);
1954 if (logbuffer->next)
1955 safe_send (prof, logbuffer);
1957 process_requests (prof);
1961 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
1963 int len = strlen (name) + 1;
1965 LogBuffer *logbuffer;
1966 logbuffer = ensure_logbuf (
1967 EVENT_SIZE /* event */ +
1968 LEB128_SIZE /* time */ +
1969 EVENT_SIZE /* type */ +
1970 LEB128_SIZE /* tid */ +
1971 LEB128_SIZE /* flags */ +
1974 now = current_time ();
1975 ENTER_LOG (logbuffer, "tname");
1976 emit_byte (logbuffer, TYPE_METADATA);
1977 emit_time (logbuffer, now);
1978 emit_byte (logbuffer, TYPE_THREAD);
1979 emit_ptr (logbuffer, (void*)tid);
1980 emit_value (logbuffer, 0); /* flags */
1981 memcpy (logbuffer->cursor, name, len);
1982 logbuffer->cursor += len;
1983 EXIT_LOG (logbuffer);
1985 if (logbuffer->next)
1986 safe_send (prof, logbuffer);
1988 process_requests (prof);
2000 AsyncFrameInfo *data;
2004 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
2006 AsyncFrameData *frame = (AsyncFrameData *)data;
2007 if (frame->count < num_frames) {
2008 frame->data [frame->count].method = method;
2009 frame->data [frame->count].domain = domain;
2010 frame->data [frame->count].base_address = base_address;
2011 frame->data [frame->count].offset = offset;
2012 // printf ("In %d at %p (dom %p) (native: %p)\n", frame->count, method, domain, base_address);
2015 return frame->count == num_frames;
2019 (type | frame count), tid, time, ip, [method, domain, base address, offset] * frames
2021 #define SAMPLE_EVENT_SIZE_IN_SLOTS(FRAMES) (4 + (FRAMES) * 4)
2024 mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
2027 AsyncFrameInfo frames [num_frames];
2028 AsyncFrameData bt_data = { 0, &frames [0]};
2030 uintptr_t *data, *new_data, *old_data;
2036 now = current_time ();
2038 mono_stack_walk_async_safe (&async_walk_stack, context, &bt_data);
2040 elapsed = (now - profiler->startup_time) / 10000;
2044 snprintf (buf, sizeof (buf), "hit at %p in thread %p after %llu ms\n", ip, (void*)thread_id (), (unsigned long long int)elapsed/100);
2046 ign_res (write (2, buf, len));
2048 sbuf = profiler->stat_buffers;
2051 /* flush the buffer at 1 second intervals */
2052 if (sbuf->cursor > sbuf->buf && (elapsed - sbuf->buf [2]) > 100000) {
2055 /* overflow: 400 slots is a big enough number to reduce the chance of losing this event if many
2056 * threads hit this same spot at the same time
2058 if (timedout || (sbuf->cursor + 400 >= sbuf->buf_end)) {
2059 StatBuffer *oldsb, *foundsb;
2060 sbuf = create_stat_buffer ();
2062 oldsb = profiler->stat_buffers;
2064 foundsb = (StatBuffer *)InterlockedCompareExchangePointer ((void * volatile*)&profiler->stat_buffers, sbuf, oldsb);
2065 } while (foundsb != oldsb);
2067 ign_res (write (2, "overflow\n", 9));
2068 /* notify the helper thread */
2069 if (sbuf->next->next) {
2071 ign_res (write (profiler->pipes [1], &c, 1));
2073 ign_res (write (2, "notify\n", 7));
2077 old_data = sbuf->cursor;
2078 new_data = old_data + SAMPLE_EVENT_SIZE_IN_SLOTS (bt_data.count);
2079 if (new_data > sbuf->buf_end)
2080 return; /* Not enough room in buf to hold this event-- lost event */
2081 data = (uintptr_t *)InterlockedCompareExchangePointer ((void * volatile*)&sbuf->cursor, new_data, old_data);
2082 } while (data != old_data);
2084 old_data [0] = 1 | (sample_type << 16) | (bt_data.count << 8);
2085 old_data [1] = thread_id ();
2086 old_data [2] = elapsed;
2087 old_data [3] = (uintptr_t)ip;
2088 for (i = 0; i < bt_data.count; ++i) {
2089 old_data [4 + 4 * i + 0] = (uintptr_t)frames [i].method;
2090 old_data [4 + 4 * i + 1] = (uintptr_t)frames [i].domain;
2091 old_data [4 + 4 * i + 2] = (uintptr_t)frames [i].base_address;
2092 old_data [4 + 4 * i + 3] = (uintptr_t)frames [i].offset;
2096 static uintptr_t *code_pages = 0;
2097 static int num_code_pages = 0;
2098 static int size_code_pages = 0;
2099 #define CPAGE_SHIFT (9)
2100 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
2101 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
2102 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
2105 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
2108 uintptr_t start_pos;
2109 start_pos = (page >> CPAGE_SHIFT) % hsize;
2112 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
2114 } else if (!hash [i]) {
2121 } while (i != start_pos);
2122 /* should not happen */
2123 printf ("failed code page store\n");
2128 add_code_pointer (uintptr_t ip)
2131 if (num_code_pages * 2 >= size_code_pages) {
2133 uintptr_t old_size = size_code_pages;
2134 size_code_pages *= 2;
2135 if (size_code_pages == 0)
2136 size_code_pages = 16;
2137 n = (uintptr_t *)calloc (sizeof (uintptr_t) * size_code_pages, 1);
2138 for (i = 0; i < old_size; ++i) {
2140 add_code_page (n, size_code_pages, code_pages [i]);
2146 num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
2149 /* ELF code crashes on some systems. */
2150 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2153 dump_ubin (const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
2156 LogBuffer *logbuffer;
2158 len = strlen (filename) + 1;
2159 now = current_time ();
2160 logbuffer = ensure_logbuf (
2161 EVENT_SIZE /* event */ +
2162 LEB128_SIZE /* time */ +
2163 LEB128_SIZE /* load address */ +
2164 LEB128_SIZE /* offset */ +
2165 LEB128_SIZE /* size */ +
2166 nlen /* file name */
2168 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
2169 emit_time (logbuffer, now);
2170 emit_svalue (logbuffer, load_addr);
2171 emit_uvalue (logbuffer, offset);
2172 emit_uvalue (logbuffer, size);
2173 memcpy (logbuffer->cursor, filename, len);
2174 logbuffer->cursor += len;
2179 dump_usym (const char *name, uintptr_t value, uintptr_t size)
2181 LogBuffer *logbuffer;
2183 len = strlen (name) + 1;
2184 logbuffer = ensure_logbuf (
2185 EVENT_SIZE /* event */ +
2186 LEB128_SIZE /* value */ +
2187 LEB128_SIZE /* size */ +
2190 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
2191 emit_ptr (logbuffer, (void*)value);
2192 emit_value (logbuffer, size);
2193 memcpy (logbuffer->cursor, name, len);
2194 logbuffer->cursor += len;
2197 /* ELF code crashes on some systems. */
2198 //#if defined(ELFMAG0)
2201 #if SIZEOF_VOID_P == 4
2202 #define ELF_WSIZE 32
2204 #define ELF_WSIZE 64
2207 #define ElfW(type) _ElfW (Elf, ELF_WSIZE, type)
2208 #define _ElfW(e,w,t) _ElfW_1 (e, w, _##t)
2209 #define _ElfW_1(e,w,t) e##w##t
2213 dump_elf_symbols (ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
2216 for (i = 0; i < num_symbols; ++i) {
2218 sym = strtab + symbols [i].st_name;
2219 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
2221 //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
2222 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
2227 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
2234 ElfW(Shdr) *sheader;
2235 ElfW(Shdr) *shstrtabh;
2236 ElfW(Shdr) *symtabh = NULL;
2237 ElfW(Shdr) *strtabh = NULL;
2238 ElfW(Sym) *symbols = NULL;
2242 fd = open (filename, O_RDONLY);
2245 if (fstat (fd, &statb) != 0) {
2249 file_size = statb.st_size;
2250 data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
2252 if (data == MAP_FAILED)
2255 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2256 header->e_ident [EI_MAG1] != ELFMAG1 ||
2257 header->e_ident [EI_MAG2] != ELFMAG2 ||
2258 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2259 munmap (data, file_size);
2262 sheader = (void*)((char*)data + header->e_shoff);
2263 shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
2264 strtab = (const char*)data + shstrtabh->sh_offset;
2265 for (i = 0; i < header->e_shnum; ++i) {
2266 //printf ("section header: %d\n", sheader->sh_type);
2267 if (sheader->sh_type == SHT_SYMTAB) {
2269 strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
2270 /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
2273 sheader = (void*)((char*)sheader + header->e_shentsize);
2275 if (!symtabh || !strtabh) {
2276 munmap (data, file_size);
2279 strtab = (const char*)data + strtabh->sh_offset;
2280 num_symbols = symtabh->sh_size / symtabh->sh_entsize;
2281 symbols = (void*)((char*)data + symtabh->sh_offset);
2282 dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
2283 munmap (data, file_size);
2288 /* ELF code crashes on some systems. */
2289 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2292 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
2294 MonoProfiler *prof = data;
2296 const char *filename;
2298 char *a = (void*)info->dlpi_addr;
2300 ElfW(Dyn) *dyn = NULL;
2301 ElfW(Sym) *symtab = NULL;
2302 ElfW(Word) *hash_table = NULL;
2303 ElfW(Ehdr) *header = NULL;
2304 const char* strtab = NULL;
2305 for (obj = prof->binary_objects; obj; obj = obj->next) {
2309 filename = info->dlpi_name;
2312 if (!info->dlpi_addr && !filename [0]) {
2313 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
2319 obj = calloc (sizeof (BinaryObject), 1);
2320 obj->addr = (void*)info->dlpi_addr;
2321 obj->name = pstrdup (filename);
2322 obj->next = prof->binary_objects;
2323 prof->binary_objects = obj;
2324 //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
2326 for (i = 0; i < info->dlpi_phnum; ++i) {
2327 //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);
2328 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
2329 header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2330 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2331 header->e_ident [EI_MAG1] != ELFMAG1 ||
2332 header->e_ident [EI_MAG2] != ELFMAG2 ||
2333 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2336 dump_ubin (filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
2337 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
2338 dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2341 if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
2343 if (!info->dlpi_name || !info->dlpi_name[0])
2347 for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
2348 if (dyn [i].d_tag == DT_SYMTAB) {
2349 if (symtab && do_debug)
2350 printf ("multiple symtabs: %d\n", i);
2351 symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
2352 } else if (dyn [i].d_tag == DT_HASH) {
2353 hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
2354 } else if (dyn [i].d_tag == DT_STRTAB) {
2355 strtab = (const char*)(a + dyn [i].d_un.d_ptr);
2360 num_sym = hash_table [1];
2361 dump_elf_symbols (symtab, num_sym, strtab, (void*)info->dlpi_addr);
2366 load_binaries (MonoProfiler *prof)
2368 dl_iterate_phdr (elf_dl_callback, prof);
2373 load_binaries (MonoProfiler *prof)
2380 symbol_for (uintptr_t code)
2383 void *ip = (void*)code;
2385 if (dladdr (ip, &di)) {
2387 return di.dli_sname;
2390 names = backtrace_symbols (&ip, 1);
2392 const char* p = names [0];
2403 dump_unmanaged_coderefs (MonoProfiler *prof)
2406 const char* last_symbol;
2407 uintptr_t addr, page_end;
2409 if (load_binaries (prof))
2411 for (i = 0; i < size_code_pages; ++i) {
2413 if (!code_pages [i] || code_pages [i] & 1)
2416 addr = CPAGE_ADDR (code_pages [i]);
2417 page_end = addr + CPAGE_SIZE;
2418 code_pages [i] |= 1;
2419 /* we dump the symbols for the whole page */
2420 for (; addr < page_end; addr += 16) {
2421 sym = symbol_for (addr);
2422 if (sym && sym == last_symbol)
2427 dump_usym (sym, addr, 0); /* let's not guess the size */
2428 //printf ("found symbol at %p: %s\n", (void*)addr, sym);
2434 compare_sample_events (gconstpointer a, gconstpointer b)
2436 uintptr_t tid1 = (*(uintptr_t **) a) [1];
2437 uintptr_t tid2 = (*(uintptr_t **) b) [1];
2439 return tid1 > tid2 ? 1 :
2445 dump_sample_hits (MonoProfiler *prof, StatBuffer *sbuf)
2447 LogBuffer *logbuffer;
2451 dump_sample_hits (prof, sbuf->next);
2452 free_buffer (sbuf->next, sbuf->next->size);
2456 g_ptr_array_set_size (prof->sorted_sample_events, 0);
2458 for (uintptr_t *sample = sbuf->buf; sample < sbuf->cursor;) {
2459 int count = sample [0] & 0xff;
2460 int mbt_count = (sample [0] & 0xff00) >> 8;
2462 if (sample + SAMPLE_EVENT_SIZE_IN_SLOTS (mbt_count) > sbuf->cursor)
2465 g_ptr_array_add (prof->sorted_sample_events, sample);
2467 sample += count + 3 + 4 * mbt_count;
2470 g_ptr_array_sort (prof->sorted_sample_events, compare_sample_events);
2472 for (guint sidx = 0; sidx < prof->sorted_sample_events->len; sidx++) {
2473 uintptr_t *sample = (uintptr_t *)g_ptr_array_index (prof->sorted_sample_events, sidx);
2474 int count = sample [0] & 0xff;
2475 int mbt_count = (sample [0] & 0xff00) >> 8;
2476 int type = sample [0] >> 16;
2477 uintptr_t *managed_sample_base = sample + count + 3;
2478 uintptr_t thread_id = sample [1];
2480 for (int i = 0; i < mbt_count; ++i) {
2481 MonoMethod *method = (MonoMethod*)managed_sample_base [i * 4 + 0];
2482 MonoDomain *domain = (MonoDomain*)managed_sample_base [i * 4 + 1];
2483 void *address = (void*)managed_sample_base [i * 4 + 2];
2487 MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *)address);
2490 managed_sample_base [i * 4 + 0] = (uintptr_t)mono_jit_info_get_method (ji);
2494 logbuffer = ensure_logbuf (
2495 EVENT_SIZE /* event */ +
2496 LEB128_SIZE /* type */ +
2497 LEB128_SIZE /* time */ +
2498 LEB128_SIZE /* tid */ +
2499 LEB128_SIZE /* count */ +
2501 LEB128_SIZE /* ip */
2503 LEB128_SIZE /* managed count */ +
2505 LEB128_SIZE /* method */ +
2506 LEB128_SIZE /* il offset */ +
2507 LEB128_SIZE /* native offset */
2510 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
2511 emit_value (logbuffer, type);
2512 emit_uvalue (logbuffer, prof->startup_time + (uint64_t)sample [2] * (uint64_t)10000);
2513 emit_ptr (logbuffer, (void *) thread_id);
2514 emit_value (logbuffer, count);
2515 for (int i = 0; i < count; ++i) {
2516 emit_ptr (logbuffer, (void*)sample [i + 3]);
2517 add_code_pointer (sample [i + 3]);
2520 sample += count + 3;
2521 /* new in data version 6 */
2522 emit_uvalue (logbuffer, mbt_count);
2523 for (int i = 0; i < mbt_count; ++i) {
2524 MonoMethod *method = (MonoMethod *) sample [i * 4 + 0];
2525 uintptr_t native_offset = sample [i * 4 + 3];
2527 emit_method (prof, logbuffer, method);
2528 emit_svalue (logbuffer, 0); /* il offset will always be 0 from now on */
2529 emit_svalue (logbuffer, native_offset);
2533 dump_unmanaged_coderefs (prof);
2539 mono_cpu_count (void)
2541 #ifdef PLATFORM_ANDROID
2542 /* Android tries really hard to save power by powering off CPUs on SMP phones which
2543 * means the normal way to query cpu count returns a wrong value with userspace API.
2544 * Instead we use /sys entries to query the actual hardware CPU count.
2547 char buffer[8] = {'\0'};
2548 int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
2549 /* Format of the /sys entry is a cpulist of indexes which in the case
2550 * of present is always of the form "0-(n-1)" when there is more than
2551 * 1 core, n being the number of CPU cores in the system. Otherwise
2552 * the value is simply 0
2554 if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
2555 count = strtol (((char*)buffer) + 2, NULL, 10);
2562 #if defined(HOST_ARM) || defined (HOST_ARM64)
2564 /* ARM platforms tries really hard to save power by powering off CPUs on SMP phones which
2565 * means the normal way to query cpu count returns a wrong value with userspace API. */
2567 #ifdef _SC_NPROCESSORS_CONF
2569 int count = sysconf (_SC_NPROCESSORS_CONF);
2577 #ifdef HAVE_SCHED_GETAFFINITY
2580 if (sched_getaffinity (getpid (), sizeof (set), &set) == 0)
2581 return CPU_COUNT (&set);
2584 #ifdef _SC_NPROCESSORS_ONLN
2586 int count = sysconf (_SC_NPROCESSORS_ONLN);
2592 #endif /* defined(HOST_ARM) || defined (HOST_ARM64) */
2598 size_t len = sizeof (int);
2601 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
2608 GetSystemInfo (&info);
2609 return info.dwNumberOfProcessors;
2618 unsigned int prev_pos;
2620 struct perf_event_mmap_page *page_desc;
2623 static PerfData *perf_data = NULL;
2624 static int num_perf;
2625 #define PERF_PAGES_SHIFT 4
2626 static int num_pages = 1 << PERF_PAGES_SHIFT;
2627 static unsigned int mmap_mask;
2630 struct perf_event_header h;
2640 perf_event_syscall (struct perf_event_attr *attr, pid_t pid, int cpu, int group_fd, unsigned long flags)
2642 attr->size = PERF_ATTR_SIZE_VER0;
2643 //printf ("perf attr size: %d\n", attr->size);
2644 #if defined(__x86_64__)
2645 return syscall(/*__NR_perf_event_open*/ 298, attr, pid, cpu, group_fd, flags);
2646 #elif defined(__i386__)
2647 return syscall(/*__NR_perf_event_open*/ 336, attr, pid, cpu, group_fd, flags);
2648 #elif defined(__arm__) || defined (__aarch64__)
2649 return syscall(/*__NR_perf_event_open*/ 364, attr, pid, cpu, group_fd, flags);
2656 setup_perf_map (PerfData *perf)
2658 perf->mmap_base = mmap (NULL, (num_pages + 1) * getpagesize (), PROT_READ|PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
2659 if (perf->mmap_base == MAP_FAILED) {
2661 printf ("failed mmap\n");
2664 perf->page_desc = perf->mmap_base;
2666 printf ("mmap version: %d\n", perf->page_desc->version);
2671 dump_perf_hits (MonoProfiler *prof, void *buf, int size)
2673 LogBuffer *logbuffer;
2676 void *end = (char*)buf + size;
2678 int pid = getpid ();
2684 if (pid != s->pid) {
2686 printf ("event for different pid: %d\n", s->pid);
2687 buf = (char*)buf + s->h.size;
2690 /*ip = (void*)s->ip;
2691 printf ("sample: %d, size: %d, ip: %p (%s), timestamp: %llu, nframes: %llu\n",
2692 s->h.type, s->h.size, ip, symbol_for (ip), s->timestamp, s->nframes);*/
2693 logbuffer = ensure_logbuf (
2694 EVENT_SIZE /* event */ +
2695 LEB128_SIZE /* type */ +
2696 LEB128_SIZE /* time */ +
2697 LEB128_SIZE /* tid */ +
2698 LEB128_SIZE /* count */ +
2700 LEB128_SIZE /* ip */
2702 LEB128_SIZE /* managed count */ +
2704 LEB128_SIZE /* method */ +
2705 LEB128_SIZE /* il offset */ +
2706 LEB128_SIZE /* native offset */
2709 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
2710 emit_value (logbuffer, sample_type);
2711 emit_uvalue (logbuffer, s->timestamp - prof->startup_time);
2713 * No useful thread ID to write here, since throughout the
2714 * profiler we use pthread_self () but the ID we get from
2715 * perf is the kernel's thread ID.
2717 emit_ptr (logbuffer, 0);
2718 emit_value (logbuffer, count);
2719 emit_ptr (logbuffer, (void*)(uintptr_t)s->ip);
2720 add_code_pointer (s->ip);
2721 /* no support here yet for the managed backtrace */
2722 emit_uvalue (logbuffer, mbt_count);
2723 buf = (char*)buf + s->h.size;
2727 printf ("dumped %d samples\n", samples);
2728 dump_unmanaged_coderefs (prof);
2731 /* read events from the ring buffer */
2733 read_perf_mmap (MonoProfiler* prof, int cpu)
2735 PerfData *perf = perf_data + cpu;
2737 unsigned char *data = (unsigned char*)perf->mmap_base + getpagesize ();
2738 unsigned int head = perf->page_desc->data_head;
2742 mono_memory_read_barrier ();
2744 old = perf->prev_pos;
2748 printf ("lost mmap events: old: %d, head: %d\n", old, head);
2752 if ((old & mmap_mask) + size != (head & mmap_mask)) {
2753 buf = data + (old & mmap_mask);
2754 size = mmap_mask + 1 - (old & mmap_mask);
2756 /* size bytes at buf */
2758 printf ("found1 bytes of events: %d\n", size);
2759 dump_perf_hits (prof, buf, size);
2761 buf = data + (old & mmap_mask);
2763 /* size bytes at buf */
2765 printf ("found bytes of events: %d\n", size);
2766 dump_perf_hits (prof, buf, size);
2768 perf->prev_pos = old;
2769 perf->page_desc->data_tail = old;
2774 setup_perf_event_for_cpu (PerfData *perf, int cpu)
2776 struct perf_event_attr attr;
2777 memset (&attr, 0, sizeof (attr));
2778 attr.type = PERF_TYPE_HARDWARE;
2779 switch (sample_type) {
2780 case SAMPLE_CYCLES: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2781 case SAMPLE_INSTRUCTIONS: attr.config = PERF_COUNT_HW_INSTRUCTIONS; break;
2782 case SAMPLE_CACHE_MISSES: attr.config = PERF_COUNT_HW_CACHE_MISSES; break;
2783 case SAMPLE_CACHE_REFS: attr.config = PERF_COUNT_HW_CACHE_REFERENCES; break;
2784 case SAMPLE_BRANCHES: attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS; break;
2785 case SAMPLE_BRANCH_MISSES: attr.config = PERF_COUNT_HW_BRANCH_MISSES; break;
2786 default: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2788 attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD | PERF_SAMPLE_TIME;
2789 // attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
2790 attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING | PERF_FORMAT_ID;
2793 attr.sample_freq = sample_freq;
2795 perf->perf_fd = perf_event_syscall (&attr, getpid (), cpu, -1, 0);
2797 printf ("perf fd: %d, freq: %d, event: %llu\n", perf->perf_fd, sample_freq, attr.config);
2798 if (perf->perf_fd < 0) {
2799 if (perf->perf_fd == -EPERM) {
2800 fprintf (stderr, "Perf syscall denied, do \"echo 1 > /proc/sys/kernel/perf_event_paranoid\" as root to enable.\n");
2803 perror ("open perf event");
2807 if (!setup_perf_map (perf)) {
2808 close (perf->perf_fd);
2816 setup_perf_event (void)
2819 mmap_mask = num_pages * getpagesize () - 1;
2820 num_perf = mono_cpu_count ();
2821 perf_data = calloc (num_perf, sizeof (PerfData));
2822 for (i = 0; i < num_perf; ++i) {
2823 count += setup_perf_event_for_cpu (perf_data + i, i);
2832 #endif /* USE_PERF_EVENTS */
2834 #ifndef DISABLE_HELPER_THREAD
2836 typedef struct MonoCounterAgent {
2837 MonoCounter *counter;
2838 // MonoCounterAgent specific data :
2843 struct MonoCounterAgent *next;
2846 static MonoCounterAgent* counters;
2847 static gboolean counters_initialized = FALSE;
2848 static int counters_index = 1;
2849 static mono_mutex_t counters_mutex;
2852 counters_add_agent (MonoCounter *counter)
2854 MonoCounterAgent *agent, *item;
2856 if (!counters_initialized)
2859 mono_os_mutex_lock (&counters_mutex);
2861 for (agent = counters; agent; agent = agent->next) {
2862 if (agent->counter == counter) {
2863 agent->value_size = 0;
2865 free (agent->value);
2866 agent->value = NULL;
2868 mono_os_mutex_unlock (&counters_mutex);
2873 agent = (MonoCounterAgent *)malloc (sizeof (MonoCounterAgent));
2874 agent->counter = counter;
2875 agent->value = NULL;
2876 agent->value_size = 0;
2877 agent->index = counters_index++;
2890 mono_os_mutex_unlock (&counters_mutex);
2894 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
2896 counters_add_agent (counter);
2901 counters_init (MonoProfiler *profiler)
2903 assert (!counters_initialized);
2905 mono_os_mutex_init (&counters_mutex);
2907 counters_initialized = TRUE;
2909 mono_counters_on_register (&counters_add_agent);
2910 mono_counters_foreach (counters_init_foreach_callback, NULL);
2914 counters_emit (MonoProfiler *profiler)
2916 MonoCounterAgent *agent;
2917 LogBuffer *logbuffer;
2920 EVENT_SIZE /* event */ +
2921 LEB128_SIZE /* len */
2924 if (!counters_initialized)
2927 mono_os_mutex_lock (&counters_mutex);
2929 for (agent = counters; agent; agent = agent->next) {
2934 LEB128_SIZE /* section */ +
2935 strlen (mono_counter_get_name (agent->counter)) + 1 /* name */ +
2936 LEB128_SIZE /* type */ +
2937 LEB128_SIZE /* unit */ +
2938 LEB128_SIZE /* variance */ +
2939 LEB128_SIZE /* index */
2946 mono_os_mutex_unlock (&counters_mutex);
2950 logbuffer = ensure_logbuf (size);
2952 ENTER_LOG (logbuffer, "counters");
2953 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2954 emit_value (logbuffer, len);
2955 for (agent = counters; agent; agent = agent->next) {
2961 name = mono_counter_get_name (agent->counter);
2962 emit_value (logbuffer, mono_counter_get_section (agent->counter));
2963 emit_string (logbuffer, name, strlen (name) + 1);
2964 emit_value (logbuffer, mono_counter_get_type (agent->counter));
2965 emit_value (logbuffer, mono_counter_get_unit (agent->counter));
2966 emit_value (logbuffer, mono_counter_get_variance (agent->counter));
2967 emit_value (logbuffer, agent->index);
2971 EXIT_LOG (logbuffer);
2973 safe_send (profiler, logbuffer);
2975 mono_os_mutex_unlock (&counters_mutex);
2979 counters_sample (MonoProfiler *profiler, uint64_t timestamp)
2981 MonoCounterAgent *agent;
2982 MonoCounter *counter;
2983 LogBuffer *logbuffer;
2989 if (!counters_initialized)
2992 counters_emit (profiler);
2995 buffer = calloc (1, buffer_size);
2997 mono_os_mutex_lock (&counters_mutex);
3000 EVENT_SIZE /* event */ +
3001 LEB128_SIZE /* time */
3004 for (agent = counters; agent; agent = agent->next) {
3006 LEB128_SIZE /* index */ +
3007 LEB128_SIZE /* type */ +
3008 mono_counter_get_size (agent->counter) /* value */
3013 LEB128_SIZE /* stop marker */
3016 logbuffer = ensure_logbuf (size);
3018 ENTER_LOG (logbuffer, "counters");
3019 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
3020 emit_uvalue (logbuffer, timestamp);
3021 for (agent = counters; agent; agent = agent->next) {
3024 counter = agent->counter;
3026 size = mono_counter_get_size (counter);
3028 continue; // FIXME error
3029 } else if (size > buffer_size) {
3031 buffer = realloc (buffer, buffer_size);
3034 memset (buffer, 0, buffer_size);
3036 if (mono_counters_sample (counter, buffer, size) < 0)
3037 continue; // FIXME error
3039 type = mono_counter_get_type (counter);
3041 if (!agent->value) {
3042 agent->value = calloc (1, size);
3043 agent->value_size = size;
3045 if (type == MONO_COUNTER_STRING) {
3046 if (strcmp (agent->value, buffer) == 0)
3049 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
3054 emit_uvalue (logbuffer, agent->index);
3055 emit_uvalue (logbuffer, type);
3057 case MONO_COUNTER_INT:
3058 #if SIZEOF_VOID_P == 4
3059 case MONO_COUNTER_WORD:
3061 emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
3063 case MONO_COUNTER_UINT:
3064 emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
3066 case MONO_COUNTER_TIME_INTERVAL:
3067 case MONO_COUNTER_LONG:
3068 #if SIZEOF_VOID_P == 8
3069 case MONO_COUNTER_WORD:
3071 emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
3073 case MONO_COUNTER_ULONG:
3074 emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
3076 case MONO_COUNTER_DOUBLE:
3077 emit_double (logbuffer, *(double*)buffer);
3079 case MONO_COUNTER_STRING:
3081 emit_byte (logbuffer, 0);
3083 emit_byte (logbuffer, 1);
3084 emit_string (logbuffer, (char*)buffer, size);
3091 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
3092 agent->value = realloc (agent->value, size);
3093 agent->value_size = size;
3097 memcpy (agent->value, buffer, size);
3101 emit_value (logbuffer, 0);
3102 EXIT_LOG (logbuffer);
3104 safe_send (profiler, logbuffer);
3106 mono_os_mutex_unlock (&counters_mutex);
3109 typedef struct _PerfCounterAgent PerfCounterAgent;
3110 struct _PerfCounterAgent {
3111 PerfCounterAgent *next;
3113 char *category_name;
3122 static PerfCounterAgent *perfcounters = NULL;
3125 perfcounters_emit (MonoProfiler *profiler)
3127 PerfCounterAgent *pcagent;
3128 LogBuffer *logbuffer;
3131 EVENT_SIZE /* event */ +
3132 LEB128_SIZE /* len */
3135 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3136 if (pcagent->emitted)
3140 LEB128_SIZE /* section */ +
3141 strlen (pcagent->category_name) + 1 /* category name */ +
3142 strlen (pcagent->name) + 1 /* name */ +
3143 LEB128_SIZE /* type */ +
3144 LEB128_SIZE /* unit */ +
3145 LEB128_SIZE /* variance */ +
3146 LEB128_SIZE /* index */
3155 logbuffer = ensure_logbuf (size);
3157 ENTER_LOG (logbuffer, "perfcounters");
3158 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
3159 emit_value (logbuffer, len);
3160 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3161 if (pcagent->emitted)
3164 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
3165 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
3166 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
3167 emit_value (logbuffer, MONO_COUNTER_LONG);
3168 emit_value (logbuffer, MONO_COUNTER_RAW);
3169 emit_value (logbuffer, MONO_COUNTER_VARIABLE);
3170 emit_value (logbuffer, pcagent->index);
3172 pcagent->emitted = 1;
3174 EXIT_LOG (logbuffer);
3176 safe_send (profiler, logbuffer);
3180 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
3182 PerfCounterAgent *pcagent;
3184 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3185 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
3187 if (pcagent->value == value)
3190 pcagent->value = value;
3191 pcagent->updated = 1;
3192 pcagent->deleted = 0;
3196 pcagent = g_new0 (PerfCounterAgent, 1);
3197 pcagent->next = perfcounters;
3198 pcagent->index = counters_index++;
3199 pcagent->category_name = g_strdup (category_name);
3200 pcagent->name = g_strdup (name);
3201 pcagent->type = (int) type;
3202 pcagent->value = value;
3203 pcagent->emitted = 0;
3204 pcagent->updated = 1;
3205 pcagent->deleted = 0;
3207 perfcounters = pcagent;
3213 perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp)
3215 PerfCounterAgent *pcagent;
3216 LogBuffer *logbuffer;
3219 if (!counters_initialized)
3222 mono_os_mutex_lock (&counters_mutex);
3224 /* mark all perfcounters as deleted, foreach will unmark them as necessary */
3225 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
3226 pcagent->deleted = 1;
3228 mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
3230 perfcounters_emit (profiler);
3233 EVENT_SIZE /* event */ +
3234 LEB128_SIZE /* time */
3237 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3238 if (pcagent->deleted || !pcagent->updated)
3242 LEB128_SIZE /* index */ +
3243 LEB128_SIZE /* type */ +
3244 LEB128_SIZE /* value */
3249 LEB128_SIZE /* stop marker */
3252 logbuffer = ensure_logbuf (size);
3254 ENTER_LOG (logbuffer, "perfcounters");
3255 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
3256 emit_uvalue (logbuffer, timestamp);
3257 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3258 if (pcagent->deleted || !pcagent->updated)
3260 emit_uvalue (logbuffer, pcagent->index);
3261 emit_uvalue (logbuffer, MONO_COUNTER_LONG);
3262 emit_svalue (logbuffer, pcagent->value);
3264 pcagent->updated = 0;
3267 emit_value (logbuffer, 0);
3268 EXIT_LOG (logbuffer);
3270 safe_send (profiler, logbuffer);
3272 mono_os_mutex_unlock (&counters_mutex);
3276 counters_and_perfcounters_sample (MonoProfiler *prof)
3278 static uint64_t start = -1;
3282 start = current_time ();
3284 now = current_time ();
3285 counters_sample (prof, (now - start) / 1000/ 1000);
3286 perfcounters_sample (prof, (now - start) / 1000/ 1000);
3289 #define COVERAGE_DEBUG(x) if (debug_coverage) {x}
3290 static mono_mutex_t coverage_mutex;
3291 static MonoConcurrentHashTable *coverage_methods = NULL;
3292 static MonoConcurrentHashTable *coverage_assemblies = NULL;
3293 static MonoConcurrentHashTable *coverage_classes = NULL;
3295 static MonoConcurrentHashTable *filtered_classes = NULL;
3296 static MonoConcurrentHashTable *entered_methods = NULL;
3297 static MonoConcurrentHashTable *image_to_methods = NULL;
3298 static MonoConcurrentHashTable *suppressed_assemblies = NULL;
3299 static gboolean coverage_initialized = FALSE;
3301 static GPtrArray *coverage_data = NULL;
3302 static int previous_offset = 0;
3304 typedef struct _MethodNode MethodNode;
3305 struct _MethodNode {
3306 MonoLockFreeQueueNode node;
3310 typedef struct _CoverageEntry CoverageEntry;
3311 struct _CoverageEntry {
3320 free_coverage_entry (gpointer data, gpointer userdata)
3322 CoverageEntry *entry = (CoverageEntry *)data;
3323 g_free (entry->filename);
3328 obtain_coverage_for_method (MonoProfiler *prof, const MonoProfileCoverageEntry *entry)
3330 int offset = entry->iloffset - previous_offset;
3331 CoverageEntry *e = g_new (CoverageEntry, 1);
3333 previous_offset = entry->iloffset;
3336 e->counter = entry->counter;
3337 e->filename = g_strdup(entry->filename ? entry->filename : "");
3338 e->line = entry->line;
3339 e->column = entry->col;
3341 g_ptr_array_add (coverage_data, e);
3345 parse_generic_type_names(char *name)
3347 char *new_name, *ret;
3348 int within_generic_declaration = 0, generic_members = 1;
3350 if (name == NULL || *name == '\0')
3351 return g_strdup ("");
3353 if (!(ret = new_name = (char *)calloc (strlen (name) * 4 + 1, sizeof (char))))
3359 within_generic_declaration = 1;
3363 within_generic_declaration = 0;
3365 if (*(name - 1) != '<') {
3367 *new_name++ = '0' + generic_members;
3369 memcpy (new_name, "<>", 8);
3373 generic_members = 0;
3381 if (!within_generic_declaration)
3382 *new_name++ = *name;
3391 static int method_id;
3393 build_method_buffer (gpointer key, gpointer value, gpointer userdata)
3395 MonoMethod *method = (MonoMethod *)value;
3396 MonoProfiler *prof = (MonoProfiler *)userdata;
3400 const char *image_name, *method_name, *sig, *first_filename;
3401 LogBuffer *logbuffer;
3404 previous_offset = 0;
3405 coverage_data = g_ptr_array_new ();
3407 mono_profiler_coverage_get (prof, method, obtain_coverage_for_method);
3409 klass = mono_method_get_class (method);
3410 image = mono_class_get_image (klass);
3411 image_name = mono_image_get_name (image);
3413 sig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3414 class_name = parse_generic_type_names (mono_type_get_name (mono_class_get_type (klass)));
3415 method_name = mono_method_get_name (method);
3417 if (coverage_data->len != 0) {
3418 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[0];
3419 first_filename = entry->filename ? entry->filename : "";
3421 first_filename = "";
3423 image_name = image_name ? image_name : "";
3424 sig = sig ? sig : "";
3425 method_name = method_name ? method_name : "";
3427 logbuffer = ensure_logbuf (
3428 EVENT_SIZE /* event */ +
3429 strlen (image_name) + 1 /* image name */ +
3430 strlen (class_name) + 1 /* class name */ +
3431 strlen (method_name) + 1 /* method name */ +
3432 strlen (sig) + 1 /* signature */ +
3433 strlen (first_filename) + 1 /* first file name */ +
3434 LEB128_SIZE /* token */ +
3435 LEB128_SIZE /* method id */ +
3436 LEB128_SIZE /* entries */
3438 ENTER_LOG (logbuffer, "coverage-methods");
3440 emit_byte (logbuffer, TYPE_COVERAGE_METHOD | TYPE_COVERAGE);
3441 emit_string (logbuffer, image_name, strlen (image_name) + 1);
3442 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3443 emit_string (logbuffer, method_name, strlen (method_name) + 1);
3444 emit_string (logbuffer, sig, strlen (sig) + 1);
3445 emit_string (logbuffer, first_filename, strlen (first_filename) + 1);
3447 emit_uvalue (logbuffer, mono_method_get_token (method));
3448 emit_uvalue (logbuffer, method_id);
3449 emit_value (logbuffer, coverage_data->len);
3451 EXIT_LOG (logbuffer);
3452 safe_send (prof, logbuffer);
3454 for (i = 0; i < coverage_data->len; i++) {
3455 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[i];
3457 logbuffer = ensure_logbuf (
3458 EVENT_SIZE /* event */ +
3459 LEB128_SIZE /* method id */ +
3460 LEB128_SIZE /* offset */ +
3461 LEB128_SIZE /* counter */ +
3462 LEB128_SIZE /* line */ +
3463 LEB128_SIZE /* column */
3465 ENTER_LOG (logbuffer, "coverage-statement");
3467 emit_byte (logbuffer, TYPE_COVERAGE_STATEMENT | TYPE_COVERAGE);
3468 emit_uvalue (logbuffer, method_id);
3469 emit_uvalue (logbuffer, entry->offset);
3470 emit_uvalue (logbuffer, entry->counter);
3471 emit_uvalue (logbuffer, entry->line);
3472 emit_uvalue (logbuffer, entry->column);
3474 EXIT_LOG (logbuffer);
3475 safe_send (prof, logbuffer);
3480 g_free (class_name);
3482 g_ptr_array_foreach (coverage_data, free_coverage_entry, NULL);
3483 g_ptr_array_free (coverage_data, TRUE);
3484 coverage_data = NULL;
3487 /* This empties the queue */
3489 count_queue (MonoLockFreeQueue *queue)
3491 MonoLockFreeQueueNode *node;
3494 while ((node = mono_lock_free_queue_dequeue (queue))) {
3496 mono_lock_free_queue_node_free (node);
3503 build_class_buffer (gpointer key, gpointer value, gpointer userdata)
3505 MonoClass *klass = (MonoClass *)key;
3506 MonoLockFreeQueue *class_methods = (MonoLockFreeQueue *)value;
3507 MonoProfiler *prof = (MonoProfiler *)userdata;
3510 const char *assembly_name;
3511 int number_of_methods, partially_covered;
3512 guint fully_covered;
3513 LogBuffer *logbuffer;
3515 image = mono_class_get_image (klass);
3516 assembly_name = mono_image_get_name (image);
3517 class_name = mono_type_get_name (mono_class_get_type (klass));
3519 assembly_name = assembly_name ? assembly_name : "";
3520 number_of_methods = mono_class_num_methods (klass);
3521 fully_covered = count_queue (class_methods);
3522 /* We don't handle partial covered yet */
3523 partially_covered = 0;
3525 logbuffer = ensure_logbuf (
3526 EVENT_SIZE /* event */ +
3527 strlen (assembly_name) + 1 /* assembly name */ +
3528 strlen (class_name) + 1 /* class name */ +
3529 LEB128_SIZE /* no. methods */ +
3530 LEB128_SIZE /* fully covered */ +
3531 LEB128_SIZE /* partially covered */
3534 ENTER_LOG (logbuffer, "coverage-class");
3535 emit_byte (logbuffer, TYPE_COVERAGE_CLASS | TYPE_COVERAGE);
3536 emit_string (logbuffer, assembly_name, strlen (assembly_name) + 1);
3537 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3538 emit_uvalue (logbuffer, number_of_methods);
3539 emit_uvalue (logbuffer, fully_covered);
3540 emit_uvalue (logbuffer, partially_covered);
3541 EXIT_LOG (logbuffer);
3543 safe_send (prof, logbuffer);
3545 g_free (class_name);
3549 get_coverage_for_image (MonoImage *image, int *number_of_methods, guint *fully_covered, int *partially_covered)
3551 MonoLockFreeQueue *image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3553 *number_of_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
3555 *fully_covered = count_queue (image_methods);
3559 // FIXME: We don't handle partially covered yet.
3560 *partially_covered = 0;
3564 build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
3566 MonoAssembly *assembly = (MonoAssembly *)value;
3567 MonoProfiler *prof = (MonoProfiler *)userdata;
3568 MonoImage *image = mono_assembly_get_image (assembly);
3569 LogBuffer *logbuffer;
3570 const char *name, *guid, *filename;
3571 int number_of_methods = 0, partially_covered = 0;
3572 guint fully_covered = 0;
3574 name = mono_image_get_name (image);
3575 guid = mono_image_get_guid (image);
3576 filename = mono_image_get_filename (image);
3578 name = name ? name : "";
3579 guid = guid ? guid : "";
3580 filename = filename ? filename : "";
3582 get_coverage_for_image (image, &number_of_methods, &fully_covered, &partially_covered);
3584 logbuffer = ensure_logbuf (
3585 EVENT_SIZE /* event */ +
3586 strlen (name) + 1 /* name */ +
3587 strlen (guid) + 1 /* guid */ +
3588 strlen (filename) + 1 /* file name */ +
3589 LEB128_SIZE /* no. methods */ +
3590 LEB128_SIZE /* fully covered */ +
3591 LEB128_SIZE /* partially covered */
3594 ENTER_LOG (logbuffer, "coverage-assemblies");
3595 emit_byte (logbuffer, TYPE_COVERAGE_ASSEMBLY | TYPE_COVERAGE);
3596 emit_string (logbuffer, name, strlen (name) + 1);
3597 emit_string (logbuffer, guid, strlen (guid) + 1);
3598 emit_string (logbuffer, filename, strlen (filename) + 1);
3599 emit_uvalue (logbuffer, number_of_methods);
3600 emit_uvalue (logbuffer, fully_covered);
3601 emit_uvalue (logbuffer, partially_covered);
3602 EXIT_LOG (logbuffer);
3604 safe_send (prof, logbuffer);
3608 dump_coverage (MonoProfiler *prof)
3610 if (!coverage_initialized)
3613 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Started dump\n");)
3616 mono_os_mutex_lock (&coverage_mutex);
3617 mono_conc_hashtable_foreach (coverage_assemblies, build_assembly_buffer, prof);
3618 mono_conc_hashtable_foreach (coverage_classes, build_class_buffer, prof);
3619 mono_conc_hashtable_foreach (coverage_methods, build_method_buffer, prof);
3620 mono_os_mutex_unlock (&coverage_mutex);
3622 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Finished dump\n");)
3626 process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method)
3631 if (!coverage_initialized)
3634 klass = mono_method_get_class (method);
3635 image = mono_class_get_image (klass);
3637 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)))
3640 mono_os_mutex_lock (&coverage_mutex);
3641 mono_conc_hashtable_insert (entered_methods, method, method);
3642 mono_os_mutex_unlock (&coverage_mutex);
3645 static MonoLockFreeQueueNode *
3646 create_method_node (MonoMethod *method)
3648 MethodNode *node = (MethodNode *)g_malloc (sizeof (MethodNode));
3649 mono_lock_free_queue_node_init ((MonoLockFreeQueueNode *) node, FALSE);
3650 node->method = method;
3652 return (MonoLockFreeQueueNode *) node;
3656 coverage_filter (MonoProfiler *prof, MonoMethod *method)
3661 MonoAssembly *assembly;
3662 MonoMethodHeader *header;
3663 guint32 iflags, flags, code_size;
3664 char *fqn, *classname;
3665 gboolean has_positive, found;
3666 MonoLockFreeQueue *image_methods, *class_methods;
3667 MonoLockFreeQueueNode *node;
3669 if (!coverage_initialized)
3672 COVERAGE_DEBUG(fprintf (stderr, "Coverage filter for %s\n", mono_method_get_name (method));)
3674 flags = mono_method_get_flags (method, &iflags);
3675 if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
3676 (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/)) {
3677 COVERAGE_DEBUG(fprintf (stderr, " Internal call or pinvoke - ignoring\n");)
3681 // Don't need to do anything else if we're already tracking this method
3682 if (mono_conc_hashtable_lookup (coverage_methods, method)) {
3683 COVERAGE_DEBUG(fprintf (stderr, " Already tracking\n");)
3687 klass = mono_method_get_class (method);
3688 image = mono_class_get_image (klass);
3690 // Don't handle coverage for the core assemblies
3691 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)) != NULL)
3694 if (prof->coverage_filters) {
3695 /* Check already filtered classes first */
3696 if (mono_conc_hashtable_lookup (filtered_classes, klass)) {
3697 COVERAGE_DEBUG(fprintf (stderr, " Already filtered\n");)
3701 classname = mono_type_get_name (mono_class_get_type (klass));
3703 fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
3705 COVERAGE_DEBUG(fprintf (stderr, " Looking for %s in filter\n", fqn);)
3706 // Check positive filters first
3707 has_positive = FALSE;
3709 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3710 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3712 if (filter [0] == '+') {
3713 filter = &filter [1];
3715 COVERAGE_DEBUG(fprintf (stderr, " Checking against +%s ...", filter);)
3717 if (strstr (fqn, filter) != NULL) {
3718 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3721 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3723 has_positive = TRUE;
3727 if (has_positive && !found) {
3728 COVERAGE_DEBUG(fprintf (stderr, " Positive match was not found\n");)
3730 mono_os_mutex_lock (&coverage_mutex);
3731 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3732 mono_os_mutex_unlock (&coverage_mutex);
3739 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3740 // FIXME: Is substring search sufficient?
3741 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3742 if (filter [0] == '+')
3746 filter = &filter [1];
3747 COVERAGE_DEBUG(fprintf (stderr, " Checking against -%s ...", filter);)
3749 if (strstr (fqn, filter) != NULL) {
3750 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3752 mono_os_mutex_lock (&coverage_mutex);
3753 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3754 mono_os_mutex_unlock (&coverage_mutex);
3760 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3768 COVERAGE_DEBUG(fprintf (stderr, " Handling coverage for %s\n", mono_method_get_name (method));)
3769 header = mono_method_get_header_checked (method, &error);
3770 mono_error_cleanup (&error);
3772 mono_method_header_get_code (header, &code_size, NULL);
3774 assembly = mono_image_get_assembly (image);
3776 // Need to keep the assemblies around for as long as they are kept in the hashtable
3777 // Nunit, for example, has a habit of unloading them before the coverage statistics are
3778 // generated causing a crash. See https://bugzilla.xamarin.com/show_bug.cgi?id=39325
3779 mono_assembly_addref (assembly);
3781 mono_os_mutex_lock (&coverage_mutex);
3782 mono_conc_hashtable_insert (coverage_methods, method, method);
3783 mono_conc_hashtable_insert (coverage_assemblies, assembly, assembly);
3784 mono_os_mutex_unlock (&coverage_mutex);
3786 image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3788 if (image_methods == NULL) {
3789 image_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
3790 mono_lock_free_queue_init (image_methods);
3791 mono_os_mutex_lock (&coverage_mutex);
3792 mono_conc_hashtable_insert (image_to_methods, image, image_methods);
3793 mono_os_mutex_unlock (&coverage_mutex);
3796 node = create_method_node (method);
3797 mono_lock_free_queue_enqueue (image_methods, node);
3799 class_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (coverage_classes, klass);
3801 if (class_methods == NULL) {
3802 class_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
3803 mono_lock_free_queue_init (class_methods);
3804 mono_os_mutex_lock (&coverage_mutex);
3805 mono_conc_hashtable_insert (coverage_classes, klass, class_methods);
3806 mono_os_mutex_unlock (&coverage_mutex);
3809 node = create_method_node (method);
3810 mono_lock_free_queue_enqueue (class_methods, node);
3815 #define LINE_BUFFER_SIZE 4096
3816 /* Max file limit of 128KB */
3817 #define MAX_FILE_SIZE 128 * 1024
3819 get_file_content (FILE *stream)
3824 int res, offset = 0;
3826 res = fseek (stream, 0, SEEK_END);
3830 filesize = ftell (stream);
3834 res = fseek (stream, 0, SEEK_SET);
3838 if (filesize > MAX_FILE_SIZE)
3841 buffer = (char *)g_malloc ((filesize + 1) * sizeof (char));
3842 while ((bytes_read = fread (buffer + offset, 1, LINE_BUFFER_SIZE, stream)) > 0)
3843 offset += bytes_read;
3845 /* NULL terminate our buffer */
3846 buffer[filesize] = '\0';
3851 get_next_line (char *contents, char **next_start)
3855 if (p == NULL || *p == '\0') {
3860 while (*p != '\n' && *p != '\0')
3865 *next_start = p + 1;
3873 init_suppressed_assemblies (void)
3879 suppressed_assemblies = mono_conc_hashtable_new (g_str_hash, g_str_equal);
3880 sa_file = fopen (SUPPRESSION_DIR "/mono-profiler-log.suppression", "r");
3881 if (sa_file == NULL)
3884 /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
3885 content = get_file_content (sa_file);
3886 if (content == NULL) {
3887 g_error ("mono-profiler-log.suppression is greater than 128kb - aborting\n");
3890 while ((line = get_next_line (content, &content))) {
3891 line = g_strchomp (g_strchug (line));
3892 /* No locking needed as we're doing initialization */
3893 mono_conc_hashtable_insert (suppressed_assemblies, line, line);
3899 #endif /* DISABLE_HELPER_THREAD */
3902 coverage_init (MonoProfiler *prof)
3904 #ifndef DISABLE_HELPER_THREAD
3905 assert (!coverage_initialized);
3907 COVERAGE_DEBUG(fprintf (stderr, "Coverage initialized\n");)
3909 mono_os_mutex_init (&coverage_mutex);
3910 coverage_methods = mono_conc_hashtable_new (NULL, NULL);
3911 coverage_assemblies = mono_conc_hashtable_new (NULL, NULL);
3912 coverage_classes = mono_conc_hashtable_new (NULL, NULL);
3913 filtered_classes = mono_conc_hashtable_new (NULL, NULL);
3914 entered_methods = mono_conc_hashtable_new (NULL, NULL);
3915 image_to_methods = mono_conc_hashtable_new (NULL, NULL);
3916 init_suppressed_assemblies ();
3918 coverage_initialized = TRUE;
3919 #endif /* DISABLE_HELPER_THREAD */
3923 unref_coverage_assemblies (gpointer key, gpointer value, gpointer userdata)
3925 MonoAssembly *assembly = (MonoAssembly *)value;
3926 mono_assembly_close (assembly);
3930 log_shutdown (MonoProfiler *prof)
3935 #ifndef DISABLE_HELPER_THREAD
3936 counters_and_perfcounters_sample (prof);
3938 dump_coverage (prof);
3940 if (prof->command_port) {
3942 ign_res (write (prof->pipes [1], &c, 1));
3943 pthread_join (prof->helper_thread, &res);
3949 for (i = 0; i < num_perf; ++i)
3950 read_perf_mmap (prof, i);
3954 g_ptr_array_free (prof->sorted_sample_events, TRUE);
3956 if (TLS_GET (LogBuffer, tlsbuffer))
3957 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
3959 TLS_SET (tlsbuffer, NULL);
3960 TLS_SET (tlsmethodlist, NULL);
3962 InterlockedWrite (&prof->run_writer_thread, 0);
3963 pthread_join (prof->writer_thread, &res);
3965 #if defined (HAVE_SYS_ZLIB)
3967 gzclose (prof->gzfile);
3969 if (prof->pipe_output)
3970 pclose (prof->file);
3972 fclose (prof->file);
3974 mono_conc_hashtable_destroy (prof->method_table);
3975 mono_os_mutex_destroy (&prof->method_table_mutex);
3977 if (coverage_initialized) {
3978 mono_os_mutex_lock (&coverage_mutex);
3979 mono_conc_hashtable_foreach (coverage_assemblies, unref_coverage_assemblies, prof);
3980 mono_os_mutex_unlock (&coverage_mutex);
3982 mono_conc_hashtable_destroy (coverage_methods);
3983 mono_conc_hashtable_destroy (coverage_assemblies);
3984 mono_conc_hashtable_destroy (coverage_classes);
3985 mono_conc_hashtable_destroy (filtered_classes);
3987 mono_conc_hashtable_destroy (entered_methods);
3988 mono_conc_hashtable_destroy (image_to_methods);
3989 mono_conc_hashtable_destroy (suppressed_assemblies);
3990 mono_os_mutex_destroy (&coverage_mutex);
3997 new_filename (const char* filename)
3999 time_t t = time (NULL);
4000 int pid = process_id ();
4005 int count_dates = 0;
4009 for (p = filename; *p; p++) {
4020 if (!count_dates && !count_pids)
4021 return pstrdup (filename);
4022 snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
4024 snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
4025 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
4026 s_date = strlen (time_buf);
4027 s_pid = strlen (pid_buf);
4028 d = res = (char *)malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
4029 for (p = filename; *p; p++) {
4036 strcpy (d, time_buf);
4039 } else if (*p == 'p') {
4040 strcpy (d, pid_buf);
4043 } else if (*p == '%') {
4055 //this is exposed by the JIT, but it's not meant to be a supported API for now.
4056 extern void mono_threads_attach_tools_thread (void);
4058 #ifndef DISABLE_HELPER_THREAD
4061 helper_thread (void* arg)
4063 MonoProfiler* prof = (MonoProfiler *)arg;
4067 MonoThread *thread = NULL;
4069 mono_threads_attach_tools_thread ();
4070 //fprintf (stderr, "Server listening\n");
4071 command_socket = -1;
4077 FD_SET (prof->server_socket, &rfds);
4078 max_fd = prof->server_socket;
4079 FD_SET (prof->pipes [0], &rfds);
4080 if (max_fd < prof->pipes [0])
4081 max_fd = prof->pipes [0];
4082 if (command_socket >= 0) {
4083 FD_SET (command_socket, &rfds);
4084 if (max_fd < command_socket)
4085 max_fd = command_socket;
4090 for ( i = 0; i < num_perf; ++i) {
4091 if (perf_data [i].perf_fd < 0)
4093 FD_SET (perf_data [i].perf_fd, &rfds);
4094 if (max_fd < perf_data [i].perf_fd)
4095 max_fd = perf_data [i].perf_fd;
4100 counters_and_perfcounters_sample (prof);
4104 len = select (max_fd + 1, &rfds, NULL, NULL, &tv);
4110 g_warning ("Error in proflog server: %s", strerror (errno));
4114 if (FD_ISSET (prof->pipes [0], &rfds)) {
4116 int r = read (prof->pipes [0], &c, 1);
4117 if (r == 1 && c == 0) {
4118 StatBuffer *sbufbase = prof->stat_buffers;
4120 if (!sbufbase->next)
4122 sbuf = sbufbase->next->next;
4123 sbufbase->next->next = NULL;
4125 fprintf (stderr, "stat buffer dump\n");
4127 dump_sample_hits (prof, sbuf);
4128 free_buffer (sbuf, sbuf->size);
4129 safe_send (prof, ensure_logbuf (0));
4133 /* time to shut down */
4134 dump_sample_hits (prof, prof->stat_buffers);
4136 mono_thread_detach (thread);
4138 fprintf (stderr, "helper shutdown\n");
4142 for ( i = 0; i < num_perf; ++i) {
4143 if (perf_data [i].perf_fd < 0)
4145 if (FD_ISSET (perf_data [i].perf_fd, &rfds))
4146 read_perf_mmap (prof, i);
4150 safe_send (prof, ensure_logbuf (0));
4156 for ( i = 0; i < num_perf; ++i) {
4157 if (perf_data [i].perf_fd < 0)
4159 if (FD_ISSET (perf_data [i].perf_fd, &rfds)) {
4160 read_perf_mmap (prof, i);
4161 safe_send (prof, ensure_logbuf (0));
4166 if (command_socket >= 0 && FD_ISSET (command_socket, &rfds)) {
4167 len = read (command_socket, buf, sizeof (buf) - 1);
4171 close (command_socket);
4172 command_socket = -1;
4176 if (strcmp (buf, "heapshot\n") == 0) {
4177 heapshot_requested = 1;
4178 //fprintf (stderr, "perform heapshot\n");
4179 if (InterlockedRead (&runtime_inited) && !thread) {
4180 thread = mono_thread_attach (mono_get_root_domain ());
4181 /*fprintf (stderr, "attached\n");*/
4184 process_requests (prof);
4185 mono_thread_detach (thread);
4191 if (!FD_ISSET (prof->server_socket, &rfds)) {
4194 command_socket = accept (prof->server_socket, NULL, NULL);
4195 if (command_socket < 0)
4197 //fprintf (stderr, "Accepted connection\n");
4203 start_helper_thread (MonoProfiler* prof)
4205 struct sockaddr_in server_address;
4208 if (pipe (prof->pipes) < 0) {
4209 fprintf (stderr, "Cannot create pipe\n");
4212 prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
4213 if (prof->server_socket < 0) {
4214 fprintf (stderr, "Cannot create server socket\n");
4217 memset (&server_address, 0, sizeof (server_address));
4218 server_address.sin_family = AF_INET;
4219 server_address.sin_addr.s_addr = INADDR_ANY;
4220 server_address.sin_port = htons (prof->command_port);
4221 if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) < 0) {
4222 fprintf (stderr, "Cannot bind server socket, port: %d: %s\n", prof->command_port, strerror (errno));
4223 close (prof->server_socket);
4226 if (listen (prof->server_socket, 1) < 0) {
4227 fprintf (stderr, "Cannot listen server socket\n");
4228 close (prof->server_socket);
4231 slen = sizeof (server_address);
4232 if (getsockname (prof->server_socket, (struct sockaddr *)&server_address, &slen) == 0) {
4233 prof->command_port = ntohs (server_address.sin_port);
4234 /*fprintf (stderr, "Assigned server port: %d\n", prof->command_port);*/
4237 r = pthread_create (&prof->helper_thread, NULL, helper_thread, prof);
4239 close (prof->server_socket);
4247 writer_thread (void *arg)
4249 MonoProfiler *prof = (MonoProfiler *)arg;
4251 mono_threads_attach_tools_thread ();
4255 while (InterlockedRead (&prof->run_writer_thread)) {
4256 WriterQueueEntry *entry;
4258 while ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&prof->writer_queue))) {
4259 LogBuffer *method_buffer = NULL;
4260 gboolean new_methods = FALSE;
4262 if (entry->methods->len)
4263 method_buffer = create_buffer ();
4266 * Encode the method events in a temporary log buffer that we
4267 * flush to disk before the main buffer, ensuring that all
4268 * methods have metadata emitted before they're referenced.
4270 for (guint i = 0; i < entry->methods->len; i++) {
4271 MethodInfo *info = (MethodInfo *)g_ptr_array_index (entry->methods, i);
4273 if (mono_conc_hashtable_lookup (prof->method_table, info->method))
4279 * Other threads use this hash table to get a general
4280 * idea of whether a method has already been emitted to
4281 * the stream. Due to the way we add to this table, it
4282 * can easily happen that multiple threads queue up the
4283 * same methods, but that's OK since eventually all
4284 * methods will be in this table and the thread-local
4285 * method lists will just be empty for the rest of the
4288 mono_os_mutex_lock (&prof->method_table_mutex);
4289 mono_conc_hashtable_insert (prof->method_table, info->method, info->method);
4290 mono_os_mutex_unlock (&prof->method_table_mutex);
4292 char *name = mono_method_full_name (info->method, 1);
4293 int nlen = strlen (name) + 1;
4294 void *cstart = info->ji ? mono_jit_info_get_code_start (info->ji) : NULL;
4295 int csize = info->ji ? mono_jit_info_get_code_size (info->ji) : 0;
4297 method_buffer = ensure_logbuf_inner (method_buffer,
4298 EVENT_SIZE /* event */ +
4299 LEB128_SIZE /* time */ +
4300 LEB128_SIZE /* method */ +
4301 LEB128_SIZE /* start */ +
4302 LEB128_SIZE /* size */ +
4306 emit_byte (method_buffer, TYPE_JIT | TYPE_METHOD);
4307 emit_time (method_buffer, info->time);
4308 emit_method_inner (method_buffer, info->method);
4309 emit_ptr (method_buffer, cstart);
4310 emit_value (method_buffer, csize);
4312 memcpy (method_buffer->cursor, name, nlen);
4313 method_buffer->cursor += nlen;
4319 g_ptr_array_free (entry->methods, TRUE);
4322 dump_buffer (prof, method_buffer);
4323 else if (method_buffer)
4324 free_buffer (method_buffer, method_buffer->size);
4326 dump_buffer (prof, entry->buffer);
4336 start_writer_thread (MonoProfiler* prof)
4338 InterlockedWrite (&prof->run_writer_thread, 1);
4340 return !pthread_create (&prof->writer_thread, NULL, writer_thread, prof);
4344 runtime_initialized (MonoProfiler *profiler)
4346 #ifndef DISABLE_HELPER_THREAD
4347 if (hs_mode_ondemand || need_helper_thread) {
4348 if (!start_helper_thread (profiler))
4349 profiler->command_port = 0;
4353 start_writer_thread (profiler);
4355 InterlockedWrite (&runtime_inited, 1);
4356 #ifndef DISABLE_HELPER_THREAD
4357 counters_init (profiler);
4358 counters_sample (profiler, 0);
4360 /* ensure the main thread data and startup are available soon */
4361 safe_send (profiler, ensure_logbuf (0));
4364 static MonoProfiler*
4365 create_profiler (const char *filename, GPtrArray *filters)
4369 int force_delete = 0;
4370 prof = (MonoProfiler *)calloc (1, sizeof (MonoProfiler));
4372 prof->command_port = command_port;
4373 if (filename && *filename == '-') {
4379 filename = "|mprof-report -";
4381 filename = "output.mlpd";
4382 nf = (char*)filename;
4384 nf = new_filename (filename);
4386 int s = strlen (nf) + 32;
4387 char *p = (char *)malloc (s);
4388 snprintf (p, s, "|mprof-report '--out=%s' -", nf);
4394 prof->file = popen (nf + 1, "w");
4395 prof->pipe_output = 1;
4396 } else if (*nf == '#') {
4397 int fd = strtol (nf + 1, NULL, 10);
4398 prof->file = fdopen (fd, "a");
4402 prof->file = fopen (nf, "wb");
4405 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
4408 #if defined (HAVE_SYS_ZLIB)
4410 prof->gzfile = gzdopen (fileno (prof->file), "wb");
4413 if (sample_type && !do_mono_sample)
4414 need_helper_thread = setup_perf_event ();
4416 /* FIXME: warn if different freq or sample type */
4420 if (do_mono_sample) {
4421 prof->stat_buffers = create_stat_buffer ();
4422 need_helper_thread = 1;
4424 if (do_counters && !need_helper_thread) {
4425 need_helper_thread = 1;
4428 prof->sorted_sample_events = g_ptr_array_sized_new (BUFFER_SIZE / SAMPLE_EVENT_SIZE_IN_SLOTS (0));
4430 #ifdef DISABLE_HELPER_THREAD
4431 if (hs_mode_ondemand)
4432 fprintf (stderr, "Ondemand heapshot unavailable on this arch.\n");
4435 fprintf (stderr, "Coverage unavailable on this arch.\n");
4439 mono_lock_free_queue_init (&prof->writer_queue);
4440 mono_os_mutex_init (&prof->method_table_mutex);
4441 prof->method_table = mono_conc_hashtable_new (NULL, NULL);
4444 coverage_init (prof);
4445 prof->coverage_filters = filters;
4447 prof->startup_time = current_time ();
4454 printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
4455 printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
4456 printf ("Options:\n");
4457 printf ("\thelp show this usage info\n");
4458 printf ("\t[no]alloc enable/disable recording allocation info\n");
4459 printf ("\t[no]calls enable/disable recording enter/leave method events\n");
4460 printf ("\theapshot[=MODE] record heap shot info (by default at each major collection)\n");
4461 printf ("\t MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
4462 printf ("\tcounters sample counters every 1s\n");
4463 printf ("\tsample[=TYPE] use statistical sampling mode (by default cycles/1000)\n");
4464 printf ("\t TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
4465 printf ("\t TYPE can be followed by /FREQUENCY\n");
4466 printf ("\ttime=fast use a faster (but more inaccurate) timer\n");
4467 printf ("\tmaxframes=NUM collect up to NUM stack frames\n");
4468 printf ("\tcalldepth=NUM ignore method events for call chain depth bigger than NUM\n");
4469 printf ("\toutput=FILENAME write the data to file FILENAME (-FILENAME to overwrite)\n");
4470 printf ("\toutput=|PROGRAM write the data to the stdin of PROGRAM\n");
4471 printf ("\t %%t is subtituted with date and time, %%p with the pid\n");
4472 printf ("\treport create a report instead of writing the raw data to a file\n");
4473 printf ("\tzip compress the output data\n");
4474 printf ("\tport=PORTNUM use PORTNUM for the listening command server\n");
4475 printf ("\tcoverage enable collection of code coverage data\n");
4476 printf ("\tcovfilter=ASSEMBLY add an assembly to the code coverage filters\n");
4477 printf ("\t add a + to include the assembly or a - to exclude it\n");
4478 printf ("\t filter=-mscorlib\n");
4479 printf ("\tcovfilter-file=FILE use FILE to generate the list of assemblies to be filtered\n");
4485 match_option (const char* p, const char *opt, char **rval)
4487 int len = strlen (opt);
4488 if (strncmp (p, opt, len) == 0) {
4490 if (p [len] == '=' && p [len + 1]) {
4491 const char *opt = p + len + 1;
4492 const char *end = strchr (opt, ',');
4500 val = (char *)malloc (l + 1);
4501 memcpy (val, opt, l);
4506 if (p [len] == 0 || p [len] == ',') {
4508 return p + len + (p [len] == ',');
4526 static const SampleMode sample_modes [] = {
4527 {"cycles", SAMPLE_CYCLES},
4528 {"instr", SAMPLE_INSTRUCTIONS},
4529 {"cachemiss", SAMPLE_CACHE_MISSES},
4530 {"cacherefs", SAMPLE_CACHE_REFS},
4531 {"branches", SAMPLE_BRANCHES},
4532 {"branchmiss", SAMPLE_BRANCH_MISSES},
4537 set_sample_mode (char* val, int allow_empty)
4540 char *maybe_freq = NULL;
4542 const SampleMode *smode = sample_modes;
4543 #ifndef USE_PERF_EVENTS
4546 if (allow_empty && !val) {
4547 sample_type = SAMPLE_CYCLES;
4551 if (strcmp (val, "mono") == 0) {
4553 sample_type = SAMPLE_CYCLES;
4557 for (smode = sample_modes; smode->name; smode++) {
4558 int l = strlen (smode->name);
4559 if (strncmp (val, smode->name, l) == 0) {
4560 sample_type = smode->sample_mode;
4561 maybe_freq = val + l;
4567 if (*maybe_freq == '/') {
4568 count = strtoul (maybe_freq + 1, &end, 10);
4569 if (maybe_freq + 1 == end)
4571 sample_freq = count;
4572 } else if (*maybe_freq != 0) {
4581 set_hsmode (char* val, int allow_empty)
4585 if (allow_empty && !val)
4587 if (strcmp (val, "ondemand") == 0) {
4588 hs_mode_ondemand = 1;
4592 count = strtoul (val, &end, 10);
4595 if (strcmp (end, "ms") == 0)
4597 else if (strcmp (end, "gc") == 0)
4605 * declaration to silence the compiler: this is the entry point that
4606 * mono will load from the shared library and call.
4609 mono_profiler_startup (const char *desc);
4612 mono_profiler_startup_log (const char *desc);
4615 * this is the entry point that will be used when the profiler
4616 * is embedded inside the main executable.
4619 mono_profiler_startup_log (const char *desc)
4621 mono_profiler_startup (desc);
4625 mono_profiler_startup (const char *desc)
4628 GPtrArray *filters = NULL;
4629 char *filename = NULL;
4633 int calls_enabled = 0;
4634 int allocs_enabled = 0;
4635 int only_counters = 0;
4636 int only_coverage = 0;
4637 int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
4638 MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
4639 MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
4640 MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS|
4641 MONO_PROFILE_INS_COVERAGE|MONO_PROFILE_APPDOMAIN_EVENTS|MONO_PROFILE_CONTEXT_EVENTS|
4642 MONO_PROFILE_ASSEMBLY_EVENTS;
4645 if (strncmp (p, "log", 3))
4650 for (; *p; p = opt) {
4656 if ((opt = match_option (p, "help", NULL)) != p) {
4660 if ((opt = match_option (p, "calls", NULL)) != p) {
4664 if ((opt = match_option (p, "nocalls", NULL)) != p) {
4665 events &= ~MONO_PROFILE_ENTER_LEAVE;
4669 if ((opt = match_option (p, "alloc", NULL)) != p) {
4673 if ((opt = match_option (p, "noalloc", NULL)) != p) {
4674 events &= ~MONO_PROFILE_ALLOCATIONS;
4677 if ((opt = match_option (p, "time", &val)) != p) {
4678 if (strcmp (val, "fast") == 0)
4680 else if (strcmp (val, "null") == 0)
4687 if ((opt = match_option (p, "report", NULL)) != p) {
4691 if ((opt = match_option (p, "debug", NULL)) != p) {
4695 if ((opt = match_option (p, "sampling-real", NULL)) != p) {
4696 sampling_mode = MONO_PROFILER_STAT_MODE_REAL;
4699 if ((opt = match_option (p, "sampling-process", NULL)) != p) {
4700 sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
4703 if ((opt = match_option (p, "heapshot", &val)) != p) {
4704 events &= ~MONO_PROFILE_ALLOCATIONS;
4705 events &= ~MONO_PROFILE_ENTER_LEAVE;
4708 set_hsmode (val, 1);
4711 if ((opt = match_option (p, "sample", &val)) != p) {
4712 events &= ~MONO_PROFILE_ALLOCATIONS;
4713 events &= ~MONO_PROFILE_ENTER_LEAVE;
4715 set_sample_mode (val, 1);
4718 if ((opt = match_option (p, "hsmode", &val)) != p) {
4719 fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
4720 set_hsmode (val, 0);
4723 if ((opt = match_option (p, "zip", NULL)) != p) {
4727 if ((opt = match_option (p, "output", &val)) != p) {
4731 if ((opt = match_option (p, "port", &val)) != p) {
4733 command_port = strtoul (val, &end, 10);
4737 if ((opt = match_option (p, "maxframes", &val)) != p) {
4739 num_frames = strtoul (val, &end, 10);
4740 if (num_frames > MAX_FRAMES)
4741 num_frames = MAX_FRAMES;
4743 notraces = num_frames == 0;
4746 if ((opt = match_option (p, "calldepth", &val)) != p) {
4748 max_call_depth = strtoul (val, &end, 10);
4752 if ((opt = match_option (p, "counters", NULL)) != p) {
4756 if ((opt = match_option (p, "countersonly", NULL)) != p) {
4760 if ((opt = match_option (p, "coverage", NULL)) != p) {
4762 events |= MONO_PROFILE_ENTER_LEAVE;
4763 debug_coverage = (g_getenv ("MONO_PROFILER_DEBUG_COVERAGE") != NULL);
4766 if ((opt = match_option (p, "onlycoverage", NULL)) != p) {
4770 if ((opt = match_option (p, "covfilter-file", &val)) != p) {
4772 char *line, *content;
4774 if (filters == NULL)
4775 filters = g_ptr_array_new ();
4777 filter_file = fopen (val, "r");
4778 if (filter_file == NULL) {
4779 fprintf (stderr, "Unable to open %s\n", val);
4783 /* Don't need to free content as it is referred to by the lines stored in @filters */
4784 content = get_file_content (filter_file);
4785 if (content == NULL)
4786 fprintf (stderr, "WARNING: %s is greater than 128kb - ignoring\n", val);
4788 while ((line = get_next_line (content, &content)))
4789 g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
4791 fclose (filter_file);
4794 if ((opt = match_option (p, "covfilter", &val)) != p) {
4795 if (filters == NULL)
4796 filters = g_ptr_array_new ();
4798 g_ptr_array_add (filters, val);
4806 if (calls_enabled) {
4807 events |= MONO_PROFILE_ENTER_LEAVE;
4811 events |= MONO_PROFILE_ALLOCATIONS;
4815 events = MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_INS_COVERAGE;
4817 utils_init (fast_time);
4819 prof = create_profiler (filename, filters);
4824 mono_profiler_install (prof, log_shutdown);
4825 mono_profiler_install_gc (gc_event, gc_resize);
4826 mono_profiler_install_allocation (gc_alloc);
4827 mono_profiler_install_gc_moves (gc_moves);
4828 mono_profiler_install_gc_roots (gc_handle, gc_roots);
4829 mono_profiler_install_appdomain (NULL, domain_loaded, NULL, domain_unloaded);
4830 mono_profiler_install_appdomain_name (domain_name);
4831 mono_profiler_install_context (context_loaded, context_unloaded);
4832 mono_profiler_install_class (NULL, class_loaded, NULL, class_unloaded);
4833 mono_profiler_install_module (NULL, image_loaded, NULL, image_unloaded);
4834 mono_profiler_install_assembly (NULL, assembly_loaded, assembly_unloaded, NULL);
4835 mono_profiler_install_thread (thread_start, thread_end);
4836 mono_profiler_install_thread_name (thread_name);
4837 mono_profiler_install_enter_leave (method_enter, method_leave);
4838 mono_profiler_install_jit_end (method_jitted);
4839 mono_profiler_install_code_buffer_new (code_buffer_new);
4840 mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
4841 mono_profiler_install_monitor (monitor_event);
4842 mono_profiler_install_runtime_initialized (runtime_initialized);
4844 mono_profiler_install_coverage_filter (coverage_filter);
4846 if (do_mono_sample && sample_type == SAMPLE_CYCLES && !only_counters) {
4847 events |= MONO_PROFILE_STATISTICAL;
4848 mono_profiler_set_statistical_mode (sampling_mode, 1000000 / sample_freq);
4849 mono_profiler_install_statistical (mono_sample_hit);
4852 mono_profiler_set_events ((MonoProfileFlags)events);
4854 TLS_INIT (tlsbuffer);
4855 TLS_INIT (tlsmethodlist);