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, gboolean threadless);
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 safe_send_threadless (MonoProfiler *prof, LogBuffer *buf)
969 for (LogBuffer *iter = buf; iter; iter = iter->next)
972 safe_send (prof, buf);
976 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
979 uintptr_t last_offset = 0;
980 //const char *name = mono_class_get_name (klass);
981 LogBuffer *logbuffer = ensure_logbuf (
982 EVENT_SIZE /* event */ +
983 LEB128_SIZE /* obj */ +
984 LEB128_SIZE /* klass */ +
985 LEB128_SIZE /* size */ +
986 LEB128_SIZE /* num */ +
988 LEB128_SIZE /* offset */ +
989 LEB128_SIZE /* ref */
992 emit_byte (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
993 emit_obj (logbuffer, obj);
994 emit_ptr (logbuffer, klass);
995 /* account for object alignment in the heap */
998 emit_value (logbuffer, size);
999 emit_value (logbuffer, num);
1000 for (i = 0; i < num; ++i) {
1001 emit_value (logbuffer, offsets [i] - last_offset);
1002 last_offset = offsets [i];
1003 emit_obj (logbuffer, refs [i]);
1006 // printf ("obj: %p, klass: %s, refs: %d, size: %d\n", obj, name, (int)num, (int)size);
1010 static unsigned int hs_mode_ms = 0;
1011 static unsigned int hs_mode_gc = 0;
1012 static unsigned int hs_mode_ondemand = 0;
1013 static unsigned int gc_count = 0;
1014 static uint64_t last_hs_time = 0;
1017 heap_walk (MonoProfiler *profiler)
1021 LogBuffer *logbuffer;
1024 logbuffer = ensure_logbuf (
1025 EVENT_SIZE /* event */ +
1026 LEB128_SIZE /* time */
1028 now = current_time ();
1029 if (hs_mode_ms && (now - last_hs_time)/1000000 >= hs_mode_ms)
1031 else if (hs_mode_gc && (gc_count % hs_mode_gc) == 0)
1033 else if (hs_mode_ondemand)
1034 do_walk = heapshot_requested;
1035 else if (!hs_mode_ms && !hs_mode_gc && profiler->last_gc_gen_started == mono_gc_max_generation ())
1040 heapshot_requested = 0;
1041 emit_byte (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
1042 emit_time (logbuffer, now);
1043 mono_gc_walk_heap (0, gc_reference, NULL);
1044 logbuffer = ensure_logbuf (
1045 EVENT_SIZE /* event */ +
1046 LEB128_SIZE /* time */
1048 now = current_time ();
1049 emit_byte (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
1050 emit_time (logbuffer, now);
1055 gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation) {
1057 LogBuffer *logbuffer = ensure_logbuf (
1058 EVENT_SIZE /* event */ +
1059 LEB128_SIZE /* time */ +
1060 LEB128_SIZE /* gc event */ +
1061 LEB128_SIZE /* generation */
1063 now = current_time ();
1064 ENTER_LOG (logbuffer, "gcevent");
1065 emit_byte (logbuffer, TYPE_GC_EVENT | TYPE_GC);
1066 emit_time (logbuffer, now);
1067 emit_value (logbuffer, ev);
1068 emit_value (logbuffer, generation);
1069 /* to deal with nested gen1 after gen0 started */
1070 if (ev == MONO_GC_EVENT_START) {
1071 profiler->last_gc_gen_started = generation;
1072 if (generation == mono_gc_max_generation ())
1075 if (ev == MONO_GC_EVENT_PRE_START_WORLD)
1076 heap_walk (profiler);
1077 EXIT_LOG (logbuffer);
1078 if (ev == MONO_GC_EVENT_POST_START_WORLD)
1079 safe_send (profiler, logbuffer);
1080 //printf ("gc event %d for generation %d\n", ev, generation);
1084 gc_resize (MonoProfiler *profiler, int64_t new_size) {
1086 LogBuffer *logbuffer = ensure_logbuf (
1087 EVENT_SIZE /* event */ +
1088 LEB128_SIZE /* time */ +
1089 LEB128_SIZE /* new size */
1091 now = current_time ();
1092 ENTER_LOG (logbuffer, "gcresize");
1093 emit_byte (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
1094 emit_time (logbuffer, now);
1095 emit_value (logbuffer, new_size);
1096 //printf ("gc resized to %lld\n", new_size);
1097 EXIT_LOG (logbuffer);
1100 #define MAX_FRAMES 32
1103 MonoMethod* methods [MAX_FRAMES];
1104 int32_t il_offsets [MAX_FRAMES];
1105 int32_t native_offsets [MAX_FRAMES];
1107 static int num_frames = MAX_FRAMES;
1110 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
1112 FrameData *frame = (FrameData *)data;
1113 if (method && frame->count < num_frames) {
1114 frame->il_offsets [frame->count] = il_offset;
1115 frame->native_offsets [frame->count] = native_offset;
1116 frame->methods [frame->count++] = method;
1117 //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
1119 return frame->count == num_frames;
1123 * a note about stack walks: they can cause more profiler events to fire,
1124 * so we need to make sure they don't happen after we started emitting an
1125 * event, hence the collect_bt/emit_bt split.
1128 collect_bt (FrameData *data)
1131 mono_stack_walk_no_il (walk_stack, data);
1135 emit_bt (MonoProfiler *prof, LogBuffer *logbuffer, FrameData *data)
1137 /* FIXME: this is actually tons of data and we should
1138 * just output it the first time and use an id the next
1140 if (data->count > num_frames)
1141 printf ("bad num frames: %d\n", data->count);
1142 emit_value (logbuffer, 0); /* flags */
1143 emit_value (logbuffer, data->count);
1144 //if (*p != data.count) {
1145 // 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);}
1146 while (data->count) {
1147 emit_method_as_ptr (prof, logbuffer, data->methods [--data->count]);
1152 gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1156 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces)? TYPE_ALLOC_BT: 0;
1158 LogBuffer *logbuffer;
1159 len = mono_object_get_size (obj);
1160 /* account for object alignment in the heap */
1165 logbuffer = ensure_logbuf (
1166 EVENT_SIZE /* event */ +
1167 LEB128_SIZE /* time */ +
1168 LEB128_SIZE /* klass */ +
1169 LEB128_SIZE /* obj */ +
1170 LEB128_SIZE /* size */ +
1172 LEB128_SIZE /* flags */ +
1173 LEB128_SIZE /* count */ +
1175 LEB128_SIZE /* method */
1179 now = current_time ();
1180 ENTER_LOG (logbuffer, "gcalloc");
1181 emit_byte (logbuffer, do_bt | TYPE_ALLOC);
1182 emit_time (logbuffer, now);
1183 emit_ptr (logbuffer, klass);
1184 emit_obj (logbuffer, obj);
1185 emit_value (logbuffer, len);
1187 emit_bt (prof, logbuffer, &data);
1188 EXIT_LOG (logbuffer);
1189 if (logbuffer->next)
1190 safe_send (prof, logbuffer);
1191 process_requests (prof);
1192 //printf ("gc alloc %s at %p\n", mono_class_get_name (klass), obj);
1196 gc_moves (MonoProfiler *prof, void **objects, int num)
1200 LogBuffer *logbuffer = ensure_logbuf (
1201 EVENT_SIZE /* event */ +
1202 LEB128_SIZE /* time */ +
1203 LEB128_SIZE /* num */ +
1205 LEB128_SIZE /* object */
1208 now = current_time ();
1209 ENTER_LOG (logbuffer, "gcmove");
1210 emit_byte (logbuffer, TYPE_GC_MOVE | TYPE_GC);
1211 emit_time (logbuffer, now);
1212 emit_value (logbuffer, num);
1213 for (i = 0; i < num; ++i)
1214 emit_obj (logbuffer, objects [i]);
1215 //printf ("gc moved %d objects\n", num/2);
1216 EXIT_LOG (logbuffer);
1220 gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
1223 LogBuffer *logbuffer = ensure_logbuf (
1224 EVENT_SIZE /* event */ +
1225 LEB128_SIZE /* num */ +
1226 LEB128_SIZE /* collections */ +
1228 LEB128_SIZE /* object */ +
1229 LEB128_SIZE /* root type */ +
1230 LEB128_SIZE /* extra info */
1233 ENTER_LOG (logbuffer, "gcroots");
1234 emit_byte (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
1235 emit_value (logbuffer, num);
1236 emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
1237 for (i = 0; i < num; ++i) {
1238 emit_obj (logbuffer, objects [i]);
1239 emit_value (logbuffer, root_types [i]);
1240 emit_value (logbuffer, extra_info [i]);
1242 EXIT_LOG (logbuffer);
1246 gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
1248 int do_bt = nocalls && InterlockedRead (&runtime_inited) && !notraces;
1255 LogBuffer *logbuffer = ensure_logbuf (
1256 EVENT_SIZE /* event */ +
1257 LEB128_SIZE /* time */ +
1258 LEB128_SIZE /* type */ +
1259 LEB128_SIZE /* handle */ +
1260 (op == MONO_PROFILER_GC_HANDLE_CREATED ? (
1261 LEB128_SIZE /* obj */
1264 LEB128_SIZE /* flags */ +
1265 LEB128_SIZE /* count */ +
1267 LEB128_SIZE /* method */
1272 now = current_time ();
1273 ENTER_LOG (logbuffer, "gchandle");
1275 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1276 emit_byte (logbuffer, (do_bt ? TYPE_GC_HANDLE_CREATED_BT : TYPE_GC_HANDLE_CREATED) | TYPE_GC);
1277 else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
1278 emit_byte (logbuffer, (do_bt ? TYPE_GC_HANDLE_DESTROYED_BT : TYPE_GC_HANDLE_DESTROYED) | TYPE_GC);
1280 g_assert_not_reached ();
1282 emit_time (logbuffer, now);
1283 emit_value (logbuffer, type);
1284 emit_value (logbuffer, handle);
1286 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1287 emit_obj (logbuffer, obj);
1290 emit_bt (prof, logbuffer, &data);
1292 EXIT_LOG (logbuffer);
1293 process_requests (prof);
1297 push_nesting (char *p, MonoClass *klass)
1302 nesting = mono_class_get_nesting_type (klass);
1304 p = push_nesting (p, nesting);
1308 name = mono_class_get_name (klass);
1309 nspace = mono_class_get_namespace (klass);
1312 p += strlen (nspace);
1322 type_name (MonoClass *klass)
1326 push_nesting (buf, klass);
1327 p = (char *)malloc (strlen (buf) + 1);
1333 image_loaded (MonoProfiler *prof, MonoImage *image, int result)
1338 LogBuffer *logbuffer;
1339 if (result != MONO_PROFILE_OK)
1341 name = mono_image_get_filename (image);
1342 nlen = strlen (name) + 1;
1343 logbuffer = ensure_logbuf (
1344 EVENT_SIZE /* event */ +
1345 LEB128_SIZE /* time */ +
1346 EVENT_SIZE /* type */ +
1347 LEB128_SIZE /* image */ +
1348 LEB128_SIZE /* flags */ +
1351 now = current_time ();
1352 ENTER_LOG (logbuffer, "image");
1353 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1354 emit_time (logbuffer, now);
1355 emit_byte (logbuffer, TYPE_IMAGE);
1356 emit_ptr (logbuffer, image);
1357 emit_value (logbuffer, 0); /* flags */
1358 memcpy (logbuffer->cursor, name, nlen);
1359 logbuffer->cursor += nlen;
1360 //printf ("loaded image %p (%s)\n", image, name);
1361 EXIT_LOG (logbuffer);
1362 if (logbuffer->next)
1363 safe_send (prof, logbuffer);
1364 process_requests (prof);
1368 image_unloaded (MonoProfiler *prof, MonoImage *image)
1370 const char *name = mono_image_get_filename (image);
1371 int nlen = strlen (name) + 1;
1372 LogBuffer *logbuffer = ensure_logbuf (
1373 EVENT_SIZE /* event */ +
1374 LEB128_SIZE /* time */ +
1375 EVENT_SIZE /* type */ +
1376 LEB128_SIZE /* image */ +
1377 LEB128_SIZE /* flags */ +
1380 uint64_t now = current_time ();
1382 ENTER_LOG (logbuffer, "image-unload");
1383 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1384 emit_time (logbuffer, now);
1385 emit_byte (logbuffer, TYPE_IMAGE);
1386 emit_ptr (logbuffer, image);
1387 emit_value (logbuffer, 0); /* flags */
1388 memcpy (logbuffer->cursor, name, nlen);
1389 logbuffer->cursor += nlen;
1390 EXIT_LOG (logbuffer);
1392 if (logbuffer->next)
1393 safe_send (prof, logbuffer);
1395 process_requests (prof);
1399 assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly, int result)
1401 if (result != MONO_PROFILE_OK)
1404 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1405 int nlen = strlen (name) + 1;
1406 LogBuffer *logbuffer = ensure_logbuf (
1407 EVENT_SIZE /* event */ +
1408 LEB128_SIZE /* time */ +
1409 EVENT_SIZE /* type */ +
1410 LEB128_SIZE /* assembly */ +
1411 LEB128_SIZE /* flags */ +
1414 uint64_t now = current_time ();
1416 ENTER_LOG (logbuffer, "assembly-load");
1417 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1418 emit_time (logbuffer, now);
1419 emit_byte (logbuffer, TYPE_ASSEMBLY);
1420 emit_ptr (logbuffer, assembly);
1421 emit_value (logbuffer, 0); /* flags */
1422 memcpy (logbuffer->cursor, name, nlen);
1423 logbuffer->cursor += nlen;
1424 EXIT_LOG (logbuffer);
1428 if (logbuffer->next)
1429 safe_send (prof, logbuffer);
1431 process_requests (prof);
1435 assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
1437 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1438 int nlen = strlen (name) + 1;
1439 LogBuffer *logbuffer = ensure_logbuf (
1440 EVENT_SIZE /* event */ +
1441 LEB128_SIZE /* time */ +
1442 EVENT_SIZE /* type */ +
1443 LEB128_SIZE /* assembly */ +
1444 LEB128_SIZE /* flags */ +
1447 uint64_t now = current_time ();
1449 ENTER_LOG (logbuffer, "assembly-unload");
1450 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1451 emit_time (logbuffer, now);
1452 emit_byte (logbuffer, TYPE_ASSEMBLY);
1453 emit_ptr (logbuffer, assembly);
1454 emit_value (logbuffer, 0); /* flags */
1455 memcpy (logbuffer->cursor, name, nlen);
1456 logbuffer->cursor += nlen;
1457 EXIT_LOG (logbuffer);
1461 if (logbuffer->next)
1462 safe_send (prof, logbuffer);
1464 process_requests (prof);
1468 class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
1474 LogBuffer *logbuffer;
1475 if (result != MONO_PROFILE_OK)
1477 if (InterlockedRead (&runtime_inited))
1478 name = mono_type_get_name (mono_class_get_type (klass));
1480 name = type_name (klass);
1481 nlen = strlen (name) + 1;
1482 image = mono_class_get_image (klass);
1483 logbuffer = ensure_logbuf (
1484 EVENT_SIZE /* event */ +
1485 LEB128_SIZE /* time */ +
1486 EVENT_SIZE /* type */ +
1487 LEB128_SIZE /* klass */ +
1488 LEB128_SIZE /* image */ +
1489 LEB128_SIZE /* flags */ +
1492 now = current_time ();
1493 ENTER_LOG (logbuffer, "class");
1494 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1495 emit_time (logbuffer, now);
1496 emit_byte (logbuffer, TYPE_CLASS);
1497 emit_ptr (logbuffer, klass);
1498 emit_ptr (logbuffer, image);
1499 emit_value (logbuffer, 0); /* flags */
1500 memcpy (logbuffer->cursor, name, nlen);
1501 logbuffer->cursor += nlen;
1502 //printf ("loaded class %p (%s)\n", klass, name);
1507 EXIT_LOG (logbuffer);
1508 if (logbuffer->next)
1509 safe_send (prof, logbuffer);
1510 process_requests (prof);
1514 class_unloaded (MonoProfiler *prof, MonoClass *klass)
1518 if (InterlockedRead (&runtime_inited))
1519 name = mono_type_get_name (mono_class_get_type (klass));
1521 name = type_name (klass);
1523 int nlen = strlen (name) + 1;
1524 MonoImage *image = mono_class_get_image (klass);
1525 LogBuffer *logbuffer = ensure_logbuf (
1526 EVENT_SIZE /* event */ +
1527 LEB128_SIZE /* time */ +
1528 EVENT_SIZE /* type */ +
1529 LEB128_SIZE /* klass */ +
1530 LEB128_SIZE /* image */ +
1531 LEB128_SIZE /* flags */ +
1534 uint64_t now = current_time ();
1536 ENTER_LOG (logbuffer, "class-unload");
1537 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1538 emit_time (logbuffer, now);
1539 emit_byte (logbuffer, TYPE_CLASS);
1540 emit_ptr (logbuffer, klass);
1541 emit_ptr (logbuffer, image);
1542 emit_value (logbuffer, 0); /* flags */
1543 memcpy (logbuffer->cursor, name, nlen);
1544 logbuffer->cursor += nlen;
1545 EXIT_LOG (logbuffer);
1552 if (logbuffer->next)
1553 safe_send (prof, logbuffer);
1555 process_requests (prof);
1558 #ifndef DISABLE_HELPER_THREAD
1559 static void process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method);
1560 #endif /* DISABLE_HELPER_THREAD */
1563 method_enter (MonoProfiler *prof, MonoMethod *method)
1565 uint64_t now = current_time ();
1567 #ifndef DISABLE_HELPER_THREAD
1568 process_method_enter_coverage (prof, method);
1569 #endif /* DISABLE_HELPER_THREAD */
1571 LogBuffer *logbuffer = ensure_logbuf (
1572 EVENT_SIZE /* event */ +
1573 LEB128_SIZE /* time */ +
1574 LEB128_SIZE /* method */
1576 if (logbuffer->call_depth++ > max_call_depth)
1578 ENTER_LOG (logbuffer, "enter");
1579 emit_byte (logbuffer, TYPE_ENTER | TYPE_METHOD);
1580 emit_time (logbuffer, now);
1581 emit_method (prof, logbuffer, method);
1582 EXIT_LOG (logbuffer);
1584 process_requests (prof);
1588 method_leave (MonoProfiler *prof, MonoMethod *method)
1591 LogBuffer *logbuffer = ensure_logbuf (
1592 EVENT_SIZE /* event */ +
1593 LEB128_SIZE /* time */ +
1594 LEB128_SIZE /* method */
1596 if (--logbuffer->call_depth > max_call_depth)
1598 now = current_time ();
1599 ENTER_LOG (logbuffer, "leave");
1600 emit_byte (logbuffer, TYPE_LEAVE | TYPE_METHOD);
1601 emit_time (logbuffer, now);
1602 emit_method (prof, logbuffer, method);
1603 EXIT_LOG (logbuffer);
1604 if (logbuffer->next)
1605 safe_send (prof, logbuffer);
1606 process_requests (prof);
1610 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
1613 LogBuffer *logbuffer;
1616 logbuffer = ensure_logbuf (
1617 EVENT_SIZE /* event */ +
1618 LEB128_SIZE /* time */ +
1619 LEB128_SIZE /* method */
1621 if (--logbuffer->call_depth > max_call_depth)
1623 now = current_time ();
1624 ENTER_LOG (logbuffer, "eleave");
1625 emit_byte (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
1626 emit_time (logbuffer, now);
1627 emit_method (prof, logbuffer, method);
1628 EXIT_LOG (logbuffer);
1629 process_requests (prof);
1633 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji, int result)
1635 if (result != MONO_PROFILE_OK)
1638 register_method_local (prof, method, ji);
1640 process_requests (prof);
1644 code_buffer_new (MonoProfiler *prof, void *buffer, int size, MonoProfilerCodeBufferType type, void *data)
1649 LogBuffer *logbuffer;
1650 if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
1651 name = (char *)data;
1652 nlen = strlen (name) + 1;
1657 logbuffer = ensure_logbuf (
1658 EVENT_SIZE /* event */ +
1659 LEB128_SIZE /* time */ +
1660 LEB128_SIZE /* type */ +
1661 LEB128_SIZE /* buffer */ +
1662 LEB128_SIZE /* size */ +
1667 now = current_time ();
1668 ENTER_LOG (logbuffer, "code buffer");
1669 emit_byte (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
1670 emit_time (logbuffer, now);
1671 emit_value (logbuffer, type);
1672 emit_ptr (logbuffer, buffer);
1673 emit_value (logbuffer, size);
1675 memcpy (logbuffer->cursor, name, nlen);
1676 logbuffer->cursor += nlen;
1678 EXIT_LOG (logbuffer);
1679 process_requests (prof);
1683 throw_exc (MonoProfiler *prof, MonoObject *object)
1685 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces)? TYPE_EXCEPTION_BT: 0;
1688 LogBuffer *logbuffer;
1691 logbuffer = ensure_logbuf (
1692 EVENT_SIZE /* event */ +
1693 LEB128_SIZE /* time */ +
1694 LEB128_SIZE /* object */ +
1696 LEB128_SIZE /* flags */ +
1697 LEB128_SIZE /* count */ +
1699 LEB128_SIZE /* method */
1703 now = current_time ();
1704 ENTER_LOG (logbuffer, "throw");
1705 emit_byte (logbuffer, do_bt | TYPE_EXCEPTION);
1706 emit_time (logbuffer, now);
1707 emit_obj (logbuffer, object);
1709 emit_bt (prof, logbuffer, &data);
1710 EXIT_LOG (logbuffer);
1711 process_requests (prof);
1715 clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
1718 LogBuffer *logbuffer = ensure_logbuf (
1719 EVENT_SIZE /* event */ +
1720 LEB128_SIZE /* time */ +
1721 LEB128_SIZE /* clause type */ +
1722 LEB128_SIZE /* clause num */ +
1723 LEB128_SIZE /* method */
1725 now = current_time ();
1726 ENTER_LOG (logbuffer, "clause");
1727 emit_byte (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
1728 emit_time (logbuffer, now);
1729 emit_value (logbuffer, clause_type);
1730 emit_value (logbuffer, clause_num);
1731 emit_method (prof, logbuffer, method);
1732 EXIT_LOG (logbuffer);
1734 process_requests (prof);
1738 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
1740 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION)? TYPE_MONITOR_BT: 0;
1743 LogBuffer *logbuffer;
1746 logbuffer = ensure_logbuf (
1747 EVENT_SIZE /* event */ +
1748 LEB128_SIZE /* time */ +
1749 LEB128_SIZE /* object */ +
1751 LEB128_SIZE /* flags */ +
1752 LEB128_SIZE /* count */ +
1754 LEB128_SIZE /* method */
1758 now = current_time ();
1759 ENTER_LOG (logbuffer, "monitor");
1760 emit_byte (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
1761 emit_time (logbuffer, now);
1762 emit_obj (logbuffer, object);
1764 emit_bt (profiler, logbuffer, &data);
1765 EXIT_LOG (logbuffer);
1766 process_requests (profiler);
1770 thread_start (MonoProfiler *prof, uintptr_t tid)
1772 //printf ("thread start %p\n", (void*)tid);
1775 LogBuffer *logbuffer = ensure_logbuf (
1776 EVENT_SIZE /* event */ +
1777 LEB128_SIZE /* time */ +
1778 EVENT_SIZE /* type */ +
1779 LEB128_SIZE /* tid */ +
1780 LEB128_SIZE /* flags */
1782 uint64_t now = current_time ();
1784 ENTER_LOG (logbuffer, "thread-start");
1785 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1786 emit_time (logbuffer, now);
1787 emit_byte (logbuffer, TYPE_THREAD);
1788 emit_ptr (logbuffer, (void*) tid);
1789 emit_value (logbuffer, 0); /* flags */
1790 EXIT_LOG (logbuffer);
1792 if (logbuffer->next)
1793 safe_send (prof, logbuffer);
1795 process_requests (prof);
1799 thread_end (MonoProfiler *prof, uintptr_t tid)
1801 if (TLS_GET (LogBuffer, tlsbuffer)) {
1802 LogBuffer *logbuffer = ensure_logbuf (
1803 EVENT_SIZE /* event */ +
1804 LEB128_SIZE /* time */ +
1805 EVENT_SIZE /* type */ +
1806 LEB128_SIZE /* tid */ +
1807 LEB128_SIZE /* flags */
1809 uint64_t now = current_time ();
1811 ENTER_LOG (logbuffer, "thread-end");
1812 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1813 emit_time (logbuffer, now);
1814 emit_byte (logbuffer, TYPE_THREAD);
1815 emit_ptr (logbuffer, (void*) tid);
1816 emit_value (logbuffer, 0); /* flags */
1817 EXIT_LOG (logbuffer);
1819 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), logbuffer);
1821 /* Don't process requests as the thread is detached from the runtime. */
1824 TLS_SET (tlsbuffer, NULL);
1825 TLS_SET (tlsmethodlist, NULL);
1829 domain_loaded (MonoProfiler *prof, MonoDomain *domain, int result)
1831 if (result != MONO_PROFILE_OK)
1834 LogBuffer *logbuffer = ensure_logbuf (
1835 EVENT_SIZE /* event */ +
1836 LEB128_SIZE /* time */ +
1837 EVENT_SIZE /* type */ +
1838 LEB128_SIZE /* domain id */ +
1839 LEB128_SIZE /* flags */
1841 uint64_t now = current_time ();
1843 ENTER_LOG (logbuffer, "domain-start");
1844 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1845 emit_time (logbuffer, now);
1846 emit_byte (logbuffer, TYPE_DOMAIN);
1847 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1848 emit_value (logbuffer, 0); /* flags */
1849 EXIT_LOG (logbuffer);
1851 if (logbuffer->next)
1852 safe_send (prof, logbuffer);
1854 process_requests (prof);
1858 domain_unloaded (MonoProfiler *prof, MonoDomain *domain)
1860 LogBuffer *logbuffer = ensure_logbuf (
1861 EVENT_SIZE /* event */ +
1862 LEB128_SIZE /* time */ +
1863 EVENT_SIZE /* type */ +
1864 LEB128_SIZE /* domain id */ +
1865 LEB128_SIZE /* flags */
1867 uint64_t now = current_time ();
1869 ENTER_LOG (logbuffer, "domain-end");
1870 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1871 emit_time (logbuffer, now);
1872 emit_byte (logbuffer, TYPE_DOMAIN);
1873 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1874 emit_value (logbuffer, 0); /* flags */
1875 EXIT_LOG (logbuffer);
1877 if (logbuffer->next)
1878 safe_send (prof, logbuffer);
1880 process_requests (prof);
1884 domain_name (MonoProfiler *prof, MonoDomain *domain, const char *name)
1886 int nlen = strlen (name) + 1;
1887 LogBuffer *logbuffer = ensure_logbuf (
1888 EVENT_SIZE /* event */ +
1889 LEB128_SIZE /* time */ +
1890 EVENT_SIZE /* type */ +
1891 LEB128_SIZE /* domain id */ +
1892 LEB128_SIZE /* flags */ +
1895 uint64_t now = current_time ();
1897 ENTER_LOG (logbuffer, "domain-name");
1898 emit_byte (logbuffer, TYPE_METADATA);
1899 emit_time (logbuffer, now);
1900 emit_byte (logbuffer, TYPE_DOMAIN);
1901 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1902 emit_value (logbuffer, 0); /* flags */
1903 memcpy (logbuffer->cursor, name, nlen);
1904 logbuffer->cursor += nlen;
1905 EXIT_LOG (logbuffer);
1907 if (logbuffer->next)
1908 safe_send (prof, logbuffer);
1910 process_requests (prof);
1914 context_loaded (MonoProfiler *prof, MonoAppContext *context)
1916 LogBuffer *logbuffer = ensure_logbuf (
1917 EVENT_SIZE /* event */ +
1918 LEB128_SIZE /* time */ +
1919 EVENT_SIZE /* type */ +
1920 LEB128_SIZE /* context id */ +
1921 LEB128_SIZE /* flags */ +
1922 LEB128_SIZE /* domain id */
1924 uint64_t now = current_time ();
1926 ENTER_LOG (logbuffer, "context-start");
1927 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1928 emit_time (logbuffer, now);
1929 emit_byte (logbuffer, TYPE_CONTEXT);
1930 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
1931 emit_value (logbuffer, 0); /* flags */
1932 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
1933 EXIT_LOG (logbuffer);
1935 if (logbuffer->next)
1936 safe_send (prof, logbuffer);
1938 process_requests (prof);
1942 context_unloaded (MonoProfiler *prof, MonoAppContext *context)
1944 LogBuffer *logbuffer = ensure_logbuf (
1945 EVENT_SIZE /* event */ +
1946 LEB128_SIZE /* time */ +
1947 EVENT_SIZE /* type */ +
1948 LEB128_SIZE /* context id */ +
1949 LEB128_SIZE /* flags */ +
1950 LEB128_SIZE /* domain id */
1952 uint64_t now = current_time ();
1954 ENTER_LOG (logbuffer, "context-end");
1955 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1956 emit_time (logbuffer, now);
1957 emit_byte (logbuffer, TYPE_CONTEXT);
1958 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
1959 emit_value (logbuffer, 0); /* flags */
1960 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
1961 EXIT_LOG (logbuffer);
1963 if (logbuffer->next)
1964 safe_send (prof, logbuffer);
1966 process_requests (prof);
1970 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
1972 int len = strlen (name) + 1;
1974 LogBuffer *logbuffer;
1975 logbuffer = ensure_logbuf (
1976 EVENT_SIZE /* event */ +
1977 LEB128_SIZE /* time */ +
1978 EVENT_SIZE /* type */ +
1979 LEB128_SIZE /* tid */ +
1980 LEB128_SIZE /* flags */ +
1983 now = current_time ();
1984 ENTER_LOG (logbuffer, "tname");
1985 emit_byte (logbuffer, TYPE_METADATA);
1986 emit_time (logbuffer, now);
1987 emit_byte (logbuffer, TYPE_THREAD);
1988 emit_ptr (logbuffer, (void*)tid);
1989 emit_value (logbuffer, 0); /* flags */
1990 memcpy (logbuffer->cursor, name, len);
1991 logbuffer->cursor += len;
1992 EXIT_LOG (logbuffer);
1994 if (logbuffer->next)
1995 safe_send (prof, logbuffer);
1997 process_requests (prof);
2009 AsyncFrameInfo *data;
2013 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
2015 AsyncFrameData *frame = (AsyncFrameData *)data;
2016 if (frame->count < num_frames) {
2017 frame->data [frame->count].method = method;
2018 frame->data [frame->count].domain = domain;
2019 frame->data [frame->count].base_address = base_address;
2020 frame->data [frame->count].offset = offset;
2021 // printf ("In %d at %p (dom %p) (native: %p)\n", frame->count, method, domain, base_address);
2024 return frame->count == num_frames;
2028 (type | frame count), tid, time, ip, [method, domain, base address, offset] * frames
2030 #define SAMPLE_EVENT_SIZE_IN_SLOTS(FRAMES) (4 + (FRAMES) * 4)
2033 mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
2036 AsyncFrameInfo frames [num_frames];
2037 AsyncFrameData bt_data = { 0, &frames [0]};
2039 uintptr_t *data, *new_data, *old_data;
2045 now = current_time ();
2047 mono_stack_walk_async_safe (&async_walk_stack, context, &bt_data);
2049 elapsed = (now - profiler->startup_time) / 10000;
2053 snprintf (buf, sizeof (buf), "hit at %p in thread %p after %llu ms\n", ip, (void*)thread_id (), (unsigned long long int)elapsed/100);
2055 ign_res (write (2, buf, len));
2057 sbuf = profiler->stat_buffers;
2060 /* flush the buffer at 1 second intervals */
2061 if (sbuf->cursor > sbuf->buf && (elapsed - sbuf->buf [2]) > 100000) {
2064 /* overflow: 400 slots is a big enough number to reduce the chance of losing this event if many
2065 * threads hit this same spot at the same time
2067 if (timedout || (sbuf->cursor + 400 >= sbuf->buf_end)) {
2068 StatBuffer *oldsb, *foundsb;
2069 sbuf = create_stat_buffer ();
2071 oldsb = profiler->stat_buffers;
2073 foundsb = (StatBuffer *)InterlockedCompareExchangePointer ((void * volatile*)&profiler->stat_buffers, sbuf, oldsb);
2074 } while (foundsb != oldsb);
2076 ign_res (write (2, "overflow\n", 9));
2077 /* notify the helper thread */
2078 if (sbuf->next->next) {
2080 ign_res (write (profiler->pipes [1], &c, 1));
2082 ign_res (write (2, "notify\n", 7));
2086 old_data = sbuf->cursor;
2087 new_data = old_data + SAMPLE_EVENT_SIZE_IN_SLOTS (bt_data.count);
2088 if (new_data > sbuf->buf_end)
2089 return; /* Not enough room in buf to hold this event-- lost event */
2090 data = (uintptr_t *)InterlockedCompareExchangePointer ((void * volatile*)&sbuf->cursor, new_data, old_data);
2091 } while (data != old_data);
2093 old_data [0] = 1 | (sample_type << 16) | (bt_data.count << 8);
2094 old_data [1] = thread_id ();
2095 old_data [2] = elapsed;
2096 old_data [3] = (uintptr_t)ip;
2097 for (i = 0; i < bt_data.count; ++i) {
2098 old_data [4 + 4 * i + 0] = (uintptr_t)frames [i].method;
2099 old_data [4 + 4 * i + 1] = (uintptr_t)frames [i].domain;
2100 old_data [4 + 4 * i + 2] = (uintptr_t)frames [i].base_address;
2101 old_data [4 + 4 * i + 3] = (uintptr_t)frames [i].offset;
2105 static uintptr_t *code_pages = 0;
2106 static int num_code_pages = 0;
2107 static int size_code_pages = 0;
2108 #define CPAGE_SHIFT (9)
2109 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
2110 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
2111 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
2114 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
2117 uintptr_t start_pos;
2118 start_pos = (page >> CPAGE_SHIFT) % hsize;
2121 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
2123 } else if (!hash [i]) {
2130 } while (i != start_pos);
2131 /* should not happen */
2132 printf ("failed code page store\n");
2137 add_code_pointer (uintptr_t ip)
2140 if (num_code_pages * 2 >= size_code_pages) {
2142 uintptr_t old_size = size_code_pages;
2143 size_code_pages *= 2;
2144 if (size_code_pages == 0)
2145 size_code_pages = 16;
2146 n = (uintptr_t *)calloc (sizeof (uintptr_t) * size_code_pages, 1);
2147 for (i = 0; i < old_size; ++i) {
2149 add_code_page (n, size_code_pages, code_pages [i]);
2155 num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
2158 /* ELF code crashes on some systems. */
2159 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2162 dump_ubin (const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
2165 LogBuffer *logbuffer;
2167 len = strlen (filename) + 1;
2168 now = current_time ();
2169 logbuffer = ensure_logbuf (
2170 EVENT_SIZE /* event */ +
2171 LEB128_SIZE /* time */ +
2172 LEB128_SIZE /* load address */ +
2173 LEB128_SIZE /* offset */ +
2174 LEB128_SIZE /* size */ +
2175 nlen /* file name */
2177 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
2178 emit_time (logbuffer, now);
2179 emit_svalue (logbuffer, load_addr);
2180 emit_uvalue (logbuffer, offset);
2181 emit_uvalue (logbuffer, size);
2182 memcpy (logbuffer->cursor, filename, len);
2183 logbuffer->cursor += len;
2188 dump_usym (const char *name, uintptr_t value, uintptr_t size)
2190 LogBuffer *logbuffer;
2192 len = strlen (name) + 1;
2193 logbuffer = ensure_logbuf (
2194 EVENT_SIZE /* event */ +
2195 LEB128_SIZE /* value */ +
2196 LEB128_SIZE /* size */ +
2199 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
2200 emit_ptr (logbuffer, (void*)value);
2201 emit_value (logbuffer, size);
2202 memcpy (logbuffer->cursor, name, len);
2203 logbuffer->cursor += len;
2206 /* ELF code crashes on some systems. */
2207 //#if defined(ELFMAG0)
2210 #if SIZEOF_VOID_P == 4
2211 #define ELF_WSIZE 32
2213 #define ELF_WSIZE 64
2216 #define ElfW(type) _ElfW (Elf, ELF_WSIZE, type)
2217 #define _ElfW(e,w,t) _ElfW_1 (e, w, _##t)
2218 #define _ElfW_1(e,w,t) e##w##t
2222 dump_elf_symbols (ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
2225 for (i = 0; i < num_symbols; ++i) {
2227 sym = strtab + symbols [i].st_name;
2228 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
2230 //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
2231 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
2236 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
2243 ElfW(Shdr) *sheader;
2244 ElfW(Shdr) *shstrtabh;
2245 ElfW(Shdr) *symtabh = NULL;
2246 ElfW(Shdr) *strtabh = NULL;
2247 ElfW(Sym) *symbols = NULL;
2251 fd = open (filename, O_RDONLY);
2254 if (fstat (fd, &statb) != 0) {
2258 file_size = statb.st_size;
2259 data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
2261 if (data == MAP_FAILED)
2264 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2265 header->e_ident [EI_MAG1] != ELFMAG1 ||
2266 header->e_ident [EI_MAG2] != ELFMAG2 ||
2267 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2268 munmap (data, file_size);
2271 sheader = (void*)((char*)data + header->e_shoff);
2272 shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
2273 strtab = (const char*)data + shstrtabh->sh_offset;
2274 for (i = 0; i < header->e_shnum; ++i) {
2275 //printf ("section header: %d\n", sheader->sh_type);
2276 if (sheader->sh_type == SHT_SYMTAB) {
2278 strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
2279 /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
2282 sheader = (void*)((char*)sheader + header->e_shentsize);
2284 if (!symtabh || !strtabh) {
2285 munmap (data, file_size);
2288 strtab = (const char*)data + strtabh->sh_offset;
2289 num_symbols = symtabh->sh_size / symtabh->sh_entsize;
2290 symbols = (void*)((char*)data + symtabh->sh_offset);
2291 dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
2292 munmap (data, file_size);
2297 /* ELF code crashes on some systems. */
2298 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2301 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
2303 MonoProfiler *prof = data;
2305 const char *filename;
2307 char *a = (void*)info->dlpi_addr;
2309 ElfW(Dyn) *dyn = NULL;
2310 ElfW(Sym) *symtab = NULL;
2311 ElfW(Word) *hash_table = NULL;
2312 ElfW(Ehdr) *header = NULL;
2313 const char* strtab = NULL;
2314 for (obj = prof->binary_objects; obj; obj = obj->next) {
2318 filename = info->dlpi_name;
2321 if (!info->dlpi_addr && !filename [0]) {
2322 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
2328 obj = calloc (sizeof (BinaryObject), 1);
2329 obj->addr = (void*)info->dlpi_addr;
2330 obj->name = pstrdup (filename);
2331 obj->next = prof->binary_objects;
2332 prof->binary_objects = obj;
2333 //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
2335 for (i = 0; i < info->dlpi_phnum; ++i) {
2336 //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);
2337 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
2338 header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2339 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2340 header->e_ident [EI_MAG1] != ELFMAG1 ||
2341 header->e_ident [EI_MAG2] != ELFMAG2 ||
2342 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2345 dump_ubin (filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
2346 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
2347 dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2350 if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
2352 if (!info->dlpi_name || !info->dlpi_name[0])
2356 for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
2357 if (dyn [i].d_tag == DT_SYMTAB) {
2358 if (symtab && do_debug)
2359 printf ("multiple symtabs: %d\n", i);
2360 symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
2361 } else if (dyn [i].d_tag == DT_HASH) {
2362 hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
2363 } else if (dyn [i].d_tag == DT_STRTAB) {
2364 strtab = (const char*)(a + dyn [i].d_un.d_ptr);
2369 num_sym = hash_table [1];
2370 dump_elf_symbols (symtab, num_sym, strtab, (void*)info->dlpi_addr);
2375 load_binaries (MonoProfiler *prof)
2377 dl_iterate_phdr (elf_dl_callback, prof);
2382 load_binaries (MonoProfiler *prof)
2389 symbol_for (uintptr_t code)
2392 void *ip = (void*)code;
2394 if (dladdr (ip, &di)) {
2396 return di.dli_sname;
2399 names = backtrace_symbols (&ip, 1);
2401 const char* p = names [0];
2412 dump_unmanaged_coderefs (MonoProfiler *prof)
2415 const char* last_symbol;
2416 uintptr_t addr, page_end;
2418 if (load_binaries (prof))
2420 for (i = 0; i < size_code_pages; ++i) {
2422 if (!code_pages [i] || code_pages [i] & 1)
2425 addr = CPAGE_ADDR (code_pages [i]);
2426 page_end = addr + CPAGE_SIZE;
2427 code_pages [i] |= 1;
2428 /* we dump the symbols for the whole page */
2429 for (; addr < page_end; addr += 16) {
2430 sym = symbol_for (addr);
2431 if (sym && sym == last_symbol)
2436 dump_usym (sym, addr, 0); /* let's not guess the size */
2437 //printf ("found symbol at %p: %s\n", (void*)addr, sym);
2443 compare_sample_events (gconstpointer a, gconstpointer b)
2445 uintptr_t tid1 = (*(uintptr_t **) a) [1];
2446 uintptr_t tid2 = (*(uintptr_t **) b) [1];
2448 return tid1 > tid2 ? 1 :
2454 dump_sample_hits (MonoProfiler *prof, StatBuffer *sbuf)
2456 LogBuffer *logbuffer;
2460 dump_sample_hits (prof, sbuf->next);
2461 free_buffer (sbuf->next, sbuf->next->size);
2465 g_ptr_array_set_size (prof->sorted_sample_events, 0);
2467 for (uintptr_t *sample = sbuf->buf; sample < sbuf->cursor;) {
2468 int count = sample [0] & 0xff;
2469 int mbt_count = (sample [0] & 0xff00) >> 8;
2471 if (sample + SAMPLE_EVENT_SIZE_IN_SLOTS (mbt_count) > sbuf->cursor)
2474 g_ptr_array_add (prof->sorted_sample_events, sample);
2476 sample += count + 3 + 4 * mbt_count;
2479 g_ptr_array_sort (prof->sorted_sample_events, compare_sample_events);
2481 for (guint sidx = 0; sidx < prof->sorted_sample_events->len; sidx++) {
2482 uintptr_t *sample = (uintptr_t *)g_ptr_array_index (prof->sorted_sample_events, sidx);
2483 int count = sample [0] & 0xff;
2484 int mbt_count = (sample [0] & 0xff00) >> 8;
2485 int type = sample [0] >> 16;
2486 uintptr_t *managed_sample_base = sample + count + 3;
2487 uintptr_t thread_id = sample [1];
2489 for (int i = 0; i < mbt_count; ++i) {
2490 MonoMethod *method = (MonoMethod*)managed_sample_base [i * 4 + 0];
2491 MonoDomain *domain = (MonoDomain*)managed_sample_base [i * 4 + 1];
2492 void *address = (void*)managed_sample_base [i * 4 + 2];
2496 MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *)address);
2499 managed_sample_base [i * 4 + 0] = (uintptr_t)mono_jit_info_get_method (ji);
2503 logbuffer = ensure_logbuf (
2504 EVENT_SIZE /* event */ +
2505 LEB128_SIZE /* type */ +
2506 LEB128_SIZE /* time */ +
2507 LEB128_SIZE /* tid */ +
2508 LEB128_SIZE /* count */ +
2510 LEB128_SIZE /* ip */
2512 LEB128_SIZE /* managed count */ +
2514 LEB128_SIZE /* method */ +
2515 LEB128_SIZE /* il offset */ +
2516 LEB128_SIZE /* native offset */
2519 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
2520 emit_value (logbuffer, type);
2521 emit_uvalue (logbuffer, prof->startup_time + (uint64_t)sample [2] * (uint64_t)10000);
2522 emit_ptr (logbuffer, (void *) thread_id);
2523 emit_value (logbuffer, count);
2524 for (int i = 0; i < count; ++i) {
2525 emit_ptr (logbuffer, (void*)sample [i + 3]);
2526 add_code_pointer (sample [i + 3]);
2529 sample += count + 3;
2530 /* new in data version 6 */
2531 emit_uvalue (logbuffer, mbt_count);
2532 for (int i = 0; i < mbt_count; ++i) {
2533 MonoMethod *method = (MonoMethod *) sample [i * 4 + 0];
2534 uintptr_t native_offset = sample [i * 4 + 3];
2536 emit_method (prof, logbuffer, method);
2537 emit_svalue (logbuffer, 0); /* il offset will always be 0 from now on */
2538 emit_svalue (logbuffer, native_offset);
2542 dump_unmanaged_coderefs (prof);
2548 mono_cpu_count (void)
2550 #ifdef PLATFORM_ANDROID
2551 /* Android tries really hard to save power by powering off CPUs on SMP phones which
2552 * means the normal way to query cpu count returns a wrong value with userspace API.
2553 * Instead we use /sys entries to query the actual hardware CPU count.
2556 char buffer[8] = {'\0'};
2557 int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
2558 /* Format of the /sys entry is a cpulist of indexes which in the case
2559 * of present is always of the form "0-(n-1)" when there is more than
2560 * 1 core, n being the number of CPU cores in the system. Otherwise
2561 * the value is simply 0
2563 if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
2564 count = strtol (((char*)buffer) + 2, NULL, 10);
2571 #if defined(HOST_ARM) || defined (HOST_ARM64)
2573 /* ARM platforms tries really hard to save power by powering off CPUs on SMP phones which
2574 * means the normal way to query cpu count returns a wrong value with userspace API. */
2576 #ifdef _SC_NPROCESSORS_CONF
2578 int count = sysconf (_SC_NPROCESSORS_CONF);
2586 #ifdef HAVE_SCHED_GETAFFINITY
2589 if (sched_getaffinity (getpid (), sizeof (set), &set) == 0)
2590 return CPU_COUNT (&set);
2593 #ifdef _SC_NPROCESSORS_ONLN
2595 int count = sysconf (_SC_NPROCESSORS_ONLN);
2601 #endif /* defined(HOST_ARM) || defined (HOST_ARM64) */
2607 size_t len = sizeof (int);
2610 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
2617 GetSystemInfo (&info);
2618 return info.dwNumberOfProcessors;
2627 unsigned int prev_pos;
2629 struct perf_event_mmap_page *page_desc;
2632 static PerfData *perf_data = NULL;
2633 static int num_perf;
2634 #define PERF_PAGES_SHIFT 4
2635 static int num_pages = 1 << PERF_PAGES_SHIFT;
2636 static unsigned int mmap_mask;
2639 struct perf_event_header h;
2649 perf_event_syscall (struct perf_event_attr *attr, pid_t pid, int cpu, int group_fd, unsigned long flags)
2651 attr->size = PERF_ATTR_SIZE_VER0;
2652 //printf ("perf attr size: %d\n", attr->size);
2653 #if defined(__x86_64__)
2654 return syscall(/*__NR_perf_event_open*/ 298, attr, pid, cpu, group_fd, flags);
2655 #elif defined(__i386__)
2656 return syscall(/*__NR_perf_event_open*/ 336, attr, pid, cpu, group_fd, flags);
2657 #elif defined(__arm__) || defined (__aarch64__)
2658 return syscall(/*__NR_perf_event_open*/ 364, attr, pid, cpu, group_fd, flags);
2665 setup_perf_map (PerfData *perf)
2667 perf->mmap_base = mmap (NULL, (num_pages + 1) * getpagesize (), PROT_READ|PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
2668 if (perf->mmap_base == MAP_FAILED) {
2670 printf ("failed mmap\n");
2673 perf->page_desc = perf->mmap_base;
2675 printf ("mmap version: %d\n", perf->page_desc->version);
2680 dump_perf_hits (MonoProfiler *prof, void *buf, int size)
2682 LogBuffer *logbuffer;
2685 void *end = (char*)buf + size;
2687 int pid = getpid ();
2693 if (pid != s->pid) {
2695 printf ("event for different pid: %d\n", s->pid);
2696 buf = (char*)buf + s->h.size;
2699 /*ip = (void*)s->ip;
2700 printf ("sample: %d, size: %d, ip: %p (%s), timestamp: %llu, nframes: %llu\n",
2701 s->h.type, s->h.size, ip, symbol_for (ip), s->timestamp, s->nframes);*/
2702 logbuffer = ensure_logbuf (
2703 EVENT_SIZE /* event */ +
2704 LEB128_SIZE /* type */ +
2705 LEB128_SIZE /* time */ +
2706 LEB128_SIZE /* tid */ +
2707 LEB128_SIZE /* count */ +
2709 LEB128_SIZE /* ip */
2711 LEB128_SIZE /* managed count */ +
2713 LEB128_SIZE /* method */ +
2714 LEB128_SIZE /* il offset */ +
2715 LEB128_SIZE /* native offset */
2718 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
2719 emit_value (logbuffer, sample_type);
2720 emit_uvalue (logbuffer, s->timestamp - prof->startup_time);
2722 * No useful thread ID to write here, since throughout the
2723 * profiler we use pthread_self () but the ID we get from
2724 * perf is the kernel's thread ID.
2726 emit_ptr (logbuffer, 0);
2727 emit_value (logbuffer, count);
2728 emit_ptr (logbuffer, (void*)(uintptr_t)s->ip);
2729 add_code_pointer (s->ip);
2730 /* no support here yet for the managed backtrace */
2731 emit_uvalue (logbuffer, mbt_count);
2732 buf = (char*)buf + s->h.size;
2736 printf ("dumped %d samples\n", samples);
2737 dump_unmanaged_coderefs (prof);
2740 /* read events from the ring buffer */
2742 read_perf_mmap (MonoProfiler* prof, int cpu)
2744 PerfData *perf = perf_data + cpu;
2746 unsigned char *data = (unsigned char*)perf->mmap_base + getpagesize ();
2747 unsigned int head = perf->page_desc->data_head;
2751 mono_memory_read_barrier ();
2753 old = perf->prev_pos;
2757 printf ("lost mmap events: old: %d, head: %d\n", old, head);
2761 if ((old & mmap_mask) + size != (head & mmap_mask)) {
2762 buf = data + (old & mmap_mask);
2763 size = mmap_mask + 1 - (old & mmap_mask);
2765 /* size bytes at buf */
2767 printf ("found1 bytes of events: %d\n", size);
2768 dump_perf_hits (prof, buf, size);
2770 buf = data + (old & mmap_mask);
2772 /* size bytes at buf */
2774 printf ("found bytes of events: %d\n", size);
2775 dump_perf_hits (prof, buf, size);
2777 perf->prev_pos = old;
2778 perf->page_desc->data_tail = old;
2783 setup_perf_event_for_cpu (PerfData *perf, int cpu)
2785 struct perf_event_attr attr;
2786 memset (&attr, 0, sizeof (attr));
2787 attr.type = PERF_TYPE_HARDWARE;
2788 switch (sample_type) {
2789 case SAMPLE_CYCLES: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2790 case SAMPLE_INSTRUCTIONS: attr.config = PERF_COUNT_HW_INSTRUCTIONS; break;
2791 case SAMPLE_CACHE_MISSES: attr.config = PERF_COUNT_HW_CACHE_MISSES; break;
2792 case SAMPLE_CACHE_REFS: attr.config = PERF_COUNT_HW_CACHE_REFERENCES; break;
2793 case SAMPLE_BRANCHES: attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS; break;
2794 case SAMPLE_BRANCH_MISSES: attr.config = PERF_COUNT_HW_BRANCH_MISSES; break;
2795 default: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2797 attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD | PERF_SAMPLE_TIME;
2798 // attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
2799 attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING | PERF_FORMAT_ID;
2802 attr.sample_freq = sample_freq;
2804 perf->perf_fd = perf_event_syscall (&attr, getpid (), cpu, -1, 0);
2806 printf ("perf fd: %d, freq: %d, event: %llu\n", perf->perf_fd, sample_freq, attr.config);
2807 if (perf->perf_fd < 0) {
2808 if (perf->perf_fd == -EPERM) {
2809 fprintf (stderr, "Perf syscall denied, do \"echo 1 > /proc/sys/kernel/perf_event_paranoid\" as root to enable.\n");
2812 perror ("open perf event");
2816 if (!setup_perf_map (perf)) {
2817 close (perf->perf_fd);
2825 setup_perf_event (void)
2828 mmap_mask = num_pages * getpagesize () - 1;
2829 num_perf = mono_cpu_count ();
2830 perf_data = calloc (num_perf, sizeof (PerfData));
2831 for (i = 0; i < num_perf; ++i) {
2832 count += setup_perf_event_for_cpu (perf_data + i, i);
2841 #endif /* USE_PERF_EVENTS */
2843 #ifndef DISABLE_HELPER_THREAD
2845 typedef struct MonoCounterAgent {
2846 MonoCounter *counter;
2847 // MonoCounterAgent specific data :
2852 struct MonoCounterAgent *next;
2855 static MonoCounterAgent* counters;
2856 static gboolean counters_initialized = FALSE;
2857 static int counters_index = 1;
2858 static mono_mutex_t counters_mutex;
2861 counters_add_agent (MonoCounter *counter)
2863 MonoCounterAgent *agent, *item;
2865 if (!counters_initialized)
2868 mono_os_mutex_lock (&counters_mutex);
2870 for (agent = counters; agent; agent = agent->next) {
2871 if (agent->counter == counter) {
2872 agent->value_size = 0;
2874 free (agent->value);
2875 agent->value = NULL;
2877 mono_os_mutex_unlock (&counters_mutex);
2882 agent = (MonoCounterAgent *)malloc (sizeof (MonoCounterAgent));
2883 agent->counter = counter;
2884 agent->value = NULL;
2885 agent->value_size = 0;
2886 agent->index = counters_index++;
2899 mono_os_mutex_unlock (&counters_mutex);
2903 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
2905 counters_add_agent (counter);
2910 counters_init (MonoProfiler *profiler)
2912 assert (!counters_initialized);
2914 mono_os_mutex_init (&counters_mutex);
2916 counters_initialized = TRUE;
2918 mono_counters_on_register (&counters_add_agent);
2919 mono_counters_foreach (counters_init_foreach_callback, NULL);
2923 counters_emit (MonoProfiler *profiler, gboolean threadless)
2925 MonoCounterAgent *agent;
2926 LogBuffer *logbuffer;
2929 EVENT_SIZE /* event */ +
2930 LEB128_SIZE /* len */
2933 if (!counters_initialized)
2936 mono_os_mutex_lock (&counters_mutex);
2938 for (agent = counters; agent; agent = agent->next) {
2943 LEB128_SIZE /* section */ +
2944 strlen (mono_counter_get_name (agent->counter)) + 1 /* name */ +
2945 LEB128_SIZE /* type */ +
2946 LEB128_SIZE /* unit */ +
2947 LEB128_SIZE /* variance */ +
2948 LEB128_SIZE /* index */
2955 mono_os_mutex_unlock (&counters_mutex);
2959 logbuffer = ensure_logbuf (size);
2961 ENTER_LOG (logbuffer, "counters");
2962 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2963 emit_value (logbuffer, len);
2964 for (agent = counters; agent; agent = agent->next) {
2970 name = mono_counter_get_name (agent->counter);
2971 emit_value (logbuffer, mono_counter_get_section (agent->counter));
2972 emit_string (logbuffer, name, strlen (name) + 1);
2973 emit_value (logbuffer, mono_counter_get_type (agent->counter));
2974 emit_value (logbuffer, mono_counter_get_unit (agent->counter));
2975 emit_value (logbuffer, mono_counter_get_variance (agent->counter));
2976 emit_value (logbuffer, agent->index);
2980 EXIT_LOG (logbuffer);
2983 safe_send_threadless (profiler, logbuffer);
2985 safe_send (profiler, logbuffer);
2987 mono_os_mutex_unlock (&counters_mutex);
2991 counters_sample (MonoProfiler *profiler, uint64_t timestamp, gboolean threadless)
2993 MonoCounterAgent *agent;
2994 MonoCounter *counter;
2995 LogBuffer *logbuffer;
3001 if (!counters_initialized)
3004 counters_emit (profiler, threadless);
3007 buffer = calloc (1, buffer_size);
3009 mono_os_mutex_lock (&counters_mutex);
3012 EVENT_SIZE /* event */ +
3013 LEB128_SIZE /* time */
3016 for (agent = counters; agent; agent = agent->next) {
3018 LEB128_SIZE /* index */ +
3019 LEB128_SIZE /* type */ +
3020 mono_counter_get_size (agent->counter) /* value */
3025 LEB128_SIZE /* stop marker */
3028 logbuffer = ensure_logbuf (size);
3030 ENTER_LOG (logbuffer, "counters");
3031 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
3032 emit_uvalue (logbuffer, timestamp);
3033 for (agent = counters; agent; agent = agent->next) {
3036 counter = agent->counter;
3038 size = mono_counter_get_size (counter);
3040 continue; // FIXME error
3041 } else if (size > buffer_size) {
3043 buffer = realloc (buffer, buffer_size);
3046 memset (buffer, 0, buffer_size);
3048 if (mono_counters_sample (counter, buffer, size) < 0)
3049 continue; // FIXME error
3051 type = mono_counter_get_type (counter);
3053 if (!agent->value) {
3054 agent->value = calloc (1, size);
3055 agent->value_size = size;
3057 if (type == MONO_COUNTER_STRING) {
3058 if (strcmp (agent->value, buffer) == 0)
3061 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
3066 emit_uvalue (logbuffer, agent->index);
3067 emit_uvalue (logbuffer, type);
3069 case MONO_COUNTER_INT:
3070 #if SIZEOF_VOID_P == 4
3071 case MONO_COUNTER_WORD:
3073 emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
3075 case MONO_COUNTER_UINT:
3076 emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
3078 case MONO_COUNTER_TIME_INTERVAL:
3079 case MONO_COUNTER_LONG:
3080 #if SIZEOF_VOID_P == 8
3081 case MONO_COUNTER_WORD:
3083 emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
3085 case MONO_COUNTER_ULONG:
3086 emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
3088 case MONO_COUNTER_DOUBLE:
3089 emit_double (logbuffer, *(double*)buffer);
3091 case MONO_COUNTER_STRING:
3093 emit_byte (logbuffer, 0);
3095 emit_byte (logbuffer, 1);
3096 emit_string (logbuffer, (char*)buffer, size);
3103 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
3104 agent->value = realloc (agent->value, size);
3105 agent->value_size = size;
3109 memcpy (agent->value, buffer, size);
3113 emit_value (logbuffer, 0);
3114 EXIT_LOG (logbuffer);
3117 safe_send_threadless (profiler, logbuffer);
3119 safe_send (profiler, logbuffer);
3121 mono_os_mutex_unlock (&counters_mutex);
3124 typedef struct _PerfCounterAgent PerfCounterAgent;
3125 struct _PerfCounterAgent {
3126 PerfCounterAgent *next;
3128 char *category_name;
3137 static PerfCounterAgent *perfcounters = NULL;
3140 perfcounters_emit (MonoProfiler *profiler, gboolean threadless)
3142 PerfCounterAgent *pcagent;
3143 LogBuffer *logbuffer;
3146 EVENT_SIZE /* event */ +
3147 LEB128_SIZE /* len */
3150 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3151 if (pcagent->emitted)
3155 LEB128_SIZE /* section */ +
3156 strlen (pcagent->category_name) + 1 /* category name */ +
3157 strlen (pcagent->name) + 1 /* name */ +
3158 LEB128_SIZE /* type */ +
3159 LEB128_SIZE /* unit */ +
3160 LEB128_SIZE /* variance */ +
3161 LEB128_SIZE /* index */
3170 logbuffer = ensure_logbuf (size);
3172 ENTER_LOG (logbuffer, "perfcounters");
3173 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
3174 emit_value (logbuffer, len);
3175 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3176 if (pcagent->emitted)
3179 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
3180 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
3181 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
3182 emit_value (logbuffer, MONO_COUNTER_LONG);
3183 emit_value (logbuffer, MONO_COUNTER_RAW);
3184 emit_value (logbuffer, MONO_COUNTER_VARIABLE);
3185 emit_value (logbuffer, pcagent->index);
3187 pcagent->emitted = 1;
3189 EXIT_LOG (logbuffer);
3192 safe_send_threadless (profiler, logbuffer);
3194 safe_send (profiler, logbuffer);
3198 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
3200 PerfCounterAgent *pcagent;
3202 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3203 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
3205 if (pcagent->value == value)
3208 pcagent->value = value;
3209 pcagent->updated = 1;
3210 pcagent->deleted = 0;
3214 pcagent = g_new0 (PerfCounterAgent, 1);
3215 pcagent->next = perfcounters;
3216 pcagent->index = counters_index++;
3217 pcagent->category_name = g_strdup (category_name);
3218 pcagent->name = g_strdup (name);
3219 pcagent->type = (int) type;
3220 pcagent->value = value;
3221 pcagent->emitted = 0;
3222 pcagent->updated = 1;
3223 pcagent->deleted = 0;
3225 perfcounters = pcagent;
3231 perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp, gboolean threadless)
3233 PerfCounterAgent *pcagent;
3234 LogBuffer *logbuffer;
3237 if (!counters_initialized)
3240 mono_os_mutex_lock (&counters_mutex);
3242 /* mark all perfcounters as deleted, foreach will unmark them as necessary */
3243 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
3244 pcagent->deleted = 1;
3246 mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
3248 perfcounters_emit (profiler, threadless);
3251 EVENT_SIZE /* event */ +
3252 LEB128_SIZE /* time */
3255 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3256 if (pcagent->deleted || !pcagent->updated)
3260 LEB128_SIZE /* index */ +
3261 LEB128_SIZE /* type */ +
3262 LEB128_SIZE /* value */
3267 LEB128_SIZE /* stop marker */
3270 logbuffer = ensure_logbuf (size);
3272 ENTER_LOG (logbuffer, "perfcounters");
3273 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
3274 emit_uvalue (logbuffer, timestamp);
3275 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3276 if (pcagent->deleted || !pcagent->updated)
3278 emit_uvalue (logbuffer, pcagent->index);
3279 emit_uvalue (logbuffer, MONO_COUNTER_LONG);
3280 emit_svalue (logbuffer, pcagent->value);
3282 pcagent->updated = 0;
3285 emit_value (logbuffer, 0);
3286 EXIT_LOG (logbuffer);
3289 safe_send_threadless (profiler, logbuffer);
3291 safe_send (profiler, logbuffer);
3293 mono_os_mutex_unlock (&counters_mutex);
3297 counters_and_perfcounters_sample (MonoProfiler *prof, gboolean threadless)
3299 static uint64_t start = -1;
3303 start = current_time ();
3305 now = current_time ();
3306 counters_sample (prof, (now - start) / 1000/ 1000, threadless);
3307 perfcounters_sample (prof, (now - start) / 1000/ 1000, threadless);
3310 #define COVERAGE_DEBUG(x) if (debug_coverage) {x}
3311 static mono_mutex_t coverage_mutex;
3312 static MonoConcurrentHashTable *coverage_methods = NULL;
3313 static MonoConcurrentHashTable *coverage_assemblies = NULL;
3314 static MonoConcurrentHashTable *coverage_classes = NULL;
3316 static MonoConcurrentHashTable *filtered_classes = NULL;
3317 static MonoConcurrentHashTable *entered_methods = NULL;
3318 static MonoConcurrentHashTable *image_to_methods = NULL;
3319 static MonoConcurrentHashTable *suppressed_assemblies = NULL;
3320 static gboolean coverage_initialized = FALSE;
3322 static GPtrArray *coverage_data = NULL;
3323 static int previous_offset = 0;
3325 typedef struct _MethodNode MethodNode;
3326 struct _MethodNode {
3327 MonoLockFreeQueueNode node;
3331 typedef struct _CoverageEntry CoverageEntry;
3332 struct _CoverageEntry {
3341 free_coverage_entry (gpointer data, gpointer userdata)
3343 CoverageEntry *entry = (CoverageEntry *)data;
3344 g_free (entry->filename);
3349 obtain_coverage_for_method (MonoProfiler *prof, const MonoProfileCoverageEntry *entry)
3351 int offset = entry->iloffset - previous_offset;
3352 CoverageEntry *e = g_new (CoverageEntry, 1);
3354 previous_offset = entry->iloffset;
3357 e->counter = entry->counter;
3358 e->filename = g_strdup(entry->filename ? entry->filename : "");
3359 e->line = entry->line;
3360 e->column = entry->col;
3362 g_ptr_array_add (coverage_data, e);
3366 parse_generic_type_names(char *name)
3368 char *new_name, *ret;
3369 int within_generic_declaration = 0, generic_members = 1;
3371 if (name == NULL || *name == '\0')
3372 return g_strdup ("");
3374 if (!(ret = new_name = (char *)calloc (strlen (name) * 4 + 1, sizeof (char))))
3380 within_generic_declaration = 1;
3384 within_generic_declaration = 0;
3386 if (*(name - 1) != '<') {
3388 *new_name++ = '0' + generic_members;
3390 memcpy (new_name, "<>", 8);
3394 generic_members = 0;
3402 if (!within_generic_declaration)
3403 *new_name++ = *name;
3412 static int method_id;
3414 build_method_buffer (gpointer key, gpointer value, gpointer userdata)
3416 MonoMethod *method = (MonoMethod *)value;
3417 MonoProfiler *prof = (MonoProfiler *)userdata;
3421 const char *image_name, *method_name, *sig, *first_filename;
3422 LogBuffer *logbuffer;
3425 previous_offset = 0;
3426 coverage_data = g_ptr_array_new ();
3428 mono_profiler_coverage_get (prof, method, obtain_coverage_for_method);
3430 klass = mono_method_get_class (method);
3431 image = mono_class_get_image (klass);
3432 image_name = mono_image_get_name (image);
3434 sig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3435 class_name = parse_generic_type_names (mono_type_get_name (mono_class_get_type (klass)));
3436 method_name = mono_method_get_name (method);
3438 if (coverage_data->len != 0) {
3439 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[0];
3440 first_filename = entry->filename ? entry->filename : "";
3442 first_filename = "";
3444 image_name = image_name ? image_name : "";
3445 sig = sig ? sig : "";
3446 method_name = method_name ? method_name : "";
3448 logbuffer = ensure_logbuf (
3449 EVENT_SIZE /* event */ +
3450 strlen (image_name) + 1 /* image name */ +
3451 strlen (class_name) + 1 /* class name */ +
3452 strlen (method_name) + 1 /* method name */ +
3453 strlen (sig) + 1 /* signature */ +
3454 strlen (first_filename) + 1 /* first file name */ +
3455 LEB128_SIZE /* token */ +
3456 LEB128_SIZE /* method id */ +
3457 LEB128_SIZE /* entries */
3459 ENTER_LOG (logbuffer, "coverage-methods");
3461 emit_byte (logbuffer, TYPE_COVERAGE_METHOD | TYPE_COVERAGE);
3462 emit_string (logbuffer, image_name, strlen (image_name) + 1);
3463 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3464 emit_string (logbuffer, method_name, strlen (method_name) + 1);
3465 emit_string (logbuffer, sig, strlen (sig) + 1);
3466 emit_string (logbuffer, first_filename, strlen (first_filename) + 1);
3468 emit_uvalue (logbuffer, mono_method_get_token (method));
3469 emit_uvalue (logbuffer, method_id);
3470 emit_value (logbuffer, coverage_data->len);
3472 EXIT_LOG (logbuffer);
3473 safe_send (prof, logbuffer);
3475 for (i = 0; i < coverage_data->len; i++) {
3476 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[i];
3478 logbuffer = ensure_logbuf (
3479 EVENT_SIZE /* event */ +
3480 LEB128_SIZE /* method id */ +
3481 LEB128_SIZE /* offset */ +
3482 LEB128_SIZE /* counter */ +
3483 LEB128_SIZE /* line */ +
3484 LEB128_SIZE /* column */
3486 ENTER_LOG (logbuffer, "coverage-statement");
3488 emit_byte (logbuffer, TYPE_COVERAGE_STATEMENT | TYPE_COVERAGE);
3489 emit_uvalue (logbuffer, method_id);
3490 emit_uvalue (logbuffer, entry->offset);
3491 emit_uvalue (logbuffer, entry->counter);
3492 emit_uvalue (logbuffer, entry->line);
3493 emit_uvalue (logbuffer, entry->column);
3495 EXIT_LOG (logbuffer);
3496 safe_send (prof, logbuffer);
3501 g_free (class_name);
3503 g_ptr_array_foreach (coverage_data, free_coverage_entry, NULL);
3504 g_ptr_array_free (coverage_data, TRUE);
3505 coverage_data = NULL;
3508 /* This empties the queue */
3510 count_queue (MonoLockFreeQueue *queue)
3512 MonoLockFreeQueueNode *node;
3515 while ((node = mono_lock_free_queue_dequeue (queue))) {
3517 mono_lock_free_queue_node_free (node);
3524 build_class_buffer (gpointer key, gpointer value, gpointer userdata)
3526 MonoClass *klass = (MonoClass *)key;
3527 MonoLockFreeQueue *class_methods = (MonoLockFreeQueue *)value;
3528 MonoProfiler *prof = (MonoProfiler *)userdata;
3531 const char *assembly_name;
3532 int number_of_methods, partially_covered;
3533 guint fully_covered;
3534 LogBuffer *logbuffer;
3536 image = mono_class_get_image (klass);
3537 assembly_name = mono_image_get_name (image);
3538 class_name = mono_type_get_name (mono_class_get_type (klass));
3540 assembly_name = assembly_name ? assembly_name : "";
3541 number_of_methods = mono_class_num_methods (klass);
3542 fully_covered = count_queue (class_methods);
3543 /* We don't handle partial covered yet */
3544 partially_covered = 0;
3546 logbuffer = ensure_logbuf (
3547 EVENT_SIZE /* event */ +
3548 strlen (assembly_name) + 1 /* assembly name */ +
3549 strlen (class_name) + 1 /* class name */ +
3550 LEB128_SIZE /* no. methods */ +
3551 LEB128_SIZE /* fully covered */ +
3552 LEB128_SIZE /* partially covered */
3555 ENTER_LOG (logbuffer, "coverage-class");
3556 emit_byte (logbuffer, TYPE_COVERAGE_CLASS | TYPE_COVERAGE);
3557 emit_string (logbuffer, assembly_name, strlen (assembly_name) + 1);
3558 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3559 emit_uvalue (logbuffer, number_of_methods);
3560 emit_uvalue (logbuffer, fully_covered);
3561 emit_uvalue (logbuffer, partially_covered);
3562 EXIT_LOG (logbuffer);
3564 safe_send (prof, logbuffer);
3566 g_free (class_name);
3570 get_coverage_for_image (MonoImage *image, int *number_of_methods, guint *fully_covered, int *partially_covered)
3572 MonoLockFreeQueue *image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3574 *number_of_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
3576 *fully_covered = count_queue (image_methods);
3580 // FIXME: We don't handle partially covered yet.
3581 *partially_covered = 0;
3585 build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
3587 MonoAssembly *assembly = (MonoAssembly *)value;
3588 MonoProfiler *prof = (MonoProfiler *)userdata;
3589 MonoImage *image = mono_assembly_get_image (assembly);
3590 LogBuffer *logbuffer;
3591 const char *name, *guid, *filename;
3592 int number_of_methods = 0, partially_covered = 0;
3593 guint fully_covered = 0;
3595 name = mono_image_get_name (image);
3596 guid = mono_image_get_guid (image);
3597 filename = mono_image_get_filename (image);
3599 name = name ? name : "";
3600 guid = guid ? guid : "";
3601 filename = filename ? filename : "";
3603 get_coverage_for_image (image, &number_of_methods, &fully_covered, &partially_covered);
3605 logbuffer = ensure_logbuf (
3606 EVENT_SIZE /* event */ +
3607 strlen (name) + 1 /* name */ +
3608 strlen (guid) + 1 /* guid */ +
3609 strlen (filename) + 1 /* file name */ +
3610 LEB128_SIZE /* no. methods */ +
3611 LEB128_SIZE /* fully covered */ +
3612 LEB128_SIZE /* partially covered */
3615 ENTER_LOG (logbuffer, "coverage-assemblies");
3616 emit_byte (logbuffer, TYPE_COVERAGE_ASSEMBLY | TYPE_COVERAGE);
3617 emit_string (logbuffer, name, strlen (name) + 1);
3618 emit_string (logbuffer, guid, strlen (guid) + 1);
3619 emit_string (logbuffer, filename, strlen (filename) + 1);
3620 emit_uvalue (logbuffer, number_of_methods);
3621 emit_uvalue (logbuffer, fully_covered);
3622 emit_uvalue (logbuffer, partially_covered);
3623 EXIT_LOG (logbuffer);
3625 safe_send (prof, logbuffer);
3629 dump_coverage (MonoProfiler *prof)
3631 if (!coverage_initialized)
3634 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Started dump\n");)
3637 mono_os_mutex_lock (&coverage_mutex);
3638 mono_conc_hashtable_foreach (coverage_assemblies, build_assembly_buffer, prof);
3639 mono_conc_hashtable_foreach (coverage_classes, build_class_buffer, prof);
3640 mono_conc_hashtable_foreach (coverage_methods, build_method_buffer, prof);
3641 mono_os_mutex_unlock (&coverage_mutex);
3643 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Finished dump\n");)
3647 process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method)
3652 if (!coverage_initialized)
3655 klass = mono_method_get_class (method);
3656 image = mono_class_get_image (klass);
3658 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)))
3661 mono_os_mutex_lock (&coverage_mutex);
3662 mono_conc_hashtable_insert (entered_methods, method, method);
3663 mono_os_mutex_unlock (&coverage_mutex);
3666 static MonoLockFreeQueueNode *
3667 create_method_node (MonoMethod *method)
3669 MethodNode *node = (MethodNode *)g_malloc (sizeof (MethodNode));
3670 mono_lock_free_queue_node_init ((MonoLockFreeQueueNode *) node, FALSE);
3671 node->method = method;
3673 return (MonoLockFreeQueueNode *) node;
3677 coverage_filter (MonoProfiler *prof, MonoMethod *method)
3682 MonoAssembly *assembly;
3683 MonoMethodHeader *header;
3684 guint32 iflags, flags, code_size;
3685 char *fqn, *classname;
3686 gboolean has_positive, found;
3687 MonoLockFreeQueue *image_methods, *class_methods;
3688 MonoLockFreeQueueNode *node;
3690 if (!coverage_initialized)
3693 COVERAGE_DEBUG(fprintf (stderr, "Coverage filter for %s\n", mono_method_get_name (method));)
3695 flags = mono_method_get_flags (method, &iflags);
3696 if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
3697 (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/)) {
3698 COVERAGE_DEBUG(fprintf (stderr, " Internal call or pinvoke - ignoring\n");)
3702 // Don't need to do anything else if we're already tracking this method
3703 if (mono_conc_hashtable_lookup (coverage_methods, method)) {
3704 COVERAGE_DEBUG(fprintf (stderr, " Already tracking\n");)
3708 klass = mono_method_get_class (method);
3709 image = mono_class_get_image (klass);
3711 // Don't handle coverage for the core assemblies
3712 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)) != NULL)
3715 if (prof->coverage_filters) {
3716 /* Check already filtered classes first */
3717 if (mono_conc_hashtable_lookup (filtered_classes, klass)) {
3718 COVERAGE_DEBUG(fprintf (stderr, " Already filtered\n");)
3722 classname = mono_type_get_name (mono_class_get_type (klass));
3724 fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
3726 COVERAGE_DEBUG(fprintf (stderr, " Looking for %s in filter\n", fqn);)
3727 // Check positive filters first
3728 has_positive = FALSE;
3730 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3731 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3733 if (filter [0] == '+') {
3734 filter = &filter [1];
3736 COVERAGE_DEBUG(fprintf (stderr, " Checking against +%s ...", filter);)
3738 if (strstr (fqn, filter) != NULL) {
3739 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3742 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3744 has_positive = TRUE;
3748 if (has_positive && !found) {
3749 COVERAGE_DEBUG(fprintf (stderr, " Positive match was not found\n");)
3751 mono_os_mutex_lock (&coverage_mutex);
3752 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3753 mono_os_mutex_unlock (&coverage_mutex);
3760 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3761 // FIXME: Is substring search sufficient?
3762 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3763 if (filter [0] == '+')
3767 filter = &filter [1];
3768 COVERAGE_DEBUG(fprintf (stderr, " Checking against -%s ...", filter);)
3770 if (strstr (fqn, filter) != NULL) {
3771 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3773 mono_os_mutex_lock (&coverage_mutex);
3774 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3775 mono_os_mutex_unlock (&coverage_mutex);
3781 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3789 COVERAGE_DEBUG(fprintf (stderr, " Handling coverage for %s\n", mono_method_get_name (method));)
3790 header = mono_method_get_header_checked (method, &error);
3791 mono_error_cleanup (&error);
3793 mono_method_header_get_code (header, &code_size, NULL);
3795 assembly = mono_image_get_assembly (image);
3797 // Need to keep the assemblies around for as long as they are kept in the hashtable
3798 // Nunit, for example, has a habit of unloading them before the coverage statistics are
3799 // generated causing a crash. See https://bugzilla.xamarin.com/show_bug.cgi?id=39325
3800 mono_assembly_addref (assembly);
3802 mono_os_mutex_lock (&coverage_mutex);
3803 mono_conc_hashtable_insert (coverage_methods, method, method);
3804 mono_conc_hashtable_insert (coverage_assemblies, assembly, assembly);
3805 mono_os_mutex_unlock (&coverage_mutex);
3807 image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3809 if (image_methods == NULL) {
3810 image_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
3811 mono_lock_free_queue_init (image_methods);
3812 mono_os_mutex_lock (&coverage_mutex);
3813 mono_conc_hashtable_insert (image_to_methods, image, image_methods);
3814 mono_os_mutex_unlock (&coverage_mutex);
3817 node = create_method_node (method);
3818 mono_lock_free_queue_enqueue (image_methods, node);
3820 class_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (coverage_classes, klass);
3822 if (class_methods == NULL) {
3823 class_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
3824 mono_lock_free_queue_init (class_methods);
3825 mono_os_mutex_lock (&coverage_mutex);
3826 mono_conc_hashtable_insert (coverage_classes, klass, class_methods);
3827 mono_os_mutex_unlock (&coverage_mutex);
3830 node = create_method_node (method);
3831 mono_lock_free_queue_enqueue (class_methods, node);
3836 #define LINE_BUFFER_SIZE 4096
3837 /* Max file limit of 128KB */
3838 #define MAX_FILE_SIZE 128 * 1024
3840 get_file_content (FILE *stream)
3845 int res, offset = 0;
3847 res = fseek (stream, 0, SEEK_END);
3851 filesize = ftell (stream);
3855 res = fseek (stream, 0, SEEK_SET);
3859 if (filesize > MAX_FILE_SIZE)
3862 buffer = (char *)g_malloc ((filesize + 1) * sizeof (char));
3863 while ((bytes_read = fread (buffer + offset, 1, LINE_BUFFER_SIZE, stream)) > 0)
3864 offset += bytes_read;
3866 /* NULL terminate our buffer */
3867 buffer[filesize] = '\0';
3872 get_next_line (char *contents, char **next_start)
3876 if (p == NULL || *p == '\0') {
3881 while (*p != '\n' && *p != '\0')
3886 *next_start = p + 1;
3894 init_suppressed_assemblies (void)
3900 suppressed_assemblies = mono_conc_hashtable_new (g_str_hash, g_str_equal);
3901 sa_file = fopen (SUPPRESSION_DIR "/mono-profiler-log.suppression", "r");
3902 if (sa_file == NULL)
3905 /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
3906 content = get_file_content (sa_file);
3907 if (content == NULL) {
3908 g_error ("mono-profiler-log.suppression is greater than 128kb - aborting\n");
3911 while ((line = get_next_line (content, &content))) {
3912 line = g_strchomp (g_strchug (line));
3913 /* No locking needed as we're doing initialization */
3914 mono_conc_hashtable_insert (suppressed_assemblies, line, line);
3920 #endif /* DISABLE_HELPER_THREAD */
3923 coverage_init (MonoProfiler *prof)
3925 #ifndef DISABLE_HELPER_THREAD
3926 assert (!coverage_initialized);
3928 COVERAGE_DEBUG(fprintf (stderr, "Coverage initialized\n");)
3930 mono_os_mutex_init (&coverage_mutex);
3931 coverage_methods = mono_conc_hashtable_new (NULL, NULL);
3932 coverage_assemblies = mono_conc_hashtable_new (NULL, NULL);
3933 coverage_classes = mono_conc_hashtable_new (NULL, NULL);
3934 filtered_classes = mono_conc_hashtable_new (NULL, NULL);
3935 entered_methods = mono_conc_hashtable_new (NULL, NULL);
3936 image_to_methods = mono_conc_hashtable_new (NULL, NULL);
3937 init_suppressed_assemblies ();
3939 coverage_initialized = TRUE;
3940 #endif /* DISABLE_HELPER_THREAD */
3944 unref_coverage_assemblies (gpointer key, gpointer value, gpointer userdata)
3946 MonoAssembly *assembly = (MonoAssembly *)value;
3947 mono_assembly_close (assembly);
3951 log_shutdown (MonoProfiler *prof)
3956 #ifndef DISABLE_HELPER_THREAD
3957 counters_and_perfcounters_sample (prof, FALSE);
3959 dump_coverage (prof);
3961 if (prof->command_port) {
3963 ign_res (write (prof->pipes [1], &c, 1));
3964 pthread_join (prof->helper_thread, &res);
3970 for (i = 0; i < num_perf; ++i)
3971 read_perf_mmap (prof, i);
3975 g_ptr_array_free (prof->sorted_sample_events, TRUE);
3977 if (TLS_GET (LogBuffer, tlsbuffer))
3978 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
3980 TLS_SET (tlsbuffer, NULL);
3981 TLS_SET (tlsmethodlist, NULL);
3983 InterlockedWrite (&prof->run_writer_thread, 0);
3984 pthread_join (prof->writer_thread, &res);
3986 #if defined (HAVE_SYS_ZLIB)
3988 gzclose (prof->gzfile);
3990 if (prof->pipe_output)
3991 pclose (prof->file);
3993 fclose (prof->file);
3995 mono_conc_hashtable_destroy (prof->method_table);
3996 mono_os_mutex_destroy (&prof->method_table_mutex);
3998 if (coverage_initialized) {
3999 mono_os_mutex_lock (&coverage_mutex);
4000 mono_conc_hashtable_foreach (coverage_assemblies, unref_coverage_assemblies, prof);
4001 mono_os_mutex_unlock (&coverage_mutex);
4003 mono_conc_hashtable_destroy (coverage_methods);
4004 mono_conc_hashtable_destroy (coverage_assemblies);
4005 mono_conc_hashtable_destroy (coverage_classes);
4006 mono_conc_hashtable_destroy (filtered_classes);
4008 mono_conc_hashtable_destroy (entered_methods);
4009 mono_conc_hashtable_destroy (image_to_methods);
4010 mono_conc_hashtable_destroy (suppressed_assemblies);
4011 mono_os_mutex_destroy (&coverage_mutex);
4018 new_filename (const char* filename)
4020 time_t t = time (NULL);
4021 int pid = process_id ();
4026 int count_dates = 0;
4030 for (p = filename; *p; p++) {
4041 if (!count_dates && !count_pids)
4042 return pstrdup (filename);
4043 snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
4045 snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
4046 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
4047 s_date = strlen (time_buf);
4048 s_pid = strlen (pid_buf);
4049 d = res = (char *)malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
4050 for (p = filename; *p; p++) {
4057 strcpy (d, time_buf);
4060 } else if (*p == 'p') {
4061 strcpy (d, pid_buf);
4064 } else if (*p == '%') {
4076 //this is exposed by the JIT, but it's not meant to be a supported API for now.
4077 extern void mono_threads_attach_tools_thread (void);
4079 #ifndef DISABLE_HELPER_THREAD
4082 helper_thread (void* arg)
4084 MonoProfiler* prof = (MonoProfiler *)arg;
4088 MonoThread *thread = NULL;
4090 mono_threads_attach_tools_thread ();
4091 mono_thread_info_set_name (mono_native_thread_id_get (), "Profiler helper");
4093 //fprintf (stderr, "Server listening\n");
4094 command_socket = -1;
4100 FD_SET (prof->server_socket, &rfds);
4101 max_fd = prof->server_socket;
4102 FD_SET (prof->pipes [0], &rfds);
4103 if (max_fd < prof->pipes [0])
4104 max_fd = prof->pipes [0];
4105 if (command_socket >= 0) {
4106 FD_SET (command_socket, &rfds);
4107 if (max_fd < command_socket)
4108 max_fd = command_socket;
4113 for ( i = 0; i < num_perf; ++i) {
4114 if (perf_data [i].perf_fd < 0)
4116 FD_SET (perf_data [i].perf_fd, &rfds);
4117 if (max_fd < perf_data [i].perf_fd)
4118 max_fd = perf_data [i].perf_fd;
4123 counters_and_perfcounters_sample (prof, TRUE);
4127 len = select (max_fd + 1, &rfds, NULL, NULL, &tv);
4133 g_warning ("Error in proflog server: %s", strerror (errno));
4137 if (FD_ISSET (prof->pipes [0], &rfds)) {
4139 int r = read (prof->pipes [0], &c, 1);
4140 if (r == 1 && c == 0) {
4141 StatBuffer *sbufbase = prof->stat_buffers;
4143 if (!sbufbase->next)
4145 sbuf = sbufbase->next->next;
4146 sbufbase->next->next = NULL;
4148 fprintf (stderr, "stat buffer dump\n");
4150 dump_sample_hits (prof, sbuf);
4151 free_buffer (sbuf, sbuf->size);
4152 safe_send_threadless (prof, ensure_logbuf (0));
4156 /* time to shut down */
4157 dump_sample_hits (prof, prof->stat_buffers);
4159 mono_thread_detach (thread);
4161 fprintf (stderr, "helper shutdown\n");
4165 for ( i = 0; i < num_perf; ++i) {
4166 if (perf_data [i].perf_fd < 0)
4168 if (FD_ISSET (perf_data [i].perf_fd, &rfds))
4169 read_perf_mmap (prof, i);
4173 safe_send_threadless (prof, ensure_logbuf (0));
4179 for ( i = 0; i < num_perf; ++i) {
4180 if (perf_data [i].perf_fd < 0)
4182 if (FD_ISSET (perf_data [i].perf_fd, &rfds)) {
4183 read_perf_mmap (prof, i);
4184 safe_send_threadless (prof, ensure_logbuf (0));
4189 if (command_socket >= 0 && FD_ISSET (command_socket, &rfds)) {
4190 len = read (command_socket, buf, sizeof (buf) - 1);
4194 close (command_socket);
4195 command_socket = -1;
4199 if (strcmp (buf, "heapshot\n") == 0) {
4200 heapshot_requested = 1;
4201 //fprintf (stderr, "perform heapshot\n");
4202 if (InterlockedRead (&runtime_inited) && !thread) {
4203 thread = mono_thread_attach (mono_get_root_domain ());
4204 /*fprintf (stderr, "attached\n");*/
4207 process_requests (prof);
4208 mono_thread_detach (thread);
4214 if (!FD_ISSET (prof->server_socket, &rfds)) {
4217 command_socket = accept (prof->server_socket, NULL, NULL);
4218 if (command_socket < 0)
4220 //fprintf (stderr, "Accepted connection\n");
4226 start_helper_thread (MonoProfiler* prof)
4228 struct sockaddr_in server_address;
4231 if (pipe (prof->pipes) < 0) {
4232 fprintf (stderr, "Cannot create pipe\n");
4235 prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
4236 if (prof->server_socket < 0) {
4237 fprintf (stderr, "Cannot create server socket\n");
4240 memset (&server_address, 0, sizeof (server_address));
4241 server_address.sin_family = AF_INET;
4242 server_address.sin_addr.s_addr = INADDR_ANY;
4243 server_address.sin_port = htons (prof->command_port);
4244 if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) < 0) {
4245 fprintf (stderr, "Cannot bind server socket, port: %d: %s\n", prof->command_port, strerror (errno));
4246 close (prof->server_socket);
4249 if (listen (prof->server_socket, 1) < 0) {
4250 fprintf (stderr, "Cannot listen server socket\n");
4251 close (prof->server_socket);
4254 slen = sizeof (server_address);
4255 if (getsockname (prof->server_socket, (struct sockaddr *)&server_address, &slen) == 0) {
4256 prof->command_port = ntohs (server_address.sin_port);
4257 /*fprintf (stderr, "Assigned server port: %d\n", prof->command_port);*/
4260 r = pthread_create (&prof->helper_thread, NULL, helper_thread, prof);
4262 close (prof->server_socket);
4270 writer_thread (void *arg)
4272 MonoProfiler *prof = (MonoProfiler *)arg;
4274 mono_threads_attach_tools_thread ();
4275 mono_thread_info_set_name (mono_native_thread_id_get (), "Profiler writer");
4279 while (InterlockedRead (&prof->run_writer_thread)) {
4280 WriterQueueEntry *entry;
4282 while ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&prof->writer_queue))) {
4283 LogBuffer *method_buffer = NULL;
4284 gboolean new_methods = FALSE;
4286 if (entry->methods->len)
4287 method_buffer = create_buffer ();
4290 * Encode the method events in a temporary log buffer that we
4291 * flush to disk before the main buffer, ensuring that all
4292 * methods have metadata emitted before they're referenced.
4294 for (guint i = 0; i < entry->methods->len; i++) {
4295 MethodInfo *info = (MethodInfo *)g_ptr_array_index (entry->methods, i);
4297 if (mono_conc_hashtable_lookup (prof->method_table, info->method))
4303 * Other threads use this hash table to get a general
4304 * idea of whether a method has already been emitted to
4305 * the stream. Due to the way we add to this table, it
4306 * can easily happen that multiple threads queue up the
4307 * same methods, but that's OK since eventually all
4308 * methods will be in this table and the thread-local
4309 * method lists will just be empty for the rest of the
4312 mono_os_mutex_lock (&prof->method_table_mutex);
4313 mono_conc_hashtable_insert (prof->method_table, info->method, info->method);
4314 mono_os_mutex_unlock (&prof->method_table_mutex);
4316 char *name = mono_method_full_name (info->method, 1);
4317 int nlen = strlen (name) + 1;
4318 void *cstart = info->ji ? mono_jit_info_get_code_start (info->ji) : NULL;
4319 int csize = info->ji ? mono_jit_info_get_code_size (info->ji) : 0;
4321 method_buffer = ensure_logbuf_inner (method_buffer,
4322 EVENT_SIZE /* event */ +
4323 LEB128_SIZE /* time */ +
4324 LEB128_SIZE /* method */ +
4325 LEB128_SIZE /* start */ +
4326 LEB128_SIZE /* size */ +
4330 emit_byte (method_buffer, TYPE_JIT | TYPE_METHOD);
4331 emit_time (method_buffer, info->time);
4332 emit_method_inner (method_buffer, info->method);
4333 emit_ptr (method_buffer, cstart);
4334 emit_value (method_buffer, csize);
4336 memcpy (method_buffer->cursor, name, nlen);
4337 method_buffer->cursor += nlen;
4343 g_ptr_array_free (entry->methods, TRUE);
4346 for (LogBuffer *iter = method_buffer; iter; iter = iter->next)
4347 iter->thread_id = 0;
4349 dump_buffer (prof, method_buffer);
4350 } else if (method_buffer)
4351 free_buffer (method_buffer, method_buffer->size);
4353 dump_buffer (prof, entry->buffer);
4363 start_writer_thread (MonoProfiler* prof)
4365 InterlockedWrite (&prof->run_writer_thread, 1);
4367 return !pthread_create (&prof->writer_thread, NULL, writer_thread, prof);
4371 runtime_initialized (MonoProfiler *profiler)
4373 #ifndef DISABLE_HELPER_THREAD
4374 if (hs_mode_ondemand || need_helper_thread) {
4375 if (!start_helper_thread (profiler))
4376 profiler->command_port = 0;
4380 start_writer_thread (profiler);
4382 InterlockedWrite (&runtime_inited, 1);
4383 #ifndef DISABLE_HELPER_THREAD
4384 counters_init (profiler);
4385 counters_sample (profiler, 0, FALSE);
4387 /* ensure the main thread data and startup are available soon */
4388 safe_send (profiler, ensure_logbuf (0));
4391 static MonoProfiler*
4392 create_profiler (const char *filename, GPtrArray *filters)
4396 int force_delete = 0;
4397 prof = (MonoProfiler *)calloc (1, sizeof (MonoProfiler));
4399 prof->command_port = command_port;
4400 if (filename && *filename == '-') {
4406 filename = "|mprof-report -";
4408 filename = "output.mlpd";
4409 nf = (char*)filename;
4411 nf = new_filename (filename);
4413 int s = strlen (nf) + 32;
4414 char *p = (char *)malloc (s);
4415 snprintf (p, s, "|mprof-report '--out=%s' -", nf);
4421 prof->file = popen (nf + 1, "w");
4422 prof->pipe_output = 1;
4423 } else if (*nf == '#') {
4424 int fd = strtol (nf + 1, NULL, 10);
4425 prof->file = fdopen (fd, "a");
4429 prof->file = fopen (nf, "wb");
4432 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
4435 #if defined (HAVE_SYS_ZLIB)
4437 prof->gzfile = gzdopen (fileno (prof->file), "wb");
4440 if (sample_type && !do_mono_sample)
4441 need_helper_thread = setup_perf_event ();
4443 /* FIXME: warn if different freq or sample type */
4447 if (do_mono_sample) {
4448 prof->stat_buffers = create_stat_buffer ();
4449 need_helper_thread = 1;
4451 if (do_counters && !need_helper_thread) {
4452 need_helper_thread = 1;
4455 prof->sorted_sample_events = g_ptr_array_sized_new (BUFFER_SIZE / SAMPLE_EVENT_SIZE_IN_SLOTS (0));
4457 #ifdef DISABLE_HELPER_THREAD
4458 if (hs_mode_ondemand)
4459 fprintf (stderr, "Ondemand heapshot unavailable on this arch.\n");
4462 fprintf (stderr, "Coverage unavailable on this arch.\n");
4466 mono_lock_free_queue_init (&prof->writer_queue);
4467 mono_os_mutex_init (&prof->method_table_mutex);
4468 prof->method_table = mono_conc_hashtable_new (NULL, NULL);
4471 coverage_init (prof);
4472 prof->coverage_filters = filters;
4474 prof->startup_time = current_time ();
4481 printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
4482 printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
4483 printf ("Options:\n");
4484 printf ("\thelp show this usage info\n");
4485 printf ("\t[no]alloc enable/disable recording allocation info\n");
4486 printf ("\t[no]calls enable/disable recording enter/leave method events\n");
4487 printf ("\theapshot[=MODE] record heap shot info (by default at each major collection)\n");
4488 printf ("\t MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
4489 printf ("\tcounters sample counters every 1s\n");
4490 printf ("\tsample[=TYPE] use statistical sampling mode (by default cycles/1000)\n");
4491 printf ("\t TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
4492 printf ("\t TYPE can be followed by /FREQUENCY\n");
4493 printf ("\ttime=fast use a faster (but more inaccurate) timer\n");
4494 printf ("\tmaxframes=NUM collect up to NUM stack frames\n");
4495 printf ("\tcalldepth=NUM ignore method events for call chain depth bigger than NUM\n");
4496 printf ("\toutput=FILENAME write the data to file FILENAME (-FILENAME to overwrite)\n");
4497 printf ("\toutput=|PROGRAM write the data to the stdin of PROGRAM\n");
4498 printf ("\t %%t is subtituted with date and time, %%p with the pid\n");
4499 printf ("\treport create a report instead of writing the raw data to a file\n");
4500 printf ("\tzip compress the output data\n");
4501 printf ("\tport=PORTNUM use PORTNUM for the listening command server\n");
4502 printf ("\tcoverage enable collection of code coverage data\n");
4503 printf ("\tcovfilter=ASSEMBLY add an assembly to the code coverage filters\n");
4504 printf ("\t add a + to include the assembly or a - to exclude it\n");
4505 printf ("\t filter=-mscorlib\n");
4506 printf ("\tcovfilter-file=FILE use FILE to generate the list of assemblies to be filtered\n");
4512 match_option (const char* p, const char *opt, char **rval)
4514 int len = strlen (opt);
4515 if (strncmp (p, opt, len) == 0) {
4517 if (p [len] == '=' && p [len + 1]) {
4518 const char *opt = p + len + 1;
4519 const char *end = strchr (opt, ',');
4527 val = (char *)malloc (l + 1);
4528 memcpy (val, opt, l);
4533 if (p [len] == 0 || p [len] == ',') {
4535 return p + len + (p [len] == ',');
4553 static const SampleMode sample_modes [] = {
4554 {"cycles", SAMPLE_CYCLES},
4555 {"instr", SAMPLE_INSTRUCTIONS},
4556 {"cachemiss", SAMPLE_CACHE_MISSES},
4557 {"cacherefs", SAMPLE_CACHE_REFS},
4558 {"branches", SAMPLE_BRANCHES},
4559 {"branchmiss", SAMPLE_BRANCH_MISSES},
4564 set_sample_mode (char* val, int allow_empty)
4567 char *maybe_freq = NULL;
4569 const SampleMode *smode = sample_modes;
4570 #ifndef USE_PERF_EVENTS
4573 if (allow_empty && !val) {
4574 sample_type = SAMPLE_CYCLES;
4578 if (strcmp (val, "mono") == 0) {
4580 sample_type = SAMPLE_CYCLES;
4584 for (smode = sample_modes; smode->name; smode++) {
4585 int l = strlen (smode->name);
4586 if (strncmp (val, smode->name, l) == 0) {
4587 sample_type = smode->sample_mode;
4588 maybe_freq = val + l;
4594 if (*maybe_freq == '/') {
4595 count = strtoul (maybe_freq + 1, &end, 10);
4596 if (maybe_freq + 1 == end)
4598 sample_freq = count;
4599 } else if (*maybe_freq != 0) {
4608 set_hsmode (char* val, int allow_empty)
4612 if (allow_empty && !val)
4614 if (strcmp (val, "ondemand") == 0) {
4615 hs_mode_ondemand = 1;
4619 count = strtoul (val, &end, 10);
4622 if (strcmp (end, "ms") == 0)
4624 else if (strcmp (end, "gc") == 0)
4632 * declaration to silence the compiler: this is the entry point that
4633 * mono will load from the shared library and call.
4636 mono_profiler_startup (const char *desc);
4639 mono_profiler_startup_log (const char *desc);
4642 * this is the entry point that will be used when the profiler
4643 * is embedded inside the main executable.
4646 mono_profiler_startup_log (const char *desc)
4648 mono_profiler_startup (desc);
4652 mono_profiler_startup (const char *desc)
4655 GPtrArray *filters = NULL;
4656 char *filename = NULL;
4660 int calls_enabled = 0;
4661 int allocs_enabled = 0;
4662 int only_counters = 0;
4663 int only_coverage = 0;
4664 int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
4665 MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
4666 MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
4667 MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS|
4668 MONO_PROFILE_INS_COVERAGE|MONO_PROFILE_APPDOMAIN_EVENTS|MONO_PROFILE_CONTEXT_EVENTS|
4669 MONO_PROFILE_ASSEMBLY_EVENTS;
4672 if (strncmp (p, "log", 3))
4677 for (; *p; p = opt) {
4683 if ((opt = match_option (p, "help", NULL)) != p) {
4687 if ((opt = match_option (p, "calls", NULL)) != p) {
4691 if ((opt = match_option (p, "nocalls", NULL)) != p) {
4692 events &= ~MONO_PROFILE_ENTER_LEAVE;
4696 if ((opt = match_option (p, "alloc", NULL)) != p) {
4700 if ((opt = match_option (p, "noalloc", NULL)) != p) {
4701 events &= ~MONO_PROFILE_ALLOCATIONS;
4704 if ((opt = match_option (p, "time", &val)) != p) {
4705 if (strcmp (val, "fast") == 0)
4707 else if (strcmp (val, "null") == 0)
4714 if ((opt = match_option (p, "report", NULL)) != p) {
4718 if ((opt = match_option (p, "debug", NULL)) != p) {
4722 if ((opt = match_option (p, "sampling-real", NULL)) != p) {
4723 sampling_mode = MONO_PROFILER_STAT_MODE_REAL;
4726 if ((opt = match_option (p, "sampling-process", NULL)) != p) {
4727 sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
4730 if ((opt = match_option (p, "heapshot", &val)) != p) {
4731 events &= ~MONO_PROFILE_ALLOCATIONS;
4732 events &= ~MONO_PROFILE_ENTER_LEAVE;
4735 set_hsmode (val, 1);
4738 if ((opt = match_option (p, "sample", &val)) != p) {
4739 events &= ~MONO_PROFILE_ALLOCATIONS;
4740 events &= ~MONO_PROFILE_ENTER_LEAVE;
4742 set_sample_mode (val, 1);
4745 if ((opt = match_option (p, "hsmode", &val)) != p) {
4746 fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
4747 set_hsmode (val, 0);
4750 if ((opt = match_option (p, "zip", NULL)) != p) {
4754 if ((opt = match_option (p, "output", &val)) != p) {
4758 if ((opt = match_option (p, "port", &val)) != p) {
4760 command_port = strtoul (val, &end, 10);
4764 if ((opt = match_option (p, "maxframes", &val)) != p) {
4766 num_frames = strtoul (val, &end, 10);
4767 if (num_frames > MAX_FRAMES)
4768 num_frames = MAX_FRAMES;
4770 notraces = num_frames == 0;
4773 if ((opt = match_option (p, "calldepth", &val)) != p) {
4775 max_call_depth = strtoul (val, &end, 10);
4779 if ((opt = match_option (p, "counters", NULL)) != p) {
4783 if ((opt = match_option (p, "countersonly", NULL)) != p) {
4787 if ((opt = match_option (p, "coverage", NULL)) != p) {
4789 events |= MONO_PROFILE_ENTER_LEAVE;
4790 debug_coverage = (g_getenv ("MONO_PROFILER_DEBUG_COVERAGE") != NULL);
4793 if ((opt = match_option (p, "onlycoverage", NULL)) != p) {
4797 if ((opt = match_option (p, "covfilter-file", &val)) != p) {
4799 char *line, *content;
4801 if (filters == NULL)
4802 filters = g_ptr_array_new ();
4804 filter_file = fopen (val, "r");
4805 if (filter_file == NULL) {
4806 fprintf (stderr, "Unable to open %s\n", val);
4810 /* Don't need to free content as it is referred to by the lines stored in @filters */
4811 content = get_file_content (filter_file);
4812 if (content == NULL)
4813 fprintf (stderr, "WARNING: %s is greater than 128kb - ignoring\n", val);
4815 while ((line = get_next_line (content, &content)))
4816 g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
4818 fclose (filter_file);
4821 if ((opt = match_option (p, "covfilter", &val)) != p) {
4822 if (filters == NULL)
4823 filters = g_ptr_array_new ();
4825 g_ptr_array_add (filters, val);
4833 if (calls_enabled) {
4834 events |= MONO_PROFILE_ENTER_LEAVE;
4838 events |= MONO_PROFILE_ALLOCATIONS;
4842 events = MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_INS_COVERAGE;
4844 utils_init (fast_time);
4846 prof = create_profiler (filename, filters);
4851 mono_profiler_install (prof, log_shutdown);
4852 mono_profiler_install_gc (gc_event, gc_resize);
4853 mono_profiler_install_allocation (gc_alloc);
4854 mono_profiler_install_gc_moves (gc_moves);
4855 mono_profiler_install_gc_roots (gc_handle, gc_roots);
4856 mono_profiler_install_appdomain (NULL, domain_loaded, NULL, domain_unloaded);
4857 mono_profiler_install_appdomain_name (domain_name);
4858 mono_profiler_install_context (context_loaded, context_unloaded);
4859 mono_profiler_install_class (NULL, class_loaded, NULL, class_unloaded);
4860 mono_profiler_install_module (NULL, image_loaded, NULL, image_unloaded);
4861 mono_profiler_install_assembly (NULL, assembly_loaded, assembly_unloaded, NULL);
4862 mono_profiler_install_thread (thread_start, thread_end);
4863 mono_profiler_install_thread_name (thread_name);
4864 mono_profiler_install_enter_leave (method_enter, method_leave);
4865 mono_profiler_install_jit_end (method_jitted);
4866 mono_profiler_install_code_buffer_new (code_buffer_new);
4867 mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
4868 mono_profiler_install_monitor (monitor_event);
4869 mono_profiler_install_runtime_initialized (runtime_initialized);
4871 mono_profiler_install_coverage_filter (coverage_filter);
4873 if (do_mono_sample && sample_type == SAMPLE_CYCLES && !only_counters) {
4874 events |= MONO_PROFILE_STATISTICAL;
4875 mono_profiler_set_statistical_mode (sampling_mode, 1000000 / sample_freq);
4876 mono_profiler_install_statistical (mono_sample_hit);
4879 mono_profiler_set_events ((MonoProfileFlags)events);
4881 TLS_INIT (tlsbuffer);
4882 TLS_INIT (tlsmethodlist);