2 * proflog.c: mono log profiler
5 * Paolo Molaro (lupus@ximian.com)
6 * Alex Rønne Petersen (alexrp@xamarin.com)
8 * Copyright 2010 Novell, Inc (http://www.novell.com)
9 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
13 #include "../mini/jit.h"
14 #include <mono/metadata/profiler.h>
15 #include <mono/metadata/threads.h>
16 #include <mono/metadata/mono-gc.h>
17 #include <mono/metadata/debug-helpers.h>
18 #include <mono/metadata/mono-perfcounters.h>
19 #include <mono/metadata/appdomain.h>
20 #include <mono/metadata/assembly.h>
21 #include <mono/metadata/tokentype.h>
22 #include <mono/metadata/tabledefs.h>
23 #include <mono/utils/atomic.h>
24 #include <mono/utils/mono-membar.h>
25 #include <mono/utils/mono-counters.h>
26 #include <mono/utils/mono-mutex.h>
27 #include <mono/utils/mono-conc-hashtable.h>
28 #include <mono/utils/lock-free-queue.h>
38 #if defined(HOST_WIN32) || defined(DISABLE_SOCKETS)
39 #define DISABLE_HELPER_THREAD 1
48 #ifdef HAVE_EXECINFO_H
55 #ifndef DISABLE_HELPER_THREAD
56 #include <sys/types.h>
57 #include <sys/socket.h>
58 #include <netinet/in.h>
59 #include <sys/select.h>
68 #ifdef HAVE_SYS_STAT_H
75 #if defined (HAVE_SYS_ZLIB)
79 #if defined(__linux__)
82 #include <sys/syscall.h>
83 #include "perf_event.h"
85 #ifdef ENABLE_PERF_EVENTS
86 #define USE_PERF_EVENTS 1
88 static int read_perf_mmap (MonoProfiler* prof, int cpu);
93 #define BUFFER_SIZE (4096 * 16)
95 /* Worst-case size in bytes of a 64-bit value encoded with LEB128. */
96 #define LEB128_SIZE 10
97 /* Size in bytes of the event ID prefix. */
100 static int nocalls = 0;
101 static int notraces = 0;
102 static int use_zip = 0;
103 static int do_report = 0;
104 static int do_heap_shot = 0;
105 static int max_call_depth = 100;
106 static volatile int runtime_inited = 0;
107 static int need_helper_thread = 0;
108 static int command_port = 0;
109 static int heapshot_requested = 0;
110 static int sample_type = 0;
111 static int sample_freq = 0;
112 static int do_mono_sample = 0;
113 static int in_shutdown = 0;
114 static int do_debug = 0;
115 static int do_counters = 0;
116 static int do_coverage = 0;
117 static gboolean debug_coverage = FALSE;
118 static MonoProfileSamplingMode sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
120 typedef struct _LogBuffer LogBuffer;
126 * The file is composed by a header followed by 0 or more buffers.
127 * Each buffer contains events that happened on a thread: for a given thread
128 * buffers that appear later in the file are guaranteed to contain events
129 * that happened later in time. Buffers from separate threads could be interleaved,
131 * Buffers are not required to be aligned.
134 * [id: 4 bytes] constant value: LOG_HEADER_ID
135 * [major: 1 byte] [minor: 1 byte] major and minor version of the log profiler
136 * [format: 1 byte] version of the data format for the rest of the file
137 * [ptrsize: 1 byte] size in bytes of a pointer in the profiled program
138 * [startup time: 8 bytes] time in milliseconds since the unix epoch when the program started
139 * [timer overhead: 4 bytes] approximate overhead in nanoseconds of the timer
140 * [flags: 4 bytes] file format flags, should be 0 for now
141 * [pid: 4 bytes] pid of the profiled process
142 * [port: 2 bytes] tcp port for server if != 0
143 * [sysid: 2 bytes] operating system and architecture identifier
145 * The multiple byte integers are in little-endian format.
148 * [buffer header] [event]*
149 * Buffers have a fixed-size header followed by 0 or more bytes of event data.
150 * Timing information and other values in the event data are usually stored
151 * as uleb128 or sleb128 integers. To save space, as noted for each item below,
152 * some data is represented as a difference between the actual value and
153 * either the last value of the same type (like for timing information) or
154 * as the difference from a value stored in a buffer header.
156 * For timing information the data is stored as uleb128, since timing
157 * increases in a monotonic way in each thread: the value is the number of
158 * nanoseconds to add to the last seen timing data in a buffer. The first value
159 * in a buffer will be calculated from the time_base field in the buffer head.
161 * Object or heap sizes are stored as uleb128.
162 * Pointer differences are stored as sleb128, instead.
164 * If an unexpected value is found, the rest of the buffer should be ignored,
165 * as generally the later values need the former to be interpreted correctly.
167 * buffer header format:
168 * [bufid: 4 bytes] constant value: BUF_ID
169 * [len: 4 bytes] size of the data following the buffer header
170 * [time_base: 8 bytes] time base in nanoseconds since an unspecified epoch
171 * [ptr_base: 8 bytes] base value for pointers
172 * [obj_base: 8 bytes] base value for object addresses
173 * [thread id: 8 bytes] system-specific thread ID (pthread_t for example)
174 * [method_base: 8 bytes] base value for MonoMethod pointers
177 * [extended info: upper 4 bits] [type: lower 4 bits] [data]*
178 * The data that follows depends on type and the extended info.
179 * Type is one of the enum values in proflog.h: TYPE_ALLOC, TYPE_GC,
180 * TYPE_METADATA, TYPE_METHOD, TYPE_EXCEPTION, TYPE_MONITOR, TYPE_HEAP.
181 * The extended info bits are interpreted based on type, see
182 * each individual event description below.
183 * strings are represented as a 0-terminated utf8 sequence.
186 * [flags: uleb128] must be 0
187 * [num: uleb128] number of frames following
188 * [frame: sleb128]* num MonoMethod pointers as differences from ptr_base
192 * exinfo: flags: TYPE_ALLOC_BT
193 * [time diff: uleb128] nanoseconds since last timing
194 * [ptr: sleb128] class as a byte difference from ptr_base
195 * [obj: sleb128] object address as a byte difference from obj_base
196 * [size: uleb128] size of the object in the heap
197 * If the TYPE_ALLOC_BT flag is set, a backtrace follows.
201 * exinfo: one of TYPE_GC_EVENT, TYPE_GC_RESIZE, TYPE_GC_MOVE, TYPE_GC_HANDLE_CREATED,
202 * TYPE_GC_HANDLE_DESTROYED
203 * [time diff: uleb128] nanoseconds since last timing
204 * if exinfo == TYPE_GC_RESIZE
205 * [heap_size: uleb128] new heap size
206 * if exinfo == TYPE_GC_EVENT
207 * [event type: uleb128] GC event (MONO_GC_EVENT_* from profiler.h)
208 * [generation: uleb128] GC generation event refers to
209 * if exinfo == TYPE_GC_MOVE
210 * [num_objects: uleb128] number of object moves that follow
211 * [objaddr: sleb128]+ num_objects object pointer differences from obj_base
212 * num is always an even number: the even items are the old
213 * addresses, the odd numbers are the respective new object addresses
214 * if exinfo == TYPE_GC_HANDLE_CREATED
215 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
216 * upper bits reserved as flags
217 * [handle: uleb128] GC handle value
218 * [objaddr: sleb128] object pointer differences from obj_base
219 * if exinfo == TYPE_GC_HANDLE_DESTROYED
220 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
221 * upper bits reserved as flags
222 * [handle: uleb128] GC handle value
224 * type metadata format:
225 * type: TYPE_METADATA
226 * exinfo: one of: TYPE_END_LOAD, TYPE_END_UNLOAD (optional for TYPE_THREAD and TYPE_DOMAIN)
227 * [time diff: uleb128] nanoseconds since last timing
228 * [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
229 * TYPE_THREAD, TYPE_CONTEXT
230 * [pointer: sleb128] pointer of the metadata type depending on mtype
231 * if mtype == TYPE_CLASS
232 * [image: sleb128] MonoImage* as a pointer difference from ptr_base
233 * [flags: uleb128] must be 0
234 * [name: string] full class name
235 * if mtype == TYPE_IMAGE
236 * [flags: uleb128] must be 0
237 * [name: string] image file name
238 * if mtype == TYPE_ASSEMBLY
239 * [flags: uleb128] must be 0
240 * [name: string] assembly name
241 * if mtype == TYPE_DOMAIN
242 * [flags: uleb128] must be 0
243 * if mtype == TYPE_DOMAIN && exinfo == 0
244 * [name: string] domain friendly name
245 * if mtype == TYPE_CONTEXT
246 * [domain: sleb128] domain id as pointer
247 * if mtype == TYPE_THREAD && (format_version < 11 || (format_version > 10 && exinfo == 0))
248 * [name: string] thread name
250 * type method format:
252 * exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
253 * [time diff: uleb128] nanoseconds since last timing
254 * [method: sleb128] MonoMethod* as a pointer difference from the last such
255 * pointer or the buffer method_base
256 * if exinfo == TYPE_JIT
257 * [code address: sleb128] pointer to the native code as a diff from ptr_base
258 * [code size: uleb128] size of the generated code
259 * [name: string] full method name
261 * type runtime format:
263 * exinfo: one of: TYPE_JITHELPER
264 * [time diff: uleb128] nanoseconds since last timing
265 * if exinfo == TYPE_JITHELPER
266 * [type: uleb128] MonoProfilerCodeBufferType enum value
267 * [buffer address: sleb128] pointer to the native code as a diff from ptr_base
268 * [buffer size: uleb128] size of the generated code
269 * if type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE
270 * [name: string] buffer description name
272 * type monitor format:
274 * exinfo: TYPE_MONITOR_BT flag and one of: MONO_PROFILER_MONITOR_(CONTENTION|FAIL|DONE)
275 * [time diff: uleb128] nanoseconds since last timing
276 * [object: sleb128] the lock object as a difference from obj_base
277 * if exinfo.low3bits == MONO_PROFILER_MONITOR_CONTENTION
278 * If the TYPE_MONITOR_BT flag is set, a backtrace follows.
282 * exinfo: one of TYPE_HEAP_START, TYPE_HEAP_END, TYPE_HEAP_OBJECT, TYPE_HEAP_ROOT
283 * if exinfo == TYPE_HEAP_START
284 * [time diff: uleb128] nanoseconds since last timing
285 * if exinfo == TYPE_HEAP_END
286 * [time diff: uleb128] nanoseconds since last timing
287 * if exinfo == TYPE_HEAP_OBJECT
288 * [object: sleb128] the object as a difference from obj_base
289 * [class: sleb128] the object MonoClass* as a difference from ptr_base
290 * [size: uleb128] size of the object on the heap
291 * [num_refs: uleb128] number of object references
292 * if (format version > 1) each referenced objref is preceded by a
293 * uleb128 encoded offset: the first offset is from the object address
294 * and each next offset is relative to the previous one
295 * [objrefs: sleb128]+ object referenced as a difference from obj_base
296 * The same object can appear multiple times, but only the first time
297 * with size != 0: in the other cases this data will only be used to
298 * provide additional referenced objects.
299 * if exinfo == TYPE_HEAP_ROOT
300 * [num_roots: uleb128] number of root references
301 * [num_gc: uleb128] number of major gcs
302 * [object: sleb128] the object as a difference from obj_base
303 * [root_type: uleb128] the root_type: MonoProfileGCRootType (profiler.h)
304 * [extra_info: uleb128] the extra_info value
305 * object, root_type and extra_info are repeated num_roots times
309 * exinfo: one of TYPE_SAMPLE_HIT, TYPE_SAMPLE_USYM, TYPE_SAMPLE_UBIN, TYPE_SAMPLE_COUNTERS_DESC, TYPE_SAMPLE_COUNTERS
310 * if exinfo == TYPE_SAMPLE_HIT
311 * [sample_type: uleb128] type of sample (SAMPLE_*)
312 * [timestamp: uleb128] nanoseconds since startup (note: different from other timestamps!)
313 * if (format_version > 10)
314 * [thread: sleb128] thread id as difference from ptr_base
315 * [count: uleb128] number of following instruction addresses
316 * [ip: sleb128]* instruction pointer as difference from ptr_base
317 * if (format_version > 5)
318 * [mbt_count: uleb128] number of managed backtrace info triplets (method + IL offset + native offset)
319 * [method: sleb128]* MonoMethod* as a pointer difference from the last such
320 * pointer or the buffer method_base (the first such method can be also indentified by ip, but this is not neccessarily true)
321 * [il_offset: sleb128]* IL offset inside method where the hit occurred
322 * [native_offset: sleb128]* native offset inside method where the hit occurred
323 * if exinfo == TYPE_SAMPLE_USYM
324 * [address: sleb128] symbol address as a difference from ptr_base
325 * [size: uleb128] symbol size (may be 0 if unknown)
326 * [name: string] symbol name
327 * if exinfo == TYPE_SAMPLE_UBIN
328 * [time diff: uleb128] nanoseconds since last timing
329 * [address: sleb128] address where binary has been loaded
330 * [offset: uleb128] file offset of mapping (the same file can be mapped multiple times)
331 * [size: uleb128] memory size
332 * [name: string] binary name
333 * if exinfo == TYPE_SAMPLE_COUNTERS_DESC
334 * [len: uleb128] number of counters
336 * [section: uleb128] section of counter
337 * if section == MONO_COUNTER_PERFCOUNTERS:
338 * [section_name: string] section name of counter
339 * [name: string] name of counter
340 * [type: uleb128] type of counter
341 * [unit: uleb128] unit of counter
342 * [variance: uleb128] variance of counter
343 * [index: uleb128] unique index of counter
344 * if exinfo == TYPE_SAMPLE_COUNTERS
345 * [timestamp: uleb128] sampling timestamp
347 * [index: uleb128] unique index of counter
350 * [type: uleb128] type of counter value
353 * [0: uleb128] 0 -> value is null
355 * [1: uleb128] 1 -> value is not null
356 * [value: string] counter value
358 * [value: uleb128/sleb128/double] counter value, can be sleb128, uleb128 or double (determined by using type)
360 * type coverage format
361 * type: TYPE_COVERAGE
362 * exinfo: one of TYPE_COVERAGE_METHOD, TYPE_COVERAGE_STATEMENT, TYPE_COVERAGE_ASSEMBLY, TYPE_COVERAGE_CLASS
363 * if exinfo == TYPE_COVERAGE_METHOD
364 * [assembly: string] name of assembly
365 * [class: string] name of the class
366 * [name: string] name of the method
367 * [signature: string] the signature of the method
368 * [filename: string] the file path of the file that contains this method
369 * [token: uleb128] the method token
370 * [method_id: uleb128] an ID for this data to associate with the buffers of TYPE_COVERAGE_STATEMENTS
371 * [len: uleb128] the number of TYPE_COVERAGE_BUFFERS associated with this method
372 * if exinfo == TYPE_COVERAGE_STATEMENTS
373 * [method_id: uleb128] an the TYPE_COVERAGE_METHOD buffer to associate this with
374 * [offset: uleb128] the il offset relative to the previous offset
375 * [counter: uleb128] the counter for this instruction
376 * [line: uleb128] the line of filename containing this instruction
377 * [column: uleb128] the column containing this instruction
378 * if exinfo == TYPE_COVERAGE_ASSEMBLY
379 * [name: string] assembly name
380 * [guid: string] assembly GUID
381 * [filename: string] assembly filename
382 * [number_of_methods: uleb128] the number of methods in this assembly
383 * [fully_covered: uleb128] the number of fully covered methods
384 * [partially_covered: uleb128] the number of partially covered methods
385 * currently partially_covered will always be 0, and fully_covered is the
386 * number of methods that are fully and partially covered.
387 * if exinfo == TYPE_COVERAGE_CLASS
388 * [name: string] assembly name
389 * [class: string] class name
390 * [number_of_methods: uleb128] the number of methods in this class
391 * [fully_covered: uleb128] the number of fully covered methods
392 * [partially_covered: uleb128] the number of partially covered methods
393 * currently partially_covered will always be 0, and fully_covered is the
394 * number of methods that are fully and partially covered.
398 * Format oddities that we ought to fix:
400 * - Methods written in emit_bt () should be based on the buffer's base
401 * method instead of the base pointer.
402 * - The TYPE_SAMPLE_HIT event contains (currently) pointless data like
403 * always-one unmanaged frame count and always-zero IL offsets.
405 * These are mostly small things and are not worth a format change by
406 * themselves. They should be done when some other major change has to
407 * be done to the format.
415 uintptr_t method_base;
416 uintptr_t last_method;
419 unsigned char* data_end;
424 unsigned char buf [1];
428 ign_res (int G_GNUC_UNUSED unused, ...)
432 #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++;}
433 #define EXIT_LOG(lb) (lb)->locked--;
435 typedef struct _StatBuffer StatBuffer;
444 typedef struct _BinaryObject BinaryObject;
446 struct _BinaryObject {
452 struct _MonoProfiler {
453 StatBuffer *stat_buffers;
455 #if defined (HAVE_SYS_ZLIB)
458 uint64_t startup_time;
460 int last_gc_gen_started;
465 pthread_t helper_thread;
466 pthread_t writer_thread;
468 volatile gint32 run_writer_thread;
469 MonoLockFreeQueue writer_queue;
470 MonoConcurrentHashTable *method_table;
471 mono_mutex_t method_table_mutex;
472 BinaryObject *binary_objects;
473 GPtrArray *coverage_filters;
474 GPtrArray *sorted_sample_events;
477 typedef struct _WriterQueueEntry WriterQueueEntry;
478 struct _WriterQueueEntry {
479 MonoLockFreeQueueNode node;
484 typedef struct _MethodInfo MethodInfo;
495 #define TLS_SET(x,y) (TlsSetValue (x, y))
496 #define TLS_GET(t,x) ((t *) TlsGetValue (x))
497 #define TLS_INIT(x) (x = TlsAlloc ())
498 static int tlsbuffer;
499 static int tlsmethodlist;
501 #define TLS_SET(x,y) (x = y)
502 #define TLS_GET(t,x) (x)
504 static __thread LogBuffer* tlsbuffer = NULL;
505 static __thread GPtrArray* tlsmethodlist = NULL;
507 #define TLS_SET(x,y) (pthread_setspecific (x, y))
508 #define TLS_GET(t,x) ((t *) pthread_getspecific (x))
509 #define TLS_INIT(x) (pthread_key_create (&x, NULL))
510 static pthread_key_t tlsbuffer;
511 static pthread_key_t tlsmethodlist;
514 static void safe_send (MonoProfiler *profiler, LogBuffer *logbuffer);
517 pstrdup (const char *s)
519 int len = strlen (s) + 1;
520 char *p = malloc (len);
526 create_stat_buffer (void)
528 StatBuffer* buf = alloc_buffer (BUFFER_SIZE);
529 buf->size = BUFFER_SIZE;
530 buf->data_end = (uintptr_t*)((unsigned char*)buf + buf->size);
531 buf->data = buf->buf;
538 LogBuffer* buf = alloc_buffer (BUFFER_SIZE);
539 buf->size = BUFFER_SIZE;
540 buf->time_base = current_time ();
541 buf->last_time = buf->time_base;
542 buf->data_end = (unsigned char*)buf + buf->size;
543 buf->data = buf->buf;
550 if (!TLS_GET (LogBuffer, tlsbuffer)) {
551 LogBuffer *logbuffer = create_buffer ();
552 TLS_SET (tlsbuffer, logbuffer);
553 logbuffer->thread_id = thread_id ();
555 if (!TLS_GET (GPtrArray, tlsmethodlist)) {
556 GPtrArray *methodlist = g_ptr_array_new ();
557 TLS_SET (tlsmethodlist, methodlist);
560 //printf ("thread %p at time %llu\n", (void*)logbuffer->thread_id, logbuffer->time_base);
564 ensure_logbuf_inner (LogBuffer *old, int bytes)
566 if (old && old->data + bytes + 100 < old->data_end)
569 LogBuffer *new = create_buffer ();
570 new->thread_id = thread_id ();
574 new->call_depth = old->call_depth;
580 ensure_logbuf (int bytes)
582 LogBuffer *old = TLS_GET (LogBuffer, tlsbuffer);
583 LogBuffer *new = ensure_logbuf_inner (old, bytes);
586 return old; // Still enough space.
588 TLS_SET (tlsbuffer, new);
595 emit_byte (LogBuffer *logbuffer, int value)
597 logbuffer->data [0] = value;
599 assert (logbuffer->data <= logbuffer->data_end);
603 emit_value (LogBuffer *logbuffer, int value)
605 encode_uleb128 (value, logbuffer->data, &logbuffer->data);
606 assert (logbuffer->data <= logbuffer->data_end);
610 emit_time (LogBuffer *logbuffer, uint64_t value)
612 uint64_t tdiff = value - logbuffer->last_time;
613 if (value < logbuffer->last_time)
614 printf ("time went backwards\n");
615 //if (tdiff > 1000000)
616 // printf ("large time offset: %llu\n", tdiff);
617 encode_uleb128 (tdiff, logbuffer->data, &logbuffer->data);
618 /*if (tdiff != decode_uleb128 (p, &p))
619 printf ("incorrect encoding: %llu\n", tdiff);*/
620 logbuffer->last_time = value;
621 assert (logbuffer->data <= logbuffer->data_end);
625 emit_svalue (LogBuffer *logbuffer, int64_t value)
627 encode_sleb128 (value, logbuffer->data, &logbuffer->data);
628 assert (logbuffer->data <= logbuffer->data_end);
632 emit_uvalue (LogBuffer *logbuffer, uint64_t value)
634 encode_uleb128 (value, logbuffer->data, &logbuffer->data);
635 assert (logbuffer->data <= logbuffer->data_end);
639 emit_ptr (LogBuffer *logbuffer, void *ptr)
641 if (!logbuffer->ptr_base)
642 logbuffer->ptr_base = (uintptr_t)ptr;
643 emit_svalue (logbuffer, (intptr_t)ptr - logbuffer->ptr_base);
644 assert (logbuffer->data <= logbuffer->data_end);
648 emit_method_inner (LogBuffer *logbuffer, void *method)
650 if (!logbuffer->method_base) {
651 logbuffer->method_base = (intptr_t)method;
652 logbuffer->last_method = (intptr_t)method;
654 encode_sleb128 ((intptr_t)((char*)method - (char*)logbuffer->last_method), logbuffer->data, &logbuffer->data);
655 logbuffer->last_method = (intptr_t)method;
656 assert (logbuffer->data <= logbuffer->data_end);
665 find_method (MonoDomain *domain, void *user_data)
667 MethodSearch *search = user_data;
672 MonoJitInfo *ji = mono_get_jit_info_from_method (domain, search->method);
674 // It could be AOT'd, so we need to get it from the AOT runtime's cache.
676 void *ip = mono_aot_get_method (domain, search->method);
678 // Avoid a slow path in mono_jit_info_table_find ().
680 ji = mono_jit_info_table_find (domain, ip);
688 register_method_local (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji)
690 if (!mono_conc_hashtable_lookup (prof->method_table, method)) {
692 MethodSearch search = { method, NULL };
694 mono_domain_foreach (find_method, &search);
701 MethodInfo *info = malloc (sizeof (MethodInfo));
703 info->method = method;
706 g_ptr_array_add (TLS_GET (GPtrArray, tlsmethodlist), info);
711 emit_method (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
713 register_method_local (prof, method, NULL);
714 emit_method_inner (logbuffer, method);
718 emit_method_as_ptr (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
720 register_method_local (prof, method, NULL);
721 emit_ptr (logbuffer, method);
725 emit_obj (LogBuffer *logbuffer, void *ptr)
727 if (!logbuffer->obj_base)
728 logbuffer->obj_base = (uintptr_t)ptr >> 3;
729 emit_svalue (logbuffer, ((uintptr_t)ptr >> 3) - logbuffer->obj_base);
730 assert (logbuffer->data <= logbuffer->data_end);
734 emit_string (LogBuffer *logbuffer, const char *str, size_t size)
738 for (; i < size; i++) {
741 emit_byte (logbuffer, str [i]);
744 emit_byte (logbuffer, '\0');
748 emit_double (LogBuffer *logbuffer, double value)
751 unsigned char buffer[8];
752 memcpy (buffer, &value, 8);
753 #if G_BYTE_ORDER == G_BIG_ENDIAN
754 for (i = 7; i >= 0; i--)
756 for (i = 0; i < 8; i++)
758 emit_byte (logbuffer, buffer[i]);
762 write_int16 (char *buf, int32_t value)
765 for (i = 0; i < 2; ++i) {
773 write_int32 (char *buf, int32_t value)
776 for (i = 0; i < 4; ++i) {
784 write_int64 (char *buf, int64_t value)
787 for (i = 0; i < 8; ++i) {
795 dump_header (MonoProfiler *profiler)
799 p = write_int32 (p, LOG_HEADER_ID);
800 *p++ = LOG_VERSION_MAJOR;
801 *p++ = LOG_VERSION_MINOR;
802 *p++ = LOG_DATA_VERSION;
803 *p++ = sizeof (void*);
804 p = write_int64 (p, ((uint64_t)time (NULL)) * 1000); /* startup time */
805 p = write_int32 (p, get_timer_overhead ()); /* timer overhead */
806 p = write_int32 (p, 0); /* flags */
807 p = write_int32 (p, process_id ()); /* pid */
808 p = write_int16 (p, profiler->command_port); /* port */
809 p = write_int16 (p, 0); /* opsystem */
810 #if defined (HAVE_SYS_ZLIB)
811 if (profiler->gzfile) {
812 gzwrite (profiler->gzfile, hbuf, p - hbuf);
814 fwrite (hbuf, p - hbuf, 1, profiler->file);
817 fwrite (hbuf, p - hbuf, 1, profiler->file);
818 fflush (profiler->file);
823 send_buffer (MonoProfiler *prof, GPtrArray *methods, LogBuffer *buffer)
825 WriterQueueEntry *entry = calloc (1, sizeof (WriterQueueEntry));
826 mono_lock_free_queue_node_init (&entry->node, FALSE);
827 entry->methods = methods;
828 entry->buffer = buffer;
829 mono_lock_free_queue_enqueue (&prof->writer_queue, &entry->node);
833 dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
838 dump_buffer (profiler, buf->next);
839 p = write_int32 (p, BUF_ID);
840 p = write_int32 (p, buf->data - buf->buf);
841 p = write_int64 (p, buf->time_base);
842 p = write_int64 (p, buf->ptr_base);
843 p = write_int64 (p, buf->obj_base);
844 p = write_int64 (p, buf->thread_id);
845 p = write_int64 (p, buf->method_base);
846 #if defined (HAVE_SYS_ZLIB)
847 if (profiler->gzfile) {
848 gzwrite (profiler->gzfile, hbuf, p - hbuf);
849 gzwrite (profiler->gzfile, buf->buf, buf->data - buf->buf);
852 fwrite (hbuf, p - hbuf, 1, profiler->file);
853 fwrite (buf->buf, buf->data - buf->buf, 1, profiler->file);
854 fflush (profiler->file);
855 #if defined (HAVE_SYS_ZLIB)
858 free_buffer (buf, buf->size);
862 process_requests (MonoProfiler *profiler)
864 if (heapshot_requested)
865 mono_gc_collect (mono_gc_max_generation ());
868 static void counters_init (MonoProfiler *profiler);
869 static void counters_sample (MonoProfiler *profiler, uint64_t timestamp);
872 * Can be called only at safe callback locations.
875 safe_send (MonoProfiler *profiler, LogBuffer *logbuffer)
877 /* We need the runtime initialized so that we have threads and hazard
878 * pointers available. Otherwise, the lock free queue will not work and
879 * there won't be a thread to process the data.
881 * While the runtime isn't initialized, we just accumulate data in the
882 * thread local buffer list.
884 if (!InterlockedRead (&runtime_inited))
887 int cd = logbuffer->call_depth;
889 send_buffer (profiler, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
891 TLS_SET (tlsbuffer, NULL);
892 TLS_SET (tlsmethodlist, NULL);
896 TLS_GET (LogBuffer, tlsbuffer)->call_depth = cd;
900 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
903 uintptr_t last_offset = 0;
904 //const char *name = mono_class_get_name (klass);
905 LogBuffer *logbuffer = ensure_logbuf (
906 EVENT_SIZE /* event */ +
907 LEB128_SIZE /* obj */ +
908 LEB128_SIZE /* klass */ +
909 LEB128_SIZE /* size */ +
910 LEB128_SIZE /* num */ +
912 LEB128_SIZE /* offset */ +
913 LEB128_SIZE /* ref */
916 emit_byte (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
917 emit_obj (logbuffer, obj);
918 emit_ptr (logbuffer, klass);
919 /* account for object alignment in the heap */
922 emit_value (logbuffer, size);
923 emit_value (logbuffer, num);
924 for (i = 0; i < num; ++i) {
925 emit_value (logbuffer, offsets [i] - last_offset);
926 last_offset = offsets [i];
927 emit_obj (logbuffer, refs [i]);
930 // printf ("obj: %p, klass: %s, refs: %d, size: %d\n", obj, name, (int)num, (int)size);
934 static unsigned int hs_mode_ms = 0;
935 static unsigned int hs_mode_gc = 0;
936 static unsigned int hs_mode_ondemand = 0;
937 static unsigned int gc_count = 0;
938 static uint64_t last_hs_time = 0;
941 heap_walk (MonoProfiler *profiler)
945 LogBuffer *logbuffer;
948 logbuffer = ensure_logbuf (
949 EVENT_SIZE /* event */ +
950 LEB128_SIZE /* time */
952 now = current_time ();
953 if (hs_mode_ms && (now - last_hs_time)/1000000 >= hs_mode_ms)
955 else if (hs_mode_gc && (gc_count % hs_mode_gc) == 0)
957 else if (hs_mode_ondemand)
958 do_walk = heapshot_requested;
959 else if (!hs_mode_ms && !hs_mode_gc && profiler->last_gc_gen_started == mono_gc_max_generation ())
964 heapshot_requested = 0;
965 emit_byte (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
966 emit_time (logbuffer, now);
967 mono_gc_walk_heap (0, gc_reference, NULL);
968 logbuffer = ensure_logbuf (
969 EVENT_SIZE /* event */ +
970 LEB128_SIZE /* time */
972 now = current_time ();
973 emit_byte (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
974 emit_time (logbuffer, now);
979 gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation) {
981 LogBuffer *logbuffer = ensure_logbuf (
982 EVENT_SIZE /* event */ +
983 LEB128_SIZE /* time */ +
984 LEB128_SIZE /* gc event */ +
985 LEB128_SIZE /* generation */
987 now = current_time ();
988 ENTER_LOG (logbuffer, "gcevent");
989 emit_byte (logbuffer, TYPE_GC_EVENT | TYPE_GC);
990 emit_time (logbuffer, now);
991 emit_value (logbuffer, ev);
992 emit_value (logbuffer, generation);
993 /* to deal with nested gen1 after gen0 started */
994 if (ev == MONO_GC_EVENT_START) {
995 profiler->last_gc_gen_started = generation;
996 if (generation == mono_gc_max_generation ())
999 if (ev == MONO_GC_EVENT_PRE_START_WORLD)
1000 heap_walk (profiler);
1001 EXIT_LOG (logbuffer);
1002 if (ev == MONO_GC_EVENT_POST_START_WORLD)
1003 safe_send (profiler, logbuffer);
1004 //printf ("gc event %d for generation %d\n", ev, generation);
1008 gc_resize (MonoProfiler *profiler, int64_t new_size) {
1010 LogBuffer *logbuffer = ensure_logbuf (
1011 EVENT_SIZE /* event */ +
1012 LEB128_SIZE /* time */ +
1013 LEB128_SIZE /* new size */
1015 now = current_time ();
1016 ENTER_LOG (logbuffer, "gcresize");
1017 emit_byte (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
1018 emit_time (logbuffer, now);
1019 emit_value (logbuffer, new_size);
1020 //printf ("gc resized to %lld\n", new_size);
1021 EXIT_LOG (logbuffer);
1024 #define MAX_FRAMES 32
1027 MonoMethod* methods [MAX_FRAMES];
1028 int32_t il_offsets [MAX_FRAMES];
1029 int32_t native_offsets [MAX_FRAMES];
1031 static int num_frames = MAX_FRAMES;
1034 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
1036 FrameData *frame = data;
1037 if (method && frame->count < num_frames) {
1038 frame->il_offsets [frame->count] = il_offset;
1039 frame->native_offsets [frame->count] = native_offset;
1040 frame->methods [frame->count++] = method;
1041 //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
1043 return frame->count == num_frames;
1047 * a note about stack walks: they can cause more profiler events to fire,
1048 * so we need to make sure they don't happen after we started emitting an
1049 * event, hence the collect_bt/emit_bt split.
1052 collect_bt (FrameData *data)
1055 mono_stack_walk_no_il (walk_stack, data);
1059 emit_bt (MonoProfiler *prof, LogBuffer *logbuffer, FrameData *data)
1061 /* FIXME: this is actually tons of data and we should
1062 * just output it the first time and use an id the next
1064 if (data->count > num_frames)
1065 printf ("bad num frames: %d\n", data->count);
1066 emit_value (logbuffer, 0); /* flags */
1067 emit_value (logbuffer, data->count);
1068 //if (*p != data.count) {
1069 // 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);}
1070 while (data->count) {
1071 emit_method_as_ptr (prof, logbuffer, data->methods [--data->count]);
1076 gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1080 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces)? TYPE_ALLOC_BT: 0;
1082 LogBuffer *logbuffer;
1083 len = mono_object_get_size (obj);
1084 /* account for object alignment in the heap */
1089 logbuffer = ensure_logbuf (
1090 EVENT_SIZE /* event */ +
1091 LEB128_SIZE /* time */ +
1092 LEB128_SIZE /* klass */ +
1093 LEB128_SIZE /* obj */ +
1094 LEB128_SIZE /* size */ +
1096 LEB128_SIZE /* flags */ +
1097 LEB128_SIZE /* count */ +
1099 LEB128_SIZE /* method */
1103 now = current_time ();
1104 ENTER_LOG (logbuffer, "gcalloc");
1105 emit_byte (logbuffer, do_bt | TYPE_ALLOC);
1106 emit_time (logbuffer, now);
1107 emit_ptr (logbuffer, klass);
1108 emit_obj (logbuffer, obj);
1109 emit_value (logbuffer, len);
1111 emit_bt (prof, logbuffer, &data);
1112 EXIT_LOG (logbuffer);
1113 if (logbuffer->next)
1114 safe_send (prof, logbuffer);
1115 process_requests (prof);
1116 //printf ("gc alloc %s at %p\n", mono_class_get_name (klass), obj);
1120 gc_moves (MonoProfiler *prof, void **objects, int num)
1124 LogBuffer *logbuffer = ensure_logbuf (
1125 EVENT_SIZE /* event */ +
1126 LEB128_SIZE /* time */ +
1127 LEB128_SIZE /* num */ +
1129 LEB128_SIZE /* object */
1132 now = current_time ();
1133 ENTER_LOG (logbuffer, "gcmove");
1134 emit_byte (logbuffer, TYPE_GC_MOVE | TYPE_GC);
1135 emit_time (logbuffer, now);
1136 emit_value (logbuffer, num);
1137 for (i = 0; i < num; ++i)
1138 emit_obj (logbuffer, objects [i]);
1139 //printf ("gc moved %d objects\n", num/2);
1140 EXIT_LOG (logbuffer);
1144 gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
1147 LogBuffer *logbuffer = ensure_logbuf (
1148 EVENT_SIZE /* event */ +
1149 LEB128_SIZE /* num */ +
1150 LEB128_SIZE /* collections */ +
1152 LEB128_SIZE /* object */ +
1153 LEB128_SIZE /* root type */ +
1154 LEB128_SIZE /* extra info */
1157 ENTER_LOG (logbuffer, "gcroots");
1158 emit_byte (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
1159 emit_value (logbuffer, num);
1160 emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
1161 for (i = 0; i < num; ++i) {
1162 emit_obj (logbuffer, objects [i]);
1163 emit_value (logbuffer, root_types [i]);
1164 emit_value (logbuffer, extra_info [i]);
1166 EXIT_LOG (logbuffer);
1170 gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
1173 LogBuffer *logbuffer = ensure_logbuf (
1174 EVENT_SIZE /* event */ +
1175 LEB128_SIZE /* time */ +
1176 LEB128_SIZE /* type */ +
1177 LEB128_SIZE /* handle */ +
1178 (op == MONO_PROFILER_GC_HANDLE_CREATED ? (
1179 LEB128_SIZE /* obj */
1182 now = current_time ();
1183 ENTER_LOG (logbuffer, "gchandle");
1184 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1185 emit_byte (logbuffer, TYPE_GC_HANDLE_CREATED | TYPE_GC);
1186 else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
1187 emit_byte (logbuffer, TYPE_GC_HANDLE_DESTROYED | TYPE_GC);
1190 emit_time (logbuffer, now);
1191 emit_value (logbuffer, type);
1192 emit_value (logbuffer, handle);
1193 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1194 emit_obj (logbuffer, obj);
1195 EXIT_LOG (logbuffer);
1196 process_requests (prof);
1200 push_nesting (char *p, MonoClass *klass)
1205 nesting = mono_class_get_nesting_type (klass);
1207 p = push_nesting (p, nesting);
1211 name = mono_class_get_name (klass);
1212 nspace = mono_class_get_namespace (klass);
1215 p += strlen (nspace);
1225 type_name (MonoClass *klass)
1229 push_nesting (buf, klass);
1230 p = malloc (strlen (buf) + 1);
1236 image_loaded (MonoProfiler *prof, MonoImage *image, int result)
1241 LogBuffer *logbuffer;
1242 if (result != MONO_PROFILE_OK)
1244 name = mono_image_get_filename (image);
1245 nlen = strlen (name) + 1;
1246 logbuffer = ensure_logbuf (
1247 EVENT_SIZE /* event */ +
1248 LEB128_SIZE /* time */ +
1249 EVENT_SIZE /* type */ +
1250 LEB128_SIZE /* image */ +
1251 LEB128_SIZE /* flags */ +
1254 now = current_time ();
1255 ENTER_LOG (logbuffer, "image");
1256 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1257 emit_time (logbuffer, now);
1258 emit_byte (logbuffer, TYPE_IMAGE);
1259 emit_ptr (logbuffer, image);
1260 emit_value (logbuffer, 0); /* flags */
1261 memcpy (logbuffer->data, name, nlen);
1262 logbuffer->data += nlen;
1263 //printf ("loaded image %p (%s)\n", image, name);
1264 EXIT_LOG (logbuffer);
1265 if (logbuffer->next)
1266 safe_send (prof, logbuffer);
1267 process_requests (prof);
1271 image_unloaded (MonoProfiler *prof, MonoImage *image)
1273 const char *name = mono_image_get_filename (image);
1274 int nlen = strlen (name) + 1;
1275 LogBuffer *logbuffer = ensure_logbuf (
1276 EVENT_SIZE /* event */ +
1277 LEB128_SIZE /* time */ +
1278 EVENT_SIZE /* type */ +
1279 LEB128_SIZE /* image */ +
1280 LEB128_SIZE /* flags */ +
1283 uint64_t now = current_time ();
1285 ENTER_LOG (logbuffer, "image-unload");
1286 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1287 emit_time (logbuffer, now);
1288 emit_byte (logbuffer, TYPE_IMAGE);
1289 emit_ptr (logbuffer, image);
1290 emit_value (logbuffer, 0); /* flags */
1291 memcpy (logbuffer->data, name, nlen);
1292 logbuffer->data += nlen;
1293 EXIT_LOG (logbuffer);
1295 if (logbuffer->next)
1296 safe_send (prof, logbuffer);
1298 process_requests (prof);
1302 assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly, int result)
1304 if (result != MONO_PROFILE_OK)
1307 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1308 int nlen = strlen (name) + 1;
1309 LogBuffer *logbuffer = ensure_logbuf (
1310 EVENT_SIZE /* event */ +
1311 LEB128_SIZE /* time */ +
1312 EVENT_SIZE /* type */ +
1313 LEB128_SIZE /* assembly */ +
1314 LEB128_SIZE /* flags */ +
1317 uint64_t now = current_time ();
1319 ENTER_LOG (logbuffer, "assembly-load");
1320 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1321 emit_time (logbuffer, now);
1322 emit_byte (logbuffer, TYPE_ASSEMBLY);
1323 emit_ptr (logbuffer, assembly);
1324 emit_value (logbuffer, 0); /* flags */
1325 memcpy (logbuffer->data, name, nlen);
1326 logbuffer->data += nlen;
1327 EXIT_LOG (logbuffer);
1331 if (logbuffer->next)
1332 safe_send (prof, logbuffer);
1334 process_requests (prof);
1338 assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
1340 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1341 int nlen = strlen (name) + 1;
1342 LogBuffer *logbuffer = ensure_logbuf (
1343 EVENT_SIZE /* event */ +
1344 LEB128_SIZE /* time */ +
1345 EVENT_SIZE /* type */ +
1346 LEB128_SIZE /* assembly */ +
1347 LEB128_SIZE /* flags */ +
1350 uint64_t now = current_time ();
1352 ENTER_LOG (logbuffer, "assembly-unload");
1353 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1354 emit_time (logbuffer, now);
1355 emit_byte (logbuffer, TYPE_ASSEMBLY);
1356 emit_ptr (logbuffer, assembly);
1357 emit_value (logbuffer, 0); /* flags */
1358 memcpy (logbuffer->data, name, nlen);
1359 logbuffer->data += nlen;
1360 EXIT_LOG (logbuffer);
1364 if (logbuffer->next)
1365 safe_send (prof, logbuffer);
1367 process_requests (prof);
1371 class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
1377 LogBuffer *logbuffer;
1378 if (result != MONO_PROFILE_OK)
1380 if (InterlockedRead (&runtime_inited))
1381 name = mono_type_get_name (mono_class_get_type (klass));
1383 name = type_name (klass);
1384 nlen = strlen (name) + 1;
1385 image = mono_class_get_image (klass);
1386 logbuffer = ensure_logbuf (
1387 EVENT_SIZE /* event */ +
1388 LEB128_SIZE /* time */ +
1389 EVENT_SIZE /* type */ +
1390 LEB128_SIZE /* klass */ +
1391 LEB128_SIZE /* image */ +
1392 LEB128_SIZE /* flags */ +
1395 now = current_time ();
1396 ENTER_LOG (logbuffer, "class");
1397 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1398 emit_time (logbuffer, now);
1399 emit_byte (logbuffer, TYPE_CLASS);
1400 emit_ptr (logbuffer, klass);
1401 emit_ptr (logbuffer, image);
1402 emit_value (logbuffer, 0); /* flags */
1403 memcpy (logbuffer->data, name, nlen);
1404 logbuffer->data += nlen;
1405 //printf ("loaded class %p (%s)\n", klass, name);
1410 EXIT_LOG (logbuffer);
1411 if (logbuffer->next)
1412 safe_send (prof, logbuffer);
1413 process_requests (prof);
1417 class_unloaded (MonoProfiler *prof, MonoClass *klass)
1421 if (InterlockedRead (&runtime_inited))
1422 name = mono_type_get_name (mono_class_get_type (klass));
1424 name = type_name (klass);
1426 int nlen = strlen (name) + 1;
1427 MonoImage *image = mono_class_get_image (klass);
1428 LogBuffer *logbuffer = ensure_logbuf (
1429 EVENT_SIZE /* event */ +
1430 LEB128_SIZE /* time */ +
1431 EVENT_SIZE /* type */ +
1432 LEB128_SIZE /* klass */ +
1433 LEB128_SIZE /* image */ +
1434 LEB128_SIZE /* flags */ +
1437 uint64_t now = current_time ();
1439 ENTER_LOG (logbuffer, "class-unload");
1440 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1441 emit_time (logbuffer, now);
1442 emit_byte (logbuffer, TYPE_CLASS);
1443 emit_ptr (logbuffer, klass);
1444 emit_ptr (logbuffer, image);
1445 emit_value (logbuffer, 0); /* flags */
1446 memcpy (logbuffer->data, name, nlen);
1447 logbuffer->data += nlen;
1448 EXIT_LOG (logbuffer);
1455 if (logbuffer->next)
1456 safe_send (prof, logbuffer);
1458 process_requests (prof);
1461 #ifndef DISABLE_HELPER_THREAD
1462 static void process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method);
1463 #endif /* DISABLE_HELPER_THREAD */
1466 method_enter (MonoProfiler *prof, MonoMethod *method)
1468 uint64_t now = current_time ();
1470 #ifndef DISABLE_HELPER_THREAD
1471 process_method_enter_coverage (prof, method);
1472 #endif /* DISABLE_HELPER_THREAD */
1474 LogBuffer *logbuffer = ensure_logbuf (
1475 EVENT_SIZE /* event */ +
1476 LEB128_SIZE /* time */ +
1477 LEB128_SIZE /* method */
1479 if (logbuffer->call_depth++ > max_call_depth)
1481 ENTER_LOG (logbuffer, "enter");
1482 emit_byte (logbuffer, TYPE_ENTER | TYPE_METHOD);
1483 emit_time (logbuffer, now);
1484 emit_method (prof, logbuffer, method);
1485 EXIT_LOG (logbuffer);
1487 process_requests (prof);
1491 method_leave (MonoProfiler *prof, MonoMethod *method)
1494 LogBuffer *logbuffer = ensure_logbuf (
1495 EVENT_SIZE /* event */ +
1496 LEB128_SIZE /* time */ +
1497 LEB128_SIZE /* method */
1499 if (--logbuffer->call_depth > max_call_depth)
1501 now = current_time ();
1502 ENTER_LOG (logbuffer, "leave");
1503 emit_byte (logbuffer, TYPE_LEAVE | TYPE_METHOD);
1504 emit_time (logbuffer, now);
1505 emit_method (prof, logbuffer, method);
1506 EXIT_LOG (logbuffer);
1507 if (logbuffer->next)
1508 safe_send (prof, logbuffer);
1509 process_requests (prof);
1513 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
1516 LogBuffer *logbuffer;
1519 logbuffer = ensure_logbuf (
1520 EVENT_SIZE /* event */ +
1521 LEB128_SIZE /* time */ +
1522 LEB128_SIZE /* method */
1524 if (--logbuffer->call_depth > max_call_depth)
1526 now = current_time ();
1527 ENTER_LOG (logbuffer, "eleave");
1528 emit_byte (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
1529 emit_time (logbuffer, now);
1530 emit_method (prof, logbuffer, method);
1531 EXIT_LOG (logbuffer);
1532 process_requests (prof);
1536 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji, int result)
1538 if (result != MONO_PROFILE_OK)
1541 register_method_local (prof, method, ji);
1543 process_requests (prof);
1547 code_buffer_new (MonoProfiler *prof, void *buffer, int size, MonoProfilerCodeBufferType type, void *data)
1552 LogBuffer *logbuffer;
1553 if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
1555 nlen = strlen (name) + 1;
1560 logbuffer = ensure_logbuf (
1561 EVENT_SIZE /* event */ +
1562 LEB128_SIZE /* time */ +
1563 LEB128_SIZE /* type */ +
1564 LEB128_SIZE /* buffer */ +
1565 LEB128_SIZE /* size */ +
1570 now = current_time ();
1571 ENTER_LOG (logbuffer, "code buffer");
1572 emit_byte (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
1573 emit_time (logbuffer, now);
1574 emit_value (logbuffer, type);
1575 emit_ptr (logbuffer, buffer);
1576 emit_value (logbuffer, size);
1578 memcpy (logbuffer->data, name, nlen);
1579 logbuffer->data += nlen;
1581 EXIT_LOG (logbuffer);
1582 process_requests (prof);
1586 throw_exc (MonoProfiler *prof, MonoObject *object)
1588 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces)? TYPE_EXCEPTION_BT: 0;
1591 LogBuffer *logbuffer;
1594 logbuffer = ensure_logbuf (
1595 EVENT_SIZE /* event */ +
1596 LEB128_SIZE /* time */ +
1597 LEB128_SIZE /* object */ +
1599 LEB128_SIZE /* flags */ +
1600 LEB128_SIZE /* count */ +
1602 LEB128_SIZE /* method */
1606 now = current_time ();
1607 ENTER_LOG (logbuffer, "throw");
1608 emit_byte (logbuffer, do_bt | TYPE_EXCEPTION);
1609 emit_time (logbuffer, now);
1610 emit_obj (logbuffer, object);
1612 emit_bt (prof, logbuffer, &data);
1613 EXIT_LOG (logbuffer);
1614 process_requests (prof);
1618 clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
1621 LogBuffer *logbuffer = ensure_logbuf (
1622 EVENT_SIZE /* event */ +
1623 LEB128_SIZE /* time */ +
1624 LEB128_SIZE /* clause type */ +
1625 LEB128_SIZE /* clause num */ +
1626 LEB128_SIZE /* method */
1628 now = current_time ();
1629 ENTER_LOG (logbuffer, "clause");
1630 emit_byte (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
1631 emit_time (logbuffer, now);
1632 emit_value (logbuffer, clause_type);
1633 emit_value (logbuffer, clause_num);
1634 emit_method (prof, logbuffer, method);
1635 EXIT_LOG (logbuffer);
1637 process_requests (prof);
1641 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
1643 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION)? TYPE_MONITOR_BT: 0;
1646 LogBuffer *logbuffer;
1649 logbuffer = ensure_logbuf (
1650 EVENT_SIZE /* event */ +
1651 LEB128_SIZE /* time */ +
1652 LEB128_SIZE /* object */ +
1654 LEB128_SIZE /* flags */ +
1655 LEB128_SIZE /* count */ +
1657 LEB128_SIZE /* method */
1661 now = current_time ();
1662 ENTER_LOG (logbuffer, "monitor");
1663 emit_byte (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
1664 emit_time (logbuffer, now);
1665 emit_obj (logbuffer, object);
1667 emit_bt (profiler, logbuffer, &data);
1668 EXIT_LOG (logbuffer);
1669 process_requests (profiler);
1673 thread_start (MonoProfiler *prof, uintptr_t tid)
1675 //printf ("thread start %p\n", (void*)tid);
1678 LogBuffer *logbuffer = ensure_logbuf (
1679 EVENT_SIZE /* event */ +
1680 LEB128_SIZE /* time */ +
1681 EVENT_SIZE /* type */ +
1682 LEB128_SIZE /* tid */ +
1683 LEB128_SIZE /* flags */
1685 uint64_t now = current_time ();
1687 ENTER_LOG (logbuffer, "thread-start");
1688 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1689 emit_time (logbuffer, now);
1690 emit_byte (logbuffer, TYPE_THREAD);
1691 emit_ptr (logbuffer, (void*) tid);
1692 emit_value (logbuffer, 0); /* flags */
1693 EXIT_LOG (logbuffer);
1695 if (logbuffer->next)
1696 safe_send (prof, logbuffer);
1698 process_requests (prof);
1702 thread_end (MonoProfiler *prof, uintptr_t tid)
1704 if (TLS_GET (LogBuffer, tlsbuffer)) {
1705 LogBuffer *logbuffer = ensure_logbuf (
1706 EVENT_SIZE /* event */ +
1707 LEB128_SIZE /* time */ +
1708 EVENT_SIZE /* type */ +
1709 LEB128_SIZE /* tid */ +
1710 LEB128_SIZE /* flags */
1712 uint64_t now = current_time ();
1714 ENTER_LOG (logbuffer, "thread-end");
1715 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1716 emit_time (logbuffer, now);
1717 emit_byte (logbuffer, TYPE_THREAD);
1718 emit_ptr (logbuffer, (void*) tid);
1719 emit_value (logbuffer, 0); /* flags */
1720 EXIT_LOG (logbuffer);
1722 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), logbuffer);
1724 /* Don't process requests as the thread is detached from the runtime. */
1727 TLS_SET (tlsbuffer, NULL);
1728 TLS_SET (tlsmethodlist, NULL);
1732 domain_loaded (MonoProfiler *prof, MonoDomain *domain, int result)
1734 if (result != MONO_PROFILE_OK)
1737 LogBuffer *logbuffer = ensure_logbuf (
1738 EVENT_SIZE /* event */ +
1739 LEB128_SIZE /* time */ +
1740 EVENT_SIZE /* type */ +
1741 LEB128_SIZE /* domain id */ +
1742 LEB128_SIZE /* flags */
1744 uint64_t now = current_time ();
1746 ENTER_LOG (logbuffer, "domain-start");
1747 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1748 emit_time (logbuffer, now);
1749 emit_byte (logbuffer, TYPE_DOMAIN);
1750 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1751 emit_value (logbuffer, 0); /* flags */
1752 EXIT_LOG (logbuffer);
1754 if (logbuffer->next)
1755 safe_send (prof, logbuffer);
1757 process_requests (prof);
1761 domain_unloaded (MonoProfiler *prof, MonoDomain *domain)
1763 LogBuffer *logbuffer = ensure_logbuf (
1764 EVENT_SIZE /* event */ +
1765 LEB128_SIZE /* time */ +
1766 EVENT_SIZE /* type */ +
1767 LEB128_SIZE /* domain id */ +
1768 LEB128_SIZE /* flags */
1770 uint64_t now = current_time ();
1772 ENTER_LOG (logbuffer, "domain-end");
1773 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1774 emit_time (logbuffer, now);
1775 emit_byte (logbuffer, TYPE_DOMAIN);
1776 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1777 emit_value (logbuffer, 0); /* flags */
1778 EXIT_LOG (logbuffer);
1780 if (logbuffer->next)
1781 safe_send (prof, logbuffer);
1783 process_requests (prof);
1787 domain_name (MonoProfiler *prof, MonoDomain *domain, const char *name)
1789 int nlen = strlen (name) + 1;
1790 LogBuffer *logbuffer = ensure_logbuf (
1791 EVENT_SIZE /* event */ +
1792 LEB128_SIZE /* time */ +
1793 EVENT_SIZE /* type */ +
1794 LEB128_SIZE /* domain id */ +
1795 LEB128_SIZE /* flags */ +
1798 uint64_t now = current_time ();
1800 ENTER_LOG (logbuffer, "domain-name");
1801 emit_byte (logbuffer, TYPE_METADATA);
1802 emit_time (logbuffer, now);
1803 emit_byte (logbuffer, TYPE_DOMAIN);
1804 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1805 emit_value (logbuffer, 0); /* flags */
1806 memcpy (logbuffer->data, name, nlen);
1807 logbuffer->data += nlen;
1808 EXIT_LOG (logbuffer);
1810 if (logbuffer->next)
1811 safe_send (prof, logbuffer);
1813 process_requests (prof);
1817 context_loaded (MonoProfiler *prof, MonoAppContext *context)
1819 LogBuffer *logbuffer = ensure_logbuf (
1820 EVENT_SIZE /* event */ +
1821 LEB128_SIZE /* time */ +
1822 EVENT_SIZE /* type */ +
1823 LEB128_SIZE /* context id */ +
1824 LEB128_SIZE /* flags */ +
1825 LEB128_SIZE /* domain id */
1827 uint64_t now = current_time ();
1829 ENTER_LOG (logbuffer, "context-start");
1830 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1831 emit_time (logbuffer, now);
1832 emit_byte (logbuffer, TYPE_CONTEXT);
1833 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
1834 emit_value (logbuffer, 0); /* flags */
1835 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
1836 EXIT_LOG (logbuffer);
1838 if (logbuffer->next)
1839 safe_send (prof, logbuffer);
1841 process_requests (prof);
1845 context_unloaded (MonoProfiler *prof, MonoAppContext *context)
1847 LogBuffer *logbuffer = ensure_logbuf (
1848 EVENT_SIZE /* event */ +
1849 LEB128_SIZE /* time */ +
1850 EVENT_SIZE /* type */ +
1851 LEB128_SIZE /* context id */ +
1852 LEB128_SIZE /* flags */ +
1853 LEB128_SIZE /* domain id */
1855 uint64_t now = current_time ();
1857 ENTER_LOG (logbuffer, "context-end");
1858 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1859 emit_time (logbuffer, now);
1860 emit_byte (logbuffer, TYPE_CONTEXT);
1861 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
1862 emit_value (logbuffer, 0); /* flags */
1863 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
1864 EXIT_LOG (logbuffer);
1866 if (logbuffer->next)
1867 safe_send (prof, logbuffer);
1869 process_requests (prof);
1873 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
1875 int len = strlen (name) + 1;
1877 LogBuffer *logbuffer;
1878 logbuffer = ensure_logbuf (
1879 EVENT_SIZE /* event */ +
1880 LEB128_SIZE /* time */ +
1881 EVENT_SIZE /* type */ +
1882 LEB128_SIZE /* tid */ +
1883 LEB128_SIZE /* flags */ +
1886 now = current_time ();
1887 ENTER_LOG (logbuffer, "tname");
1888 emit_byte (logbuffer, TYPE_METADATA);
1889 emit_time (logbuffer, now);
1890 emit_byte (logbuffer, TYPE_THREAD);
1891 emit_ptr (logbuffer, (void*)tid);
1892 emit_value (logbuffer, 0); /* flags */
1893 memcpy (logbuffer->data, name, len);
1894 logbuffer->data += len;
1895 EXIT_LOG (logbuffer);
1897 if (logbuffer->next)
1898 safe_send (prof, logbuffer);
1900 process_requests (prof);
1912 AsyncFrameInfo *data;
1916 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
1918 AsyncFrameData *frame = data;
1919 if (frame->count < num_frames) {
1920 frame->data [frame->count].method = method;
1921 frame->data [frame->count].domain = domain;
1922 frame->data [frame->count].base_address = base_address;
1923 frame->data [frame->count].offset = offset;
1924 // printf ("In %d at %p (dom %p) (native: %p)\n", frame->count, method, domain, base_address);
1927 return frame->count == num_frames;
1931 (type | frame count), tid, time, ip, [method, domain, base address, offset] * frames
1933 #define SAMPLE_EVENT_SIZE_IN_SLOTS(FRAMES) (4 + (FRAMES) * 4)
1936 mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
1939 AsyncFrameInfo frames [num_frames];
1940 AsyncFrameData bt_data = { 0, &frames [0]};
1942 uintptr_t *data, *new_data, *old_data;
1948 now = current_time ();
1950 mono_stack_walk_async_safe (&async_walk_stack, context, &bt_data);
1952 elapsed = (now - profiler->startup_time) / 10000;
1956 snprintf (buf, sizeof (buf), "hit at %p in thread %p after %llu ms\n", ip, (void*)thread_id (), (unsigned long long int)elapsed/100);
1958 ign_res (write (2, buf, len));
1960 sbuf = profiler->stat_buffers;
1963 /* flush the buffer at 1 second intervals */
1964 if (sbuf->data > sbuf->buf && (elapsed - sbuf->buf [2]) > 100000) {
1967 /* overflow: 400 slots is a big enough number to reduce the chance of losing this event if many
1968 * threads hit this same spot at the same time
1970 if (timedout || (sbuf->data + 400 >= sbuf->data_end)) {
1971 StatBuffer *oldsb, *foundsb;
1972 sbuf = create_stat_buffer ();
1974 oldsb = profiler->stat_buffers;
1976 foundsb = InterlockedCompareExchangePointer ((void * volatile*)&profiler->stat_buffers, sbuf, oldsb);
1977 } while (foundsb != oldsb);
1979 ign_res (write (2, "overflow\n", 9));
1980 /* notify the helper thread */
1981 if (sbuf->next->next) {
1983 ign_res (write (profiler->pipes [1], &c, 1));
1985 ign_res (write (2, "notify\n", 7));
1989 old_data = sbuf->data;
1990 new_data = old_data + SAMPLE_EVENT_SIZE_IN_SLOTS (bt_data.count);
1991 data = InterlockedCompareExchangePointer ((void * volatile*)&sbuf->data, new_data, old_data);
1992 } while (data != old_data);
1993 if (old_data >= sbuf->data_end)
1994 return; /* lost event */
1995 old_data [0] = 1 | (sample_type << 16) | (bt_data.count << 8);
1996 old_data [1] = thread_id ();
1997 old_data [2] = elapsed;
1998 old_data [3] = (uintptr_t)ip;
1999 for (i = 0; i < bt_data.count; ++i) {
2000 old_data [4 + 4 * i + 0] = (uintptr_t)frames [i].method;
2001 old_data [4 + 4 * i + 1] = (uintptr_t)frames [i].domain;
2002 old_data [4 + 4 * i + 2] = (uintptr_t)frames [i].base_address;
2003 old_data [4 + 4 * i + 3] = (uintptr_t)frames [i].offset;
2007 static uintptr_t *code_pages = 0;
2008 static int num_code_pages = 0;
2009 static int size_code_pages = 0;
2010 #define CPAGE_SHIFT (9)
2011 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
2012 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
2013 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
2016 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
2019 uintptr_t start_pos;
2020 start_pos = (page >> CPAGE_SHIFT) % hsize;
2023 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
2025 } else if (!hash [i]) {
2032 } while (i != start_pos);
2033 /* should not happen */
2034 printf ("failed code page store\n");
2039 add_code_pointer (uintptr_t ip)
2042 if (num_code_pages * 2 >= size_code_pages) {
2044 uintptr_t old_size = size_code_pages;
2045 size_code_pages *= 2;
2046 if (size_code_pages == 0)
2047 size_code_pages = 16;
2048 n = calloc (sizeof (uintptr_t) * size_code_pages, 1);
2049 for (i = 0; i < old_size; ++i) {
2051 add_code_page (n, size_code_pages, code_pages [i]);
2057 num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
2060 /* ELF code crashes on some systems. */
2061 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2064 dump_ubin (const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
2067 LogBuffer *logbuffer;
2069 len = strlen (filename) + 1;
2070 now = current_time ();
2071 logbuffer = ensure_logbuf (
2072 EVENT_SIZE /* event */ +
2073 LEB128_SIZE /* time */ +
2074 LEB128_SIZE /* load address */ +
2075 LEB128_SIZE /* offset */ +
2076 LEB128_SIZE /* size */ +
2077 nlen /* file name */
2079 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
2080 emit_time (logbuffer, now);
2081 emit_svalue (logbuffer, load_addr);
2082 emit_uvalue (logbuffer, offset);
2083 emit_uvalue (logbuffer, size);
2084 memcpy (logbuffer->data, filename, len);
2085 logbuffer->data += len;
2090 dump_usym (const char *name, uintptr_t value, uintptr_t size)
2092 LogBuffer *logbuffer;
2094 len = strlen (name) + 1;
2095 logbuffer = ensure_logbuf (
2096 EVENT_SIZE /* event */ +
2097 LEB128_SIZE /* value */ +
2098 LEB128_SIZE /* size */ +
2101 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
2102 emit_ptr (logbuffer, (void*)value);
2103 emit_value (logbuffer, size);
2104 memcpy (logbuffer->data, name, len);
2105 logbuffer->data += len;
2108 /* ELF code crashes on some systems. */
2109 //#if defined(ELFMAG0)
2112 #if SIZEOF_VOID_P == 4
2113 #define ELF_WSIZE 32
2115 #define ELF_WSIZE 64
2118 #define ElfW(type) _ElfW (Elf, ELF_WSIZE, type)
2119 #define _ElfW(e,w,t) _ElfW_1 (e, w, _##t)
2120 #define _ElfW_1(e,w,t) e##w##t
2124 dump_elf_symbols (ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
2127 for (i = 0; i < num_symbols; ++i) {
2129 sym = strtab + symbols [i].st_name;
2130 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
2132 //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
2133 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
2138 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
2145 ElfW(Shdr) *sheader;
2146 ElfW(Shdr) *shstrtabh;
2147 ElfW(Shdr) *symtabh = NULL;
2148 ElfW(Shdr) *strtabh = NULL;
2149 ElfW(Sym) *symbols = NULL;
2153 fd = open (filename, O_RDONLY);
2156 if (fstat (fd, &statb) != 0) {
2160 file_size = statb.st_size;
2161 data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
2163 if (data == MAP_FAILED)
2166 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2167 header->e_ident [EI_MAG1] != ELFMAG1 ||
2168 header->e_ident [EI_MAG2] != ELFMAG2 ||
2169 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2170 munmap (data, file_size);
2173 sheader = (void*)((char*)data + header->e_shoff);
2174 shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
2175 strtab = (const char*)data + shstrtabh->sh_offset;
2176 for (i = 0; i < header->e_shnum; ++i) {
2177 //printf ("section header: %d\n", sheader->sh_type);
2178 if (sheader->sh_type == SHT_SYMTAB) {
2180 strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
2181 /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
2184 sheader = (void*)((char*)sheader + header->e_shentsize);
2186 if (!symtabh || !strtabh) {
2187 munmap (data, file_size);
2190 strtab = (const char*)data + strtabh->sh_offset;
2191 num_symbols = symtabh->sh_size / symtabh->sh_entsize;
2192 symbols = (void*)((char*)data + symtabh->sh_offset);
2193 dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
2194 munmap (data, file_size);
2199 /* ELF code crashes on some systems. */
2200 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2203 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
2205 MonoProfiler *prof = data;
2207 const char *filename;
2209 char *a = (void*)info->dlpi_addr;
2211 ElfW(Dyn) *dyn = NULL;
2212 ElfW(Sym) *symtab = NULL;
2213 ElfW(Word) *hash_table = NULL;
2214 ElfW(Ehdr) *header = NULL;
2215 const char* strtab = NULL;
2216 for (obj = prof->binary_objects; obj; obj = obj->next) {
2220 filename = info->dlpi_name;
2223 if (!info->dlpi_addr && !filename [0]) {
2224 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
2230 obj = calloc (sizeof (BinaryObject), 1);
2231 obj->addr = (void*)info->dlpi_addr;
2232 obj->name = pstrdup (filename);
2233 obj->next = prof->binary_objects;
2234 prof->binary_objects = obj;
2235 //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
2237 for (i = 0; i < info->dlpi_phnum; ++i) {
2238 //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);
2239 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
2240 header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2241 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2242 header->e_ident [EI_MAG1] != ELFMAG1 ||
2243 header->e_ident [EI_MAG2] != ELFMAG2 ||
2244 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2247 dump_ubin (filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
2248 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
2249 dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2252 if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
2254 if (!info->dlpi_name || !info->dlpi_name[0])
2258 for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
2259 if (dyn [i].d_tag == DT_SYMTAB) {
2260 if (symtab && do_debug)
2261 printf ("multiple symtabs: %d\n", i);
2262 symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
2263 } else if (dyn [i].d_tag == DT_HASH) {
2264 hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
2265 } else if (dyn [i].d_tag == DT_STRTAB) {
2266 strtab = (const char*)(a + dyn [i].d_un.d_ptr);
2271 num_sym = hash_table [1];
2272 dump_elf_symbols (symtab, num_sym, strtab, (void*)info->dlpi_addr);
2277 load_binaries (MonoProfiler *prof)
2279 dl_iterate_phdr (elf_dl_callback, prof);
2284 load_binaries (MonoProfiler *prof)
2291 symbol_for (uintptr_t code)
2294 void *ip = (void*)code;
2296 if (dladdr (ip, &di)) {
2298 return di.dli_sname;
2301 names = backtrace_symbols (&ip, 1);
2303 const char* p = names [0];
2314 dump_unmanaged_coderefs (MonoProfiler *prof)
2317 const char* last_symbol;
2318 uintptr_t addr, page_end;
2320 if (load_binaries (prof))
2322 for (i = 0; i < size_code_pages; ++i) {
2324 if (!code_pages [i] || code_pages [i] & 1)
2327 addr = CPAGE_ADDR (code_pages [i]);
2328 page_end = addr + CPAGE_SIZE;
2329 code_pages [i] |= 1;
2330 /* we dump the symbols for the whole page */
2331 for (; addr < page_end; addr += 16) {
2332 sym = symbol_for (addr);
2333 if (sym && sym == last_symbol)
2338 dump_usym (sym, addr, 0); /* let's not guess the size */
2339 //printf ("found symbol at %p: %s\n", (void*)addr, sym);
2345 compare_sample_events (gconstpointer a, gconstpointer b)
2347 uintptr_t tid1 = (*(uintptr_t **) a) [1];
2348 uintptr_t tid2 = (*(uintptr_t **) b) [1];
2350 return tid1 > tid2 ? 1 :
2356 dump_sample_hits (MonoProfiler *prof, StatBuffer *sbuf)
2358 LogBuffer *logbuffer;
2362 dump_sample_hits (prof, sbuf->next);
2363 free_buffer (sbuf->next, sbuf->next->size);
2367 g_ptr_array_set_size (prof->sorted_sample_events, 0);
2369 for (uintptr_t *sample = sbuf->buf; sample < sbuf->data;) {
2370 int count = sample [0] & 0xff;
2371 int mbt_count = (sample [0] & 0xff00) >> 8;
2373 if (sample + SAMPLE_EVENT_SIZE_IN_SLOTS (mbt_count) > sbuf->data)
2376 g_ptr_array_add (prof->sorted_sample_events, sample);
2378 sample += count + 3 + 4 * mbt_count;
2381 g_ptr_array_sort (prof->sorted_sample_events, compare_sample_events);
2383 for (guint sidx = 0; sidx < prof->sorted_sample_events->len; sidx++) {
2384 uintptr_t *sample = g_ptr_array_index (prof->sorted_sample_events, sidx);
2385 int count = sample [0] & 0xff;
2386 int mbt_count = (sample [0] & 0xff00) >> 8;
2387 int type = sample [0] >> 16;
2388 uintptr_t *managed_sample_base = sample + count + 3;
2389 uintptr_t thread_id = sample [1];
2391 for (int i = 0; i < mbt_count; ++i) {
2392 MonoMethod *method = (MonoMethod*)managed_sample_base [i * 4 + 0];
2393 MonoDomain *domain = (MonoDomain*)managed_sample_base [i * 4 + 1];
2394 void *address = (void*)managed_sample_base [i * 4 + 2];
2397 MonoJitInfo *ji = mono_jit_info_table_find (domain, address);
2400 managed_sample_base [i * 4 + 0] = (uintptr_t)mono_jit_info_get_method (ji);
2404 logbuffer = ensure_logbuf (
2405 EVENT_SIZE /* event */ +
2406 LEB128_SIZE /* type */ +
2407 LEB128_SIZE /* time */ +
2408 LEB128_SIZE /* tid */ +
2409 LEB128_SIZE /* count */ +
2411 LEB128_SIZE /* ip */
2413 LEB128_SIZE /* managed count */ +
2415 LEB128_SIZE /* method */ +
2416 LEB128_SIZE /* il offset */ +
2417 LEB128_SIZE /* native offset */
2420 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
2421 emit_value (logbuffer, type);
2422 emit_uvalue (logbuffer, prof->startup_time + (uint64_t)sample [2] * (uint64_t)10000);
2423 emit_ptr (logbuffer, (void *) thread_id);
2424 emit_value (logbuffer, count);
2425 for (int i = 0; i < count; ++i) {
2426 emit_ptr (logbuffer, (void*)sample [i + 3]);
2427 add_code_pointer (sample [i + 3]);
2430 sample += count + 3;
2431 /* new in data version 6 */
2432 emit_uvalue (logbuffer, mbt_count);
2433 for (int i = 0; i < mbt_count; ++i) {
2434 MonoMethod *method = (MonoMethod *) sample [i * 4 + 0];
2435 uintptr_t native_offset = sample [i * 4 + 3];
2437 emit_method (prof, logbuffer, method);
2438 emit_svalue (logbuffer, 0); /* il offset will always be 0 from now on */
2439 emit_svalue (logbuffer, native_offset);
2443 dump_unmanaged_coderefs (prof);
2449 mono_cpu_count (void)
2452 #ifdef PLATFORM_ANDROID
2453 /* Android tries really hard to save power by powering off CPUs on SMP phones which
2454 * means the normal way to query cpu count returns a wrong value with userspace API.
2455 * Instead we use /sys entries to query the actual hardware CPU count.
2457 char buffer[8] = {'\0'};
2458 int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
2459 /* Format of the /sys entry is a cpulist of indexes which in the case
2460 * of present is always of the form "0-(n-1)" when there is more than
2461 * 1 core, n being the number of CPU cores in the system. Otherwise
2462 * the value is simply 0
2464 if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
2465 count = strtol (((char*)buffer) + 2, NULL, 10);
2471 #ifdef _SC_NPROCESSORS_ONLN
2472 count = sysconf (_SC_NPROCESSORS_ONLN);
2479 size_t len = sizeof (int);
2482 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
2489 GetSystemInfo (&info);
2490 return info.dwNumberOfProcessors;
2499 unsigned int prev_pos;
2501 struct perf_event_mmap_page *page_desc;
2504 static PerfData *perf_data = NULL;
2505 static int num_perf;
2506 #define PERF_PAGES_SHIFT 4
2507 static int num_pages = 1 << PERF_PAGES_SHIFT;
2508 static unsigned int mmap_mask;
2511 struct perf_event_header h;
2521 perf_event_syscall (struct perf_event_attr *attr, pid_t pid, int cpu, int group_fd, unsigned long flags)
2523 attr->size = PERF_ATTR_SIZE_VER0;
2524 //printf ("perf attr size: %d\n", attr->size);
2525 #if defined(__x86_64__)
2526 return syscall(/*__NR_perf_event_open*/ 298, attr, pid, cpu, group_fd, flags);
2527 #elif defined(__i386__)
2528 return syscall(/*__NR_perf_event_open*/ 336, attr, pid, cpu, group_fd, flags);
2529 #elif defined(__arm__) || defined (__aarch64__)
2530 return syscall(/*__NR_perf_event_open*/ 364, attr, pid, cpu, group_fd, flags);
2537 setup_perf_map (PerfData *perf)
2539 perf->mmap_base = mmap (NULL, (num_pages + 1) * getpagesize (), PROT_READ|PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
2540 if (perf->mmap_base == MAP_FAILED) {
2542 printf ("failed mmap\n");
2545 perf->page_desc = perf->mmap_base;
2547 printf ("mmap version: %d\n", perf->page_desc->version);
2552 dump_perf_hits (MonoProfiler *prof, void *buf, int size)
2554 LogBuffer *logbuffer;
2557 void *end = (char*)buf + size;
2559 int pid = getpid ();
2565 if (pid != s->pid) {
2567 printf ("event for different pid: %d\n", s->pid);
2568 buf = (char*)buf + s->h.size;
2571 /*ip = (void*)s->ip;
2572 printf ("sample: %d, size: %d, ip: %p (%s), timestamp: %llu, nframes: %llu\n",
2573 s->h.type, s->h.size, ip, symbol_for (ip), s->timestamp, s->nframes);*/
2574 logbuffer = ensure_logbuf (
2575 EVENT_SIZE /* event */ +
2576 LEB128_SIZE /* type */ +
2577 LEB128_SIZE /* time */ +
2578 LEB128_SIZE /* tid */ +
2579 LEB128_SIZE /* count */ +
2581 LEB128_SIZE /* ip */
2583 LEB128_SIZE /* managed count */ +
2585 LEB128_SIZE /* method */ +
2586 LEB128_SIZE /* il offset */ +
2587 LEB128_SIZE /* native offset */
2590 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
2591 emit_value (logbuffer, sample_type);
2592 emit_uvalue (logbuffer, s->timestamp - prof->startup_time);
2594 * No useful thread ID to write here, since throughout the
2595 * profiler we use pthread_self () but the ID we get from
2596 * perf is the kernel's thread ID.
2598 emit_ptr (logbuffer, 0);
2599 emit_value (logbuffer, count);
2600 emit_ptr (logbuffer, (void*)(uintptr_t)s->ip);
2601 add_code_pointer (s->ip);
2602 /* no support here yet for the managed backtrace */
2603 emit_uvalue (logbuffer, mbt_count);
2604 buf = (char*)buf + s->h.size;
2608 printf ("dumped %d samples\n", samples);
2609 dump_unmanaged_coderefs (prof);
2612 /* read events from the ring buffer */
2614 read_perf_mmap (MonoProfiler* prof, int cpu)
2616 PerfData *perf = perf_data + cpu;
2618 unsigned char *data = (unsigned char*)perf->mmap_base + getpagesize ();
2619 unsigned int head = perf->page_desc->data_head;
2623 mono_memory_read_barrier ();
2625 old = perf->prev_pos;
2629 printf ("lost mmap events: old: %d, head: %d\n", old, head);
2633 if ((old & mmap_mask) + size != (head & mmap_mask)) {
2634 buf = data + (old & mmap_mask);
2635 size = mmap_mask + 1 - (old & mmap_mask);
2637 /* size bytes at buf */
2639 printf ("found1 bytes of events: %d\n", size);
2640 dump_perf_hits (prof, buf, size);
2642 buf = data + (old & mmap_mask);
2644 /* size bytes at buf */
2646 printf ("found bytes of events: %d\n", size);
2647 dump_perf_hits (prof, buf, size);
2649 perf->prev_pos = old;
2650 perf->page_desc->data_tail = old;
2655 setup_perf_event_for_cpu (PerfData *perf, int cpu)
2657 struct perf_event_attr attr;
2658 memset (&attr, 0, sizeof (attr));
2659 attr.type = PERF_TYPE_HARDWARE;
2660 switch (sample_type) {
2661 case SAMPLE_CYCLES: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2662 case SAMPLE_INSTRUCTIONS: attr.config = PERF_COUNT_HW_INSTRUCTIONS; break;
2663 case SAMPLE_CACHE_MISSES: attr.config = PERF_COUNT_HW_CACHE_MISSES; break;
2664 case SAMPLE_CACHE_REFS: attr.config = PERF_COUNT_HW_CACHE_REFERENCES; break;
2665 case SAMPLE_BRANCHES: attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS; break;
2666 case SAMPLE_BRANCH_MISSES: attr.config = PERF_COUNT_HW_BRANCH_MISSES; break;
2667 default: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2669 attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD | PERF_SAMPLE_TIME;
2670 // attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
2671 attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING | PERF_FORMAT_ID;
2674 attr.sample_freq = sample_freq;
2676 perf->perf_fd = perf_event_syscall (&attr, getpid (), cpu, -1, 0);
2678 printf ("perf fd: %d, freq: %d, event: %llu\n", perf->perf_fd, sample_freq, attr.config);
2679 if (perf->perf_fd < 0) {
2680 if (perf->perf_fd == -EPERM) {
2681 fprintf (stderr, "Perf syscall denied, do \"echo 1 > /proc/sys/kernel/perf_event_paranoid\" as root to enable.\n");
2684 perror ("open perf event");
2688 if (!setup_perf_map (perf)) {
2689 close (perf->perf_fd);
2697 setup_perf_event (void)
2700 mmap_mask = num_pages * getpagesize () - 1;
2701 num_perf = mono_cpu_count ();
2702 perf_data = calloc (num_perf, sizeof (PerfData));
2703 for (i = 0; i < num_perf; ++i) {
2704 count += setup_perf_event_for_cpu (perf_data + i, i);
2713 #endif /* USE_PERF_EVENTS */
2715 #ifndef DISABLE_HELPER_THREAD
2717 typedef struct MonoCounterAgent {
2718 MonoCounter *counter;
2719 // MonoCounterAgent specific data :
2724 struct MonoCounterAgent *next;
2727 static MonoCounterAgent* counters;
2728 static gboolean counters_initialized = FALSE;
2729 static int counters_index = 1;
2730 static mono_mutex_t counters_mutex;
2733 counters_add_agent (MonoCounter *counter)
2735 MonoCounterAgent *agent, *item;
2737 if (!counters_initialized)
2740 mono_mutex_lock (&counters_mutex);
2742 for (agent = counters; agent; agent = agent->next) {
2743 if (agent->counter == counter) {
2744 agent->value_size = 0;
2746 free (agent->value);
2747 agent->value = NULL;
2749 mono_mutex_unlock (&counters_mutex);
2754 agent = malloc (sizeof (MonoCounterAgent));
2755 agent->counter = counter;
2756 agent->value = NULL;
2757 agent->value_size = 0;
2758 agent->index = counters_index++;
2771 mono_mutex_unlock (&counters_mutex);
2775 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
2777 counters_add_agent (counter);
2782 counters_init (MonoProfiler *profiler)
2784 assert (!counters_initialized);
2786 mono_mutex_init (&counters_mutex);
2788 counters_initialized = TRUE;
2790 mono_counters_on_register (&counters_add_agent);
2791 mono_counters_foreach (counters_init_foreach_callback, NULL);
2795 counters_emit (MonoProfiler *profiler)
2797 MonoCounterAgent *agent;
2798 LogBuffer *logbuffer;
2801 EVENT_SIZE /* event */ +
2802 LEB128_SIZE /* len */
2805 if (!counters_initialized)
2808 mono_mutex_lock (&counters_mutex);
2810 for (agent = counters; agent; agent = agent->next) {
2815 LEB128_SIZE /* section */ +
2816 strlen (mono_counter_get_name (agent->counter)) + 1 /* name */ +
2817 LEB128_SIZE /* type */ +
2818 LEB128_SIZE /* unit */ +
2819 LEB128_SIZE /* variance */ +
2820 LEB128_SIZE /* index */
2827 mono_mutex_unlock (&counters_mutex);
2831 logbuffer = ensure_logbuf (size);
2833 ENTER_LOG (logbuffer, "counters");
2834 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2835 emit_value (logbuffer, len);
2836 for (agent = counters; agent; agent = agent->next) {
2842 name = mono_counter_get_name (agent->counter);
2843 emit_value (logbuffer, mono_counter_get_section (agent->counter));
2844 emit_string (logbuffer, name, strlen (name) + 1);
2845 emit_value (logbuffer, mono_counter_get_type (agent->counter));
2846 emit_value (logbuffer, mono_counter_get_unit (agent->counter));
2847 emit_value (logbuffer, mono_counter_get_variance (agent->counter));
2848 emit_value (logbuffer, agent->index);
2852 EXIT_LOG (logbuffer);
2854 safe_send (profiler, logbuffer);
2856 mono_mutex_unlock (&counters_mutex);
2860 counters_sample (MonoProfiler *profiler, uint64_t timestamp)
2862 MonoCounterAgent *agent;
2863 MonoCounter *counter;
2864 LogBuffer *logbuffer;
2870 if (!counters_initialized)
2873 counters_emit (profiler);
2876 buffer = calloc (1, buffer_size);
2878 mono_mutex_lock (&counters_mutex);
2881 EVENT_SIZE /* event */ +
2882 LEB128_SIZE /* time */
2885 for (agent = counters; agent; agent = agent->next) {
2887 LEB128_SIZE /* index */ +
2888 LEB128_SIZE /* type */ +
2889 mono_counter_get_size (agent->counter) /* value */
2894 LEB128_SIZE /* stop marker */
2897 logbuffer = ensure_logbuf (size);
2899 ENTER_LOG (logbuffer, "counters");
2900 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
2901 emit_uvalue (logbuffer, timestamp);
2902 for (agent = counters; agent; agent = agent->next) {
2905 counter = agent->counter;
2907 size = mono_counter_get_size (counter);
2909 continue; // FIXME error
2910 } else if (size > buffer_size) {
2912 buffer = realloc (buffer, buffer_size);
2915 memset (buffer, 0, buffer_size);
2917 if (mono_counters_sample (counter, buffer, size) < 0)
2918 continue; // FIXME error
2920 type = mono_counter_get_type (counter);
2922 if (!agent->value) {
2923 agent->value = calloc (1, size);
2924 agent->value_size = size;
2926 if (type == MONO_COUNTER_STRING) {
2927 if (strcmp (agent->value, buffer) == 0)
2930 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
2935 emit_uvalue (logbuffer, agent->index);
2936 emit_uvalue (logbuffer, type);
2938 case MONO_COUNTER_INT:
2939 #if SIZEOF_VOID_P == 4
2940 case MONO_COUNTER_WORD:
2942 emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
2944 case MONO_COUNTER_UINT:
2945 emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
2947 case MONO_COUNTER_TIME_INTERVAL:
2948 case MONO_COUNTER_LONG:
2949 #if SIZEOF_VOID_P == 8
2950 case MONO_COUNTER_WORD:
2952 emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
2954 case MONO_COUNTER_ULONG:
2955 emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
2957 case MONO_COUNTER_DOUBLE:
2958 emit_double (logbuffer, *(double*)buffer);
2960 case MONO_COUNTER_STRING:
2962 emit_byte (logbuffer, 0);
2964 emit_byte (logbuffer, 1);
2965 emit_string (logbuffer, (char*)buffer, size);
2972 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
2973 agent->value = realloc (agent->value, size);
2974 agent->value_size = size;
2978 memcpy (agent->value, buffer, size);
2982 emit_value (logbuffer, 0);
2983 EXIT_LOG (logbuffer);
2985 safe_send (profiler, logbuffer);
2987 mono_mutex_unlock (&counters_mutex);
2990 typedef struct _PerfCounterAgent PerfCounterAgent;
2991 struct _PerfCounterAgent {
2992 PerfCounterAgent *next;
2994 char *category_name;
3003 static PerfCounterAgent *perfcounters = NULL;
3006 perfcounters_emit (MonoProfiler *profiler)
3008 PerfCounterAgent *pcagent;
3009 LogBuffer *logbuffer;
3012 EVENT_SIZE /* event */ +
3013 LEB128_SIZE /* len */
3016 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3017 if (pcagent->emitted)
3021 LEB128_SIZE /* section */ +
3022 strlen (pcagent->category_name) + 1 /* category name */ +
3023 strlen (pcagent->name) + 1 /* name */ +
3024 LEB128_SIZE /* type */ +
3025 LEB128_SIZE /* unit */ +
3026 LEB128_SIZE /* variance */ +
3027 LEB128_SIZE /* index */
3036 logbuffer = ensure_logbuf (size);
3038 ENTER_LOG (logbuffer, "perfcounters");
3039 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
3040 emit_value (logbuffer, len);
3041 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3042 if (pcagent->emitted)
3045 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
3046 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
3047 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
3048 emit_value (logbuffer, MONO_COUNTER_LONG);
3049 emit_value (logbuffer, MONO_COUNTER_RAW);
3050 emit_value (logbuffer, MONO_COUNTER_VARIABLE);
3051 emit_value (logbuffer, pcagent->index);
3053 pcagent->emitted = 1;
3055 EXIT_LOG (logbuffer);
3057 safe_send (profiler, logbuffer);
3061 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
3063 PerfCounterAgent *pcagent;
3065 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3066 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
3068 if (pcagent->value == value)
3071 pcagent->value = value;
3072 pcagent->updated = 1;
3073 pcagent->deleted = 0;
3077 pcagent = g_new0 (PerfCounterAgent, 1);
3078 pcagent->next = perfcounters;
3079 pcagent->index = counters_index++;
3080 pcagent->category_name = g_strdup (category_name);
3081 pcagent->name = g_strdup (name);
3082 pcagent->type = (int) type;
3083 pcagent->value = value;
3084 pcagent->emitted = 0;
3085 pcagent->updated = 1;
3086 pcagent->deleted = 0;
3088 perfcounters = pcagent;
3094 perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp)
3096 PerfCounterAgent *pcagent;
3097 LogBuffer *logbuffer;
3100 if (!counters_initialized)
3103 mono_mutex_lock (&counters_mutex);
3105 /* mark all perfcounters as deleted, foreach will unmark them as necessary */
3106 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
3107 pcagent->deleted = 1;
3109 mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
3111 perfcounters_emit (profiler);
3114 EVENT_SIZE /* event */ +
3115 LEB128_SIZE /* time */
3118 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3119 if (pcagent->deleted || !pcagent->updated)
3123 LEB128_SIZE /* index */ +
3124 LEB128_SIZE /* type */ +
3125 LEB128_SIZE /* value */
3130 LEB128_SIZE /* stop marker */
3133 logbuffer = ensure_logbuf (size);
3135 ENTER_LOG (logbuffer, "perfcounters");
3136 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
3137 emit_uvalue (logbuffer, timestamp);
3138 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3139 if (pcagent->deleted || !pcagent->updated)
3141 emit_uvalue (logbuffer, pcagent->index);
3142 emit_uvalue (logbuffer, MONO_COUNTER_LONG);
3143 emit_svalue (logbuffer, pcagent->value);
3145 pcagent->updated = 0;
3148 emit_value (logbuffer, 0);
3149 EXIT_LOG (logbuffer);
3151 safe_send (profiler, logbuffer);
3153 mono_mutex_unlock (&counters_mutex);
3157 counters_and_perfcounters_sample (MonoProfiler *prof)
3159 static uint64_t start = -1;
3163 start = current_time ();
3165 now = current_time ();
3166 counters_sample (prof, (now - start) / 1000/ 1000);
3167 perfcounters_sample (prof, (now - start) / 1000/ 1000);
3170 #define COVERAGE_DEBUG(x) if (debug_coverage) {x}
3171 static MonoConcurrentHashTable *coverage_methods = NULL;
3172 static mono_mutex_t coverage_methods_mutex;
3173 static MonoConcurrentHashTable *coverage_assemblies = NULL;
3174 static mono_mutex_t coverage_assemblies_mutex;
3175 static MonoConcurrentHashTable *coverage_classes = NULL;
3176 static mono_mutex_t coverage_classes_mutex;
3177 static MonoConcurrentHashTable *filtered_classes = NULL;
3178 static mono_mutex_t filtered_classes_mutex;
3179 static MonoConcurrentHashTable *entered_methods = NULL;
3180 static mono_mutex_t entered_methods_mutex;
3181 static MonoConcurrentHashTable *image_to_methods = NULL;
3182 static mono_mutex_t image_to_methods_mutex;
3183 static MonoConcurrentHashTable *suppressed_assemblies = NULL;
3184 static mono_mutex_t suppressed_assemblies_mutex;
3185 static gboolean coverage_initialized = FALSE;
3187 static GPtrArray *coverage_data = NULL;
3188 static int previous_offset = 0;
3190 typedef struct _MethodNode MethodNode;
3191 struct _MethodNode {
3192 MonoLockFreeQueueNode node;
3196 typedef struct _CoverageEntry CoverageEntry;
3197 struct _CoverageEntry {
3206 free_coverage_entry (gpointer data, gpointer userdata)
3208 CoverageEntry *entry = (CoverageEntry *)data;
3209 g_free (entry->filename);
3214 obtain_coverage_for_method (MonoProfiler *prof, const MonoProfileCoverageEntry *entry)
3216 int offset = entry->iloffset - previous_offset;
3217 CoverageEntry *e = g_new (CoverageEntry, 1);
3219 previous_offset = entry->iloffset;
3222 e->counter = entry->counter;
3223 e->filename = g_strdup(entry->filename ? entry->filename : "");
3224 e->line = entry->line;
3225 e->column = entry->col;
3227 g_ptr_array_add (coverage_data, e);
3231 parse_generic_type_names(char *name)
3233 char *new_name, *ret;
3234 int within_generic_declaration = 0, generic_members = 1;
3236 if (name == NULL || *name == '\0')
3237 return g_strdup ("");
3239 if (!(ret = new_name = calloc (strlen (name) * 4 + 1, sizeof (char))))
3245 within_generic_declaration = 1;
3249 within_generic_declaration = 0;
3251 if (*(name - 1) != '<') {
3253 *new_name++ = '0' + generic_members;
3255 memcpy (new_name, "<>", 8);
3259 generic_members = 0;
3267 if (!within_generic_declaration)
3268 *new_name++ = *name;
3277 static int method_id;
3279 build_method_buffer (gpointer key, gpointer value, gpointer userdata)
3281 MonoMethod *method = (MonoMethod *)value;
3282 MonoProfiler *prof = (MonoProfiler *)userdata;
3286 const char *image_name, *method_name, *sig, *first_filename;
3287 LogBuffer *logbuffer;
3290 previous_offset = 0;
3291 coverage_data = g_ptr_array_new ();
3293 mono_profiler_coverage_get (prof, method, obtain_coverage_for_method);
3295 klass = mono_method_get_class (method);
3296 image = mono_class_get_image (klass);
3297 image_name = mono_image_get_name (image);
3299 sig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3300 class_name = parse_generic_type_names (mono_type_get_name (mono_class_get_type (klass)));
3301 method_name = mono_method_get_name (method);
3303 if (coverage_data->len != 0) {
3304 CoverageEntry *entry = coverage_data->pdata[0];
3305 first_filename = entry->filename ? entry->filename : "";
3307 first_filename = "";
3309 image_name = image_name ? image_name : "";
3310 sig = sig ? sig : "";
3311 method_name = method_name ? method_name : "";
3313 logbuffer = ensure_logbuf (
3314 EVENT_SIZE /* event */ +
3315 strlen (image_name) + 1 /* image name */ +
3316 strlen (class_name) + 1 /* class name */ +
3317 strlen (method_name) + 1 /* method name */ +
3318 strlen (sig) + 1 /* signature */ +
3319 strlen (first_filename) + 1 /* first file name */ +
3320 LEB128_SIZE /* token */ +
3321 LEB128_SIZE /* method id */ +
3322 LEB128_SIZE /* entries */
3324 ENTER_LOG (logbuffer, "coverage-methods");
3326 emit_byte (logbuffer, TYPE_COVERAGE_METHOD | TYPE_COVERAGE);
3327 emit_string (logbuffer, image_name, strlen (image_name) + 1);
3328 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3329 emit_string (logbuffer, method_name, strlen (method_name) + 1);
3330 emit_string (logbuffer, sig, strlen (sig) + 1);
3331 emit_string (logbuffer, first_filename, strlen (first_filename) + 1);
3333 emit_uvalue (logbuffer, mono_method_get_token (method));
3334 emit_uvalue (logbuffer, method_id);
3335 emit_value (logbuffer, coverage_data->len);
3337 EXIT_LOG (logbuffer);
3338 safe_send (prof, logbuffer);
3340 for (i = 0; i < coverage_data->len; i++) {
3341 CoverageEntry *entry = coverage_data->pdata[i];
3343 logbuffer = ensure_logbuf (
3344 EVENT_SIZE /* event */ +
3345 LEB128_SIZE /* method id */ +
3346 LEB128_SIZE /* offset */ +
3347 LEB128_SIZE /* counter */ +
3348 LEB128_SIZE /* line */ +
3349 LEB128_SIZE /* column */
3351 ENTER_LOG (logbuffer, "coverage-statement");
3353 emit_byte (logbuffer, TYPE_COVERAGE_STATEMENT | TYPE_COVERAGE);
3354 emit_uvalue (logbuffer, method_id);
3355 emit_uvalue (logbuffer, entry->offset);
3356 emit_uvalue (logbuffer, entry->counter);
3357 emit_uvalue (logbuffer, entry->line);
3358 emit_uvalue (logbuffer, entry->column);
3360 EXIT_LOG (logbuffer);
3361 safe_send (prof, logbuffer);
3366 g_free (class_name);
3368 g_ptr_array_foreach (coverage_data, free_coverage_entry, NULL);
3369 g_ptr_array_free (coverage_data, TRUE);
3370 coverage_data = NULL;
3373 /* This empties the queue */
3375 count_queue (MonoLockFreeQueue *queue)
3377 MonoLockFreeQueueNode *node;
3380 while ((node = mono_lock_free_queue_dequeue (queue))) {
3382 mono_lock_free_queue_node_free (node);
3389 build_class_buffer (gpointer key, gpointer value, gpointer userdata)
3391 MonoClass *klass = (MonoClass *)key;
3392 MonoLockFreeQueue *class_methods = (MonoLockFreeQueue *)value;
3393 MonoProfiler *prof = (MonoProfiler *)userdata;
3396 const char *assembly_name;
3397 int number_of_methods, partially_covered;
3398 guint fully_covered;
3399 LogBuffer *logbuffer;
3401 image = mono_class_get_image (klass);
3402 assembly_name = mono_image_get_name (image);
3403 class_name = mono_type_get_name (mono_class_get_type (klass));
3405 assembly_name = assembly_name ? assembly_name : "";
3406 number_of_methods = mono_class_num_methods (klass);
3407 fully_covered = count_queue (class_methods);
3408 /* We don't handle partial covered yet */
3409 partially_covered = 0;
3411 logbuffer = ensure_logbuf (
3412 EVENT_SIZE /* event */ +
3413 strlen (assembly_name) + 1 /* assembly name */ +
3414 strlen (class_name) + 1 /* class name */ +
3415 LEB128_SIZE /* no. methods */ +
3416 LEB128_SIZE /* fully covered */ +
3417 LEB128_SIZE /* partially covered */
3420 ENTER_LOG (logbuffer, "coverage-class");
3421 emit_byte (logbuffer, TYPE_COVERAGE_CLASS | TYPE_COVERAGE);
3422 emit_string (logbuffer, assembly_name, strlen (assembly_name) + 1);
3423 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3424 emit_uvalue (logbuffer, number_of_methods);
3425 emit_uvalue (logbuffer, fully_covered);
3426 emit_uvalue (logbuffer, partially_covered);
3427 EXIT_LOG (logbuffer);
3429 safe_send (prof, logbuffer);
3431 g_free (class_name);
3435 get_coverage_for_image (MonoImage *image, int *number_of_methods, guint *fully_covered, int *partially_covered)
3437 MonoLockFreeQueue *image_methods = mono_conc_hashtable_lookup (image_to_methods, image);
3439 *number_of_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
3441 *fully_covered = count_queue (image_methods);
3445 // FIXME: We don't handle partially covered yet.
3446 *partially_covered = 0;
3450 build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
3452 MonoAssembly *assembly = (MonoAssembly *)value;
3453 MonoProfiler *prof = (MonoProfiler *)userdata;
3454 MonoImage *image = mono_assembly_get_image (assembly);
3455 LogBuffer *logbuffer;
3456 const char *name, *guid, *filename;
3457 int number_of_methods = 0, partially_covered = 0;
3458 guint fully_covered = 0;
3460 name = mono_image_get_name (image);
3461 guid = mono_image_get_guid (image);
3462 filename = mono_image_get_filename (image);
3464 name = name ? name : "";
3465 guid = guid ? guid : "";
3466 filename = filename ? filename : "";
3468 get_coverage_for_image (image, &number_of_methods, &fully_covered, &partially_covered);
3470 logbuffer = ensure_logbuf (
3471 EVENT_SIZE /* event */ +
3472 strlen (name) + 1 /* name */ +
3473 strlen (guid) + 1 /* guid */ +
3474 strlen (filename) + 1 /* file name */ +
3475 LEB128_SIZE /* no. methods */ +
3476 LEB128_SIZE /* fully covered */ +
3477 LEB128_SIZE /* partially covered */
3480 ENTER_LOG (logbuffer, "coverage-assemblies");
3481 emit_byte (logbuffer, TYPE_COVERAGE_ASSEMBLY | TYPE_COVERAGE);
3482 emit_string (logbuffer, name, strlen (name) + 1);
3483 emit_string (logbuffer, guid, strlen (guid) + 1);
3484 emit_string (logbuffer, filename, strlen (filename) + 1);
3485 emit_uvalue (logbuffer, number_of_methods);
3486 emit_uvalue (logbuffer, fully_covered);
3487 emit_uvalue (logbuffer, partially_covered);
3488 EXIT_LOG (logbuffer);
3490 safe_send (prof, logbuffer);
3494 dump_coverage (MonoProfiler *prof)
3496 if (!coverage_initialized)
3499 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Started dump\n");)
3502 mono_conc_hashtable_foreach (coverage_assemblies, build_assembly_buffer, prof);
3503 mono_conc_hashtable_foreach (coverage_classes, build_class_buffer, prof);
3504 mono_conc_hashtable_foreach (coverage_methods, build_method_buffer, prof);
3506 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Finished dump\n");)
3510 process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method)
3515 if (!coverage_initialized)
3518 klass = mono_method_get_class (method);
3519 image = mono_class_get_image (klass);
3521 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)))
3524 mono_conc_hashtable_insert (entered_methods, method, method);
3527 static MonoLockFreeQueueNode *
3528 create_method_node (MonoMethod *method)
3530 MethodNode *node = g_malloc (sizeof (MethodNode));
3531 mono_lock_free_queue_node_init ((MonoLockFreeQueueNode *) node, FALSE);
3532 node->method = method;
3534 return (MonoLockFreeQueueNode *) node;
3538 coverage_filter (MonoProfiler *prof, MonoMethod *method)
3542 MonoAssembly *assembly;
3543 MonoMethodHeader *header;
3544 guint32 iflags, flags, code_size;
3545 char *fqn, *classname;
3546 gboolean has_positive, found;
3547 MonoLockFreeQueue *image_methods, *class_methods;
3548 MonoLockFreeQueueNode *node;
3550 if (!coverage_initialized)
3553 COVERAGE_DEBUG(fprintf (stderr, "Coverage filter for %s\n", mono_method_get_name (method));)
3555 flags = mono_method_get_flags (method, &iflags);
3556 if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
3557 (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/)) {
3558 COVERAGE_DEBUG(fprintf (stderr, " Internal call or pinvoke - ignoring\n");)
3562 // Don't need to do anything else if we're already tracking this method
3563 if (mono_conc_hashtable_lookup (coverage_methods, method)) {
3564 COVERAGE_DEBUG(fprintf (stderr, " Already tracking\n");)
3568 klass = mono_method_get_class (method);
3569 image = mono_class_get_image (klass);
3571 // Don't handle coverage for the core assemblies
3572 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)) != NULL)
3575 if (prof->coverage_filters) {
3576 /* Check already filtered classes first */
3577 if (mono_conc_hashtable_lookup (filtered_classes, klass)) {
3578 COVERAGE_DEBUG(fprintf (stderr, " Already filtered\n");)
3582 classname = mono_type_get_name (mono_class_get_type (klass));
3584 fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
3586 COVERAGE_DEBUG(fprintf (stderr, " Looking for %s in filter\n", fqn);)
3587 // Check positive filters first
3588 has_positive = FALSE;
3590 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3591 char *filter = g_ptr_array_index (prof->coverage_filters, i);
3593 if (filter [0] == '+') {
3594 filter = &filter [1];
3596 COVERAGE_DEBUG(fprintf (stderr, " Checking against +%s ...", filter);)
3598 if (strstr (fqn, filter) != NULL) {
3599 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3602 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3604 has_positive = TRUE;
3608 if (has_positive && !found) {
3609 COVERAGE_DEBUG(fprintf (stderr, " Positive match was not found\n");)
3611 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3618 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3619 // FIXME: Is substring search sufficient?
3620 char *filter = g_ptr_array_index (prof->coverage_filters, i);
3621 if (filter [0] == '+')
3625 filter = &filter [1];
3626 COVERAGE_DEBUG(fprintf (stderr, " Checking against -%s ...", filter);)
3628 if (strstr (fqn, filter) != NULL) {
3629 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3631 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3637 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3645 COVERAGE_DEBUG(fprintf (stderr, " Handling coverage for %s\n", mono_method_get_name (method));)
3646 header = mono_method_get_header (method);
3648 mono_method_header_get_code (header, &code_size, NULL);
3650 assembly = mono_image_get_assembly (image);
3652 mono_conc_hashtable_insert (coverage_methods, method, method);
3653 mono_conc_hashtable_insert (coverage_assemblies, assembly, assembly);
3655 image_methods = mono_conc_hashtable_lookup (image_to_methods, image);
3657 if (image_methods == NULL) {
3658 image_methods = g_malloc (sizeof (MonoLockFreeQueue));
3659 mono_lock_free_queue_init (image_methods);
3660 mono_conc_hashtable_insert (image_to_methods, image, image_methods);
3663 node = create_method_node (method);
3664 mono_lock_free_queue_enqueue (image_methods, node);
3666 class_methods = mono_conc_hashtable_lookup (coverage_classes, klass);
3668 if (class_methods == NULL) {
3669 class_methods = g_malloc (sizeof (MonoLockFreeQueue));
3670 mono_lock_free_queue_init (class_methods);
3671 mono_conc_hashtable_insert (coverage_classes, klass, class_methods);
3674 node = create_method_node (method);
3675 mono_lock_free_queue_enqueue (class_methods, node);
3680 #define LINE_BUFFER_SIZE 4096
3681 /* Max file limit of 128KB */
3682 #define MAX_FILE_SIZE 128 * 1024
3684 get_file_content (FILE *stream)
3689 int res, offset = 0;
3691 res = fseek (stream, 0, SEEK_END);
3695 filesize = ftell (stream);
3699 res = fseek (stream, 0, SEEK_SET);
3703 if (filesize > MAX_FILE_SIZE)
3706 buffer = g_malloc ((filesize + 1) * sizeof (char));
3707 while ((bytes_read = fread (buffer + offset, 1, LINE_BUFFER_SIZE, stream)) > 0)
3708 offset += bytes_read;
3710 /* NULL terminate our buffer */
3711 buffer[filesize] = '\0';
3716 get_next_line (char *contents, char **next_start)
3720 if (p == NULL || *p == '\0') {
3725 while (*p != '\n' && *p != '\0')
3730 *next_start = p + 1;
3738 init_suppressed_assemblies (void)
3744 mono_mutex_init (&suppressed_assemblies_mutex);
3745 suppressed_assemblies = mono_conc_hashtable_new (&suppressed_assemblies_mutex, g_str_hash, g_str_equal);
3746 sa_file = fopen (SUPPRESSION_DIR "/mono-profiler-log.suppression", "r");
3747 if (sa_file == NULL)
3750 /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
3751 content = get_file_content (sa_file);
3752 if (content == NULL) {
3753 g_error ("mono-profiler-log.suppression is greater than 128kb - aborting\n");
3756 while ((line = get_next_line (content, &content))) {
3757 line = g_strchomp (g_strchug (line));
3758 mono_conc_hashtable_insert (suppressed_assemblies, line, line);
3764 static MonoConcurrentHashTable *
3765 init_hashtable (mono_mutex_t *mutex)
3767 mono_mutex_init (mutex);
3768 return mono_conc_hashtable_new (mutex, NULL, NULL);
3772 destroy_hashtable (MonoConcurrentHashTable *hashtable, mono_mutex_t *mutex)
3774 mono_conc_hashtable_destroy (hashtable);
3775 mono_mutex_destroy (mutex);
3778 #endif /* DISABLE_HELPER_THREAD */
3781 coverage_init (MonoProfiler *prof)
3783 #ifndef DISABLE_HELPER_THREAD
3784 assert (!coverage_initialized);
3786 COVERAGE_DEBUG(fprintf (stderr, "Coverage initialized\n");)
3788 coverage_methods = init_hashtable (&coverage_methods_mutex);
3789 coverage_assemblies = init_hashtable (&coverage_assemblies_mutex);
3790 coverage_classes = init_hashtable (&coverage_classes_mutex);
3791 filtered_classes = init_hashtable (&filtered_classes_mutex);
3792 entered_methods = init_hashtable (&entered_methods_mutex);
3793 image_to_methods = init_hashtable (&image_to_methods_mutex);
3794 init_suppressed_assemblies ();
3796 coverage_initialized = TRUE;
3797 #endif /* DISABLE_HELPER_THREAD */
3801 log_shutdown (MonoProfiler *prof)
3806 #ifndef DISABLE_HELPER_THREAD
3807 counters_and_perfcounters_sample (prof);
3809 dump_coverage (prof);
3811 if (prof->command_port) {
3813 ign_res (write (prof->pipes [1], &c, 1));
3814 pthread_join (prof->helper_thread, &res);
3820 for (i = 0; i < num_perf; ++i)
3821 read_perf_mmap (prof, i);
3825 g_ptr_array_free (prof->sorted_sample_events, TRUE);
3827 if (TLS_GET (LogBuffer, tlsbuffer))
3828 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
3830 TLS_SET (tlsbuffer, NULL);
3831 TLS_SET (tlsmethodlist, NULL);
3833 InterlockedWrite (&prof->run_writer_thread, 0);
3834 pthread_join (prof->writer_thread, &res);
3836 #if defined (HAVE_SYS_ZLIB)
3838 gzclose (prof->gzfile);
3840 if (prof->pipe_output)
3841 pclose (prof->file);
3843 fclose (prof->file);
3845 destroy_hashtable (prof->method_table, &prof->method_table_mutex);
3847 if (coverage_initialized) {
3848 destroy_hashtable (coverage_methods, &coverage_methods_mutex);
3849 destroy_hashtable (coverage_assemblies, &coverage_assemblies_mutex);
3850 destroy_hashtable (coverage_classes, &coverage_classes_mutex);
3851 destroy_hashtable (filtered_classes, &filtered_classes_mutex);
3852 destroy_hashtable (entered_methods, &entered_methods_mutex);
3853 destroy_hashtable (image_to_methods, &image_to_methods_mutex);
3854 destroy_hashtable (suppressed_assemblies, &suppressed_assemblies_mutex);
3861 new_filename (const char* filename)
3863 time_t t = time (NULL);
3864 int pid = process_id ();
3869 int count_dates = 0;
3873 for (p = filename; *p; p++) {
3884 if (!count_dates && !count_pids)
3885 return pstrdup (filename);
3886 snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
3888 snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
3889 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
3890 s_date = strlen (time_buf);
3891 s_pid = strlen (pid_buf);
3892 d = res = malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
3893 for (p = filename; *p; p++) {
3900 strcpy (d, time_buf);
3903 } else if (*p == 'p') {
3904 strcpy (d, pid_buf);
3907 } else if (*p == '%') {
3919 //this is exposed by the JIT, but it's not meant to be a supported API for now.
3920 extern void mono_threads_attach_tools_thread (void);
3922 #ifndef DISABLE_HELPER_THREAD
3925 helper_thread (void* arg)
3927 MonoProfiler* prof = arg;
3931 MonoThread *thread = NULL;
3933 mono_threads_attach_tools_thread ();
3934 //fprintf (stderr, "Server listening\n");
3935 command_socket = -1;
3941 FD_SET (prof->server_socket, &rfds);
3942 max_fd = prof->server_socket;
3943 FD_SET (prof->pipes [0], &rfds);
3944 if (max_fd < prof->pipes [0])
3945 max_fd = prof->pipes [0];
3946 if (command_socket >= 0) {
3947 FD_SET (command_socket, &rfds);
3948 if (max_fd < command_socket)
3949 max_fd = command_socket;
3954 for ( i = 0; i < num_perf; ++i) {
3955 if (perf_data [i].perf_fd < 0)
3957 FD_SET (perf_data [i].perf_fd, &rfds);
3958 if (max_fd < perf_data [i].perf_fd)
3959 max_fd = perf_data [i].perf_fd;
3964 counters_and_perfcounters_sample (prof);
3968 len = select (max_fd + 1, &rfds, NULL, NULL, &tv);
3974 g_warning ("Error in proflog server: %s", strerror (errno));
3978 if (FD_ISSET (prof->pipes [0], &rfds)) {
3980 int r = read (prof->pipes [0], &c, 1);
3981 if (r == 1 && c == 0) {
3982 StatBuffer *sbufbase = prof->stat_buffers;
3984 if (!sbufbase->next)
3986 sbuf = sbufbase->next->next;
3987 sbufbase->next->next = NULL;
3989 fprintf (stderr, "stat buffer dump\n");
3991 dump_sample_hits (prof, sbuf);
3992 free_buffer (sbuf, sbuf->size);
3993 safe_send (prof, ensure_logbuf (0));
3997 /* time to shut down */
3998 dump_sample_hits (prof, prof->stat_buffers);
4000 mono_thread_detach (thread);
4002 fprintf (stderr, "helper shutdown\n");
4006 for ( i = 0; i < num_perf; ++i) {
4007 if (perf_data [i].perf_fd < 0)
4009 if (FD_ISSET (perf_data [i].perf_fd, &rfds))
4010 read_perf_mmap (prof, i);
4014 safe_send (prof, ensure_logbuf (0));
4020 for ( i = 0; i < num_perf; ++i) {
4021 if (perf_data [i].perf_fd < 0)
4023 if (FD_ISSET (perf_data [i].perf_fd, &rfds)) {
4024 read_perf_mmap (prof, i);
4025 safe_send (prof, ensure_logbuf (0));
4030 if (command_socket >= 0 && FD_ISSET (command_socket, &rfds)) {
4031 len = read (command_socket, buf, sizeof (buf) - 1);
4035 close (command_socket);
4036 command_socket = -1;
4040 if (strcmp (buf, "heapshot\n") == 0) {
4041 heapshot_requested = 1;
4042 //fprintf (stderr, "perform heapshot\n");
4043 if (InterlockedRead (&runtime_inited) && !thread) {
4044 thread = mono_thread_attach (mono_get_root_domain ());
4045 /*fprintf (stderr, "attached\n");*/
4048 process_requests (prof);
4049 mono_thread_detach (thread);
4055 if (!FD_ISSET (prof->server_socket, &rfds)) {
4058 command_socket = accept (prof->server_socket, NULL, NULL);
4059 if (command_socket < 0)
4061 //fprintf (stderr, "Accepted connection\n");
4067 start_helper_thread (MonoProfiler* prof)
4069 struct sockaddr_in server_address;
4072 if (pipe (prof->pipes) < 0) {
4073 fprintf (stderr, "Cannot create pipe\n");
4076 prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
4077 if (prof->server_socket < 0) {
4078 fprintf (stderr, "Cannot create server socket\n");
4081 memset (&server_address, 0, sizeof (server_address));
4082 server_address.sin_family = AF_INET;
4083 server_address.sin_addr.s_addr = INADDR_ANY;
4084 server_address.sin_port = htons (prof->command_port);
4085 if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) < 0) {
4086 fprintf (stderr, "Cannot bind server socket, port: %d: %s\n", prof->command_port, strerror (errno));
4087 close (prof->server_socket);
4090 if (listen (prof->server_socket, 1) < 0) {
4091 fprintf (stderr, "Cannot listen server socket\n");
4092 close (prof->server_socket);
4095 slen = sizeof (server_address);
4096 if (getsockname (prof->server_socket, (struct sockaddr *)&server_address, &slen) == 0) {
4097 prof->command_port = ntohs (server_address.sin_port);
4098 /*fprintf (stderr, "Assigned server port: %d\n", prof->command_port);*/
4101 r = pthread_create (&prof->helper_thread, NULL, helper_thread, prof);
4103 close (prof->server_socket);
4111 writer_thread (void *arg)
4113 MonoProfiler *prof = arg;
4115 mono_threads_attach_tools_thread ();
4119 while (InterlockedRead (&prof->run_writer_thread)) {
4120 WriterQueueEntry *entry;
4122 while ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&prof->writer_queue))) {
4123 LogBuffer *method_buffer = NULL;
4124 gboolean new_methods = FALSE;
4126 if (entry->methods->len)
4127 method_buffer = create_buffer ();
4130 * Encode the method events in a temporary log buffer that we
4131 * flush to disk before the main buffer, ensuring that all
4132 * methods have metadata emitted before they're referenced.
4134 for (guint i = 0; i < entry->methods->len; i++) {
4135 MethodInfo *info = g_ptr_array_index (entry->methods, i);
4137 if (mono_conc_hashtable_lookup (prof->method_table, info->method))
4143 * Other threads use this hash table to get a general
4144 * idea of whether a method has already been emitted to
4145 * the stream. Due to the way we add to this table, it
4146 * can easily happen that multiple threads queue up the
4147 * same methods, but that's OK since eventually all
4148 * methods will be in this table and the thread-local
4149 * method lists will just be empty for the rest of the
4152 mono_conc_hashtable_insert (prof->method_table, info->method, info->method);
4154 char *name = mono_method_full_name (info->method, 1);
4155 int nlen = strlen (name) + 1;
4156 uint64_t now = current_time ();
4158 method_buffer = ensure_logbuf_inner (method_buffer,
4159 EVENT_SIZE /* event */ +
4160 LEB128_SIZE /* time */ +
4161 LEB128_SIZE /* method */ +
4162 LEB128_SIZE /* start */ +
4163 LEB128_SIZE /* size */ +
4167 emit_byte (method_buffer, TYPE_JIT | TYPE_METHOD);
4168 emit_time (method_buffer, now);
4169 emit_method_inner (method_buffer, info->method);
4170 emit_ptr (method_buffer, mono_jit_info_get_code_start (info->ji));
4171 emit_value (method_buffer, mono_jit_info_get_code_size (info->ji));
4173 memcpy (method_buffer->data, name, nlen);
4174 method_buffer->data += nlen;
4180 g_ptr_array_free (entry->methods, TRUE);
4183 dump_buffer (prof, method_buffer);
4184 else if (method_buffer)
4185 free_buffer (method_buffer, method_buffer->size);
4187 dump_buffer (prof, entry->buffer);
4197 start_writer_thread (MonoProfiler* prof)
4199 InterlockedWrite (&prof->run_writer_thread, 1);
4201 return !pthread_create (&prof->writer_thread, NULL, writer_thread, prof);
4205 runtime_initialized (MonoProfiler *profiler)
4207 #ifndef DISABLE_HELPER_THREAD
4208 if (hs_mode_ondemand || need_helper_thread) {
4209 if (!start_helper_thread (profiler))
4210 profiler->command_port = 0;
4214 start_writer_thread (profiler);
4216 InterlockedWrite (&runtime_inited, 1);
4217 #ifndef DISABLE_HELPER_THREAD
4218 counters_init (profiler);
4219 counters_sample (profiler, 0);
4221 /* ensure the main thread data and startup are available soon */
4222 safe_send (profiler, ensure_logbuf (0));
4225 static MonoProfiler*
4226 create_profiler (const char *filename, GPtrArray *filters)
4230 int force_delete = 0;
4231 prof = calloc (1, sizeof (MonoProfiler));
4233 prof->command_port = command_port;
4234 if (filename && *filename == '-') {
4240 filename = "|mprof-report -";
4242 filename = "output.mlpd";
4243 nf = (char*)filename;
4245 nf = new_filename (filename);
4247 int s = strlen (nf) + 32;
4248 char *p = malloc (s);
4249 snprintf (p, s, "|mprof-report '--out=%s' -", nf);
4255 prof->file = popen (nf + 1, "w");
4256 prof->pipe_output = 1;
4257 } else if (*nf == '#') {
4258 int fd = strtol (nf + 1, NULL, 10);
4259 prof->file = fdopen (fd, "a");
4263 prof->file = fopen (nf, "wb");
4266 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
4269 #if defined (HAVE_SYS_ZLIB)
4271 prof->gzfile = gzdopen (fileno (prof->file), "wb");
4274 if (sample_type && !do_mono_sample)
4275 need_helper_thread = setup_perf_event ();
4277 /* FIXME: warn if different freq or sample type */
4281 if (do_mono_sample) {
4282 prof->stat_buffers = create_stat_buffer ();
4283 need_helper_thread = 1;
4285 if (do_counters && !need_helper_thread) {
4286 need_helper_thread = 1;
4289 prof->sorted_sample_events = g_ptr_array_sized_new (BUFFER_SIZE / SAMPLE_EVENT_SIZE_IN_SLOTS (0));
4291 #ifdef DISABLE_HELPER_THREAD
4292 if (hs_mode_ondemand)
4293 fprintf (stderr, "Ondemand heapshot unavailable on this arch.\n");
4296 fprintf (stderr, "Coverage unavailable on this arch.\n");
4300 mono_lock_free_queue_init (&prof->writer_queue);
4301 mono_mutex_init (&prof->method_table_mutex);
4302 prof->method_table = mono_conc_hashtable_new (&prof->method_table_mutex, NULL, NULL);
4305 coverage_init (prof);
4306 prof->coverage_filters = filters;
4308 prof->startup_time = current_time ();
4315 printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
4316 printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
4317 printf ("Options:\n");
4318 printf ("\thelp show this usage info\n");
4319 printf ("\t[no]alloc enable/disable recording allocation info\n");
4320 printf ("\t[no]calls enable/disable recording enter/leave method events\n");
4321 printf ("\theapshot[=MODE] record heap shot info (by default at each major collection)\n");
4322 printf ("\t MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
4323 printf ("\tcounters sample counters every 1s\n");
4324 printf ("\tsample[=TYPE] use statistical sampling mode (by default cycles/1000)\n");
4325 printf ("\t TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
4326 printf ("\t TYPE can be followed by /FREQUENCY\n");
4327 printf ("\ttime=fast use a faster (but more inaccurate) timer\n");
4328 printf ("\tmaxframes=NUM collect up to NUM stack frames\n");
4329 printf ("\tcalldepth=NUM ignore method events for call chain depth bigger than NUM\n");
4330 printf ("\toutput=FILENAME write the data to file FILENAME (-FILENAME to overwrite)\n");
4331 printf ("\toutput=|PROGRAM write the data to the stdin of PROGRAM\n");
4332 printf ("\t %%t is subtituted with date and time, %%p with the pid\n");
4333 printf ("\treport create a report instead of writing the raw data to a file\n");
4334 printf ("\tzip compress the output data\n");
4335 printf ("\tport=PORTNUM use PORTNUM for the listening command server\n");
4336 printf ("\tcoverage enable collection of code coverage data\n");
4337 printf ("\tcovfilter=ASSEMBLY add an assembly to the code coverage filters\n");
4338 printf ("\t add a + to include the assembly or a - to exclude it\n");
4339 printf ("\t filter=-mscorlib\n");
4340 printf ("\tcovfilter-file=FILE use FILE to generate the list of assemblies to be filtered\n");
4346 match_option (const char* p, const char *opt, char **rval)
4348 int len = strlen (opt);
4349 if (strncmp (p, opt, len) == 0) {
4351 if (p [len] == '=' && p [len + 1]) {
4352 const char *opt = p + len + 1;
4353 const char *end = strchr (opt, ',');
4361 val = malloc (l + 1);
4362 memcpy (val, opt, l);
4367 if (p [len] == 0 || p [len] == ',') {
4369 return p + len + (p [len] == ',');
4387 static const SampleMode sample_modes [] = {
4388 {"cycles", SAMPLE_CYCLES},
4389 {"instr", SAMPLE_INSTRUCTIONS},
4390 {"cachemiss", SAMPLE_CACHE_MISSES},
4391 {"cacherefs", SAMPLE_CACHE_REFS},
4392 {"branches", SAMPLE_BRANCHES},
4393 {"branchmiss", SAMPLE_BRANCH_MISSES},
4398 set_sample_mode (char* val, int allow_empty)
4401 char *maybe_freq = NULL;
4403 const SampleMode *smode = sample_modes;
4404 #ifndef USE_PERF_EVENTS
4407 if (allow_empty && !val) {
4408 sample_type = SAMPLE_CYCLES;
4412 if (strcmp (val, "mono") == 0) {
4414 sample_type = SAMPLE_CYCLES;
4418 for (smode = sample_modes; smode->name; smode++) {
4419 int l = strlen (smode->name);
4420 if (strncmp (val, smode->name, l) == 0) {
4421 sample_type = smode->sample_mode;
4422 maybe_freq = val + l;
4428 if (*maybe_freq == '/') {
4429 count = strtoul (maybe_freq + 1, &end, 10);
4430 if (maybe_freq + 1 == end)
4432 sample_freq = count;
4433 } else if (*maybe_freq != 0) {
4442 set_hsmode (char* val, int allow_empty)
4446 if (allow_empty && !val)
4448 if (strcmp (val, "ondemand") == 0) {
4449 hs_mode_ondemand = 1;
4453 count = strtoul (val, &end, 10);
4456 if (strcmp (end, "ms") == 0)
4458 else if (strcmp (end, "gc") == 0)
4466 * declaration to silence the compiler: this is the entry point that
4467 * mono will load from the shared library and call.
4470 mono_profiler_startup (const char *desc);
4473 mono_profiler_startup_log (const char *desc);
4476 * this is the entry point that will be used when the profiler
4477 * is embedded inside the main executable.
4480 mono_profiler_startup_log (const char *desc)
4482 mono_profiler_startup (desc);
4486 mono_profiler_startup (const char *desc)
4489 GPtrArray *filters = NULL;
4490 char *filename = NULL;
4494 int calls_enabled = 0;
4495 int allocs_enabled = 0;
4496 int only_counters = 0;
4497 int only_coverage = 0;
4498 int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
4499 MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
4500 MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
4501 MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS|
4502 MONO_PROFILE_INS_COVERAGE|MONO_PROFILE_APPDOMAIN_EVENTS|MONO_PROFILE_CONTEXT_EVENTS|
4503 MONO_PROFILE_ASSEMBLY_EVENTS;
4506 if (strncmp (p, "log", 3))
4511 for (; *p; p = opt) {
4517 if ((opt = match_option (p, "help", NULL)) != p) {
4521 if ((opt = match_option (p, "calls", NULL)) != p) {
4525 if ((opt = match_option (p, "nocalls", NULL)) != p) {
4526 events &= ~MONO_PROFILE_ENTER_LEAVE;
4530 if ((opt = match_option (p, "alloc", NULL)) != p) {
4534 if ((opt = match_option (p, "noalloc", NULL)) != p) {
4535 events &= ~MONO_PROFILE_ALLOCATIONS;
4538 if ((opt = match_option (p, "time", &val)) != p) {
4539 if (strcmp (val, "fast") == 0)
4541 else if (strcmp (val, "null") == 0)
4548 if ((opt = match_option (p, "report", NULL)) != p) {
4552 if ((opt = match_option (p, "debug", NULL)) != p) {
4556 if ((opt = match_option (p, "sampling-real", NULL)) != p) {
4557 sampling_mode = MONO_PROFILER_STAT_MODE_REAL;
4560 if ((opt = match_option (p, "sampling-process", NULL)) != p) {
4561 sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
4564 if ((opt = match_option (p, "heapshot", &val)) != p) {
4565 events &= ~MONO_PROFILE_ALLOCATIONS;
4566 events &= ~MONO_PROFILE_ENTER_LEAVE;
4569 set_hsmode (val, 1);
4572 if ((opt = match_option (p, "sample", &val)) != p) {
4573 events &= ~MONO_PROFILE_ALLOCATIONS;
4574 events &= ~MONO_PROFILE_ENTER_LEAVE;
4576 set_sample_mode (val, 1);
4579 if ((opt = match_option (p, "hsmode", &val)) != p) {
4580 fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
4581 set_hsmode (val, 0);
4584 if ((opt = match_option (p, "zip", NULL)) != p) {
4588 if ((opt = match_option (p, "output", &val)) != p) {
4592 if ((opt = match_option (p, "port", &val)) != p) {
4594 command_port = strtoul (val, &end, 10);
4598 if ((opt = match_option (p, "maxframes", &val)) != p) {
4600 num_frames = strtoul (val, &end, 10);
4601 if (num_frames > MAX_FRAMES)
4602 num_frames = MAX_FRAMES;
4604 notraces = num_frames == 0;
4607 if ((opt = match_option (p, "calldepth", &val)) != p) {
4609 max_call_depth = strtoul (val, &end, 10);
4613 if ((opt = match_option (p, "counters", NULL)) != p) {
4617 if ((opt = match_option (p, "countersonly", NULL)) != p) {
4621 if ((opt = match_option (p, "coverage", NULL)) != p) {
4623 events |= MONO_PROFILE_ENTER_LEAVE;
4624 debug_coverage = (g_getenv ("MONO_PROFILER_DEBUG_COVERAGE") != NULL);
4627 if ((opt = match_option (p, "onlycoverage", NULL)) != p) {
4631 if ((opt = match_option (p, "covfilter-file", &val)) != p) {
4633 char *line, *content;
4635 if (filters == NULL)
4636 filters = g_ptr_array_new ();
4638 filter_file = fopen (val, "r");
4639 if (filter_file == NULL) {
4640 fprintf (stderr, "Unable to open %s\n", val);
4644 /* Don't need to free content as it is referred to by the lines stored in @filters */
4645 content = get_file_content (filter_file);
4646 if (content == NULL)
4647 fprintf (stderr, "WARNING: %s is greater than 128kb - ignoring\n", val);
4649 while ((line = get_next_line (content, &content)))
4650 g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
4652 fclose (filter_file);
4655 if ((opt = match_option (p, "covfilter", &val)) != p) {
4656 if (filters == NULL)
4657 filters = g_ptr_array_new ();
4659 g_ptr_array_add (filters, val);
4667 if (calls_enabled) {
4668 events |= MONO_PROFILE_ENTER_LEAVE;
4672 events |= MONO_PROFILE_ALLOCATIONS;
4676 events = MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_INS_COVERAGE;
4678 utils_init (fast_time);
4680 prof = create_profiler (filename, filters);
4685 mono_profiler_install (prof, log_shutdown);
4686 mono_profiler_install_gc (gc_event, gc_resize);
4687 mono_profiler_install_allocation (gc_alloc);
4688 mono_profiler_install_gc_moves (gc_moves);
4689 mono_profiler_install_gc_roots (gc_handle, gc_roots);
4690 mono_profiler_install_appdomain (NULL, domain_loaded, NULL, domain_unloaded);
4691 mono_profiler_install_appdomain_name (domain_name);
4692 mono_profiler_install_context (context_loaded, context_unloaded);
4693 mono_profiler_install_class (NULL, class_loaded, NULL, class_unloaded);
4694 mono_profiler_install_module (NULL, image_loaded, NULL, image_unloaded);
4695 mono_profiler_install_assembly (NULL, assembly_loaded, NULL, assembly_unloaded);
4696 mono_profiler_install_thread (thread_start, thread_end);
4697 mono_profiler_install_thread_name (thread_name);
4698 mono_profiler_install_enter_leave (method_enter, method_leave);
4699 mono_profiler_install_jit_end (method_jitted);
4700 mono_profiler_install_code_buffer_new (code_buffer_new);
4701 mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
4702 mono_profiler_install_monitor (monitor_event);
4703 mono_profiler_install_runtime_initialized (runtime_initialized);
4705 mono_profiler_install_coverage_filter (coverage_filter);
4707 if (do_mono_sample && sample_type == SAMPLE_CYCLES && !only_counters) {
4708 events |= MONO_PROFILE_STATISTICAL;
4709 mono_profiler_set_statistical_mode (sampling_mode, 1000000 / sample_freq);
4710 mono_profiler_install_statistical (mono_sample_hit);
4713 mono_profiler_set_events (events);
4715 TLS_INIT (tlsbuffer);
4716 TLS_INIT (tlsmethodlist);