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-os-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>
84 #ifdef ENABLE_PERF_EVENTS
85 #include <linux/perf_event.h>
87 #define USE_PERF_EVENTS 1
89 static int read_perf_mmap (MonoProfiler* prof, int cpu);
94 #define BUFFER_SIZE (4096 * 16)
96 /* Worst-case size in bytes of a 64-bit value encoded with LEB128. */
97 #define LEB128_SIZE 10
98 /* Size in bytes of the event ID prefix. */
101 static int nocalls = 0;
102 static int notraces = 0;
103 static int use_zip = 0;
104 static int do_report = 0;
105 static int do_heap_shot = 0;
106 static int max_call_depth = 100;
107 static volatile int runtime_inited = 0;
108 static int need_helper_thread = 0;
109 static int command_port = 0;
110 static int heapshot_requested = 0;
111 static int sample_type = 0;
112 static int sample_freq = 0;
113 static int do_mono_sample = 0;
114 static int in_shutdown = 0;
115 static int do_debug = 0;
116 static int do_counters = 0;
117 static int do_coverage = 0;
118 static gboolean debug_coverage = FALSE;
119 static MonoProfileSamplingMode sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
121 typedef struct _LogBuffer LogBuffer;
127 * The file is composed by a header followed by 0 or more buffers.
128 * Each buffer contains events that happened on a thread: for a given thread
129 * buffers that appear later in the file are guaranteed to contain events
130 * that happened later in time. Buffers from separate threads could be interleaved,
132 * Buffers are not required to be aligned.
135 * [id: 4 bytes] constant value: LOG_HEADER_ID
136 * [major: 1 byte] [minor: 1 byte] major and minor version of the log profiler
137 * [format: 1 byte] version of the data format for the rest of the file
138 * [ptrsize: 1 byte] size in bytes of a pointer in the profiled program
139 * [startup time: 8 bytes] time in milliseconds since the unix epoch when the program started
140 * [timer overhead: 4 bytes] approximate overhead in nanoseconds of the timer
141 * [flags: 4 bytes] file format flags, should be 0 for now
142 * [pid: 4 bytes] pid of the profiled process
143 * [port: 2 bytes] tcp port for server if != 0
144 * [sysid: 2 bytes] operating system and architecture identifier
146 * The multiple byte integers are in little-endian format.
149 * [buffer header] [event]*
150 * Buffers have a fixed-size header followed by 0 or more bytes of event data.
151 * Timing information and other values in the event data are usually stored
152 * as uleb128 or sleb128 integers. To save space, as noted for each item below,
153 * some data is represented as a difference between the actual value and
154 * either the last value of the same type (like for timing information) or
155 * as the difference from a value stored in a buffer header.
157 * For timing information the data is stored as uleb128, since timing
158 * increases in a monotonic way in each thread: the value is the number of
159 * nanoseconds to add to the last seen timing data in a buffer. The first value
160 * in a buffer will be calculated from the time_base field in the buffer head.
162 * Object or heap sizes are stored as uleb128.
163 * Pointer differences are stored as sleb128, instead.
165 * If an unexpected value is found, the rest of the buffer should be ignored,
166 * as generally the later values need the former to be interpreted correctly.
168 * buffer header format:
169 * [bufid: 4 bytes] constant value: BUF_ID
170 * [len: 4 bytes] size of the data following the buffer header
171 * [time_base: 8 bytes] time base in nanoseconds since an unspecified epoch
172 * [ptr_base: 8 bytes] base value for pointers
173 * [obj_base: 8 bytes] base value for object addresses
174 * [thread id: 8 bytes] system-specific thread ID (pthread_t for example)
175 * [method_base: 8 bytes] base value for MonoMethod pointers
178 * [extended info: upper 4 bits] [type: lower 4 bits] [data]*
179 * The data that follows depends on type and the extended info.
180 * Type is one of the enum values in proflog.h: TYPE_ALLOC, TYPE_GC,
181 * TYPE_METADATA, TYPE_METHOD, TYPE_EXCEPTION, TYPE_MONITOR, TYPE_HEAP.
182 * The extended info bits are interpreted based on type, see
183 * each individual event description below.
184 * strings are represented as a 0-terminated utf8 sequence.
187 * [flags: uleb128] must be 0
188 * [num: uleb128] number of frames following
189 * [frame: sleb128]* num MonoMethod pointers as differences from ptr_base
193 * exinfo: flags: TYPE_ALLOC_BT
194 * [time diff: uleb128] nanoseconds since last timing
195 * [ptr: sleb128] class as a byte difference from ptr_base
196 * [obj: sleb128] object address as a byte difference from obj_base
197 * [size: uleb128] size of the object in the heap
198 * If the TYPE_ALLOC_BT flag is set, a backtrace follows.
202 * exinfo: one of TYPE_GC_EVENT, TYPE_GC_RESIZE, TYPE_GC_MOVE, TYPE_GC_HANDLE_CREATED[_BT],
203 * TYPE_GC_HANDLE_DESTROYED[_BT]
204 * [time diff: uleb128] nanoseconds since last timing
205 * if exinfo == TYPE_GC_RESIZE
206 * [heap_size: uleb128] new heap size
207 * if exinfo == TYPE_GC_EVENT
208 * [event type: uleb128] GC event (MONO_GC_EVENT_* from profiler.h)
209 * [generation: uleb128] GC generation event refers to
210 * if exinfo == TYPE_GC_MOVE
211 * [num_objects: uleb128] number of object moves that follow
212 * [objaddr: sleb128]+ num_objects object pointer differences from obj_base
213 * num is always an even number: the even items are the old
214 * addresses, the odd numbers are the respective new object addresses
215 * if exinfo == TYPE_GC_HANDLE_CREATED[_BT]
216 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
217 * upper bits reserved as flags
218 * [handle: uleb128] GC handle value
219 * [objaddr: sleb128] object pointer differences from obj_base
220 * If exinfo == TYPE_GC_HANDLE_CREATED_BT, a backtrace follows.
221 * if exinfo == TYPE_GC_HANDLE_DESTROYED[_BT]
222 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
223 * upper bits reserved as flags
224 * [handle: uleb128] GC handle value
225 * If exinfo == TYPE_GC_HANDLE_DESTROYED_BT, a backtrace follows.
227 * type metadata format:
228 * type: TYPE_METADATA
229 * exinfo: one of: TYPE_END_LOAD, TYPE_END_UNLOAD (optional for TYPE_THREAD and TYPE_DOMAIN)
230 * [time diff: uleb128] nanoseconds since last timing
231 * [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
232 * TYPE_THREAD, TYPE_CONTEXT
233 * [pointer: sleb128] pointer of the metadata type depending on mtype
234 * if mtype == TYPE_CLASS
235 * [image: sleb128] MonoImage* as a pointer difference from ptr_base
236 * [flags: uleb128] must be 0
237 * [name: string] full class name
238 * if mtype == TYPE_IMAGE
239 * [flags: uleb128] must be 0
240 * [name: string] image file name
241 * if mtype == TYPE_ASSEMBLY
242 * [flags: uleb128] must be 0
243 * [name: string] assembly name
244 * if mtype == TYPE_DOMAIN
245 * [flags: uleb128] must be 0
246 * if mtype == TYPE_DOMAIN && exinfo == 0
247 * [name: string] domain friendly name
248 * if mtype == TYPE_CONTEXT
249 * [flags: uleb128] must be 0
250 * [domain: sleb128] domain id as pointer
251 * if mtype == TYPE_THREAD && (format_version < 11 || (format_version > 10 && exinfo == 0))
252 * [flags: uleb128] must be 0
253 * [name: string] thread name
255 * type method format:
257 * exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
258 * [time diff: uleb128] nanoseconds since last timing
259 * [method: sleb128] MonoMethod* as a pointer difference from the last such
260 * pointer or the buffer method_base
261 * if exinfo == TYPE_JIT
262 * [code address: sleb128] pointer to the native code as a diff from ptr_base
263 * [code size: uleb128] size of the generated code
264 * [name: string] full method name
266 * type runtime format:
268 * exinfo: one of: TYPE_JITHELPER
269 * [time diff: uleb128] nanoseconds since last timing
270 * if exinfo == TYPE_JITHELPER
271 * [type: uleb128] MonoProfilerCodeBufferType enum value
272 * [buffer address: sleb128] pointer to the native code as a diff from ptr_base
273 * [buffer size: uleb128] size of the generated code
274 * if type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE
275 * [name: string] buffer description name
277 * type monitor format:
279 * exinfo: TYPE_MONITOR_BT flag and one of: MONO_PROFILER_MONITOR_(CONTENTION|FAIL|DONE)
280 * [time diff: uleb128] nanoseconds since last timing
281 * [object: sleb128] the lock object as a difference from obj_base
282 * if exinfo.low3bits == MONO_PROFILER_MONITOR_CONTENTION
283 * If the TYPE_MONITOR_BT flag is set, a backtrace follows.
287 * exinfo: one of TYPE_HEAP_START, TYPE_HEAP_END, TYPE_HEAP_OBJECT, TYPE_HEAP_ROOT
288 * if exinfo == TYPE_HEAP_START
289 * [time diff: uleb128] nanoseconds since last timing
290 * if exinfo == TYPE_HEAP_END
291 * [time diff: uleb128] nanoseconds since last timing
292 * if exinfo == TYPE_HEAP_OBJECT
293 * [object: sleb128] the object as a difference from obj_base
294 * [class: sleb128] the object MonoClass* as a difference from ptr_base
295 * [size: uleb128] size of the object on the heap
296 * [num_refs: uleb128] number of object references
297 * if (format version > 1) each referenced objref is preceded by a
298 * uleb128 encoded offset: the first offset is from the object address
299 * and each next offset is relative to the previous one
300 * [objrefs: sleb128]+ object referenced as a difference from obj_base
301 * The same object can appear multiple times, but only the first time
302 * with size != 0: in the other cases this data will only be used to
303 * provide additional referenced objects.
304 * if exinfo == TYPE_HEAP_ROOT
305 * [num_roots: uleb128] number of root references
306 * [num_gc: uleb128] number of major gcs
307 * [object: sleb128] the object as a difference from obj_base
308 * [root_type: uleb128] the root_type: MonoProfileGCRootType (profiler.h)
309 * [extra_info: uleb128] the extra_info value
310 * object, root_type and extra_info are repeated num_roots times
314 * exinfo: one of TYPE_SAMPLE_HIT, TYPE_SAMPLE_USYM, TYPE_SAMPLE_UBIN, TYPE_SAMPLE_COUNTERS_DESC, TYPE_SAMPLE_COUNTERS
315 * if exinfo == TYPE_SAMPLE_HIT
316 * [sample_type: uleb128] type of sample (SAMPLE_*)
317 * [timestamp: uleb128] nanoseconds since startup (note: different from other timestamps!)
318 * if (format_version > 10)
319 * [thread: sleb128] thread id as difference from ptr_base
320 * [count: uleb128] number of following instruction addresses
321 * [ip: sleb128]* instruction pointer as difference from ptr_base
322 * if (format_version > 5)
323 * [mbt_count: uleb128] number of managed backtrace info triplets (method + IL offset + native offset)
324 * [method: sleb128]* MonoMethod* as a pointer difference from the last such
325 * pointer or the buffer method_base (the first such method can be also indentified by ip, but this is not neccessarily true)
326 * [il_offset: sleb128]* IL offset inside method where the hit occurred
327 * [native_offset: sleb128]* native offset inside method where the hit occurred
328 * if exinfo == TYPE_SAMPLE_USYM
329 * [address: sleb128] symbol address as a difference from ptr_base
330 * [size: uleb128] symbol size (may be 0 if unknown)
331 * [name: string] symbol name
332 * if exinfo == TYPE_SAMPLE_UBIN
333 * [time diff: uleb128] nanoseconds since last timing
334 * [address: sleb128] address where binary has been loaded
335 * [offset: uleb128] file offset of mapping (the same file can be mapped multiple times)
336 * [size: uleb128] memory size
337 * [name: string] binary name
338 * if exinfo == TYPE_SAMPLE_COUNTERS_DESC
339 * [len: uleb128] number of counters
341 * [section: uleb128] section of counter
342 * if section == MONO_COUNTER_PERFCOUNTERS:
343 * [section_name: string] section name of counter
344 * [name: string] name of counter
345 * [type: uleb128] type of counter
346 * [unit: uleb128] unit of counter
347 * [variance: uleb128] variance of counter
348 * [index: uleb128] unique index of counter
349 * if exinfo == TYPE_SAMPLE_COUNTERS
350 * [timestamp: uleb128] sampling timestamp
352 * [index: uleb128] unique index of counter
355 * [type: uleb128] type of counter value
358 * [0: uleb128] 0 -> value is null
360 * [1: uleb128] 1 -> value is not null
361 * [value: string] counter value
363 * [value: uleb128/sleb128/double] counter value, can be sleb128, uleb128 or double (determined by using type)
365 * type coverage format
366 * type: TYPE_COVERAGE
367 * exinfo: one of TYPE_COVERAGE_METHOD, TYPE_COVERAGE_STATEMENT, TYPE_COVERAGE_ASSEMBLY, TYPE_COVERAGE_CLASS
368 * if exinfo == TYPE_COVERAGE_METHOD
369 * [assembly: string] name of assembly
370 * [class: string] name of the class
371 * [name: string] name of the method
372 * [signature: string] the signature of the method
373 * [filename: string] the file path of the file that contains this method
374 * [token: uleb128] the method token
375 * [method_id: uleb128] an ID for this data to associate with the buffers of TYPE_COVERAGE_STATEMENTS
376 * [len: uleb128] the number of TYPE_COVERAGE_BUFFERS associated with this method
377 * if exinfo == TYPE_COVERAGE_STATEMENTS
378 * [method_id: uleb128] an the TYPE_COVERAGE_METHOD buffer to associate this with
379 * [offset: uleb128] the il offset relative to the previous offset
380 * [counter: uleb128] the counter for this instruction
381 * [line: uleb128] the line of filename containing this instruction
382 * [column: uleb128] the column containing this instruction
383 * if exinfo == TYPE_COVERAGE_ASSEMBLY
384 * [name: string] assembly name
385 * [guid: string] assembly GUID
386 * [filename: string] assembly filename
387 * [number_of_methods: uleb128] the number of methods in this assembly
388 * [fully_covered: uleb128] the number of fully covered methods
389 * [partially_covered: uleb128] the number of partially covered methods
390 * currently partially_covered will always be 0, and fully_covered is the
391 * number of methods that are fully and partially covered.
392 * if exinfo == TYPE_COVERAGE_CLASS
393 * [name: string] assembly name
394 * [class: string] class name
395 * [number_of_methods: uleb128] the number of methods in this class
396 * [fully_covered: uleb128] the number of fully covered methods
397 * [partially_covered: uleb128] the number of partially covered methods
398 * currently partially_covered will always be 0, and fully_covered is the
399 * number of methods that are fully and partially covered.
403 * Format oddities that we ought to fix:
405 * - Methods written in emit_bt () should be based on the buffer's base
406 * method instead of the base pointer.
407 * - The TYPE_SAMPLE_HIT event contains (currently) pointless data like
408 * always-one unmanaged frame count and always-zero IL offsets.
410 * These are mostly small things and are not worth a format change by
411 * themselves. They should be done when some other major change has to
412 * be done to the format.
420 uintptr_t method_base;
421 uintptr_t last_method;
424 unsigned char* data_end;
429 unsigned char buf [1];
433 ign_res (int G_GNUC_UNUSED unused, ...)
437 #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++;}
438 #define EXIT_LOG(lb) (lb)->locked--;
440 typedef struct _StatBuffer StatBuffer;
449 typedef struct _BinaryObject BinaryObject;
451 struct _BinaryObject {
457 struct _MonoProfiler {
458 StatBuffer *stat_buffers;
460 #if defined (HAVE_SYS_ZLIB)
463 uint64_t startup_time;
465 int last_gc_gen_started;
470 pthread_t helper_thread;
471 pthread_t writer_thread;
473 volatile gint32 run_writer_thread;
474 MonoLockFreeQueue writer_queue;
475 MonoConcurrentHashTable *method_table;
476 mono_mutex_t method_table_mutex;
477 BinaryObject *binary_objects;
478 GPtrArray *coverage_filters;
479 GPtrArray *sorted_sample_events;
482 typedef struct _WriterQueueEntry WriterQueueEntry;
483 struct _WriterQueueEntry {
484 MonoLockFreeQueueNode node;
489 typedef struct _MethodInfo MethodInfo;
501 #define TLS_SET(x,y) (TlsSetValue (x, y))
502 #define TLS_GET(t,x) ((t *) TlsGetValue (x))
503 #define TLS_INIT(x) (x = TlsAlloc ())
504 static int tlsbuffer;
505 static int tlsmethodlist;
507 #define TLS_SET(x,y) (x = y)
508 #define TLS_GET(t,x) (x)
510 static __thread LogBuffer* tlsbuffer = NULL;
511 static __thread GPtrArray* tlsmethodlist = NULL;
513 #define TLS_SET(x,y) (pthread_setspecific (x, y))
514 #define TLS_GET(t,x) ((t *) pthread_getspecific (x))
515 #define TLS_INIT(x) (pthread_key_create (&x, NULL))
516 static pthread_key_t tlsbuffer;
517 static pthread_key_t tlsmethodlist;
520 static void safe_send (MonoProfiler *profiler, LogBuffer *logbuffer);
523 pstrdup (const char *s)
525 int len = strlen (s) + 1;
526 char *p = (char *)malloc (len);
532 create_stat_buffer (void)
534 StatBuffer* buf = (StatBuffer *)alloc_buffer (BUFFER_SIZE);
535 buf->size = BUFFER_SIZE;
536 buf->data_end = (uintptr_t*)((unsigned char*)buf + buf->size);
537 buf->data = buf->buf;
544 LogBuffer* buf = (LogBuffer *)alloc_buffer (BUFFER_SIZE);
545 buf->size = BUFFER_SIZE;
546 buf->time_base = current_time ();
547 buf->last_time = buf->time_base;
548 buf->data_end = (unsigned char*)buf + buf->size;
549 buf->data = buf->buf;
556 if (!TLS_GET (LogBuffer, tlsbuffer)) {
557 LogBuffer *logbuffer = create_buffer ();
558 TLS_SET (tlsbuffer, logbuffer);
559 logbuffer->thread_id = thread_id ();
561 if (!TLS_GET (GPtrArray, tlsmethodlist)) {
562 GPtrArray *methodlist = g_ptr_array_new ();
563 TLS_SET (tlsmethodlist, methodlist);
566 //printf ("thread %p at time %llu\n", (void*)logbuffer->thread_id, logbuffer->time_base);
570 ensure_logbuf_inner (LogBuffer *old, int bytes)
572 if (old && old->data + bytes + 100 < old->data_end)
575 LogBuffer *new_ = (LogBuffer *)create_buffer ();
576 new_->thread_id = thread_id ();
580 new_->call_depth = old->call_depth;
586 ensure_logbuf (int bytes)
588 LogBuffer *old = TLS_GET (LogBuffer, tlsbuffer);
589 LogBuffer *new_ = ensure_logbuf_inner (old, bytes);
592 return old; // Still enough space.
594 TLS_SET (tlsbuffer, new_);
601 emit_byte (LogBuffer *logbuffer, int value)
603 logbuffer->data [0] = value;
605 assert (logbuffer->data <= logbuffer->data_end);
609 emit_value (LogBuffer *logbuffer, int value)
611 encode_uleb128 (value, logbuffer->data, &logbuffer->data);
612 assert (logbuffer->data <= logbuffer->data_end);
616 emit_time (LogBuffer *logbuffer, uint64_t value)
618 uint64_t tdiff = value - logbuffer->last_time;
619 //if (value < logbuffer->last_time)
620 // printf ("time went backwards\n");
621 //if (tdiff > 1000000)
622 // printf ("large time offset: %llu\n", tdiff);
623 encode_uleb128 (tdiff, logbuffer->data, &logbuffer->data);
624 /*if (tdiff != decode_uleb128 (p, &p))
625 printf ("incorrect encoding: %llu\n", tdiff);*/
626 logbuffer->last_time = value;
627 assert (logbuffer->data <= logbuffer->data_end);
631 emit_svalue (LogBuffer *logbuffer, int64_t value)
633 encode_sleb128 (value, logbuffer->data, &logbuffer->data);
634 assert (logbuffer->data <= logbuffer->data_end);
638 emit_uvalue (LogBuffer *logbuffer, uint64_t value)
640 encode_uleb128 (value, logbuffer->data, &logbuffer->data);
641 assert (logbuffer->data <= logbuffer->data_end);
645 emit_ptr (LogBuffer *logbuffer, void *ptr)
647 if (!logbuffer->ptr_base)
648 logbuffer->ptr_base = (uintptr_t)ptr;
649 emit_svalue (logbuffer, (intptr_t)ptr - logbuffer->ptr_base);
650 assert (logbuffer->data <= logbuffer->data_end);
654 emit_method_inner (LogBuffer *logbuffer, void *method)
656 if (!logbuffer->method_base) {
657 logbuffer->method_base = (intptr_t)method;
658 logbuffer->last_method = (intptr_t)method;
660 encode_sleb128 ((intptr_t)((char*)method - (char*)logbuffer->last_method), logbuffer->data, &logbuffer->data);
661 logbuffer->last_method = (intptr_t)method;
662 assert (logbuffer->data <= logbuffer->data_end);
672 find_method (MonoDomain *domain, void *user_data)
674 MethodSearch *search = user_data;
679 MonoJitInfo *ji = mono_get_jit_info_from_method (domain, search->method);
681 // It could be AOT'd, so we need to get it from the AOT runtime's cache.
683 void *ip = mono_aot_get_method (domain, search->method);
685 // Avoid a slow path in mono_jit_info_table_find ().
687 ji = mono_jit_info_table_find (domain, ip);
696 register_method_local (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji)
698 if (!mono_conc_hashtable_lookup (prof->method_table, method)) {
700 * FIXME: In some cases, we crash while looking up JIT info for AOT'd methods.
701 * This usually happens for static constructors. This code is disabled for now
702 * as we don't need this info for anything critical.
704 * https://bugzilla.xamarin.com/show_bug.cgi?id=35171
708 MethodSearch search = { method, NULL };
710 mono_domain_foreach (find_method, &search);
717 * FIXME: We can't always find JIT info for a generic shared method, especially
718 * if we obtained the MonoMethod during an async stack walk. For now, we deal
719 * with this by giving the generic shared method name and dummy code start/size
720 * information (i.e. zeroes).
724 MethodInfo *info = (MethodInfo *)malloc (sizeof (MethodInfo));
726 info->method = method;
728 info->time = current_time ();
730 g_ptr_array_add (TLS_GET (GPtrArray, tlsmethodlist), info);
735 emit_method (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
737 register_method_local (prof, method, NULL);
738 emit_method_inner (logbuffer, method);
742 emit_method_as_ptr (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
744 register_method_local (prof, method, NULL);
745 emit_ptr (logbuffer, method);
749 emit_obj (LogBuffer *logbuffer, void *ptr)
751 if (!logbuffer->obj_base)
752 logbuffer->obj_base = (uintptr_t)ptr >> 3;
753 emit_svalue (logbuffer, ((uintptr_t)ptr >> 3) - logbuffer->obj_base);
754 assert (logbuffer->data <= logbuffer->data_end);
758 emit_string (LogBuffer *logbuffer, const char *str, size_t size)
762 for (; i < size; i++) {
765 emit_byte (logbuffer, str [i]);
768 emit_byte (logbuffer, '\0');
772 emit_double (LogBuffer *logbuffer, double value)
775 unsigned char buffer[8];
776 memcpy (buffer, &value, 8);
777 #if G_BYTE_ORDER == G_BIG_ENDIAN
778 for (i = 7; i >= 0; i--)
780 for (i = 0; i < 8; i++)
782 emit_byte (logbuffer, buffer[i]);
786 write_int16 (char *buf, int32_t value)
789 for (i = 0; i < 2; ++i) {
797 write_int32 (char *buf, int32_t value)
800 for (i = 0; i < 4; ++i) {
808 write_int64 (char *buf, int64_t value)
811 for (i = 0; i < 8; ++i) {
819 dump_header (MonoProfiler *profiler)
823 p = write_int32 (p, LOG_HEADER_ID);
824 *p++ = LOG_VERSION_MAJOR;
825 *p++ = LOG_VERSION_MINOR;
826 *p++ = LOG_DATA_VERSION;
827 *p++ = sizeof (void*);
828 p = write_int64 (p, ((uint64_t)time (NULL)) * 1000); /* startup time */
829 p = write_int32 (p, get_timer_overhead ()); /* timer overhead */
830 p = write_int32 (p, 0); /* flags */
831 p = write_int32 (p, process_id ()); /* pid */
832 p = write_int16 (p, profiler->command_port); /* port */
833 p = write_int16 (p, 0); /* opsystem */
834 #if defined (HAVE_SYS_ZLIB)
835 if (profiler->gzfile) {
836 gzwrite (profiler->gzfile, hbuf, p - hbuf);
838 fwrite (hbuf, p - hbuf, 1, profiler->file);
841 fwrite (hbuf, p - hbuf, 1, profiler->file);
842 fflush (profiler->file);
847 send_buffer (MonoProfiler *prof, GPtrArray *methods, LogBuffer *buffer)
849 WriterQueueEntry *entry = (WriterQueueEntry *)calloc (1, sizeof (WriterQueueEntry));
850 mono_lock_free_queue_node_init (&entry->node, FALSE);
851 entry->methods = methods;
852 entry->buffer = buffer;
853 mono_lock_free_queue_enqueue (&prof->writer_queue, &entry->node);
857 dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
862 dump_buffer (profiler, buf->next);
863 p = write_int32 (p, BUF_ID);
864 p = write_int32 (p, buf->data - buf->buf);
865 p = write_int64 (p, buf->time_base);
866 p = write_int64 (p, buf->ptr_base);
867 p = write_int64 (p, buf->obj_base);
868 p = write_int64 (p, buf->thread_id);
869 p = write_int64 (p, buf->method_base);
870 #if defined (HAVE_SYS_ZLIB)
871 if (profiler->gzfile) {
872 gzwrite (profiler->gzfile, hbuf, p - hbuf);
873 gzwrite (profiler->gzfile, buf->buf, buf->data - buf->buf);
876 fwrite (hbuf, p - hbuf, 1, profiler->file);
877 fwrite (buf->buf, buf->data - buf->buf, 1, profiler->file);
878 fflush (profiler->file);
879 #if defined (HAVE_SYS_ZLIB)
882 free_buffer (buf, buf->size);
886 process_requests (MonoProfiler *profiler)
888 if (heapshot_requested)
889 mono_gc_collect (mono_gc_max_generation ());
892 static void counters_init (MonoProfiler *profiler);
893 static void counters_sample (MonoProfiler *profiler, uint64_t timestamp);
896 * Can be called only at safe callback locations.
899 safe_send (MonoProfiler *profiler, LogBuffer *logbuffer)
901 /* We need the runtime initialized so that we have threads and hazard
902 * pointers available. Otherwise, the lock free queue will not work and
903 * there won't be a thread to process the data.
905 * While the runtime isn't initialized, we just accumulate data in the
906 * thread local buffer list.
908 if (!InterlockedRead (&runtime_inited))
911 int cd = logbuffer->call_depth;
913 send_buffer (profiler, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
915 TLS_SET (tlsbuffer, NULL);
916 TLS_SET (tlsmethodlist, NULL);
920 TLS_GET (LogBuffer, tlsbuffer)->call_depth = cd;
924 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
927 uintptr_t last_offset = 0;
928 //const char *name = mono_class_get_name (klass);
929 LogBuffer *logbuffer = ensure_logbuf (
930 EVENT_SIZE /* event */ +
931 LEB128_SIZE /* obj */ +
932 LEB128_SIZE /* klass */ +
933 LEB128_SIZE /* size */ +
934 LEB128_SIZE /* num */ +
936 LEB128_SIZE /* offset */ +
937 LEB128_SIZE /* ref */
940 emit_byte (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
941 emit_obj (logbuffer, obj);
942 emit_ptr (logbuffer, klass);
943 /* account for object alignment in the heap */
946 emit_value (logbuffer, size);
947 emit_value (logbuffer, num);
948 for (i = 0; i < num; ++i) {
949 emit_value (logbuffer, offsets [i] - last_offset);
950 last_offset = offsets [i];
951 emit_obj (logbuffer, refs [i]);
954 // printf ("obj: %p, klass: %s, refs: %d, size: %d\n", obj, name, (int)num, (int)size);
958 static unsigned int hs_mode_ms = 0;
959 static unsigned int hs_mode_gc = 0;
960 static unsigned int hs_mode_ondemand = 0;
961 static unsigned int gc_count = 0;
962 static uint64_t last_hs_time = 0;
965 heap_walk (MonoProfiler *profiler)
969 LogBuffer *logbuffer;
972 logbuffer = ensure_logbuf (
973 EVENT_SIZE /* event */ +
974 LEB128_SIZE /* time */
976 now = current_time ();
977 if (hs_mode_ms && (now - last_hs_time)/1000000 >= hs_mode_ms)
979 else if (hs_mode_gc && (gc_count % hs_mode_gc) == 0)
981 else if (hs_mode_ondemand)
982 do_walk = heapshot_requested;
983 else if (!hs_mode_ms && !hs_mode_gc && profiler->last_gc_gen_started == mono_gc_max_generation ())
988 heapshot_requested = 0;
989 emit_byte (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
990 emit_time (logbuffer, now);
991 mono_gc_walk_heap (0, gc_reference, NULL);
992 logbuffer = ensure_logbuf (
993 EVENT_SIZE /* event */ +
994 LEB128_SIZE /* time */
996 now = current_time ();
997 emit_byte (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
998 emit_time (logbuffer, now);
1003 gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation) {
1005 LogBuffer *logbuffer = ensure_logbuf (
1006 EVENT_SIZE /* event */ +
1007 LEB128_SIZE /* time */ +
1008 LEB128_SIZE /* gc event */ +
1009 LEB128_SIZE /* generation */
1011 now = current_time ();
1012 ENTER_LOG (logbuffer, "gcevent");
1013 emit_byte (logbuffer, TYPE_GC_EVENT | TYPE_GC);
1014 emit_time (logbuffer, now);
1015 emit_value (logbuffer, ev);
1016 emit_value (logbuffer, generation);
1017 /* to deal with nested gen1 after gen0 started */
1018 if (ev == MONO_GC_EVENT_START) {
1019 profiler->last_gc_gen_started = generation;
1020 if (generation == mono_gc_max_generation ())
1023 if (ev == MONO_GC_EVENT_PRE_START_WORLD)
1024 heap_walk (profiler);
1025 EXIT_LOG (logbuffer);
1026 if (ev == MONO_GC_EVENT_POST_START_WORLD)
1027 safe_send (profiler, logbuffer);
1028 //printf ("gc event %d for generation %d\n", ev, generation);
1032 gc_resize (MonoProfiler *profiler, int64_t new_size) {
1034 LogBuffer *logbuffer = ensure_logbuf (
1035 EVENT_SIZE /* event */ +
1036 LEB128_SIZE /* time */ +
1037 LEB128_SIZE /* new size */
1039 now = current_time ();
1040 ENTER_LOG (logbuffer, "gcresize");
1041 emit_byte (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
1042 emit_time (logbuffer, now);
1043 emit_value (logbuffer, new_size);
1044 //printf ("gc resized to %lld\n", new_size);
1045 EXIT_LOG (logbuffer);
1048 #define MAX_FRAMES 32
1051 MonoMethod* methods [MAX_FRAMES];
1052 int32_t il_offsets [MAX_FRAMES];
1053 int32_t native_offsets [MAX_FRAMES];
1055 static int num_frames = MAX_FRAMES;
1058 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
1060 FrameData *frame = (FrameData *)data;
1061 if (method && frame->count < num_frames) {
1062 frame->il_offsets [frame->count] = il_offset;
1063 frame->native_offsets [frame->count] = native_offset;
1064 frame->methods [frame->count++] = method;
1065 //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
1067 return frame->count == num_frames;
1071 * a note about stack walks: they can cause more profiler events to fire,
1072 * so we need to make sure they don't happen after we started emitting an
1073 * event, hence the collect_bt/emit_bt split.
1076 collect_bt (FrameData *data)
1079 mono_stack_walk_no_il (walk_stack, data);
1083 emit_bt (MonoProfiler *prof, LogBuffer *logbuffer, FrameData *data)
1085 /* FIXME: this is actually tons of data and we should
1086 * just output it the first time and use an id the next
1088 if (data->count > num_frames)
1089 printf ("bad num frames: %d\n", data->count);
1090 emit_value (logbuffer, 0); /* flags */
1091 emit_value (logbuffer, data->count);
1092 //if (*p != data.count) {
1093 // 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);}
1094 while (data->count) {
1095 emit_method_as_ptr (prof, logbuffer, data->methods [--data->count]);
1100 gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1104 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces)? TYPE_ALLOC_BT: 0;
1106 LogBuffer *logbuffer;
1107 len = mono_object_get_size (obj);
1108 /* account for object alignment in the heap */
1113 logbuffer = ensure_logbuf (
1114 EVENT_SIZE /* event */ +
1115 LEB128_SIZE /* time */ +
1116 LEB128_SIZE /* klass */ +
1117 LEB128_SIZE /* obj */ +
1118 LEB128_SIZE /* size */ +
1120 LEB128_SIZE /* flags */ +
1121 LEB128_SIZE /* count */ +
1123 LEB128_SIZE /* method */
1127 now = current_time ();
1128 ENTER_LOG (logbuffer, "gcalloc");
1129 emit_byte (logbuffer, do_bt | TYPE_ALLOC);
1130 emit_time (logbuffer, now);
1131 emit_ptr (logbuffer, klass);
1132 emit_obj (logbuffer, obj);
1133 emit_value (logbuffer, len);
1135 emit_bt (prof, logbuffer, &data);
1136 EXIT_LOG (logbuffer);
1137 if (logbuffer->next)
1138 safe_send (prof, logbuffer);
1139 process_requests (prof);
1140 //printf ("gc alloc %s at %p\n", mono_class_get_name (klass), obj);
1144 gc_moves (MonoProfiler *prof, void **objects, int num)
1148 LogBuffer *logbuffer = ensure_logbuf (
1149 EVENT_SIZE /* event */ +
1150 LEB128_SIZE /* time */ +
1151 LEB128_SIZE /* num */ +
1153 LEB128_SIZE /* object */
1156 now = current_time ();
1157 ENTER_LOG (logbuffer, "gcmove");
1158 emit_byte (logbuffer, TYPE_GC_MOVE | TYPE_GC);
1159 emit_time (logbuffer, now);
1160 emit_value (logbuffer, num);
1161 for (i = 0; i < num; ++i)
1162 emit_obj (logbuffer, objects [i]);
1163 //printf ("gc moved %d objects\n", num/2);
1164 EXIT_LOG (logbuffer);
1168 gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
1171 LogBuffer *logbuffer = ensure_logbuf (
1172 EVENT_SIZE /* event */ +
1173 LEB128_SIZE /* num */ +
1174 LEB128_SIZE /* collections */ +
1176 LEB128_SIZE /* object */ +
1177 LEB128_SIZE /* root type */ +
1178 LEB128_SIZE /* extra info */
1181 ENTER_LOG (logbuffer, "gcroots");
1182 emit_byte (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
1183 emit_value (logbuffer, num);
1184 emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
1185 for (i = 0; i < num; ++i) {
1186 emit_obj (logbuffer, objects [i]);
1187 emit_value (logbuffer, root_types [i]);
1188 emit_value (logbuffer, extra_info [i]);
1190 EXIT_LOG (logbuffer);
1194 gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
1196 int do_bt = nocalls && InterlockedRead (&runtime_inited) && !notraces;
1203 LogBuffer *logbuffer = ensure_logbuf (
1204 EVENT_SIZE /* event */ +
1205 LEB128_SIZE /* time */ +
1206 LEB128_SIZE /* type */ +
1207 LEB128_SIZE /* handle */ +
1208 (op == MONO_PROFILER_GC_HANDLE_CREATED ? (
1209 LEB128_SIZE /* obj */
1212 LEB128_SIZE /* flags */ +
1213 LEB128_SIZE /* count */ +
1215 LEB128_SIZE /* method */
1220 now = current_time ();
1221 ENTER_LOG (logbuffer, "gchandle");
1223 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1224 emit_byte (logbuffer, (do_bt ? TYPE_GC_HANDLE_CREATED_BT : TYPE_GC_HANDLE_CREATED) | TYPE_GC);
1225 else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
1226 emit_byte (logbuffer, (do_bt ? TYPE_GC_HANDLE_DESTROYED_BT : TYPE_GC_HANDLE_DESTROYED) | TYPE_GC);
1228 g_assert_not_reached ();
1230 emit_time (logbuffer, now);
1231 emit_value (logbuffer, type);
1232 emit_value (logbuffer, handle);
1234 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1235 emit_obj (logbuffer, obj);
1238 emit_bt (prof, logbuffer, &data);
1240 EXIT_LOG (logbuffer);
1241 process_requests (prof);
1245 push_nesting (char *p, MonoClass *klass)
1250 nesting = mono_class_get_nesting_type (klass);
1252 p = push_nesting (p, nesting);
1256 name = mono_class_get_name (klass);
1257 nspace = mono_class_get_namespace (klass);
1260 p += strlen (nspace);
1270 type_name (MonoClass *klass)
1274 push_nesting (buf, klass);
1275 p = (char *)malloc (strlen (buf) + 1);
1281 image_loaded (MonoProfiler *prof, MonoImage *image, int result)
1286 LogBuffer *logbuffer;
1287 if (result != MONO_PROFILE_OK)
1289 name = mono_image_get_filename (image);
1290 nlen = strlen (name) + 1;
1291 logbuffer = ensure_logbuf (
1292 EVENT_SIZE /* event */ +
1293 LEB128_SIZE /* time */ +
1294 EVENT_SIZE /* type */ +
1295 LEB128_SIZE /* image */ +
1296 LEB128_SIZE /* flags */ +
1299 now = current_time ();
1300 ENTER_LOG (logbuffer, "image");
1301 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1302 emit_time (logbuffer, now);
1303 emit_byte (logbuffer, TYPE_IMAGE);
1304 emit_ptr (logbuffer, image);
1305 emit_value (logbuffer, 0); /* flags */
1306 memcpy (logbuffer->data, name, nlen);
1307 logbuffer->data += nlen;
1308 //printf ("loaded image %p (%s)\n", image, name);
1309 EXIT_LOG (logbuffer);
1310 if (logbuffer->next)
1311 safe_send (prof, logbuffer);
1312 process_requests (prof);
1316 image_unloaded (MonoProfiler *prof, MonoImage *image)
1318 const char *name = mono_image_get_filename (image);
1319 int nlen = strlen (name) + 1;
1320 LogBuffer *logbuffer = ensure_logbuf (
1321 EVENT_SIZE /* event */ +
1322 LEB128_SIZE /* time */ +
1323 EVENT_SIZE /* type */ +
1324 LEB128_SIZE /* image */ +
1325 LEB128_SIZE /* flags */ +
1328 uint64_t now = current_time ();
1330 ENTER_LOG (logbuffer, "image-unload");
1331 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1332 emit_time (logbuffer, now);
1333 emit_byte (logbuffer, TYPE_IMAGE);
1334 emit_ptr (logbuffer, image);
1335 emit_value (logbuffer, 0); /* flags */
1336 memcpy (logbuffer->data, name, nlen);
1337 logbuffer->data += nlen;
1338 EXIT_LOG (logbuffer);
1340 if (logbuffer->next)
1341 safe_send (prof, logbuffer);
1343 process_requests (prof);
1347 assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly, int result)
1349 if (result != MONO_PROFILE_OK)
1352 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1353 int nlen = strlen (name) + 1;
1354 LogBuffer *logbuffer = ensure_logbuf (
1355 EVENT_SIZE /* event */ +
1356 LEB128_SIZE /* time */ +
1357 EVENT_SIZE /* type */ +
1358 LEB128_SIZE /* assembly */ +
1359 LEB128_SIZE /* flags */ +
1362 uint64_t now = current_time ();
1364 ENTER_LOG (logbuffer, "assembly-load");
1365 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1366 emit_time (logbuffer, now);
1367 emit_byte (logbuffer, TYPE_ASSEMBLY);
1368 emit_ptr (logbuffer, assembly);
1369 emit_value (logbuffer, 0); /* flags */
1370 memcpy (logbuffer->data, name, nlen);
1371 logbuffer->data += nlen;
1372 EXIT_LOG (logbuffer);
1376 if (logbuffer->next)
1377 safe_send (prof, logbuffer);
1379 process_requests (prof);
1383 assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
1385 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1386 int nlen = strlen (name) + 1;
1387 LogBuffer *logbuffer = ensure_logbuf (
1388 EVENT_SIZE /* event */ +
1389 LEB128_SIZE /* time */ +
1390 EVENT_SIZE /* type */ +
1391 LEB128_SIZE /* assembly */ +
1392 LEB128_SIZE /* flags */ +
1395 uint64_t now = current_time ();
1397 ENTER_LOG (logbuffer, "assembly-unload");
1398 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1399 emit_time (logbuffer, now);
1400 emit_byte (logbuffer, TYPE_ASSEMBLY);
1401 emit_ptr (logbuffer, assembly);
1402 emit_value (logbuffer, 0); /* flags */
1403 memcpy (logbuffer->data, name, nlen);
1404 logbuffer->data += nlen;
1405 EXIT_LOG (logbuffer);
1409 if (logbuffer->next)
1410 safe_send (prof, logbuffer);
1412 process_requests (prof);
1416 class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
1422 LogBuffer *logbuffer;
1423 if (result != MONO_PROFILE_OK)
1425 if (InterlockedRead (&runtime_inited))
1426 name = mono_type_get_name (mono_class_get_type (klass));
1428 name = type_name (klass);
1429 nlen = strlen (name) + 1;
1430 image = mono_class_get_image (klass);
1431 logbuffer = ensure_logbuf (
1432 EVENT_SIZE /* event */ +
1433 LEB128_SIZE /* time */ +
1434 EVENT_SIZE /* type */ +
1435 LEB128_SIZE /* klass */ +
1436 LEB128_SIZE /* image */ +
1437 LEB128_SIZE /* flags */ +
1440 now = current_time ();
1441 ENTER_LOG (logbuffer, "class");
1442 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1443 emit_time (logbuffer, now);
1444 emit_byte (logbuffer, TYPE_CLASS);
1445 emit_ptr (logbuffer, klass);
1446 emit_ptr (logbuffer, image);
1447 emit_value (logbuffer, 0); /* flags */
1448 memcpy (logbuffer->data, name, nlen);
1449 logbuffer->data += nlen;
1450 //printf ("loaded class %p (%s)\n", klass, name);
1455 EXIT_LOG (logbuffer);
1456 if (logbuffer->next)
1457 safe_send (prof, logbuffer);
1458 process_requests (prof);
1462 class_unloaded (MonoProfiler *prof, MonoClass *klass)
1466 if (InterlockedRead (&runtime_inited))
1467 name = mono_type_get_name (mono_class_get_type (klass));
1469 name = type_name (klass);
1471 int nlen = strlen (name) + 1;
1472 MonoImage *image = mono_class_get_image (klass);
1473 LogBuffer *logbuffer = ensure_logbuf (
1474 EVENT_SIZE /* event */ +
1475 LEB128_SIZE /* time */ +
1476 EVENT_SIZE /* type */ +
1477 LEB128_SIZE /* klass */ +
1478 LEB128_SIZE /* image */ +
1479 LEB128_SIZE /* flags */ +
1482 uint64_t now = current_time ();
1484 ENTER_LOG (logbuffer, "class-unload");
1485 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1486 emit_time (logbuffer, now);
1487 emit_byte (logbuffer, TYPE_CLASS);
1488 emit_ptr (logbuffer, klass);
1489 emit_ptr (logbuffer, image);
1490 emit_value (logbuffer, 0); /* flags */
1491 memcpy (logbuffer->data, name, nlen);
1492 logbuffer->data += nlen;
1493 EXIT_LOG (logbuffer);
1500 if (logbuffer->next)
1501 safe_send (prof, logbuffer);
1503 process_requests (prof);
1506 #ifndef DISABLE_HELPER_THREAD
1507 static void process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method);
1508 #endif /* DISABLE_HELPER_THREAD */
1511 method_enter (MonoProfiler *prof, MonoMethod *method)
1513 uint64_t now = current_time ();
1515 #ifndef DISABLE_HELPER_THREAD
1516 process_method_enter_coverage (prof, method);
1517 #endif /* DISABLE_HELPER_THREAD */
1519 LogBuffer *logbuffer = ensure_logbuf (
1520 EVENT_SIZE /* event */ +
1521 LEB128_SIZE /* time */ +
1522 LEB128_SIZE /* method */
1524 if (logbuffer->call_depth++ > max_call_depth)
1526 ENTER_LOG (logbuffer, "enter");
1527 emit_byte (logbuffer, TYPE_ENTER | TYPE_METHOD);
1528 emit_time (logbuffer, now);
1529 emit_method (prof, logbuffer, method);
1530 EXIT_LOG (logbuffer);
1532 process_requests (prof);
1536 method_leave (MonoProfiler *prof, MonoMethod *method)
1539 LogBuffer *logbuffer = ensure_logbuf (
1540 EVENT_SIZE /* event */ +
1541 LEB128_SIZE /* time */ +
1542 LEB128_SIZE /* method */
1544 if (--logbuffer->call_depth > max_call_depth)
1546 now = current_time ();
1547 ENTER_LOG (logbuffer, "leave");
1548 emit_byte (logbuffer, TYPE_LEAVE | TYPE_METHOD);
1549 emit_time (logbuffer, now);
1550 emit_method (prof, logbuffer, method);
1551 EXIT_LOG (logbuffer);
1552 if (logbuffer->next)
1553 safe_send (prof, logbuffer);
1554 process_requests (prof);
1558 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
1561 LogBuffer *logbuffer;
1564 logbuffer = ensure_logbuf (
1565 EVENT_SIZE /* event */ +
1566 LEB128_SIZE /* time */ +
1567 LEB128_SIZE /* method */
1569 if (--logbuffer->call_depth > max_call_depth)
1571 now = current_time ();
1572 ENTER_LOG (logbuffer, "eleave");
1573 emit_byte (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
1574 emit_time (logbuffer, now);
1575 emit_method (prof, logbuffer, method);
1576 EXIT_LOG (logbuffer);
1577 process_requests (prof);
1581 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji, int result)
1583 if (result != MONO_PROFILE_OK)
1586 register_method_local (prof, method, ji);
1588 process_requests (prof);
1592 code_buffer_new (MonoProfiler *prof, void *buffer, int size, MonoProfilerCodeBufferType type, void *data)
1597 LogBuffer *logbuffer;
1598 if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
1599 name = (char *)data;
1600 nlen = strlen (name) + 1;
1605 logbuffer = ensure_logbuf (
1606 EVENT_SIZE /* event */ +
1607 LEB128_SIZE /* time */ +
1608 LEB128_SIZE /* type */ +
1609 LEB128_SIZE /* buffer */ +
1610 LEB128_SIZE /* size */ +
1615 now = current_time ();
1616 ENTER_LOG (logbuffer, "code buffer");
1617 emit_byte (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
1618 emit_time (logbuffer, now);
1619 emit_value (logbuffer, type);
1620 emit_ptr (logbuffer, buffer);
1621 emit_value (logbuffer, size);
1623 memcpy (logbuffer->data, name, nlen);
1624 logbuffer->data += nlen;
1626 EXIT_LOG (logbuffer);
1627 process_requests (prof);
1631 throw_exc (MonoProfiler *prof, MonoObject *object)
1633 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces)? TYPE_EXCEPTION_BT: 0;
1636 LogBuffer *logbuffer;
1639 logbuffer = ensure_logbuf (
1640 EVENT_SIZE /* event */ +
1641 LEB128_SIZE /* time */ +
1642 LEB128_SIZE /* object */ +
1644 LEB128_SIZE /* flags */ +
1645 LEB128_SIZE /* count */ +
1647 LEB128_SIZE /* method */
1651 now = current_time ();
1652 ENTER_LOG (logbuffer, "throw");
1653 emit_byte (logbuffer, do_bt | TYPE_EXCEPTION);
1654 emit_time (logbuffer, now);
1655 emit_obj (logbuffer, object);
1657 emit_bt (prof, logbuffer, &data);
1658 EXIT_LOG (logbuffer);
1659 process_requests (prof);
1663 clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
1666 LogBuffer *logbuffer = ensure_logbuf (
1667 EVENT_SIZE /* event */ +
1668 LEB128_SIZE /* time */ +
1669 LEB128_SIZE /* clause type */ +
1670 LEB128_SIZE /* clause num */ +
1671 LEB128_SIZE /* method */
1673 now = current_time ();
1674 ENTER_LOG (logbuffer, "clause");
1675 emit_byte (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
1676 emit_time (logbuffer, now);
1677 emit_value (logbuffer, clause_type);
1678 emit_value (logbuffer, clause_num);
1679 emit_method (prof, logbuffer, method);
1680 EXIT_LOG (logbuffer);
1682 process_requests (prof);
1686 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
1688 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION)? TYPE_MONITOR_BT: 0;
1691 LogBuffer *logbuffer;
1694 logbuffer = ensure_logbuf (
1695 EVENT_SIZE /* event */ +
1696 LEB128_SIZE /* time */ +
1697 LEB128_SIZE /* object */ +
1699 LEB128_SIZE /* flags */ +
1700 LEB128_SIZE /* count */ +
1702 LEB128_SIZE /* method */
1706 now = current_time ();
1707 ENTER_LOG (logbuffer, "monitor");
1708 emit_byte (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
1709 emit_time (logbuffer, now);
1710 emit_obj (logbuffer, object);
1712 emit_bt (profiler, logbuffer, &data);
1713 EXIT_LOG (logbuffer);
1714 process_requests (profiler);
1718 thread_start (MonoProfiler *prof, uintptr_t tid)
1720 //printf ("thread start %p\n", (void*)tid);
1723 LogBuffer *logbuffer = ensure_logbuf (
1724 EVENT_SIZE /* event */ +
1725 LEB128_SIZE /* time */ +
1726 EVENT_SIZE /* type */ +
1727 LEB128_SIZE /* tid */ +
1728 LEB128_SIZE /* flags */
1730 uint64_t now = current_time ();
1732 ENTER_LOG (logbuffer, "thread-start");
1733 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1734 emit_time (logbuffer, now);
1735 emit_byte (logbuffer, TYPE_THREAD);
1736 emit_ptr (logbuffer, (void*) tid);
1737 emit_value (logbuffer, 0); /* flags */
1738 EXIT_LOG (logbuffer);
1740 if (logbuffer->next)
1741 safe_send (prof, logbuffer);
1743 process_requests (prof);
1747 thread_end (MonoProfiler *prof, uintptr_t tid)
1749 if (TLS_GET (LogBuffer, tlsbuffer)) {
1750 LogBuffer *logbuffer = ensure_logbuf (
1751 EVENT_SIZE /* event */ +
1752 LEB128_SIZE /* time */ +
1753 EVENT_SIZE /* type */ +
1754 LEB128_SIZE /* tid */ +
1755 LEB128_SIZE /* flags */
1757 uint64_t now = current_time ();
1759 ENTER_LOG (logbuffer, "thread-end");
1760 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1761 emit_time (logbuffer, now);
1762 emit_byte (logbuffer, TYPE_THREAD);
1763 emit_ptr (logbuffer, (void*) tid);
1764 emit_value (logbuffer, 0); /* flags */
1765 EXIT_LOG (logbuffer);
1767 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), logbuffer);
1769 /* Don't process requests as the thread is detached from the runtime. */
1772 TLS_SET (tlsbuffer, NULL);
1773 TLS_SET (tlsmethodlist, NULL);
1777 domain_loaded (MonoProfiler *prof, MonoDomain *domain, int result)
1779 if (result != MONO_PROFILE_OK)
1782 LogBuffer *logbuffer = ensure_logbuf (
1783 EVENT_SIZE /* event */ +
1784 LEB128_SIZE /* time */ +
1785 EVENT_SIZE /* type */ +
1786 LEB128_SIZE /* domain id */ +
1787 LEB128_SIZE /* flags */
1789 uint64_t now = current_time ();
1791 ENTER_LOG (logbuffer, "domain-start");
1792 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1793 emit_time (logbuffer, now);
1794 emit_byte (logbuffer, TYPE_DOMAIN);
1795 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1796 emit_value (logbuffer, 0); /* flags */
1797 EXIT_LOG (logbuffer);
1799 if (logbuffer->next)
1800 safe_send (prof, logbuffer);
1802 process_requests (prof);
1806 domain_unloaded (MonoProfiler *prof, MonoDomain *domain)
1808 LogBuffer *logbuffer = ensure_logbuf (
1809 EVENT_SIZE /* event */ +
1810 LEB128_SIZE /* time */ +
1811 EVENT_SIZE /* type */ +
1812 LEB128_SIZE /* domain id */ +
1813 LEB128_SIZE /* flags */
1815 uint64_t now = current_time ();
1817 ENTER_LOG (logbuffer, "domain-end");
1818 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1819 emit_time (logbuffer, now);
1820 emit_byte (logbuffer, TYPE_DOMAIN);
1821 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1822 emit_value (logbuffer, 0); /* flags */
1823 EXIT_LOG (logbuffer);
1825 if (logbuffer->next)
1826 safe_send (prof, logbuffer);
1828 process_requests (prof);
1832 domain_name (MonoProfiler *prof, MonoDomain *domain, const char *name)
1834 int nlen = strlen (name) + 1;
1835 LogBuffer *logbuffer = ensure_logbuf (
1836 EVENT_SIZE /* event */ +
1837 LEB128_SIZE /* time */ +
1838 EVENT_SIZE /* type */ +
1839 LEB128_SIZE /* domain id */ +
1840 LEB128_SIZE /* flags */ +
1843 uint64_t now = current_time ();
1845 ENTER_LOG (logbuffer, "domain-name");
1846 emit_byte (logbuffer, TYPE_METADATA);
1847 emit_time (logbuffer, now);
1848 emit_byte (logbuffer, TYPE_DOMAIN);
1849 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1850 emit_value (logbuffer, 0); /* flags */
1851 memcpy (logbuffer->data, name, nlen);
1852 logbuffer->data += nlen;
1853 EXIT_LOG (logbuffer);
1855 if (logbuffer->next)
1856 safe_send (prof, logbuffer);
1858 process_requests (prof);
1862 context_loaded (MonoProfiler *prof, MonoAppContext *context)
1864 LogBuffer *logbuffer = ensure_logbuf (
1865 EVENT_SIZE /* event */ +
1866 LEB128_SIZE /* time */ +
1867 EVENT_SIZE /* type */ +
1868 LEB128_SIZE /* context id */ +
1869 LEB128_SIZE /* flags */ +
1870 LEB128_SIZE /* domain id */
1872 uint64_t now = current_time ();
1874 ENTER_LOG (logbuffer, "context-start");
1875 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1876 emit_time (logbuffer, now);
1877 emit_byte (logbuffer, TYPE_CONTEXT);
1878 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
1879 emit_value (logbuffer, 0); /* flags */
1880 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
1881 EXIT_LOG (logbuffer);
1883 if (logbuffer->next)
1884 safe_send (prof, logbuffer);
1886 process_requests (prof);
1890 context_unloaded (MonoProfiler *prof, MonoAppContext *context)
1892 LogBuffer *logbuffer = ensure_logbuf (
1893 EVENT_SIZE /* event */ +
1894 LEB128_SIZE /* time */ +
1895 EVENT_SIZE /* type */ +
1896 LEB128_SIZE /* context id */ +
1897 LEB128_SIZE /* flags */ +
1898 LEB128_SIZE /* domain id */
1900 uint64_t now = current_time ();
1902 ENTER_LOG (logbuffer, "context-end");
1903 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1904 emit_time (logbuffer, now);
1905 emit_byte (logbuffer, TYPE_CONTEXT);
1906 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
1907 emit_value (logbuffer, 0); /* flags */
1908 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
1909 EXIT_LOG (logbuffer);
1911 if (logbuffer->next)
1912 safe_send (prof, logbuffer);
1914 process_requests (prof);
1918 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
1920 int len = strlen (name) + 1;
1922 LogBuffer *logbuffer;
1923 logbuffer = ensure_logbuf (
1924 EVENT_SIZE /* event */ +
1925 LEB128_SIZE /* time */ +
1926 EVENT_SIZE /* type */ +
1927 LEB128_SIZE /* tid */ +
1928 LEB128_SIZE /* flags */ +
1931 now = current_time ();
1932 ENTER_LOG (logbuffer, "tname");
1933 emit_byte (logbuffer, TYPE_METADATA);
1934 emit_time (logbuffer, now);
1935 emit_byte (logbuffer, TYPE_THREAD);
1936 emit_ptr (logbuffer, (void*)tid);
1937 emit_value (logbuffer, 0); /* flags */
1938 memcpy (logbuffer->data, name, len);
1939 logbuffer->data += len;
1940 EXIT_LOG (logbuffer);
1942 if (logbuffer->next)
1943 safe_send (prof, logbuffer);
1945 process_requests (prof);
1957 AsyncFrameInfo *data;
1961 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
1963 AsyncFrameData *frame = (AsyncFrameData *)data;
1964 if (frame->count < num_frames) {
1965 frame->data [frame->count].method = method;
1966 frame->data [frame->count].domain = domain;
1967 frame->data [frame->count].base_address = base_address;
1968 frame->data [frame->count].offset = offset;
1969 // printf ("In %d at %p (dom %p) (native: %p)\n", frame->count, method, domain, base_address);
1972 return frame->count == num_frames;
1976 (type | frame count), tid, time, ip, [method, domain, base address, offset] * frames
1978 #define SAMPLE_EVENT_SIZE_IN_SLOTS(FRAMES) (4 + (FRAMES) * 4)
1981 mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
1984 AsyncFrameInfo frames [num_frames];
1985 AsyncFrameData bt_data = { 0, &frames [0]};
1987 uintptr_t *data, *new_data, *old_data;
1993 now = current_time ();
1995 mono_stack_walk_async_safe (&async_walk_stack, context, &bt_data);
1997 elapsed = (now - profiler->startup_time) / 10000;
2001 snprintf (buf, sizeof (buf), "hit at %p in thread %p after %llu ms\n", ip, (void*)thread_id (), (unsigned long long int)elapsed/100);
2003 ign_res (write (2, buf, len));
2005 sbuf = profiler->stat_buffers;
2008 /* flush the buffer at 1 second intervals */
2009 if (sbuf->data > sbuf->buf && (elapsed - sbuf->buf [2]) > 100000) {
2012 /* overflow: 400 slots is a big enough number to reduce the chance of losing this event if many
2013 * threads hit this same spot at the same time
2015 if (timedout || (sbuf->data + 400 >= sbuf->data_end)) {
2016 StatBuffer *oldsb, *foundsb;
2017 sbuf = create_stat_buffer ();
2019 oldsb = profiler->stat_buffers;
2021 foundsb = (StatBuffer *)InterlockedCompareExchangePointer ((void * volatile*)&profiler->stat_buffers, sbuf, oldsb);
2022 } while (foundsb != oldsb);
2024 ign_res (write (2, "overflow\n", 9));
2025 /* notify the helper thread */
2026 if (sbuf->next->next) {
2028 ign_res (write (profiler->pipes [1], &c, 1));
2030 ign_res (write (2, "notify\n", 7));
2034 old_data = sbuf->data;
2035 new_data = old_data + SAMPLE_EVENT_SIZE_IN_SLOTS (bt_data.count);
2036 data = (uintptr_t *)InterlockedCompareExchangePointer ((void * volatile*)&sbuf->data, new_data, old_data);
2037 } while (data != old_data);
2038 if (old_data >= sbuf->data_end)
2039 return; /* lost event */
2040 old_data [0] = 1 | (sample_type << 16) | (bt_data.count << 8);
2041 old_data [1] = thread_id ();
2042 old_data [2] = elapsed;
2043 old_data [3] = (uintptr_t)ip;
2044 for (i = 0; i < bt_data.count; ++i) {
2045 old_data [4 + 4 * i + 0] = (uintptr_t)frames [i].method;
2046 old_data [4 + 4 * i + 1] = (uintptr_t)frames [i].domain;
2047 old_data [4 + 4 * i + 2] = (uintptr_t)frames [i].base_address;
2048 old_data [4 + 4 * i + 3] = (uintptr_t)frames [i].offset;
2052 static uintptr_t *code_pages = 0;
2053 static int num_code_pages = 0;
2054 static int size_code_pages = 0;
2055 #define CPAGE_SHIFT (9)
2056 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
2057 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
2058 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
2061 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
2064 uintptr_t start_pos;
2065 start_pos = (page >> CPAGE_SHIFT) % hsize;
2068 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
2070 } else if (!hash [i]) {
2077 } while (i != start_pos);
2078 /* should not happen */
2079 printf ("failed code page store\n");
2084 add_code_pointer (uintptr_t ip)
2087 if (num_code_pages * 2 >= size_code_pages) {
2089 uintptr_t old_size = size_code_pages;
2090 size_code_pages *= 2;
2091 if (size_code_pages == 0)
2092 size_code_pages = 16;
2093 n = (uintptr_t *)calloc (sizeof (uintptr_t) * size_code_pages, 1);
2094 for (i = 0; i < old_size; ++i) {
2096 add_code_page (n, size_code_pages, code_pages [i]);
2102 num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
2105 /* ELF code crashes on some systems. */
2106 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2109 dump_ubin (const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
2112 LogBuffer *logbuffer;
2114 len = strlen (filename) + 1;
2115 now = current_time ();
2116 logbuffer = ensure_logbuf (
2117 EVENT_SIZE /* event */ +
2118 LEB128_SIZE /* time */ +
2119 LEB128_SIZE /* load address */ +
2120 LEB128_SIZE /* offset */ +
2121 LEB128_SIZE /* size */ +
2122 nlen /* file name */
2124 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
2125 emit_time (logbuffer, now);
2126 emit_svalue (logbuffer, load_addr);
2127 emit_uvalue (logbuffer, offset);
2128 emit_uvalue (logbuffer, size);
2129 memcpy (logbuffer->data, filename, len);
2130 logbuffer->data += len;
2135 dump_usym (const char *name, uintptr_t value, uintptr_t size)
2137 LogBuffer *logbuffer;
2139 len = strlen (name) + 1;
2140 logbuffer = ensure_logbuf (
2141 EVENT_SIZE /* event */ +
2142 LEB128_SIZE /* value */ +
2143 LEB128_SIZE /* size */ +
2146 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
2147 emit_ptr (logbuffer, (void*)value);
2148 emit_value (logbuffer, size);
2149 memcpy (logbuffer->data, name, len);
2150 logbuffer->data += len;
2153 /* ELF code crashes on some systems. */
2154 //#if defined(ELFMAG0)
2157 #if SIZEOF_VOID_P == 4
2158 #define ELF_WSIZE 32
2160 #define ELF_WSIZE 64
2163 #define ElfW(type) _ElfW (Elf, ELF_WSIZE, type)
2164 #define _ElfW(e,w,t) _ElfW_1 (e, w, _##t)
2165 #define _ElfW_1(e,w,t) e##w##t
2169 dump_elf_symbols (ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
2172 for (i = 0; i < num_symbols; ++i) {
2174 sym = strtab + symbols [i].st_name;
2175 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
2177 //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
2178 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
2183 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
2190 ElfW(Shdr) *sheader;
2191 ElfW(Shdr) *shstrtabh;
2192 ElfW(Shdr) *symtabh = NULL;
2193 ElfW(Shdr) *strtabh = NULL;
2194 ElfW(Sym) *symbols = NULL;
2198 fd = open (filename, O_RDONLY);
2201 if (fstat (fd, &statb) != 0) {
2205 file_size = statb.st_size;
2206 data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
2208 if (data == MAP_FAILED)
2211 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2212 header->e_ident [EI_MAG1] != ELFMAG1 ||
2213 header->e_ident [EI_MAG2] != ELFMAG2 ||
2214 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2215 munmap (data, file_size);
2218 sheader = (void*)((char*)data + header->e_shoff);
2219 shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
2220 strtab = (const char*)data + shstrtabh->sh_offset;
2221 for (i = 0; i < header->e_shnum; ++i) {
2222 //printf ("section header: %d\n", sheader->sh_type);
2223 if (sheader->sh_type == SHT_SYMTAB) {
2225 strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
2226 /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
2229 sheader = (void*)((char*)sheader + header->e_shentsize);
2231 if (!symtabh || !strtabh) {
2232 munmap (data, file_size);
2235 strtab = (const char*)data + strtabh->sh_offset;
2236 num_symbols = symtabh->sh_size / symtabh->sh_entsize;
2237 symbols = (void*)((char*)data + symtabh->sh_offset);
2238 dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
2239 munmap (data, file_size);
2244 /* ELF code crashes on some systems. */
2245 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2248 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
2250 MonoProfiler *prof = data;
2252 const char *filename;
2254 char *a = (void*)info->dlpi_addr;
2256 ElfW(Dyn) *dyn = NULL;
2257 ElfW(Sym) *symtab = NULL;
2258 ElfW(Word) *hash_table = NULL;
2259 ElfW(Ehdr) *header = NULL;
2260 const char* strtab = NULL;
2261 for (obj = prof->binary_objects; obj; obj = obj->next) {
2265 filename = info->dlpi_name;
2268 if (!info->dlpi_addr && !filename [0]) {
2269 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
2275 obj = calloc (sizeof (BinaryObject), 1);
2276 obj->addr = (void*)info->dlpi_addr;
2277 obj->name = pstrdup (filename);
2278 obj->next = prof->binary_objects;
2279 prof->binary_objects = obj;
2280 //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
2282 for (i = 0; i < info->dlpi_phnum; ++i) {
2283 //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);
2284 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
2285 header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2286 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2287 header->e_ident [EI_MAG1] != ELFMAG1 ||
2288 header->e_ident [EI_MAG2] != ELFMAG2 ||
2289 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2292 dump_ubin (filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
2293 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
2294 dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2297 if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
2299 if (!info->dlpi_name || !info->dlpi_name[0])
2303 for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
2304 if (dyn [i].d_tag == DT_SYMTAB) {
2305 if (symtab && do_debug)
2306 printf ("multiple symtabs: %d\n", i);
2307 symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
2308 } else if (dyn [i].d_tag == DT_HASH) {
2309 hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
2310 } else if (dyn [i].d_tag == DT_STRTAB) {
2311 strtab = (const char*)(a + dyn [i].d_un.d_ptr);
2316 num_sym = hash_table [1];
2317 dump_elf_symbols (symtab, num_sym, strtab, (void*)info->dlpi_addr);
2322 load_binaries (MonoProfiler *prof)
2324 dl_iterate_phdr (elf_dl_callback, prof);
2329 load_binaries (MonoProfiler *prof)
2336 symbol_for (uintptr_t code)
2339 void *ip = (void*)code;
2341 if (dladdr (ip, &di)) {
2343 return di.dli_sname;
2346 names = backtrace_symbols (&ip, 1);
2348 const char* p = names [0];
2359 dump_unmanaged_coderefs (MonoProfiler *prof)
2362 const char* last_symbol;
2363 uintptr_t addr, page_end;
2365 if (load_binaries (prof))
2367 for (i = 0; i < size_code_pages; ++i) {
2369 if (!code_pages [i] || code_pages [i] & 1)
2372 addr = CPAGE_ADDR (code_pages [i]);
2373 page_end = addr + CPAGE_SIZE;
2374 code_pages [i] |= 1;
2375 /* we dump the symbols for the whole page */
2376 for (; addr < page_end; addr += 16) {
2377 sym = symbol_for (addr);
2378 if (sym && sym == last_symbol)
2383 dump_usym (sym, addr, 0); /* let's not guess the size */
2384 //printf ("found symbol at %p: %s\n", (void*)addr, sym);
2390 compare_sample_events (gconstpointer a, gconstpointer b)
2392 uintptr_t tid1 = (*(uintptr_t **) a) [1];
2393 uintptr_t tid2 = (*(uintptr_t **) b) [1];
2395 return tid1 > tid2 ? 1 :
2401 dump_sample_hits (MonoProfiler *prof, StatBuffer *sbuf)
2403 LogBuffer *logbuffer;
2407 dump_sample_hits (prof, sbuf->next);
2408 free_buffer (sbuf->next, sbuf->next->size);
2412 g_ptr_array_set_size (prof->sorted_sample_events, 0);
2414 for (uintptr_t *sample = sbuf->buf; sample < sbuf->data;) {
2415 int count = sample [0] & 0xff;
2416 int mbt_count = (sample [0] & 0xff00) >> 8;
2418 if (sample + SAMPLE_EVENT_SIZE_IN_SLOTS (mbt_count) > sbuf->data)
2421 g_ptr_array_add (prof->sorted_sample_events, sample);
2423 sample += count + 3 + 4 * mbt_count;
2426 g_ptr_array_sort (prof->sorted_sample_events, compare_sample_events);
2428 for (guint sidx = 0; sidx < prof->sorted_sample_events->len; sidx++) {
2429 uintptr_t *sample = (uintptr_t *)g_ptr_array_index (prof->sorted_sample_events, sidx);
2430 int count = sample [0] & 0xff;
2431 int mbt_count = (sample [0] & 0xff00) >> 8;
2432 int type = sample [0] >> 16;
2433 uintptr_t *managed_sample_base = sample + count + 3;
2434 uintptr_t thread_id = sample [1];
2436 for (int i = 0; i < mbt_count; ++i) {
2437 MonoMethod *method = (MonoMethod*)managed_sample_base [i * 4 + 0];
2438 MonoDomain *domain = (MonoDomain*)managed_sample_base [i * 4 + 1];
2439 void *address = (void*)managed_sample_base [i * 4 + 2];
2442 MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *)address);
2445 managed_sample_base [i * 4 + 0] = (uintptr_t)mono_jit_info_get_method (ji);
2449 logbuffer = ensure_logbuf (
2450 EVENT_SIZE /* event */ +
2451 LEB128_SIZE /* type */ +
2452 LEB128_SIZE /* time */ +
2453 LEB128_SIZE /* tid */ +
2454 LEB128_SIZE /* count */ +
2456 LEB128_SIZE /* ip */
2458 LEB128_SIZE /* managed count */ +
2460 LEB128_SIZE /* method */ +
2461 LEB128_SIZE /* il offset */ +
2462 LEB128_SIZE /* native offset */
2465 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
2466 emit_value (logbuffer, type);
2467 emit_uvalue (logbuffer, prof->startup_time + (uint64_t)sample [2] * (uint64_t)10000);
2468 emit_ptr (logbuffer, (void *) thread_id);
2469 emit_value (logbuffer, count);
2470 for (int i = 0; i < count; ++i) {
2471 emit_ptr (logbuffer, (void*)sample [i + 3]);
2472 add_code_pointer (sample [i + 3]);
2475 sample += count + 3;
2476 /* new in data version 6 */
2477 emit_uvalue (logbuffer, mbt_count);
2478 for (int i = 0; i < mbt_count; ++i) {
2479 MonoMethod *method = (MonoMethod *) sample [i * 4 + 0];
2480 uintptr_t native_offset = sample [i * 4 + 3];
2482 emit_method (prof, logbuffer, method);
2483 emit_svalue (logbuffer, 0); /* il offset will always be 0 from now on */
2484 emit_svalue (logbuffer, native_offset);
2488 dump_unmanaged_coderefs (prof);
2494 mono_cpu_count (void)
2497 #ifdef PLATFORM_ANDROID
2498 /* Android tries really hard to save power by powering off CPUs on SMP phones which
2499 * means the normal way to query cpu count returns a wrong value with userspace API.
2500 * Instead we use /sys entries to query the actual hardware CPU count.
2502 char buffer[8] = {'\0'};
2503 int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
2504 /* Format of the /sys entry is a cpulist of indexes which in the case
2505 * of present is always of the form "0-(n-1)" when there is more than
2506 * 1 core, n being the number of CPU cores in the system. Otherwise
2507 * the value is simply 0
2509 if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
2510 count = strtol (((char*)buffer) + 2, NULL, 10);
2516 #ifdef _SC_NPROCESSORS_ONLN
2517 count = sysconf (_SC_NPROCESSORS_ONLN);
2524 size_t len = sizeof (int);
2527 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
2534 GetSystemInfo (&info);
2535 return info.dwNumberOfProcessors;
2544 unsigned int prev_pos;
2546 struct perf_event_mmap_page *page_desc;
2549 static PerfData *perf_data = NULL;
2550 static int num_perf;
2551 #define PERF_PAGES_SHIFT 4
2552 static int num_pages = 1 << PERF_PAGES_SHIFT;
2553 static unsigned int mmap_mask;
2556 struct perf_event_header h;
2566 perf_event_syscall (struct perf_event_attr *attr, pid_t pid, int cpu, int group_fd, unsigned long flags)
2568 attr->size = PERF_ATTR_SIZE_VER0;
2569 //printf ("perf attr size: %d\n", attr->size);
2570 #if defined(__x86_64__)
2571 return syscall(/*__NR_perf_event_open*/ 298, attr, pid, cpu, group_fd, flags);
2572 #elif defined(__i386__)
2573 return syscall(/*__NR_perf_event_open*/ 336, attr, pid, cpu, group_fd, flags);
2574 #elif defined(__arm__) || defined (__aarch64__)
2575 return syscall(/*__NR_perf_event_open*/ 364, attr, pid, cpu, group_fd, flags);
2582 setup_perf_map (PerfData *perf)
2584 perf->mmap_base = mmap (NULL, (num_pages + 1) * getpagesize (), PROT_READ|PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
2585 if (perf->mmap_base == MAP_FAILED) {
2587 printf ("failed mmap\n");
2590 perf->page_desc = perf->mmap_base;
2592 printf ("mmap version: %d\n", perf->page_desc->version);
2597 dump_perf_hits (MonoProfiler *prof, void *buf, int size)
2599 LogBuffer *logbuffer;
2602 void *end = (char*)buf + size;
2604 int pid = getpid ();
2610 if (pid != s->pid) {
2612 printf ("event for different pid: %d\n", s->pid);
2613 buf = (char*)buf + s->h.size;
2616 /*ip = (void*)s->ip;
2617 printf ("sample: %d, size: %d, ip: %p (%s), timestamp: %llu, nframes: %llu\n",
2618 s->h.type, s->h.size, ip, symbol_for (ip), s->timestamp, s->nframes);*/
2619 logbuffer = ensure_logbuf (
2620 EVENT_SIZE /* event */ +
2621 LEB128_SIZE /* type */ +
2622 LEB128_SIZE /* time */ +
2623 LEB128_SIZE /* tid */ +
2624 LEB128_SIZE /* count */ +
2626 LEB128_SIZE /* ip */
2628 LEB128_SIZE /* managed count */ +
2630 LEB128_SIZE /* method */ +
2631 LEB128_SIZE /* il offset */ +
2632 LEB128_SIZE /* native offset */
2635 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
2636 emit_value (logbuffer, sample_type);
2637 emit_uvalue (logbuffer, s->timestamp - prof->startup_time);
2639 * No useful thread ID to write here, since throughout the
2640 * profiler we use pthread_self () but the ID we get from
2641 * perf is the kernel's thread ID.
2643 emit_ptr (logbuffer, 0);
2644 emit_value (logbuffer, count);
2645 emit_ptr (logbuffer, (void*)(uintptr_t)s->ip);
2646 add_code_pointer (s->ip);
2647 /* no support here yet for the managed backtrace */
2648 emit_uvalue (logbuffer, mbt_count);
2649 buf = (char*)buf + s->h.size;
2653 printf ("dumped %d samples\n", samples);
2654 dump_unmanaged_coderefs (prof);
2657 /* read events from the ring buffer */
2659 read_perf_mmap (MonoProfiler* prof, int cpu)
2661 PerfData *perf = perf_data + cpu;
2663 unsigned char *data = (unsigned char*)perf->mmap_base + getpagesize ();
2664 unsigned int head = perf->page_desc->data_head;
2668 mono_memory_read_barrier ();
2670 old = perf->prev_pos;
2674 printf ("lost mmap events: old: %d, head: %d\n", old, head);
2678 if ((old & mmap_mask) + size != (head & mmap_mask)) {
2679 buf = data + (old & mmap_mask);
2680 size = mmap_mask + 1 - (old & mmap_mask);
2682 /* size bytes at buf */
2684 printf ("found1 bytes of events: %d\n", size);
2685 dump_perf_hits (prof, buf, size);
2687 buf = data + (old & mmap_mask);
2689 /* size bytes at buf */
2691 printf ("found bytes of events: %d\n", size);
2692 dump_perf_hits (prof, buf, size);
2694 perf->prev_pos = old;
2695 perf->page_desc->data_tail = old;
2700 setup_perf_event_for_cpu (PerfData *perf, int cpu)
2702 struct perf_event_attr attr;
2703 memset (&attr, 0, sizeof (attr));
2704 attr.type = PERF_TYPE_HARDWARE;
2705 switch (sample_type) {
2706 case SAMPLE_CYCLES: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2707 case SAMPLE_INSTRUCTIONS: attr.config = PERF_COUNT_HW_INSTRUCTIONS; break;
2708 case SAMPLE_CACHE_MISSES: attr.config = PERF_COUNT_HW_CACHE_MISSES; break;
2709 case SAMPLE_CACHE_REFS: attr.config = PERF_COUNT_HW_CACHE_REFERENCES; break;
2710 case SAMPLE_BRANCHES: attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS; break;
2711 case SAMPLE_BRANCH_MISSES: attr.config = PERF_COUNT_HW_BRANCH_MISSES; break;
2712 default: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2714 attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD | PERF_SAMPLE_TIME;
2715 // attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
2716 attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING | PERF_FORMAT_ID;
2719 attr.sample_freq = sample_freq;
2721 perf->perf_fd = perf_event_syscall (&attr, getpid (), cpu, -1, 0);
2723 printf ("perf fd: %d, freq: %d, event: %llu\n", perf->perf_fd, sample_freq, attr.config);
2724 if (perf->perf_fd < 0) {
2725 if (perf->perf_fd == -EPERM) {
2726 fprintf (stderr, "Perf syscall denied, do \"echo 1 > /proc/sys/kernel/perf_event_paranoid\" as root to enable.\n");
2729 perror ("open perf event");
2733 if (!setup_perf_map (perf)) {
2734 close (perf->perf_fd);
2742 setup_perf_event (void)
2745 mmap_mask = num_pages * getpagesize () - 1;
2746 num_perf = mono_cpu_count ();
2747 perf_data = calloc (num_perf, sizeof (PerfData));
2748 for (i = 0; i < num_perf; ++i) {
2749 count += setup_perf_event_for_cpu (perf_data + i, i);
2758 #endif /* USE_PERF_EVENTS */
2760 #ifndef DISABLE_HELPER_THREAD
2762 typedef struct MonoCounterAgent {
2763 MonoCounter *counter;
2764 // MonoCounterAgent specific data :
2769 struct MonoCounterAgent *next;
2772 static MonoCounterAgent* counters;
2773 static gboolean counters_initialized = FALSE;
2774 static int counters_index = 1;
2775 static mono_mutex_t counters_mutex;
2778 counters_add_agent (MonoCounter *counter)
2780 MonoCounterAgent *agent, *item;
2782 if (!counters_initialized)
2785 mono_os_mutex_lock (&counters_mutex);
2787 for (agent = counters; agent; agent = agent->next) {
2788 if (agent->counter == counter) {
2789 agent->value_size = 0;
2791 free (agent->value);
2792 agent->value = NULL;
2794 mono_os_mutex_unlock (&counters_mutex);
2799 agent = (MonoCounterAgent *)malloc (sizeof (MonoCounterAgent));
2800 agent->counter = counter;
2801 agent->value = NULL;
2802 agent->value_size = 0;
2803 agent->index = counters_index++;
2816 mono_os_mutex_unlock (&counters_mutex);
2820 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
2822 counters_add_agent (counter);
2827 counters_init (MonoProfiler *profiler)
2829 assert (!counters_initialized);
2831 mono_os_mutex_init (&counters_mutex);
2833 counters_initialized = TRUE;
2835 mono_counters_on_register (&counters_add_agent);
2836 mono_counters_foreach (counters_init_foreach_callback, NULL);
2840 counters_emit (MonoProfiler *profiler)
2842 MonoCounterAgent *agent;
2843 LogBuffer *logbuffer;
2846 EVENT_SIZE /* event */ +
2847 LEB128_SIZE /* len */
2850 if (!counters_initialized)
2853 mono_os_mutex_lock (&counters_mutex);
2855 for (agent = counters; agent; agent = agent->next) {
2860 LEB128_SIZE /* section */ +
2861 strlen (mono_counter_get_name (agent->counter)) + 1 /* name */ +
2862 LEB128_SIZE /* type */ +
2863 LEB128_SIZE /* unit */ +
2864 LEB128_SIZE /* variance */ +
2865 LEB128_SIZE /* index */
2872 mono_os_mutex_unlock (&counters_mutex);
2876 logbuffer = ensure_logbuf (size);
2878 ENTER_LOG (logbuffer, "counters");
2879 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2880 emit_value (logbuffer, len);
2881 for (agent = counters; agent; agent = agent->next) {
2887 name = mono_counter_get_name (agent->counter);
2888 emit_value (logbuffer, mono_counter_get_section (agent->counter));
2889 emit_string (logbuffer, name, strlen (name) + 1);
2890 emit_value (logbuffer, mono_counter_get_type (agent->counter));
2891 emit_value (logbuffer, mono_counter_get_unit (agent->counter));
2892 emit_value (logbuffer, mono_counter_get_variance (agent->counter));
2893 emit_value (logbuffer, agent->index);
2897 EXIT_LOG (logbuffer);
2899 safe_send (profiler, logbuffer);
2901 mono_os_mutex_unlock (&counters_mutex);
2905 counters_sample (MonoProfiler *profiler, uint64_t timestamp)
2907 MonoCounterAgent *agent;
2908 MonoCounter *counter;
2909 LogBuffer *logbuffer;
2915 if (!counters_initialized)
2918 counters_emit (profiler);
2921 buffer = calloc (1, buffer_size);
2923 mono_os_mutex_lock (&counters_mutex);
2926 EVENT_SIZE /* event */ +
2927 LEB128_SIZE /* time */
2930 for (agent = counters; agent; agent = agent->next) {
2932 LEB128_SIZE /* index */ +
2933 LEB128_SIZE /* type */ +
2934 mono_counter_get_size (agent->counter) /* value */
2939 LEB128_SIZE /* stop marker */
2942 logbuffer = ensure_logbuf (size);
2944 ENTER_LOG (logbuffer, "counters");
2945 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
2946 emit_uvalue (logbuffer, timestamp);
2947 for (agent = counters; agent; agent = agent->next) {
2950 counter = agent->counter;
2952 size = mono_counter_get_size (counter);
2954 continue; // FIXME error
2955 } else if (size > buffer_size) {
2957 buffer = realloc (buffer, buffer_size);
2960 memset (buffer, 0, buffer_size);
2962 if (mono_counters_sample (counter, buffer, size) < 0)
2963 continue; // FIXME error
2965 type = mono_counter_get_type (counter);
2967 if (!agent->value) {
2968 agent->value = calloc (1, size);
2969 agent->value_size = size;
2971 if (type == MONO_COUNTER_STRING) {
2972 if (strcmp (agent->value, buffer) == 0)
2975 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
2980 emit_uvalue (logbuffer, agent->index);
2981 emit_uvalue (logbuffer, type);
2983 case MONO_COUNTER_INT:
2984 #if SIZEOF_VOID_P == 4
2985 case MONO_COUNTER_WORD:
2987 emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
2989 case MONO_COUNTER_UINT:
2990 emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
2992 case MONO_COUNTER_TIME_INTERVAL:
2993 case MONO_COUNTER_LONG:
2994 #if SIZEOF_VOID_P == 8
2995 case MONO_COUNTER_WORD:
2997 emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
2999 case MONO_COUNTER_ULONG:
3000 emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
3002 case MONO_COUNTER_DOUBLE:
3003 emit_double (logbuffer, *(double*)buffer);
3005 case MONO_COUNTER_STRING:
3007 emit_byte (logbuffer, 0);
3009 emit_byte (logbuffer, 1);
3010 emit_string (logbuffer, (char*)buffer, size);
3017 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
3018 agent->value = realloc (agent->value, size);
3019 agent->value_size = size;
3023 memcpy (agent->value, buffer, size);
3027 emit_value (logbuffer, 0);
3028 EXIT_LOG (logbuffer);
3030 safe_send (profiler, logbuffer);
3032 mono_os_mutex_unlock (&counters_mutex);
3035 typedef struct _PerfCounterAgent PerfCounterAgent;
3036 struct _PerfCounterAgent {
3037 PerfCounterAgent *next;
3039 char *category_name;
3048 static PerfCounterAgent *perfcounters = NULL;
3051 perfcounters_emit (MonoProfiler *profiler)
3053 PerfCounterAgent *pcagent;
3054 LogBuffer *logbuffer;
3057 EVENT_SIZE /* event */ +
3058 LEB128_SIZE /* len */
3061 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3062 if (pcagent->emitted)
3066 LEB128_SIZE /* section */ +
3067 strlen (pcagent->category_name) + 1 /* category name */ +
3068 strlen (pcagent->name) + 1 /* name */ +
3069 LEB128_SIZE /* type */ +
3070 LEB128_SIZE /* unit */ +
3071 LEB128_SIZE /* variance */ +
3072 LEB128_SIZE /* index */
3081 logbuffer = ensure_logbuf (size);
3083 ENTER_LOG (logbuffer, "perfcounters");
3084 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
3085 emit_value (logbuffer, len);
3086 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3087 if (pcagent->emitted)
3090 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
3091 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
3092 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
3093 emit_value (logbuffer, MONO_COUNTER_LONG);
3094 emit_value (logbuffer, MONO_COUNTER_RAW);
3095 emit_value (logbuffer, MONO_COUNTER_VARIABLE);
3096 emit_value (logbuffer, pcagent->index);
3098 pcagent->emitted = 1;
3100 EXIT_LOG (logbuffer);
3102 safe_send (profiler, logbuffer);
3106 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
3108 PerfCounterAgent *pcagent;
3110 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3111 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
3113 if (pcagent->value == value)
3116 pcagent->value = value;
3117 pcagent->updated = 1;
3118 pcagent->deleted = 0;
3122 pcagent = g_new0 (PerfCounterAgent, 1);
3123 pcagent->next = perfcounters;
3124 pcagent->index = counters_index++;
3125 pcagent->category_name = g_strdup (category_name);
3126 pcagent->name = g_strdup (name);
3127 pcagent->type = (int) type;
3128 pcagent->value = value;
3129 pcagent->emitted = 0;
3130 pcagent->updated = 1;
3131 pcagent->deleted = 0;
3133 perfcounters = pcagent;
3139 perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp)
3141 PerfCounterAgent *pcagent;
3142 LogBuffer *logbuffer;
3145 if (!counters_initialized)
3148 mono_os_mutex_lock (&counters_mutex);
3150 /* mark all perfcounters as deleted, foreach will unmark them as necessary */
3151 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
3152 pcagent->deleted = 1;
3154 mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
3156 perfcounters_emit (profiler);
3159 EVENT_SIZE /* event */ +
3160 LEB128_SIZE /* time */
3163 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3164 if (pcagent->deleted || !pcagent->updated)
3168 LEB128_SIZE /* index */ +
3169 LEB128_SIZE /* type */ +
3170 LEB128_SIZE /* value */
3175 LEB128_SIZE /* stop marker */
3178 logbuffer = ensure_logbuf (size);
3180 ENTER_LOG (logbuffer, "perfcounters");
3181 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
3182 emit_uvalue (logbuffer, timestamp);
3183 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3184 if (pcagent->deleted || !pcagent->updated)
3186 emit_uvalue (logbuffer, pcagent->index);
3187 emit_uvalue (logbuffer, MONO_COUNTER_LONG);
3188 emit_svalue (logbuffer, pcagent->value);
3190 pcagent->updated = 0;
3193 emit_value (logbuffer, 0);
3194 EXIT_LOG (logbuffer);
3196 safe_send (profiler, logbuffer);
3198 mono_os_mutex_unlock (&counters_mutex);
3202 counters_and_perfcounters_sample (MonoProfiler *prof)
3204 static uint64_t start = -1;
3208 start = current_time ();
3210 now = current_time ();
3211 counters_sample (prof, (now - start) / 1000/ 1000);
3212 perfcounters_sample (prof, (now - start) / 1000/ 1000);
3215 #define COVERAGE_DEBUG(x) if (debug_coverage) {x}
3216 static mono_mutex_t coverage_mutex;
3217 static MonoConcurrentHashTable *coverage_methods = NULL;
3218 static MonoConcurrentHashTable *coverage_assemblies = NULL;
3219 static MonoConcurrentHashTable *coverage_classes = NULL;
3221 static MonoConcurrentHashTable *filtered_classes = NULL;
3222 static MonoConcurrentHashTable *entered_methods = NULL;
3223 static MonoConcurrentHashTable *image_to_methods = NULL;
3224 static MonoConcurrentHashTable *suppressed_assemblies = NULL;
3225 static gboolean coverage_initialized = FALSE;
3227 static GPtrArray *coverage_data = NULL;
3228 static int previous_offset = 0;
3230 typedef struct _MethodNode MethodNode;
3231 struct _MethodNode {
3232 MonoLockFreeQueueNode node;
3236 typedef struct _CoverageEntry CoverageEntry;
3237 struct _CoverageEntry {
3246 free_coverage_entry (gpointer data, gpointer userdata)
3248 CoverageEntry *entry = (CoverageEntry *)data;
3249 g_free (entry->filename);
3254 obtain_coverage_for_method (MonoProfiler *prof, const MonoProfileCoverageEntry *entry)
3256 int offset = entry->iloffset - previous_offset;
3257 CoverageEntry *e = g_new (CoverageEntry, 1);
3259 previous_offset = entry->iloffset;
3262 e->counter = entry->counter;
3263 e->filename = g_strdup(entry->filename ? entry->filename : "");
3264 e->line = entry->line;
3265 e->column = entry->col;
3267 g_ptr_array_add (coverage_data, e);
3271 parse_generic_type_names(char *name)
3273 char *new_name, *ret;
3274 int within_generic_declaration = 0, generic_members = 1;
3276 if (name == NULL || *name == '\0')
3277 return g_strdup ("");
3279 if (!(ret = new_name = (char *)calloc (strlen (name) * 4 + 1, sizeof (char))))
3285 within_generic_declaration = 1;
3289 within_generic_declaration = 0;
3291 if (*(name - 1) != '<') {
3293 *new_name++ = '0' + generic_members;
3295 memcpy (new_name, "<>", 8);
3299 generic_members = 0;
3307 if (!within_generic_declaration)
3308 *new_name++ = *name;
3317 static int method_id;
3319 build_method_buffer (gpointer key, gpointer value, gpointer userdata)
3321 MonoMethod *method = (MonoMethod *)value;
3322 MonoProfiler *prof = (MonoProfiler *)userdata;
3326 const char *image_name, *method_name, *sig, *first_filename;
3327 LogBuffer *logbuffer;
3330 previous_offset = 0;
3331 coverage_data = g_ptr_array_new ();
3333 mono_profiler_coverage_get (prof, method, obtain_coverage_for_method);
3335 klass = mono_method_get_class (method);
3336 image = mono_class_get_image (klass);
3337 image_name = mono_image_get_name (image);
3339 sig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3340 class_name = parse_generic_type_names (mono_type_get_name (mono_class_get_type (klass)));
3341 method_name = mono_method_get_name (method);
3343 if (coverage_data->len != 0) {
3344 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[0];
3345 first_filename = entry->filename ? entry->filename : "";
3347 first_filename = "";
3349 image_name = image_name ? image_name : "";
3350 sig = sig ? sig : "";
3351 method_name = method_name ? method_name : "";
3353 logbuffer = ensure_logbuf (
3354 EVENT_SIZE /* event */ +
3355 strlen (image_name) + 1 /* image name */ +
3356 strlen (class_name) + 1 /* class name */ +
3357 strlen (method_name) + 1 /* method name */ +
3358 strlen (sig) + 1 /* signature */ +
3359 strlen (first_filename) + 1 /* first file name */ +
3360 LEB128_SIZE /* token */ +
3361 LEB128_SIZE /* method id */ +
3362 LEB128_SIZE /* entries */
3364 ENTER_LOG (logbuffer, "coverage-methods");
3366 emit_byte (logbuffer, TYPE_COVERAGE_METHOD | TYPE_COVERAGE);
3367 emit_string (logbuffer, image_name, strlen (image_name) + 1);
3368 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3369 emit_string (logbuffer, method_name, strlen (method_name) + 1);
3370 emit_string (logbuffer, sig, strlen (sig) + 1);
3371 emit_string (logbuffer, first_filename, strlen (first_filename) + 1);
3373 emit_uvalue (logbuffer, mono_method_get_token (method));
3374 emit_uvalue (logbuffer, method_id);
3375 emit_value (logbuffer, coverage_data->len);
3377 EXIT_LOG (logbuffer);
3378 safe_send (prof, logbuffer);
3380 for (i = 0; i < coverage_data->len; i++) {
3381 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[i];
3383 logbuffer = ensure_logbuf (
3384 EVENT_SIZE /* event */ +
3385 LEB128_SIZE /* method id */ +
3386 LEB128_SIZE /* offset */ +
3387 LEB128_SIZE /* counter */ +
3388 LEB128_SIZE /* line */ +
3389 LEB128_SIZE /* column */
3391 ENTER_LOG (logbuffer, "coverage-statement");
3393 emit_byte (logbuffer, TYPE_COVERAGE_STATEMENT | TYPE_COVERAGE);
3394 emit_uvalue (logbuffer, method_id);
3395 emit_uvalue (logbuffer, entry->offset);
3396 emit_uvalue (logbuffer, entry->counter);
3397 emit_uvalue (logbuffer, entry->line);
3398 emit_uvalue (logbuffer, entry->column);
3400 EXIT_LOG (logbuffer);
3401 safe_send (prof, logbuffer);
3406 g_free (class_name);
3408 g_ptr_array_foreach (coverage_data, free_coverage_entry, NULL);
3409 g_ptr_array_free (coverage_data, TRUE);
3410 coverage_data = NULL;
3413 /* This empties the queue */
3415 count_queue (MonoLockFreeQueue *queue)
3417 MonoLockFreeQueueNode *node;
3420 while ((node = mono_lock_free_queue_dequeue (queue))) {
3422 mono_lock_free_queue_node_free (node);
3429 build_class_buffer (gpointer key, gpointer value, gpointer userdata)
3431 MonoClass *klass = (MonoClass *)key;
3432 MonoLockFreeQueue *class_methods = (MonoLockFreeQueue *)value;
3433 MonoProfiler *prof = (MonoProfiler *)userdata;
3436 const char *assembly_name;
3437 int number_of_methods, partially_covered;
3438 guint fully_covered;
3439 LogBuffer *logbuffer;
3441 image = mono_class_get_image (klass);
3442 assembly_name = mono_image_get_name (image);
3443 class_name = mono_type_get_name (mono_class_get_type (klass));
3445 assembly_name = assembly_name ? assembly_name : "";
3446 number_of_methods = mono_class_num_methods (klass);
3447 fully_covered = count_queue (class_methods);
3448 /* We don't handle partial covered yet */
3449 partially_covered = 0;
3451 logbuffer = ensure_logbuf (
3452 EVENT_SIZE /* event */ +
3453 strlen (assembly_name) + 1 /* assembly name */ +
3454 strlen (class_name) + 1 /* class name */ +
3455 LEB128_SIZE /* no. methods */ +
3456 LEB128_SIZE /* fully covered */ +
3457 LEB128_SIZE /* partially covered */
3460 ENTER_LOG (logbuffer, "coverage-class");
3461 emit_byte (logbuffer, TYPE_COVERAGE_CLASS | TYPE_COVERAGE);
3462 emit_string (logbuffer, assembly_name, strlen (assembly_name) + 1);
3463 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3464 emit_uvalue (logbuffer, number_of_methods);
3465 emit_uvalue (logbuffer, fully_covered);
3466 emit_uvalue (logbuffer, partially_covered);
3467 EXIT_LOG (logbuffer);
3469 safe_send (prof, logbuffer);
3471 g_free (class_name);
3475 get_coverage_for_image (MonoImage *image, int *number_of_methods, guint *fully_covered, int *partially_covered)
3477 MonoLockFreeQueue *image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3479 *number_of_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
3481 *fully_covered = count_queue (image_methods);
3485 // FIXME: We don't handle partially covered yet.
3486 *partially_covered = 0;
3490 build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
3492 MonoAssembly *assembly = (MonoAssembly *)value;
3493 MonoProfiler *prof = (MonoProfiler *)userdata;
3494 MonoImage *image = mono_assembly_get_image (assembly);
3495 LogBuffer *logbuffer;
3496 const char *name, *guid, *filename;
3497 int number_of_methods = 0, partially_covered = 0;
3498 guint fully_covered = 0;
3500 name = mono_image_get_name (image);
3501 guid = mono_image_get_guid (image);
3502 filename = mono_image_get_filename (image);
3504 name = name ? name : "";
3505 guid = guid ? guid : "";
3506 filename = filename ? filename : "";
3508 get_coverage_for_image (image, &number_of_methods, &fully_covered, &partially_covered);
3510 logbuffer = ensure_logbuf (
3511 EVENT_SIZE /* event */ +
3512 strlen (name) + 1 /* name */ +
3513 strlen (guid) + 1 /* guid */ +
3514 strlen (filename) + 1 /* file name */ +
3515 LEB128_SIZE /* no. methods */ +
3516 LEB128_SIZE /* fully covered */ +
3517 LEB128_SIZE /* partially covered */
3520 ENTER_LOG (logbuffer, "coverage-assemblies");
3521 emit_byte (logbuffer, TYPE_COVERAGE_ASSEMBLY | TYPE_COVERAGE);
3522 emit_string (logbuffer, name, strlen (name) + 1);
3523 emit_string (logbuffer, guid, strlen (guid) + 1);
3524 emit_string (logbuffer, filename, strlen (filename) + 1);
3525 emit_uvalue (logbuffer, number_of_methods);
3526 emit_uvalue (logbuffer, fully_covered);
3527 emit_uvalue (logbuffer, partially_covered);
3528 EXIT_LOG (logbuffer);
3530 safe_send (prof, logbuffer);
3534 dump_coverage (MonoProfiler *prof)
3536 if (!coverage_initialized)
3539 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Started dump\n");)
3542 mono_os_mutex_lock (&coverage_mutex);
3543 mono_conc_hashtable_foreach (coverage_assemblies, build_assembly_buffer, prof);
3544 mono_conc_hashtable_foreach (coverage_classes, build_class_buffer, prof);
3545 mono_conc_hashtable_foreach (coverage_methods, build_method_buffer, prof);
3546 mono_os_mutex_unlock (&coverage_mutex);
3548 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Finished dump\n");)
3552 process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method)
3557 if (!coverage_initialized)
3560 klass = mono_method_get_class (method);
3561 image = mono_class_get_image (klass);
3563 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)))
3566 mono_os_mutex_lock (&coverage_mutex);
3567 mono_conc_hashtable_insert (entered_methods, method, method);
3568 mono_os_mutex_unlock (&coverage_mutex);
3571 static MonoLockFreeQueueNode *
3572 create_method_node (MonoMethod *method)
3574 MethodNode *node = (MethodNode *)g_malloc (sizeof (MethodNode));
3575 mono_lock_free_queue_node_init ((MonoLockFreeQueueNode *) node, FALSE);
3576 node->method = method;
3578 return (MonoLockFreeQueueNode *) node;
3582 coverage_filter (MonoProfiler *prof, MonoMethod *method)
3586 MonoAssembly *assembly;
3587 MonoMethodHeader *header;
3588 guint32 iflags, flags, code_size;
3589 char *fqn, *classname;
3590 gboolean has_positive, found;
3591 MonoLockFreeQueue *image_methods, *class_methods;
3592 MonoLockFreeQueueNode *node;
3594 if (!coverage_initialized)
3597 COVERAGE_DEBUG(fprintf (stderr, "Coverage filter for %s\n", mono_method_get_name (method));)
3599 flags = mono_method_get_flags (method, &iflags);
3600 if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
3601 (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/)) {
3602 COVERAGE_DEBUG(fprintf (stderr, " Internal call or pinvoke - ignoring\n");)
3606 // Don't need to do anything else if we're already tracking this method
3607 if (mono_conc_hashtable_lookup (coverage_methods, method)) {
3608 COVERAGE_DEBUG(fprintf (stderr, " Already tracking\n");)
3612 klass = mono_method_get_class (method);
3613 image = mono_class_get_image (klass);
3615 // Don't handle coverage for the core assemblies
3616 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)) != NULL)
3619 if (prof->coverage_filters) {
3620 /* Check already filtered classes first */
3621 if (mono_conc_hashtable_lookup (filtered_classes, klass)) {
3622 COVERAGE_DEBUG(fprintf (stderr, " Already filtered\n");)
3626 classname = mono_type_get_name (mono_class_get_type (klass));
3628 fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
3630 COVERAGE_DEBUG(fprintf (stderr, " Looking for %s in filter\n", fqn);)
3631 // Check positive filters first
3632 has_positive = FALSE;
3634 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3635 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3637 if (filter [0] == '+') {
3638 filter = &filter [1];
3640 COVERAGE_DEBUG(fprintf (stderr, " Checking against +%s ...", filter);)
3642 if (strstr (fqn, filter) != NULL) {
3643 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3646 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3648 has_positive = TRUE;
3652 if (has_positive && !found) {
3653 COVERAGE_DEBUG(fprintf (stderr, " Positive match was not found\n");)
3655 mono_os_mutex_lock (&coverage_mutex);
3656 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3657 mono_os_mutex_unlock (&coverage_mutex);
3664 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3665 // FIXME: Is substring search sufficient?
3666 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3667 if (filter [0] == '+')
3671 filter = &filter [1];
3672 COVERAGE_DEBUG(fprintf (stderr, " Checking against -%s ...", filter);)
3674 if (strstr (fqn, filter) != NULL) {
3675 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3677 mono_os_mutex_lock (&coverage_mutex);
3678 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3679 mono_os_mutex_unlock (&coverage_mutex);
3685 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3693 COVERAGE_DEBUG(fprintf (stderr, " Handling coverage for %s\n", mono_method_get_name (method));)
3694 header = mono_method_get_header (method);
3696 mono_method_header_get_code (header, &code_size, NULL);
3698 assembly = mono_image_get_assembly (image);
3700 mono_os_mutex_lock (&coverage_mutex);
3701 mono_conc_hashtable_insert (coverage_methods, method, method);
3702 mono_conc_hashtable_insert (coverage_assemblies, assembly, assembly);
3703 mono_os_mutex_unlock (&coverage_mutex);
3705 image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3707 if (image_methods == NULL) {
3708 image_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
3709 mono_lock_free_queue_init (image_methods);
3710 mono_os_mutex_lock (&coverage_mutex);
3711 mono_conc_hashtable_insert (image_to_methods, image, image_methods);
3712 mono_os_mutex_unlock (&coverage_mutex);
3715 node = create_method_node (method);
3716 mono_lock_free_queue_enqueue (image_methods, node);
3718 class_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (coverage_classes, klass);
3720 if (class_methods == NULL) {
3721 class_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
3722 mono_lock_free_queue_init (class_methods);
3723 mono_os_mutex_lock (&coverage_mutex);
3724 mono_conc_hashtable_insert (coverage_classes, klass, class_methods);
3725 mono_os_mutex_unlock (&coverage_mutex);
3728 node = create_method_node (method);
3729 mono_lock_free_queue_enqueue (class_methods, node);
3734 #define LINE_BUFFER_SIZE 4096
3735 /* Max file limit of 128KB */
3736 #define MAX_FILE_SIZE 128 * 1024
3738 get_file_content (FILE *stream)
3743 int res, offset = 0;
3745 res = fseek (stream, 0, SEEK_END);
3749 filesize = ftell (stream);
3753 res = fseek (stream, 0, SEEK_SET);
3757 if (filesize > MAX_FILE_SIZE)
3760 buffer = (char *)g_malloc ((filesize + 1) * sizeof (char));
3761 while ((bytes_read = fread (buffer + offset, 1, LINE_BUFFER_SIZE, stream)) > 0)
3762 offset += bytes_read;
3764 /* NULL terminate our buffer */
3765 buffer[filesize] = '\0';
3770 get_next_line (char *contents, char **next_start)
3774 if (p == NULL || *p == '\0') {
3779 while (*p != '\n' && *p != '\0')
3784 *next_start = p + 1;
3792 init_suppressed_assemblies (void)
3798 suppressed_assemblies = mono_conc_hashtable_new (g_str_hash, g_str_equal);
3799 sa_file = fopen (SUPPRESSION_DIR "/mono-profiler-log.suppression", "r");
3800 if (sa_file == NULL)
3803 /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
3804 content = get_file_content (sa_file);
3805 if (content == NULL) {
3806 g_error ("mono-profiler-log.suppression is greater than 128kb - aborting\n");
3809 while ((line = get_next_line (content, &content))) {
3810 line = g_strchomp (g_strchug (line));
3811 /* No locking needed as we're doing initialization */
3812 mono_conc_hashtable_insert (suppressed_assemblies, line, line);
3818 #endif /* DISABLE_HELPER_THREAD */
3821 coverage_init (MonoProfiler *prof)
3823 #ifndef DISABLE_HELPER_THREAD
3824 assert (!coverage_initialized);
3826 COVERAGE_DEBUG(fprintf (stderr, "Coverage initialized\n");)
3828 mono_os_mutex_init (&coverage_mutex);
3829 coverage_methods = mono_conc_hashtable_new (NULL, NULL);
3830 coverage_assemblies = mono_conc_hashtable_new (NULL, NULL);
3831 coverage_classes = mono_conc_hashtable_new (NULL, NULL);
3832 filtered_classes = mono_conc_hashtable_new (NULL, NULL);
3833 entered_methods = mono_conc_hashtable_new (NULL, NULL);
3834 image_to_methods = mono_conc_hashtable_new (NULL, NULL);
3835 init_suppressed_assemblies ();
3837 coverage_initialized = TRUE;
3838 #endif /* DISABLE_HELPER_THREAD */
3842 log_shutdown (MonoProfiler *prof)
3847 #ifndef DISABLE_HELPER_THREAD
3848 counters_and_perfcounters_sample (prof);
3850 dump_coverage (prof);
3852 if (prof->command_port) {
3854 ign_res (write (prof->pipes [1], &c, 1));
3855 pthread_join (prof->helper_thread, &res);
3861 for (i = 0; i < num_perf; ++i)
3862 read_perf_mmap (prof, i);
3866 g_ptr_array_free (prof->sorted_sample_events, TRUE);
3868 if (TLS_GET (LogBuffer, tlsbuffer))
3869 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
3871 TLS_SET (tlsbuffer, NULL);
3872 TLS_SET (tlsmethodlist, NULL);
3874 InterlockedWrite (&prof->run_writer_thread, 0);
3875 pthread_join (prof->writer_thread, &res);
3877 #if defined (HAVE_SYS_ZLIB)
3879 gzclose (prof->gzfile);
3881 if (prof->pipe_output)
3882 pclose (prof->file);
3884 fclose (prof->file);
3886 mono_conc_hashtable_destroy (prof->method_table);
3887 mono_os_mutex_destroy (&prof->method_table_mutex);
3889 if (coverage_initialized) {
3890 mono_conc_hashtable_destroy (coverage_methods);
3891 mono_conc_hashtable_destroy (coverage_assemblies);
3892 mono_conc_hashtable_destroy (coverage_classes);
3893 mono_conc_hashtable_destroy (filtered_classes);
3895 mono_conc_hashtable_destroy (entered_methods);
3896 mono_conc_hashtable_destroy (image_to_methods);
3897 mono_conc_hashtable_destroy (suppressed_assemblies);
3898 mono_os_mutex_destroy (&coverage_mutex);
3905 new_filename (const char* filename)
3907 time_t t = time (NULL);
3908 int pid = process_id ();
3913 int count_dates = 0;
3917 for (p = filename; *p; p++) {
3928 if (!count_dates && !count_pids)
3929 return pstrdup (filename);
3930 snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
3932 snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
3933 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
3934 s_date = strlen (time_buf);
3935 s_pid = strlen (pid_buf);
3936 d = res = (char *)malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
3937 for (p = filename; *p; p++) {
3944 strcpy (d, time_buf);
3947 } else if (*p == 'p') {
3948 strcpy (d, pid_buf);
3951 } else if (*p == '%') {
3963 //this is exposed by the JIT, but it's not meant to be a supported API for now.
3964 extern void mono_threads_attach_tools_thread (void);
3966 #ifndef DISABLE_HELPER_THREAD
3969 helper_thread (void* arg)
3971 MonoProfiler* prof = (MonoProfiler *)arg;
3975 MonoThread *thread = NULL;
3977 mono_threads_attach_tools_thread ();
3978 //fprintf (stderr, "Server listening\n");
3979 command_socket = -1;
3985 FD_SET (prof->server_socket, &rfds);
3986 max_fd = prof->server_socket;
3987 FD_SET (prof->pipes [0], &rfds);
3988 if (max_fd < prof->pipes [0])
3989 max_fd = prof->pipes [0];
3990 if (command_socket >= 0) {
3991 FD_SET (command_socket, &rfds);
3992 if (max_fd < command_socket)
3993 max_fd = command_socket;
3998 for ( i = 0; i < num_perf; ++i) {
3999 if (perf_data [i].perf_fd < 0)
4001 FD_SET (perf_data [i].perf_fd, &rfds);
4002 if (max_fd < perf_data [i].perf_fd)
4003 max_fd = perf_data [i].perf_fd;
4008 counters_and_perfcounters_sample (prof);
4012 len = select (max_fd + 1, &rfds, NULL, NULL, &tv);
4018 g_warning ("Error in proflog server: %s", strerror (errno));
4022 if (FD_ISSET (prof->pipes [0], &rfds)) {
4024 int r = read (prof->pipes [0], &c, 1);
4025 if (r == 1 && c == 0) {
4026 StatBuffer *sbufbase = prof->stat_buffers;
4028 if (!sbufbase->next)
4030 sbuf = sbufbase->next->next;
4031 sbufbase->next->next = NULL;
4033 fprintf (stderr, "stat buffer dump\n");
4035 dump_sample_hits (prof, sbuf);
4036 free_buffer (sbuf, sbuf->size);
4037 safe_send (prof, ensure_logbuf (0));
4041 /* time to shut down */
4042 dump_sample_hits (prof, prof->stat_buffers);
4044 mono_thread_detach (thread);
4046 fprintf (stderr, "helper shutdown\n");
4050 for ( i = 0; i < num_perf; ++i) {
4051 if (perf_data [i].perf_fd < 0)
4053 if (FD_ISSET (perf_data [i].perf_fd, &rfds))
4054 read_perf_mmap (prof, i);
4058 safe_send (prof, ensure_logbuf (0));
4064 for ( i = 0; i < num_perf; ++i) {
4065 if (perf_data [i].perf_fd < 0)
4067 if (FD_ISSET (perf_data [i].perf_fd, &rfds)) {
4068 read_perf_mmap (prof, i);
4069 safe_send (prof, ensure_logbuf (0));
4074 if (command_socket >= 0 && FD_ISSET (command_socket, &rfds)) {
4075 len = read (command_socket, buf, sizeof (buf) - 1);
4079 close (command_socket);
4080 command_socket = -1;
4084 if (strcmp (buf, "heapshot\n") == 0) {
4085 heapshot_requested = 1;
4086 //fprintf (stderr, "perform heapshot\n");
4087 if (InterlockedRead (&runtime_inited) && !thread) {
4088 thread = mono_thread_attach (mono_get_root_domain ());
4089 /*fprintf (stderr, "attached\n");*/
4092 process_requests (prof);
4093 mono_thread_detach (thread);
4099 if (!FD_ISSET (prof->server_socket, &rfds)) {
4102 command_socket = accept (prof->server_socket, NULL, NULL);
4103 if (command_socket < 0)
4105 //fprintf (stderr, "Accepted connection\n");
4111 start_helper_thread (MonoProfiler* prof)
4113 struct sockaddr_in server_address;
4116 if (pipe (prof->pipes) < 0) {
4117 fprintf (stderr, "Cannot create pipe\n");
4120 prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
4121 if (prof->server_socket < 0) {
4122 fprintf (stderr, "Cannot create server socket\n");
4125 memset (&server_address, 0, sizeof (server_address));
4126 server_address.sin_family = AF_INET;
4127 server_address.sin_addr.s_addr = INADDR_ANY;
4128 server_address.sin_port = htons (prof->command_port);
4129 if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) < 0) {
4130 fprintf (stderr, "Cannot bind server socket, port: %d: %s\n", prof->command_port, strerror (errno));
4131 close (prof->server_socket);
4134 if (listen (prof->server_socket, 1) < 0) {
4135 fprintf (stderr, "Cannot listen server socket\n");
4136 close (prof->server_socket);
4139 slen = sizeof (server_address);
4140 if (getsockname (prof->server_socket, (struct sockaddr *)&server_address, &slen) == 0) {
4141 prof->command_port = ntohs (server_address.sin_port);
4142 /*fprintf (stderr, "Assigned server port: %d\n", prof->command_port);*/
4145 r = pthread_create (&prof->helper_thread, NULL, helper_thread, prof);
4147 close (prof->server_socket);
4155 writer_thread (void *arg)
4157 MonoProfiler *prof = (MonoProfiler *)arg;
4159 mono_threads_attach_tools_thread ();
4163 while (InterlockedRead (&prof->run_writer_thread)) {
4164 WriterQueueEntry *entry;
4166 while ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&prof->writer_queue))) {
4167 LogBuffer *method_buffer = NULL;
4168 gboolean new_methods = FALSE;
4170 if (entry->methods->len)
4171 method_buffer = create_buffer ();
4174 * Encode the method events in a temporary log buffer that we
4175 * flush to disk before the main buffer, ensuring that all
4176 * methods have metadata emitted before they're referenced.
4178 for (guint i = 0; i < entry->methods->len; i++) {
4179 MethodInfo *info = (MethodInfo *)g_ptr_array_index (entry->methods, i);
4181 if (mono_conc_hashtable_lookup (prof->method_table, info->method))
4187 * Other threads use this hash table to get a general
4188 * idea of whether a method has already been emitted to
4189 * the stream. Due to the way we add to this table, it
4190 * can easily happen that multiple threads queue up the
4191 * same methods, but that's OK since eventually all
4192 * methods will be in this table and the thread-local
4193 * method lists will just be empty for the rest of the
4196 mono_os_mutex_lock (&prof->method_table_mutex);
4197 mono_conc_hashtable_insert (prof->method_table, info->method, info->method);
4198 mono_os_mutex_unlock (&prof->method_table_mutex);
4200 char *name = mono_method_full_name (info->method, 1);
4201 int nlen = strlen (name) + 1;
4202 void *cstart = info->ji ? mono_jit_info_get_code_start (info->ji) : NULL;
4203 int csize = info->ji ? mono_jit_info_get_code_size (info->ji) : 0;
4205 method_buffer = ensure_logbuf_inner (method_buffer,
4206 EVENT_SIZE /* event */ +
4207 LEB128_SIZE /* time */ +
4208 LEB128_SIZE /* method */ +
4209 LEB128_SIZE /* start */ +
4210 LEB128_SIZE /* size */ +
4214 emit_byte (method_buffer, TYPE_JIT | TYPE_METHOD);
4215 emit_time (method_buffer, info->time);
4216 emit_method_inner (method_buffer, info->method);
4217 emit_ptr (method_buffer, cstart);
4218 emit_value (method_buffer, csize);
4220 memcpy (method_buffer->data, name, nlen);
4221 method_buffer->data += nlen;
4227 g_ptr_array_free (entry->methods, TRUE);
4230 dump_buffer (prof, method_buffer);
4231 else if (method_buffer)
4232 free_buffer (method_buffer, method_buffer->size);
4234 dump_buffer (prof, entry->buffer);
4244 start_writer_thread (MonoProfiler* prof)
4246 InterlockedWrite (&prof->run_writer_thread, 1);
4248 return !pthread_create (&prof->writer_thread, NULL, writer_thread, prof);
4252 runtime_initialized (MonoProfiler *profiler)
4254 #ifndef DISABLE_HELPER_THREAD
4255 if (hs_mode_ondemand || need_helper_thread) {
4256 if (!start_helper_thread (profiler))
4257 profiler->command_port = 0;
4261 start_writer_thread (profiler);
4263 InterlockedWrite (&runtime_inited, 1);
4264 #ifndef DISABLE_HELPER_THREAD
4265 counters_init (profiler);
4266 counters_sample (profiler, 0);
4268 /* ensure the main thread data and startup are available soon */
4269 safe_send (profiler, ensure_logbuf (0));
4272 static MonoProfiler*
4273 create_profiler (const char *filename, GPtrArray *filters)
4277 int force_delete = 0;
4278 prof = (MonoProfiler *)calloc (1, sizeof (MonoProfiler));
4280 prof->command_port = command_port;
4281 if (filename && *filename == '-') {
4287 filename = "|mprof-report -";
4289 filename = "output.mlpd";
4290 nf = (char*)filename;
4292 nf = new_filename (filename);
4294 int s = strlen (nf) + 32;
4295 char *p = (char *)malloc (s);
4296 snprintf (p, s, "|mprof-report '--out=%s' -", nf);
4302 prof->file = popen (nf + 1, "w");
4303 prof->pipe_output = 1;
4304 } else if (*nf == '#') {
4305 int fd = strtol (nf + 1, NULL, 10);
4306 prof->file = fdopen (fd, "a");
4310 prof->file = fopen (nf, "wb");
4313 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
4316 #if defined (HAVE_SYS_ZLIB)
4318 prof->gzfile = gzdopen (fileno (prof->file), "wb");
4321 if (sample_type && !do_mono_sample)
4322 need_helper_thread = setup_perf_event ();
4324 /* FIXME: warn if different freq or sample type */
4328 if (do_mono_sample) {
4329 prof->stat_buffers = create_stat_buffer ();
4330 need_helper_thread = 1;
4332 if (do_counters && !need_helper_thread) {
4333 need_helper_thread = 1;
4336 prof->sorted_sample_events = g_ptr_array_sized_new (BUFFER_SIZE / SAMPLE_EVENT_SIZE_IN_SLOTS (0));
4338 #ifdef DISABLE_HELPER_THREAD
4339 if (hs_mode_ondemand)
4340 fprintf (stderr, "Ondemand heapshot unavailable on this arch.\n");
4343 fprintf (stderr, "Coverage unavailable on this arch.\n");
4347 mono_lock_free_queue_init (&prof->writer_queue);
4348 mono_os_mutex_init (&prof->method_table_mutex);
4349 prof->method_table = mono_conc_hashtable_new (NULL, NULL);
4352 coverage_init (prof);
4353 prof->coverage_filters = filters;
4355 prof->startup_time = current_time ();
4362 printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
4363 printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
4364 printf ("Options:\n");
4365 printf ("\thelp show this usage info\n");
4366 printf ("\t[no]alloc enable/disable recording allocation info\n");
4367 printf ("\t[no]calls enable/disable recording enter/leave method events\n");
4368 printf ("\theapshot[=MODE] record heap shot info (by default at each major collection)\n");
4369 printf ("\t MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
4370 printf ("\tcounters sample counters every 1s\n");
4371 printf ("\tsample[=TYPE] use statistical sampling mode (by default cycles/1000)\n");
4372 printf ("\t TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
4373 printf ("\t TYPE can be followed by /FREQUENCY\n");
4374 printf ("\ttime=fast use a faster (but more inaccurate) timer\n");
4375 printf ("\tmaxframes=NUM collect up to NUM stack frames\n");
4376 printf ("\tcalldepth=NUM ignore method events for call chain depth bigger than NUM\n");
4377 printf ("\toutput=FILENAME write the data to file FILENAME (-FILENAME to overwrite)\n");
4378 printf ("\toutput=|PROGRAM write the data to the stdin of PROGRAM\n");
4379 printf ("\t %%t is subtituted with date and time, %%p with the pid\n");
4380 printf ("\treport create a report instead of writing the raw data to a file\n");
4381 printf ("\tzip compress the output data\n");
4382 printf ("\tport=PORTNUM use PORTNUM for the listening command server\n");
4383 printf ("\tcoverage enable collection of code coverage data\n");
4384 printf ("\tcovfilter=ASSEMBLY add an assembly to the code coverage filters\n");
4385 printf ("\t add a + to include the assembly or a - to exclude it\n");
4386 printf ("\t filter=-mscorlib\n");
4387 printf ("\tcovfilter-file=FILE use FILE to generate the list of assemblies to be filtered\n");
4393 match_option (const char* p, const char *opt, char **rval)
4395 int len = strlen (opt);
4396 if (strncmp (p, opt, len) == 0) {
4398 if (p [len] == '=' && p [len + 1]) {
4399 const char *opt = p + len + 1;
4400 const char *end = strchr (opt, ',');
4408 val = (char *)malloc (l + 1);
4409 memcpy (val, opt, l);
4414 if (p [len] == 0 || p [len] == ',') {
4416 return p + len + (p [len] == ',');
4434 static const SampleMode sample_modes [] = {
4435 {"cycles", SAMPLE_CYCLES},
4436 {"instr", SAMPLE_INSTRUCTIONS},
4437 {"cachemiss", SAMPLE_CACHE_MISSES},
4438 {"cacherefs", SAMPLE_CACHE_REFS},
4439 {"branches", SAMPLE_BRANCHES},
4440 {"branchmiss", SAMPLE_BRANCH_MISSES},
4445 set_sample_mode (char* val, int allow_empty)
4448 char *maybe_freq = NULL;
4450 const SampleMode *smode = sample_modes;
4451 #ifndef USE_PERF_EVENTS
4454 if (allow_empty && !val) {
4455 sample_type = SAMPLE_CYCLES;
4459 if (strcmp (val, "mono") == 0) {
4461 sample_type = SAMPLE_CYCLES;
4465 for (smode = sample_modes; smode->name; smode++) {
4466 int l = strlen (smode->name);
4467 if (strncmp (val, smode->name, l) == 0) {
4468 sample_type = smode->sample_mode;
4469 maybe_freq = val + l;
4475 if (*maybe_freq == '/') {
4476 count = strtoul (maybe_freq + 1, &end, 10);
4477 if (maybe_freq + 1 == end)
4479 sample_freq = count;
4480 } else if (*maybe_freq != 0) {
4489 set_hsmode (char* val, int allow_empty)
4493 if (allow_empty && !val)
4495 if (strcmp (val, "ondemand") == 0) {
4496 hs_mode_ondemand = 1;
4500 count = strtoul (val, &end, 10);
4503 if (strcmp (end, "ms") == 0)
4505 else if (strcmp (end, "gc") == 0)
4513 * declaration to silence the compiler: this is the entry point that
4514 * mono will load from the shared library and call.
4517 mono_profiler_startup (const char *desc);
4520 mono_profiler_startup_log (const char *desc);
4523 * this is the entry point that will be used when the profiler
4524 * is embedded inside the main executable.
4527 mono_profiler_startup_log (const char *desc)
4529 mono_profiler_startup (desc);
4533 mono_profiler_startup (const char *desc)
4536 GPtrArray *filters = NULL;
4537 char *filename = NULL;
4541 int calls_enabled = 0;
4542 int allocs_enabled = 0;
4543 int only_counters = 0;
4544 int only_coverage = 0;
4545 int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
4546 MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
4547 MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
4548 MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS|
4549 MONO_PROFILE_INS_COVERAGE|MONO_PROFILE_APPDOMAIN_EVENTS|MONO_PROFILE_CONTEXT_EVENTS|
4550 MONO_PROFILE_ASSEMBLY_EVENTS;
4553 if (strncmp (p, "log", 3))
4558 for (; *p; p = opt) {
4564 if ((opt = match_option (p, "help", NULL)) != p) {
4568 if ((opt = match_option (p, "calls", NULL)) != p) {
4572 if ((opt = match_option (p, "nocalls", NULL)) != p) {
4573 events &= ~MONO_PROFILE_ENTER_LEAVE;
4577 if ((opt = match_option (p, "alloc", NULL)) != p) {
4581 if ((opt = match_option (p, "noalloc", NULL)) != p) {
4582 events &= ~MONO_PROFILE_ALLOCATIONS;
4585 if ((opt = match_option (p, "time", &val)) != p) {
4586 if (strcmp (val, "fast") == 0)
4588 else if (strcmp (val, "null") == 0)
4595 if ((opt = match_option (p, "report", NULL)) != p) {
4599 if ((opt = match_option (p, "debug", NULL)) != p) {
4603 if ((opt = match_option (p, "sampling-real", NULL)) != p) {
4604 sampling_mode = MONO_PROFILER_STAT_MODE_REAL;
4607 if ((opt = match_option (p, "sampling-process", NULL)) != p) {
4608 sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
4611 if ((opt = match_option (p, "heapshot", &val)) != p) {
4612 events &= ~MONO_PROFILE_ALLOCATIONS;
4613 events &= ~MONO_PROFILE_ENTER_LEAVE;
4616 set_hsmode (val, 1);
4619 if ((opt = match_option (p, "sample", &val)) != p) {
4620 events &= ~MONO_PROFILE_ALLOCATIONS;
4621 events &= ~MONO_PROFILE_ENTER_LEAVE;
4623 set_sample_mode (val, 1);
4626 if ((opt = match_option (p, "hsmode", &val)) != p) {
4627 fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
4628 set_hsmode (val, 0);
4631 if ((opt = match_option (p, "zip", NULL)) != p) {
4635 if ((opt = match_option (p, "output", &val)) != p) {
4639 if ((opt = match_option (p, "port", &val)) != p) {
4641 command_port = strtoul (val, &end, 10);
4645 if ((opt = match_option (p, "maxframes", &val)) != p) {
4647 num_frames = strtoul (val, &end, 10);
4648 if (num_frames > MAX_FRAMES)
4649 num_frames = MAX_FRAMES;
4651 notraces = num_frames == 0;
4654 if ((opt = match_option (p, "calldepth", &val)) != p) {
4656 max_call_depth = strtoul (val, &end, 10);
4660 if ((opt = match_option (p, "counters", NULL)) != p) {
4664 if ((opt = match_option (p, "countersonly", NULL)) != p) {
4668 if ((opt = match_option (p, "coverage", NULL)) != p) {
4670 events |= MONO_PROFILE_ENTER_LEAVE;
4671 debug_coverage = (g_getenv ("MONO_PROFILER_DEBUG_COVERAGE") != NULL);
4674 if ((opt = match_option (p, "onlycoverage", NULL)) != p) {
4678 if ((opt = match_option (p, "covfilter-file", &val)) != p) {
4680 char *line, *content;
4682 if (filters == NULL)
4683 filters = g_ptr_array_new ();
4685 filter_file = fopen (val, "r");
4686 if (filter_file == NULL) {
4687 fprintf (stderr, "Unable to open %s\n", val);
4691 /* Don't need to free content as it is referred to by the lines stored in @filters */
4692 content = get_file_content (filter_file);
4693 if (content == NULL)
4694 fprintf (stderr, "WARNING: %s is greater than 128kb - ignoring\n", val);
4696 while ((line = get_next_line (content, &content)))
4697 g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
4699 fclose (filter_file);
4702 if ((opt = match_option (p, "covfilter", &val)) != p) {
4703 if (filters == NULL)
4704 filters = g_ptr_array_new ();
4706 g_ptr_array_add (filters, val);
4714 if (calls_enabled) {
4715 events |= MONO_PROFILE_ENTER_LEAVE;
4719 events |= MONO_PROFILE_ALLOCATIONS;
4723 events = MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_INS_COVERAGE;
4725 utils_init (fast_time);
4727 prof = create_profiler (filename, filters);
4732 mono_profiler_install (prof, log_shutdown);
4733 mono_profiler_install_gc (gc_event, gc_resize);
4734 mono_profiler_install_allocation (gc_alloc);
4735 mono_profiler_install_gc_moves (gc_moves);
4736 mono_profiler_install_gc_roots (gc_handle, gc_roots);
4737 mono_profiler_install_appdomain (NULL, domain_loaded, NULL, domain_unloaded);
4738 mono_profiler_install_appdomain_name (domain_name);
4739 mono_profiler_install_context (context_loaded, context_unloaded);
4740 mono_profiler_install_class (NULL, class_loaded, NULL, class_unloaded);
4741 mono_profiler_install_module (NULL, image_loaded, NULL, image_unloaded);
4742 mono_profiler_install_assembly (NULL, assembly_loaded, assembly_unloaded, NULL);
4743 mono_profiler_install_thread (thread_start, thread_end);
4744 mono_profiler_install_thread_name (thread_name);
4745 mono_profiler_install_enter_leave (method_enter, method_leave);
4746 mono_profiler_install_jit_end (method_jitted);
4747 mono_profiler_install_code_buffer_new (code_buffer_new);
4748 mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
4749 mono_profiler_install_monitor (monitor_event);
4750 mono_profiler_install_runtime_initialized (runtime_initialized);
4752 mono_profiler_install_coverage_filter (coverage_filter);
4754 if (do_mono_sample && sample_type == SAMPLE_CYCLES && !only_counters) {
4755 events |= MONO_PROFILE_STATISTICAL;
4756 mono_profiler_set_statistical_mode (sampling_mode, 1000000 / sample_freq);
4757 mono_profiler_install_statistical (mono_sample_hit);
4760 mono_profiler_set_events ((MonoProfileFlags)events);
4762 TLS_INIT (tlsbuffer);
4763 TLS_INIT (tlsmethodlist);