2 * proflog.c: mono log profiler
5 * Paolo Molaro (lupus@ximian.com)
6 * Alex Rønne Petersen (alexrp@xamarin.com)
8 * Copyright 2010 Novell, Inc (http://www.novell.com)
9 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
10 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
14 #include "../mini/jit.h"
15 #include <mono/metadata/profiler.h>
16 #include <mono/metadata/threads.h>
17 #include <mono/metadata/mono-gc.h>
18 #include <mono/metadata/debug-helpers.h>
19 #include <mono/metadata/mono-perfcounters.h>
20 #include <mono/metadata/appdomain.h>
21 #include <mono/metadata/assembly.h>
22 #include <mono/metadata/tokentype.h>
23 #include <mono/metadata/tabledefs.h>
24 #include <mono/utils/atomic.h>
25 #include <mono/utils/mono-membar.h>
26 #include <mono/utils/mono-counters.h>
27 #include <mono/utils/mono-os-mutex.h>
28 #include <mono/utils/mono-conc-hashtable.h>
29 #include <mono/utils/lock-free-queue.h>
37 #ifdef HAVE_SCHED_GETAFFINITY
42 #if defined(HOST_WIN32) || defined(DISABLE_SOCKETS)
43 #define DISABLE_HELPER_THREAD 1
52 #ifdef HAVE_EXECINFO_H
59 #ifndef DISABLE_HELPER_THREAD
60 #include <sys/types.h>
61 #include <sys/socket.h>
62 #include <netinet/in.h>
63 #include <sys/select.h>
72 #ifdef HAVE_SYS_STAT_H
79 #if defined (HAVE_SYS_ZLIB)
83 #if defined(__linux__)
86 #include <sys/syscall.h>
88 #ifdef ENABLE_PERF_EVENTS
89 #include <linux/perf_event.h>
91 #define USE_PERF_EVENTS 1
93 static int read_perf_mmap (MonoProfiler* prof, int cpu);
98 #define BUFFER_SIZE (4096 * 16)
100 /* Worst-case size in bytes of a 64-bit value encoded with LEB128. */
101 #define LEB128_SIZE 10
102 /* Size in bytes of the event ID prefix. */
105 static int nocalls = 0;
106 static int notraces = 0;
107 static int use_zip = 0;
108 static int do_report = 0;
109 static int do_heap_shot = 0;
110 static int max_call_depth = 100;
111 static volatile int runtime_inited = 0;
112 static int need_helper_thread = 0;
113 static int command_port = 0;
114 static int heapshot_requested = 0;
115 static int sample_type = 0;
116 static int sample_freq = 0;
117 static int do_mono_sample = 0;
118 static int in_shutdown = 0;
119 static int do_debug = 0;
120 static int do_counters = 0;
121 static int do_coverage = 0;
122 static gboolean debug_coverage = FALSE;
123 static MonoProfileSamplingMode sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
125 typedef struct _LogBuffer LogBuffer;
131 * The file is composed by a header followed by 0 or more buffers.
132 * Each buffer contains events that happened on a thread: for a given thread
133 * buffers that appear later in the file are guaranteed to contain events
134 * that happened later in time. Buffers from separate threads could be interleaved,
136 * Buffers are not required to be aligned.
139 * [id: 4 bytes] constant value: LOG_HEADER_ID
140 * [major: 1 byte] [minor: 1 byte] major and minor version of the log profiler
141 * [format: 1 byte] version of the data format for the rest of the file
142 * [ptrsize: 1 byte] size in bytes of a pointer in the profiled program
143 * [startup time: 8 bytes] time in milliseconds since the unix epoch when the program started
144 * [timer overhead: 4 bytes] approximate overhead in nanoseconds of the timer
145 * [flags: 4 bytes] file format flags, should be 0 for now
146 * [pid: 4 bytes] pid of the profiled process
147 * [port: 2 bytes] tcp port for server if != 0
148 * [sysid: 2 bytes] operating system and architecture identifier
150 * The multiple byte integers are in little-endian format.
153 * [buffer header] [event]*
154 * Buffers have a fixed-size header followed by 0 or more bytes of event data.
155 * Timing information and other values in the event data are usually stored
156 * as uleb128 or sleb128 integers. To save space, as noted for each item below,
157 * some data is represented as a difference between the actual value and
158 * either the last value of the same type (like for timing information) or
159 * as the difference from a value stored in a buffer header.
161 * For timing information the data is stored as uleb128, since timing
162 * increases in a monotonic way in each thread: the value is the number of
163 * nanoseconds to add to the last seen timing data in a buffer. The first value
164 * in a buffer will be calculated from the time_base field in the buffer head.
166 * Object or heap sizes are stored as uleb128.
167 * Pointer differences are stored as sleb128, instead.
169 * If an unexpected value is found, the rest of the buffer should be ignored,
170 * as generally the later values need the former to be interpreted correctly.
172 * buffer header format:
173 * [bufid: 4 bytes] constant value: BUF_ID
174 * [len: 4 bytes] size of the data following the buffer header
175 * [time_base: 8 bytes] time base in nanoseconds since an unspecified epoch
176 * [ptr_base: 8 bytes] base value for pointers
177 * [obj_base: 8 bytes] base value for object addresses
178 * [thread id: 8 bytes] system-specific thread ID (pthread_t for example)
179 * [method_base: 8 bytes] base value for MonoMethod pointers
182 * [extended info: upper 4 bits] [type: lower 4 bits] [data]*
183 * The data that follows depends on type and the extended info.
184 * Type is one of the enum values in proflog.h: TYPE_ALLOC, TYPE_GC,
185 * TYPE_METADATA, TYPE_METHOD, TYPE_EXCEPTION, TYPE_MONITOR, TYPE_HEAP.
186 * The extended info bits are interpreted based on type, see
187 * each individual event description below.
188 * strings are represented as a 0-terminated utf8 sequence.
191 * [flags: uleb128] must be 0
192 * [num: uleb128] number of frames following
193 * [frame: sleb128]* num MonoMethod pointers as differences from ptr_base
197 * exinfo: flags: TYPE_ALLOC_BT
198 * [time diff: uleb128] nanoseconds since last timing
199 * [ptr: sleb128] class as a byte difference from ptr_base
200 * [obj: sleb128] object address as a byte difference from obj_base
201 * [size: uleb128] size of the object in the heap
202 * If the TYPE_ALLOC_BT flag is set, a backtrace follows.
206 * exinfo: one of TYPE_GC_EVENT, TYPE_GC_RESIZE, TYPE_GC_MOVE, TYPE_GC_HANDLE_CREATED[_BT],
207 * TYPE_GC_HANDLE_DESTROYED[_BT]
208 * [time diff: uleb128] nanoseconds since last timing
209 * if exinfo == TYPE_GC_RESIZE
210 * [heap_size: uleb128] new heap size
211 * if exinfo == TYPE_GC_EVENT
212 * [event type: uleb128] GC event (MONO_GC_EVENT_* from profiler.h)
213 * [generation: uleb128] GC generation event refers to
214 * if exinfo == TYPE_GC_MOVE
215 * [num_objects: uleb128] number of object moves that follow
216 * [objaddr: sleb128]+ num_objects object pointer differences from obj_base
217 * num is always an even number: the even items are the old
218 * addresses, the odd numbers are the respective new object addresses
219 * if exinfo == TYPE_GC_HANDLE_CREATED[_BT]
220 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
221 * upper bits reserved as flags
222 * [handle: uleb128] GC handle value
223 * [objaddr: sleb128] object pointer differences from obj_base
224 * If exinfo == TYPE_GC_HANDLE_CREATED_BT, a backtrace follows.
225 * if exinfo == TYPE_GC_HANDLE_DESTROYED[_BT]
226 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
227 * upper bits reserved as flags
228 * [handle: uleb128] GC handle value
229 * If exinfo == TYPE_GC_HANDLE_DESTROYED_BT, a backtrace follows.
231 * type metadata format:
232 * type: TYPE_METADATA
233 * exinfo: one of: TYPE_END_LOAD, TYPE_END_UNLOAD (optional for TYPE_THREAD and TYPE_DOMAIN)
234 * [time diff: uleb128] nanoseconds since last timing
235 * [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
236 * TYPE_THREAD, TYPE_CONTEXT
237 * [pointer: sleb128] pointer of the metadata type depending on mtype
238 * if mtype == TYPE_CLASS
239 * [image: sleb128] MonoImage* as a pointer difference from ptr_base
240 * [flags: uleb128] must be 0
241 * [name: string] full class name
242 * if mtype == TYPE_IMAGE
243 * [flags: uleb128] must be 0
244 * [name: string] image file name
245 * if mtype == TYPE_ASSEMBLY
246 * [flags: uleb128] must be 0
247 * [name: string] assembly name
248 * if mtype == TYPE_DOMAIN
249 * [flags: uleb128] must be 0
250 * if mtype == TYPE_DOMAIN && exinfo == 0
251 * [name: string] domain friendly name
252 * if mtype == TYPE_CONTEXT
253 * [flags: uleb128] must be 0
254 * [domain: sleb128] domain id as pointer
255 * if mtype == TYPE_THREAD && (format_version < 11 || (format_version > 10 && exinfo == 0))
256 * [flags: uleb128] must be 0
257 * [name: string] thread name
259 * type method format:
261 * exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
262 * [time diff: uleb128] nanoseconds since last timing
263 * [method: sleb128] MonoMethod* as a pointer difference from the last such
264 * pointer or the buffer method_base
265 * if exinfo == TYPE_JIT
266 * [code address: sleb128] pointer to the native code as a diff from ptr_base
267 * [code size: uleb128] size of the generated code
268 * [name: string] full method name
270 * type runtime format:
272 * exinfo: one of: TYPE_JITHELPER
273 * [time diff: uleb128] nanoseconds since last timing
274 * if exinfo == TYPE_JITHELPER
275 * [type: uleb128] MonoProfilerCodeBufferType enum value
276 * [buffer address: sleb128] pointer to the native code as a diff from ptr_base
277 * [buffer size: uleb128] size of the generated code
278 * if type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE
279 * [name: string] buffer description name
281 * type monitor format:
283 * exinfo: TYPE_MONITOR_BT flag and one of: MONO_PROFILER_MONITOR_(CONTENTION|FAIL|DONE)
284 * [time diff: uleb128] nanoseconds since last timing
285 * [object: sleb128] the lock object as a difference from obj_base
286 * if exinfo.low3bits == MONO_PROFILER_MONITOR_CONTENTION
287 * If the TYPE_MONITOR_BT flag is set, a backtrace follows.
291 * exinfo: one of TYPE_HEAP_START, TYPE_HEAP_END, TYPE_HEAP_OBJECT, TYPE_HEAP_ROOT
292 * if exinfo == TYPE_HEAP_START
293 * [time diff: uleb128] nanoseconds since last timing
294 * if exinfo == TYPE_HEAP_END
295 * [time diff: uleb128] nanoseconds since last timing
296 * if exinfo == TYPE_HEAP_OBJECT
297 * [object: sleb128] the object as a difference from obj_base
298 * [class: sleb128] the object MonoClass* as a difference from ptr_base
299 * [size: uleb128] size of the object on the heap
300 * [num_refs: uleb128] number of object references
301 * if (format version > 1) each referenced objref is preceded by a
302 * uleb128 encoded offset: the first offset is from the object address
303 * and each next offset is relative to the previous one
304 * [objrefs: sleb128]+ object referenced as a difference from obj_base
305 * The same object can appear multiple times, but only the first time
306 * with size != 0: in the other cases this data will only be used to
307 * provide additional referenced objects.
308 * if exinfo == TYPE_HEAP_ROOT
309 * [num_roots: uleb128] number of root references
310 * [num_gc: uleb128] number of major gcs
311 * [object: sleb128] the object as a difference from obj_base
312 * [root_type: uleb128] the root_type: MonoProfileGCRootType (profiler.h)
313 * [extra_info: uleb128] the extra_info value
314 * object, root_type and extra_info are repeated num_roots times
318 * exinfo: one of TYPE_SAMPLE_HIT, TYPE_SAMPLE_USYM, TYPE_SAMPLE_UBIN, TYPE_SAMPLE_COUNTERS_DESC, TYPE_SAMPLE_COUNTERS
319 * if exinfo == TYPE_SAMPLE_HIT
320 * [sample_type: uleb128] type of sample (SAMPLE_*)
321 * [timestamp: uleb128] nanoseconds since startup (note: different from other timestamps!)
322 * if (format_version > 10)
323 * [thread: sleb128] thread id as difference from ptr_base
324 * [count: uleb128] number of following instruction addresses
325 * [ip: sleb128]* instruction pointer as difference from ptr_base
326 * if (format_version > 5)
327 * [mbt_count: uleb128] number of managed backtrace info triplets (method + IL offset + native offset)
328 * [method: sleb128]* MonoMethod* as a pointer difference from the last such
329 * pointer or the buffer method_base (the first such method can be also indentified by ip, but this is not neccessarily true)
330 * [il_offset: sleb128]* IL offset inside method where the hit occurred
331 * [native_offset: sleb128]* native offset inside method where the hit occurred
332 * if exinfo == TYPE_SAMPLE_USYM
333 * [address: sleb128] symbol address as a difference from ptr_base
334 * [size: uleb128] symbol size (may be 0 if unknown)
335 * [name: string] symbol name
336 * if exinfo == TYPE_SAMPLE_UBIN
337 * [time diff: uleb128] nanoseconds since last timing
338 * [address: sleb128] address where binary has been loaded
339 * [offset: uleb128] file offset of mapping (the same file can be mapped multiple times)
340 * [size: uleb128] memory size
341 * [name: string] binary name
342 * if exinfo == TYPE_SAMPLE_COUNTERS_DESC
343 * [len: uleb128] number of counters
345 * [section: uleb128] section of counter
346 * if section == MONO_COUNTER_PERFCOUNTERS:
347 * [section_name: string] section name of counter
348 * [name: string] name of counter
349 * [type: uleb128] type of counter
350 * [unit: uleb128] unit of counter
351 * [variance: uleb128] variance of counter
352 * [index: uleb128] unique index of counter
353 * if exinfo == TYPE_SAMPLE_COUNTERS
354 * [timestamp: uleb128] sampling timestamp
356 * [index: uleb128] unique index of counter
359 * [type: uleb128] type of counter value
362 * [0: uleb128] 0 -> value is null
364 * [1: uleb128] 1 -> value is not null
365 * [value: string] counter value
367 * [value: uleb128/sleb128/double] counter value, can be sleb128, uleb128 or double (determined by using type)
369 * type coverage format
370 * type: TYPE_COVERAGE
371 * exinfo: one of TYPE_COVERAGE_METHOD, TYPE_COVERAGE_STATEMENT, TYPE_COVERAGE_ASSEMBLY, TYPE_COVERAGE_CLASS
372 * if exinfo == TYPE_COVERAGE_METHOD
373 * [assembly: string] name of assembly
374 * [class: string] name of the class
375 * [name: string] name of the method
376 * [signature: string] the signature of the method
377 * [filename: string] the file path of the file that contains this method
378 * [token: uleb128] the method token
379 * [method_id: uleb128] an ID for this data to associate with the buffers of TYPE_COVERAGE_STATEMENTS
380 * [len: uleb128] the number of TYPE_COVERAGE_BUFFERS associated with this method
381 * if exinfo == TYPE_COVERAGE_STATEMENTS
382 * [method_id: uleb128] an the TYPE_COVERAGE_METHOD buffer to associate this with
383 * [offset: uleb128] the il offset relative to the previous offset
384 * [counter: uleb128] the counter for this instruction
385 * [line: uleb128] the line of filename containing this instruction
386 * [column: uleb128] the column containing this instruction
387 * if exinfo == TYPE_COVERAGE_ASSEMBLY
388 * [name: string] assembly name
389 * [guid: string] assembly GUID
390 * [filename: string] assembly filename
391 * [number_of_methods: uleb128] the number of methods in this assembly
392 * [fully_covered: uleb128] the number of fully covered methods
393 * [partially_covered: uleb128] the number of partially covered methods
394 * currently partially_covered will always be 0, and fully_covered is the
395 * number of methods that are fully and partially covered.
396 * if exinfo == TYPE_COVERAGE_CLASS
397 * [name: string] assembly name
398 * [class: string] class name
399 * [number_of_methods: uleb128] the number of methods in this class
400 * [fully_covered: uleb128] the number of fully covered methods
401 * [partially_covered: uleb128] the number of partially covered methods
402 * currently partially_covered will always be 0, and fully_covered is the
403 * number of methods that are fully and partially covered.
407 * Format oddities that we ought to fix:
409 * - Methods written in emit_bt () should be based on the buffer's base
410 * method instead of the base pointer.
411 * - The TYPE_SAMPLE_HIT event contains (currently) pointless data like
412 * always-one unmanaged frame count and always-zero IL offsets.
414 * These are mostly small things and are not worth a format change by
415 * themselves. They should be done when some other major change has to
416 * be done to the format.
424 uintptr_t method_base;
425 uintptr_t last_method;
428 unsigned char* data_end;
433 unsigned char buf [1];
437 ign_res (int G_GNUC_UNUSED unused, ...)
441 #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++;}
442 #define EXIT_LOG(lb) (lb)->locked--;
444 typedef struct _StatBuffer StatBuffer;
453 typedef struct _BinaryObject BinaryObject;
455 struct _BinaryObject {
461 struct _MonoProfiler {
462 StatBuffer *stat_buffers;
464 #if defined (HAVE_SYS_ZLIB)
467 uint64_t startup_time;
469 int last_gc_gen_started;
474 pthread_t helper_thread;
475 pthread_t writer_thread;
477 volatile gint32 run_writer_thread;
478 MonoLockFreeQueue writer_queue;
479 MonoConcurrentHashTable *method_table;
480 mono_mutex_t method_table_mutex;
481 BinaryObject *binary_objects;
482 GPtrArray *coverage_filters;
483 GPtrArray *sorted_sample_events;
486 typedef struct _WriterQueueEntry WriterQueueEntry;
487 struct _WriterQueueEntry {
488 MonoLockFreeQueueNode node;
493 typedef struct _MethodInfo MethodInfo;
505 #define TLS_SET(x,y) (TlsSetValue (x, y))
506 #define TLS_GET(t,x) ((t *) TlsGetValue (x))
507 #define TLS_INIT(x) (x = TlsAlloc ())
508 static int tlsbuffer;
509 static int tlsmethodlist;
511 #define TLS_SET(x,y) (x = y)
512 #define TLS_GET(t,x) (x)
514 static __thread LogBuffer* tlsbuffer = NULL;
515 static __thread GPtrArray* tlsmethodlist = NULL;
517 #define TLS_SET(x,y) (pthread_setspecific (x, y))
518 #define TLS_GET(t,x) ((t *) pthread_getspecific (x))
519 #define TLS_INIT(x) (pthread_key_create (&x, NULL))
520 static pthread_key_t tlsbuffer;
521 static pthread_key_t tlsmethodlist;
524 static void safe_send (MonoProfiler *profiler, LogBuffer *logbuffer);
527 pstrdup (const char *s)
529 int len = strlen (s) + 1;
530 char *p = (char *)malloc (len);
536 create_stat_buffer (void)
538 StatBuffer* buf = (StatBuffer *)alloc_buffer (BUFFER_SIZE);
539 buf->size = BUFFER_SIZE;
540 buf->data_end = (uintptr_t*)((unsigned char*)buf + buf->size);
541 buf->data = buf->buf;
548 LogBuffer* buf = (LogBuffer *)alloc_buffer (BUFFER_SIZE);
549 buf->size = BUFFER_SIZE;
550 buf->time_base = current_time ();
551 buf->last_time = buf->time_base;
552 buf->data_end = (unsigned char*)buf + buf->size;
553 buf->data = buf->buf;
560 if (!TLS_GET (LogBuffer, tlsbuffer)) {
561 LogBuffer *logbuffer = create_buffer ();
562 TLS_SET (tlsbuffer, logbuffer);
563 logbuffer->thread_id = thread_id ();
565 if (!TLS_GET (GPtrArray, tlsmethodlist)) {
566 GPtrArray *methodlist = g_ptr_array_new ();
567 TLS_SET (tlsmethodlist, methodlist);
570 //printf ("thread %p at time %llu\n", (void*)logbuffer->thread_id, logbuffer->time_base);
574 ensure_logbuf_inner (LogBuffer *old, int bytes)
576 if (old && old->data + bytes + 100 < old->data_end)
579 LogBuffer *new_ = (LogBuffer *)create_buffer ();
580 new_->thread_id = thread_id ();
584 new_->call_depth = old->call_depth;
590 ensure_logbuf (int bytes)
592 LogBuffer *old = TLS_GET (LogBuffer, tlsbuffer);
593 LogBuffer *new_ = ensure_logbuf_inner (old, bytes);
596 return old; // Still enough space.
598 TLS_SET (tlsbuffer, new_);
605 emit_byte (LogBuffer *logbuffer, int value)
607 logbuffer->data [0] = value;
609 assert (logbuffer->data <= logbuffer->data_end);
613 emit_value (LogBuffer *logbuffer, int value)
615 encode_uleb128 (value, logbuffer->data, &logbuffer->data);
616 assert (logbuffer->data <= logbuffer->data_end);
620 emit_time (LogBuffer *logbuffer, uint64_t value)
622 uint64_t tdiff = value - logbuffer->last_time;
623 //if (value < logbuffer->last_time)
624 // printf ("time went backwards\n");
625 //if (tdiff > 1000000)
626 // printf ("large time offset: %llu\n", tdiff);
627 encode_uleb128 (tdiff, logbuffer->data, &logbuffer->data);
628 /*if (tdiff != decode_uleb128 (p, &p))
629 printf ("incorrect encoding: %llu\n", tdiff);*/
630 logbuffer->last_time = value;
631 assert (logbuffer->data <= logbuffer->data_end);
635 emit_svalue (LogBuffer *logbuffer, int64_t value)
637 encode_sleb128 (value, logbuffer->data, &logbuffer->data);
638 assert (logbuffer->data <= logbuffer->data_end);
642 emit_uvalue (LogBuffer *logbuffer, uint64_t value)
644 encode_uleb128 (value, logbuffer->data, &logbuffer->data);
645 assert (logbuffer->data <= logbuffer->data_end);
649 emit_ptr (LogBuffer *logbuffer, void *ptr)
651 if (!logbuffer->ptr_base)
652 logbuffer->ptr_base = (uintptr_t)ptr;
653 emit_svalue (logbuffer, (intptr_t)ptr - logbuffer->ptr_base);
654 assert (logbuffer->data <= logbuffer->data_end);
658 emit_method_inner (LogBuffer *logbuffer, void *method)
660 if (!logbuffer->method_base) {
661 logbuffer->method_base = (intptr_t)method;
662 logbuffer->last_method = (intptr_t)method;
664 encode_sleb128 ((intptr_t)((char*)method - (char*)logbuffer->last_method), logbuffer->data, &logbuffer->data);
665 logbuffer->last_method = (intptr_t)method;
666 assert (logbuffer->data <= logbuffer->data_end);
676 find_method (MonoDomain *domain, void *user_data)
678 MethodSearch *search = user_data;
683 MonoJitInfo *ji = mono_get_jit_info_from_method (domain, search->method);
685 // It could be AOT'd, so we need to get it from the AOT runtime's cache.
687 void *ip = mono_aot_get_method (domain, search->method);
689 // Avoid a slow path in mono_jit_info_table_find ().
691 ji = mono_jit_info_table_find (domain, ip);
700 register_method_local (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji)
702 if (!mono_conc_hashtable_lookup (prof->method_table, method)) {
704 * FIXME: In some cases, we crash while looking up JIT info for AOT'd methods.
705 * This usually happens for static constructors. This code is disabled for now
706 * as we don't need this info for anything critical.
708 * https://bugzilla.xamarin.com/show_bug.cgi?id=35171
712 MethodSearch search = { method, NULL };
714 mono_domain_foreach (find_method, &search);
721 * FIXME: We can't always find JIT info for a generic shared method, especially
722 * if we obtained the MonoMethod during an async stack walk. For now, we deal
723 * with this by giving the generic shared method name and dummy code start/size
724 * information (i.e. zeroes).
728 MethodInfo *info = (MethodInfo *)malloc (sizeof (MethodInfo));
730 info->method = method;
732 info->time = current_time ();
734 g_ptr_array_add (TLS_GET (GPtrArray, tlsmethodlist), info);
739 emit_method (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
741 register_method_local (prof, method, NULL);
742 emit_method_inner (logbuffer, method);
746 emit_method_as_ptr (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
748 register_method_local (prof, method, NULL);
749 emit_ptr (logbuffer, method);
753 emit_obj (LogBuffer *logbuffer, void *ptr)
755 if (!logbuffer->obj_base)
756 logbuffer->obj_base = (uintptr_t)ptr >> 3;
757 emit_svalue (logbuffer, ((uintptr_t)ptr >> 3) - logbuffer->obj_base);
758 assert (logbuffer->data <= logbuffer->data_end);
762 emit_string (LogBuffer *logbuffer, const char *str, size_t size)
766 for (; i < size; i++) {
769 emit_byte (logbuffer, str [i]);
772 emit_byte (logbuffer, '\0');
776 emit_double (LogBuffer *logbuffer, double value)
779 unsigned char buffer[8];
780 memcpy (buffer, &value, 8);
781 #if G_BYTE_ORDER == G_BIG_ENDIAN
782 for (i = 7; i >= 0; i--)
784 for (i = 0; i < 8; i++)
786 emit_byte (logbuffer, buffer[i]);
790 write_int16 (char *buf, int32_t value)
793 for (i = 0; i < 2; ++i) {
801 write_int32 (char *buf, int32_t value)
804 for (i = 0; i < 4; ++i) {
812 write_int64 (char *buf, int64_t value)
815 for (i = 0; i < 8; ++i) {
823 dump_header (MonoProfiler *profiler)
827 p = write_int32 (p, LOG_HEADER_ID);
828 *p++ = LOG_VERSION_MAJOR;
829 *p++ = LOG_VERSION_MINOR;
830 *p++ = LOG_DATA_VERSION;
831 *p++ = sizeof (void*);
832 p = write_int64 (p, ((uint64_t)time (NULL)) * 1000); /* startup time */
833 p = write_int32 (p, get_timer_overhead ()); /* timer overhead */
834 p = write_int32 (p, 0); /* flags */
835 p = write_int32 (p, process_id ()); /* pid */
836 p = write_int16 (p, profiler->command_port); /* port */
837 p = write_int16 (p, 0); /* opsystem */
838 #if defined (HAVE_SYS_ZLIB)
839 if (profiler->gzfile) {
840 gzwrite (profiler->gzfile, hbuf, p - hbuf);
842 fwrite (hbuf, p - hbuf, 1, profiler->file);
845 fwrite (hbuf, p - hbuf, 1, profiler->file);
846 fflush (profiler->file);
851 send_buffer (MonoProfiler *prof, GPtrArray *methods, LogBuffer *buffer)
853 WriterQueueEntry *entry = (WriterQueueEntry *)calloc (1, sizeof (WriterQueueEntry));
854 mono_lock_free_queue_node_init (&entry->node, FALSE);
855 entry->methods = methods;
856 entry->buffer = buffer;
857 mono_lock_free_queue_enqueue (&prof->writer_queue, &entry->node);
861 dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
866 dump_buffer (profiler, buf->next);
867 p = write_int32 (p, BUF_ID);
868 p = write_int32 (p, buf->data - buf->buf);
869 p = write_int64 (p, buf->time_base);
870 p = write_int64 (p, buf->ptr_base);
871 p = write_int64 (p, buf->obj_base);
872 p = write_int64 (p, buf->thread_id);
873 p = write_int64 (p, buf->method_base);
874 #if defined (HAVE_SYS_ZLIB)
875 if (profiler->gzfile) {
876 gzwrite (profiler->gzfile, hbuf, p - hbuf);
877 gzwrite (profiler->gzfile, buf->buf, buf->data - buf->buf);
880 fwrite (hbuf, p - hbuf, 1, profiler->file);
881 fwrite (buf->buf, buf->data - buf->buf, 1, profiler->file);
882 fflush (profiler->file);
883 #if defined (HAVE_SYS_ZLIB)
886 free_buffer (buf, buf->size);
890 process_requests (MonoProfiler *profiler)
892 if (heapshot_requested)
893 mono_gc_collect (mono_gc_max_generation ());
896 static void counters_init (MonoProfiler *profiler);
897 static void counters_sample (MonoProfiler *profiler, uint64_t timestamp);
900 * Can be called only at safe callback locations.
903 safe_send (MonoProfiler *profiler, LogBuffer *logbuffer)
905 /* We need the runtime initialized so that we have threads and hazard
906 * pointers available. Otherwise, the lock free queue will not work and
907 * there won't be a thread to process the data.
909 * While the runtime isn't initialized, we just accumulate data in the
910 * thread local buffer list.
912 if (!InterlockedRead (&runtime_inited))
915 int cd = logbuffer->call_depth;
917 send_buffer (profiler, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
919 TLS_SET (tlsbuffer, NULL);
920 TLS_SET (tlsmethodlist, NULL);
924 TLS_GET (LogBuffer, tlsbuffer)->call_depth = cd;
928 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
931 uintptr_t last_offset = 0;
932 //const char *name = mono_class_get_name (klass);
933 LogBuffer *logbuffer = ensure_logbuf (
934 EVENT_SIZE /* event */ +
935 LEB128_SIZE /* obj */ +
936 LEB128_SIZE /* klass */ +
937 LEB128_SIZE /* size */ +
938 LEB128_SIZE /* num */ +
940 LEB128_SIZE /* offset */ +
941 LEB128_SIZE /* ref */
944 emit_byte (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
945 emit_obj (logbuffer, obj);
946 emit_ptr (logbuffer, klass);
947 /* account for object alignment in the heap */
950 emit_value (logbuffer, size);
951 emit_value (logbuffer, num);
952 for (i = 0; i < num; ++i) {
953 emit_value (logbuffer, offsets [i] - last_offset);
954 last_offset = offsets [i];
955 emit_obj (logbuffer, refs [i]);
958 // printf ("obj: %p, klass: %s, refs: %d, size: %d\n", obj, name, (int)num, (int)size);
962 static unsigned int hs_mode_ms = 0;
963 static unsigned int hs_mode_gc = 0;
964 static unsigned int hs_mode_ondemand = 0;
965 static unsigned int gc_count = 0;
966 static uint64_t last_hs_time = 0;
969 heap_walk (MonoProfiler *profiler)
973 LogBuffer *logbuffer;
976 logbuffer = ensure_logbuf (
977 EVENT_SIZE /* event */ +
978 LEB128_SIZE /* time */
980 now = current_time ();
981 if (hs_mode_ms && (now - last_hs_time)/1000000 >= hs_mode_ms)
983 else if (hs_mode_gc && (gc_count % hs_mode_gc) == 0)
985 else if (hs_mode_ondemand)
986 do_walk = heapshot_requested;
987 else if (!hs_mode_ms && !hs_mode_gc && profiler->last_gc_gen_started == mono_gc_max_generation ())
992 heapshot_requested = 0;
993 emit_byte (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
994 emit_time (logbuffer, now);
995 mono_gc_walk_heap (0, gc_reference, NULL);
996 logbuffer = ensure_logbuf (
997 EVENT_SIZE /* event */ +
998 LEB128_SIZE /* time */
1000 now = current_time ();
1001 emit_byte (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
1002 emit_time (logbuffer, now);
1007 gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation) {
1009 LogBuffer *logbuffer = ensure_logbuf (
1010 EVENT_SIZE /* event */ +
1011 LEB128_SIZE /* time */ +
1012 LEB128_SIZE /* gc event */ +
1013 LEB128_SIZE /* generation */
1015 now = current_time ();
1016 ENTER_LOG (logbuffer, "gcevent");
1017 emit_byte (logbuffer, TYPE_GC_EVENT | TYPE_GC);
1018 emit_time (logbuffer, now);
1019 emit_value (logbuffer, ev);
1020 emit_value (logbuffer, generation);
1021 /* to deal with nested gen1 after gen0 started */
1022 if (ev == MONO_GC_EVENT_START) {
1023 profiler->last_gc_gen_started = generation;
1024 if (generation == mono_gc_max_generation ())
1027 if (ev == MONO_GC_EVENT_PRE_START_WORLD)
1028 heap_walk (profiler);
1029 EXIT_LOG (logbuffer);
1030 if (ev == MONO_GC_EVENT_POST_START_WORLD)
1031 safe_send (profiler, logbuffer);
1032 //printf ("gc event %d for generation %d\n", ev, generation);
1036 gc_resize (MonoProfiler *profiler, int64_t new_size) {
1038 LogBuffer *logbuffer = ensure_logbuf (
1039 EVENT_SIZE /* event */ +
1040 LEB128_SIZE /* time */ +
1041 LEB128_SIZE /* new size */
1043 now = current_time ();
1044 ENTER_LOG (logbuffer, "gcresize");
1045 emit_byte (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
1046 emit_time (logbuffer, now);
1047 emit_value (logbuffer, new_size);
1048 //printf ("gc resized to %lld\n", new_size);
1049 EXIT_LOG (logbuffer);
1052 #define MAX_FRAMES 32
1055 MonoMethod* methods [MAX_FRAMES];
1056 int32_t il_offsets [MAX_FRAMES];
1057 int32_t native_offsets [MAX_FRAMES];
1059 static int num_frames = MAX_FRAMES;
1062 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
1064 FrameData *frame = (FrameData *)data;
1065 if (method && frame->count < num_frames) {
1066 frame->il_offsets [frame->count] = il_offset;
1067 frame->native_offsets [frame->count] = native_offset;
1068 frame->methods [frame->count++] = method;
1069 //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
1071 return frame->count == num_frames;
1075 * a note about stack walks: they can cause more profiler events to fire,
1076 * so we need to make sure they don't happen after we started emitting an
1077 * event, hence the collect_bt/emit_bt split.
1080 collect_bt (FrameData *data)
1083 mono_stack_walk_no_il (walk_stack, data);
1087 emit_bt (MonoProfiler *prof, LogBuffer *logbuffer, FrameData *data)
1089 /* FIXME: this is actually tons of data and we should
1090 * just output it the first time and use an id the next
1092 if (data->count > num_frames)
1093 printf ("bad num frames: %d\n", data->count);
1094 emit_value (logbuffer, 0); /* flags */
1095 emit_value (logbuffer, data->count);
1096 //if (*p != data.count) {
1097 // printf ("bad num frames enc at %d: %d -> %d\n", count, data.count, *p); printf ("frames end: %p->%p\n", p, logbuffer->data); exit(0);}
1098 while (data->count) {
1099 emit_method_as_ptr (prof, logbuffer, data->methods [--data->count]);
1104 gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1108 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces)? TYPE_ALLOC_BT: 0;
1110 LogBuffer *logbuffer;
1111 len = mono_object_get_size (obj);
1112 /* account for object alignment in the heap */
1117 logbuffer = ensure_logbuf (
1118 EVENT_SIZE /* event */ +
1119 LEB128_SIZE /* time */ +
1120 LEB128_SIZE /* klass */ +
1121 LEB128_SIZE /* obj */ +
1122 LEB128_SIZE /* size */ +
1124 LEB128_SIZE /* flags */ +
1125 LEB128_SIZE /* count */ +
1127 LEB128_SIZE /* method */
1131 now = current_time ();
1132 ENTER_LOG (logbuffer, "gcalloc");
1133 emit_byte (logbuffer, do_bt | TYPE_ALLOC);
1134 emit_time (logbuffer, now);
1135 emit_ptr (logbuffer, klass);
1136 emit_obj (logbuffer, obj);
1137 emit_value (logbuffer, len);
1139 emit_bt (prof, logbuffer, &data);
1140 EXIT_LOG (logbuffer);
1141 if (logbuffer->next)
1142 safe_send (prof, logbuffer);
1143 process_requests (prof);
1144 //printf ("gc alloc %s at %p\n", mono_class_get_name (klass), obj);
1148 gc_moves (MonoProfiler *prof, void **objects, int num)
1152 LogBuffer *logbuffer = ensure_logbuf (
1153 EVENT_SIZE /* event */ +
1154 LEB128_SIZE /* time */ +
1155 LEB128_SIZE /* num */ +
1157 LEB128_SIZE /* object */
1160 now = current_time ();
1161 ENTER_LOG (logbuffer, "gcmove");
1162 emit_byte (logbuffer, TYPE_GC_MOVE | TYPE_GC);
1163 emit_time (logbuffer, now);
1164 emit_value (logbuffer, num);
1165 for (i = 0; i < num; ++i)
1166 emit_obj (logbuffer, objects [i]);
1167 //printf ("gc moved %d objects\n", num/2);
1168 EXIT_LOG (logbuffer);
1172 gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
1175 LogBuffer *logbuffer = ensure_logbuf (
1176 EVENT_SIZE /* event */ +
1177 LEB128_SIZE /* num */ +
1178 LEB128_SIZE /* collections */ +
1180 LEB128_SIZE /* object */ +
1181 LEB128_SIZE /* root type */ +
1182 LEB128_SIZE /* extra info */
1185 ENTER_LOG (logbuffer, "gcroots");
1186 emit_byte (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
1187 emit_value (logbuffer, num);
1188 emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
1189 for (i = 0; i < num; ++i) {
1190 emit_obj (logbuffer, objects [i]);
1191 emit_value (logbuffer, root_types [i]);
1192 emit_value (logbuffer, extra_info [i]);
1194 EXIT_LOG (logbuffer);
1198 gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
1200 int do_bt = nocalls && InterlockedRead (&runtime_inited) && !notraces;
1207 LogBuffer *logbuffer = ensure_logbuf (
1208 EVENT_SIZE /* event */ +
1209 LEB128_SIZE /* time */ +
1210 LEB128_SIZE /* type */ +
1211 LEB128_SIZE /* handle */ +
1212 (op == MONO_PROFILER_GC_HANDLE_CREATED ? (
1213 LEB128_SIZE /* obj */
1216 LEB128_SIZE /* flags */ +
1217 LEB128_SIZE /* count */ +
1219 LEB128_SIZE /* method */
1224 now = current_time ();
1225 ENTER_LOG (logbuffer, "gchandle");
1227 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1228 emit_byte (logbuffer, (do_bt ? TYPE_GC_HANDLE_CREATED_BT : TYPE_GC_HANDLE_CREATED) | TYPE_GC);
1229 else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
1230 emit_byte (logbuffer, (do_bt ? TYPE_GC_HANDLE_DESTROYED_BT : TYPE_GC_HANDLE_DESTROYED) | TYPE_GC);
1232 g_assert_not_reached ();
1234 emit_time (logbuffer, now);
1235 emit_value (logbuffer, type);
1236 emit_value (logbuffer, handle);
1238 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1239 emit_obj (logbuffer, obj);
1242 emit_bt (prof, logbuffer, &data);
1244 EXIT_LOG (logbuffer);
1245 process_requests (prof);
1249 push_nesting (char *p, MonoClass *klass)
1254 nesting = mono_class_get_nesting_type (klass);
1256 p = push_nesting (p, nesting);
1260 name = mono_class_get_name (klass);
1261 nspace = mono_class_get_namespace (klass);
1264 p += strlen (nspace);
1274 type_name (MonoClass *klass)
1278 push_nesting (buf, klass);
1279 p = (char *)malloc (strlen (buf) + 1);
1285 image_loaded (MonoProfiler *prof, MonoImage *image, int result)
1290 LogBuffer *logbuffer;
1291 if (result != MONO_PROFILE_OK)
1293 name = mono_image_get_filename (image);
1294 nlen = strlen (name) + 1;
1295 logbuffer = ensure_logbuf (
1296 EVENT_SIZE /* event */ +
1297 LEB128_SIZE /* time */ +
1298 EVENT_SIZE /* type */ +
1299 LEB128_SIZE /* image */ +
1300 LEB128_SIZE /* flags */ +
1303 now = current_time ();
1304 ENTER_LOG (logbuffer, "image");
1305 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1306 emit_time (logbuffer, now);
1307 emit_byte (logbuffer, TYPE_IMAGE);
1308 emit_ptr (logbuffer, image);
1309 emit_value (logbuffer, 0); /* flags */
1310 memcpy (logbuffer->data, name, nlen);
1311 logbuffer->data += nlen;
1312 //printf ("loaded image %p (%s)\n", image, name);
1313 EXIT_LOG (logbuffer);
1314 if (logbuffer->next)
1315 safe_send (prof, logbuffer);
1316 process_requests (prof);
1320 image_unloaded (MonoProfiler *prof, MonoImage *image)
1322 const char *name = mono_image_get_filename (image);
1323 int nlen = strlen (name) + 1;
1324 LogBuffer *logbuffer = ensure_logbuf (
1325 EVENT_SIZE /* event */ +
1326 LEB128_SIZE /* time */ +
1327 EVENT_SIZE /* type */ +
1328 LEB128_SIZE /* image */ +
1329 LEB128_SIZE /* flags */ +
1332 uint64_t now = current_time ();
1334 ENTER_LOG (logbuffer, "image-unload");
1335 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1336 emit_time (logbuffer, now);
1337 emit_byte (logbuffer, TYPE_IMAGE);
1338 emit_ptr (logbuffer, image);
1339 emit_value (logbuffer, 0); /* flags */
1340 memcpy (logbuffer->data, name, nlen);
1341 logbuffer->data += nlen;
1342 EXIT_LOG (logbuffer);
1344 if (logbuffer->next)
1345 safe_send (prof, logbuffer);
1347 process_requests (prof);
1351 assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly, int result)
1353 if (result != MONO_PROFILE_OK)
1356 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1357 int nlen = strlen (name) + 1;
1358 LogBuffer *logbuffer = ensure_logbuf (
1359 EVENT_SIZE /* event */ +
1360 LEB128_SIZE /* time */ +
1361 EVENT_SIZE /* type */ +
1362 LEB128_SIZE /* assembly */ +
1363 LEB128_SIZE /* flags */ +
1366 uint64_t now = current_time ();
1368 ENTER_LOG (logbuffer, "assembly-load");
1369 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1370 emit_time (logbuffer, now);
1371 emit_byte (logbuffer, TYPE_ASSEMBLY);
1372 emit_ptr (logbuffer, assembly);
1373 emit_value (logbuffer, 0); /* flags */
1374 memcpy (logbuffer->data, name, nlen);
1375 logbuffer->data += nlen;
1376 EXIT_LOG (logbuffer);
1380 if (logbuffer->next)
1381 safe_send (prof, logbuffer);
1383 process_requests (prof);
1387 assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
1389 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1390 int nlen = strlen (name) + 1;
1391 LogBuffer *logbuffer = ensure_logbuf (
1392 EVENT_SIZE /* event */ +
1393 LEB128_SIZE /* time */ +
1394 EVENT_SIZE /* type */ +
1395 LEB128_SIZE /* assembly */ +
1396 LEB128_SIZE /* flags */ +
1399 uint64_t now = current_time ();
1401 ENTER_LOG (logbuffer, "assembly-unload");
1402 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1403 emit_time (logbuffer, now);
1404 emit_byte (logbuffer, TYPE_ASSEMBLY);
1405 emit_ptr (logbuffer, assembly);
1406 emit_value (logbuffer, 0); /* flags */
1407 memcpy (logbuffer->data, name, nlen);
1408 logbuffer->data += nlen;
1409 EXIT_LOG (logbuffer);
1413 if (logbuffer->next)
1414 safe_send (prof, logbuffer);
1416 process_requests (prof);
1420 class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
1426 LogBuffer *logbuffer;
1427 if (result != MONO_PROFILE_OK)
1429 if (InterlockedRead (&runtime_inited))
1430 name = mono_type_get_name (mono_class_get_type (klass));
1432 name = type_name (klass);
1433 nlen = strlen (name) + 1;
1434 image = mono_class_get_image (klass);
1435 logbuffer = ensure_logbuf (
1436 EVENT_SIZE /* event */ +
1437 LEB128_SIZE /* time */ +
1438 EVENT_SIZE /* type */ +
1439 LEB128_SIZE /* klass */ +
1440 LEB128_SIZE /* image */ +
1441 LEB128_SIZE /* flags */ +
1444 now = current_time ();
1445 ENTER_LOG (logbuffer, "class");
1446 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1447 emit_time (logbuffer, now);
1448 emit_byte (logbuffer, TYPE_CLASS);
1449 emit_ptr (logbuffer, klass);
1450 emit_ptr (logbuffer, image);
1451 emit_value (logbuffer, 0); /* flags */
1452 memcpy (logbuffer->data, name, nlen);
1453 logbuffer->data += nlen;
1454 //printf ("loaded class %p (%s)\n", klass, name);
1459 EXIT_LOG (logbuffer);
1460 if (logbuffer->next)
1461 safe_send (prof, logbuffer);
1462 process_requests (prof);
1466 class_unloaded (MonoProfiler *prof, MonoClass *klass)
1470 if (InterlockedRead (&runtime_inited))
1471 name = mono_type_get_name (mono_class_get_type (klass));
1473 name = type_name (klass);
1475 int nlen = strlen (name) + 1;
1476 MonoImage *image = mono_class_get_image (klass);
1477 LogBuffer *logbuffer = ensure_logbuf (
1478 EVENT_SIZE /* event */ +
1479 LEB128_SIZE /* time */ +
1480 EVENT_SIZE /* type */ +
1481 LEB128_SIZE /* klass */ +
1482 LEB128_SIZE /* image */ +
1483 LEB128_SIZE /* flags */ +
1486 uint64_t now = current_time ();
1488 ENTER_LOG (logbuffer, "class-unload");
1489 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1490 emit_time (logbuffer, now);
1491 emit_byte (logbuffer, TYPE_CLASS);
1492 emit_ptr (logbuffer, klass);
1493 emit_ptr (logbuffer, image);
1494 emit_value (logbuffer, 0); /* flags */
1495 memcpy (logbuffer->data, name, nlen);
1496 logbuffer->data += nlen;
1497 EXIT_LOG (logbuffer);
1504 if (logbuffer->next)
1505 safe_send (prof, logbuffer);
1507 process_requests (prof);
1510 #ifndef DISABLE_HELPER_THREAD
1511 static void process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method);
1512 #endif /* DISABLE_HELPER_THREAD */
1515 method_enter (MonoProfiler *prof, MonoMethod *method)
1517 uint64_t now = current_time ();
1519 #ifndef DISABLE_HELPER_THREAD
1520 process_method_enter_coverage (prof, method);
1521 #endif /* DISABLE_HELPER_THREAD */
1523 LogBuffer *logbuffer = ensure_logbuf (
1524 EVENT_SIZE /* event */ +
1525 LEB128_SIZE /* time */ +
1526 LEB128_SIZE /* method */
1528 if (logbuffer->call_depth++ > max_call_depth)
1530 ENTER_LOG (logbuffer, "enter");
1531 emit_byte (logbuffer, TYPE_ENTER | TYPE_METHOD);
1532 emit_time (logbuffer, now);
1533 emit_method (prof, logbuffer, method);
1534 EXIT_LOG (logbuffer);
1536 process_requests (prof);
1540 method_leave (MonoProfiler *prof, MonoMethod *method)
1543 LogBuffer *logbuffer = ensure_logbuf (
1544 EVENT_SIZE /* event */ +
1545 LEB128_SIZE /* time */ +
1546 LEB128_SIZE /* method */
1548 if (--logbuffer->call_depth > max_call_depth)
1550 now = current_time ();
1551 ENTER_LOG (logbuffer, "leave");
1552 emit_byte (logbuffer, TYPE_LEAVE | TYPE_METHOD);
1553 emit_time (logbuffer, now);
1554 emit_method (prof, logbuffer, method);
1555 EXIT_LOG (logbuffer);
1556 if (logbuffer->next)
1557 safe_send (prof, logbuffer);
1558 process_requests (prof);
1562 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
1565 LogBuffer *logbuffer;
1568 logbuffer = ensure_logbuf (
1569 EVENT_SIZE /* event */ +
1570 LEB128_SIZE /* time */ +
1571 LEB128_SIZE /* method */
1573 if (--logbuffer->call_depth > max_call_depth)
1575 now = current_time ();
1576 ENTER_LOG (logbuffer, "eleave");
1577 emit_byte (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
1578 emit_time (logbuffer, now);
1579 emit_method (prof, logbuffer, method);
1580 EXIT_LOG (logbuffer);
1581 process_requests (prof);
1585 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji, int result)
1587 if (result != MONO_PROFILE_OK)
1590 register_method_local (prof, method, ji);
1592 process_requests (prof);
1596 code_buffer_new (MonoProfiler *prof, void *buffer, int size, MonoProfilerCodeBufferType type, void *data)
1601 LogBuffer *logbuffer;
1602 if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
1603 name = (char *)data;
1604 nlen = strlen (name) + 1;
1609 logbuffer = ensure_logbuf (
1610 EVENT_SIZE /* event */ +
1611 LEB128_SIZE /* time */ +
1612 LEB128_SIZE /* type */ +
1613 LEB128_SIZE /* buffer */ +
1614 LEB128_SIZE /* size */ +
1619 now = current_time ();
1620 ENTER_LOG (logbuffer, "code buffer");
1621 emit_byte (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
1622 emit_time (logbuffer, now);
1623 emit_value (logbuffer, type);
1624 emit_ptr (logbuffer, buffer);
1625 emit_value (logbuffer, size);
1627 memcpy (logbuffer->data, name, nlen);
1628 logbuffer->data += nlen;
1630 EXIT_LOG (logbuffer);
1631 process_requests (prof);
1635 throw_exc (MonoProfiler *prof, MonoObject *object)
1637 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces)? TYPE_EXCEPTION_BT: 0;
1640 LogBuffer *logbuffer;
1643 logbuffer = ensure_logbuf (
1644 EVENT_SIZE /* event */ +
1645 LEB128_SIZE /* time */ +
1646 LEB128_SIZE /* object */ +
1648 LEB128_SIZE /* flags */ +
1649 LEB128_SIZE /* count */ +
1651 LEB128_SIZE /* method */
1655 now = current_time ();
1656 ENTER_LOG (logbuffer, "throw");
1657 emit_byte (logbuffer, do_bt | TYPE_EXCEPTION);
1658 emit_time (logbuffer, now);
1659 emit_obj (logbuffer, object);
1661 emit_bt (prof, logbuffer, &data);
1662 EXIT_LOG (logbuffer);
1663 process_requests (prof);
1667 clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
1670 LogBuffer *logbuffer = ensure_logbuf (
1671 EVENT_SIZE /* event */ +
1672 LEB128_SIZE /* time */ +
1673 LEB128_SIZE /* clause type */ +
1674 LEB128_SIZE /* clause num */ +
1675 LEB128_SIZE /* method */
1677 now = current_time ();
1678 ENTER_LOG (logbuffer, "clause");
1679 emit_byte (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
1680 emit_time (logbuffer, now);
1681 emit_value (logbuffer, clause_type);
1682 emit_value (logbuffer, clause_num);
1683 emit_method (prof, logbuffer, method);
1684 EXIT_LOG (logbuffer);
1686 process_requests (prof);
1690 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
1692 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION)? TYPE_MONITOR_BT: 0;
1695 LogBuffer *logbuffer;
1698 logbuffer = ensure_logbuf (
1699 EVENT_SIZE /* event */ +
1700 LEB128_SIZE /* time */ +
1701 LEB128_SIZE /* object */ +
1703 LEB128_SIZE /* flags */ +
1704 LEB128_SIZE /* count */ +
1706 LEB128_SIZE /* method */
1710 now = current_time ();
1711 ENTER_LOG (logbuffer, "monitor");
1712 emit_byte (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
1713 emit_time (logbuffer, now);
1714 emit_obj (logbuffer, object);
1716 emit_bt (profiler, logbuffer, &data);
1717 EXIT_LOG (logbuffer);
1718 process_requests (profiler);
1722 thread_start (MonoProfiler *prof, uintptr_t tid)
1724 //printf ("thread start %p\n", (void*)tid);
1727 LogBuffer *logbuffer = ensure_logbuf (
1728 EVENT_SIZE /* event */ +
1729 LEB128_SIZE /* time */ +
1730 EVENT_SIZE /* type */ +
1731 LEB128_SIZE /* tid */ +
1732 LEB128_SIZE /* flags */
1734 uint64_t now = current_time ();
1736 ENTER_LOG (logbuffer, "thread-start");
1737 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1738 emit_time (logbuffer, now);
1739 emit_byte (logbuffer, TYPE_THREAD);
1740 emit_ptr (logbuffer, (void*) tid);
1741 emit_value (logbuffer, 0); /* flags */
1742 EXIT_LOG (logbuffer);
1744 if (logbuffer->next)
1745 safe_send (prof, logbuffer);
1747 process_requests (prof);
1751 thread_end (MonoProfiler *prof, uintptr_t tid)
1753 if (TLS_GET (LogBuffer, tlsbuffer)) {
1754 LogBuffer *logbuffer = ensure_logbuf (
1755 EVENT_SIZE /* event */ +
1756 LEB128_SIZE /* time */ +
1757 EVENT_SIZE /* type */ +
1758 LEB128_SIZE /* tid */ +
1759 LEB128_SIZE /* flags */
1761 uint64_t now = current_time ();
1763 ENTER_LOG (logbuffer, "thread-end");
1764 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1765 emit_time (logbuffer, now);
1766 emit_byte (logbuffer, TYPE_THREAD);
1767 emit_ptr (logbuffer, (void*) tid);
1768 emit_value (logbuffer, 0); /* flags */
1769 EXIT_LOG (logbuffer);
1771 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), logbuffer);
1773 /* Don't process requests as the thread is detached from the runtime. */
1776 TLS_SET (tlsbuffer, NULL);
1777 TLS_SET (tlsmethodlist, NULL);
1781 domain_loaded (MonoProfiler *prof, MonoDomain *domain, int result)
1783 if (result != MONO_PROFILE_OK)
1786 LogBuffer *logbuffer = ensure_logbuf (
1787 EVENT_SIZE /* event */ +
1788 LEB128_SIZE /* time */ +
1789 EVENT_SIZE /* type */ +
1790 LEB128_SIZE /* domain id */ +
1791 LEB128_SIZE /* flags */
1793 uint64_t now = current_time ();
1795 ENTER_LOG (logbuffer, "domain-start");
1796 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1797 emit_time (logbuffer, now);
1798 emit_byte (logbuffer, TYPE_DOMAIN);
1799 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1800 emit_value (logbuffer, 0); /* flags */
1801 EXIT_LOG (logbuffer);
1803 if (logbuffer->next)
1804 safe_send (prof, logbuffer);
1806 process_requests (prof);
1810 domain_unloaded (MonoProfiler *prof, MonoDomain *domain)
1812 LogBuffer *logbuffer = ensure_logbuf (
1813 EVENT_SIZE /* event */ +
1814 LEB128_SIZE /* time */ +
1815 EVENT_SIZE /* type */ +
1816 LEB128_SIZE /* domain id */ +
1817 LEB128_SIZE /* flags */
1819 uint64_t now = current_time ();
1821 ENTER_LOG (logbuffer, "domain-end");
1822 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1823 emit_time (logbuffer, now);
1824 emit_byte (logbuffer, TYPE_DOMAIN);
1825 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1826 emit_value (logbuffer, 0); /* flags */
1827 EXIT_LOG (logbuffer);
1829 if (logbuffer->next)
1830 safe_send (prof, logbuffer);
1832 process_requests (prof);
1836 domain_name (MonoProfiler *prof, MonoDomain *domain, const char *name)
1838 int nlen = strlen (name) + 1;
1839 LogBuffer *logbuffer = ensure_logbuf (
1840 EVENT_SIZE /* event */ +
1841 LEB128_SIZE /* time */ +
1842 EVENT_SIZE /* type */ +
1843 LEB128_SIZE /* domain id */ +
1844 LEB128_SIZE /* flags */ +
1847 uint64_t now = current_time ();
1849 ENTER_LOG (logbuffer, "domain-name");
1850 emit_byte (logbuffer, TYPE_METADATA);
1851 emit_time (logbuffer, now);
1852 emit_byte (logbuffer, TYPE_DOMAIN);
1853 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1854 emit_value (logbuffer, 0); /* flags */
1855 memcpy (logbuffer->data, name, nlen);
1856 logbuffer->data += nlen;
1857 EXIT_LOG (logbuffer);
1859 if (logbuffer->next)
1860 safe_send (prof, logbuffer);
1862 process_requests (prof);
1866 context_loaded (MonoProfiler *prof, MonoAppContext *context)
1868 LogBuffer *logbuffer = ensure_logbuf (
1869 EVENT_SIZE /* event */ +
1870 LEB128_SIZE /* time */ +
1871 EVENT_SIZE /* type */ +
1872 LEB128_SIZE /* context id */ +
1873 LEB128_SIZE /* flags */ +
1874 LEB128_SIZE /* domain id */
1876 uint64_t now = current_time ();
1878 ENTER_LOG (logbuffer, "context-start");
1879 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1880 emit_time (logbuffer, now);
1881 emit_byte (logbuffer, TYPE_CONTEXT);
1882 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
1883 emit_value (logbuffer, 0); /* flags */
1884 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
1885 EXIT_LOG (logbuffer);
1887 if (logbuffer->next)
1888 safe_send (prof, logbuffer);
1890 process_requests (prof);
1894 context_unloaded (MonoProfiler *prof, MonoAppContext *context)
1896 LogBuffer *logbuffer = ensure_logbuf (
1897 EVENT_SIZE /* event */ +
1898 LEB128_SIZE /* time */ +
1899 EVENT_SIZE /* type */ +
1900 LEB128_SIZE /* context id */ +
1901 LEB128_SIZE /* flags */ +
1902 LEB128_SIZE /* domain id */
1904 uint64_t now = current_time ();
1906 ENTER_LOG (logbuffer, "context-end");
1907 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1908 emit_time (logbuffer, now);
1909 emit_byte (logbuffer, TYPE_CONTEXT);
1910 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
1911 emit_value (logbuffer, 0); /* flags */
1912 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
1913 EXIT_LOG (logbuffer);
1915 if (logbuffer->next)
1916 safe_send (prof, logbuffer);
1918 process_requests (prof);
1922 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
1924 int len = strlen (name) + 1;
1926 LogBuffer *logbuffer;
1927 logbuffer = ensure_logbuf (
1928 EVENT_SIZE /* event */ +
1929 LEB128_SIZE /* time */ +
1930 EVENT_SIZE /* type */ +
1931 LEB128_SIZE /* tid */ +
1932 LEB128_SIZE /* flags */ +
1935 now = current_time ();
1936 ENTER_LOG (logbuffer, "tname");
1937 emit_byte (logbuffer, TYPE_METADATA);
1938 emit_time (logbuffer, now);
1939 emit_byte (logbuffer, TYPE_THREAD);
1940 emit_ptr (logbuffer, (void*)tid);
1941 emit_value (logbuffer, 0); /* flags */
1942 memcpy (logbuffer->data, name, len);
1943 logbuffer->data += len;
1944 EXIT_LOG (logbuffer);
1946 if (logbuffer->next)
1947 safe_send (prof, logbuffer);
1949 process_requests (prof);
1961 AsyncFrameInfo *data;
1965 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
1967 AsyncFrameData *frame = (AsyncFrameData *)data;
1968 if (frame->count < num_frames) {
1969 frame->data [frame->count].method = method;
1970 frame->data [frame->count].domain = domain;
1971 frame->data [frame->count].base_address = base_address;
1972 frame->data [frame->count].offset = offset;
1973 // printf ("In %d at %p (dom %p) (native: %p)\n", frame->count, method, domain, base_address);
1976 return frame->count == num_frames;
1980 (type | frame count), tid, time, ip, [method, domain, base address, offset] * frames
1982 #define SAMPLE_EVENT_SIZE_IN_SLOTS(FRAMES) (4 + (FRAMES) * 4)
1985 mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
1988 AsyncFrameInfo frames [num_frames];
1989 AsyncFrameData bt_data = { 0, &frames [0]};
1991 uintptr_t *data, *new_data, *old_data;
1997 now = current_time ();
1999 mono_stack_walk_async_safe (&async_walk_stack, context, &bt_data);
2001 elapsed = (now - profiler->startup_time) / 10000;
2005 snprintf (buf, sizeof (buf), "hit at %p in thread %p after %llu ms\n", ip, (void*)thread_id (), (unsigned long long int)elapsed/100);
2007 ign_res (write (2, buf, len));
2009 sbuf = profiler->stat_buffers;
2012 /* flush the buffer at 1 second intervals */
2013 if (sbuf->data > sbuf->buf && (elapsed - sbuf->buf [2]) > 100000) {
2016 /* overflow: 400 slots is a big enough number to reduce the chance of losing this event if many
2017 * threads hit this same spot at the same time
2019 if (timedout || (sbuf->data + 400 >= sbuf->data_end)) {
2020 StatBuffer *oldsb, *foundsb;
2021 sbuf = create_stat_buffer ();
2023 oldsb = profiler->stat_buffers;
2025 foundsb = (StatBuffer *)InterlockedCompareExchangePointer ((void * volatile*)&profiler->stat_buffers, sbuf, oldsb);
2026 } while (foundsb != oldsb);
2028 ign_res (write (2, "overflow\n", 9));
2029 /* notify the helper thread */
2030 if (sbuf->next->next) {
2032 ign_res (write (profiler->pipes [1], &c, 1));
2034 ign_res (write (2, "notify\n", 7));
2038 old_data = sbuf->data;
2039 new_data = old_data + SAMPLE_EVENT_SIZE_IN_SLOTS (bt_data.count);
2040 data = (uintptr_t *)InterlockedCompareExchangePointer ((void * volatile*)&sbuf->data, new_data, old_data);
2041 } while (data != old_data);
2042 if (old_data >= sbuf->data_end)
2043 return; /* lost event */
2044 old_data [0] = 1 | (sample_type << 16) | (bt_data.count << 8);
2045 old_data [1] = thread_id ();
2046 old_data [2] = elapsed;
2047 old_data [3] = (uintptr_t)ip;
2048 for (i = 0; i < bt_data.count; ++i) {
2049 old_data [4 + 4 * i + 0] = (uintptr_t)frames [i].method;
2050 old_data [4 + 4 * i + 1] = (uintptr_t)frames [i].domain;
2051 old_data [4 + 4 * i + 2] = (uintptr_t)frames [i].base_address;
2052 old_data [4 + 4 * i + 3] = (uintptr_t)frames [i].offset;
2056 static uintptr_t *code_pages = 0;
2057 static int num_code_pages = 0;
2058 static int size_code_pages = 0;
2059 #define CPAGE_SHIFT (9)
2060 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
2061 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
2062 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
2065 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
2068 uintptr_t start_pos;
2069 start_pos = (page >> CPAGE_SHIFT) % hsize;
2072 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
2074 } else if (!hash [i]) {
2081 } while (i != start_pos);
2082 /* should not happen */
2083 printf ("failed code page store\n");
2088 add_code_pointer (uintptr_t ip)
2091 if (num_code_pages * 2 >= size_code_pages) {
2093 uintptr_t old_size = size_code_pages;
2094 size_code_pages *= 2;
2095 if (size_code_pages == 0)
2096 size_code_pages = 16;
2097 n = (uintptr_t *)calloc (sizeof (uintptr_t) * size_code_pages, 1);
2098 for (i = 0; i < old_size; ++i) {
2100 add_code_page (n, size_code_pages, code_pages [i]);
2106 num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
2109 /* ELF code crashes on some systems. */
2110 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2113 dump_ubin (const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
2116 LogBuffer *logbuffer;
2118 len = strlen (filename) + 1;
2119 now = current_time ();
2120 logbuffer = ensure_logbuf (
2121 EVENT_SIZE /* event */ +
2122 LEB128_SIZE /* time */ +
2123 LEB128_SIZE /* load address */ +
2124 LEB128_SIZE /* offset */ +
2125 LEB128_SIZE /* size */ +
2126 nlen /* file name */
2128 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
2129 emit_time (logbuffer, now);
2130 emit_svalue (logbuffer, load_addr);
2131 emit_uvalue (logbuffer, offset);
2132 emit_uvalue (logbuffer, size);
2133 memcpy (logbuffer->data, filename, len);
2134 logbuffer->data += len;
2139 dump_usym (const char *name, uintptr_t value, uintptr_t size)
2141 LogBuffer *logbuffer;
2143 len = strlen (name) + 1;
2144 logbuffer = ensure_logbuf (
2145 EVENT_SIZE /* event */ +
2146 LEB128_SIZE /* value */ +
2147 LEB128_SIZE /* size */ +
2150 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
2151 emit_ptr (logbuffer, (void*)value);
2152 emit_value (logbuffer, size);
2153 memcpy (logbuffer->data, name, len);
2154 logbuffer->data += len;
2157 /* ELF code crashes on some systems. */
2158 //#if defined(ELFMAG0)
2161 #if SIZEOF_VOID_P == 4
2162 #define ELF_WSIZE 32
2164 #define ELF_WSIZE 64
2167 #define ElfW(type) _ElfW (Elf, ELF_WSIZE, type)
2168 #define _ElfW(e,w,t) _ElfW_1 (e, w, _##t)
2169 #define _ElfW_1(e,w,t) e##w##t
2173 dump_elf_symbols (ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
2176 for (i = 0; i < num_symbols; ++i) {
2178 sym = strtab + symbols [i].st_name;
2179 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
2181 //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
2182 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
2187 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
2194 ElfW(Shdr) *sheader;
2195 ElfW(Shdr) *shstrtabh;
2196 ElfW(Shdr) *symtabh = NULL;
2197 ElfW(Shdr) *strtabh = NULL;
2198 ElfW(Sym) *symbols = NULL;
2202 fd = open (filename, O_RDONLY);
2205 if (fstat (fd, &statb) != 0) {
2209 file_size = statb.st_size;
2210 data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
2212 if (data == MAP_FAILED)
2215 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2216 header->e_ident [EI_MAG1] != ELFMAG1 ||
2217 header->e_ident [EI_MAG2] != ELFMAG2 ||
2218 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2219 munmap (data, file_size);
2222 sheader = (void*)((char*)data + header->e_shoff);
2223 shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
2224 strtab = (const char*)data + shstrtabh->sh_offset;
2225 for (i = 0; i < header->e_shnum; ++i) {
2226 //printf ("section header: %d\n", sheader->sh_type);
2227 if (sheader->sh_type == SHT_SYMTAB) {
2229 strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
2230 /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
2233 sheader = (void*)((char*)sheader + header->e_shentsize);
2235 if (!symtabh || !strtabh) {
2236 munmap (data, file_size);
2239 strtab = (const char*)data + strtabh->sh_offset;
2240 num_symbols = symtabh->sh_size / symtabh->sh_entsize;
2241 symbols = (void*)((char*)data + symtabh->sh_offset);
2242 dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
2243 munmap (data, file_size);
2248 /* ELF code crashes on some systems. */
2249 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2252 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
2254 MonoProfiler *prof = data;
2256 const char *filename;
2258 char *a = (void*)info->dlpi_addr;
2260 ElfW(Dyn) *dyn = NULL;
2261 ElfW(Sym) *symtab = NULL;
2262 ElfW(Word) *hash_table = NULL;
2263 ElfW(Ehdr) *header = NULL;
2264 const char* strtab = NULL;
2265 for (obj = prof->binary_objects; obj; obj = obj->next) {
2269 filename = info->dlpi_name;
2272 if (!info->dlpi_addr && !filename [0]) {
2273 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
2279 obj = calloc (sizeof (BinaryObject), 1);
2280 obj->addr = (void*)info->dlpi_addr;
2281 obj->name = pstrdup (filename);
2282 obj->next = prof->binary_objects;
2283 prof->binary_objects = obj;
2284 //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
2286 for (i = 0; i < info->dlpi_phnum; ++i) {
2287 //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);
2288 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
2289 header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2290 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2291 header->e_ident [EI_MAG1] != ELFMAG1 ||
2292 header->e_ident [EI_MAG2] != ELFMAG2 ||
2293 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2296 dump_ubin (filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
2297 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
2298 dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2301 if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
2303 if (!info->dlpi_name || !info->dlpi_name[0])
2307 for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
2308 if (dyn [i].d_tag == DT_SYMTAB) {
2309 if (symtab && do_debug)
2310 printf ("multiple symtabs: %d\n", i);
2311 symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
2312 } else if (dyn [i].d_tag == DT_HASH) {
2313 hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
2314 } else if (dyn [i].d_tag == DT_STRTAB) {
2315 strtab = (const char*)(a + dyn [i].d_un.d_ptr);
2320 num_sym = hash_table [1];
2321 dump_elf_symbols (symtab, num_sym, strtab, (void*)info->dlpi_addr);
2326 load_binaries (MonoProfiler *prof)
2328 dl_iterate_phdr (elf_dl_callback, prof);
2333 load_binaries (MonoProfiler *prof)
2340 symbol_for (uintptr_t code)
2343 void *ip = (void*)code;
2345 if (dladdr (ip, &di)) {
2347 return di.dli_sname;
2350 names = backtrace_symbols (&ip, 1);
2352 const char* p = names [0];
2363 dump_unmanaged_coderefs (MonoProfiler *prof)
2366 const char* last_symbol;
2367 uintptr_t addr, page_end;
2369 if (load_binaries (prof))
2371 for (i = 0; i < size_code_pages; ++i) {
2373 if (!code_pages [i] || code_pages [i] & 1)
2376 addr = CPAGE_ADDR (code_pages [i]);
2377 page_end = addr + CPAGE_SIZE;
2378 code_pages [i] |= 1;
2379 /* we dump the symbols for the whole page */
2380 for (; addr < page_end; addr += 16) {
2381 sym = symbol_for (addr);
2382 if (sym && sym == last_symbol)
2387 dump_usym (sym, addr, 0); /* let's not guess the size */
2388 //printf ("found symbol at %p: %s\n", (void*)addr, sym);
2394 compare_sample_events (gconstpointer a, gconstpointer b)
2396 uintptr_t tid1 = (*(uintptr_t **) a) [1];
2397 uintptr_t tid2 = (*(uintptr_t **) b) [1];
2399 return tid1 > tid2 ? 1 :
2405 dump_sample_hits (MonoProfiler *prof, StatBuffer *sbuf)
2407 LogBuffer *logbuffer;
2411 dump_sample_hits (prof, sbuf->next);
2412 free_buffer (sbuf->next, sbuf->next->size);
2416 g_ptr_array_set_size (prof->sorted_sample_events, 0);
2418 for (uintptr_t *sample = sbuf->buf; sample < sbuf->data;) {
2419 int count = sample [0] & 0xff;
2420 int mbt_count = (sample [0] & 0xff00) >> 8;
2422 if (sample + SAMPLE_EVENT_SIZE_IN_SLOTS (mbt_count) > sbuf->data)
2425 g_ptr_array_add (prof->sorted_sample_events, sample);
2427 sample += count + 3 + 4 * mbt_count;
2430 g_ptr_array_sort (prof->sorted_sample_events, compare_sample_events);
2432 for (guint sidx = 0; sidx < prof->sorted_sample_events->len; sidx++) {
2433 uintptr_t *sample = (uintptr_t *)g_ptr_array_index (prof->sorted_sample_events, sidx);
2434 int count = sample [0] & 0xff;
2435 int mbt_count = (sample [0] & 0xff00) >> 8;
2436 int type = sample [0] >> 16;
2437 uintptr_t *managed_sample_base = sample + count + 3;
2438 uintptr_t thread_id = sample [1];
2440 for (int i = 0; i < mbt_count; ++i) {
2441 MonoMethod *method = (MonoMethod*)managed_sample_base [i * 4 + 0];
2442 MonoDomain *domain = (MonoDomain*)managed_sample_base [i * 4 + 1];
2443 void *address = (void*)managed_sample_base [i * 4 + 2];
2446 MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *)address);
2449 managed_sample_base [i * 4 + 0] = (uintptr_t)mono_jit_info_get_method (ji);
2453 logbuffer = ensure_logbuf (
2454 EVENT_SIZE /* event */ +
2455 LEB128_SIZE /* type */ +
2456 LEB128_SIZE /* time */ +
2457 LEB128_SIZE /* tid */ +
2458 LEB128_SIZE /* count */ +
2460 LEB128_SIZE /* ip */
2462 LEB128_SIZE /* managed count */ +
2464 LEB128_SIZE /* method */ +
2465 LEB128_SIZE /* il offset */ +
2466 LEB128_SIZE /* native offset */
2469 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
2470 emit_value (logbuffer, type);
2471 emit_uvalue (logbuffer, prof->startup_time + (uint64_t)sample [2] * (uint64_t)10000);
2472 emit_ptr (logbuffer, (void *) thread_id);
2473 emit_value (logbuffer, count);
2474 for (int i = 0; i < count; ++i) {
2475 emit_ptr (logbuffer, (void*)sample [i + 3]);
2476 add_code_pointer (sample [i + 3]);
2479 sample += count + 3;
2480 /* new in data version 6 */
2481 emit_uvalue (logbuffer, mbt_count);
2482 for (int i = 0; i < mbt_count; ++i) {
2483 MonoMethod *method = (MonoMethod *) sample [i * 4 + 0];
2484 uintptr_t native_offset = sample [i * 4 + 3];
2486 emit_method (prof, logbuffer, method);
2487 emit_svalue (logbuffer, 0); /* il offset will always be 0 from now on */
2488 emit_svalue (logbuffer, native_offset);
2492 dump_unmanaged_coderefs (prof);
2498 mono_cpu_count (void)
2500 #ifdef PLATFORM_ANDROID
2501 /* Android tries really hard to save power by powering off CPUs on SMP phones which
2502 * means the normal way to query cpu count returns a wrong value with userspace API.
2503 * Instead we use /sys entries to query the actual hardware CPU count.
2506 char buffer[8] = {'\0'};
2507 int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
2508 /* Format of the /sys entry is a cpulist of indexes which in the case
2509 * of present is always of the form "0-(n-1)" when there is more than
2510 * 1 core, n being the number of CPU cores in the system. Otherwise
2511 * the value is simply 0
2513 if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
2514 count = strtol (((char*)buffer) + 2, NULL, 10);
2521 #if defined(HOST_ARM) || defined (HOST_ARM64)
2523 /* ARM platforms tries really hard to save power by powering off CPUs on SMP phones which
2524 * means the normal way to query cpu count returns a wrong value with userspace API. */
2526 #ifdef _SC_NPROCESSORS_CONF
2528 int count = sysconf (_SC_NPROCESSORS_CONF);
2536 #ifdef HAVE_SCHED_GETAFFINITY
2539 if (sched_getaffinity (getpid (), sizeof (set), &set) == 0)
2540 return CPU_COUNT (&set);
2543 #ifdef _SC_NPROCESSORS_ONLN
2545 int count = sysconf (_SC_NPROCESSORS_ONLN);
2551 #endif /* defined(HOST_ARM) || defined (HOST_ARM64) */
2557 size_t len = sizeof (int);
2560 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
2567 GetSystemInfo (&info);
2568 return info.dwNumberOfProcessors;
2577 unsigned int prev_pos;
2579 struct perf_event_mmap_page *page_desc;
2582 static PerfData *perf_data = NULL;
2583 static int num_perf;
2584 #define PERF_PAGES_SHIFT 4
2585 static int num_pages = 1 << PERF_PAGES_SHIFT;
2586 static unsigned int mmap_mask;
2589 struct perf_event_header h;
2599 perf_event_syscall (struct perf_event_attr *attr, pid_t pid, int cpu, int group_fd, unsigned long flags)
2601 attr->size = PERF_ATTR_SIZE_VER0;
2602 //printf ("perf attr size: %d\n", attr->size);
2603 #if defined(__x86_64__)
2604 return syscall(/*__NR_perf_event_open*/ 298, attr, pid, cpu, group_fd, flags);
2605 #elif defined(__i386__)
2606 return syscall(/*__NR_perf_event_open*/ 336, attr, pid, cpu, group_fd, flags);
2607 #elif defined(__arm__) || defined (__aarch64__)
2608 return syscall(/*__NR_perf_event_open*/ 364, attr, pid, cpu, group_fd, flags);
2615 setup_perf_map (PerfData *perf)
2617 perf->mmap_base = mmap (NULL, (num_pages + 1) * getpagesize (), PROT_READ|PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
2618 if (perf->mmap_base == MAP_FAILED) {
2620 printf ("failed mmap\n");
2623 perf->page_desc = perf->mmap_base;
2625 printf ("mmap version: %d\n", perf->page_desc->version);
2630 dump_perf_hits (MonoProfiler *prof, void *buf, int size)
2632 LogBuffer *logbuffer;
2635 void *end = (char*)buf + size;
2637 int pid = getpid ();
2643 if (pid != s->pid) {
2645 printf ("event for different pid: %d\n", s->pid);
2646 buf = (char*)buf + s->h.size;
2649 /*ip = (void*)s->ip;
2650 printf ("sample: %d, size: %d, ip: %p (%s), timestamp: %llu, nframes: %llu\n",
2651 s->h.type, s->h.size, ip, symbol_for (ip), s->timestamp, s->nframes);*/
2652 logbuffer = ensure_logbuf (
2653 EVENT_SIZE /* event */ +
2654 LEB128_SIZE /* type */ +
2655 LEB128_SIZE /* time */ +
2656 LEB128_SIZE /* tid */ +
2657 LEB128_SIZE /* count */ +
2659 LEB128_SIZE /* ip */
2661 LEB128_SIZE /* managed count */ +
2663 LEB128_SIZE /* method */ +
2664 LEB128_SIZE /* il offset */ +
2665 LEB128_SIZE /* native offset */
2668 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
2669 emit_value (logbuffer, sample_type);
2670 emit_uvalue (logbuffer, s->timestamp - prof->startup_time);
2672 * No useful thread ID to write here, since throughout the
2673 * profiler we use pthread_self () but the ID we get from
2674 * perf is the kernel's thread ID.
2676 emit_ptr (logbuffer, 0);
2677 emit_value (logbuffer, count);
2678 emit_ptr (logbuffer, (void*)(uintptr_t)s->ip);
2679 add_code_pointer (s->ip);
2680 /* no support here yet for the managed backtrace */
2681 emit_uvalue (logbuffer, mbt_count);
2682 buf = (char*)buf + s->h.size;
2686 printf ("dumped %d samples\n", samples);
2687 dump_unmanaged_coderefs (prof);
2690 /* read events from the ring buffer */
2692 read_perf_mmap (MonoProfiler* prof, int cpu)
2694 PerfData *perf = perf_data + cpu;
2696 unsigned char *data = (unsigned char*)perf->mmap_base + getpagesize ();
2697 unsigned int head = perf->page_desc->data_head;
2701 mono_memory_read_barrier ();
2703 old = perf->prev_pos;
2707 printf ("lost mmap events: old: %d, head: %d\n", old, head);
2711 if ((old & mmap_mask) + size != (head & mmap_mask)) {
2712 buf = data + (old & mmap_mask);
2713 size = mmap_mask + 1 - (old & mmap_mask);
2715 /* size bytes at buf */
2717 printf ("found1 bytes of events: %d\n", size);
2718 dump_perf_hits (prof, buf, size);
2720 buf = data + (old & mmap_mask);
2722 /* size bytes at buf */
2724 printf ("found bytes of events: %d\n", size);
2725 dump_perf_hits (prof, buf, size);
2727 perf->prev_pos = old;
2728 perf->page_desc->data_tail = old;
2733 setup_perf_event_for_cpu (PerfData *perf, int cpu)
2735 struct perf_event_attr attr;
2736 memset (&attr, 0, sizeof (attr));
2737 attr.type = PERF_TYPE_HARDWARE;
2738 switch (sample_type) {
2739 case SAMPLE_CYCLES: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2740 case SAMPLE_INSTRUCTIONS: attr.config = PERF_COUNT_HW_INSTRUCTIONS; break;
2741 case SAMPLE_CACHE_MISSES: attr.config = PERF_COUNT_HW_CACHE_MISSES; break;
2742 case SAMPLE_CACHE_REFS: attr.config = PERF_COUNT_HW_CACHE_REFERENCES; break;
2743 case SAMPLE_BRANCHES: attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS; break;
2744 case SAMPLE_BRANCH_MISSES: attr.config = PERF_COUNT_HW_BRANCH_MISSES; break;
2745 default: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2747 attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD | PERF_SAMPLE_TIME;
2748 // attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
2749 attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING | PERF_FORMAT_ID;
2752 attr.sample_freq = sample_freq;
2754 perf->perf_fd = perf_event_syscall (&attr, getpid (), cpu, -1, 0);
2756 printf ("perf fd: %d, freq: %d, event: %llu\n", perf->perf_fd, sample_freq, attr.config);
2757 if (perf->perf_fd < 0) {
2758 if (perf->perf_fd == -EPERM) {
2759 fprintf (stderr, "Perf syscall denied, do \"echo 1 > /proc/sys/kernel/perf_event_paranoid\" as root to enable.\n");
2762 perror ("open perf event");
2766 if (!setup_perf_map (perf)) {
2767 close (perf->perf_fd);
2775 setup_perf_event (void)
2778 mmap_mask = num_pages * getpagesize () - 1;
2779 num_perf = mono_cpu_count ();
2780 perf_data = calloc (num_perf, sizeof (PerfData));
2781 for (i = 0; i < num_perf; ++i) {
2782 count += setup_perf_event_for_cpu (perf_data + i, i);
2791 #endif /* USE_PERF_EVENTS */
2793 #ifndef DISABLE_HELPER_THREAD
2795 typedef struct MonoCounterAgent {
2796 MonoCounter *counter;
2797 // MonoCounterAgent specific data :
2802 struct MonoCounterAgent *next;
2805 static MonoCounterAgent* counters;
2806 static gboolean counters_initialized = FALSE;
2807 static int counters_index = 1;
2808 static mono_mutex_t counters_mutex;
2811 counters_add_agent (MonoCounter *counter)
2813 MonoCounterAgent *agent, *item;
2815 if (!counters_initialized)
2818 mono_os_mutex_lock (&counters_mutex);
2820 for (agent = counters; agent; agent = agent->next) {
2821 if (agent->counter == counter) {
2822 agent->value_size = 0;
2824 free (agent->value);
2825 agent->value = NULL;
2827 mono_os_mutex_unlock (&counters_mutex);
2832 agent = (MonoCounterAgent *)malloc (sizeof (MonoCounterAgent));
2833 agent->counter = counter;
2834 agent->value = NULL;
2835 agent->value_size = 0;
2836 agent->index = counters_index++;
2849 mono_os_mutex_unlock (&counters_mutex);
2853 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
2855 counters_add_agent (counter);
2860 counters_init (MonoProfiler *profiler)
2862 assert (!counters_initialized);
2864 mono_os_mutex_init (&counters_mutex);
2866 counters_initialized = TRUE;
2868 mono_counters_on_register (&counters_add_agent);
2869 mono_counters_foreach (counters_init_foreach_callback, NULL);
2873 counters_emit (MonoProfiler *profiler)
2875 MonoCounterAgent *agent;
2876 LogBuffer *logbuffer;
2879 EVENT_SIZE /* event */ +
2880 LEB128_SIZE /* len */
2883 if (!counters_initialized)
2886 mono_os_mutex_lock (&counters_mutex);
2888 for (agent = counters; agent; agent = agent->next) {
2893 LEB128_SIZE /* section */ +
2894 strlen (mono_counter_get_name (agent->counter)) + 1 /* name */ +
2895 LEB128_SIZE /* type */ +
2896 LEB128_SIZE /* unit */ +
2897 LEB128_SIZE /* variance */ +
2898 LEB128_SIZE /* index */
2905 mono_os_mutex_unlock (&counters_mutex);
2909 logbuffer = ensure_logbuf (size);
2911 ENTER_LOG (logbuffer, "counters");
2912 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2913 emit_value (logbuffer, len);
2914 for (agent = counters; agent; agent = agent->next) {
2920 name = mono_counter_get_name (agent->counter);
2921 emit_value (logbuffer, mono_counter_get_section (agent->counter));
2922 emit_string (logbuffer, name, strlen (name) + 1);
2923 emit_value (logbuffer, mono_counter_get_type (agent->counter));
2924 emit_value (logbuffer, mono_counter_get_unit (agent->counter));
2925 emit_value (logbuffer, mono_counter_get_variance (agent->counter));
2926 emit_value (logbuffer, agent->index);
2930 EXIT_LOG (logbuffer);
2932 safe_send (profiler, logbuffer);
2934 mono_os_mutex_unlock (&counters_mutex);
2938 counters_sample (MonoProfiler *profiler, uint64_t timestamp)
2940 MonoCounterAgent *agent;
2941 MonoCounter *counter;
2942 LogBuffer *logbuffer;
2948 if (!counters_initialized)
2951 counters_emit (profiler);
2954 buffer = calloc (1, buffer_size);
2956 mono_os_mutex_lock (&counters_mutex);
2959 EVENT_SIZE /* event */ +
2960 LEB128_SIZE /* time */
2963 for (agent = counters; agent; agent = agent->next) {
2965 LEB128_SIZE /* index */ +
2966 LEB128_SIZE /* type */ +
2967 mono_counter_get_size (agent->counter) /* value */
2972 LEB128_SIZE /* stop marker */
2975 logbuffer = ensure_logbuf (size);
2977 ENTER_LOG (logbuffer, "counters");
2978 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
2979 emit_uvalue (logbuffer, timestamp);
2980 for (agent = counters; agent; agent = agent->next) {
2983 counter = agent->counter;
2985 size = mono_counter_get_size (counter);
2987 continue; // FIXME error
2988 } else if (size > buffer_size) {
2990 buffer = realloc (buffer, buffer_size);
2993 memset (buffer, 0, buffer_size);
2995 if (mono_counters_sample (counter, buffer, size) < 0)
2996 continue; // FIXME error
2998 type = mono_counter_get_type (counter);
3000 if (!agent->value) {
3001 agent->value = calloc (1, size);
3002 agent->value_size = size;
3004 if (type == MONO_COUNTER_STRING) {
3005 if (strcmp (agent->value, buffer) == 0)
3008 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
3013 emit_uvalue (logbuffer, agent->index);
3014 emit_uvalue (logbuffer, type);
3016 case MONO_COUNTER_INT:
3017 #if SIZEOF_VOID_P == 4
3018 case MONO_COUNTER_WORD:
3020 emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
3022 case MONO_COUNTER_UINT:
3023 emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
3025 case MONO_COUNTER_TIME_INTERVAL:
3026 case MONO_COUNTER_LONG:
3027 #if SIZEOF_VOID_P == 8
3028 case MONO_COUNTER_WORD:
3030 emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
3032 case MONO_COUNTER_ULONG:
3033 emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
3035 case MONO_COUNTER_DOUBLE:
3036 emit_double (logbuffer, *(double*)buffer);
3038 case MONO_COUNTER_STRING:
3040 emit_byte (logbuffer, 0);
3042 emit_byte (logbuffer, 1);
3043 emit_string (logbuffer, (char*)buffer, size);
3050 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
3051 agent->value = realloc (agent->value, size);
3052 agent->value_size = size;
3056 memcpy (agent->value, buffer, size);
3060 emit_value (logbuffer, 0);
3061 EXIT_LOG (logbuffer);
3063 safe_send (profiler, logbuffer);
3065 mono_os_mutex_unlock (&counters_mutex);
3068 typedef struct _PerfCounterAgent PerfCounterAgent;
3069 struct _PerfCounterAgent {
3070 PerfCounterAgent *next;
3072 char *category_name;
3081 static PerfCounterAgent *perfcounters = NULL;
3084 perfcounters_emit (MonoProfiler *profiler)
3086 PerfCounterAgent *pcagent;
3087 LogBuffer *logbuffer;
3090 EVENT_SIZE /* event */ +
3091 LEB128_SIZE /* len */
3094 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3095 if (pcagent->emitted)
3099 LEB128_SIZE /* section */ +
3100 strlen (pcagent->category_name) + 1 /* category name */ +
3101 strlen (pcagent->name) + 1 /* name */ +
3102 LEB128_SIZE /* type */ +
3103 LEB128_SIZE /* unit */ +
3104 LEB128_SIZE /* variance */ +
3105 LEB128_SIZE /* index */
3114 logbuffer = ensure_logbuf (size);
3116 ENTER_LOG (logbuffer, "perfcounters");
3117 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
3118 emit_value (logbuffer, len);
3119 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3120 if (pcagent->emitted)
3123 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
3124 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
3125 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
3126 emit_value (logbuffer, MONO_COUNTER_LONG);
3127 emit_value (logbuffer, MONO_COUNTER_RAW);
3128 emit_value (logbuffer, MONO_COUNTER_VARIABLE);
3129 emit_value (logbuffer, pcagent->index);
3131 pcagent->emitted = 1;
3133 EXIT_LOG (logbuffer);
3135 safe_send (profiler, logbuffer);
3139 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
3141 PerfCounterAgent *pcagent;
3143 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3144 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
3146 if (pcagent->value == value)
3149 pcagent->value = value;
3150 pcagent->updated = 1;
3151 pcagent->deleted = 0;
3155 pcagent = g_new0 (PerfCounterAgent, 1);
3156 pcagent->next = perfcounters;
3157 pcagent->index = counters_index++;
3158 pcagent->category_name = g_strdup (category_name);
3159 pcagent->name = g_strdup (name);
3160 pcagent->type = (int) type;
3161 pcagent->value = value;
3162 pcagent->emitted = 0;
3163 pcagent->updated = 1;
3164 pcagent->deleted = 0;
3166 perfcounters = pcagent;
3172 perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp)
3174 PerfCounterAgent *pcagent;
3175 LogBuffer *logbuffer;
3178 if (!counters_initialized)
3181 mono_os_mutex_lock (&counters_mutex);
3183 /* mark all perfcounters as deleted, foreach will unmark them as necessary */
3184 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
3185 pcagent->deleted = 1;
3187 mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
3189 perfcounters_emit (profiler);
3192 EVENT_SIZE /* event */ +
3193 LEB128_SIZE /* time */
3196 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3197 if (pcagent->deleted || !pcagent->updated)
3201 LEB128_SIZE /* index */ +
3202 LEB128_SIZE /* type */ +
3203 LEB128_SIZE /* value */
3208 LEB128_SIZE /* stop marker */
3211 logbuffer = ensure_logbuf (size);
3213 ENTER_LOG (logbuffer, "perfcounters");
3214 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
3215 emit_uvalue (logbuffer, timestamp);
3216 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3217 if (pcagent->deleted || !pcagent->updated)
3219 emit_uvalue (logbuffer, pcagent->index);
3220 emit_uvalue (logbuffer, MONO_COUNTER_LONG);
3221 emit_svalue (logbuffer, pcagent->value);
3223 pcagent->updated = 0;
3226 emit_value (logbuffer, 0);
3227 EXIT_LOG (logbuffer);
3229 safe_send (profiler, logbuffer);
3231 mono_os_mutex_unlock (&counters_mutex);
3235 counters_and_perfcounters_sample (MonoProfiler *prof)
3237 static uint64_t start = -1;
3241 start = current_time ();
3243 now = current_time ();
3244 counters_sample (prof, (now - start) / 1000/ 1000);
3245 perfcounters_sample (prof, (now - start) / 1000/ 1000);
3248 #define COVERAGE_DEBUG(x) if (debug_coverage) {x}
3249 static mono_mutex_t coverage_mutex;
3250 static MonoConcurrentHashTable *coverage_methods = NULL;
3251 static MonoConcurrentHashTable *coverage_assemblies = NULL;
3252 static MonoConcurrentHashTable *coverage_classes = NULL;
3254 static MonoConcurrentHashTable *filtered_classes = NULL;
3255 static MonoConcurrentHashTable *entered_methods = NULL;
3256 static MonoConcurrentHashTable *image_to_methods = NULL;
3257 static MonoConcurrentHashTable *suppressed_assemblies = NULL;
3258 static gboolean coverage_initialized = FALSE;
3260 static GPtrArray *coverage_data = NULL;
3261 static int previous_offset = 0;
3263 typedef struct _MethodNode MethodNode;
3264 struct _MethodNode {
3265 MonoLockFreeQueueNode node;
3269 typedef struct _CoverageEntry CoverageEntry;
3270 struct _CoverageEntry {
3279 free_coverage_entry (gpointer data, gpointer userdata)
3281 CoverageEntry *entry = (CoverageEntry *)data;
3282 g_free (entry->filename);
3287 obtain_coverage_for_method (MonoProfiler *prof, const MonoProfileCoverageEntry *entry)
3289 int offset = entry->iloffset - previous_offset;
3290 CoverageEntry *e = g_new (CoverageEntry, 1);
3292 previous_offset = entry->iloffset;
3295 e->counter = entry->counter;
3296 e->filename = g_strdup(entry->filename ? entry->filename : "");
3297 e->line = entry->line;
3298 e->column = entry->col;
3300 g_ptr_array_add (coverage_data, e);
3304 parse_generic_type_names(char *name)
3306 char *new_name, *ret;
3307 int within_generic_declaration = 0, generic_members = 1;
3309 if (name == NULL || *name == '\0')
3310 return g_strdup ("");
3312 if (!(ret = new_name = (char *)calloc (strlen (name) * 4 + 1, sizeof (char))))
3318 within_generic_declaration = 1;
3322 within_generic_declaration = 0;
3324 if (*(name - 1) != '<') {
3326 *new_name++ = '0' + generic_members;
3328 memcpy (new_name, "<>", 8);
3332 generic_members = 0;
3340 if (!within_generic_declaration)
3341 *new_name++ = *name;
3350 static int method_id;
3352 build_method_buffer (gpointer key, gpointer value, gpointer userdata)
3354 MonoMethod *method = (MonoMethod *)value;
3355 MonoProfiler *prof = (MonoProfiler *)userdata;
3359 const char *image_name, *method_name, *sig, *first_filename;
3360 LogBuffer *logbuffer;
3363 previous_offset = 0;
3364 coverage_data = g_ptr_array_new ();
3366 mono_profiler_coverage_get (prof, method, obtain_coverage_for_method);
3368 klass = mono_method_get_class (method);
3369 image = mono_class_get_image (klass);
3370 image_name = mono_image_get_name (image);
3372 sig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3373 class_name = parse_generic_type_names (mono_type_get_name (mono_class_get_type (klass)));
3374 method_name = mono_method_get_name (method);
3376 if (coverage_data->len != 0) {
3377 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[0];
3378 first_filename = entry->filename ? entry->filename : "";
3380 first_filename = "";
3382 image_name = image_name ? image_name : "";
3383 sig = sig ? sig : "";
3384 method_name = method_name ? method_name : "";
3386 logbuffer = ensure_logbuf (
3387 EVENT_SIZE /* event */ +
3388 strlen (image_name) + 1 /* image name */ +
3389 strlen (class_name) + 1 /* class name */ +
3390 strlen (method_name) + 1 /* method name */ +
3391 strlen (sig) + 1 /* signature */ +
3392 strlen (first_filename) + 1 /* first file name */ +
3393 LEB128_SIZE /* token */ +
3394 LEB128_SIZE /* method id */ +
3395 LEB128_SIZE /* entries */
3397 ENTER_LOG (logbuffer, "coverage-methods");
3399 emit_byte (logbuffer, TYPE_COVERAGE_METHOD | TYPE_COVERAGE);
3400 emit_string (logbuffer, image_name, strlen (image_name) + 1);
3401 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3402 emit_string (logbuffer, method_name, strlen (method_name) + 1);
3403 emit_string (logbuffer, sig, strlen (sig) + 1);
3404 emit_string (logbuffer, first_filename, strlen (first_filename) + 1);
3406 emit_uvalue (logbuffer, mono_method_get_token (method));
3407 emit_uvalue (logbuffer, method_id);
3408 emit_value (logbuffer, coverage_data->len);
3410 EXIT_LOG (logbuffer);
3411 safe_send (prof, logbuffer);
3413 for (i = 0; i < coverage_data->len; i++) {
3414 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[i];
3416 logbuffer = ensure_logbuf (
3417 EVENT_SIZE /* event */ +
3418 LEB128_SIZE /* method id */ +
3419 LEB128_SIZE /* offset */ +
3420 LEB128_SIZE /* counter */ +
3421 LEB128_SIZE /* line */ +
3422 LEB128_SIZE /* column */
3424 ENTER_LOG (logbuffer, "coverage-statement");
3426 emit_byte (logbuffer, TYPE_COVERAGE_STATEMENT | TYPE_COVERAGE);
3427 emit_uvalue (logbuffer, method_id);
3428 emit_uvalue (logbuffer, entry->offset);
3429 emit_uvalue (logbuffer, entry->counter);
3430 emit_uvalue (logbuffer, entry->line);
3431 emit_uvalue (logbuffer, entry->column);
3433 EXIT_LOG (logbuffer);
3434 safe_send (prof, logbuffer);
3439 g_free (class_name);
3441 g_ptr_array_foreach (coverage_data, free_coverage_entry, NULL);
3442 g_ptr_array_free (coverage_data, TRUE);
3443 coverage_data = NULL;
3446 /* This empties the queue */
3448 count_queue (MonoLockFreeQueue *queue)
3450 MonoLockFreeQueueNode *node;
3453 while ((node = mono_lock_free_queue_dequeue (queue))) {
3455 mono_lock_free_queue_node_free (node);
3462 build_class_buffer (gpointer key, gpointer value, gpointer userdata)
3464 MonoClass *klass = (MonoClass *)key;
3465 MonoLockFreeQueue *class_methods = (MonoLockFreeQueue *)value;
3466 MonoProfiler *prof = (MonoProfiler *)userdata;
3469 const char *assembly_name;
3470 int number_of_methods, partially_covered;
3471 guint fully_covered;
3472 LogBuffer *logbuffer;
3474 image = mono_class_get_image (klass);
3475 assembly_name = mono_image_get_name (image);
3476 class_name = mono_type_get_name (mono_class_get_type (klass));
3478 assembly_name = assembly_name ? assembly_name : "";
3479 number_of_methods = mono_class_num_methods (klass);
3480 fully_covered = count_queue (class_methods);
3481 /* We don't handle partial covered yet */
3482 partially_covered = 0;
3484 logbuffer = ensure_logbuf (
3485 EVENT_SIZE /* event */ +
3486 strlen (assembly_name) + 1 /* assembly name */ +
3487 strlen (class_name) + 1 /* class name */ +
3488 LEB128_SIZE /* no. methods */ +
3489 LEB128_SIZE /* fully covered */ +
3490 LEB128_SIZE /* partially covered */
3493 ENTER_LOG (logbuffer, "coverage-class");
3494 emit_byte (logbuffer, TYPE_COVERAGE_CLASS | TYPE_COVERAGE);
3495 emit_string (logbuffer, assembly_name, strlen (assembly_name) + 1);
3496 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3497 emit_uvalue (logbuffer, number_of_methods);
3498 emit_uvalue (logbuffer, fully_covered);
3499 emit_uvalue (logbuffer, partially_covered);
3500 EXIT_LOG (logbuffer);
3502 safe_send (prof, logbuffer);
3504 g_free (class_name);
3508 get_coverage_for_image (MonoImage *image, int *number_of_methods, guint *fully_covered, int *partially_covered)
3510 MonoLockFreeQueue *image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3512 *number_of_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
3514 *fully_covered = count_queue (image_methods);
3518 // FIXME: We don't handle partially covered yet.
3519 *partially_covered = 0;
3523 build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
3525 MonoAssembly *assembly = (MonoAssembly *)value;
3526 MonoProfiler *prof = (MonoProfiler *)userdata;
3527 MonoImage *image = mono_assembly_get_image (assembly);
3528 LogBuffer *logbuffer;
3529 const char *name, *guid, *filename;
3530 int number_of_methods = 0, partially_covered = 0;
3531 guint fully_covered = 0;
3533 name = mono_image_get_name (image);
3534 guid = mono_image_get_guid (image);
3535 filename = mono_image_get_filename (image);
3537 name = name ? name : "";
3538 guid = guid ? guid : "";
3539 filename = filename ? filename : "";
3541 get_coverage_for_image (image, &number_of_methods, &fully_covered, &partially_covered);
3543 logbuffer = ensure_logbuf (
3544 EVENT_SIZE /* event */ +
3545 strlen (name) + 1 /* name */ +
3546 strlen (guid) + 1 /* guid */ +
3547 strlen (filename) + 1 /* file name */ +
3548 LEB128_SIZE /* no. methods */ +
3549 LEB128_SIZE /* fully covered */ +
3550 LEB128_SIZE /* partially covered */
3553 ENTER_LOG (logbuffer, "coverage-assemblies");
3554 emit_byte (logbuffer, TYPE_COVERAGE_ASSEMBLY | TYPE_COVERAGE);
3555 emit_string (logbuffer, name, strlen (name) + 1);
3556 emit_string (logbuffer, guid, strlen (guid) + 1);
3557 emit_string (logbuffer, filename, strlen (filename) + 1);
3558 emit_uvalue (logbuffer, number_of_methods);
3559 emit_uvalue (logbuffer, fully_covered);
3560 emit_uvalue (logbuffer, partially_covered);
3561 EXIT_LOG (logbuffer);
3563 safe_send (prof, logbuffer);
3567 dump_coverage (MonoProfiler *prof)
3569 if (!coverage_initialized)
3572 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Started dump\n");)
3575 mono_os_mutex_lock (&coverage_mutex);
3576 mono_conc_hashtable_foreach (coverage_assemblies, build_assembly_buffer, prof);
3577 mono_conc_hashtable_foreach (coverage_classes, build_class_buffer, prof);
3578 mono_conc_hashtable_foreach (coverage_methods, build_method_buffer, prof);
3579 mono_os_mutex_unlock (&coverage_mutex);
3581 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Finished dump\n");)
3585 process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method)
3590 if (!coverage_initialized)
3593 klass = mono_method_get_class (method);
3594 image = mono_class_get_image (klass);
3596 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)))
3599 mono_os_mutex_lock (&coverage_mutex);
3600 mono_conc_hashtable_insert (entered_methods, method, method);
3601 mono_os_mutex_unlock (&coverage_mutex);
3604 static MonoLockFreeQueueNode *
3605 create_method_node (MonoMethod *method)
3607 MethodNode *node = (MethodNode *)g_malloc (sizeof (MethodNode));
3608 mono_lock_free_queue_node_init ((MonoLockFreeQueueNode *) node, FALSE);
3609 node->method = method;
3611 return (MonoLockFreeQueueNode *) node;
3615 coverage_filter (MonoProfiler *prof, MonoMethod *method)
3620 MonoAssembly *assembly;
3621 MonoMethodHeader *header;
3622 guint32 iflags, flags, code_size;
3623 char *fqn, *classname;
3624 gboolean has_positive, found;
3625 MonoLockFreeQueue *image_methods, *class_methods;
3626 MonoLockFreeQueueNode *node;
3628 if (!coverage_initialized)
3631 COVERAGE_DEBUG(fprintf (stderr, "Coverage filter for %s\n", mono_method_get_name (method));)
3633 flags = mono_method_get_flags (method, &iflags);
3634 if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
3635 (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/)) {
3636 COVERAGE_DEBUG(fprintf (stderr, " Internal call or pinvoke - ignoring\n");)
3640 // Don't need to do anything else if we're already tracking this method
3641 if (mono_conc_hashtable_lookup (coverage_methods, method)) {
3642 COVERAGE_DEBUG(fprintf (stderr, " Already tracking\n");)
3646 klass = mono_method_get_class (method);
3647 image = mono_class_get_image (klass);
3649 // Don't handle coverage for the core assemblies
3650 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)) != NULL)
3653 if (prof->coverage_filters) {
3654 /* Check already filtered classes first */
3655 if (mono_conc_hashtable_lookup (filtered_classes, klass)) {
3656 COVERAGE_DEBUG(fprintf (stderr, " Already filtered\n");)
3660 classname = mono_type_get_name (mono_class_get_type (klass));
3662 fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
3664 COVERAGE_DEBUG(fprintf (stderr, " Looking for %s in filter\n", fqn);)
3665 // Check positive filters first
3666 has_positive = FALSE;
3668 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3669 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3671 if (filter [0] == '+') {
3672 filter = &filter [1];
3674 COVERAGE_DEBUG(fprintf (stderr, " Checking against +%s ...", filter);)
3676 if (strstr (fqn, filter) != NULL) {
3677 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3680 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3682 has_positive = TRUE;
3686 if (has_positive && !found) {
3687 COVERAGE_DEBUG(fprintf (stderr, " Positive match was not found\n");)
3689 mono_os_mutex_lock (&coverage_mutex);
3690 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3691 mono_os_mutex_unlock (&coverage_mutex);
3698 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3699 // FIXME: Is substring search sufficient?
3700 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3701 if (filter [0] == '+')
3705 filter = &filter [1];
3706 COVERAGE_DEBUG(fprintf (stderr, " Checking against -%s ...", filter);)
3708 if (strstr (fqn, filter) != NULL) {
3709 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3711 mono_os_mutex_lock (&coverage_mutex);
3712 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3713 mono_os_mutex_unlock (&coverage_mutex);
3719 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3727 COVERAGE_DEBUG(fprintf (stderr, " Handling coverage for %s\n", mono_method_get_name (method));)
3728 header = mono_method_get_header_checked (method, &error);
3729 mono_error_cleanup (&error);
3731 mono_method_header_get_code (header, &code_size, NULL);
3733 assembly = mono_image_get_assembly (image);
3735 mono_os_mutex_lock (&coverage_mutex);
3736 mono_conc_hashtable_insert (coverage_methods, method, method);
3737 mono_conc_hashtable_insert (coverage_assemblies, assembly, assembly);
3738 mono_os_mutex_unlock (&coverage_mutex);
3740 image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3742 if (image_methods == NULL) {
3743 image_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
3744 mono_lock_free_queue_init (image_methods);
3745 mono_os_mutex_lock (&coverage_mutex);
3746 mono_conc_hashtable_insert (image_to_methods, image, image_methods);
3747 mono_os_mutex_unlock (&coverage_mutex);
3750 node = create_method_node (method);
3751 mono_lock_free_queue_enqueue (image_methods, node);
3753 class_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (coverage_classes, klass);
3755 if (class_methods == NULL) {
3756 class_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
3757 mono_lock_free_queue_init (class_methods);
3758 mono_os_mutex_lock (&coverage_mutex);
3759 mono_conc_hashtable_insert (coverage_classes, klass, class_methods);
3760 mono_os_mutex_unlock (&coverage_mutex);
3763 node = create_method_node (method);
3764 mono_lock_free_queue_enqueue (class_methods, node);
3769 #define LINE_BUFFER_SIZE 4096
3770 /* Max file limit of 128KB */
3771 #define MAX_FILE_SIZE 128 * 1024
3773 get_file_content (FILE *stream)
3778 int res, offset = 0;
3780 res = fseek (stream, 0, SEEK_END);
3784 filesize = ftell (stream);
3788 res = fseek (stream, 0, SEEK_SET);
3792 if (filesize > MAX_FILE_SIZE)
3795 buffer = (char *)g_malloc ((filesize + 1) * sizeof (char));
3796 while ((bytes_read = fread (buffer + offset, 1, LINE_BUFFER_SIZE, stream)) > 0)
3797 offset += bytes_read;
3799 /* NULL terminate our buffer */
3800 buffer[filesize] = '\0';
3805 get_next_line (char *contents, char **next_start)
3809 if (p == NULL || *p == '\0') {
3814 while (*p != '\n' && *p != '\0')
3819 *next_start = p + 1;
3827 init_suppressed_assemblies (void)
3833 suppressed_assemblies = mono_conc_hashtable_new (g_str_hash, g_str_equal);
3834 sa_file = fopen (SUPPRESSION_DIR "/mono-profiler-log.suppression", "r");
3835 if (sa_file == NULL)
3838 /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
3839 content = get_file_content (sa_file);
3840 if (content == NULL) {
3841 g_error ("mono-profiler-log.suppression is greater than 128kb - aborting\n");
3844 while ((line = get_next_line (content, &content))) {
3845 line = g_strchomp (g_strchug (line));
3846 /* No locking needed as we're doing initialization */
3847 mono_conc_hashtable_insert (suppressed_assemblies, line, line);
3853 #endif /* DISABLE_HELPER_THREAD */
3856 coverage_init (MonoProfiler *prof)
3858 #ifndef DISABLE_HELPER_THREAD
3859 assert (!coverage_initialized);
3861 COVERAGE_DEBUG(fprintf (stderr, "Coverage initialized\n");)
3863 mono_os_mutex_init (&coverage_mutex);
3864 coverage_methods = mono_conc_hashtable_new (NULL, NULL);
3865 coverage_assemblies = mono_conc_hashtable_new (NULL, NULL);
3866 coverage_classes = mono_conc_hashtable_new (NULL, NULL);
3867 filtered_classes = mono_conc_hashtable_new (NULL, NULL);
3868 entered_methods = mono_conc_hashtable_new (NULL, NULL);
3869 image_to_methods = mono_conc_hashtable_new (NULL, NULL);
3870 init_suppressed_assemblies ();
3872 coverage_initialized = TRUE;
3873 #endif /* DISABLE_HELPER_THREAD */
3877 log_shutdown (MonoProfiler *prof)
3882 #ifndef DISABLE_HELPER_THREAD
3883 counters_and_perfcounters_sample (prof);
3885 dump_coverage (prof);
3887 if (prof->command_port) {
3889 ign_res (write (prof->pipes [1], &c, 1));
3890 pthread_join (prof->helper_thread, &res);
3896 for (i = 0; i < num_perf; ++i)
3897 read_perf_mmap (prof, i);
3901 g_ptr_array_free (prof->sorted_sample_events, TRUE);
3903 if (TLS_GET (LogBuffer, tlsbuffer))
3904 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
3906 TLS_SET (tlsbuffer, NULL);
3907 TLS_SET (tlsmethodlist, NULL);
3909 InterlockedWrite (&prof->run_writer_thread, 0);
3910 pthread_join (prof->writer_thread, &res);
3912 #if defined (HAVE_SYS_ZLIB)
3914 gzclose (prof->gzfile);
3916 if (prof->pipe_output)
3917 pclose (prof->file);
3919 fclose (prof->file);
3921 mono_conc_hashtable_destroy (prof->method_table);
3922 mono_os_mutex_destroy (&prof->method_table_mutex);
3924 if (coverage_initialized) {
3925 mono_conc_hashtable_destroy (coverage_methods);
3926 mono_conc_hashtable_destroy (coverage_assemblies);
3927 mono_conc_hashtable_destroy (coverage_classes);
3928 mono_conc_hashtable_destroy (filtered_classes);
3930 mono_conc_hashtable_destroy (entered_methods);
3931 mono_conc_hashtable_destroy (image_to_methods);
3932 mono_conc_hashtable_destroy (suppressed_assemblies);
3933 mono_os_mutex_destroy (&coverage_mutex);
3940 new_filename (const char* filename)
3942 time_t t = time (NULL);
3943 int pid = process_id ();
3948 int count_dates = 0;
3952 for (p = filename; *p; p++) {
3963 if (!count_dates && !count_pids)
3964 return pstrdup (filename);
3965 snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
3967 snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
3968 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
3969 s_date = strlen (time_buf);
3970 s_pid = strlen (pid_buf);
3971 d = res = (char *)malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
3972 for (p = filename; *p; p++) {
3979 strcpy (d, time_buf);
3982 } else if (*p == 'p') {
3983 strcpy (d, pid_buf);
3986 } else if (*p == '%') {
3998 //this is exposed by the JIT, but it's not meant to be a supported API for now.
3999 extern void mono_threads_attach_tools_thread (void);
4001 #ifndef DISABLE_HELPER_THREAD
4004 helper_thread (void* arg)
4006 MonoProfiler* prof = (MonoProfiler *)arg;
4010 MonoThread *thread = NULL;
4012 mono_threads_attach_tools_thread ();
4013 //fprintf (stderr, "Server listening\n");
4014 command_socket = -1;
4020 FD_SET (prof->server_socket, &rfds);
4021 max_fd = prof->server_socket;
4022 FD_SET (prof->pipes [0], &rfds);
4023 if (max_fd < prof->pipes [0])
4024 max_fd = prof->pipes [0];
4025 if (command_socket >= 0) {
4026 FD_SET (command_socket, &rfds);
4027 if (max_fd < command_socket)
4028 max_fd = command_socket;
4033 for ( i = 0; i < num_perf; ++i) {
4034 if (perf_data [i].perf_fd < 0)
4036 FD_SET (perf_data [i].perf_fd, &rfds);
4037 if (max_fd < perf_data [i].perf_fd)
4038 max_fd = perf_data [i].perf_fd;
4043 counters_and_perfcounters_sample (prof);
4047 len = select (max_fd + 1, &rfds, NULL, NULL, &tv);
4053 g_warning ("Error in proflog server: %s", strerror (errno));
4057 if (FD_ISSET (prof->pipes [0], &rfds)) {
4059 int r = read (prof->pipes [0], &c, 1);
4060 if (r == 1 && c == 0) {
4061 StatBuffer *sbufbase = prof->stat_buffers;
4063 if (!sbufbase->next)
4065 sbuf = sbufbase->next->next;
4066 sbufbase->next->next = NULL;
4068 fprintf (stderr, "stat buffer dump\n");
4070 dump_sample_hits (prof, sbuf);
4071 free_buffer (sbuf, sbuf->size);
4072 safe_send (prof, ensure_logbuf (0));
4076 /* time to shut down */
4077 dump_sample_hits (prof, prof->stat_buffers);
4079 mono_thread_detach (thread);
4081 fprintf (stderr, "helper shutdown\n");
4085 for ( i = 0; i < num_perf; ++i) {
4086 if (perf_data [i].perf_fd < 0)
4088 if (FD_ISSET (perf_data [i].perf_fd, &rfds))
4089 read_perf_mmap (prof, i);
4093 safe_send (prof, ensure_logbuf (0));
4099 for ( i = 0; i < num_perf; ++i) {
4100 if (perf_data [i].perf_fd < 0)
4102 if (FD_ISSET (perf_data [i].perf_fd, &rfds)) {
4103 read_perf_mmap (prof, i);
4104 safe_send (prof, ensure_logbuf (0));
4109 if (command_socket >= 0 && FD_ISSET (command_socket, &rfds)) {
4110 len = read (command_socket, buf, sizeof (buf) - 1);
4114 close (command_socket);
4115 command_socket = -1;
4119 if (strcmp (buf, "heapshot\n") == 0) {
4120 heapshot_requested = 1;
4121 //fprintf (stderr, "perform heapshot\n");
4122 if (InterlockedRead (&runtime_inited) && !thread) {
4123 thread = mono_thread_attach (mono_get_root_domain ());
4124 /*fprintf (stderr, "attached\n");*/
4127 process_requests (prof);
4128 mono_thread_detach (thread);
4134 if (!FD_ISSET (prof->server_socket, &rfds)) {
4137 command_socket = accept (prof->server_socket, NULL, NULL);
4138 if (command_socket < 0)
4140 //fprintf (stderr, "Accepted connection\n");
4146 start_helper_thread (MonoProfiler* prof)
4148 struct sockaddr_in server_address;
4151 if (pipe (prof->pipes) < 0) {
4152 fprintf (stderr, "Cannot create pipe\n");
4155 prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
4156 if (prof->server_socket < 0) {
4157 fprintf (stderr, "Cannot create server socket\n");
4160 memset (&server_address, 0, sizeof (server_address));
4161 server_address.sin_family = AF_INET;
4162 server_address.sin_addr.s_addr = INADDR_ANY;
4163 server_address.sin_port = htons (prof->command_port);
4164 if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) < 0) {
4165 fprintf (stderr, "Cannot bind server socket, port: %d: %s\n", prof->command_port, strerror (errno));
4166 close (prof->server_socket);
4169 if (listen (prof->server_socket, 1) < 0) {
4170 fprintf (stderr, "Cannot listen server socket\n");
4171 close (prof->server_socket);
4174 slen = sizeof (server_address);
4175 if (getsockname (prof->server_socket, (struct sockaddr *)&server_address, &slen) == 0) {
4176 prof->command_port = ntohs (server_address.sin_port);
4177 /*fprintf (stderr, "Assigned server port: %d\n", prof->command_port);*/
4180 r = pthread_create (&prof->helper_thread, NULL, helper_thread, prof);
4182 close (prof->server_socket);
4190 writer_thread (void *arg)
4192 MonoProfiler *prof = (MonoProfiler *)arg;
4194 mono_threads_attach_tools_thread ();
4198 while (InterlockedRead (&prof->run_writer_thread)) {
4199 WriterQueueEntry *entry;
4201 while ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&prof->writer_queue))) {
4202 LogBuffer *method_buffer = NULL;
4203 gboolean new_methods = FALSE;
4205 if (entry->methods->len)
4206 method_buffer = create_buffer ();
4209 * Encode the method events in a temporary log buffer that we
4210 * flush to disk before the main buffer, ensuring that all
4211 * methods have metadata emitted before they're referenced.
4213 for (guint i = 0; i < entry->methods->len; i++) {
4214 MethodInfo *info = (MethodInfo *)g_ptr_array_index (entry->methods, i);
4216 if (mono_conc_hashtable_lookup (prof->method_table, info->method))
4222 * Other threads use this hash table to get a general
4223 * idea of whether a method has already been emitted to
4224 * the stream. Due to the way we add to this table, it
4225 * can easily happen that multiple threads queue up the
4226 * same methods, but that's OK since eventually all
4227 * methods will be in this table and the thread-local
4228 * method lists will just be empty for the rest of the
4231 mono_os_mutex_lock (&prof->method_table_mutex);
4232 mono_conc_hashtable_insert (prof->method_table, info->method, info->method);
4233 mono_os_mutex_unlock (&prof->method_table_mutex);
4235 char *name = mono_method_full_name (info->method, 1);
4236 int nlen = strlen (name) + 1;
4237 void *cstart = info->ji ? mono_jit_info_get_code_start (info->ji) : NULL;
4238 int csize = info->ji ? mono_jit_info_get_code_size (info->ji) : 0;
4240 method_buffer = ensure_logbuf_inner (method_buffer,
4241 EVENT_SIZE /* event */ +
4242 LEB128_SIZE /* time */ +
4243 LEB128_SIZE /* method */ +
4244 LEB128_SIZE /* start */ +
4245 LEB128_SIZE /* size */ +
4249 emit_byte (method_buffer, TYPE_JIT | TYPE_METHOD);
4250 emit_time (method_buffer, info->time);
4251 emit_method_inner (method_buffer, info->method);
4252 emit_ptr (method_buffer, cstart);
4253 emit_value (method_buffer, csize);
4255 memcpy (method_buffer->data, name, nlen);
4256 method_buffer->data += nlen;
4262 g_ptr_array_free (entry->methods, TRUE);
4265 dump_buffer (prof, method_buffer);
4266 else if (method_buffer)
4267 free_buffer (method_buffer, method_buffer->size);
4269 dump_buffer (prof, entry->buffer);
4279 start_writer_thread (MonoProfiler* prof)
4281 InterlockedWrite (&prof->run_writer_thread, 1);
4283 return !pthread_create (&prof->writer_thread, NULL, writer_thread, prof);
4287 runtime_initialized (MonoProfiler *profiler)
4289 #ifndef DISABLE_HELPER_THREAD
4290 if (hs_mode_ondemand || need_helper_thread) {
4291 if (!start_helper_thread (profiler))
4292 profiler->command_port = 0;
4296 start_writer_thread (profiler);
4298 InterlockedWrite (&runtime_inited, 1);
4299 #ifndef DISABLE_HELPER_THREAD
4300 counters_init (profiler);
4301 counters_sample (profiler, 0);
4303 /* ensure the main thread data and startup are available soon */
4304 safe_send (profiler, ensure_logbuf (0));
4307 static MonoProfiler*
4308 create_profiler (const char *filename, GPtrArray *filters)
4312 int force_delete = 0;
4313 prof = (MonoProfiler *)calloc (1, sizeof (MonoProfiler));
4315 prof->command_port = command_port;
4316 if (filename && *filename == '-') {
4322 filename = "|mprof-report -";
4324 filename = "output.mlpd";
4325 nf = (char*)filename;
4327 nf = new_filename (filename);
4329 int s = strlen (nf) + 32;
4330 char *p = (char *)malloc (s);
4331 snprintf (p, s, "|mprof-report '--out=%s' -", nf);
4337 prof->file = popen (nf + 1, "w");
4338 prof->pipe_output = 1;
4339 } else if (*nf == '#') {
4340 int fd = strtol (nf + 1, NULL, 10);
4341 prof->file = fdopen (fd, "a");
4345 prof->file = fopen (nf, "wb");
4348 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
4351 #if defined (HAVE_SYS_ZLIB)
4353 prof->gzfile = gzdopen (fileno (prof->file), "wb");
4356 if (sample_type && !do_mono_sample)
4357 need_helper_thread = setup_perf_event ();
4359 /* FIXME: warn if different freq or sample type */
4363 if (do_mono_sample) {
4364 prof->stat_buffers = create_stat_buffer ();
4365 need_helper_thread = 1;
4367 if (do_counters && !need_helper_thread) {
4368 need_helper_thread = 1;
4371 prof->sorted_sample_events = g_ptr_array_sized_new (BUFFER_SIZE / SAMPLE_EVENT_SIZE_IN_SLOTS (0));
4373 #ifdef DISABLE_HELPER_THREAD
4374 if (hs_mode_ondemand)
4375 fprintf (stderr, "Ondemand heapshot unavailable on this arch.\n");
4378 fprintf (stderr, "Coverage unavailable on this arch.\n");
4382 mono_lock_free_queue_init (&prof->writer_queue);
4383 mono_os_mutex_init (&prof->method_table_mutex);
4384 prof->method_table = mono_conc_hashtable_new (NULL, NULL);
4387 coverage_init (prof);
4388 prof->coverage_filters = filters;
4390 prof->startup_time = current_time ();
4397 printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
4398 printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
4399 printf ("Options:\n");
4400 printf ("\thelp show this usage info\n");
4401 printf ("\t[no]alloc enable/disable recording allocation info\n");
4402 printf ("\t[no]calls enable/disable recording enter/leave method events\n");
4403 printf ("\theapshot[=MODE] record heap shot info (by default at each major collection)\n");
4404 printf ("\t MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
4405 printf ("\tcounters sample counters every 1s\n");
4406 printf ("\tsample[=TYPE] use statistical sampling mode (by default cycles/1000)\n");
4407 printf ("\t TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
4408 printf ("\t TYPE can be followed by /FREQUENCY\n");
4409 printf ("\ttime=fast use a faster (but more inaccurate) timer\n");
4410 printf ("\tmaxframes=NUM collect up to NUM stack frames\n");
4411 printf ("\tcalldepth=NUM ignore method events for call chain depth bigger than NUM\n");
4412 printf ("\toutput=FILENAME write the data to file FILENAME (-FILENAME to overwrite)\n");
4413 printf ("\toutput=|PROGRAM write the data to the stdin of PROGRAM\n");
4414 printf ("\t %%t is subtituted with date and time, %%p with the pid\n");
4415 printf ("\treport create a report instead of writing the raw data to a file\n");
4416 printf ("\tzip compress the output data\n");
4417 printf ("\tport=PORTNUM use PORTNUM for the listening command server\n");
4418 printf ("\tcoverage enable collection of code coverage data\n");
4419 printf ("\tcovfilter=ASSEMBLY add an assembly to the code coverage filters\n");
4420 printf ("\t add a + to include the assembly or a - to exclude it\n");
4421 printf ("\t filter=-mscorlib\n");
4422 printf ("\tcovfilter-file=FILE use FILE to generate the list of assemblies to be filtered\n");
4428 match_option (const char* p, const char *opt, char **rval)
4430 int len = strlen (opt);
4431 if (strncmp (p, opt, len) == 0) {
4433 if (p [len] == '=' && p [len + 1]) {
4434 const char *opt = p + len + 1;
4435 const char *end = strchr (opt, ',');
4443 val = (char *)malloc (l + 1);
4444 memcpy (val, opt, l);
4449 if (p [len] == 0 || p [len] == ',') {
4451 return p + len + (p [len] == ',');
4469 static const SampleMode sample_modes [] = {
4470 {"cycles", SAMPLE_CYCLES},
4471 {"instr", SAMPLE_INSTRUCTIONS},
4472 {"cachemiss", SAMPLE_CACHE_MISSES},
4473 {"cacherefs", SAMPLE_CACHE_REFS},
4474 {"branches", SAMPLE_BRANCHES},
4475 {"branchmiss", SAMPLE_BRANCH_MISSES},
4480 set_sample_mode (char* val, int allow_empty)
4483 char *maybe_freq = NULL;
4485 const SampleMode *smode = sample_modes;
4486 #ifndef USE_PERF_EVENTS
4489 if (allow_empty && !val) {
4490 sample_type = SAMPLE_CYCLES;
4494 if (strcmp (val, "mono") == 0) {
4496 sample_type = SAMPLE_CYCLES;
4500 for (smode = sample_modes; smode->name; smode++) {
4501 int l = strlen (smode->name);
4502 if (strncmp (val, smode->name, l) == 0) {
4503 sample_type = smode->sample_mode;
4504 maybe_freq = val + l;
4510 if (*maybe_freq == '/') {
4511 count = strtoul (maybe_freq + 1, &end, 10);
4512 if (maybe_freq + 1 == end)
4514 sample_freq = count;
4515 } else if (*maybe_freq != 0) {
4524 set_hsmode (char* val, int allow_empty)
4528 if (allow_empty && !val)
4530 if (strcmp (val, "ondemand") == 0) {
4531 hs_mode_ondemand = 1;
4535 count = strtoul (val, &end, 10);
4538 if (strcmp (end, "ms") == 0)
4540 else if (strcmp (end, "gc") == 0)
4548 * declaration to silence the compiler: this is the entry point that
4549 * mono will load from the shared library and call.
4552 mono_profiler_startup (const char *desc);
4555 mono_profiler_startup_log (const char *desc);
4558 * this is the entry point that will be used when the profiler
4559 * is embedded inside the main executable.
4562 mono_profiler_startup_log (const char *desc)
4564 mono_profiler_startup (desc);
4568 mono_profiler_startup (const char *desc)
4571 GPtrArray *filters = NULL;
4572 char *filename = NULL;
4576 int calls_enabled = 0;
4577 int allocs_enabled = 0;
4578 int only_counters = 0;
4579 int only_coverage = 0;
4580 int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
4581 MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
4582 MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
4583 MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS|
4584 MONO_PROFILE_INS_COVERAGE|MONO_PROFILE_APPDOMAIN_EVENTS|MONO_PROFILE_CONTEXT_EVENTS|
4585 MONO_PROFILE_ASSEMBLY_EVENTS;
4588 if (strncmp (p, "log", 3))
4593 for (; *p; p = opt) {
4599 if ((opt = match_option (p, "help", NULL)) != p) {
4603 if ((opt = match_option (p, "calls", NULL)) != p) {
4607 if ((opt = match_option (p, "nocalls", NULL)) != p) {
4608 events &= ~MONO_PROFILE_ENTER_LEAVE;
4612 if ((opt = match_option (p, "alloc", NULL)) != p) {
4616 if ((opt = match_option (p, "noalloc", NULL)) != p) {
4617 events &= ~MONO_PROFILE_ALLOCATIONS;
4620 if ((opt = match_option (p, "time", &val)) != p) {
4621 if (strcmp (val, "fast") == 0)
4623 else if (strcmp (val, "null") == 0)
4630 if ((opt = match_option (p, "report", NULL)) != p) {
4634 if ((opt = match_option (p, "debug", NULL)) != p) {
4638 if ((opt = match_option (p, "sampling-real", NULL)) != p) {
4639 sampling_mode = MONO_PROFILER_STAT_MODE_REAL;
4642 if ((opt = match_option (p, "sampling-process", NULL)) != p) {
4643 sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
4646 if ((opt = match_option (p, "heapshot", &val)) != p) {
4647 events &= ~MONO_PROFILE_ALLOCATIONS;
4648 events &= ~MONO_PROFILE_ENTER_LEAVE;
4651 set_hsmode (val, 1);
4654 if ((opt = match_option (p, "sample", &val)) != p) {
4655 events &= ~MONO_PROFILE_ALLOCATIONS;
4656 events &= ~MONO_PROFILE_ENTER_LEAVE;
4658 set_sample_mode (val, 1);
4661 if ((opt = match_option (p, "hsmode", &val)) != p) {
4662 fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
4663 set_hsmode (val, 0);
4666 if ((opt = match_option (p, "zip", NULL)) != p) {
4670 if ((opt = match_option (p, "output", &val)) != p) {
4674 if ((opt = match_option (p, "port", &val)) != p) {
4676 command_port = strtoul (val, &end, 10);
4680 if ((opt = match_option (p, "maxframes", &val)) != p) {
4682 num_frames = strtoul (val, &end, 10);
4683 if (num_frames > MAX_FRAMES)
4684 num_frames = MAX_FRAMES;
4686 notraces = num_frames == 0;
4689 if ((opt = match_option (p, "calldepth", &val)) != p) {
4691 max_call_depth = strtoul (val, &end, 10);
4695 if ((opt = match_option (p, "counters", NULL)) != p) {
4699 if ((opt = match_option (p, "countersonly", NULL)) != p) {
4703 if ((opt = match_option (p, "coverage", NULL)) != p) {
4705 events |= MONO_PROFILE_ENTER_LEAVE;
4706 debug_coverage = (g_getenv ("MONO_PROFILER_DEBUG_COVERAGE") != NULL);
4709 if ((opt = match_option (p, "onlycoverage", NULL)) != p) {
4713 if ((opt = match_option (p, "covfilter-file", &val)) != p) {
4715 char *line, *content;
4717 if (filters == NULL)
4718 filters = g_ptr_array_new ();
4720 filter_file = fopen (val, "r");
4721 if (filter_file == NULL) {
4722 fprintf (stderr, "Unable to open %s\n", val);
4726 /* Don't need to free content as it is referred to by the lines stored in @filters */
4727 content = get_file_content (filter_file);
4728 if (content == NULL)
4729 fprintf (stderr, "WARNING: %s is greater than 128kb - ignoring\n", val);
4731 while ((line = get_next_line (content, &content)))
4732 g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
4734 fclose (filter_file);
4737 if ((opt = match_option (p, "covfilter", &val)) != p) {
4738 if (filters == NULL)
4739 filters = g_ptr_array_new ();
4741 g_ptr_array_add (filters, val);
4749 if (calls_enabled) {
4750 events |= MONO_PROFILE_ENTER_LEAVE;
4754 events |= MONO_PROFILE_ALLOCATIONS;
4758 events = MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_INS_COVERAGE;
4760 utils_init (fast_time);
4762 prof = create_profiler (filename, filters);
4767 mono_profiler_install (prof, log_shutdown);
4768 mono_profiler_install_gc (gc_event, gc_resize);
4769 mono_profiler_install_allocation (gc_alloc);
4770 mono_profiler_install_gc_moves (gc_moves);
4771 mono_profiler_install_gc_roots (gc_handle, gc_roots);
4772 mono_profiler_install_appdomain (NULL, domain_loaded, NULL, domain_unloaded);
4773 mono_profiler_install_appdomain_name (domain_name);
4774 mono_profiler_install_context (context_loaded, context_unloaded);
4775 mono_profiler_install_class (NULL, class_loaded, NULL, class_unloaded);
4776 mono_profiler_install_module (NULL, image_loaded, NULL, image_unloaded);
4777 mono_profiler_install_assembly (NULL, assembly_loaded, assembly_unloaded, NULL);
4778 mono_profiler_install_thread (thread_start, thread_end);
4779 mono_profiler_install_thread_name (thread_name);
4780 mono_profiler_install_enter_leave (method_enter, method_leave);
4781 mono_profiler_install_jit_end (method_jitted);
4782 mono_profiler_install_code_buffer_new (code_buffer_new);
4783 mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
4784 mono_profiler_install_monitor (monitor_event);
4785 mono_profiler_install_runtime_initialized (runtime_initialized);
4787 mono_profiler_install_coverage_filter (coverage_filter);
4789 if (do_mono_sample && sample_type == SAMPLE_CYCLES && !only_counters) {
4790 events |= MONO_PROFILE_STATISTICAL;
4791 mono_profiler_set_statistical_mode (sampling_mode, 1000000 / sample_freq);
4792 mono_profiler_install_statistical (mono_sample_hit);
4795 mono_profiler_set_events ((MonoProfileFlags)events);
4797 TLS_INIT (tlsbuffer);
4798 TLS_INIT (tlsmethodlist);