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 MonoSemType writer_queue_sem;
519 MonoConcurrentHashTable *method_table;
520 mono_mutex_t method_table_mutex;
521 BinaryObject *binary_objects;
522 GPtrArray *coverage_filters;
523 GPtrArray *sorted_sample_events;
526 typedef struct _WriterQueueEntry WriterQueueEntry;
527 struct _WriterQueueEntry {
528 MonoLockFreeQueueNode node;
533 typedef struct _MethodInfo MethodInfo;
545 #define TLS_SET(x,y) (TlsSetValue (x, y))
546 #define TLS_GET(t,x) ((t *) TlsGetValue (x))
547 #define TLS_INIT(x) (x = TlsAlloc ())
548 static int tlsbuffer;
549 static int tlsmethodlist;
551 #define TLS_SET(x,y) (x = y)
552 #define TLS_GET(t,x) (x)
554 static __thread LogBuffer* tlsbuffer = NULL;
555 static __thread GPtrArray* tlsmethodlist = NULL;
557 #define TLS_SET(x,y) (pthread_setspecific (x, y))
558 #define TLS_GET(t,x) ((t *) pthread_getspecific (x))
559 #define TLS_INIT(x) (pthread_key_create (&x, NULL))
560 static pthread_key_t tlsbuffer;
561 static pthread_key_t tlsmethodlist;
564 static void safe_send (MonoProfiler *profiler, LogBuffer *logbuffer);
567 pstrdup (const char *s)
569 int len = strlen (s) + 1;
570 char *p = (char *)malloc (len);
576 create_stat_buffer (void)
578 StatBuffer* buf = (StatBuffer *)alloc_buffer (BUFFER_SIZE);
579 buf->size = BUFFER_SIZE;
580 buf->buf_end = (uintptr_t*)((unsigned char*)buf + buf->size);
581 buf->cursor = buf->buf;
588 LogBuffer* buf = (LogBuffer *)alloc_buffer (BUFFER_SIZE);
589 buf->size = BUFFER_SIZE;
590 buf->time_base = current_time ();
591 buf->last_time = buf->time_base;
592 buf->buf_end = (unsigned char*)buf + buf->size;
593 buf->cursor = buf->buf;
600 if (!TLS_GET (LogBuffer, tlsbuffer)) {
601 LogBuffer *logbuffer = create_buffer ();
602 TLS_SET (tlsbuffer, logbuffer);
603 logbuffer->thread_id = thread_id ();
605 if (!TLS_GET (GPtrArray, tlsmethodlist)) {
606 GPtrArray *methodlist = g_ptr_array_new ();
607 TLS_SET (tlsmethodlist, methodlist);
610 //printf ("thread %p at time %llu\n", (void*)logbuffer->thread_id, logbuffer->time_base);
614 ensure_logbuf_inner (LogBuffer *old, int bytes)
616 if (old && old->cursor + bytes + 100 < old->buf_end)
619 LogBuffer *new_ = (LogBuffer *)create_buffer ();
620 new_->thread_id = thread_id ();
624 new_->call_depth = old->call_depth;
630 ensure_logbuf (int bytes)
632 LogBuffer *old = TLS_GET (LogBuffer, tlsbuffer);
633 LogBuffer *new_ = ensure_logbuf_inner (old, bytes);
636 return old; // Still enough space.
638 TLS_SET (tlsbuffer, new_);
645 emit_byte (LogBuffer *logbuffer, int value)
647 logbuffer->cursor [0] = value;
649 assert (logbuffer->cursor <= logbuffer->buf_end);
653 emit_value (LogBuffer *logbuffer, int value)
655 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
656 assert (logbuffer->cursor <= logbuffer->buf_end);
660 emit_time (LogBuffer *logbuffer, uint64_t value)
662 uint64_t tdiff = value - logbuffer->last_time;
663 //if (value < logbuffer->last_time)
664 // printf ("time went backwards\n");
665 //if (tdiff > 1000000)
666 // printf ("large time offset: %llu\n", tdiff);
667 encode_uleb128 (tdiff, logbuffer->cursor, &logbuffer->cursor);
668 /*if (tdiff != decode_uleb128 (p, &p))
669 printf ("incorrect encoding: %llu\n", tdiff);*/
670 logbuffer->last_time = value;
671 assert (logbuffer->cursor <= logbuffer->buf_end);
675 emit_svalue (LogBuffer *logbuffer, int64_t value)
677 encode_sleb128 (value, logbuffer->cursor, &logbuffer->cursor);
678 assert (logbuffer->cursor <= logbuffer->buf_end);
682 emit_uvalue (LogBuffer *logbuffer, uint64_t value)
684 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
685 assert (logbuffer->cursor <= logbuffer->buf_end);
689 emit_ptr (LogBuffer *logbuffer, void *ptr)
691 if (!logbuffer->ptr_base)
692 logbuffer->ptr_base = (uintptr_t)ptr;
693 emit_svalue (logbuffer, (intptr_t)ptr - logbuffer->ptr_base);
694 assert (logbuffer->cursor <= logbuffer->buf_end);
698 emit_method_inner (LogBuffer *logbuffer, void *method)
700 if (!logbuffer->method_base) {
701 logbuffer->method_base = (intptr_t)method;
702 logbuffer->last_method = (intptr_t)method;
704 encode_sleb128 ((intptr_t)((char*)method - (char*)logbuffer->last_method), logbuffer->cursor, &logbuffer->cursor);
705 logbuffer->last_method = (intptr_t)method;
706 assert (logbuffer->cursor <= logbuffer->buf_end);
716 find_method (MonoDomain *domain, void *user_data)
718 MethodSearch *search = user_data;
723 MonoJitInfo *ji = mono_get_jit_info_from_method (domain, search->method);
725 // It could be AOT'd, so we need to get it from the AOT runtime's cache.
727 void *ip = mono_aot_get_method (domain, search->method);
729 // Avoid a slow path in mono_jit_info_table_find ().
731 ji = mono_jit_info_table_find (domain, ip);
740 register_method_local (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji)
742 if (!mono_conc_hashtable_lookup (prof->method_table, method)) {
744 * FIXME: In some cases, we crash while looking up JIT info for AOT'd methods.
745 * This usually happens for static constructors. This code is disabled for now
746 * as we don't need this info for anything critical.
748 * https://bugzilla.xamarin.com/show_bug.cgi?id=35171
752 MethodSearch search = { method, NULL };
754 mono_domain_foreach (find_method, &search);
761 * FIXME: We can't always find JIT info for a generic shared method, especially
762 * if we obtained the MonoMethod during an async stack walk. For now, we deal
763 * with this by giving the generic shared method name and dummy code start/size
764 * information (i.e. zeroes).
768 MethodInfo *info = (MethodInfo *)malloc (sizeof (MethodInfo));
770 info->method = method;
772 info->time = current_time ();
774 g_ptr_array_add (TLS_GET (GPtrArray, tlsmethodlist), info);
779 emit_method (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
781 register_method_local (prof, method, NULL);
782 emit_method_inner (logbuffer, method);
786 emit_method_as_ptr (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
788 register_method_local (prof, method, NULL);
789 emit_ptr (logbuffer, method);
793 emit_obj (LogBuffer *logbuffer, void *ptr)
795 if (!logbuffer->obj_base)
796 logbuffer->obj_base = (uintptr_t)ptr >> 3;
797 emit_svalue (logbuffer, ((uintptr_t)ptr >> 3) - logbuffer->obj_base);
798 assert (logbuffer->cursor <= logbuffer->buf_end);
802 emit_string (LogBuffer *logbuffer, const char *str, size_t size)
806 for (; i < size; i++) {
809 emit_byte (logbuffer, str [i]);
812 emit_byte (logbuffer, '\0');
816 emit_double (LogBuffer *logbuffer, double value)
819 unsigned char buffer[8];
820 memcpy (buffer, &value, 8);
821 #if G_BYTE_ORDER == G_BIG_ENDIAN
822 for (i = 7; i >= 0; i--)
824 for (i = 0; i < 8; i++)
826 emit_byte (logbuffer, buffer[i]);
830 write_int16 (char *buf, int32_t value)
833 for (i = 0; i < 2; ++i) {
841 write_int32 (char *buf, int32_t value)
844 for (i = 0; i < 4; ++i) {
852 write_int64 (char *buf, int64_t value)
855 for (i = 0; i < 8; ++i) {
863 dump_header (MonoProfiler *profiler)
867 p = write_int32 (p, LOG_HEADER_ID);
868 *p++ = LOG_VERSION_MAJOR;
869 *p++ = LOG_VERSION_MINOR;
870 *p++ = LOG_DATA_VERSION;
871 *p++ = sizeof (void*);
872 p = write_int64 (p, ((uint64_t)time (NULL)) * 1000); /* startup time */
873 p = write_int32 (p, get_timer_overhead ()); /* timer overhead */
874 p = write_int32 (p, 0); /* flags */
875 p = write_int32 (p, process_id ()); /* pid */
876 p = write_int16 (p, profiler->command_port); /* port */
877 p = write_int16 (p, 0); /* opsystem */
878 #if defined (HAVE_SYS_ZLIB)
879 if (profiler->gzfile) {
880 gzwrite (profiler->gzfile, hbuf, p - hbuf);
882 fwrite (hbuf, p - hbuf, 1, profiler->file);
885 fwrite (hbuf, p - hbuf, 1, profiler->file);
886 fflush (profiler->file);
891 send_buffer (MonoProfiler *prof, GPtrArray *methods, LogBuffer *buffer)
893 WriterQueueEntry *entry = (WriterQueueEntry *)calloc (1, sizeof (WriterQueueEntry));
894 mono_lock_free_queue_node_init (&entry->node, FALSE);
895 entry->methods = methods;
896 entry->buffer = buffer;
897 mono_lock_free_queue_enqueue (&prof->writer_queue, &entry->node);
898 mono_os_sem_post (&prof->writer_queue_sem);
902 dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
907 dump_buffer (profiler, buf->next);
908 p = write_int32 (p, BUF_ID);
909 p = write_int32 (p, buf->cursor - buf->buf);
910 p = write_int64 (p, buf->time_base);
911 p = write_int64 (p, buf->ptr_base);
912 p = write_int64 (p, buf->obj_base);
913 p = write_int64 (p, buf->thread_id);
914 p = write_int64 (p, buf->method_base);
915 #if defined (HAVE_SYS_ZLIB)
916 if (profiler->gzfile) {
917 gzwrite (profiler->gzfile, hbuf, p - hbuf);
918 gzwrite (profiler->gzfile, buf->buf, buf->cursor - buf->buf);
921 fwrite (hbuf, p - hbuf, 1, profiler->file);
922 fwrite (buf->buf, buf->cursor - buf->buf, 1, profiler->file);
923 fflush (profiler->file);
924 #if defined (HAVE_SYS_ZLIB)
927 free_buffer (buf, buf->size);
931 process_requests (MonoProfiler *profiler)
933 if (heapshot_requested)
934 mono_gc_collect (mono_gc_max_generation ());
937 static void counters_init (MonoProfiler *profiler);
938 static void counters_sample (MonoProfiler *profiler, uint64_t timestamp, gboolean threadless);
941 * Can be called only at safe callback locations.
944 safe_send (MonoProfiler *profiler, LogBuffer *logbuffer)
946 /* We need the runtime initialized so that we have threads and hazard
947 * pointers available. Otherwise, the lock free queue will not work and
948 * there won't be a thread to process the data.
950 * While the runtime isn't initialized, we just accumulate data in the
951 * thread local buffer list.
953 if (!InterlockedRead (&runtime_inited))
956 int cd = logbuffer->call_depth;
958 send_buffer (profiler, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
960 TLS_SET (tlsbuffer, NULL);
961 TLS_SET (tlsmethodlist, NULL);
965 TLS_GET (LogBuffer, tlsbuffer)->call_depth = cd;
969 safe_send_threadless (MonoProfiler *prof, LogBuffer *buf)
971 for (LogBuffer *iter = buf; iter; iter = iter->next)
974 safe_send (prof, buf);
978 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
981 uintptr_t last_offset = 0;
982 //const char *name = mono_class_get_name (klass);
983 LogBuffer *logbuffer = ensure_logbuf (
984 EVENT_SIZE /* event */ +
985 LEB128_SIZE /* obj */ +
986 LEB128_SIZE /* klass */ +
987 LEB128_SIZE /* size */ +
988 LEB128_SIZE /* num */ +
990 LEB128_SIZE /* offset */ +
991 LEB128_SIZE /* ref */
994 emit_byte (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
995 emit_obj (logbuffer, obj);
996 emit_ptr (logbuffer, klass);
997 /* account for object alignment in the heap */
1000 emit_value (logbuffer, size);
1001 emit_value (logbuffer, num);
1002 for (i = 0; i < num; ++i) {
1003 emit_value (logbuffer, offsets [i] - last_offset);
1004 last_offset = offsets [i];
1005 emit_obj (logbuffer, refs [i]);
1008 // printf ("obj: %p, klass: %s, refs: %d, size: %d\n", obj, name, (int)num, (int)size);
1012 static unsigned int hs_mode_ms = 0;
1013 static unsigned int hs_mode_gc = 0;
1014 static unsigned int hs_mode_ondemand = 0;
1015 static unsigned int gc_count = 0;
1016 static uint64_t last_hs_time = 0;
1019 heap_walk (MonoProfiler *profiler)
1023 LogBuffer *logbuffer;
1026 logbuffer = ensure_logbuf (
1027 EVENT_SIZE /* event */ +
1028 LEB128_SIZE /* time */
1030 now = current_time ();
1031 if (hs_mode_ms && (now - last_hs_time)/1000000 >= hs_mode_ms)
1033 else if (hs_mode_gc && (gc_count % hs_mode_gc) == 0)
1035 else if (hs_mode_ondemand)
1036 do_walk = heapshot_requested;
1037 else if (!hs_mode_ms && !hs_mode_gc && profiler->last_gc_gen_started == mono_gc_max_generation ())
1042 heapshot_requested = 0;
1043 emit_byte (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
1044 emit_time (logbuffer, now);
1045 mono_gc_walk_heap (0, gc_reference, NULL);
1046 logbuffer = ensure_logbuf (
1047 EVENT_SIZE /* event */ +
1048 LEB128_SIZE /* time */
1050 now = current_time ();
1051 emit_byte (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
1052 emit_time (logbuffer, now);
1057 gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation) {
1059 LogBuffer *logbuffer = ensure_logbuf (
1060 EVENT_SIZE /* event */ +
1061 LEB128_SIZE /* time */ +
1062 LEB128_SIZE /* gc event */ +
1063 LEB128_SIZE /* generation */
1065 now = current_time ();
1066 ENTER_LOG (logbuffer, "gcevent");
1067 emit_byte (logbuffer, TYPE_GC_EVENT | TYPE_GC);
1068 emit_time (logbuffer, now);
1069 emit_value (logbuffer, ev);
1070 emit_value (logbuffer, generation);
1071 /* to deal with nested gen1 after gen0 started */
1072 if (ev == MONO_GC_EVENT_START) {
1073 profiler->last_gc_gen_started = generation;
1074 if (generation == mono_gc_max_generation ())
1077 if (ev == MONO_GC_EVENT_PRE_START_WORLD)
1078 heap_walk (profiler);
1079 EXIT_LOG (logbuffer);
1080 if (ev == MONO_GC_EVENT_POST_START_WORLD)
1081 safe_send (profiler, logbuffer);
1082 //printf ("gc event %d for generation %d\n", ev, generation);
1086 gc_resize (MonoProfiler *profiler, int64_t new_size) {
1088 LogBuffer *logbuffer = ensure_logbuf (
1089 EVENT_SIZE /* event */ +
1090 LEB128_SIZE /* time */ +
1091 LEB128_SIZE /* new size */
1093 now = current_time ();
1094 ENTER_LOG (logbuffer, "gcresize");
1095 emit_byte (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
1096 emit_time (logbuffer, now);
1097 emit_value (logbuffer, new_size);
1098 //printf ("gc resized to %lld\n", new_size);
1099 EXIT_LOG (logbuffer);
1102 #define MAX_FRAMES 32
1105 MonoMethod* methods [MAX_FRAMES];
1106 int32_t il_offsets [MAX_FRAMES];
1107 int32_t native_offsets [MAX_FRAMES];
1109 static int num_frames = MAX_FRAMES;
1112 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
1114 FrameData *frame = (FrameData *)data;
1115 if (method && frame->count < num_frames) {
1116 frame->il_offsets [frame->count] = il_offset;
1117 frame->native_offsets [frame->count] = native_offset;
1118 frame->methods [frame->count++] = method;
1119 //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
1121 return frame->count == num_frames;
1125 * a note about stack walks: they can cause more profiler events to fire,
1126 * so we need to make sure they don't happen after we started emitting an
1127 * event, hence the collect_bt/emit_bt split.
1130 collect_bt (FrameData *data)
1133 mono_stack_walk_no_il (walk_stack, data);
1137 emit_bt (MonoProfiler *prof, LogBuffer *logbuffer, FrameData *data)
1139 /* FIXME: this is actually tons of data and we should
1140 * just output it the first time and use an id the next
1142 if (data->count > num_frames)
1143 printf ("bad num frames: %d\n", data->count);
1144 emit_value (logbuffer, 0); /* flags */
1145 emit_value (logbuffer, data->count);
1146 //if (*p != data.count) {
1147 // 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);}
1148 while (data->count) {
1149 emit_method_as_ptr (prof, logbuffer, data->methods [--data->count]);
1154 gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1158 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces)? TYPE_ALLOC_BT: 0;
1160 LogBuffer *logbuffer;
1161 len = mono_object_get_size (obj);
1162 /* account for object alignment in the heap */
1167 logbuffer = ensure_logbuf (
1168 EVENT_SIZE /* event */ +
1169 LEB128_SIZE /* time */ +
1170 LEB128_SIZE /* klass */ +
1171 LEB128_SIZE /* obj */ +
1172 LEB128_SIZE /* size */ +
1174 LEB128_SIZE /* flags */ +
1175 LEB128_SIZE /* count */ +
1177 LEB128_SIZE /* method */
1181 now = current_time ();
1182 ENTER_LOG (logbuffer, "gcalloc");
1183 emit_byte (logbuffer, do_bt | TYPE_ALLOC);
1184 emit_time (logbuffer, now);
1185 emit_ptr (logbuffer, klass);
1186 emit_obj (logbuffer, obj);
1187 emit_value (logbuffer, len);
1189 emit_bt (prof, logbuffer, &data);
1190 EXIT_LOG (logbuffer);
1191 if (logbuffer->next)
1192 safe_send (prof, logbuffer);
1193 process_requests (prof);
1194 //printf ("gc alloc %s at %p\n", mono_class_get_name (klass), obj);
1198 gc_moves (MonoProfiler *prof, void **objects, int num)
1202 LogBuffer *logbuffer = ensure_logbuf (
1203 EVENT_SIZE /* event */ +
1204 LEB128_SIZE /* time */ +
1205 LEB128_SIZE /* num */ +
1207 LEB128_SIZE /* object */
1210 now = current_time ();
1211 ENTER_LOG (logbuffer, "gcmove");
1212 emit_byte (logbuffer, TYPE_GC_MOVE | TYPE_GC);
1213 emit_time (logbuffer, now);
1214 emit_value (logbuffer, num);
1215 for (i = 0; i < num; ++i)
1216 emit_obj (logbuffer, objects [i]);
1217 //printf ("gc moved %d objects\n", num/2);
1218 EXIT_LOG (logbuffer);
1222 gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
1225 LogBuffer *logbuffer = ensure_logbuf (
1226 EVENT_SIZE /* event */ +
1227 LEB128_SIZE /* num */ +
1228 LEB128_SIZE /* collections */ +
1230 LEB128_SIZE /* object */ +
1231 LEB128_SIZE /* root type */ +
1232 LEB128_SIZE /* extra info */
1235 ENTER_LOG (logbuffer, "gcroots");
1236 emit_byte (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
1237 emit_value (logbuffer, num);
1238 emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
1239 for (i = 0; i < num; ++i) {
1240 emit_obj (logbuffer, objects [i]);
1241 emit_value (logbuffer, root_types [i]);
1242 emit_value (logbuffer, extra_info [i]);
1244 EXIT_LOG (logbuffer);
1248 gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
1250 int do_bt = nocalls && InterlockedRead (&runtime_inited) && !notraces;
1257 LogBuffer *logbuffer = ensure_logbuf (
1258 EVENT_SIZE /* event */ +
1259 LEB128_SIZE /* time */ +
1260 LEB128_SIZE /* type */ +
1261 LEB128_SIZE /* handle */ +
1262 (op == MONO_PROFILER_GC_HANDLE_CREATED ? (
1263 LEB128_SIZE /* obj */
1266 LEB128_SIZE /* flags */ +
1267 LEB128_SIZE /* count */ +
1269 LEB128_SIZE /* method */
1274 now = current_time ();
1275 ENTER_LOG (logbuffer, "gchandle");
1277 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1278 emit_byte (logbuffer, (do_bt ? TYPE_GC_HANDLE_CREATED_BT : TYPE_GC_HANDLE_CREATED) | TYPE_GC);
1279 else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
1280 emit_byte (logbuffer, (do_bt ? TYPE_GC_HANDLE_DESTROYED_BT : TYPE_GC_HANDLE_DESTROYED) | TYPE_GC);
1282 g_assert_not_reached ();
1284 emit_time (logbuffer, now);
1285 emit_value (logbuffer, type);
1286 emit_value (logbuffer, handle);
1288 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1289 emit_obj (logbuffer, obj);
1292 emit_bt (prof, logbuffer, &data);
1294 EXIT_LOG (logbuffer);
1295 process_requests (prof);
1299 push_nesting (char *p, MonoClass *klass)
1304 nesting = mono_class_get_nesting_type (klass);
1306 p = push_nesting (p, nesting);
1310 name = mono_class_get_name (klass);
1311 nspace = mono_class_get_namespace (klass);
1314 p += strlen (nspace);
1324 type_name (MonoClass *klass)
1328 push_nesting (buf, klass);
1329 p = (char *)malloc (strlen (buf) + 1);
1335 image_loaded (MonoProfiler *prof, MonoImage *image, int result)
1340 LogBuffer *logbuffer;
1341 if (result != MONO_PROFILE_OK)
1343 name = mono_image_get_filename (image);
1344 nlen = strlen (name) + 1;
1345 logbuffer = ensure_logbuf (
1346 EVENT_SIZE /* event */ +
1347 LEB128_SIZE /* time */ +
1348 EVENT_SIZE /* type */ +
1349 LEB128_SIZE /* image */ +
1350 LEB128_SIZE /* flags */ +
1353 now = current_time ();
1354 ENTER_LOG (logbuffer, "image");
1355 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1356 emit_time (logbuffer, now);
1357 emit_byte (logbuffer, TYPE_IMAGE);
1358 emit_ptr (logbuffer, image);
1359 emit_value (logbuffer, 0); /* flags */
1360 memcpy (logbuffer->cursor, name, nlen);
1361 logbuffer->cursor += nlen;
1362 //printf ("loaded image %p (%s)\n", image, name);
1363 EXIT_LOG (logbuffer);
1364 if (logbuffer->next)
1365 safe_send (prof, logbuffer);
1366 process_requests (prof);
1370 image_unloaded (MonoProfiler *prof, MonoImage *image)
1372 const char *name = mono_image_get_filename (image);
1373 int nlen = strlen (name) + 1;
1374 LogBuffer *logbuffer = ensure_logbuf (
1375 EVENT_SIZE /* event */ +
1376 LEB128_SIZE /* time */ +
1377 EVENT_SIZE /* type */ +
1378 LEB128_SIZE /* image */ +
1379 LEB128_SIZE /* flags */ +
1382 uint64_t now = current_time ();
1384 ENTER_LOG (logbuffer, "image-unload");
1385 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1386 emit_time (logbuffer, now);
1387 emit_byte (logbuffer, TYPE_IMAGE);
1388 emit_ptr (logbuffer, image);
1389 emit_value (logbuffer, 0); /* flags */
1390 memcpy (logbuffer->cursor, name, nlen);
1391 logbuffer->cursor += nlen;
1392 EXIT_LOG (logbuffer);
1394 if (logbuffer->next)
1395 safe_send (prof, logbuffer);
1397 process_requests (prof);
1401 assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly, int result)
1403 if (result != MONO_PROFILE_OK)
1406 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1407 int nlen = strlen (name) + 1;
1408 LogBuffer *logbuffer = ensure_logbuf (
1409 EVENT_SIZE /* event */ +
1410 LEB128_SIZE /* time */ +
1411 EVENT_SIZE /* type */ +
1412 LEB128_SIZE /* assembly */ +
1413 LEB128_SIZE /* flags */ +
1416 uint64_t now = current_time ();
1418 ENTER_LOG (logbuffer, "assembly-load");
1419 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1420 emit_time (logbuffer, now);
1421 emit_byte (logbuffer, TYPE_ASSEMBLY);
1422 emit_ptr (logbuffer, assembly);
1423 emit_value (logbuffer, 0); /* flags */
1424 memcpy (logbuffer->cursor, name, nlen);
1425 logbuffer->cursor += nlen;
1426 EXIT_LOG (logbuffer);
1430 if (logbuffer->next)
1431 safe_send (prof, logbuffer);
1433 process_requests (prof);
1437 assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
1439 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1440 int nlen = strlen (name) + 1;
1441 LogBuffer *logbuffer = ensure_logbuf (
1442 EVENT_SIZE /* event */ +
1443 LEB128_SIZE /* time */ +
1444 EVENT_SIZE /* type */ +
1445 LEB128_SIZE /* assembly */ +
1446 LEB128_SIZE /* flags */ +
1449 uint64_t now = current_time ();
1451 ENTER_LOG (logbuffer, "assembly-unload");
1452 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1453 emit_time (logbuffer, now);
1454 emit_byte (logbuffer, TYPE_ASSEMBLY);
1455 emit_ptr (logbuffer, assembly);
1456 emit_value (logbuffer, 0); /* flags */
1457 memcpy (logbuffer->cursor, name, nlen);
1458 logbuffer->cursor += nlen;
1459 EXIT_LOG (logbuffer);
1463 if (logbuffer->next)
1464 safe_send (prof, logbuffer);
1466 process_requests (prof);
1470 class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
1476 LogBuffer *logbuffer;
1477 if (result != MONO_PROFILE_OK)
1479 if (InterlockedRead (&runtime_inited))
1480 name = mono_type_get_name (mono_class_get_type (klass));
1482 name = type_name (klass);
1483 nlen = strlen (name) + 1;
1484 image = mono_class_get_image (klass);
1485 logbuffer = ensure_logbuf (
1486 EVENT_SIZE /* event */ +
1487 LEB128_SIZE /* time */ +
1488 EVENT_SIZE /* type */ +
1489 LEB128_SIZE /* klass */ +
1490 LEB128_SIZE /* image */ +
1491 LEB128_SIZE /* flags */ +
1494 now = current_time ();
1495 ENTER_LOG (logbuffer, "class");
1496 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1497 emit_time (logbuffer, now);
1498 emit_byte (logbuffer, TYPE_CLASS);
1499 emit_ptr (logbuffer, klass);
1500 emit_ptr (logbuffer, image);
1501 emit_value (logbuffer, 0); /* flags */
1502 memcpy (logbuffer->cursor, name, nlen);
1503 logbuffer->cursor += nlen;
1504 //printf ("loaded class %p (%s)\n", klass, name);
1509 EXIT_LOG (logbuffer);
1510 if (logbuffer->next)
1511 safe_send (prof, logbuffer);
1512 process_requests (prof);
1516 class_unloaded (MonoProfiler *prof, MonoClass *klass)
1520 if (InterlockedRead (&runtime_inited))
1521 name = mono_type_get_name (mono_class_get_type (klass));
1523 name = type_name (klass);
1525 int nlen = strlen (name) + 1;
1526 MonoImage *image = mono_class_get_image (klass);
1527 LogBuffer *logbuffer = ensure_logbuf (
1528 EVENT_SIZE /* event */ +
1529 LEB128_SIZE /* time */ +
1530 EVENT_SIZE /* type */ +
1531 LEB128_SIZE /* klass */ +
1532 LEB128_SIZE /* image */ +
1533 LEB128_SIZE /* flags */ +
1536 uint64_t now = current_time ();
1538 ENTER_LOG (logbuffer, "class-unload");
1539 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1540 emit_time (logbuffer, now);
1541 emit_byte (logbuffer, TYPE_CLASS);
1542 emit_ptr (logbuffer, klass);
1543 emit_ptr (logbuffer, image);
1544 emit_value (logbuffer, 0); /* flags */
1545 memcpy (logbuffer->cursor, name, nlen);
1546 logbuffer->cursor += nlen;
1547 EXIT_LOG (logbuffer);
1554 if (logbuffer->next)
1555 safe_send (prof, logbuffer);
1557 process_requests (prof);
1560 #ifndef DISABLE_HELPER_THREAD
1561 static void process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method);
1562 #endif /* DISABLE_HELPER_THREAD */
1565 method_enter (MonoProfiler *prof, MonoMethod *method)
1567 uint64_t now = current_time ();
1569 #ifndef DISABLE_HELPER_THREAD
1570 process_method_enter_coverage (prof, method);
1571 #endif /* DISABLE_HELPER_THREAD */
1573 LogBuffer *logbuffer = ensure_logbuf (
1574 EVENT_SIZE /* event */ +
1575 LEB128_SIZE /* time */ +
1576 LEB128_SIZE /* method */
1578 if (logbuffer->call_depth++ > max_call_depth)
1580 ENTER_LOG (logbuffer, "enter");
1581 emit_byte (logbuffer, TYPE_ENTER | TYPE_METHOD);
1582 emit_time (logbuffer, now);
1583 emit_method (prof, logbuffer, method);
1584 EXIT_LOG (logbuffer);
1586 process_requests (prof);
1590 method_leave (MonoProfiler *prof, MonoMethod *method)
1593 LogBuffer *logbuffer = ensure_logbuf (
1594 EVENT_SIZE /* event */ +
1595 LEB128_SIZE /* time */ +
1596 LEB128_SIZE /* method */
1598 if (--logbuffer->call_depth > max_call_depth)
1600 now = current_time ();
1601 ENTER_LOG (logbuffer, "leave");
1602 emit_byte (logbuffer, TYPE_LEAVE | TYPE_METHOD);
1603 emit_time (logbuffer, now);
1604 emit_method (prof, logbuffer, method);
1605 EXIT_LOG (logbuffer);
1606 if (logbuffer->next)
1607 safe_send (prof, logbuffer);
1608 process_requests (prof);
1612 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
1615 LogBuffer *logbuffer;
1618 logbuffer = ensure_logbuf (
1619 EVENT_SIZE /* event */ +
1620 LEB128_SIZE /* time */ +
1621 LEB128_SIZE /* method */
1623 if (--logbuffer->call_depth > max_call_depth)
1625 now = current_time ();
1626 ENTER_LOG (logbuffer, "eleave");
1627 emit_byte (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
1628 emit_time (logbuffer, now);
1629 emit_method (prof, logbuffer, method);
1630 EXIT_LOG (logbuffer);
1631 process_requests (prof);
1635 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji, int result)
1637 if (result != MONO_PROFILE_OK)
1640 register_method_local (prof, method, ji);
1642 process_requests (prof);
1646 code_buffer_new (MonoProfiler *prof, void *buffer, int size, MonoProfilerCodeBufferType type, void *data)
1651 LogBuffer *logbuffer;
1652 if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
1653 name = (char *)data;
1654 nlen = strlen (name) + 1;
1659 logbuffer = ensure_logbuf (
1660 EVENT_SIZE /* event */ +
1661 LEB128_SIZE /* time */ +
1662 LEB128_SIZE /* type */ +
1663 LEB128_SIZE /* buffer */ +
1664 LEB128_SIZE /* size */ +
1669 now = current_time ();
1670 ENTER_LOG (logbuffer, "code buffer");
1671 emit_byte (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
1672 emit_time (logbuffer, now);
1673 emit_value (logbuffer, type);
1674 emit_ptr (logbuffer, buffer);
1675 emit_value (logbuffer, size);
1677 memcpy (logbuffer->cursor, name, nlen);
1678 logbuffer->cursor += nlen;
1680 EXIT_LOG (logbuffer);
1681 process_requests (prof);
1685 throw_exc (MonoProfiler *prof, MonoObject *object)
1687 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces)? TYPE_EXCEPTION_BT: 0;
1690 LogBuffer *logbuffer;
1693 logbuffer = ensure_logbuf (
1694 EVENT_SIZE /* event */ +
1695 LEB128_SIZE /* time */ +
1696 LEB128_SIZE /* object */ +
1698 LEB128_SIZE /* flags */ +
1699 LEB128_SIZE /* count */ +
1701 LEB128_SIZE /* method */
1705 now = current_time ();
1706 ENTER_LOG (logbuffer, "throw");
1707 emit_byte (logbuffer, do_bt | TYPE_EXCEPTION);
1708 emit_time (logbuffer, now);
1709 emit_obj (logbuffer, object);
1711 emit_bt (prof, logbuffer, &data);
1712 EXIT_LOG (logbuffer);
1713 process_requests (prof);
1717 clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
1720 LogBuffer *logbuffer = ensure_logbuf (
1721 EVENT_SIZE /* event */ +
1722 LEB128_SIZE /* time */ +
1723 LEB128_SIZE /* clause type */ +
1724 LEB128_SIZE /* clause num */ +
1725 LEB128_SIZE /* method */
1727 now = current_time ();
1728 ENTER_LOG (logbuffer, "clause");
1729 emit_byte (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
1730 emit_time (logbuffer, now);
1731 emit_value (logbuffer, clause_type);
1732 emit_value (logbuffer, clause_num);
1733 emit_method (prof, logbuffer, method);
1734 EXIT_LOG (logbuffer);
1736 process_requests (prof);
1740 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
1742 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION)? TYPE_MONITOR_BT: 0;
1745 LogBuffer *logbuffer;
1748 logbuffer = ensure_logbuf (
1749 EVENT_SIZE /* event */ +
1750 LEB128_SIZE /* time */ +
1751 LEB128_SIZE /* object */ +
1753 LEB128_SIZE /* flags */ +
1754 LEB128_SIZE /* count */ +
1756 LEB128_SIZE /* method */
1760 now = current_time ();
1761 ENTER_LOG (logbuffer, "monitor");
1762 emit_byte (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
1763 emit_time (logbuffer, now);
1764 emit_obj (logbuffer, object);
1766 emit_bt (profiler, logbuffer, &data);
1767 EXIT_LOG (logbuffer);
1768 process_requests (profiler);
1772 thread_start (MonoProfiler *prof, uintptr_t tid)
1774 //printf ("thread start %p\n", (void*)tid);
1777 LogBuffer *logbuffer = ensure_logbuf (
1778 EVENT_SIZE /* event */ +
1779 LEB128_SIZE /* time */ +
1780 EVENT_SIZE /* type */ +
1781 LEB128_SIZE /* tid */ +
1782 LEB128_SIZE /* flags */
1784 uint64_t now = current_time ();
1786 ENTER_LOG (logbuffer, "thread-start");
1787 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1788 emit_time (logbuffer, now);
1789 emit_byte (logbuffer, TYPE_THREAD);
1790 emit_ptr (logbuffer, (void*) tid);
1791 emit_value (logbuffer, 0); /* flags */
1792 EXIT_LOG (logbuffer);
1794 if (logbuffer->next)
1795 safe_send (prof, logbuffer);
1797 process_requests (prof);
1801 thread_end (MonoProfiler *prof, uintptr_t tid)
1803 if (TLS_GET (LogBuffer, tlsbuffer)) {
1804 LogBuffer *logbuffer = ensure_logbuf (
1805 EVENT_SIZE /* event */ +
1806 LEB128_SIZE /* time */ +
1807 EVENT_SIZE /* type */ +
1808 LEB128_SIZE /* tid */ +
1809 LEB128_SIZE /* flags */
1811 uint64_t now = current_time ();
1813 ENTER_LOG (logbuffer, "thread-end");
1814 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1815 emit_time (logbuffer, now);
1816 emit_byte (logbuffer, TYPE_THREAD);
1817 emit_ptr (logbuffer, (void*) tid);
1818 emit_value (logbuffer, 0); /* flags */
1819 EXIT_LOG (logbuffer);
1821 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), logbuffer);
1823 /* Don't process requests as the thread is detached from the runtime. */
1826 TLS_SET (tlsbuffer, NULL);
1827 TLS_SET (tlsmethodlist, NULL);
1831 domain_loaded (MonoProfiler *prof, MonoDomain *domain, int result)
1833 if (result != MONO_PROFILE_OK)
1836 LogBuffer *logbuffer = ensure_logbuf (
1837 EVENT_SIZE /* event */ +
1838 LEB128_SIZE /* time */ +
1839 EVENT_SIZE /* type */ +
1840 LEB128_SIZE /* domain id */ +
1841 LEB128_SIZE /* flags */
1843 uint64_t now = current_time ();
1845 ENTER_LOG (logbuffer, "domain-start");
1846 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1847 emit_time (logbuffer, now);
1848 emit_byte (logbuffer, TYPE_DOMAIN);
1849 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1850 emit_value (logbuffer, 0); /* flags */
1851 EXIT_LOG (logbuffer);
1853 if (logbuffer->next)
1854 safe_send (prof, logbuffer);
1856 process_requests (prof);
1860 domain_unloaded (MonoProfiler *prof, MonoDomain *domain)
1862 LogBuffer *logbuffer = ensure_logbuf (
1863 EVENT_SIZE /* event */ +
1864 LEB128_SIZE /* time */ +
1865 EVENT_SIZE /* type */ +
1866 LEB128_SIZE /* domain id */ +
1867 LEB128_SIZE /* flags */
1869 uint64_t now = current_time ();
1871 ENTER_LOG (logbuffer, "domain-end");
1872 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1873 emit_time (logbuffer, now);
1874 emit_byte (logbuffer, TYPE_DOMAIN);
1875 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1876 emit_value (logbuffer, 0); /* flags */
1877 EXIT_LOG (logbuffer);
1879 if (logbuffer->next)
1880 safe_send (prof, logbuffer);
1882 process_requests (prof);
1886 domain_name (MonoProfiler *prof, MonoDomain *domain, const char *name)
1888 int nlen = strlen (name) + 1;
1889 LogBuffer *logbuffer = ensure_logbuf (
1890 EVENT_SIZE /* event */ +
1891 LEB128_SIZE /* time */ +
1892 EVENT_SIZE /* type */ +
1893 LEB128_SIZE /* domain id */ +
1894 LEB128_SIZE /* flags */ +
1897 uint64_t now = current_time ();
1899 ENTER_LOG (logbuffer, "domain-name");
1900 emit_byte (logbuffer, TYPE_METADATA);
1901 emit_time (logbuffer, now);
1902 emit_byte (logbuffer, TYPE_DOMAIN);
1903 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1904 emit_value (logbuffer, 0); /* flags */
1905 memcpy (logbuffer->cursor, name, nlen);
1906 logbuffer->cursor += nlen;
1907 EXIT_LOG (logbuffer);
1909 if (logbuffer->next)
1910 safe_send (prof, logbuffer);
1912 process_requests (prof);
1916 context_loaded (MonoProfiler *prof, MonoAppContext *context)
1918 LogBuffer *logbuffer = ensure_logbuf (
1919 EVENT_SIZE /* event */ +
1920 LEB128_SIZE /* time */ +
1921 EVENT_SIZE /* type */ +
1922 LEB128_SIZE /* context id */ +
1923 LEB128_SIZE /* flags */ +
1924 LEB128_SIZE /* domain id */
1926 uint64_t now = current_time ();
1928 ENTER_LOG (logbuffer, "context-start");
1929 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1930 emit_time (logbuffer, now);
1931 emit_byte (logbuffer, TYPE_CONTEXT);
1932 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
1933 emit_value (logbuffer, 0); /* flags */
1934 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
1935 EXIT_LOG (logbuffer);
1937 if (logbuffer->next)
1938 safe_send (prof, logbuffer);
1940 process_requests (prof);
1944 context_unloaded (MonoProfiler *prof, MonoAppContext *context)
1946 LogBuffer *logbuffer = ensure_logbuf (
1947 EVENT_SIZE /* event */ +
1948 LEB128_SIZE /* time */ +
1949 EVENT_SIZE /* type */ +
1950 LEB128_SIZE /* context id */ +
1951 LEB128_SIZE /* flags */ +
1952 LEB128_SIZE /* domain id */
1954 uint64_t now = current_time ();
1956 ENTER_LOG (logbuffer, "context-end");
1957 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1958 emit_time (logbuffer, now);
1959 emit_byte (logbuffer, TYPE_CONTEXT);
1960 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
1961 emit_value (logbuffer, 0); /* flags */
1962 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
1963 EXIT_LOG (logbuffer);
1965 if (logbuffer->next)
1966 safe_send (prof, logbuffer);
1968 process_requests (prof);
1972 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
1974 int len = strlen (name) + 1;
1976 LogBuffer *logbuffer;
1977 logbuffer = ensure_logbuf (
1978 EVENT_SIZE /* event */ +
1979 LEB128_SIZE /* time */ +
1980 EVENT_SIZE /* type */ +
1981 LEB128_SIZE /* tid */ +
1982 LEB128_SIZE /* flags */ +
1985 now = current_time ();
1986 ENTER_LOG (logbuffer, "tname");
1987 emit_byte (logbuffer, TYPE_METADATA);
1988 emit_time (logbuffer, now);
1989 emit_byte (logbuffer, TYPE_THREAD);
1990 emit_ptr (logbuffer, (void*)tid);
1991 emit_value (logbuffer, 0); /* flags */
1992 memcpy (logbuffer->cursor, name, len);
1993 logbuffer->cursor += len;
1994 EXIT_LOG (logbuffer);
1996 if (logbuffer->next)
1997 safe_send (prof, logbuffer);
1999 process_requests (prof);
2011 AsyncFrameInfo *data;
2015 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
2017 AsyncFrameData *frame = (AsyncFrameData *)data;
2018 if (frame->count < num_frames) {
2019 frame->data [frame->count].method = method;
2020 frame->data [frame->count].domain = domain;
2021 frame->data [frame->count].base_address = base_address;
2022 frame->data [frame->count].offset = offset;
2023 // printf ("In %d at %p (dom %p) (native: %p)\n", frame->count, method, domain, base_address);
2026 return frame->count == num_frames;
2030 (type | frame count), tid, time, ip, [method, domain, base address, offset] * frames
2032 #define SAMPLE_EVENT_SIZE_IN_SLOTS(FRAMES) (4 + (FRAMES) * 4)
2035 mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
2038 AsyncFrameInfo frames [num_frames];
2039 AsyncFrameData bt_data = { 0, &frames [0]};
2041 uintptr_t *data, *new_data, *old_data;
2047 now = current_time ();
2049 mono_stack_walk_async_safe (&async_walk_stack, context, &bt_data);
2051 elapsed = (now - profiler->startup_time) / 10000;
2055 snprintf (buf, sizeof (buf), "hit at %p in thread %p after %llu ms\n", ip, (void*)thread_id (), (unsigned long long int)elapsed/100);
2057 ign_res (write (2, buf, len));
2059 sbuf = profiler->stat_buffers;
2062 /* flush the buffer at 1 second intervals */
2063 if (sbuf->cursor > sbuf->buf && (elapsed - sbuf->buf [2]) > 100000) {
2066 /* overflow: 400 slots is a big enough number to reduce the chance of losing this event if many
2067 * threads hit this same spot at the same time
2069 if (timedout || (sbuf->cursor + 400 >= sbuf->buf_end)) {
2070 StatBuffer *oldsb, *foundsb;
2071 sbuf = create_stat_buffer ();
2073 oldsb = profiler->stat_buffers;
2075 foundsb = (StatBuffer *)InterlockedCompareExchangePointer ((void * volatile*)&profiler->stat_buffers, sbuf, oldsb);
2076 } while (foundsb != oldsb);
2078 ign_res (write (2, "overflow\n", 9));
2079 /* notify the helper thread */
2080 if (sbuf->next->next) {
2082 ign_res (write (profiler->pipes [1], &c, 1));
2084 ign_res (write (2, "notify\n", 7));
2088 old_data = sbuf->cursor;
2089 new_data = old_data + SAMPLE_EVENT_SIZE_IN_SLOTS (bt_data.count);
2090 if (new_data > sbuf->buf_end)
2091 return; /* Not enough room in buf to hold this event-- lost event */
2092 data = (uintptr_t *)InterlockedCompareExchangePointer ((void * volatile*)&sbuf->cursor, new_data, old_data);
2093 } while (data != old_data);
2095 old_data [0] = 1 | (sample_type << 16) | (bt_data.count << 8);
2096 old_data [1] = thread_id ();
2097 old_data [2] = elapsed;
2098 old_data [3] = (uintptr_t)ip;
2099 for (i = 0; i < bt_data.count; ++i) {
2100 old_data [4 + 4 * i + 0] = (uintptr_t)frames [i].method;
2101 old_data [4 + 4 * i + 1] = (uintptr_t)frames [i].domain;
2102 old_data [4 + 4 * i + 2] = (uintptr_t)frames [i].base_address;
2103 old_data [4 + 4 * i + 3] = (uintptr_t)frames [i].offset;
2107 static uintptr_t *code_pages = 0;
2108 static int num_code_pages = 0;
2109 static int size_code_pages = 0;
2110 #define CPAGE_SHIFT (9)
2111 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
2112 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
2113 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
2116 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
2119 uintptr_t start_pos;
2120 start_pos = (page >> CPAGE_SHIFT) % hsize;
2123 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
2125 } else if (!hash [i]) {
2132 } while (i != start_pos);
2133 /* should not happen */
2134 printf ("failed code page store\n");
2139 add_code_pointer (uintptr_t ip)
2142 if (num_code_pages * 2 >= size_code_pages) {
2144 uintptr_t old_size = size_code_pages;
2145 size_code_pages *= 2;
2146 if (size_code_pages == 0)
2147 size_code_pages = 16;
2148 n = (uintptr_t *)calloc (sizeof (uintptr_t) * size_code_pages, 1);
2149 for (i = 0; i < old_size; ++i) {
2151 add_code_page (n, size_code_pages, code_pages [i]);
2157 num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
2160 /* ELF code crashes on some systems. */
2161 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2164 dump_ubin (const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
2167 LogBuffer *logbuffer;
2169 len = strlen (filename) + 1;
2170 now = current_time ();
2171 logbuffer = ensure_logbuf (
2172 EVENT_SIZE /* event */ +
2173 LEB128_SIZE /* time */ +
2174 LEB128_SIZE /* load address */ +
2175 LEB128_SIZE /* offset */ +
2176 LEB128_SIZE /* size */ +
2177 nlen /* file name */
2179 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
2180 emit_time (logbuffer, now);
2181 emit_svalue (logbuffer, load_addr);
2182 emit_uvalue (logbuffer, offset);
2183 emit_uvalue (logbuffer, size);
2184 memcpy (logbuffer->cursor, filename, len);
2185 logbuffer->cursor += len;
2190 dump_usym (const char *name, uintptr_t value, uintptr_t size)
2192 LogBuffer *logbuffer;
2194 len = strlen (name) + 1;
2195 logbuffer = ensure_logbuf (
2196 EVENT_SIZE /* event */ +
2197 LEB128_SIZE /* value */ +
2198 LEB128_SIZE /* size */ +
2201 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
2202 emit_ptr (logbuffer, (void*)value);
2203 emit_value (logbuffer, size);
2204 memcpy (logbuffer->cursor, name, len);
2205 logbuffer->cursor += len;
2208 /* ELF code crashes on some systems. */
2209 //#if defined(ELFMAG0)
2212 #if SIZEOF_VOID_P == 4
2213 #define ELF_WSIZE 32
2215 #define ELF_WSIZE 64
2218 #define ElfW(type) _ElfW (Elf, ELF_WSIZE, type)
2219 #define _ElfW(e,w,t) _ElfW_1 (e, w, _##t)
2220 #define _ElfW_1(e,w,t) e##w##t
2224 dump_elf_symbols (ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
2227 for (i = 0; i < num_symbols; ++i) {
2229 sym = strtab + symbols [i].st_name;
2230 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
2232 //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
2233 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
2238 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
2245 ElfW(Shdr) *sheader;
2246 ElfW(Shdr) *shstrtabh;
2247 ElfW(Shdr) *symtabh = NULL;
2248 ElfW(Shdr) *strtabh = NULL;
2249 ElfW(Sym) *symbols = NULL;
2253 fd = open (filename, O_RDONLY);
2256 if (fstat (fd, &statb) != 0) {
2260 file_size = statb.st_size;
2261 data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
2263 if (data == MAP_FAILED)
2266 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2267 header->e_ident [EI_MAG1] != ELFMAG1 ||
2268 header->e_ident [EI_MAG2] != ELFMAG2 ||
2269 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2270 munmap (data, file_size);
2273 sheader = (void*)((char*)data + header->e_shoff);
2274 shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
2275 strtab = (const char*)data + shstrtabh->sh_offset;
2276 for (i = 0; i < header->e_shnum; ++i) {
2277 //printf ("section header: %d\n", sheader->sh_type);
2278 if (sheader->sh_type == SHT_SYMTAB) {
2280 strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
2281 /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
2284 sheader = (void*)((char*)sheader + header->e_shentsize);
2286 if (!symtabh || !strtabh) {
2287 munmap (data, file_size);
2290 strtab = (const char*)data + strtabh->sh_offset;
2291 num_symbols = symtabh->sh_size / symtabh->sh_entsize;
2292 symbols = (void*)((char*)data + symtabh->sh_offset);
2293 dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
2294 munmap (data, file_size);
2299 /* ELF code crashes on some systems. */
2300 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2303 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
2305 MonoProfiler *prof = data;
2307 const char *filename;
2309 char *a = (void*)info->dlpi_addr;
2311 ElfW(Dyn) *dyn = NULL;
2312 ElfW(Sym) *symtab = NULL;
2313 ElfW(Word) *hash_table = NULL;
2314 ElfW(Ehdr) *header = NULL;
2315 const char* strtab = NULL;
2316 for (obj = prof->binary_objects; obj; obj = obj->next) {
2320 filename = info->dlpi_name;
2323 if (!info->dlpi_addr && !filename [0]) {
2324 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
2330 obj = calloc (sizeof (BinaryObject), 1);
2331 obj->addr = (void*)info->dlpi_addr;
2332 obj->name = pstrdup (filename);
2333 obj->next = prof->binary_objects;
2334 prof->binary_objects = obj;
2335 //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
2337 for (i = 0; i < info->dlpi_phnum; ++i) {
2338 //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);
2339 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
2340 header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2341 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2342 header->e_ident [EI_MAG1] != ELFMAG1 ||
2343 header->e_ident [EI_MAG2] != ELFMAG2 ||
2344 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2347 dump_ubin (filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
2348 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
2349 dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2352 if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
2354 if (!info->dlpi_name || !info->dlpi_name[0])
2358 for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
2359 if (dyn [i].d_tag == DT_SYMTAB) {
2360 if (symtab && do_debug)
2361 printf ("multiple symtabs: %d\n", i);
2362 symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
2363 } else if (dyn [i].d_tag == DT_HASH) {
2364 hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
2365 } else if (dyn [i].d_tag == DT_STRTAB) {
2366 strtab = (const char*)(a + dyn [i].d_un.d_ptr);
2371 num_sym = hash_table [1];
2372 dump_elf_symbols (symtab, num_sym, strtab, (void*)info->dlpi_addr);
2377 load_binaries (MonoProfiler *prof)
2379 dl_iterate_phdr (elf_dl_callback, prof);
2384 load_binaries (MonoProfiler *prof)
2391 symbol_for (uintptr_t code)
2394 void *ip = (void*)code;
2396 if (dladdr (ip, &di)) {
2398 return di.dli_sname;
2401 names = backtrace_symbols (&ip, 1);
2403 const char* p = names [0];
2414 dump_unmanaged_coderefs (MonoProfiler *prof)
2417 const char* last_symbol;
2418 uintptr_t addr, page_end;
2420 if (load_binaries (prof))
2422 for (i = 0; i < size_code_pages; ++i) {
2424 if (!code_pages [i] || code_pages [i] & 1)
2427 addr = CPAGE_ADDR (code_pages [i]);
2428 page_end = addr + CPAGE_SIZE;
2429 code_pages [i] |= 1;
2430 /* we dump the symbols for the whole page */
2431 for (; addr < page_end; addr += 16) {
2432 sym = symbol_for (addr);
2433 if (sym && sym == last_symbol)
2438 dump_usym (sym, addr, 0); /* let's not guess the size */
2439 //printf ("found symbol at %p: %s\n", (void*)addr, sym);
2445 compare_sample_events (gconstpointer a, gconstpointer b)
2447 uintptr_t tid1 = (*(uintptr_t **) a) [1];
2448 uintptr_t tid2 = (*(uintptr_t **) b) [1];
2450 return tid1 > tid2 ? 1 :
2456 dump_sample_hits (MonoProfiler *prof, StatBuffer *sbuf)
2458 LogBuffer *logbuffer;
2462 dump_sample_hits (prof, sbuf->next);
2463 free_buffer (sbuf->next, sbuf->next->size);
2467 g_ptr_array_set_size (prof->sorted_sample_events, 0);
2469 for (uintptr_t *sample = sbuf->buf; sample < sbuf->cursor;) {
2470 int count = sample [0] & 0xff;
2471 int mbt_count = (sample [0] & 0xff00) >> 8;
2473 if (sample + SAMPLE_EVENT_SIZE_IN_SLOTS (mbt_count) > sbuf->cursor)
2476 g_ptr_array_add (prof->sorted_sample_events, sample);
2478 sample += count + 3 + 4 * mbt_count;
2481 g_ptr_array_sort (prof->sorted_sample_events, compare_sample_events);
2483 for (guint sidx = 0; sidx < prof->sorted_sample_events->len; sidx++) {
2484 uintptr_t *sample = (uintptr_t *)g_ptr_array_index (prof->sorted_sample_events, sidx);
2485 int count = sample [0] & 0xff;
2486 int mbt_count = (sample [0] & 0xff00) >> 8;
2487 int type = sample [0] >> 16;
2488 uintptr_t *managed_sample_base = sample + count + 3;
2489 uintptr_t thread_id = sample [1];
2491 for (int i = 0; i < mbt_count; ++i) {
2492 MonoMethod *method = (MonoMethod*)managed_sample_base [i * 4 + 0];
2493 MonoDomain *domain = (MonoDomain*)managed_sample_base [i * 4 + 1];
2494 void *address = (void*)managed_sample_base [i * 4 + 2];
2498 MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *)address);
2501 managed_sample_base [i * 4 + 0] = (uintptr_t)mono_jit_info_get_method (ji);
2505 logbuffer = ensure_logbuf (
2506 EVENT_SIZE /* event */ +
2507 LEB128_SIZE /* type */ +
2508 LEB128_SIZE /* time */ +
2509 LEB128_SIZE /* tid */ +
2510 LEB128_SIZE /* count */ +
2512 LEB128_SIZE /* ip */
2514 LEB128_SIZE /* managed count */ +
2516 LEB128_SIZE /* method */ +
2517 LEB128_SIZE /* il offset */ +
2518 LEB128_SIZE /* native offset */
2521 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
2522 emit_value (logbuffer, type);
2523 emit_uvalue (logbuffer, prof->startup_time + (uint64_t)sample [2] * (uint64_t)10000);
2524 emit_ptr (logbuffer, (void *) thread_id);
2525 emit_value (logbuffer, count);
2526 for (int i = 0; i < count; ++i) {
2527 emit_ptr (logbuffer, (void*)sample [i + 3]);
2528 add_code_pointer (sample [i + 3]);
2531 sample += count + 3;
2532 /* new in data version 6 */
2533 emit_uvalue (logbuffer, mbt_count);
2534 for (int i = 0; i < mbt_count; ++i) {
2535 MonoMethod *method = (MonoMethod *) sample [i * 4 + 0];
2536 uintptr_t native_offset = sample [i * 4 + 3];
2538 emit_method (prof, logbuffer, method);
2539 emit_svalue (logbuffer, 0); /* il offset will always be 0 from now on */
2540 emit_svalue (logbuffer, native_offset);
2544 dump_unmanaged_coderefs (prof);
2550 mono_cpu_count (void)
2552 #ifdef PLATFORM_ANDROID
2553 /* Android tries really hard to save power by powering off CPUs on SMP phones which
2554 * means the normal way to query cpu count returns a wrong value with userspace API.
2555 * Instead we use /sys entries to query the actual hardware CPU count.
2558 char buffer[8] = {'\0'};
2559 int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
2560 /* Format of the /sys entry is a cpulist of indexes which in the case
2561 * of present is always of the form "0-(n-1)" when there is more than
2562 * 1 core, n being the number of CPU cores in the system. Otherwise
2563 * the value is simply 0
2565 if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
2566 count = strtol (((char*)buffer) + 2, NULL, 10);
2573 #if defined(HOST_ARM) || defined (HOST_ARM64)
2575 /* ARM platforms tries really hard to save power by powering off CPUs on SMP phones which
2576 * means the normal way to query cpu count returns a wrong value with userspace API. */
2578 #ifdef _SC_NPROCESSORS_CONF
2580 int count = sysconf (_SC_NPROCESSORS_CONF);
2588 #ifdef HAVE_SCHED_GETAFFINITY
2591 if (sched_getaffinity (getpid (), sizeof (set), &set) == 0)
2592 return CPU_COUNT (&set);
2595 #ifdef _SC_NPROCESSORS_ONLN
2597 int count = sysconf (_SC_NPROCESSORS_ONLN);
2603 #endif /* defined(HOST_ARM) || defined (HOST_ARM64) */
2609 size_t len = sizeof (int);
2612 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
2619 GetSystemInfo (&info);
2620 return info.dwNumberOfProcessors;
2629 unsigned int prev_pos;
2631 struct perf_event_mmap_page *page_desc;
2634 static PerfData *perf_data = NULL;
2635 static int num_perf;
2636 #define PERF_PAGES_SHIFT 4
2637 static int num_pages = 1 << PERF_PAGES_SHIFT;
2638 static unsigned int mmap_mask;
2641 struct perf_event_header h;
2651 perf_event_syscall (struct perf_event_attr *attr, pid_t pid, int cpu, int group_fd, unsigned long flags)
2653 attr->size = PERF_ATTR_SIZE_VER0;
2654 //printf ("perf attr size: %d\n", attr->size);
2655 #if defined(__x86_64__)
2656 return syscall(/*__NR_perf_event_open*/ 298, attr, pid, cpu, group_fd, flags);
2657 #elif defined(__i386__)
2658 return syscall(/*__NR_perf_event_open*/ 336, attr, pid, cpu, group_fd, flags);
2659 #elif defined(__arm__) || defined (__aarch64__)
2660 return syscall(/*__NR_perf_event_open*/ 364, attr, pid, cpu, group_fd, flags);
2667 setup_perf_map (PerfData *perf)
2669 perf->mmap_base = mmap (NULL, (num_pages + 1) * getpagesize (), PROT_READ|PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
2670 if (perf->mmap_base == MAP_FAILED) {
2672 printf ("failed mmap\n");
2675 perf->page_desc = perf->mmap_base;
2677 printf ("mmap version: %d\n", perf->page_desc->version);
2682 dump_perf_hits (MonoProfiler *prof, void *buf, int size)
2684 LogBuffer *logbuffer;
2687 void *end = (char*)buf + size;
2689 int pid = getpid ();
2695 if (pid != s->pid) {
2697 printf ("event for different pid: %d\n", s->pid);
2698 buf = (char*)buf + s->h.size;
2701 /*ip = (void*)s->ip;
2702 printf ("sample: %d, size: %d, ip: %p (%s), timestamp: %llu, nframes: %llu\n",
2703 s->h.type, s->h.size, ip, symbol_for (ip), s->timestamp, s->nframes);*/
2704 logbuffer = ensure_logbuf (
2705 EVENT_SIZE /* event */ +
2706 LEB128_SIZE /* type */ +
2707 LEB128_SIZE /* time */ +
2708 LEB128_SIZE /* tid */ +
2709 LEB128_SIZE /* count */ +
2711 LEB128_SIZE /* ip */
2713 LEB128_SIZE /* managed count */ +
2715 LEB128_SIZE /* method */ +
2716 LEB128_SIZE /* il offset */ +
2717 LEB128_SIZE /* native offset */
2720 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
2721 emit_value (logbuffer, sample_type);
2722 emit_uvalue (logbuffer, s->timestamp - prof->startup_time);
2724 * No useful thread ID to write here, since throughout the
2725 * profiler we use pthread_self () but the ID we get from
2726 * perf is the kernel's thread ID.
2728 emit_ptr (logbuffer, 0);
2729 emit_value (logbuffer, count);
2730 emit_ptr (logbuffer, (void*)(uintptr_t)s->ip);
2731 add_code_pointer (s->ip);
2732 /* no support here yet for the managed backtrace */
2733 emit_uvalue (logbuffer, mbt_count);
2734 buf = (char*)buf + s->h.size;
2738 printf ("dumped %d samples\n", samples);
2739 dump_unmanaged_coderefs (prof);
2742 /* read events from the ring buffer */
2744 read_perf_mmap (MonoProfiler* prof, int cpu)
2746 PerfData *perf = perf_data + cpu;
2748 unsigned char *data = (unsigned char*)perf->mmap_base + getpagesize ();
2749 unsigned int head = perf->page_desc->data_head;
2753 mono_memory_read_barrier ();
2755 old = perf->prev_pos;
2759 printf ("lost mmap events: old: %d, head: %d\n", old, head);
2763 if ((old & mmap_mask) + size != (head & mmap_mask)) {
2764 buf = data + (old & mmap_mask);
2765 size = mmap_mask + 1 - (old & mmap_mask);
2767 /* size bytes at buf */
2769 printf ("found1 bytes of events: %d\n", size);
2770 dump_perf_hits (prof, buf, size);
2772 buf = data + (old & mmap_mask);
2774 /* size bytes at buf */
2776 printf ("found bytes of events: %d\n", size);
2777 dump_perf_hits (prof, buf, size);
2779 perf->prev_pos = old;
2780 perf->page_desc->data_tail = old;
2785 setup_perf_event_for_cpu (PerfData *perf, int cpu)
2787 struct perf_event_attr attr;
2788 memset (&attr, 0, sizeof (attr));
2789 attr.type = PERF_TYPE_HARDWARE;
2790 switch (sample_type) {
2791 case SAMPLE_CYCLES: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2792 case SAMPLE_INSTRUCTIONS: attr.config = PERF_COUNT_HW_INSTRUCTIONS; break;
2793 case SAMPLE_CACHE_MISSES: attr.config = PERF_COUNT_HW_CACHE_MISSES; break;
2794 case SAMPLE_CACHE_REFS: attr.config = PERF_COUNT_HW_CACHE_REFERENCES; break;
2795 case SAMPLE_BRANCHES: attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS; break;
2796 case SAMPLE_BRANCH_MISSES: attr.config = PERF_COUNT_HW_BRANCH_MISSES; break;
2797 default: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2799 attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD | PERF_SAMPLE_TIME;
2800 // attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
2801 attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING | PERF_FORMAT_ID;
2804 attr.sample_freq = sample_freq;
2806 perf->perf_fd = perf_event_syscall (&attr, getpid (), cpu, -1, 0);
2808 printf ("perf fd: %d, freq: %d, event: %llu\n", perf->perf_fd, sample_freq, attr.config);
2809 if (perf->perf_fd < 0) {
2810 if (perf->perf_fd == -EPERM) {
2811 fprintf (stderr, "Perf syscall denied, do \"echo 1 > /proc/sys/kernel/perf_event_paranoid\" as root to enable.\n");
2814 perror ("open perf event");
2818 if (!setup_perf_map (perf)) {
2819 close (perf->perf_fd);
2827 setup_perf_event (void)
2830 mmap_mask = num_pages * getpagesize () - 1;
2831 num_perf = mono_cpu_count ();
2832 perf_data = calloc (num_perf, sizeof (PerfData));
2833 for (i = 0; i < num_perf; ++i) {
2834 count += setup_perf_event_for_cpu (perf_data + i, i);
2843 #endif /* USE_PERF_EVENTS */
2845 #ifndef DISABLE_HELPER_THREAD
2847 typedef struct MonoCounterAgent {
2848 MonoCounter *counter;
2849 // MonoCounterAgent specific data :
2854 struct MonoCounterAgent *next;
2857 static MonoCounterAgent* counters;
2858 static gboolean counters_initialized = FALSE;
2859 static int counters_index = 1;
2860 static mono_mutex_t counters_mutex;
2863 counters_add_agent (MonoCounter *counter)
2865 MonoCounterAgent *agent, *item;
2867 if (!counters_initialized)
2870 mono_os_mutex_lock (&counters_mutex);
2872 for (agent = counters; agent; agent = agent->next) {
2873 if (agent->counter == counter) {
2874 agent->value_size = 0;
2876 free (agent->value);
2877 agent->value = NULL;
2879 mono_os_mutex_unlock (&counters_mutex);
2884 agent = (MonoCounterAgent *)malloc (sizeof (MonoCounterAgent));
2885 agent->counter = counter;
2886 agent->value = NULL;
2887 agent->value_size = 0;
2888 agent->index = counters_index++;
2901 mono_os_mutex_unlock (&counters_mutex);
2905 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
2907 counters_add_agent (counter);
2912 counters_init (MonoProfiler *profiler)
2914 assert (!counters_initialized);
2916 mono_os_mutex_init (&counters_mutex);
2918 counters_initialized = TRUE;
2920 mono_counters_on_register (&counters_add_agent);
2921 mono_counters_foreach (counters_init_foreach_callback, NULL);
2925 counters_emit (MonoProfiler *profiler, gboolean threadless)
2927 MonoCounterAgent *agent;
2928 LogBuffer *logbuffer;
2931 EVENT_SIZE /* event */ +
2932 LEB128_SIZE /* len */
2935 if (!counters_initialized)
2938 mono_os_mutex_lock (&counters_mutex);
2940 for (agent = counters; agent; agent = agent->next) {
2945 LEB128_SIZE /* section */ +
2946 strlen (mono_counter_get_name (agent->counter)) + 1 /* name */ +
2947 LEB128_SIZE /* type */ +
2948 LEB128_SIZE /* unit */ +
2949 LEB128_SIZE /* variance */ +
2950 LEB128_SIZE /* index */
2957 mono_os_mutex_unlock (&counters_mutex);
2961 logbuffer = ensure_logbuf (size);
2963 ENTER_LOG (logbuffer, "counters");
2964 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2965 emit_value (logbuffer, len);
2966 for (agent = counters; agent; agent = agent->next) {
2972 name = mono_counter_get_name (agent->counter);
2973 emit_value (logbuffer, mono_counter_get_section (agent->counter));
2974 emit_string (logbuffer, name, strlen (name) + 1);
2975 emit_value (logbuffer, mono_counter_get_type (agent->counter));
2976 emit_value (logbuffer, mono_counter_get_unit (agent->counter));
2977 emit_value (logbuffer, mono_counter_get_variance (agent->counter));
2978 emit_value (logbuffer, agent->index);
2982 EXIT_LOG (logbuffer);
2985 safe_send_threadless (profiler, logbuffer);
2987 safe_send (profiler, logbuffer);
2989 mono_os_mutex_unlock (&counters_mutex);
2993 counters_sample (MonoProfiler *profiler, uint64_t timestamp, gboolean threadless)
2995 MonoCounterAgent *agent;
2996 MonoCounter *counter;
2997 LogBuffer *logbuffer;
3003 if (!counters_initialized)
3006 counters_emit (profiler, threadless);
3009 buffer = calloc (1, buffer_size);
3011 mono_os_mutex_lock (&counters_mutex);
3014 EVENT_SIZE /* event */ +
3015 LEB128_SIZE /* time */
3018 for (agent = counters; agent; agent = agent->next) {
3020 LEB128_SIZE /* index */ +
3021 LEB128_SIZE /* type */ +
3022 mono_counter_get_size (agent->counter) /* value */
3027 LEB128_SIZE /* stop marker */
3030 logbuffer = ensure_logbuf (size);
3032 ENTER_LOG (logbuffer, "counters");
3033 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
3034 emit_uvalue (logbuffer, timestamp);
3035 for (agent = counters; agent; agent = agent->next) {
3038 counter = agent->counter;
3040 size = mono_counter_get_size (counter);
3042 continue; // FIXME error
3043 } else if (size > buffer_size) {
3045 buffer = realloc (buffer, buffer_size);
3048 memset (buffer, 0, buffer_size);
3050 if (mono_counters_sample (counter, buffer, size) < 0)
3051 continue; // FIXME error
3053 type = mono_counter_get_type (counter);
3055 if (!agent->value) {
3056 agent->value = calloc (1, size);
3057 agent->value_size = size;
3059 if (type == MONO_COUNTER_STRING) {
3060 if (strcmp (agent->value, buffer) == 0)
3063 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
3068 emit_uvalue (logbuffer, agent->index);
3069 emit_uvalue (logbuffer, type);
3071 case MONO_COUNTER_INT:
3072 #if SIZEOF_VOID_P == 4
3073 case MONO_COUNTER_WORD:
3075 emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
3077 case MONO_COUNTER_UINT:
3078 emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
3080 case MONO_COUNTER_TIME_INTERVAL:
3081 case MONO_COUNTER_LONG:
3082 #if SIZEOF_VOID_P == 8
3083 case MONO_COUNTER_WORD:
3085 emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
3087 case MONO_COUNTER_ULONG:
3088 emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
3090 case MONO_COUNTER_DOUBLE:
3091 emit_double (logbuffer, *(double*)buffer);
3093 case MONO_COUNTER_STRING:
3095 emit_byte (logbuffer, 0);
3097 emit_byte (logbuffer, 1);
3098 emit_string (logbuffer, (char*)buffer, size);
3105 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
3106 agent->value = realloc (agent->value, size);
3107 agent->value_size = size;
3111 memcpy (agent->value, buffer, size);
3115 emit_value (logbuffer, 0);
3116 EXIT_LOG (logbuffer);
3119 safe_send_threadless (profiler, logbuffer);
3121 safe_send (profiler, logbuffer);
3123 mono_os_mutex_unlock (&counters_mutex);
3126 typedef struct _PerfCounterAgent PerfCounterAgent;
3127 struct _PerfCounterAgent {
3128 PerfCounterAgent *next;
3130 char *category_name;
3139 static PerfCounterAgent *perfcounters = NULL;
3142 perfcounters_emit (MonoProfiler *profiler, gboolean threadless)
3144 PerfCounterAgent *pcagent;
3145 LogBuffer *logbuffer;
3148 EVENT_SIZE /* event */ +
3149 LEB128_SIZE /* len */
3152 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3153 if (pcagent->emitted)
3157 LEB128_SIZE /* section */ +
3158 strlen (pcagent->category_name) + 1 /* category name */ +
3159 strlen (pcagent->name) + 1 /* name */ +
3160 LEB128_SIZE /* type */ +
3161 LEB128_SIZE /* unit */ +
3162 LEB128_SIZE /* variance */ +
3163 LEB128_SIZE /* index */
3172 logbuffer = ensure_logbuf (size);
3174 ENTER_LOG (logbuffer, "perfcounters");
3175 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
3176 emit_value (logbuffer, len);
3177 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3178 if (pcagent->emitted)
3181 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
3182 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
3183 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
3184 emit_value (logbuffer, MONO_COUNTER_LONG);
3185 emit_value (logbuffer, MONO_COUNTER_RAW);
3186 emit_value (logbuffer, MONO_COUNTER_VARIABLE);
3187 emit_value (logbuffer, pcagent->index);
3189 pcagent->emitted = 1;
3191 EXIT_LOG (logbuffer);
3194 safe_send_threadless (profiler, logbuffer);
3196 safe_send (profiler, logbuffer);
3200 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
3202 PerfCounterAgent *pcagent;
3204 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3205 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
3207 if (pcagent->value == value)
3210 pcagent->value = value;
3211 pcagent->updated = 1;
3212 pcagent->deleted = 0;
3216 pcagent = g_new0 (PerfCounterAgent, 1);
3217 pcagent->next = perfcounters;
3218 pcagent->index = counters_index++;
3219 pcagent->category_name = g_strdup (category_name);
3220 pcagent->name = g_strdup (name);
3221 pcagent->type = (int) type;
3222 pcagent->value = value;
3223 pcagent->emitted = 0;
3224 pcagent->updated = 1;
3225 pcagent->deleted = 0;
3227 perfcounters = pcagent;
3233 perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp, gboolean threadless)
3235 PerfCounterAgent *pcagent;
3236 LogBuffer *logbuffer;
3239 if (!counters_initialized)
3242 mono_os_mutex_lock (&counters_mutex);
3244 /* mark all perfcounters as deleted, foreach will unmark them as necessary */
3245 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
3246 pcagent->deleted = 1;
3248 mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
3250 perfcounters_emit (profiler, threadless);
3253 EVENT_SIZE /* event */ +
3254 LEB128_SIZE /* time */
3257 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3258 if (pcagent->deleted || !pcagent->updated)
3262 LEB128_SIZE /* index */ +
3263 LEB128_SIZE /* type */ +
3264 LEB128_SIZE /* value */
3269 LEB128_SIZE /* stop marker */
3272 logbuffer = ensure_logbuf (size);
3274 ENTER_LOG (logbuffer, "perfcounters");
3275 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
3276 emit_uvalue (logbuffer, timestamp);
3277 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3278 if (pcagent->deleted || !pcagent->updated)
3280 emit_uvalue (logbuffer, pcagent->index);
3281 emit_uvalue (logbuffer, MONO_COUNTER_LONG);
3282 emit_svalue (logbuffer, pcagent->value);
3284 pcagent->updated = 0;
3287 emit_value (logbuffer, 0);
3288 EXIT_LOG (logbuffer);
3291 safe_send_threadless (profiler, logbuffer);
3293 safe_send (profiler, logbuffer);
3295 mono_os_mutex_unlock (&counters_mutex);
3299 counters_and_perfcounters_sample (MonoProfiler *prof, gboolean threadless)
3301 static uint64_t start = -1;
3305 start = current_time ();
3307 now = current_time ();
3308 counters_sample (prof, (now - start) / 1000/ 1000, threadless);
3309 perfcounters_sample (prof, (now - start) / 1000/ 1000, threadless);
3312 #define COVERAGE_DEBUG(x) if (debug_coverage) {x}
3313 static mono_mutex_t coverage_mutex;
3314 static MonoConcurrentHashTable *coverage_methods = NULL;
3315 static MonoConcurrentHashTable *coverage_assemblies = NULL;
3316 static MonoConcurrentHashTable *coverage_classes = NULL;
3318 static MonoConcurrentHashTable *filtered_classes = NULL;
3319 static MonoConcurrentHashTable *entered_methods = NULL;
3320 static MonoConcurrentHashTable *image_to_methods = NULL;
3321 static MonoConcurrentHashTable *suppressed_assemblies = NULL;
3322 static gboolean coverage_initialized = FALSE;
3324 static GPtrArray *coverage_data = NULL;
3325 static int previous_offset = 0;
3327 typedef struct _MethodNode MethodNode;
3328 struct _MethodNode {
3329 MonoLockFreeQueueNode node;
3333 typedef struct _CoverageEntry CoverageEntry;
3334 struct _CoverageEntry {
3343 free_coverage_entry (gpointer data, gpointer userdata)
3345 CoverageEntry *entry = (CoverageEntry *)data;
3346 g_free (entry->filename);
3351 obtain_coverage_for_method (MonoProfiler *prof, const MonoProfileCoverageEntry *entry)
3353 int offset = entry->iloffset - previous_offset;
3354 CoverageEntry *e = g_new (CoverageEntry, 1);
3356 previous_offset = entry->iloffset;
3359 e->counter = entry->counter;
3360 e->filename = g_strdup(entry->filename ? entry->filename : "");
3361 e->line = entry->line;
3362 e->column = entry->col;
3364 g_ptr_array_add (coverage_data, e);
3368 parse_generic_type_names(char *name)
3370 char *new_name, *ret;
3371 int within_generic_declaration = 0, generic_members = 1;
3373 if (name == NULL || *name == '\0')
3374 return g_strdup ("");
3376 if (!(ret = new_name = (char *)calloc (strlen (name) * 4 + 1, sizeof (char))))
3382 within_generic_declaration = 1;
3386 within_generic_declaration = 0;
3388 if (*(name - 1) != '<') {
3390 *new_name++ = '0' + generic_members;
3392 memcpy (new_name, "<>", 8);
3396 generic_members = 0;
3404 if (!within_generic_declaration)
3405 *new_name++ = *name;
3414 static int method_id;
3416 build_method_buffer (gpointer key, gpointer value, gpointer userdata)
3418 MonoMethod *method = (MonoMethod *)value;
3419 MonoProfiler *prof = (MonoProfiler *)userdata;
3423 const char *image_name, *method_name, *sig, *first_filename;
3424 LogBuffer *logbuffer;
3427 previous_offset = 0;
3428 coverage_data = g_ptr_array_new ();
3430 mono_profiler_coverage_get (prof, method, obtain_coverage_for_method);
3432 klass = mono_method_get_class (method);
3433 image = mono_class_get_image (klass);
3434 image_name = mono_image_get_name (image);
3436 sig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3437 class_name = parse_generic_type_names (mono_type_get_name (mono_class_get_type (klass)));
3438 method_name = mono_method_get_name (method);
3440 if (coverage_data->len != 0) {
3441 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[0];
3442 first_filename = entry->filename ? entry->filename : "";
3444 first_filename = "";
3446 image_name = image_name ? image_name : "";
3447 sig = sig ? sig : "";
3448 method_name = method_name ? method_name : "";
3450 logbuffer = ensure_logbuf (
3451 EVENT_SIZE /* event */ +
3452 strlen (image_name) + 1 /* image name */ +
3453 strlen (class_name) + 1 /* class name */ +
3454 strlen (method_name) + 1 /* method name */ +
3455 strlen (sig) + 1 /* signature */ +
3456 strlen (first_filename) + 1 /* first file name */ +
3457 LEB128_SIZE /* token */ +
3458 LEB128_SIZE /* method id */ +
3459 LEB128_SIZE /* entries */
3461 ENTER_LOG (logbuffer, "coverage-methods");
3463 emit_byte (logbuffer, TYPE_COVERAGE_METHOD | TYPE_COVERAGE);
3464 emit_string (logbuffer, image_name, strlen (image_name) + 1);
3465 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3466 emit_string (logbuffer, method_name, strlen (method_name) + 1);
3467 emit_string (logbuffer, sig, strlen (sig) + 1);
3468 emit_string (logbuffer, first_filename, strlen (first_filename) + 1);
3470 emit_uvalue (logbuffer, mono_method_get_token (method));
3471 emit_uvalue (logbuffer, method_id);
3472 emit_value (logbuffer, coverage_data->len);
3474 EXIT_LOG (logbuffer);
3475 safe_send (prof, logbuffer);
3477 for (i = 0; i < coverage_data->len; i++) {
3478 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[i];
3480 logbuffer = ensure_logbuf (
3481 EVENT_SIZE /* event */ +
3482 LEB128_SIZE /* method id */ +
3483 LEB128_SIZE /* offset */ +
3484 LEB128_SIZE /* counter */ +
3485 LEB128_SIZE /* line */ +
3486 LEB128_SIZE /* column */
3488 ENTER_LOG (logbuffer, "coverage-statement");
3490 emit_byte (logbuffer, TYPE_COVERAGE_STATEMENT | TYPE_COVERAGE);
3491 emit_uvalue (logbuffer, method_id);
3492 emit_uvalue (logbuffer, entry->offset);
3493 emit_uvalue (logbuffer, entry->counter);
3494 emit_uvalue (logbuffer, entry->line);
3495 emit_uvalue (logbuffer, entry->column);
3497 EXIT_LOG (logbuffer);
3498 safe_send (prof, logbuffer);
3503 g_free (class_name);
3505 g_ptr_array_foreach (coverage_data, free_coverage_entry, NULL);
3506 g_ptr_array_free (coverage_data, TRUE);
3507 coverage_data = NULL;
3510 /* This empties the queue */
3512 count_queue (MonoLockFreeQueue *queue)
3514 MonoLockFreeQueueNode *node;
3517 while ((node = mono_lock_free_queue_dequeue (queue))) {
3519 mono_thread_hazardous_try_free (node, free);
3526 build_class_buffer (gpointer key, gpointer value, gpointer userdata)
3528 MonoClass *klass = (MonoClass *)key;
3529 MonoLockFreeQueue *class_methods = (MonoLockFreeQueue *)value;
3530 MonoProfiler *prof = (MonoProfiler *)userdata;
3533 const char *assembly_name;
3534 int number_of_methods, partially_covered;
3535 guint fully_covered;
3536 LogBuffer *logbuffer;
3538 image = mono_class_get_image (klass);
3539 assembly_name = mono_image_get_name (image);
3540 class_name = mono_type_get_name (mono_class_get_type (klass));
3542 assembly_name = assembly_name ? assembly_name : "";
3543 number_of_methods = mono_class_num_methods (klass);
3544 fully_covered = count_queue (class_methods);
3545 /* We don't handle partial covered yet */
3546 partially_covered = 0;
3548 logbuffer = ensure_logbuf (
3549 EVENT_SIZE /* event */ +
3550 strlen (assembly_name) + 1 /* assembly name */ +
3551 strlen (class_name) + 1 /* class name */ +
3552 LEB128_SIZE /* no. methods */ +
3553 LEB128_SIZE /* fully covered */ +
3554 LEB128_SIZE /* partially covered */
3557 ENTER_LOG (logbuffer, "coverage-class");
3558 emit_byte (logbuffer, TYPE_COVERAGE_CLASS | TYPE_COVERAGE);
3559 emit_string (logbuffer, assembly_name, strlen (assembly_name) + 1);
3560 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3561 emit_uvalue (logbuffer, number_of_methods);
3562 emit_uvalue (logbuffer, fully_covered);
3563 emit_uvalue (logbuffer, partially_covered);
3564 EXIT_LOG (logbuffer);
3566 safe_send (prof, logbuffer);
3568 g_free (class_name);
3572 get_coverage_for_image (MonoImage *image, int *number_of_methods, guint *fully_covered, int *partially_covered)
3574 MonoLockFreeQueue *image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3576 *number_of_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
3578 *fully_covered = count_queue (image_methods);
3582 // FIXME: We don't handle partially covered yet.
3583 *partially_covered = 0;
3587 build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
3589 MonoAssembly *assembly = (MonoAssembly *)value;
3590 MonoProfiler *prof = (MonoProfiler *)userdata;
3591 MonoImage *image = mono_assembly_get_image (assembly);
3592 LogBuffer *logbuffer;
3593 const char *name, *guid, *filename;
3594 int number_of_methods = 0, partially_covered = 0;
3595 guint fully_covered = 0;
3597 name = mono_image_get_name (image);
3598 guid = mono_image_get_guid (image);
3599 filename = mono_image_get_filename (image);
3601 name = name ? name : "";
3602 guid = guid ? guid : "";
3603 filename = filename ? filename : "";
3605 get_coverage_for_image (image, &number_of_methods, &fully_covered, &partially_covered);
3607 logbuffer = ensure_logbuf (
3608 EVENT_SIZE /* event */ +
3609 strlen (name) + 1 /* name */ +
3610 strlen (guid) + 1 /* guid */ +
3611 strlen (filename) + 1 /* file name */ +
3612 LEB128_SIZE /* no. methods */ +
3613 LEB128_SIZE /* fully covered */ +
3614 LEB128_SIZE /* partially covered */
3617 ENTER_LOG (logbuffer, "coverage-assemblies");
3618 emit_byte (logbuffer, TYPE_COVERAGE_ASSEMBLY | TYPE_COVERAGE);
3619 emit_string (logbuffer, name, strlen (name) + 1);
3620 emit_string (logbuffer, guid, strlen (guid) + 1);
3621 emit_string (logbuffer, filename, strlen (filename) + 1);
3622 emit_uvalue (logbuffer, number_of_methods);
3623 emit_uvalue (logbuffer, fully_covered);
3624 emit_uvalue (logbuffer, partially_covered);
3625 EXIT_LOG (logbuffer);
3627 safe_send (prof, logbuffer);
3631 dump_coverage (MonoProfiler *prof)
3633 if (!coverage_initialized)
3636 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Started dump\n");)
3639 mono_os_mutex_lock (&coverage_mutex);
3640 mono_conc_hashtable_foreach (coverage_assemblies, build_assembly_buffer, prof);
3641 mono_conc_hashtable_foreach (coverage_classes, build_class_buffer, prof);
3642 mono_conc_hashtable_foreach (coverage_methods, build_method_buffer, prof);
3643 mono_os_mutex_unlock (&coverage_mutex);
3645 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Finished dump\n");)
3649 process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method)
3654 if (!coverage_initialized)
3657 klass = mono_method_get_class (method);
3658 image = mono_class_get_image (klass);
3660 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)))
3663 mono_os_mutex_lock (&coverage_mutex);
3664 mono_conc_hashtable_insert (entered_methods, method, method);
3665 mono_os_mutex_unlock (&coverage_mutex);
3668 static MonoLockFreeQueueNode *
3669 create_method_node (MonoMethod *method)
3671 MethodNode *node = (MethodNode *)g_malloc (sizeof (MethodNode));
3672 mono_lock_free_queue_node_init ((MonoLockFreeQueueNode *) node, FALSE);
3673 node->method = method;
3675 return (MonoLockFreeQueueNode *) node;
3679 coverage_filter (MonoProfiler *prof, MonoMethod *method)
3684 MonoAssembly *assembly;
3685 MonoMethodHeader *header;
3686 guint32 iflags, flags, code_size;
3687 char *fqn, *classname;
3688 gboolean has_positive, found;
3689 MonoLockFreeQueue *image_methods, *class_methods;
3690 MonoLockFreeQueueNode *node;
3692 if (!coverage_initialized)
3695 COVERAGE_DEBUG(fprintf (stderr, "Coverage filter for %s\n", mono_method_get_name (method));)
3697 flags = mono_method_get_flags (method, &iflags);
3698 if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
3699 (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/)) {
3700 COVERAGE_DEBUG(fprintf (stderr, " Internal call or pinvoke - ignoring\n");)
3704 // Don't need to do anything else if we're already tracking this method
3705 if (mono_conc_hashtable_lookup (coverage_methods, method)) {
3706 COVERAGE_DEBUG(fprintf (stderr, " Already tracking\n");)
3710 klass = mono_method_get_class (method);
3711 image = mono_class_get_image (klass);
3713 // Don't handle coverage for the core assemblies
3714 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)) != NULL)
3717 if (prof->coverage_filters) {
3718 /* Check already filtered classes first */
3719 if (mono_conc_hashtable_lookup (filtered_classes, klass)) {
3720 COVERAGE_DEBUG(fprintf (stderr, " Already filtered\n");)
3724 classname = mono_type_get_name (mono_class_get_type (klass));
3726 fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
3728 COVERAGE_DEBUG(fprintf (stderr, " Looking for %s in filter\n", fqn);)
3729 // Check positive filters first
3730 has_positive = FALSE;
3732 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3733 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3735 if (filter [0] == '+') {
3736 filter = &filter [1];
3738 COVERAGE_DEBUG(fprintf (stderr, " Checking against +%s ...", filter);)
3740 if (strstr (fqn, filter) != NULL) {
3741 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3744 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3746 has_positive = TRUE;
3750 if (has_positive && !found) {
3751 COVERAGE_DEBUG(fprintf (stderr, " Positive match was not found\n");)
3753 mono_os_mutex_lock (&coverage_mutex);
3754 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3755 mono_os_mutex_unlock (&coverage_mutex);
3762 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3763 // FIXME: Is substring search sufficient?
3764 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3765 if (filter [0] == '+')
3769 filter = &filter [1];
3770 COVERAGE_DEBUG(fprintf (stderr, " Checking against -%s ...", filter);)
3772 if (strstr (fqn, filter) != NULL) {
3773 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3775 mono_os_mutex_lock (&coverage_mutex);
3776 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3777 mono_os_mutex_unlock (&coverage_mutex);
3783 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3791 COVERAGE_DEBUG(fprintf (stderr, " Handling coverage for %s\n", mono_method_get_name (method));)
3792 header = mono_method_get_header_checked (method, &error);
3793 mono_error_cleanup (&error);
3795 mono_method_header_get_code (header, &code_size, NULL);
3797 assembly = mono_image_get_assembly (image);
3799 // Need to keep the assemblies around for as long as they are kept in the hashtable
3800 // Nunit, for example, has a habit of unloading them before the coverage statistics are
3801 // generated causing a crash. See https://bugzilla.xamarin.com/show_bug.cgi?id=39325
3802 mono_assembly_addref (assembly);
3804 mono_os_mutex_lock (&coverage_mutex);
3805 mono_conc_hashtable_insert (coverage_methods, method, method);
3806 mono_conc_hashtable_insert (coverage_assemblies, assembly, assembly);
3807 mono_os_mutex_unlock (&coverage_mutex);
3809 image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3811 if (image_methods == NULL) {
3812 image_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
3813 mono_lock_free_queue_init (image_methods);
3814 mono_os_mutex_lock (&coverage_mutex);
3815 mono_conc_hashtable_insert (image_to_methods, image, image_methods);
3816 mono_os_mutex_unlock (&coverage_mutex);
3819 node = create_method_node (method);
3820 mono_lock_free_queue_enqueue (image_methods, node);
3822 class_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (coverage_classes, klass);
3824 if (class_methods == NULL) {
3825 class_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
3826 mono_lock_free_queue_init (class_methods);
3827 mono_os_mutex_lock (&coverage_mutex);
3828 mono_conc_hashtable_insert (coverage_classes, klass, class_methods);
3829 mono_os_mutex_unlock (&coverage_mutex);
3832 node = create_method_node (method);
3833 mono_lock_free_queue_enqueue (class_methods, node);
3838 #define LINE_BUFFER_SIZE 4096
3839 /* Max file limit of 128KB */
3840 #define MAX_FILE_SIZE 128 * 1024
3842 get_file_content (FILE *stream)
3847 int res, offset = 0;
3849 res = fseek (stream, 0, SEEK_END);
3853 filesize = ftell (stream);
3857 res = fseek (stream, 0, SEEK_SET);
3861 if (filesize > MAX_FILE_SIZE)
3864 buffer = (char *)g_malloc ((filesize + 1) * sizeof (char));
3865 while ((bytes_read = fread (buffer + offset, 1, LINE_BUFFER_SIZE, stream)) > 0)
3866 offset += bytes_read;
3868 /* NULL terminate our buffer */
3869 buffer[filesize] = '\0';
3874 get_next_line (char *contents, char **next_start)
3878 if (p == NULL || *p == '\0') {
3883 while (*p != '\n' && *p != '\0')
3888 *next_start = p + 1;
3896 init_suppressed_assemblies (void)
3902 suppressed_assemblies = mono_conc_hashtable_new (g_str_hash, g_str_equal);
3903 sa_file = fopen (SUPPRESSION_DIR "/mono-profiler-log.suppression", "r");
3904 if (sa_file == NULL)
3907 /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
3908 content = get_file_content (sa_file);
3909 if (content == NULL) {
3910 g_error ("mono-profiler-log.suppression is greater than 128kb - aborting\n");
3913 while ((line = get_next_line (content, &content))) {
3914 line = g_strchomp (g_strchug (line));
3915 /* No locking needed as we're doing initialization */
3916 mono_conc_hashtable_insert (suppressed_assemblies, line, line);
3922 #endif /* DISABLE_HELPER_THREAD */
3925 coverage_init (MonoProfiler *prof)
3927 #ifndef DISABLE_HELPER_THREAD
3928 assert (!coverage_initialized);
3930 COVERAGE_DEBUG(fprintf (stderr, "Coverage initialized\n");)
3932 mono_os_mutex_init (&coverage_mutex);
3933 coverage_methods = mono_conc_hashtable_new (NULL, NULL);
3934 coverage_assemblies = mono_conc_hashtable_new (NULL, NULL);
3935 coverage_classes = mono_conc_hashtable_new (NULL, NULL);
3936 filtered_classes = mono_conc_hashtable_new (NULL, NULL);
3937 entered_methods = mono_conc_hashtable_new (NULL, NULL);
3938 image_to_methods = mono_conc_hashtable_new (NULL, NULL);
3939 init_suppressed_assemblies ();
3941 coverage_initialized = TRUE;
3942 #endif /* DISABLE_HELPER_THREAD */
3946 unref_coverage_assemblies (gpointer key, gpointer value, gpointer userdata)
3948 MonoAssembly *assembly = (MonoAssembly *)value;
3949 mono_assembly_close (assembly);
3953 log_shutdown (MonoProfiler *prof)
3958 #ifndef DISABLE_HELPER_THREAD
3959 counters_and_perfcounters_sample (prof, FALSE);
3961 dump_coverage (prof);
3963 if (prof->command_port) {
3965 ign_res (write (prof->pipes [1], &c, 1));
3966 pthread_join (prof->helper_thread, &res);
3972 for (i = 0; i < num_perf; ++i)
3973 read_perf_mmap (prof, i);
3977 g_ptr_array_free (prof->sorted_sample_events, TRUE);
3979 if (TLS_GET (LogBuffer, tlsbuffer))
3980 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
3982 TLS_SET (tlsbuffer, NULL);
3983 TLS_SET (tlsmethodlist, NULL);
3985 InterlockedWrite (&prof->run_writer_thread, 0);
3986 mono_os_sem_post (&prof->writer_queue_sem);
3987 pthread_join (prof->writer_thread, &res);
3989 mono_os_sem_destroy (&prof->writer_queue_sem);
3991 #if defined (HAVE_SYS_ZLIB)
3993 gzclose (prof->gzfile);
3995 if (prof->pipe_output)
3996 pclose (prof->file);
3998 fclose (prof->file);
4000 mono_conc_hashtable_destroy (prof->method_table);
4001 mono_os_mutex_destroy (&prof->method_table_mutex);
4003 if (coverage_initialized) {
4004 mono_os_mutex_lock (&coverage_mutex);
4005 mono_conc_hashtable_foreach (coverage_assemblies, unref_coverage_assemblies, prof);
4006 mono_os_mutex_unlock (&coverage_mutex);
4008 mono_conc_hashtable_destroy (coverage_methods);
4009 mono_conc_hashtable_destroy (coverage_assemblies);
4010 mono_conc_hashtable_destroy (coverage_classes);
4011 mono_conc_hashtable_destroy (filtered_classes);
4013 mono_conc_hashtable_destroy (entered_methods);
4014 mono_conc_hashtable_destroy (image_to_methods);
4015 mono_conc_hashtable_destroy (suppressed_assemblies);
4016 mono_os_mutex_destroy (&coverage_mutex);
4023 new_filename (const char* filename)
4025 time_t t = time (NULL);
4026 int pid = process_id ();
4031 int count_dates = 0;
4035 for (p = filename; *p; p++) {
4046 if (!count_dates && !count_pids)
4047 return pstrdup (filename);
4048 snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
4050 snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
4051 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
4052 s_date = strlen (time_buf);
4053 s_pid = strlen (pid_buf);
4054 d = res = (char *)malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
4055 for (p = filename; *p; p++) {
4062 strcpy (d, time_buf);
4065 } else if (*p == 'p') {
4066 strcpy (d, pid_buf);
4069 } else if (*p == '%') {
4081 //this is exposed by the JIT, but it's not meant to be a supported API for now.
4082 extern void mono_threads_attach_tools_thread (void);
4084 #ifndef DISABLE_HELPER_THREAD
4087 helper_thread (void* arg)
4089 MonoProfiler* prof = (MonoProfiler *)arg;
4093 MonoThread *thread = NULL;
4095 mono_threads_attach_tools_thread ();
4096 mono_thread_info_set_name (mono_native_thread_id_get (), "Profiler helper");
4098 //fprintf (stderr, "Server listening\n");
4099 command_socket = -1;
4105 FD_SET (prof->server_socket, &rfds);
4106 max_fd = prof->server_socket;
4107 FD_SET (prof->pipes [0], &rfds);
4108 if (max_fd < prof->pipes [0])
4109 max_fd = prof->pipes [0];
4110 if (command_socket >= 0) {
4111 FD_SET (command_socket, &rfds);
4112 if (max_fd < command_socket)
4113 max_fd = command_socket;
4118 for ( i = 0; i < num_perf; ++i) {
4119 if (perf_data [i].perf_fd < 0)
4121 FD_SET (perf_data [i].perf_fd, &rfds);
4122 if (max_fd < perf_data [i].perf_fd)
4123 max_fd = perf_data [i].perf_fd;
4128 counters_and_perfcounters_sample (prof, TRUE);
4132 len = select (max_fd + 1, &rfds, NULL, NULL, &tv);
4138 g_warning ("Error in proflog server: %s", strerror (errno));
4142 if (FD_ISSET (prof->pipes [0], &rfds)) {
4144 int r = read (prof->pipes [0], &c, 1);
4145 if (r == 1 && c == 0) {
4146 StatBuffer *sbufbase = prof->stat_buffers;
4148 if (!sbufbase->next)
4150 sbuf = sbufbase->next->next;
4151 sbufbase->next->next = NULL;
4153 fprintf (stderr, "stat buffer dump\n");
4155 dump_sample_hits (prof, sbuf);
4156 free_buffer (sbuf, sbuf->size);
4157 safe_send_threadless (prof, ensure_logbuf (0));
4161 /* time to shut down */
4162 dump_sample_hits (prof, prof->stat_buffers);
4164 mono_thread_detach (thread);
4166 fprintf (stderr, "helper shutdown\n");
4170 for ( i = 0; i < num_perf; ++i) {
4171 if (perf_data [i].perf_fd < 0)
4173 if (FD_ISSET (perf_data [i].perf_fd, &rfds))
4174 read_perf_mmap (prof, i);
4178 safe_send_threadless (prof, ensure_logbuf (0));
4184 for ( i = 0; i < num_perf; ++i) {
4185 if (perf_data [i].perf_fd < 0)
4187 if (FD_ISSET (perf_data [i].perf_fd, &rfds)) {
4188 read_perf_mmap (prof, i);
4189 safe_send_threadless (prof, ensure_logbuf (0));
4194 if (command_socket >= 0 && FD_ISSET (command_socket, &rfds)) {
4195 len = read (command_socket, buf, sizeof (buf) - 1);
4199 close (command_socket);
4200 command_socket = -1;
4204 if (strcmp (buf, "heapshot\n") == 0) {
4205 heapshot_requested = 1;
4206 //fprintf (stderr, "perform heapshot\n");
4207 if (InterlockedRead (&runtime_inited) && !thread) {
4208 thread = mono_thread_attach (mono_get_root_domain ());
4209 /*fprintf (stderr, "attached\n");*/
4212 process_requests (prof);
4213 mono_thread_detach (thread);
4219 if (!FD_ISSET (prof->server_socket, &rfds)) {
4222 command_socket = accept (prof->server_socket, NULL, NULL);
4223 if (command_socket < 0)
4225 //fprintf (stderr, "Accepted connection\n");
4228 mono_thread_info_detach ();
4234 start_helper_thread (MonoProfiler* prof)
4236 struct sockaddr_in server_address;
4239 if (pipe (prof->pipes) < 0) {
4240 fprintf (stderr, "Cannot create pipe\n");
4243 prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
4244 if (prof->server_socket < 0) {
4245 fprintf (stderr, "Cannot create server socket\n");
4248 memset (&server_address, 0, sizeof (server_address));
4249 server_address.sin_family = AF_INET;
4250 server_address.sin_addr.s_addr = INADDR_ANY;
4251 server_address.sin_port = htons (prof->command_port);
4252 if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) < 0) {
4253 fprintf (stderr, "Cannot bind server socket, port: %d: %s\n", prof->command_port, strerror (errno));
4254 close (prof->server_socket);
4257 if (listen (prof->server_socket, 1) < 0) {
4258 fprintf (stderr, "Cannot listen server socket\n");
4259 close (prof->server_socket);
4262 slen = sizeof (server_address);
4263 if (getsockname (prof->server_socket, (struct sockaddr *)&server_address, &slen) == 0) {
4264 prof->command_port = ntohs (server_address.sin_port);
4265 /*fprintf (stderr, "Assigned server port: %d\n", prof->command_port);*/
4268 r = pthread_create (&prof->helper_thread, NULL, helper_thread, prof);
4270 close (prof->server_socket);
4278 handle_writer_queue_entry (MonoProfiler *prof)
4280 WriterQueueEntry *entry;
4282 if ((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);
4355 mono_thread_hazardous_try_free (entry, free);
4364 writer_thread (void *arg)
4366 MonoProfiler *prof = (MonoProfiler *)arg;
4368 mono_threads_attach_tools_thread ();
4369 mono_thread_info_set_name (mono_native_thread_id_get (), "Profiler writer");
4373 while (InterlockedRead (&prof->run_writer_thread)) {
4374 mono_os_sem_wait (&prof->writer_queue_sem, MONO_SEM_FLAGS_NONE);
4375 handle_writer_queue_entry (prof);
4378 /* Drain any remaining entries on shutdown. */
4379 while (handle_writer_queue_entry (prof));
4381 mono_thread_info_detach ();
4387 start_writer_thread (MonoProfiler* prof)
4389 InterlockedWrite (&prof->run_writer_thread, 1);
4391 return !pthread_create (&prof->writer_thread, NULL, writer_thread, prof);
4395 runtime_initialized (MonoProfiler *profiler)
4397 #ifndef DISABLE_HELPER_THREAD
4398 if (hs_mode_ondemand || need_helper_thread) {
4399 if (!start_helper_thread (profiler))
4400 profiler->command_port = 0;
4404 start_writer_thread (profiler);
4406 InterlockedWrite (&runtime_inited, 1);
4407 #ifndef DISABLE_HELPER_THREAD
4408 counters_init (profiler);
4409 counters_sample (profiler, 0, FALSE);
4411 /* ensure the main thread data and startup are available soon */
4412 safe_send (profiler, ensure_logbuf (0));
4415 static MonoProfiler*
4416 create_profiler (const char *filename, GPtrArray *filters)
4420 int force_delete = 0;
4421 prof = (MonoProfiler *)calloc (1, sizeof (MonoProfiler));
4423 prof->command_port = command_port;
4424 if (filename && *filename == '-') {
4430 filename = "|mprof-report -";
4432 filename = "output.mlpd";
4433 nf = (char*)filename;
4435 nf = new_filename (filename);
4437 int s = strlen (nf) + 32;
4438 char *p = (char *)malloc (s);
4439 snprintf (p, s, "|mprof-report '--out=%s' -", nf);
4445 prof->file = popen (nf + 1, "w");
4446 prof->pipe_output = 1;
4447 } else if (*nf == '#') {
4448 int fd = strtol (nf + 1, NULL, 10);
4449 prof->file = fdopen (fd, "a");
4453 prof->file = fopen (nf, "wb");
4456 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
4459 #if defined (HAVE_SYS_ZLIB)
4461 prof->gzfile = gzdopen (fileno (prof->file), "wb");
4464 if (sample_type && !do_mono_sample)
4465 need_helper_thread = setup_perf_event ();
4467 /* FIXME: warn if different freq or sample type */
4471 if (do_mono_sample) {
4472 prof->stat_buffers = create_stat_buffer ();
4473 need_helper_thread = 1;
4475 if (do_counters && !need_helper_thread) {
4476 need_helper_thread = 1;
4479 prof->sorted_sample_events = g_ptr_array_sized_new (BUFFER_SIZE / SAMPLE_EVENT_SIZE_IN_SLOTS (0));
4481 #ifdef DISABLE_HELPER_THREAD
4482 if (hs_mode_ondemand)
4483 fprintf (stderr, "Ondemand heapshot unavailable on this arch.\n");
4486 fprintf (stderr, "Coverage unavailable on this arch.\n");
4490 mono_lock_free_queue_init (&prof->writer_queue);
4491 mono_os_sem_init (&prof->writer_queue_sem, 0);
4493 mono_os_mutex_init (&prof->method_table_mutex);
4494 prof->method_table = mono_conc_hashtable_new (NULL, NULL);
4497 coverage_init (prof);
4498 prof->coverage_filters = filters;
4500 prof->startup_time = current_time ();
4507 printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
4508 printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
4509 printf ("Options:\n");
4510 printf ("\thelp show this usage info\n");
4511 printf ("\t[no]alloc enable/disable recording allocation info\n");
4512 printf ("\t[no]calls enable/disable recording enter/leave method events\n");
4513 printf ("\theapshot[=MODE] record heap shot info (by default at each major collection)\n");
4514 printf ("\t MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
4515 printf ("\tcounters sample counters every 1s\n");
4516 printf ("\tsample[=TYPE] use statistical sampling mode (by default cycles/100)\n");
4517 printf ("\t TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
4518 printf ("\t TYPE can be followed by /FREQUENCY\n");
4519 printf ("\ttime=fast use a faster (but more inaccurate) timer\n");
4520 printf ("\tmaxframes=NUM collect up to NUM stack frames\n");
4521 printf ("\tcalldepth=NUM ignore method events for call chain depth bigger than NUM\n");
4522 printf ("\toutput=FILENAME write the data to file FILENAME (-FILENAME to overwrite)\n");
4523 printf ("\toutput=|PROGRAM write the data to the stdin of PROGRAM\n");
4524 printf ("\t %%t is subtituted with date and time, %%p with the pid\n");
4525 printf ("\treport create a report instead of writing the raw data to a file\n");
4526 printf ("\tzip compress the output data\n");
4527 printf ("\tport=PORTNUM use PORTNUM for the listening command server\n");
4528 printf ("\tcoverage enable collection of code coverage data\n");
4529 printf ("\tcovfilter=ASSEMBLY add an assembly to the code coverage filters\n");
4530 printf ("\t add a + to include the assembly or a - to exclude it\n");
4531 printf ("\t filter=-mscorlib\n");
4532 printf ("\tcovfilter-file=FILE use FILE to generate the list of assemblies to be filtered\n");
4538 match_option (const char* p, const char *opt, char **rval)
4540 int len = strlen (opt);
4541 if (strncmp (p, opt, len) == 0) {
4543 if (p [len] == '=' && p [len + 1]) {
4544 const char *opt = p + len + 1;
4545 const char *end = strchr (opt, ',');
4553 val = (char *)malloc (l + 1);
4554 memcpy (val, opt, l);
4559 if (p [len] == 0 || p [len] == ',') {
4561 return p + len + (p [len] == ',');
4579 static const SampleMode sample_modes [] = {
4580 {"cycles", SAMPLE_CYCLES},
4581 {"instr", SAMPLE_INSTRUCTIONS},
4582 {"cachemiss", SAMPLE_CACHE_MISSES},
4583 {"cacherefs", SAMPLE_CACHE_REFS},
4584 {"branches", SAMPLE_BRANCHES},
4585 {"branchmiss", SAMPLE_BRANCH_MISSES},
4590 set_sample_mode (char* val, int allow_empty)
4593 char *maybe_freq = NULL;
4595 const SampleMode *smode = sample_modes;
4596 #ifndef USE_PERF_EVENTS
4599 if (allow_empty && !val) {
4600 sample_type = SAMPLE_CYCLES;
4604 if (strcmp (val, "mono") == 0) {
4606 sample_type = SAMPLE_CYCLES;
4610 for (smode = sample_modes; smode->name; smode++) {
4611 int l = strlen (smode->name);
4612 if (strncmp (val, smode->name, l) == 0) {
4613 sample_type = smode->sample_mode;
4614 maybe_freq = val + l;
4620 if (*maybe_freq == '/') {
4621 count = strtoul (maybe_freq + 1, &end, 10);
4622 if (maybe_freq + 1 == end)
4624 sample_freq = count;
4625 } else if (*maybe_freq != 0) {
4634 set_hsmode (char* val, int allow_empty)
4638 if (allow_empty && !val)
4640 if (strcmp (val, "ondemand") == 0) {
4641 hs_mode_ondemand = 1;
4645 count = strtoul (val, &end, 10);
4648 if (strcmp (end, "ms") == 0)
4650 else if (strcmp (end, "gc") == 0)
4658 * declaration to silence the compiler: this is the entry point that
4659 * mono will load from the shared library and call.
4662 mono_profiler_startup (const char *desc);
4665 mono_profiler_startup_log (const char *desc);
4668 * this is the entry point that will be used when the profiler
4669 * is embedded inside the main executable.
4672 mono_profiler_startup_log (const char *desc)
4674 mono_profiler_startup (desc);
4678 mono_profiler_startup (const char *desc)
4681 GPtrArray *filters = NULL;
4682 char *filename = NULL;
4686 int calls_enabled = 0;
4687 int allocs_enabled = 0;
4688 int only_counters = 0;
4689 int only_coverage = 0;
4690 int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
4691 MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
4692 MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
4693 MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS|
4694 MONO_PROFILE_INS_COVERAGE|MONO_PROFILE_APPDOMAIN_EVENTS|MONO_PROFILE_CONTEXT_EVENTS|
4695 MONO_PROFILE_ASSEMBLY_EVENTS;
4698 if (strncmp (p, "log", 3))
4703 for (; *p; p = opt) {
4709 if ((opt = match_option (p, "help", NULL)) != p) {
4713 if ((opt = match_option (p, "calls", NULL)) != p) {
4717 if ((opt = match_option (p, "nocalls", NULL)) != p) {
4718 events &= ~MONO_PROFILE_ENTER_LEAVE;
4722 if ((opt = match_option (p, "alloc", NULL)) != p) {
4726 if ((opt = match_option (p, "noalloc", NULL)) != p) {
4727 events &= ~MONO_PROFILE_ALLOCATIONS;
4730 if ((opt = match_option (p, "time", &val)) != p) {
4731 if (strcmp (val, "fast") == 0)
4733 else if (strcmp (val, "null") == 0)
4740 if ((opt = match_option (p, "report", NULL)) != p) {
4744 if ((opt = match_option (p, "debug", NULL)) != p) {
4748 if ((opt = match_option (p, "sampling-real", NULL)) != p) {
4749 sampling_mode = MONO_PROFILER_STAT_MODE_REAL;
4752 if ((opt = match_option (p, "sampling-process", NULL)) != p) {
4753 sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
4756 if ((opt = match_option (p, "heapshot", &val)) != p) {
4757 events &= ~MONO_PROFILE_ALLOCATIONS;
4758 events &= ~MONO_PROFILE_ENTER_LEAVE;
4761 set_hsmode (val, 1);
4764 if ((opt = match_option (p, "sample", &val)) != p) {
4765 events &= ~MONO_PROFILE_ALLOCATIONS;
4766 events &= ~MONO_PROFILE_ENTER_LEAVE;
4768 set_sample_mode (val, 1);
4771 if ((opt = match_option (p, "hsmode", &val)) != p) {
4772 fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
4773 set_hsmode (val, 0);
4776 if ((opt = match_option (p, "zip", NULL)) != p) {
4780 if ((opt = match_option (p, "output", &val)) != p) {
4784 if ((opt = match_option (p, "port", &val)) != p) {
4786 command_port = strtoul (val, &end, 10);
4790 if ((opt = match_option (p, "maxframes", &val)) != p) {
4792 num_frames = strtoul (val, &end, 10);
4793 if (num_frames > MAX_FRAMES)
4794 num_frames = MAX_FRAMES;
4796 notraces = num_frames == 0;
4799 if ((opt = match_option (p, "calldepth", &val)) != p) {
4801 max_call_depth = strtoul (val, &end, 10);
4805 if ((opt = match_option (p, "counters", NULL)) != p) {
4809 if ((opt = match_option (p, "countersonly", NULL)) != p) {
4813 if ((opt = match_option (p, "coverage", NULL)) != p) {
4815 events |= MONO_PROFILE_ENTER_LEAVE;
4816 debug_coverage = (g_getenv ("MONO_PROFILER_DEBUG_COVERAGE") != NULL);
4819 if ((opt = match_option (p, "onlycoverage", NULL)) != p) {
4823 if ((opt = match_option (p, "covfilter-file", &val)) != p) {
4825 char *line, *content;
4827 if (filters == NULL)
4828 filters = g_ptr_array_new ();
4830 filter_file = fopen (val, "r");
4831 if (filter_file == NULL) {
4832 fprintf (stderr, "Unable to open %s\n", val);
4836 /* Don't need to free content as it is referred to by the lines stored in @filters */
4837 content = get_file_content (filter_file);
4838 if (content == NULL)
4839 fprintf (stderr, "WARNING: %s is greater than 128kb - ignoring\n", val);
4841 while ((line = get_next_line (content, &content)))
4842 g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
4844 fclose (filter_file);
4847 if ((opt = match_option (p, "covfilter", &val)) != p) {
4848 if (filters == NULL)
4849 filters = g_ptr_array_new ();
4851 g_ptr_array_add (filters, val);
4859 if (calls_enabled) {
4860 events |= MONO_PROFILE_ENTER_LEAVE;
4864 events |= MONO_PROFILE_ALLOCATIONS;
4868 events = MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_INS_COVERAGE;
4870 utils_init (fast_time);
4872 prof = create_profiler (filename, filters);
4877 mono_profiler_install (prof, log_shutdown);
4878 mono_profiler_install_gc (gc_event, gc_resize);
4879 mono_profiler_install_allocation (gc_alloc);
4880 mono_profiler_install_gc_moves (gc_moves);
4881 mono_profiler_install_gc_roots (gc_handle, gc_roots);
4882 mono_profiler_install_appdomain (NULL, domain_loaded, NULL, domain_unloaded);
4883 mono_profiler_install_appdomain_name (domain_name);
4884 mono_profiler_install_context (context_loaded, context_unloaded);
4885 mono_profiler_install_class (NULL, class_loaded, NULL, class_unloaded);
4886 mono_profiler_install_module (NULL, image_loaded, NULL, image_unloaded);
4887 mono_profiler_install_assembly (NULL, assembly_loaded, assembly_unloaded, NULL);
4888 mono_profiler_install_thread (thread_start, thread_end);
4889 mono_profiler_install_thread_name (thread_name);
4890 mono_profiler_install_enter_leave (method_enter, method_leave);
4891 mono_profiler_install_jit_end (method_jitted);
4892 mono_profiler_install_code_buffer_new (code_buffer_new);
4893 mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
4894 mono_profiler_install_monitor (monitor_event);
4895 mono_profiler_install_runtime_initialized (runtime_initialized);
4897 mono_profiler_install_coverage_filter (coverage_filter);
4899 if (do_mono_sample && sample_type == SAMPLE_CYCLES && !only_counters) {
4900 events |= MONO_PROFILE_STATISTICAL;
4901 mono_profiler_set_statistical_mode (sampling_mode, sample_freq);
4902 mono_profiler_install_statistical (mono_sample_hit);
4905 mono_profiler_set_events ((MonoProfileFlags)events);
4907 TLS_INIT (tlsbuffer);
4908 TLS_INIT (tlsmethodlist);