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[_BT],
202 * TYPE_GC_HANDLE_DESTROYED[_BT]
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[_BT]
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_CREATED_BT, a backtrace follows.
220 * if exinfo == TYPE_GC_HANDLE_DESTROYED[_BT]
221 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
222 * upper bits reserved as flags
223 * [handle: uleb128] GC handle value
224 * If exinfo == TYPE_GC_HANDLE_DESTROYED_BT, a backtrace follows.
226 * type metadata format:
227 * type: TYPE_METADATA
228 * exinfo: one of: TYPE_END_LOAD, TYPE_END_UNLOAD (optional for TYPE_THREAD and TYPE_DOMAIN)
229 * [time diff: uleb128] nanoseconds since last timing
230 * [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
231 * TYPE_THREAD, TYPE_CONTEXT
232 * [pointer: sleb128] pointer of the metadata type depending on mtype
233 * if mtype == TYPE_CLASS
234 * [image: sleb128] MonoImage* as a pointer difference from ptr_base
235 * [flags: uleb128] must be 0
236 * [name: string] full class name
237 * if mtype == TYPE_IMAGE
238 * [flags: uleb128] must be 0
239 * [name: string] image file name
240 * if mtype == TYPE_ASSEMBLY
241 * [flags: uleb128] must be 0
242 * [name: string] assembly name
243 * if mtype == TYPE_DOMAIN
244 * [flags: uleb128] must be 0
245 * if mtype == TYPE_DOMAIN && exinfo == 0
246 * [name: string] domain friendly name
247 * if mtype == TYPE_CONTEXT
248 * [domain: sleb128] domain id as pointer
249 * if mtype == TYPE_THREAD && (format_version < 11 || (format_version > 10 && exinfo == 0))
250 * [name: string] thread name
252 * type method format:
254 * exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
255 * [time diff: uleb128] nanoseconds since last timing
256 * [method: sleb128] MonoMethod* as a pointer difference from the last such
257 * pointer or the buffer method_base
258 * if exinfo == TYPE_JIT
259 * [code address: sleb128] pointer to the native code as a diff from ptr_base
260 * [code size: uleb128] size of the generated code
261 * [name: string] full method name
263 * type runtime format:
265 * exinfo: one of: TYPE_JITHELPER
266 * [time diff: uleb128] nanoseconds since last timing
267 * if exinfo == TYPE_JITHELPER
268 * [type: uleb128] MonoProfilerCodeBufferType enum value
269 * [buffer address: sleb128] pointer to the native code as a diff from ptr_base
270 * [buffer size: uleb128] size of the generated code
271 * if type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE
272 * [name: string] buffer description name
274 * type monitor format:
276 * exinfo: TYPE_MONITOR_BT flag and one of: MONO_PROFILER_MONITOR_(CONTENTION|FAIL|DONE)
277 * [time diff: uleb128] nanoseconds since last timing
278 * [object: sleb128] the lock object as a difference from obj_base
279 * if exinfo.low3bits == MONO_PROFILER_MONITOR_CONTENTION
280 * If the TYPE_MONITOR_BT flag is set, a backtrace follows.
284 * exinfo: one of TYPE_HEAP_START, TYPE_HEAP_END, TYPE_HEAP_OBJECT, TYPE_HEAP_ROOT
285 * if exinfo == TYPE_HEAP_START
286 * [time diff: uleb128] nanoseconds since last timing
287 * if exinfo == TYPE_HEAP_END
288 * [time diff: uleb128] nanoseconds since last timing
289 * if exinfo == TYPE_HEAP_OBJECT
290 * [object: sleb128] the object as a difference from obj_base
291 * [class: sleb128] the object MonoClass* as a difference from ptr_base
292 * [size: uleb128] size of the object on the heap
293 * [num_refs: uleb128] number of object references
294 * if (format version > 1) each referenced objref is preceded by a
295 * uleb128 encoded offset: the first offset is from the object address
296 * and each next offset is relative to the previous one
297 * [objrefs: sleb128]+ object referenced as a difference from obj_base
298 * The same object can appear multiple times, but only the first time
299 * with size != 0: in the other cases this data will only be used to
300 * provide additional referenced objects.
301 * if exinfo == TYPE_HEAP_ROOT
302 * [num_roots: uleb128] number of root references
303 * [num_gc: uleb128] number of major gcs
304 * [object: sleb128] the object as a difference from obj_base
305 * [root_type: uleb128] the root_type: MonoProfileGCRootType (profiler.h)
306 * [extra_info: uleb128] the extra_info value
307 * object, root_type and extra_info are repeated num_roots times
311 * exinfo: one of TYPE_SAMPLE_HIT, TYPE_SAMPLE_USYM, TYPE_SAMPLE_UBIN, TYPE_SAMPLE_COUNTERS_DESC, TYPE_SAMPLE_COUNTERS
312 * if exinfo == TYPE_SAMPLE_HIT
313 * [sample_type: uleb128] type of sample (SAMPLE_*)
314 * [timestamp: uleb128] nanoseconds since startup (note: different from other timestamps!)
315 * if (format_version > 10)
316 * [thread: sleb128] thread id as difference from ptr_base
317 * [count: uleb128] number of following instruction addresses
318 * [ip: sleb128]* instruction pointer as difference from ptr_base
319 * if (format_version > 5)
320 * [mbt_count: uleb128] number of managed backtrace info triplets (method + IL offset + native offset)
321 * [method: sleb128]* MonoMethod* as a pointer difference from the last such
322 * pointer or the buffer method_base (the first such method can be also indentified by ip, but this is not neccessarily true)
323 * [il_offset: sleb128]* IL offset inside method where the hit occurred
324 * [native_offset: sleb128]* native offset inside method where the hit occurred
325 * if exinfo == TYPE_SAMPLE_USYM
326 * [address: sleb128] symbol address as a difference from ptr_base
327 * [size: uleb128] symbol size (may be 0 if unknown)
328 * [name: string] symbol name
329 * if exinfo == TYPE_SAMPLE_UBIN
330 * [time diff: uleb128] nanoseconds since last timing
331 * [address: sleb128] address where binary has been loaded
332 * [offset: uleb128] file offset of mapping (the same file can be mapped multiple times)
333 * [size: uleb128] memory size
334 * [name: string] binary name
335 * if exinfo == TYPE_SAMPLE_COUNTERS_DESC
336 * [len: uleb128] number of counters
338 * [section: uleb128] section of counter
339 * if section == MONO_COUNTER_PERFCOUNTERS:
340 * [section_name: string] section name of counter
341 * [name: string] name of counter
342 * [type: uleb128] type of counter
343 * [unit: uleb128] unit of counter
344 * [variance: uleb128] variance of counter
345 * [index: uleb128] unique index of counter
346 * if exinfo == TYPE_SAMPLE_COUNTERS
347 * [timestamp: uleb128] sampling timestamp
349 * [index: uleb128] unique index of counter
352 * [type: uleb128] type of counter value
355 * [0: uleb128] 0 -> value is null
357 * [1: uleb128] 1 -> value is not null
358 * [value: string] counter value
360 * [value: uleb128/sleb128/double] counter value, can be sleb128, uleb128 or double (determined by using type)
362 * type coverage format
363 * type: TYPE_COVERAGE
364 * exinfo: one of TYPE_COVERAGE_METHOD, TYPE_COVERAGE_STATEMENT, TYPE_COVERAGE_ASSEMBLY, TYPE_COVERAGE_CLASS
365 * if exinfo == TYPE_COVERAGE_METHOD
366 * [assembly: string] name of assembly
367 * [class: string] name of the class
368 * [name: string] name of the method
369 * [signature: string] the signature of the method
370 * [filename: string] the file path of the file that contains this method
371 * [token: uleb128] the method token
372 * [method_id: uleb128] an ID for this data to associate with the buffers of TYPE_COVERAGE_STATEMENTS
373 * [len: uleb128] the number of TYPE_COVERAGE_BUFFERS associated with this method
374 * if exinfo == TYPE_COVERAGE_STATEMENTS
375 * [method_id: uleb128] an the TYPE_COVERAGE_METHOD buffer to associate this with
376 * [offset: uleb128] the il offset relative to the previous offset
377 * [counter: uleb128] the counter for this instruction
378 * [line: uleb128] the line of filename containing this instruction
379 * [column: uleb128] the column containing this instruction
380 * if exinfo == TYPE_COVERAGE_ASSEMBLY
381 * [name: string] assembly name
382 * [guid: string] assembly GUID
383 * [filename: string] assembly filename
384 * [number_of_methods: uleb128] the number of methods in this assembly
385 * [fully_covered: uleb128] the number of fully covered methods
386 * [partially_covered: uleb128] the number of partially covered methods
387 * currently partially_covered will always be 0, and fully_covered is the
388 * number of methods that are fully and partially covered.
389 * if exinfo == TYPE_COVERAGE_CLASS
390 * [name: string] assembly name
391 * [class: string] class name
392 * [number_of_methods: uleb128] the number of methods in this class
393 * [fully_covered: uleb128] the number of fully covered methods
394 * [partially_covered: uleb128] the number of partially covered methods
395 * currently partially_covered will always be 0, and fully_covered is the
396 * number of methods that are fully and partially covered.
400 * Format oddities that we ought to fix:
402 * - Methods written in emit_bt () should be based on the buffer's base
403 * method instead of the base pointer.
404 * - The TYPE_SAMPLE_HIT event contains (currently) pointless data like
405 * always-one unmanaged frame count and always-zero IL offsets.
407 * These are mostly small things and are not worth a format change by
408 * themselves. They should be done when some other major change has to
409 * be done to the format.
417 uintptr_t method_base;
418 uintptr_t last_method;
421 unsigned char* data_end;
426 unsigned char buf [1];
430 ign_res (int G_GNUC_UNUSED unused, ...)
434 #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++;}
435 #define EXIT_LOG(lb) (lb)->locked--;
437 typedef struct _StatBuffer StatBuffer;
446 typedef struct _BinaryObject BinaryObject;
448 struct _BinaryObject {
454 struct _MonoProfiler {
455 StatBuffer *stat_buffers;
457 #if defined (HAVE_SYS_ZLIB)
460 uint64_t startup_time;
462 int last_gc_gen_started;
467 pthread_t helper_thread;
468 pthread_t writer_thread;
470 volatile gint32 run_writer_thread;
471 MonoLockFreeQueue writer_queue;
472 MonoConcurrentHashTable *method_table;
473 mono_mutex_t method_table_mutex;
474 BinaryObject *binary_objects;
475 GPtrArray *coverage_filters;
476 GPtrArray *sorted_sample_events;
479 typedef struct _WriterQueueEntry WriterQueueEntry;
480 struct _WriterQueueEntry {
481 MonoLockFreeQueueNode node;
486 typedef struct _MethodInfo MethodInfo;
497 #define TLS_SET(x,y) (TlsSetValue (x, y))
498 #define TLS_GET(t,x) ((t *) TlsGetValue (x))
499 #define TLS_INIT(x) (x = TlsAlloc ())
500 static int tlsbuffer;
501 static int tlsmethodlist;
503 #define TLS_SET(x,y) (x = y)
504 #define TLS_GET(t,x) (x)
506 static __thread LogBuffer* tlsbuffer = NULL;
507 static __thread GPtrArray* tlsmethodlist = NULL;
509 #define TLS_SET(x,y) (pthread_setspecific (x, y))
510 #define TLS_GET(t,x) ((t *) pthread_getspecific (x))
511 #define TLS_INIT(x) (pthread_key_create (&x, NULL))
512 static pthread_key_t tlsbuffer;
513 static pthread_key_t tlsmethodlist;
516 static void safe_send (MonoProfiler *profiler, LogBuffer *logbuffer);
519 pstrdup (const char *s)
521 int len = strlen (s) + 1;
522 char *p = malloc (len);
528 create_stat_buffer (void)
530 StatBuffer* buf = alloc_buffer (BUFFER_SIZE);
531 buf->size = BUFFER_SIZE;
532 buf->data_end = (uintptr_t*)((unsigned char*)buf + buf->size);
533 buf->data = buf->buf;
540 LogBuffer* buf = alloc_buffer (BUFFER_SIZE);
541 buf->size = BUFFER_SIZE;
542 buf->time_base = current_time ();
543 buf->last_time = buf->time_base;
544 buf->data_end = (unsigned char*)buf + buf->size;
545 buf->data = buf->buf;
552 if (!TLS_GET (LogBuffer, tlsbuffer)) {
553 LogBuffer *logbuffer = create_buffer ();
554 TLS_SET (tlsbuffer, logbuffer);
555 logbuffer->thread_id = thread_id ();
557 if (!TLS_GET (GPtrArray, tlsmethodlist)) {
558 GPtrArray *methodlist = g_ptr_array_new ();
559 TLS_SET (tlsmethodlist, methodlist);
562 //printf ("thread %p at time %llu\n", (void*)logbuffer->thread_id, logbuffer->time_base);
566 ensure_logbuf_inner (LogBuffer *old, int bytes)
568 if (old && old->data + bytes + 100 < old->data_end)
571 LogBuffer *new = create_buffer ();
572 new->thread_id = thread_id ();
576 new->call_depth = old->call_depth;
582 ensure_logbuf (int bytes)
584 LogBuffer *old = TLS_GET (LogBuffer, tlsbuffer);
585 LogBuffer *new = ensure_logbuf_inner (old, bytes);
588 return old; // Still enough space.
590 TLS_SET (tlsbuffer, new);
597 emit_byte (LogBuffer *logbuffer, int value)
599 logbuffer->data [0] = value;
601 assert (logbuffer->data <= logbuffer->data_end);
605 emit_value (LogBuffer *logbuffer, int value)
607 encode_uleb128 (value, logbuffer->data, &logbuffer->data);
608 assert (logbuffer->data <= logbuffer->data_end);
612 emit_time (LogBuffer *logbuffer, uint64_t value)
614 uint64_t tdiff = value - logbuffer->last_time;
615 if (value < logbuffer->last_time)
616 printf ("time went backwards\n");
617 //if (tdiff > 1000000)
618 // printf ("large time offset: %llu\n", tdiff);
619 encode_uleb128 (tdiff, logbuffer->data, &logbuffer->data);
620 /*if (tdiff != decode_uleb128 (p, &p))
621 printf ("incorrect encoding: %llu\n", tdiff);*/
622 logbuffer->last_time = value;
623 assert (logbuffer->data <= logbuffer->data_end);
627 emit_svalue (LogBuffer *logbuffer, int64_t value)
629 encode_sleb128 (value, logbuffer->data, &logbuffer->data);
630 assert (logbuffer->data <= logbuffer->data_end);
634 emit_uvalue (LogBuffer *logbuffer, uint64_t value)
636 encode_uleb128 (value, logbuffer->data, &logbuffer->data);
637 assert (logbuffer->data <= logbuffer->data_end);
641 emit_ptr (LogBuffer *logbuffer, void *ptr)
643 if (!logbuffer->ptr_base)
644 logbuffer->ptr_base = (uintptr_t)ptr;
645 emit_svalue (logbuffer, (intptr_t)ptr - logbuffer->ptr_base);
646 assert (logbuffer->data <= logbuffer->data_end);
650 emit_method_inner (LogBuffer *logbuffer, void *method)
652 if (!logbuffer->method_base) {
653 logbuffer->method_base = (intptr_t)method;
654 logbuffer->last_method = (intptr_t)method;
656 encode_sleb128 ((intptr_t)((char*)method - (char*)logbuffer->last_method), logbuffer->data, &logbuffer->data);
657 logbuffer->last_method = (intptr_t)method;
658 assert (logbuffer->data <= logbuffer->data_end);
667 find_method (MonoDomain *domain, void *user_data)
669 MethodSearch *search = user_data;
674 MonoJitInfo *ji = mono_get_jit_info_from_method (domain, search->method);
676 // It could be AOT'd, so we need to get it from the AOT runtime's cache.
678 void *ip = mono_aot_get_method (domain, search->method);
680 // Avoid a slow path in mono_jit_info_table_find ().
682 ji = mono_jit_info_table_find (domain, ip);
690 register_method_local (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji)
692 if (!mono_conc_hashtable_lookup (prof->method_table, method)) {
694 MethodSearch search = { method, NULL };
696 mono_domain_foreach (find_method, &search);
703 MethodInfo *info = malloc (sizeof (MethodInfo));
705 info->method = method;
708 g_ptr_array_add (TLS_GET (GPtrArray, tlsmethodlist), info);
713 emit_method (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
715 register_method_local (prof, method, NULL);
716 emit_method_inner (logbuffer, method);
720 emit_method_as_ptr (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
722 register_method_local (prof, method, NULL);
723 emit_ptr (logbuffer, method);
727 emit_obj (LogBuffer *logbuffer, void *ptr)
729 if (!logbuffer->obj_base)
730 logbuffer->obj_base = (uintptr_t)ptr >> 3;
731 emit_svalue (logbuffer, ((uintptr_t)ptr >> 3) - logbuffer->obj_base);
732 assert (logbuffer->data <= logbuffer->data_end);
736 emit_string (LogBuffer *logbuffer, const char *str, size_t size)
740 for (; i < size; i++) {
743 emit_byte (logbuffer, str [i]);
746 emit_byte (logbuffer, '\0');
750 emit_double (LogBuffer *logbuffer, double value)
753 unsigned char buffer[8];
754 memcpy (buffer, &value, 8);
755 #if G_BYTE_ORDER == G_BIG_ENDIAN
756 for (i = 7; i >= 0; i--)
758 for (i = 0; i < 8; i++)
760 emit_byte (logbuffer, buffer[i]);
764 write_int16 (char *buf, int32_t value)
767 for (i = 0; i < 2; ++i) {
775 write_int32 (char *buf, int32_t value)
778 for (i = 0; i < 4; ++i) {
786 write_int64 (char *buf, int64_t value)
789 for (i = 0; i < 8; ++i) {
797 dump_header (MonoProfiler *profiler)
801 p = write_int32 (p, LOG_HEADER_ID);
802 *p++ = LOG_VERSION_MAJOR;
803 *p++ = LOG_VERSION_MINOR;
804 *p++ = LOG_DATA_VERSION;
805 *p++ = sizeof (void*);
806 p = write_int64 (p, ((uint64_t)time (NULL)) * 1000); /* startup time */
807 p = write_int32 (p, get_timer_overhead ()); /* timer overhead */
808 p = write_int32 (p, 0); /* flags */
809 p = write_int32 (p, process_id ()); /* pid */
810 p = write_int16 (p, profiler->command_port); /* port */
811 p = write_int16 (p, 0); /* opsystem */
812 #if defined (HAVE_SYS_ZLIB)
813 if (profiler->gzfile) {
814 gzwrite (profiler->gzfile, hbuf, p - hbuf);
816 fwrite (hbuf, p - hbuf, 1, profiler->file);
819 fwrite (hbuf, p - hbuf, 1, profiler->file);
820 fflush (profiler->file);
825 send_buffer (MonoProfiler *prof, GPtrArray *methods, LogBuffer *buffer)
827 WriterQueueEntry *entry = calloc (1, sizeof (WriterQueueEntry));
828 mono_lock_free_queue_node_init (&entry->node, FALSE);
829 entry->methods = methods;
830 entry->buffer = buffer;
831 mono_lock_free_queue_enqueue (&prof->writer_queue, &entry->node);
835 dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
840 dump_buffer (profiler, buf->next);
841 p = write_int32 (p, BUF_ID);
842 p = write_int32 (p, buf->data - buf->buf);
843 p = write_int64 (p, buf->time_base);
844 p = write_int64 (p, buf->ptr_base);
845 p = write_int64 (p, buf->obj_base);
846 p = write_int64 (p, buf->thread_id);
847 p = write_int64 (p, buf->method_base);
848 #if defined (HAVE_SYS_ZLIB)
849 if (profiler->gzfile) {
850 gzwrite (profiler->gzfile, hbuf, p - hbuf);
851 gzwrite (profiler->gzfile, buf->buf, buf->data - buf->buf);
854 fwrite (hbuf, p - hbuf, 1, profiler->file);
855 fwrite (buf->buf, buf->data - buf->buf, 1, profiler->file);
856 fflush (profiler->file);
857 #if defined (HAVE_SYS_ZLIB)
860 free_buffer (buf, buf->size);
864 process_requests (MonoProfiler *profiler)
866 if (heapshot_requested)
867 mono_gc_collect (mono_gc_max_generation ());
870 static void counters_init (MonoProfiler *profiler);
871 static void counters_sample (MonoProfiler *profiler, uint64_t timestamp);
874 * Can be called only at safe callback locations.
877 safe_send (MonoProfiler *profiler, LogBuffer *logbuffer)
879 /* We need the runtime initialized so that we have threads and hazard
880 * pointers available. Otherwise, the lock free queue will not work and
881 * there won't be a thread to process the data.
883 * While the runtime isn't initialized, we just accumulate data in the
884 * thread local buffer list.
886 if (!InterlockedRead (&runtime_inited))
889 int cd = logbuffer->call_depth;
891 send_buffer (profiler, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
893 TLS_SET (tlsbuffer, NULL);
894 TLS_SET (tlsmethodlist, NULL);
898 TLS_GET (LogBuffer, tlsbuffer)->call_depth = cd;
902 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
905 uintptr_t last_offset = 0;
906 //const char *name = mono_class_get_name (klass);
907 LogBuffer *logbuffer = ensure_logbuf (
908 EVENT_SIZE /* event */ +
909 LEB128_SIZE /* obj */ +
910 LEB128_SIZE /* klass */ +
911 LEB128_SIZE /* size */ +
912 LEB128_SIZE /* num */ +
914 LEB128_SIZE /* offset */ +
915 LEB128_SIZE /* ref */
918 emit_byte (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
919 emit_obj (logbuffer, obj);
920 emit_ptr (logbuffer, klass);
921 /* account for object alignment in the heap */
924 emit_value (logbuffer, size);
925 emit_value (logbuffer, num);
926 for (i = 0; i < num; ++i) {
927 emit_value (logbuffer, offsets [i] - last_offset);
928 last_offset = offsets [i];
929 emit_obj (logbuffer, refs [i]);
932 // printf ("obj: %p, klass: %s, refs: %d, size: %d\n", obj, name, (int)num, (int)size);
936 static unsigned int hs_mode_ms = 0;
937 static unsigned int hs_mode_gc = 0;
938 static unsigned int hs_mode_ondemand = 0;
939 static unsigned int gc_count = 0;
940 static uint64_t last_hs_time = 0;
943 heap_walk (MonoProfiler *profiler)
947 LogBuffer *logbuffer;
950 logbuffer = ensure_logbuf (
951 EVENT_SIZE /* event */ +
952 LEB128_SIZE /* time */
954 now = current_time ();
955 if (hs_mode_ms && (now - last_hs_time)/1000000 >= hs_mode_ms)
957 else if (hs_mode_gc && (gc_count % hs_mode_gc) == 0)
959 else if (hs_mode_ondemand)
960 do_walk = heapshot_requested;
961 else if (!hs_mode_ms && !hs_mode_gc && profiler->last_gc_gen_started == mono_gc_max_generation ())
966 heapshot_requested = 0;
967 emit_byte (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
968 emit_time (logbuffer, now);
969 mono_gc_walk_heap (0, gc_reference, NULL);
970 logbuffer = ensure_logbuf (
971 EVENT_SIZE /* event */ +
972 LEB128_SIZE /* time */
974 now = current_time ();
975 emit_byte (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
976 emit_time (logbuffer, now);
981 gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation) {
983 LogBuffer *logbuffer = ensure_logbuf (
984 EVENT_SIZE /* event */ +
985 LEB128_SIZE /* time */ +
986 LEB128_SIZE /* gc event */ +
987 LEB128_SIZE /* generation */
989 now = current_time ();
990 ENTER_LOG (logbuffer, "gcevent");
991 emit_byte (logbuffer, TYPE_GC_EVENT | TYPE_GC);
992 emit_time (logbuffer, now);
993 emit_value (logbuffer, ev);
994 emit_value (logbuffer, generation);
995 /* to deal with nested gen1 after gen0 started */
996 if (ev == MONO_GC_EVENT_START) {
997 profiler->last_gc_gen_started = generation;
998 if (generation == mono_gc_max_generation ())
1001 if (ev == MONO_GC_EVENT_PRE_START_WORLD)
1002 heap_walk (profiler);
1003 EXIT_LOG (logbuffer);
1004 if (ev == MONO_GC_EVENT_POST_START_WORLD)
1005 safe_send (profiler, logbuffer);
1006 //printf ("gc event %d for generation %d\n", ev, generation);
1010 gc_resize (MonoProfiler *profiler, int64_t new_size) {
1012 LogBuffer *logbuffer = ensure_logbuf (
1013 EVENT_SIZE /* event */ +
1014 LEB128_SIZE /* time */ +
1015 LEB128_SIZE /* new size */
1017 now = current_time ();
1018 ENTER_LOG (logbuffer, "gcresize");
1019 emit_byte (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
1020 emit_time (logbuffer, now);
1021 emit_value (logbuffer, new_size);
1022 //printf ("gc resized to %lld\n", new_size);
1023 EXIT_LOG (logbuffer);
1026 #define MAX_FRAMES 32
1029 MonoMethod* methods [MAX_FRAMES];
1030 int32_t il_offsets [MAX_FRAMES];
1031 int32_t native_offsets [MAX_FRAMES];
1033 static int num_frames = MAX_FRAMES;
1036 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
1038 FrameData *frame = data;
1039 if (method && frame->count < num_frames) {
1040 frame->il_offsets [frame->count] = il_offset;
1041 frame->native_offsets [frame->count] = native_offset;
1042 frame->methods [frame->count++] = method;
1043 //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
1045 return frame->count == num_frames;
1049 * a note about stack walks: they can cause more profiler events to fire,
1050 * so we need to make sure they don't happen after we started emitting an
1051 * event, hence the collect_bt/emit_bt split.
1054 collect_bt (FrameData *data)
1057 mono_stack_walk_no_il (walk_stack, data);
1061 emit_bt (MonoProfiler *prof, LogBuffer *logbuffer, FrameData *data)
1063 /* FIXME: this is actually tons of data and we should
1064 * just output it the first time and use an id the next
1066 if (data->count > num_frames)
1067 printf ("bad num frames: %d\n", data->count);
1068 emit_value (logbuffer, 0); /* flags */
1069 emit_value (logbuffer, data->count);
1070 //if (*p != data.count) {
1071 // 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);}
1072 while (data->count) {
1073 emit_method_as_ptr (prof, logbuffer, data->methods [--data->count]);
1078 gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1082 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces)? TYPE_ALLOC_BT: 0;
1084 LogBuffer *logbuffer;
1085 len = mono_object_get_size (obj);
1086 /* account for object alignment in the heap */
1091 logbuffer = ensure_logbuf (
1092 EVENT_SIZE /* event */ +
1093 LEB128_SIZE /* time */ +
1094 LEB128_SIZE /* klass */ +
1095 LEB128_SIZE /* obj */ +
1096 LEB128_SIZE /* size */ +
1098 LEB128_SIZE /* flags */ +
1099 LEB128_SIZE /* count */ +
1101 LEB128_SIZE /* method */
1105 now = current_time ();
1106 ENTER_LOG (logbuffer, "gcalloc");
1107 emit_byte (logbuffer, do_bt | TYPE_ALLOC);
1108 emit_time (logbuffer, now);
1109 emit_ptr (logbuffer, klass);
1110 emit_obj (logbuffer, obj);
1111 emit_value (logbuffer, len);
1113 emit_bt (prof, logbuffer, &data);
1114 EXIT_LOG (logbuffer);
1115 if (logbuffer->next)
1116 safe_send (prof, logbuffer);
1117 process_requests (prof);
1118 //printf ("gc alloc %s at %p\n", mono_class_get_name (klass), obj);
1122 gc_moves (MonoProfiler *prof, void **objects, int num)
1126 LogBuffer *logbuffer = ensure_logbuf (
1127 EVENT_SIZE /* event */ +
1128 LEB128_SIZE /* time */ +
1129 LEB128_SIZE /* num */ +
1131 LEB128_SIZE /* object */
1134 now = current_time ();
1135 ENTER_LOG (logbuffer, "gcmove");
1136 emit_byte (logbuffer, TYPE_GC_MOVE | TYPE_GC);
1137 emit_time (logbuffer, now);
1138 emit_value (logbuffer, num);
1139 for (i = 0; i < num; ++i)
1140 emit_obj (logbuffer, objects [i]);
1141 //printf ("gc moved %d objects\n", num/2);
1142 EXIT_LOG (logbuffer);
1146 gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
1149 LogBuffer *logbuffer = ensure_logbuf (
1150 EVENT_SIZE /* event */ +
1151 LEB128_SIZE /* num */ +
1152 LEB128_SIZE /* collections */ +
1154 LEB128_SIZE /* object */ +
1155 LEB128_SIZE /* root type */ +
1156 LEB128_SIZE /* extra info */
1159 ENTER_LOG (logbuffer, "gcroots");
1160 emit_byte (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
1161 emit_value (logbuffer, num);
1162 emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
1163 for (i = 0; i < num; ++i) {
1164 emit_obj (logbuffer, objects [i]);
1165 emit_value (logbuffer, root_types [i]);
1166 emit_value (logbuffer, extra_info [i]);
1168 EXIT_LOG (logbuffer);
1172 gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
1174 int do_bt = nocalls && InterlockedRead (&runtime_inited) && !notraces;
1181 LogBuffer *logbuffer = ensure_logbuf (
1182 EVENT_SIZE /* event */ +
1183 LEB128_SIZE /* time */ +
1184 LEB128_SIZE /* type */ +
1185 LEB128_SIZE /* handle */ +
1186 (op == MONO_PROFILER_GC_HANDLE_CREATED ? (
1187 LEB128_SIZE /* obj */
1190 LEB128_SIZE /* flags */ +
1191 LEB128_SIZE /* count */ +
1193 LEB128_SIZE /* method */
1198 now = current_time ();
1199 ENTER_LOG (logbuffer, "gchandle");
1201 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1202 emit_byte (logbuffer, (do_bt ? TYPE_GC_HANDLE_CREATED_BT : TYPE_GC_HANDLE_CREATED) | TYPE_GC);
1203 else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
1204 emit_byte (logbuffer, (do_bt ? TYPE_GC_HANDLE_DESTROYED_BT : TYPE_GC_HANDLE_DESTROYED) | TYPE_GC);
1206 g_assert_not_reached ();
1208 emit_time (logbuffer, now);
1209 emit_value (logbuffer, type);
1210 emit_value (logbuffer, handle);
1212 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1213 emit_obj (logbuffer, obj);
1216 emit_bt (prof, logbuffer, &data);
1218 EXIT_LOG (logbuffer);
1219 process_requests (prof);
1223 push_nesting (char *p, MonoClass *klass)
1228 nesting = mono_class_get_nesting_type (klass);
1230 p = push_nesting (p, nesting);
1234 name = mono_class_get_name (klass);
1235 nspace = mono_class_get_namespace (klass);
1238 p += strlen (nspace);
1248 type_name (MonoClass *klass)
1252 push_nesting (buf, klass);
1253 p = malloc (strlen (buf) + 1);
1259 image_loaded (MonoProfiler *prof, MonoImage *image, int result)
1264 LogBuffer *logbuffer;
1265 if (result != MONO_PROFILE_OK)
1267 name = mono_image_get_filename (image);
1268 nlen = strlen (name) + 1;
1269 logbuffer = ensure_logbuf (
1270 EVENT_SIZE /* event */ +
1271 LEB128_SIZE /* time */ +
1272 EVENT_SIZE /* type */ +
1273 LEB128_SIZE /* image */ +
1274 LEB128_SIZE /* flags */ +
1277 now = current_time ();
1278 ENTER_LOG (logbuffer, "image");
1279 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1280 emit_time (logbuffer, now);
1281 emit_byte (logbuffer, TYPE_IMAGE);
1282 emit_ptr (logbuffer, image);
1283 emit_value (logbuffer, 0); /* flags */
1284 memcpy (logbuffer->data, name, nlen);
1285 logbuffer->data += nlen;
1286 //printf ("loaded image %p (%s)\n", image, name);
1287 EXIT_LOG (logbuffer);
1288 if (logbuffer->next)
1289 safe_send (prof, logbuffer);
1290 process_requests (prof);
1294 image_unloaded (MonoProfiler *prof, MonoImage *image)
1296 const char *name = mono_image_get_filename (image);
1297 int nlen = strlen (name) + 1;
1298 LogBuffer *logbuffer = ensure_logbuf (
1299 EVENT_SIZE /* event */ +
1300 LEB128_SIZE /* time */ +
1301 EVENT_SIZE /* type */ +
1302 LEB128_SIZE /* image */ +
1303 LEB128_SIZE /* flags */ +
1306 uint64_t now = current_time ();
1308 ENTER_LOG (logbuffer, "image-unload");
1309 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1310 emit_time (logbuffer, now);
1311 emit_byte (logbuffer, TYPE_IMAGE);
1312 emit_ptr (logbuffer, image);
1313 emit_value (logbuffer, 0); /* flags */
1314 memcpy (logbuffer->data, name, nlen);
1315 logbuffer->data += nlen;
1316 EXIT_LOG (logbuffer);
1318 if (logbuffer->next)
1319 safe_send (prof, logbuffer);
1321 process_requests (prof);
1325 assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly, int result)
1327 if (result != MONO_PROFILE_OK)
1330 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1331 int nlen = strlen (name) + 1;
1332 LogBuffer *logbuffer = ensure_logbuf (
1333 EVENT_SIZE /* event */ +
1334 LEB128_SIZE /* time */ +
1335 EVENT_SIZE /* type */ +
1336 LEB128_SIZE /* assembly */ +
1337 LEB128_SIZE /* flags */ +
1340 uint64_t now = current_time ();
1342 ENTER_LOG (logbuffer, "assembly-load");
1343 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1344 emit_time (logbuffer, now);
1345 emit_byte (logbuffer, TYPE_ASSEMBLY);
1346 emit_ptr (logbuffer, assembly);
1347 emit_value (logbuffer, 0); /* flags */
1348 memcpy (logbuffer->data, name, nlen);
1349 logbuffer->data += nlen;
1350 EXIT_LOG (logbuffer);
1354 if (logbuffer->next)
1355 safe_send (prof, logbuffer);
1357 process_requests (prof);
1361 assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
1363 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1364 int nlen = strlen (name) + 1;
1365 LogBuffer *logbuffer = ensure_logbuf (
1366 EVENT_SIZE /* event */ +
1367 LEB128_SIZE /* time */ +
1368 EVENT_SIZE /* type */ +
1369 LEB128_SIZE /* assembly */ +
1370 LEB128_SIZE /* flags */ +
1373 uint64_t now = current_time ();
1375 ENTER_LOG (logbuffer, "assembly-unload");
1376 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1377 emit_time (logbuffer, now);
1378 emit_byte (logbuffer, TYPE_ASSEMBLY);
1379 emit_ptr (logbuffer, assembly);
1380 emit_value (logbuffer, 0); /* flags */
1381 memcpy (logbuffer->data, name, nlen);
1382 logbuffer->data += nlen;
1383 EXIT_LOG (logbuffer);
1387 if (logbuffer->next)
1388 safe_send (prof, logbuffer);
1390 process_requests (prof);
1394 class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
1400 LogBuffer *logbuffer;
1401 if (result != MONO_PROFILE_OK)
1403 if (InterlockedRead (&runtime_inited))
1404 name = mono_type_get_name (mono_class_get_type (klass));
1406 name = type_name (klass);
1407 nlen = strlen (name) + 1;
1408 image = mono_class_get_image (klass);
1409 logbuffer = ensure_logbuf (
1410 EVENT_SIZE /* event */ +
1411 LEB128_SIZE /* time */ +
1412 EVENT_SIZE /* type */ +
1413 LEB128_SIZE /* klass */ +
1414 LEB128_SIZE /* image */ +
1415 LEB128_SIZE /* flags */ +
1418 now = current_time ();
1419 ENTER_LOG (logbuffer, "class");
1420 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1421 emit_time (logbuffer, now);
1422 emit_byte (logbuffer, TYPE_CLASS);
1423 emit_ptr (logbuffer, klass);
1424 emit_ptr (logbuffer, image);
1425 emit_value (logbuffer, 0); /* flags */
1426 memcpy (logbuffer->data, name, nlen);
1427 logbuffer->data += nlen;
1428 //printf ("loaded class %p (%s)\n", klass, name);
1433 EXIT_LOG (logbuffer);
1434 if (logbuffer->next)
1435 safe_send (prof, logbuffer);
1436 process_requests (prof);
1440 class_unloaded (MonoProfiler *prof, MonoClass *klass)
1444 if (InterlockedRead (&runtime_inited))
1445 name = mono_type_get_name (mono_class_get_type (klass));
1447 name = type_name (klass);
1449 int nlen = strlen (name) + 1;
1450 MonoImage *image = mono_class_get_image (klass);
1451 LogBuffer *logbuffer = ensure_logbuf (
1452 EVENT_SIZE /* event */ +
1453 LEB128_SIZE /* time */ +
1454 EVENT_SIZE /* type */ +
1455 LEB128_SIZE /* klass */ +
1456 LEB128_SIZE /* image */ +
1457 LEB128_SIZE /* flags */ +
1460 uint64_t now = current_time ();
1462 ENTER_LOG (logbuffer, "class-unload");
1463 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1464 emit_time (logbuffer, now);
1465 emit_byte (logbuffer, TYPE_CLASS);
1466 emit_ptr (logbuffer, klass);
1467 emit_ptr (logbuffer, image);
1468 emit_value (logbuffer, 0); /* flags */
1469 memcpy (logbuffer->data, name, nlen);
1470 logbuffer->data += nlen;
1471 EXIT_LOG (logbuffer);
1478 if (logbuffer->next)
1479 safe_send (prof, logbuffer);
1481 process_requests (prof);
1484 #ifndef DISABLE_HELPER_THREAD
1485 static void process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method);
1486 #endif /* DISABLE_HELPER_THREAD */
1489 method_enter (MonoProfiler *prof, MonoMethod *method)
1491 uint64_t now = current_time ();
1493 #ifndef DISABLE_HELPER_THREAD
1494 process_method_enter_coverage (prof, method);
1495 #endif /* DISABLE_HELPER_THREAD */
1497 LogBuffer *logbuffer = ensure_logbuf (
1498 EVENT_SIZE /* event */ +
1499 LEB128_SIZE /* time */ +
1500 LEB128_SIZE /* method */
1502 if (logbuffer->call_depth++ > max_call_depth)
1504 ENTER_LOG (logbuffer, "enter");
1505 emit_byte (logbuffer, TYPE_ENTER | TYPE_METHOD);
1506 emit_time (logbuffer, now);
1507 emit_method (prof, logbuffer, method);
1508 EXIT_LOG (logbuffer);
1510 process_requests (prof);
1514 method_leave (MonoProfiler *prof, MonoMethod *method)
1517 LogBuffer *logbuffer = ensure_logbuf (
1518 EVENT_SIZE /* event */ +
1519 LEB128_SIZE /* time */ +
1520 LEB128_SIZE /* method */
1522 if (--logbuffer->call_depth > max_call_depth)
1524 now = current_time ();
1525 ENTER_LOG (logbuffer, "leave");
1526 emit_byte (logbuffer, TYPE_LEAVE | TYPE_METHOD);
1527 emit_time (logbuffer, now);
1528 emit_method (prof, logbuffer, method);
1529 EXIT_LOG (logbuffer);
1530 if (logbuffer->next)
1531 safe_send (prof, logbuffer);
1532 process_requests (prof);
1536 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
1539 LogBuffer *logbuffer;
1542 logbuffer = ensure_logbuf (
1543 EVENT_SIZE /* event */ +
1544 LEB128_SIZE /* time */ +
1545 LEB128_SIZE /* method */
1547 if (--logbuffer->call_depth > max_call_depth)
1549 now = current_time ();
1550 ENTER_LOG (logbuffer, "eleave");
1551 emit_byte (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
1552 emit_time (logbuffer, now);
1553 emit_method (prof, logbuffer, method);
1554 EXIT_LOG (logbuffer);
1555 process_requests (prof);
1559 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji, int result)
1561 if (result != MONO_PROFILE_OK)
1564 register_method_local (prof, method, ji);
1566 process_requests (prof);
1570 code_buffer_new (MonoProfiler *prof, void *buffer, int size, MonoProfilerCodeBufferType type, void *data)
1575 LogBuffer *logbuffer;
1576 if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
1578 nlen = strlen (name) + 1;
1583 logbuffer = ensure_logbuf (
1584 EVENT_SIZE /* event */ +
1585 LEB128_SIZE /* time */ +
1586 LEB128_SIZE /* type */ +
1587 LEB128_SIZE /* buffer */ +
1588 LEB128_SIZE /* size */ +
1593 now = current_time ();
1594 ENTER_LOG (logbuffer, "code buffer");
1595 emit_byte (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
1596 emit_time (logbuffer, now);
1597 emit_value (logbuffer, type);
1598 emit_ptr (logbuffer, buffer);
1599 emit_value (logbuffer, size);
1601 memcpy (logbuffer->data, name, nlen);
1602 logbuffer->data += nlen;
1604 EXIT_LOG (logbuffer);
1605 process_requests (prof);
1609 throw_exc (MonoProfiler *prof, MonoObject *object)
1611 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces)? TYPE_EXCEPTION_BT: 0;
1614 LogBuffer *logbuffer;
1617 logbuffer = ensure_logbuf (
1618 EVENT_SIZE /* event */ +
1619 LEB128_SIZE /* time */ +
1620 LEB128_SIZE /* object */ +
1622 LEB128_SIZE /* flags */ +
1623 LEB128_SIZE /* count */ +
1625 LEB128_SIZE /* method */
1629 now = current_time ();
1630 ENTER_LOG (logbuffer, "throw");
1631 emit_byte (logbuffer, do_bt | TYPE_EXCEPTION);
1632 emit_time (logbuffer, now);
1633 emit_obj (logbuffer, object);
1635 emit_bt (prof, logbuffer, &data);
1636 EXIT_LOG (logbuffer);
1637 process_requests (prof);
1641 clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
1644 LogBuffer *logbuffer = ensure_logbuf (
1645 EVENT_SIZE /* event */ +
1646 LEB128_SIZE /* time */ +
1647 LEB128_SIZE /* clause type */ +
1648 LEB128_SIZE /* clause num */ +
1649 LEB128_SIZE /* method */
1651 now = current_time ();
1652 ENTER_LOG (logbuffer, "clause");
1653 emit_byte (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
1654 emit_time (logbuffer, now);
1655 emit_value (logbuffer, clause_type);
1656 emit_value (logbuffer, clause_num);
1657 emit_method (prof, logbuffer, method);
1658 EXIT_LOG (logbuffer);
1660 process_requests (prof);
1664 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
1666 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION)? TYPE_MONITOR_BT: 0;
1669 LogBuffer *logbuffer;
1672 logbuffer = ensure_logbuf (
1673 EVENT_SIZE /* event */ +
1674 LEB128_SIZE /* time */ +
1675 LEB128_SIZE /* object */ +
1677 LEB128_SIZE /* flags */ +
1678 LEB128_SIZE /* count */ +
1680 LEB128_SIZE /* method */
1684 now = current_time ();
1685 ENTER_LOG (logbuffer, "monitor");
1686 emit_byte (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
1687 emit_time (logbuffer, now);
1688 emit_obj (logbuffer, object);
1690 emit_bt (profiler, logbuffer, &data);
1691 EXIT_LOG (logbuffer);
1692 process_requests (profiler);
1696 thread_start (MonoProfiler *prof, uintptr_t tid)
1698 //printf ("thread start %p\n", (void*)tid);
1701 LogBuffer *logbuffer = ensure_logbuf (
1702 EVENT_SIZE /* event */ +
1703 LEB128_SIZE /* time */ +
1704 EVENT_SIZE /* type */ +
1705 LEB128_SIZE /* tid */ +
1706 LEB128_SIZE /* flags */
1708 uint64_t now = current_time ();
1710 ENTER_LOG (logbuffer, "thread-start");
1711 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1712 emit_time (logbuffer, now);
1713 emit_byte (logbuffer, TYPE_THREAD);
1714 emit_ptr (logbuffer, (void*) tid);
1715 emit_value (logbuffer, 0); /* flags */
1716 EXIT_LOG (logbuffer);
1718 if (logbuffer->next)
1719 safe_send (prof, logbuffer);
1721 process_requests (prof);
1725 thread_end (MonoProfiler *prof, uintptr_t tid)
1727 if (TLS_GET (LogBuffer, tlsbuffer)) {
1728 LogBuffer *logbuffer = ensure_logbuf (
1729 EVENT_SIZE /* event */ +
1730 LEB128_SIZE /* time */ +
1731 EVENT_SIZE /* type */ +
1732 LEB128_SIZE /* tid */ +
1733 LEB128_SIZE /* flags */
1735 uint64_t now = current_time ();
1737 ENTER_LOG (logbuffer, "thread-end");
1738 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1739 emit_time (logbuffer, now);
1740 emit_byte (logbuffer, TYPE_THREAD);
1741 emit_ptr (logbuffer, (void*) tid);
1742 emit_value (logbuffer, 0); /* flags */
1743 EXIT_LOG (logbuffer);
1745 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), logbuffer);
1747 /* Don't process requests as the thread is detached from the runtime. */
1750 TLS_SET (tlsbuffer, NULL);
1751 TLS_SET (tlsmethodlist, NULL);
1755 domain_loaded (MonoProfiler *prof, MonoDomain *domain, int result)
1757 if (result != MONO_PROFILE_OK)
1760 LogBuffer *logbuffer = ensure_logbuf (
1761 EVENT_SIZE /* event */ +
1762 LEB128_SIZE /* time */ +
1763 EVENT_SIZE /* type */ +
1764 LEB128_SIZE /* domain id */ +
1765 LEB128_SIZE /* flags */
1767 uint64_t now = current_time ();
1769 ENTER_LOG (logbuffer, "domain-start");
1770 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1771 emit_time (logbuffer, now);
1772 emit_byte (logbuffer, TYPE_DOMAIN);
1773 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1774 emit_value (logbuffer, 0); /* flags */
1775 EXIT_LOG (logbuffer);
1777 if (logbuffer->next)
1778 safe_send (prof, logbuffer);
1780 process_requests (prof);
1784 domain_unloaded (MonoProfiler *prof, MonoDomain *domain)
1786 LogBuffer *logbuffer = ensure_logbuf (
1787 EVENT_SIZE /* event */ +
1788 LEB128_SIZE /* time */ +
1789 EVENT_SIZE /* type */ +
1790 LEB128_SIZE /* domain id */ +
1791 LEB128_SIZE /* flags */
1793 uint64_t now = current_time ();
1795 ENTER_LOG (logbuffer, "domain-end");
1796 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1797 emit_time (logbuffer, now);
1798 emit_byte (logbuffer, TYPE_DOMAIN);
1799 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1800 emit_value (logbuffer, 0); /* flags */
1801 EXIT_LOG (logbuffer);
1803 if (logbuffer->next)
1804 safe_send (prof, logbuffer);
1806 process_requests (prof);
1810 domain_name (MonoProfiler *prof, MonoDomain *domain, const char *name)
1812 int nlen = strlen (name) + 1;
1813 LogBuffer *logbuffer = ensure_logbuf (
1814 EVENT_SIZE /* event */ +
1815 LEB128_SIZE /* time */ +
1816 EVENT_SIZE /* type */ +
1817 LEB128_SIZE /* domain id */ +
1818 LEB128_SIZE /* flags */ +
1821 uint64_t now = current_time ();
1823 ENTER_LOG (logbuffer, "domain-name");
1824 emit_byte (logbuffer, TYPE_METADATA);
1825 emit_time (logbuffer, now);
1826 emit_byte (logbuffer, TYPE_DOMAIN);
1827 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1828 emit_value (logbuffer, 0); /* flags */
1829 memcpy (logbuffer->data, name, nlen);
1830 logbuffer->data += nlen;
1831 EXIT_LOG (logbuffer);
1833 if (logbuffer->next)
1834 safe_send (prof, logbuffer);
1836 process_requests (prof);
1840 context_loaded (MonoProfiler *prof, MonoAppContext *context)
1842 LogBuffer *logbuffer = ensure_logbuf (
1843 EVENT_SIZE /* event */ +
1844 LEB128_SIZE /* time */ +
1845 EVENT_SIZE /* type */ +
1846 LEB128_SIZE /* context id */ +
1847 LEB128_SIZE /* flags */ +
1848 LEB128_SIZE /* domain id */
1850 uint64_t now = current_time ();
1852 ENTER_LOG (logbuffer, "context-start");
1853 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1854 emit_time (logbuffer, now);
1855 emit_byte (logbuffer, TYPE_CONTEXT);
1856 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
1857 emit_value (logbuffer, 0); /* flags */
1858 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
1859 EXIT_LOG (logbuffer);
1861 if (logbuffer->next)
1862 safe_send (prof, logbuffer);
1864 process_requests (prof);
1868 context_unloaded (MonoProfiler *prof, MonoAppContext *context)
1870 LogBuffer *logbuffer = ensure_logbuf (
1871 EVENT_SIZE /* event */ +
1872 LEB128_SIZE /* time */ +
1873 EVENT_SIZE /* type */ +
1874 LEB128_SIZE /* context id */ +
1875 LEB128_SIZE /* flags */ +
1876 LEB128_SIZE /* domain id */
1878 uint64_t now = current_time ();
1880 ENTER_LOG (logbuffer, "context-end");
1881 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1882 emit_time (logbuffer, now);
1883 emit_byte (logbuffer, TYPE_CONTEXT);
1884 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
1885 emit_value (logbuffer, 0); /* flags */
1886 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
1887 EXIT_LOG (logbuffer);
1889 if (logbuffer->next)
1890 safe_send (prof, logbuffer);
1892 process_requests (prof);
1896 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
1898 int len = strlen (name) + 1;
1900 LogBuffer *logbuffer;
1901 logbuffer = ensure_logbuf (
1902 EVENT_SIZE /* event */ +
1903 LEB128_SIZE /* time */ +
1904 EVENT_SIZE /* type */ +
1905 LEB128_SIZE /* tid */ +
1906 LEB128_SIZE /* flags */ +
1909 now = current_time ();
1910 ENTER_LOG (logbuffer, "tname");
1911 emit_byte (logbuffer, TYPE_METADATA);
1912 emit_time (logbuffer, now);
1913 emit_byte (logbuffer, TYPE_THREAD);
1914 emit_ptr (logbuffer, (void*)tid);
1915 emit_value (logbuffer, 0); /* flags */
1916 memcpy (logbuffer->data, name, len);
1917 logbuffer->data += len;
1918 EXIT_LOG (logbuffer);
1920 if (logbuffer->next)
1921 safe_send (prof, logbuffer);
1923 process_requests (prof);
1935 AsyncFrameInfo *data;
1939 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
1941 AsyncFrameData *frame = data;
1942 if (frame->count < num_frames) {
1943 frame->data [frame->count].method = method;
1944 frame->data [frame->count].domain = domain;
1945 frame->data [frame->count].base_address = base_address;
1946 frame->data [frame->count].offset = offset;
1947 // printf ("In %d at %p (dom %p) (native: %p)\n", frame->count, method, domain, base_address);
1950 return frame->count == num_frames;
1954 (type | frame count), tid, time, ip, [method, domain, base address, offset] * frames
1956 #define SAMPLE_EVENT_SIZE_IN_SLOTS(FRAMES) (4 + (FRAMES) * 4)
1959 mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
1962 AsyncFrameInfo frames [num_frames];
1963 AsyncFrameData bt_data = { 0, &frames [0]};
1965 uintptr_t *data, *new_data, *old_data;
1971 now = current_time ();
1973 mono_stack_walk_async_safe (&async_walk_stack, context, &bt_data);
1975 elapsed = (now - profiler->startup_time) / 10000;
1979 snprintf (buf, sizeof (buf), "hit at %p in thread %p after %llu ms\n", ip, (void*)thread_id (), (unsigned long long int)elapsed/100);
1981 ign_res (write (2, buf, len));
1983 sbuf = profiler->stat_buffers;
1986 /* flush the buffer at 1 second intervals */
1987 if (sbuf->data > sbuf->buf && (elapsed - sbuf->buf [2]) > 100000) {
1990 /* overflow: 400 slots is a big enough number to reduce the chance of losing this event if many
1991 * threads hit this same spot at the same time
1993 if (timedout || (sbuf->data + 400 >= sbuf->data_end)) {
1994 StatBuffer *oldsb, *foundsb;
1995 sbuf = create_stat_buffer ();
1997 oldsb = profiler->stat_buffers;
1999 foundsb = InterlockedCompareExchangePointer ((void * volatile*)&profiler->stat_buffers, sbuf, oldsb);
2000 } while (foundsb != oldsb);
2002 ign_res (write (2, "overflow\n", 9));
2003 /* notify the helper thread */
2004 if (sbuf->next->next) {
2006 ign_res (write (profiler->pipes [1], &c, 1));
2008 ign_res (write (2, "notify\n", 7));
2012 old_data = sbuf->data;
2013 new_data = old_data + SAMPLE_EVENT_SIZE_IN_SLOTS (bt_data.count);
2014 data = InterlockedCompareExchangePointer ((void * volatile*)&sbuf->data, new_data, old_data);
2015 } while (data != old_data);
2016 if (old_data >= sbuf->data_end)
2017 return; /* lost event */
2018 old_data [0] = 1 | (sample_type << 16) | (bt_data.count << 8);
2019 old_data [1] = thread_id ();
2020 old_data [2] = elapsed;
2021 old_data [3] = (uintptr_t)ip;
2022 for (i = 0; i < bt_data.count; ++i) {
2023 old_data [4 + 4 * i + 0] = (uintptr_t)frames [i].method;
2024 old_data [4 + 4 * i + 1] = (uintptr_t)frames [i].domain;
2025 old_data [4 + 4 * i + 2] = (uintptr_t)frames [i].base_address;
2026 old_data [4 + 4 * i + 3] = (uintptr_t)frames [i].offset;
2030 static uintptr_t *code_pages = 0;
2031 static int num_code_pages = 0;
2032 static int size_code_pages = 0;
2033 #define CPAGE_SHIFT (9)
2034 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
2035 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
2036 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
2039 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
2042 uintptr_t start_pos;
2043 start_pos = (page >> CPAGE_SHIFT) % hsize;
2046 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
2048 } else if (!hash [i]) {
2055 } while (i != start_pos);
2056 /* should not happen */
2057 printf ("failed code page store\n");
2062 add_code_pointer (uintptr_t ip)
2065 if (num_code_pages * 2 >= size_code_pages) {
2067 uintptr_t old_size = size_code_pages;
2068 size_code_pages *= 2;
2069 if (size_code_pages == 0)
2070 size_code_pages = 16;
2071 n = calloc (sizeof (uintptr_t) * size_code_pages, 1);
2072 for (i = 0; i < old_size; ++i) {
2074 add_code_page (n, size_code_pages, code_pages [i]);
2080 num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
2083 /* ELF code crashes on some systems. */
2084 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2087 dump_ubin (const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
2090 LogBuffer *logbuffer;
2092 len = strlen (filename) + 1;
2093 now = current_time ();
2094 logbuffer = ensure_logbuf (
2095 EVENT_SIZE /* event */ +
2096 LEB128_SIZE /* time */ +
2097 LEB128_SIZE /* load address */ +
2098 LEB128_SIZE /* offset */ +
2099 LEB128_SIZE /* size */ +
2100 nlen /* file name */
2102 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
2103 emit_time (logbuffer, now);
2104 emit_svalue (logbuffer, load_addr);
2105 emit_uvalue (logbuffer, offset);
2106 emit_uvalue (logbuffer, size);
2107 memcpy (logbuffer->data, filename, len);
2108 logbuffer->data += len;
2113 dump_usym (const char *name, uintptr_t value, uintptr_t size)
2115 LogBuffer *logbuffer;
2117 len = strlen (name) + 1;
2118 logbuffer = ensure_logbuf (
2119 EVENT_SIZE /* event */ +
2120 LEB128_SIZE /* value */ +
2121 LEB128_SIZE /* size */ +
2124 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
2125 emit_ptr (logbuffer, (void*)value);
2126 emit_value (logbuffer, size);
2127 memcpy (logbuffer->data, name, len);
2128 logbuffer->data += len;
2131 /* ELF code crashes on some systems. */
2132 //#if defined(ELFMAG0)
2135 #if SIZEOF_VOID_P == 4
2136 #define ELF_WSIZE 32
2138 #define ELF_WSIZE 64
2141 #define ElfW(type) _ElfW (Elf, ELF_WSIZE, type)
2142 #define _ElfW(e,w,t) _ElfW_1 (e, w, _##t)
2143 #define _ElfW_1(e,w,t) e##w##t
2147 dump_elf_symbols (ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
2150 for (i = 0; i < num_symbols; ++i) {
2152 sym = strtab + symbols [i].st_name;
2153 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
2155 //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
2156 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
2161 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
2168 ElfW(Shdr) *sheader;
2169 ElfW(Shdr) *shstrtabh;
2170 ElfW(Shdr) *symtabh = NULL;
2171 ElfW(Shdr) *strtabh = NULL;
2172 ElfW(Sym) *symbols = NULL;
2176 fd = open (filename, O_RDONLY);
2179 if (fstat (fd, &statb) != 0) {
2183 file_size = statb.st_size;
2184 data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
2186 if (data == MAP_FAILED)
2189 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2190 header->e_ident [EI_MAG1] != ELFMAG1 ||
2191 header->e_ident [EI_MAG2] != ELFMAG2 ||
2192 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2193 munmap (data, file_size);
2196 sheader = (void*)((char*)data + header->e_shoff);
2197 shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
2198 strtab = (const char*)data + shstrtabh->sh_offset;
2199 for (i = 0; i < header->e_shnum; ++i) {
2200 //printf ("section header: %d\n", sheader->sh_type);
2201 if (sheader->sh_type == SHT_SYMTAB) {
2203 strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
2204 /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
2207 sheader = (void*)((char*)sheader + header->e_shentsize);
2209 if (!symtabh || !strtabh) {
2210 munmap (data, file_size);
2213 strtab = (const char*)data + strtabh->sh_offset;
2214 num_symbols = symtabh->sh_size / symtabh->sh_entsize;
2215 symbols = (void*)((char*)data + symtabh->sh_offset);
2216 dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
2217 munmap (data, file_size);
2222 /* ELF code crashes on some systems. */
2223 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2226 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
2228 MonoProfiler *prof = data;
2230 const char *filename;
2232 char *a = (void*)info->dlpi_addr;
2234 ElfW(Dyn) *dyn = NULL;
2235 ElfW(Sym) *symtab = NULL;
2236 ElfW(Word) *hash_table = NULL;
2237 ElfW(Ehdr) *header = NULL;
2238 const char* strtab = NULL;
2239 for (obj = prof->binary_objects; obj; obj = obj->next) {
2243 filename = info->dlpi_name;
2246 if (!info->dlpi_addr && !filename [0]) {
2247 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
2253 obj = calloc (sizeof (BinaryObject), 1);
2254 obj->addr = (void*)info->dlpi_addr;
2255 obj->name = pstrdup (filename);
2256 obj->next = prof->binary_objects;
2257 prof->binary_objects = obj;
2258 //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
2260 for (i = 0; i < info->dlpi_phnum; ++i) {
2261 //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);
2262 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
2263 header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2264 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2265 header->e_ident [EI_MAG1] != ELFMAG1 ||
2266 header->e_ident [EI_MAG2] != ELFMAG2 ||
2267 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2270 dump_ubin (filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
2271 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
2272 dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2275 if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
2277 if (!info->dlpi_name || !info->dlpi_name[0])
2281 for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
2282 if (dyn [i].d_tag == DT_SYMTAB) {
2283 if (symtab && do_debug)
2284 printf ("multiple symtabs: %d\n", i);
2285 symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
2286 } else if (dyn [i].d_tag == DT_HASH) {
2287 hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
2288 } else if (dyn [i].d_tag == DT_STRTAB) {
2289 strtab = (const char*)(a + dyn [i].d_un.d_ptr);
2294 num_sym = hash_table [1];
2295 dump_elf_symbols (symtab, num_sym, strtab, (void*)info->dlpi_addr);
2300 load_binaries (MonoProfiler *prof)
2302 dl_iterate_phdr (elf_dl_callback, prof);
2307 load_binaries (MonoProfiler *prof)
2314 symbol_for (uintptr_t code)
2317 void *ip = (void*)code;
2319 if (dladdr (ip, &di)) {
2321 return di.dli_sname;
2324 names = backtrace_symbols (&ip, 1);
2326 const char* p = names [0];
2337 dump_unmanaged_coderefs (MonoProfiler *prof)
2340 const char* last_symbol;
2341 uintptr_t addr, page_end;
2343 if (load_binaries (prof))
2345 for (i = 0; i < size_code_pages; ++i) {
2347 if (!code_pages [i] || code_pages [i] & 1)
2350 addr = CPAGE_ADDR (code_pages [i]);
2351 page_end = addr + CPAGE_SIZE;
2352 code_pages [i] |= 1;
2353 /* we dump the symbols for the whole page */
2354 for (; addr < page_end; addr += 16) {
2355 sym = symbol_for (addr);
2356 if (sym && sym == last_symbol)
2361 dump_usym (sym, addr, 0); /* let's not guess the size */
2362 //printf ("found symbol at %p: %s\n", (void*)addr, sym);
2368 compare_sample_events (gconstpointer a, gconstpointer b)
2370 uintptr_t tid1 = (*(uintptr_t **) a) [1];
2371 uintptr_t tid2 = (*(uintptr_t **) b) [1];
2373 return tid1 > tid2 ? 1 :
2379 dump_sample_hits (MonoProfiler *prof, StatBuffer *sbuf)
2381 LogBuffer *logbuffer;
2385 dump_sample_hits (prof, sbuf->next);
2386 free_buffer (sbuf->next, sbuf->next->size);
2390 g_ptr_array_set_size (prof->sorted_sample_events, 0);
2392 for (uintptr_t *sample = sbuf->buf; sample < sbuf->data;) {
2393 int count = sample [0] & 0xff;
2394 int mbt_count = (sample [0] & 0xff00) >> 8;
2396 if (sample + SAMPLE_EVENT_SIZE_IN_SLOTS (mbt_count) > sbuf->data)
2399 g_ptr_array_add (prof->sorted_sample_events, sample);
2401 sample += count + 3 + 4 * mbt_count;
2404 g_ptr_array_sort (prof->sorted_sample_events, compare_sample_events);
2406 for (guint sidx = 0; sidx < prof->sorted_sample_events->len; sidx++) {
2407 uintptr_t *sample = g_ptr_array_index (prof->sorted_sample_events, sidx);
2408 int count = sample [0] & 0xff;
2409 int mbt_count = (sample [0] & 0xff00) >> 8;
2410 int type = sample [0] >> 16;
2411 uintptr_t *managed_sample_base = sample + count + 3;
2412 uintptr_t thread_id = sample [1];
2414 for (int i = 0; i < mbt_count; ++i) {
2415 MonoMethod *method = (MonoMethod*)managed_sample_base [i * 4 + 0];
2416 MonoDomain *domain = (MonoDomain*)managed_sample_base [i * 4 + 1];
2417 void *address = (void*)managed_sample_base [i * 4 + 2];
2420 MonoJitInfo *ji = mono_jit_info_table_find (domain, address);
2423 managed_sample_base [i * 4 + 0] = (uintptr_t)mono_jit_info_get_method (ji);
2427 logbuffer = ensure_logbuf (
2428 EVENT_SIZE /* event */ +
2429 LEB128_SIZE /* type */ +
2430 LEB128_SIZE /* time */ +
2431 LEB128_SIZE /* tid */ +
2432 LEB128_SIZE /* count */ +
2434 LEB128_SIZE /* ip */
2436 LEB128_SIZE /* managed count */ +
2438 LEB128_SIZE /* method */ +
2439 LEB128_SIZE /* il offset */ +
2440 LEB128_SIZE /* native offset */
2443 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
2444 emit_value (logbuffer, type);
2445 emit_uvalue (logbuffer, prof->startup_time + (uint64_t)sample [2] * (uint64_t)10000);
2446 emit_ptr (logbuffer, (void *) thread_id);
2447 emit_value (logbuffer, count);
2448 for (int i = 0; i < count; ++i) {
2449 emit_ptr (logbuffer, (void*)sample [i + 3]);
2450 add_code_pointer (sample [i + 3]);
2453 sample += count + 3;
2454 /* new in data version 6 */
2455 emit_uvalue (logbuffer, mbt_count);
2456 for (int i = 0; i < mbt_count; ++i) {
2457 MonoMethod *method = (MonoMethod *) sample [i * 4 + 0];
2458 uintptr_t native_offset = sample [i * 4 + 3];
2460 emit_method (prof, logbuffer, method);
2461 emit_svalue (logbuffer, 0); /* il offset will always be 0 from now on */
2462 emit_svalue (logbuffer, native_offset);
2466 dump_unmanaged_coderefs (prof);
2472 mono_cpu_count (void)
2475 #ifdef PLATFORM_ANDROID
2476 /* Android tries really hard to save power by powering off CPUs on SMP phones which
2477 * means the normal way to query cpu count returns a wrong value with userspace API.
2478 * Instead we use /sys entries to query the actual hardware CPU count.
2480 char buffer[8] = {'\0'};
2481 int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
2482 /* Format of the /sys entry is a cpulist of indexes which in the case
2483 * of present is always of the form "0-(n-1)" when there is more than
2484 * 1 core, n being the number of CPU cores in the system. Otherwise
2485 * the value is simply 0
2487 if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
2488 count = strtol (((char*)buffer) + 2, NULL, 10);
2494 #ifdef _SC_NPROCESSORS_ONLN
2495 count = sysconf (_SC_NPROCESSORS_ONLN);
2502 size_t len = sizeof (int);
2505 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
2512 GetSystemInfo (&info);
2513 return info.dwNumberOfProcessors;
2522 unsigned int prev_pos;
2524 struct perf_event_mmap_page *page_desc;
2527 static PerfData *perf_data = NULL;
2528 static int num_perf;
2529 #define PERF_PAGES_SHIFT 4
2530 static int num_pages = 1 << PERF_PAGES_SHIFT;
2531 static unsigned int mmap_mask;
2534 struct perf_event_header h;
2544 perf_event_syscall (struct perf_event_attr *attr, pid_t pid, int cpu, int group_fd, unsigned long flags)
2546 attr->size = PERF_ATTR_SIZE_VER0;
2547 //printf ("perf attr size: %d\n", attr->size);
2548 #if defined(__x86_64__)
2549 return syscall(/*__NR_perf_event_open*/ 298, attr, pid, cpu, group_fd, flags);
2550 #elif defined(__i386__)
2551 return syscall(/*__NR_perf_event_open*/ 336, attr, pid, cpu, group_fd, flags);
2552 #elif defined(__arm__) || defined (__aarch64__)
2553 return syscall(/*__NR_perf_event_open*/ 364, attr, pid, cpu, group_fd, flags);
2560 setup_perf_map (PerfData *perf)
2562 perf->mmap_base = mmap (NULL, (num_pages + 1) * getpagesize (), PROT_READ|PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
2563 if (perf->mmap_base == MAP_FAILED) {
2565 printf ("failed mmap\n");
2568 perf->page_desc = perf->mmap_base;
2570 printf ("mmap version: %d\n", perf->page_desc->version);
2575 dump_perf_hits (MonoProfiler *prof, void *buf, int size)
2577 LogBuffer *logbuffer;
2580 void *end = (char*)buf + size;
2582 int pid = getpid ();
2588 if (pid != s->pid) {
2590 printf ("event for different pid: %d\n", s->pid);
2591 buf = (char*)buf + s->h.size;
2594 /*ip = (void*)s->ip;
2595 printf ("sample: %d, size: %d, ip: %p (%s), timestamp: %llu, nframes: %llu\n",
2596 s->h.type, s->h.size, ip, symbol_for (ip), s->timestamp, s->nframes);*/
2597 logbuffer = ensure_logbuf (
2598 EVENT_SIZE /* event */ +
2599 LEB128_SIZE /* type */ +
2600 LEB128_SIZE /* time */ +
2601 LEB128_SIZE /* tid */ +
2602 LEB128_SIZE /* count */ +
2604 LEB128_SIZE /* ip */
2606 LEB128_SIZE /* managed count */ +
2608 LEB128_SIZE /* method */ +
2609 LEB128_SIZE /* il offset */ +
2610 LEB128_SIZE /* native offset */
2613 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
2614 emit_value (logbuffer, sample_type);
2615 emit_uvalue (logbuffer, s->timestamp - prof->startup_time);
2617 * No useful thread ID to write here, since throughout the
2618 * profiler we use pthread_self () but the ID we get from
2619 * perf is the kernel's thread ID.
2621 emit_ptr (logbuffer, 0);
2622 emit_value (logbuffer, count);
2623 emit_ptr (logbuffer, (void*)(uintptr_t)s->ip);
2624 add_code_pointer (s->ip);
2625 /* no support here yet for the managed backtrace */
2626 emit_uvalue (logbuffer, mbt_count);
2627 buf = (char*)buf + s->h.size;
2631 printf ("dumped %d samples\n", samples);
2632 dump_unmanaged_coderefs (prof);
2635 /* read events from the ring buffer */
2637 read_perf_mmap (MonoProfiler* prof, int cpu)
2639 PerfData *perf = perf_data + cpu;
2641 unsigned char *data = (unsigned char*)perf->mmap_base + getpagesize ();
2642 unsigned int head = perf->page_desc->data_head;
2646 mono_memory_read_barrier ();
2648 old = perf->prev_pos;
2652 printf ("lost mmap events: old: %d, head: %d\n", old, head);
2656 if ((old & mmap_mask) + size != (head & mmap_mask)) {
2657 buf = data + (old & mmap_mask);
2658 size = mmap_mask + 1 - (old & mmap_mask);
2660 /* size bytes at buf */
2662 printf ("found1 bytes of events: %d\n", size);
2663 dump_perf_hits (prof, buf, size);
2665 buf = data + (old & mmap_mask);
2667 /* size bytes at buf */
2669 printf ("found bytes of events: %d\n", size);
2670 dump_perf_hits (prof, buf, size);
2672 perf->prev_pos = old;
2673 perf->page_desc->data_tail = old;
2678 setup_perf_event_for_cpu (PerfData *perf, int cpu)
2680 struct perf_event_attr attr;
2681 memset (&attr, 0, sizeof (attr));
2682 attr.type = PERF_TYPE_HARDWARE;
2683 switch (sample_type) {
2684 case SAMPLE_CYCLES: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2685 case SAMPLE_INSTRUCTIONS: attr.config = PERF_COUNT_HW_INSTRUCTIONS; break;
2686 case SAMPLE_CACHE_MISSES: attr.config = PERF_COUNT_HW_CACHE_MISSES; break;
2687 case SAMPLE_CACHE_REFS: attr.config = PERF_COUNT_HW_CACHE_REFERENCES; break;
2688 case SAMPLE_BRANCHES: attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS; break;
2689 case SAMPLE_BRANCH_MISSES: attr.config = PERF_COUNT_HW_BRANCH_MISSES; break;
2690 default: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2692 attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD | PERF_SAMPLE_TIME;
2693 // attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
2694 attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING | PERF_FORMAT_ID;
2697 attr.sample_freq = sample_freq;
2699 perf->perf_fd = perf_event_syscall (&attr, getpid (), cpu, -1, 0);
2701 printf ("perf fd: %d, freq: %d, event: %llu\n", perf->perf_fd, sample_freq, attr.config);
2702 if (perf->perf_fd < 0) {
2703 if (perf->perf_fd == -EPERM) {
2704 fprintf (stderr, "Perf syscall denied, do \"echo 1 > /proc/sys/kernel/perf_event_paranoid\" as root to enable.\n");
2707 perror ("open perf event");
2711 if (!setup_perf_map (perf)) {
2712 close (perf->perf_fd);
2720 setup_perf_event (void)
2723 mmap_mask = num_pages * getpagesize () - 1;
2724 num_perf = mono_cpu_count ();
2725 perf_data = calloc (num_perf, sizeof (PerfData));
2726 for (i = 0; i < num_perf; ++i) {
2727 count += setup_perf_event_for_cpu (perf_data + i, i);
2736 #endif /* USE_PERF_EVENTS */
2738 #ifndef DISABLE_HELPER_THREAD
2740 typedef struct MonoCounterAgent {
2741 MonoCounter *counter;
2742 // MonoCounterAgent specific data :
2747 struct MonoCounterAgent *next;
2750 static MonoCounterAgent* counters;
2751 static gboolean counters_initialized = FALSE;
2752 static int counters_index = 1;
2753 static mono_mutex_t counters_mutex;
2756 counters_add_agent (MonoCounter *counter)
2758 MonoCounterAgent *agent, *item;
2760 if (!counters_initialized)
2763 mono_mutex_lock (&counters_mutex);
2765 for (agent = counters; agent; agent = agent->next) {
2766 if (agent->counter == counter) {
2767 agent->value_size = 0;
2769 free (agent->value);
2770 agent->value = NULL;
2772 mono_mutex_unlock (&counters_mutex);
2777 agent = malloc (sizeof (MonoCounterAgent));
2778 agent->counter = counter;
2779 agent->value = NULL;
2780 agent->value_size = 0;
2781 agent->index = counters_index++;
2794 mono_mutex_unlock (&counters_mutex);
2798 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
2800 counters_add_agent (counter);
2805 counters_init (MonoProfiler *profiler)
2807 assert (!counters_initialized);
2809 mono_mutex_init (&counters_mutex);
2811 counters_initialized = TRUE;
2813 mono_counters_on_register (&counters_add_agent);
2814 mono_counters_foreach (counters_init_foreach_callback, NULL);
2818 counters_emit (MonoProfiler *profiler)
2820 MonoCounterAgent *agent;
2821 LogBuffer *logbuffer;
2824 EVENT_SIZE /* event */ +
2825 LEB128_SIZE /* len */
2828 if (!counters_initialized)
2831 mono_mutex_lock (&counters_mutex);
2833 for (agent = counters; agent; agent = agent->next) {
2838 LEB128_SIZE /* section */ +
2839 strlen (mono_counter_get_name (agent->counter)) + 1 /* name */ +
2840 LEB128_SIZE /* type */ +
2841 LEB128_SIZE /* unit */ +
2842 LEB128_SIZE /* variance */ +
2843 LEB128_SIZE /* index */
2850 mono_mutex_unlock (&counters_mutex);
2854 logbuffer = ensure_logbuf (size);
2856 ENTER_LOG (logbuffer, "counters");
2857 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2858 emit_value (logbuffer, len);
2859 for (agent = counters; agent; agent = agent->next) {
2865 name = mono_counter_get_name (agent->counter);
2866 emit_value (logbuffer, mono_counter_get_section (agent->counter));
2867 emit_string (logbuffer, name, strlen (name) + 1);
2868 emit_value (logbuffer, mono_counter_get_type (agent->counter));
2869 emit_value (logbuffer, mono_counter_get_unit (agent->counter));
2870 emit_value (logbuffer, mono_counter_get_variance (agent->counter));
2871 emit_value (logbuffer, agent->index);
2875 EXIT_LOG (logbuffer);
2877 safe_send (profiler, logbuffer);
2879 mono_mutex_unlock (&counters_mutex);
2883 counters_sample (MonoProfiler *profiler, uint64_t timestamp)
2885 MonoCounterAgent *agent;
2886 MonoCounter *counter;
2887 LogBuffer *logbuffer;
2893 if (!counters_initialized)
2896 counters_emit (profiler);
2899 buffer = calloc (1, buffer_size);
2901 mono_mutex_lock (&counters_mutex);
2904 EVENT_SIZE /* event */ +
2905 LEB128_SIZE /* time */
2908 for (agent = counters; agent; agent = agent->next) {
2910 LEB128_SIZE /* index */ +
2911 LEB128_SIZE /* type */ +
2912 mono_counter_get_size (agent->counter) /* value */
2917 LEB128_SIZE /* stop marker */
2920 logbuffer = ensure_logbuf (size);
2922 ENTER_LOG (logbuffer, "counters");
2923 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
2924 emit_uvalue (logbuffer, timestamp);
2925 for (agent = counters; agent; agent = agent->next) {
2928 counter = agent->counter;
2930 size = mono_counter_get_size (counter);
2932 continue; // FIXME error
2933 } else if (size > buffer_size) {
2935 buffer = realloc (buffer, buffer_size);
2938 memset (buffer, 0, buffer_size);
2940 if (mono_counters_sample (counter, buffer, size) < 0)
2941 continue; // FIXME error
2943 type = mono_counter_get_type (counter);
2945 if (!agent->value) {
2946 agent->value = calloc (1, size);
2947 agent->value_size = size;
2949 if (type == MONO_COUNTER_STRING) {
2950 if (strcmp (agent->value, buffer) == 0)
2953 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
2958 emit_uvalue (logbuffer, agent->index);
2959 emit_uvalue (logbuffer, type);
2961 case MONO_COUNTER_INT:
2962 #if SIZEOF_VOID_P == 4
2963 case MONO_COUNTER_WORD:
2965 emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
2967 case MONO_COUNTER_UINT:
2968 emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
2970 case MONO_COUNTER_TIME_INTERVAL:
2971 case MONO_COUNTER_LONG:
2972 #if SIZEOF_VOID_P == 8
2973 case MONO_COUNTER_WORD:
2975 emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
2977 case MONO_COUNTER_ULONG:
2978 emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
2980 case MONO_COUNTER_DOUBLE:
2981 emit_double (logbuffer, *(double*)buffer);
2983 case MONO_COUNTER_STRING:
2985 emit_byte (logbuffer, 0);
2987 emit_byte (logbuffer, 1);
2988 emit_string (logbuffer, (char*)buffer, size);
2995 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
2996 agent->value = realloc (agent->value, size);
2997 agent->value_size = size;
3001 memcpy (agent->value, buffer, size);
3005 emit_value (logbuffer, 0);
3006 EXIT_LOG (logbuffer);
3008 safe_send (profiler, logbuffer);
3010 mono_mutex_unlock (&counters_mutex);
3013 typedef struct _PerfCounterAgent PerfCounterAgent;
3014 struct _PerfCounterAgent {
3015 PerfCounterAgent *next;
3017 char *category_name;
3026 static PerfCounterAgent *perfcounters = NULL;
3029 perfcounters_emit (MonoProfiler *profiler)
3031 PerfCounterAgent *pcagent;
3032 LogBuffer *logbuffer;
3035 EVENT_SIZE /* event */ +
3036 LEB128_SIZE /* len */
3039 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3040 if (pcagent->emitted)
3044 LEB128_SIZE /* section */ +
3045 strlen (pcagent->category_name) + 1 /* category name */ +
3046 strlen (pcagent->name) + 1 /* name */ +
3047 LEB128_SIZE /* type */ +
3048 LEB128_SIZE /* unit */ +
3049 LEB128_SIZE /* variance */ +
3050 LEB128_SIZE /* index */
3059 logbuffer = ensure_logbuf (size);
3061 ENTER_LOG (logbuffer, "perfcounters");
3062 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
3063 emit_value (logbuffer, len);
3064 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3065 if (pcagent->emitted)
3068 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
3069 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
3070 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
3071 emit_value (logbuffer, MONO_COUNTER_LONG);
3072 emit_value (logbuffer, MONO_COUNTER_RAW);
3073 emit_value (logbuffer, MONO_COUNTER_VARIABLE);
3074 emit_value (logbuffer, pcagent->index);
3076 pcagent->emitted = 1;
3078 EXIT_LOG (logbuffer);
3080 safe_send (profiler, logbuffer);
3084 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
3086 PerfCounterAgent *pcagent;
3088 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3089 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
3091 if (pcagent->value == value)
3094 pcagent->value = value;
3095 pcagent->updated = 1;
3096 pcagent->deleted = 0;
3100 pcagent = g_new0 (PerfCounterAgent, 1);
3101 pcagent->next = perfcounters;
3102 pcagent->index = counters_index++;
3103 pcagent->category_name = g_strdup (category_name);
3104 pcagent->name = g_strdup (name);
3105 pcagent->type = (int) type;
3106 pcagent->value = value;
3107 pcagent->emitted = 0;
3108 pcagent->updated = 1;
3109 pcagent->deleted = 0;
3111 perfcounters = pcagent;
3117 perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp)
3119 PerfCounterAgent *pcagent;
3120 LogBuffer *logbuffer;
3123 if (!counters_initialized)
3126 mono_mutex_lock (&counters_mutex);
3128 /* mark all perfcounters as deleted, foreach will unmark them as necessary */
3129 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
3130 pcagent->deleted = 1;
3132 mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
3134 perfcounters_emit (profiler);
3137 EVENT_SIZE /* event */ +
3138 LEB128_SIZE /* time */
3141 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3142 if (pcagent->deleted || !pcagent->updated)
3146 LEB128_SIZE /* index */ +
3147 LEB128_SIZE /* type */ +
3148 LEB128_SIZE /* value */
3153 LEB128_SIZE /* stop marker */
3156 logbuffer = ensure_logbuf (size);
3158 ENTER_LOG (logbuffer, "perfcounters");
3159 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
3160 emit_uvalue (logbuffer, timestamp);
3161 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3162 if (pcagent->deleted || !pcagent->updated)
3164 emit_uvalue (logbuffer, pcagent->index);
3165 emit_uvalue (logbuffer, MONO_COUNTER_LONG);
3166 emit_svalue (logbuffer, pcagent->value);
3168 pcagent->updated = 0;
3171 emit_value (logbuffer, 0);
3172 EXIT_LOG (logbuffer);
3174 safe_send (profiler, logbuffer);
3176 mono_mutex_unlock (&counters_mutex);
3180 counters_and_perfcounters_sample (MonoProfiler *prof)
3182 static uint64_t start = -1;
3186 start = current_time ();
3188 now = current_time ();
3189 counters_sample (prof, (now - start) / 1000/ 1000);
3190 perfcounters_sample (prof, (now - start) / 1000/ 1000);
3193 #define COVERAGE_DEBUG(x) if (debug_coverage) {x}
3194 static mono_mutex_t coverage_mutex;
3195 static MonoConcurrentHashTable *coverage_methods = NULL;
3196 static MonoConcurrentHashTable *coverage_assemblies = NULL;
3197 static MonoConcurrentHashTable *coverage_classes = NULL;
3199 static MonoConcurrentHashTable *filtered_classes = NULL;
3200 static MonoConcurrentHashTable *entered_methods = NULL;
3201 static MonoConcurrentHashTable *image_to_methods = NULL;
3202 static MonoConcurrentHashTable *suppressed_assemblies = NULL;
3203 static gboolean coverage_initialized = FALSE;
3205 static GPtrArray *coverage_data = NULL;
3206 static int previous_offset = 0;
3208 typedef struct _MethodNode MethodNode;
3209 struct _MethodNode {
3210 MonoLockFreeQueueNode node;
3214 typedef struct _CoverageEntry CoverageEntry;
3215 struct _CoverageEntry {
3224 free_coverage_entry (gpointer data, gpointer userdata)
3226 CoverageEntry *entry = (CoverageEntry *)data;
3227 g_free (entry->filename);
3232 obtain_coverage_for_method (MonoProfiler *prof, const MonoProfileCoverageEntry *entry)
3234 int offset = entry->iloffset - previous_offset;
3235 CoverageEntry *e = g_new (CoverageEntry, 1);
3237 previous_offset = entry->iloffset;
3240 e->counter = entry->counter;
3241 e->filename = g_strdup(entry->filename ? entry->filename : "");
3242 e->line = entry->line;
3243 e->column = entry->col;
3245 g_ptr_array_add (coverage_data, e);
3249 parse_generic_type_names(char *name)
3251 char *new_name, *ret;
3252 int within_generic_declaration = 0, generic_members = 1;
3254 if (name == NULL || *name == '\0')
3255 return g_strdup ("");
3257 if (!(ret = new_name = calloc (strlen (name) * 4 + 1, sizeof (char))))
3263 within_generic_declaration = 1;
3267 within_generic_declaration = 0;
3269 if (*(name - 1) != '<') {
3271 *new_name++ = '0' + generic_members;
3273 memcpy (new_name, "<>", 8);
3277 generic_members = 0;
3285 if (!within_generic_declaration)
3286 *new_name++ = *name;
3295 static int method_id;
3297 build_method_buffer (gpointer key, gpointer value, gpointer userdata)
3299 MonoMethod *method = (MonoMethod *)value;
3300 MonoProfiler *prof = (MonoProfiler *)userdata;
3304 const char *image_name, *method_name, *sig, *first_filename;
3305 LogBuffer *logbuffer;
3308 previous_offset = 0;
3309 coverage_data = g_ptr_array_new ();
3311 mono_profiler_coverage_get (prof, method, obtain_coverage_for_method);
3313 klass = mono_method_get_class (method);
3314 image = mono_class_get_image (klass);
3315 image_name = mono_image_get_name (image);
3317 sig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3318 class_name = parse_generic_type_names (mono_type_get_name (mono_class_get_type (klass)));
3319 method_name = mono_method_get_name (method);
3321 if (coverage_data->len != 0) {
3322 CoverageEntry *entry = coverage_data->pdata[0];
3323 first_filename = entry->filename ? entry->filename : "";
3325 first_filename = "";
3327 image_name = image_name ? image_name : "";
3328 sig = sig ? sig : "";
3329 method_name = method_name ? method_name : "";
3331 logbuffer = ensure_logbuf (
3332 EVENT_SIZE /* event */ +
3333 strlen (image_name) + 1 /* image name */ +
3334 strlen (class_name) + 1 /* class name */ +
3335 strlen (method_name) + 1 /* method name */ +
3336 strlen (sig) + 1 /* signature */ +
3337 strlen (first_filename) + 1 /* first file name */ +
3338 LEB128_SIZE /* token */ +
3339 LEB128_SIZE /* method id */ +
3340 LEB128_SIZE /* entries */
3342 ENTER_LOG (logbuffer, "coverage-methods");
3344 emit_byte (logbuffer, TYPE_COVERAGE_METHOD | TYPE_COVERAGE);
3345 emit_string (logbuffer, image_name, strlen (image_name) + 1);
3346 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3347 emit_string (logbuffer, method_name, strlen (method_name) + 1);
3348 emit_string (logbuffer, sig, strlen (sig) + 1);
3349 emit_string (logbuffer, first_filename, strlen (first_filename) + 1);
3351 emit_uvalue (logbuffer, mono_method_get_token (method));
3352 emit_uvalue (logbuffer, method_id);
3353 emit_value (logbuffer, coverage_data->len);
3355 EXIT_LOG (logbuffer);
3356 safe_send (prof, logbuffer);
3358 for (i = 0; i < coverage_data->len; i++) {
3359 CoverageEntry *entry = coverage_data->pdata[i];
3361 logbuffer = ensure_logbuf (
3362 EVENT_SIZE /* event */ +
3363 LEB128_SIZE /* method id */ +
3364 LEB128_SIZE /* offset */ +
3365 LEB128_SIZE /* counter */ +
3366 LEB128_SIZE /* line */ +
3367 LEB128_SIZE /* column */
3369 ENTER_LOG (logbuffer, "coverage-statement");
3371 emit_byte (logbuffer, TYPE_COVERAGE_STATEMENT | TYPE_COVERAGE);
3372 emit_uvalue (logbuffer, method_id);
3373 emit_uvalue (logbuffer, entry->offset);
3374 emit_uvalue (logbuffer, entry->counter);
3375 emit_uvalue (logbuffer, entry->line);
3376 emit_uvalue (logbuffer, entry->column);
3378 EXIT_LOG (logbuffer);
3379 safe_send (prof, logbuffer);
3384 g_free (class_name);
3386 g_ptr_array_foreach (coverage_data, free_coverage_entry, NULL);
3387 g_ptr_array_free (coverage_data, TRUE);
3388 coverage_data = NULL;
3391 /* This empties the queue */
3393 count_queue (MonoLockFreeQueue *queue)
3395 MonoLockFreeQueueNode *node;
3398 while ((node = mono_lock_free_queue_dequeue (queue))) {
3400 mono_lock_free_queue_node_free (node);
3407 build_class_buffer (gpointer key, gpointer value, gpointer userdata)
3409 MonoClass *klass = (MonoClass *)key;
3410 MonoLockFreeQueue *class_methods = (MonoLockFreeQueue *)value;
3411 MonoProfiler *prof = (MonoProfiler *)userdata;
3414 const char *assembly_name;
3415 int number_of_methods, partially_covered;
3416 guint fully_covered;
3417 LogBuffer *logbuffer;
3419 image = mono_class_get_image (klass);
3420 assembly_name = mono_image_get_name (image);
3421 class_name = mono_type_get_name (mono_class_get_type (klass));
3423 assembly_name = assembly_name ? assembly_name : "";
3424 number_of_methods = mono_class_num_methods (klass);
3425 fully_covered = count_queue (class_methods);
3426 /* We don't handle partial covered yet */
3427 partially_covered = 0;
3429 logbuffer = ensure_logbuf (
3430 EVENT_SIZE /* event */ +
3431 strlen (assembly_name) + 1 /* assembly name */ +
3432 strlen (class_name) + 1 /* class name */ +
3433 LEB128_SIZE /* no. methods */ +
3434 LEB128_SIZE /* fully covered */ +
3435 LEB128_SIZE /* partially covered */
3438 ENTER_LOG (logbuffer, "coverage-class");
3439 emit_byte (logbuffer, TYPE_COVERAGE_CLASS | TYPE_COVERAGE);
3440 emit_string (logbuffer, assembly_name, strlen (assembly_name) + 1);
3441 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3442 emit_uvalue (logbuffer, number_of_methods);
3443 emit_uvalue (logbuffer, fully_covered);
3444 emit_uvalue (logbuffer, partially_covered);
3445 EXIT_LOG (logbuffer);
3447 safe_send (prof, logbuffer);
3449 g_free (class_name);
3453 get_coverage_for_image (MonoImage *image, int *number_of_methods, guint *fully_covered, int *partially_covered)
3455 MonoLockFreeQueue *image_methods = mono_conc_hashtable_lookup (image_to_methods, image);
3457 *number_of_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
3459 *fully_covered = count_queue (image_methods);
3463 // FIXME: We don't handle partially covered yet.
3464 *partially_covered = 0;
3468 build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
3470 MonoAssembly *assembly = (MonoAssembly *)value;
3471 MonoProfiler *prof = (MonoProfiler *)userdata;
3472 MonoImage *image = mono_assembly_get_image (assembly);
3473 LogBuffer *logbuffer;
3474 const char *name, *guid, *filename;
3475 int number_of_methods = 0, partially_covered = 0;
3476 guint fully_covered = 0;
3478 name = mono_image_get_name (image);
3479 guid = mono_image_get_guid (image);
3480 filename = mono_image_get_filename (image);
3482 name = name ? name : "";
3483 guid = guid ? guid : "";
3484 filename = filename ? filename : "";
3486 get_coverage_for_image (image, &number_of_methods, &fully_covered, &partially_covered);
3488 logbuffer = ensure_logbuf (
3489 EVENT_SIZE /* event */ +
3490 strlen (name) + 1 /* name */ +
3491 strlen (guid) + 1 /* guid */ +
3492 strlen (filename) + 1 /* file name */ +
3493 LEB128_SIZE /* no. methods */ +
3494 LEB128_SIZE /* fully covered */ +
3495 LEB128_SIZE /* partially covered */
3498 ENTER_LOG (logbuffer, "coverage-assemblies");
3499 emit_byte (logbuffer, TYPE_COVERAGE_ASSEMBLY | TYPE_COVERAGE);
3500 emit_string (logbuffer, name, strlen (name) + 1);
3501 emit_string (logbuffer, guid, strlen (guid) + 1);
3502 emit_string (logbuffer, filename, strlen (filename) + 1);
3503 emit_uvalue (logbuffer, number_of_methods);
3504 emit_uvalue (logbuffer, fully_covered);
3505 emit_uvalue (logbuffer, partially_covered);
3506 EXIT_LOG (logbuffer);
3508 safe_send (prof, logbuffer);
3512 dump_coverage (MonoProfiler *prof)
3514 if (!coverage_initialized)
3517 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Started dump\n");)
3520 mono_mutex_lock (&coverage_mutex);
3521 mono_conc_hashtable_foreach (coverage_assemblies, build_assembly_buffer, prof);
3522 mono_conc_hashtable_foreach (coverage_classes, build_class_buffer, prof);
3523 mono_conc_hashtable_foreach (coverage_methods, build_method_buffer, prof);
3524 mono_mutex_unlock (&coverage_mutex);
3526 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Finished dump\n");)
3530 process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method)
3535 if (!coverage_initialized)
3538 klass = mono_method_get_class (method);
3539 image = mono_class_get_image (klass);
3541 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)))
3544 mono_mutex_lock (&coverage_mutex);
3545 mono_conc_hashtable_insert (entered_methods, method, method);
3546 mono_mutex_unlock (&coverage_mutex);
3549 static MonoLockFreeQueueNode *
3550 create_method_node (MonoMethod *method)
3552 MethodNode *node = g_malloc (sizeof (MethodNode));
3553 mono_lock_free_queue_node_init ((MonoLockFreeQueueNode *) node, FALSE);
3554 node->method = method;
3556 return (MonoLockFreeQueueNode *) node;
3560 coverage_filter (MonoProfiler *prof, MonoMethod *method)
3564 MonoAssembly *assembly;
3565 MonoMethodHeader *header;
3566 guint32 iflags, flags, code_size;
3567 char *fqn, *classname;
3568 gboolean has_positive, found;
3569 MonoLockFreeQueue *image_methods, *class_methods;
3570 MonoLockFreeQueueNode *node;
3572 if (!coverage_initialized)
3575 COVERAGE_DEBUG(fprintf (stderr, "Coverage filter for %s\n", mono_method_get_name (method));)
3577 flags = mono_method_get_flags (method, &iflags);
3578 if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
3579 (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/)) {
3580 COVERAGE_DEBUG(fprintf (stderr, " Internal call or pinvoke - ignoring\n");)
3584 // Don't need to do anything else if we're already tracking this method
3585 if (mono_conc_hashtable_lookup (coverage_methods, method)) {
3586 COVERAGE_DEBUG(fprintf (stderr, " Already tracking\n");)
3590 klass = mono_method_get_class (method);
3591 image = mono_class_get_image (klass);
3593 // Don't handle coverage for the core assemblies
3594 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)) != NULL)
3597 if (prof->coverage_filters) {
3598 /* Check already filtered classes first */
3599 if (mono_conc_hashtable_lookup (filtered_classes, klass)) {
3600 COVERAGE_DEBUG(fprintf (stderr, " Already filtered\n");)
3604 classname = mono_type_get_name (mono_class_get_type (klass));
3606 fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
3608 COVERAGE_DEBUG(fprintf (stderr, " Looking for %s in filter\n", fqn);)
3609 // Check positive filters first
3610 has_positive = FALSE;
3612 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3613 char *filter = g_ptr_array_index (prof->coverage_filters, i);
3615 if (filter [0] == '+') {
3616 filter = &filter [1];
3618 COVERAGE_DEBUG(fprintf (stderr, " Checking against +%s ...", filter);)
3620 if (strstr (fqn, filter) != NULL) {
3621 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3624 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3626 has_positive = TRUE;
3630 if (has_positive && !found) {
3631 COVERAGE_DEBUG(fprintf (stderr, " Positive match was not found\n");)
3633 mono_mutex_lock (&coverage_mutex);
3634 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3635 mono_mutex_unlock (&coverage_mutex);
3642 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3643 // FIXME: Is substring search sufficient?
3644 char *filter = g_ptr_array_index (prof->coverage_filters, i);
3645 if (filter [0] == '+')
3649 filter = &filter [1];
3650 COVERAGE_DEBUG(fprintf (stderr, " Checking against -%s ...", filter);)
3652 if (strstr (fqn, filter) != NULL) {
3653 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3655 mono_mutex_lock (&coverage_mutex);
3656 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3657 mono_mutex_unlock (&coverage_mutex);
3663 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3671 COVERAGE_DEBUG(fprintf (stderr, " Handling coverage for %s\n", mono_method_get_name (method));)
3672 header = mono_method_get_header (method);
3674 mono_method_header_get_code (header, &code_size, NULL);
3676 assembly = mono_image_get_assembly (image);
3678 mono_mutex_lock (&coverage_mutex);
3679 mono_conc_hashtable_insert (coverage_methods, method, method);
3680 mono_conc_hashtable_insert (coverage_assemblies, assembly, assembly);
3681 mono_mutex_unlock (&coverage_mutex);
3683 image_methods = mono_conc_hashtable_lookup (image_to_methods, image);
3685 if (image_methods == NULL) {
3686 image_methods = g_malloc (sizeof (MonoLockFreeQueue));
3687 mono_lock_free_queue_init (image_methods);
3688 mono_mutex_lock (&coverage_mutex);
3689 mono_conc_hashtable_insert (image_to_methods, image, image_methods);
3690 mono_mutex_unlock (&coverage_mutex);
3693 node = create_method_node (method);
3694 mono_lock_free_queue_enqueue (image_methods, node);
3696 class_methods = mono_conc_hashtable_lookup (coverage_classes, klass);
3698 if (class_methods == NULL) {
3699 class_methods = g_malloc (sizeof (MonoLockFreeQueue));
3700 mono_lock_free_queue_init (class_methods);
3701 mono_mutex_lock (&coverage_mutex);
3702 mono_conc_hashtable_insert (coverage_classes, klass, class_methods);
3703 mono_mutex_unlock (&coverage_mutex);
3706 node = create_method_node (method);
3707 mono_lock_free_queue_enqueue (class_methods, node);
3712 #define LINE_BUFFER_SIZE 4096
3713 /* Max file limit of 128KB */
3714 #define MAX_FILE_SIZE 128 * 1024
3716 get_file_content (FILE *stream)
3721 int res, offset = 0;
3723 res = fseek (stream, 0, SEEK_END);
3727 filesize = ftell (stream);
3731 res = fseek (stream, 0, SEEK_SET);
3735 if (filesize > MAX_FILE_SIZE)
3738 buffer = g_malloc ((filesize + 1) * sizeof (char));
3739 while ((bytes_read = fread (buffer + offset, 1, LINE_BUFFER_SIZE, stream)) > 0)
3740 offset += bytes_read;
3742 /* NULL terminate our buffer */
3743 buffer[filesize] = '\0';
3748 get_next_line (char *contents, char **next_start)
3752 if (p == NULL || *p == '\0') {
3757 while (*p != '\n' && *p != '\0')
3762 *next_start = p + 1;
3770 init_suppressed_assemblies (void)
3776 suppressed_assemblies = mono_conc_hashtable_new (g_str_hash, g_str_equal);
3777 sa_file = fopen (SUPPRESSION_DIR "/mono-profiler-log.suppression", "r");
3778 if (sa_file == NULL)
3781 /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
3782 content = get_file_content (sa_file);
3783 if (content == NULL) {
3784 g_error ("mono-profiler-log.suppression is greater than 128kb - aborting\n");
3787 while ((line = get_next_line (content, &content))) {
3788 line = g_strchomp (g_strchug (line));
3789 /* No locking needed as we're doing initialization */
3790 mono_conc_hashtable_insert (suppressed_assemblies, line, line);
3796 #endif /* DISABLE_HELPER_THREAD */
3799 coverage_init (MonoProfiler *prof)
3801 #ifndef DISABLE_HELPER_THREAD
3802 assert (!coverage_initialized);
3804 COVERAGE_DEBUG(fprintf (stderr, "Coverage initialized\n");)
3806 mono_mutex_init (&coverage_mutex);
3807 coverage_methods = mono_conc_hashtable_new (NULL, NULL);
3808 coverage_assemblies = mono_conc_hashtable_new (NULL, NULL);
3809 coverage_classes = mono_conc_hashtable_new (NULL, NULL);
3810 filtered_classes = mono_conc_hashtable_new (NULL, NULL);
3811 entered_methods = mono_conc_hashtable_new (NULL, NULL);
3812 image_to_methods = mono_conc_hashtable_new (NULL, NULL);
3813 init_suppressed_assemblies ();
3815 coverage_initialized = TRUE;
3816 #endif /* DISABLE_HELPER_THREAD */
3820 log_shutdown (MonoProfiler *prof)
3825 #ifndef DISABLE_HELPER_THREAD
3826 counters_and_perfcounters_sample (prof);
3828 dump_coverage (prof);
3830 if (prof->command_port) {
3832 ign_res (write (prof->pipes [1], &c, 1));
3833 pthread_join (prof->helper_thread, &res);
3839 for (i = 0; i < num_perf; ++i)
3840 read_perf_mmap (prof, i);
3844 g_ptr_array_free (prof->sorted_sample_events, TRUE);
3846 if (TLS_GET (LogBuffer, tlsbuffer))
3847 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
3849 TLS_SET (tlsbuffer, NULL);
3850 TLS_SET (tlsmethodlist, NULL);
3852 InterlockedWrite (&prof->run_writer_thread, 0);
3853 pthread_join (prof->writer_thread, &res);
3855 #if defined (HAVE_SYS_ZLIB)
3857 gzclose (prof->gzfile);
3859 if (prof->pipe_output)
3860 pclose (prof->file);
3862 fclose (prof->file);
3864 mono_conc_hashtable_destroy (prof->method_table);
3865 mono_mutex_destroy (&prof->method_table_mutex);
3867 if (coverage_initialized) {
3868 mono_conc_hashtable_destroy (coverage_methods);
3869 mono_conc_hashtable_destroy (coverage_assemblies);
3870 mono_conc_hashtable_destroy (coverage_classes);
3871 mono_conc_hashtable_destroy (filtered_classes);
3873 mono_conc_hashtable_destroy (entered_methods);
3874 mono_conc_hashtable_destroy (image_to_methods);
3875 mono_conc_hashtable_destroy (suppressed_assemblies);
3876 mono_mutex_destroy (&coverage_mutex);
3883 new_filename (const char* filename)
3885 time_t t = time (NULL);
3886 int pid = process_id ();
3891 int count_dates = 0;
3895 for (p = filename; *p; p++) {
3906 if (!count_dates && !count_pids)
3907 return pstrdup (filename);
3908 snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
3910 snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
3911 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
3912 s_date = strlen (time_buf);
3913 s_pid = strlen (pid_buf);
3914 d = res = malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
3915 for (p = filename; *p; p++) {
3922 strcpy (d, time_buf);
3925 } else if (*p == 'p') {
3926 strcpy (d, pid_buf);
3929 } else if (*p == '%') {
3941 //this is exposed by the JIT, but it's not meant to be a supported API for now.
3942 extern void mono_threads_attach_tools_thread (void);
3944 #ifndef DISABLE_HELPER_THREAD
3947 helper_thread (void* arg)
3949 MonoProfiler* prof = arg;
3953 MonoThread *thread = NULL;
3955 mono_threads_attach_tools_thread ();
3956 //fprintf (stderr, "Server listening\n");
3957 command_socket = -1;
3963 FD_SET (prof->server_socket, &rfds);
3964 max_fd = prof->server_socket;
3965 FD_SET (prof->pipes [0], &rfds);
3966 if (max_fd < prof->pipes [0])
3967 max_fd = prof->pipes [0];
3968 if (command_socket >= 0) {
3969 FD_SET (command_socket, &rfds);
3970 if (max_fd < command_socket)
3971 max_fd = command_socket;
3976 for ( i = 0; i < num_perf; ++i) {
3977 if (perf_data [i].perf_fd < 0)
3979 FD_SET (perf_data [i].perf_fd, &rfds);
3980 if (max_fd < perf_data [i].perf_fd)
3981 max_fd = perf_data [i].perf_fd;
3986 counters_and_perfcounters_sample (prof);
3990 len = select (max_fd + 1, &rfds, NULL, NULL, &tv);
3996 g_warning ("Error in proflog server: %s", strerror (errno));
4000 if (FD_ISSET (prof->pipes [0], &rfds)) {
4002 int r = read (prof->pipes [0], &c, 1);
4003 if (r == 1 && c == 0) {
4004 StatBuffer *sbufbase = prof->stat_buffers;
4006 if (!sbufbase->next)
4008 sbuf = sbufbase->next->next;
4009 sbufbase->next->next = NULL;
4011 fprintf (stderr, "stat buffer dump\n");
4013 dump_sample_hits (prof, sbuf);
4014 free_buffer (sbuf, sbuf->size);
4015 safe_send (prof, ensure_logbuf (0));
4019 /* time to shut down */
4020 dump_sample_hits (prof, prof->stat_buffers);
4022 mono_thread_detach (thread);
4024 fprintf (stderr, "helper shutdown\n");
4028 for ( i = 0; i < num_perf; ++i) {
4029 if (perf_data [i].perf_fd < 0)
4031 if (FD_ISSET (perf_data [i].perf_fd, &rfds))
4032 read_perf_mmap (prof, i);
4036 safe_send (prof, ensure_logbuf (0));
4042 for ( i = 0; i < num_perf; ++i) {
4043 if (perf_data [i].perf_fd < 0)
4045 if (FD_ISSET (perf_data [i].perf_fd, &rfds)) {
4046 read_perf_mmap (prof, i);
4047 safe_send (prof, ensure_logbuf (0));
4052 if (command_socket >= 0 && FD_ISSET (command_socket, &rfds)) {
4053 len = read (command_socket, buf, sizeof (buf) - 1);
4057 close (command_socket);
4058 command_socket = -1;
4062 if (strcmp (buf, "heapshot\n") == 0) {
4063 heapshot_requested = 1;
4064 //fprintf (stderr, "perform heapshot\n");
4065 if (InterlockedRead (&runtime_inited) && !thread) {
4066 thread = mono_thread_attach (mono_get_root_domain ());
4067 /*fprintf (stderr, "attached\n");*/
4070 process_requests (prof);
4071 mono_thread_detach (thread);
4077 if (!FD_ISSET (prof->server_socket, &rfds)) {
4080 command_socket = accept (prof->server_socket, NULL, NULL);
4081 if (command_socket < 0)
4083 //fprintf (stderr, "Accepted connection\n");
4089 start_helper_thread (MonoProfiler* prof)
4091 struct sockaddr_in server_address;
4094 if (pipe (prof->pipes) < 0) {
4095 fprintf (stderr, "Cannot create pipe\n");
4098 prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
4099 if (prof->server_socket < 0) {
4100 fprintf (stderr, "Cannot create server socket\n");
4103 memset (&server_address, 0, sizeof (server_address));
4104 server_address.sin_family = AF_INET;
4105 server_address.sin_addr.s_addr = INADDR_ANY;
4106 server_address.sin_port = htons (prof->command_port);
4107 if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) < 0) {
4108 fprintf (stderr, "Cannot bind server socket, port: %d: %s\n", prof->command_port, strerror (errno));
4109 close (prof->server_socket);
4112 if (listen (prof->server_socket, 1) < 0) {
4113 fprintf (stderr, "Cannot listen server socket\n");
4114 close (prof->server_socket);
4117 slen = sizeof (server_address);
4118 if (getsockname (prof->server_socket, (struct sockaddr *)&server_address, &slen) == 0) {
4119 prof->command_port = ntohs (server_address.sin_port);
4120 /*fprintf (stderr, "Assigned server port: %d\n", prof->command_port);*/
4123 r = pthread_create (&prof->helper_thread, NULL, helper_thread, prof);
4125 close (prof->server_socket);
4133 writer_thread (void *arg)
4135 MonoProfiler *prof = arg;
4137 mono_threads_attach_tools_thread ();
4141 while (InterlockedRead (&prof->run_writer_thread)) {
4142 WriterQueueEntry *entry;
4144 while ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&prof->writer_queue))) {
4145 LogBuffer *method_buffer = NULL;
4146 gboolean new_methods = FALSE;
4148 if (entry->methods->len)
4149 method_buffer = create_buffer ();
4152 * Encode the method events in a temporary log buffer that we
4153 * flush to disk before the main buffer, ensuring that all
4154 * methods have metadata emitted before they're referenced.
4156 for (guint i = 0; i < entry->methods->len; i++) {
4157 MethodInfo *info = g_ptr_array_index (entry->methods, i);
4159 if (mono_conc_hashtable_lookup (prof->method_table, info->method))
4165 * Other threads use this hash table to get a general
4166 * idea of whether a method has already been emitted to
4167 * the stream. Due to the way we add to this table, it
4168 * can easily happen that multiple threads queue up the
4169 * same methods, but that's OK since eventually all
4170 * methods will be in this table and the thread-local
4171 * method lists will just be empty for the rest of the
4174 mono_mutex_lock (&prof->method_table_mutex);
4175 mono_conc_hashtable_insert (prof->method_table, info->method, info->method);
4176 mono_mutex_unlock (&prof->method_table_mutex);
4178 char *name = mono_method_full_name (info->method, 1);
4179 int nlen = strlen (name) + 1;
4180 uint64_t now = current_time ();
4182 method_buffer = ensure_logbuf_inner (method_buffer,
4183 EVENT_SIZE /* event */ +
4184 LEB128_SIZE /* time */ +
4185 LEB128_SIZE /* method */ +
4186 LEB128_SIZE /* start */ +
4187 LEB128_SIZE /* size */ +
4191 emit_byte (method_buffer, TYPE_JIT | TYPE_METHOD);
4192 emit_time (method_buffer, now);
4193 emit_method_inner (method_buffer, info->method);
4194 emit_ptr (method_buffer, mono_jit_info_get_code_start (info->ji));
4195 emit_value (method_buffer, mono_jit_info_get_code_size (info->ji));
4197 memcpy (method_buffer->data, name, nlen);
4198 method_buffer->data += nlen;
4204 g_ptr_array_free (entry->methods, TRUE);
4207 dump_buffer (prof, method_buffer);
4208 else if (method_buffer)
4209 free_buffer (method_buffer, method_buffer->size);
4211 dump_buffer (prof, entry->buffer);
4221 start_writer_thread (MonoProfiler* prof)
4223 InterlockedWrite (&prof->run_writer_thread, 1);
4225 return !pthread_create (&prof->writer_thread, NULL, writer_thread, prof);
4229 runtime_initialized (MonoProfiler *profiler)
4231 #ifndef DISABLE_HELPER_THREAD
4232 if (hs_mode_ondemand || need_helper_thread) {
4233 if (!start_helper_thread (profiler))
4234 profiler->command_port = 0;
4238 start_writer_thread (profiler);
4240 InterlockedWrite (&runtime_inited, 1);
4241 #ifndef DISABLE_HELPER_THREAD
4242 counters_init (profiler);
4243 counters_sample (profiler, 0);
4245 /* ensure the main thread data and startup are available soon */
4246 safe_send (profiler, ensure_logbuf (0));
4249 static MonoProfiler*
4250 create_profiler (const char *filename, GPtrArray *filters)
4254 int force_delete = 0;
4255 prof = calloc (1, sizeof (MonoProfiler));
4257 prof->command_port = command_port;
4258 if (filename && *filename == '-') {
4264 filename = "|mprof-report -";
4266 filename = "output.mlpd";
4267 nf = (char*)filename;
4269 nf = new_filename (filename);
4271 int s = strlen (nf) + 32;
4272 char *p = malloc (s);
4273 snprintf (p, s, "|mprof-report '--out=%s' -", nf);
4279 prof->file = popen (nf + 1, "w");
4280 prof->pipe_output = 1;
4281 } else if (*nf == '#') {
4282 int fd = strtol (nf + 1, NULL, 10);
4283 prof->file = fdopen (fd, "a");
4287 prof->file = fopen (nf, "wb");
4290 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
4293 #if defined (HAVE_SYS_ZLIB)
4295 prof->gzfile = gzdopen (fileno (prof->file), "wb");
4298 if (sample_type && !do_mono_sample)
4299 need_helper_thread = setup_perf_event ();
4301 /* FIXME: warn if different freq or sample type */
4305 if (do_mono_sample) {
4306 prof->stat_buffers = create_stat_buffer ();
4307 need_helper_thread = 1;
4309 if (do_counters && !need_helper_thread) {
4310 need_helper_thread = 1;
4313 prof->sorted_sample_events = g_ptr_array_sized_new (BUFFER_SIZE / SAMPLE_EVENT_SIZE_IN_SLOTS (0));
4315 #ifdef DISABLE_HELPER_THREAD
4316 if (hs_mode_ondemand)
4317 fprintf (stderr, "Ondemand heapshot unavailable on this arch.\n");
4320 fprintf (stderr, "Coverage unavailable on this arch.\n");
4324 mono_lock_free_queue_init (&prof->writer_queue);
4325 mono_mutex_init (&prof->method_table_mutex);
4326 prof->method_table = mono_conc_hashtable_new (NULL, NULL);
4329 coverage_init (prof);
4330 prof->coverage_filters = filters;
4332 prof->startup_time = current_time ();
4339 printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
4340 printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
4341 printf ("Options:\n");
4342 printf ("\thelp show this usage info\n");
4343 printf ("\t[no]alloc enable/disable recording allocation info\n");
4344 printf ("\t[no]calls enable/disable recording enter/leave method events\n");
4345 printf ("\theapshot[=MODE] record heap shot info (by default at each major collection)\n");
4346 printf ("\t MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
4347 printf ("\tcounters sample counters every 1s\n");
4348 printf ("\tsample[=TYPE] use statistical sampling mode (by default cycles/1000)\n");
4349 printf ("\t TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
4350 printf ("\t TYPE can be followed by /FREQUENCY\n");
4351 printf ("\ttime=fast use a faster (but more inaccurate) timer\n");
4352 printf ("\tmaxframes=NUM collect up to NUM stack frames\n");
4353 printf ("\tcalldepth=NUM ignore method events for call chain depth bigger than NUM\n");
4354 printf ("\toutput=FILENAME write the data to file FILENAME (-FILENAME to overwrite)\n");
4355 printf ("\toutput=|PROGRAM write the data to the stdin of PROGRAM\n");
4356 printf ("\t %%t is subtituted with date and time, %%p with the pid\n");
4357 printf ("\treport create a report instead of writing the raw data to a file\n");
4358 printf ("\tzip compress the output data\n");
4359 printf ("\tport=PORTNUM use PORTNUM for the listening command server\n");
4360 printf ("\tcoverage enable collection of code coverage data\n");
4361 printf ("\tcovfilter=ASSEMBLY add an assembly to the code coverage filters\n");
4362 printf ("\t add a + to include the assembly or a - to exclude it\n");
4363 printf ("\t filter=-mscorlib\n");
4364 printf ("\tcovfilter-file=FILE use FILE to generate the list of assemblies to be filtered\n");
4370 match_option (const char* p, const char *opt, char **rval)
4372 int len = strlen (opt);
4373 if (strncmp (p, opt, len) == 0) {
4375 if (p [len] == '=' && p [len + 1]) {
4376 const char *opt = p + len + 1;
4377 const char *end = strchr (opt, ',');
4385 val = malloc (l + 1);
4386 memcpy (val, opt, l);
4391 if (p [len] == 0 || p [len] == ',') {
4393 return p + len + (p [len] == ',');
4411 static const SampleMode sample_modes [] = {
4412 {"cycles", SAMPLE_CYCLES},
4413 {"instr", SAMPLE_INSTRUCTIONS},
4414 {"cachemiss", SAMPLE_CACHE_MISSES},
4415 {"cacherefs", SAMPLE_CACHE_REFS},
4416 {"branches", SAMPLE_BRANCHES},
4417 {"branchmiss", SAMPLE_BRANCH_MISSES},
4422 set_sample_mode (char* val, int allow_empty)
4425 char *maybe_freq = NULL;
4427 const SampleMode *smode = sample_modes;
4428 #ifndef USE_PERF_EVENTS
4431 if (allow_empty && !val) {
4432 sample_type = SAMPLE_CYCLES;
4436 if (strcmp (val, "mono") == 0) {
4438 sample_type = SAMPLE_CYCLES;
4442 for (smode = sample_modes; smode->name; smode++) {
4443 int l = strlen (smode->name);
4444 if (strncmp (val, smode->name, l) == 0) {
4445 sample_type = smode->sample_mode;
4446 maybe_freq = val + l;
4452 if (*maybe_freq == '/') {
4453 count = strtoul (maybe_freq + 1, &end, 10);
4454 if (maybe_freq + 1 == end)
4456 sample_freq = count;
4457 } else if (*maybe_freq != 0) {
4466 set_hsmode (char* val, int allow_empty)
4470 if (allow_empty && !val)
4472 if (strcmp (val, "ondemand") == 0) {
4473 hs_mode_ondemand = 1;
4477 count = strtoul (val, &end, 10);
4480 if (strcmp (end, "ms") == 0)
4482 else if (strcmp (end, "gc") == 0)
4490 * declaration to silence the compiler: this is the entry point that
4491 * mono will load from the shared library and call.
4494 mono_profiler_startup (const char *desc);
4497 mono_profiler_startup_log (const char *desc);
4500 * this is the entry point that will be used when the profiler
4501 * is embedded inside the main executable.
4504 mono_profiler_startup_log (const char *desc)
4506 mono_profiler_startup (desc);
4510 mono_profiler_startup (const char *desc)
4513 GPtrArray *filters = NULL;
4514 char *filename = NULL;
4518 int calls_enabled = 0;
4519 int allocs_enabled = 0;
4520 int only_counters = 0;
4521 int only_coverage = 0;
4522 int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
4523 MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
4524 MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
4525 MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS|
4526 MONO_PROFILE_INS_COVERAGE|MONO_PROFILE_APPDOMAIN_EVENTS|MONO_PROFILE_CONTEXT_EVENTS|
4527 MONO_PROFILE_ASSEMBLY_EVENTS;
4530 if (strncmp (p, "log", 3))
4535 for (; *p; p = opt) {
4541 if ((opt = match_option (p, "help", NULL)) != p) {
4545 if ((opt = match_option (p, "calls", NULL)) != p) {
4549 if ((opt = match_option (p, "nocalls", NULL)) != p) {
4550 events &= ~MONO_PROFILE_ENTER_LEAVE;
4554 if ((opt = match_option (p, "alloc", NULL)) != p) {
4558 if ((opt = match_option (p, "noalloc", NULL)) != p) {
4559 events &= ~MONO_PROFILE_ALLOCATIONS;
4562 if ((opt = match_option (p, "time", &val)) != p) {
4563 if (strcmp (val, "fast") == 0)
4565 else if (strcmp (val, "null") == 0)
4572 if ((opt = match_option (p, "report", NULL)) != p) {
4576 if ((opt = match_option (p, "debug", NULL)) != p) {
4580 if ((opt = match_option (p, "sampling-real", NULL)) != p) {
4581 sampling_mode = MONO_PROFILER_STAT_MODE_REAL;
4584 if ((opt = match_option (p, "sampling-process", NULL)) != p) {
4585 sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
4588 if ((opt = match_option (p, "heapshot", &val)) != p) {
4589 events &= ~MONO_PROFILE_ALLOCATIONS;
4590 events &= ~MONO_PROFILE_ENTER_LEAVE;
4593 set_hsmode (val, 1);
4596 if ((opt = match_option (p, "sample", &val)) != p) {
4597 events &= ~MONO_PROFILE_ALLOCATIONS;
4598 events &= ~MONO_PROFILE_ENTER_LEAVE;
4600 set_sample_mode (val, 1);
4603 if ((opt = match_option (p, "hsmode", &val)) != p) {
4604 fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
4605 set_hsmode (val, 0);
4608 if ((opt = match_option (p, "zip", NULL)) != p) {
4612 if ((opt = match_option (p, "output", &val)) != p) {
4616 if ((opt = match_option (p, "port", &val)) != p) {
4618 command_port = strtoul (val, &end, 10);
4622 if ((opt = match_option (p, "maxframes", &val)) != p) {
4624 num_frames = strtoul (val, &end, 10);
4625 if (num_frames > MAX_FRAMES)
4626 num_frames = MAX_FRAMES;
4628 notraces = num_frames == 0;
4631 if ((opt = match_option (p, "calldepth", &val)) != p) {
4633 max_call_depth = strtoul (val, &end, 10);
4637 if ((opt = match_option (p, "counters", NULL)) != p) {
4641 if ((opt = match_option (p, "countersonly", NULL)) != p) {
4645 if ((opt = match_option (p, "coverage", NULL)) != p) {
4647 events |= MONO_PROFILE_ENTER_LEAVE;
4648 debug_coverage = (g_getenv ("MONO_PROFILER_DEBUG_COVERAGE") != NULL);
4651 if ((opt = match_option (p, "onlycoverage", NULL)) != p) {
4655 if ((opt = match_option (p, "covfilter-file", &val)) != p) {
4657 char *line, *content;
4659 if (filters == NULL)
4660 filters = g_ptr_array_new ();
4662 filter_file = fopen (val, "r");
4663 if (filter_file == NULL) {
4664 fprintf (stderr, "Unable to open %s\n", val);
4668 /* Don't need to free content as it is referred to by the lines stored in @filters */
4669 content = get_file_content (filter_file);
4670 if (content == NULL)
4671 fprintf (stderr, "WARNING: %s is greater than 128kb - ignoring\n", val);
4673 while ((line = get_next_line (content, &content)))
4674 g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
4676 fclose (filter_file);
4679 if ((opt = match_option (p, "covfilter", &val)) != p) {
4680 if (filters == NULL)
4681 filters = g_ptr_array_new ();
4683 g_ptr_array_add (filters, val);
4691 if (calls_enabled) {
4692 events |= MONO_PROFILE_ENTER_LEAVE;
4696 events |= MONO_PROFILE_ALLOCATIONS;
4700 events = MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_INS_COVERAGE;
4702 utils_init (fast_time);
4704 prof = create_profiler (filename, filters);
4709 mono_profiler_install (prof, log_shutdown);
4710 mono_profiler_install_gc (gc_event, gc_resize);
4711 mono_profiler_install_allocation (gc_alloc);
4712 mono_profiler_install_gc_moves (gc_moves);
4713 mono_profiler_install_gc_roots (gc_handle, gc_roots);
4714 mono_profiler_install_appdomain (NULL, domain_loaded, NULL, domain_unloaded);
4715 mono_profiler_install_appdomain_name (domain_name);
4716 mono_profiler_install_context (context_loaded, context_unloaded);
4717 mono_profiler_install_class (NULL, class_loaded, NULL, class_unloaded);
4718 mono_profiler_install_module (NULL, image_loaded, NULL, image_unloaded);
4719 mono_profiler_install_assembly (NULL, assembly_loaded, NULL, assembly_unloaded);
4720 mono_profiler_install_thread (thread_start, thread_end);
4721 mono_profiler_install_thread_name (thread_name);
4722 mono_profiler_install_enter_leave (method_enter, method_leave);
4723 mono_profiler_install_jit_end (method_jitted);
4724 mono_profiler_install_code_buffer_new (code_buffer_new);
4725 mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
4726 mono_profiler_install_monitor (monitor_event);
4727 mono_profiler_install_runtime_initialized (runtime_initialized);
4729 mono_profiler_install_coverage_filter (coverage_filter);
4731 if (do_mono_sample && sample_type == SAMPLE_CYCLES && !only_counters) {
4732 events |= MONO_PROFILE_STATISTICAL;
4733 mono_profiler_set_statistical_mode (sampling_mode, 1000000 / sample_freq);
4734 mono_profiler_install_statistical (mono_sample_hit);
4737 mono_profiler_set_events (events);
4739 TLS_INIT (tlsbuffer);
4740 TLS_INIT (tlsmethodlist);