2 * proflog.c: mono log profiler
5 * Paolo Molaro (lupus@ximian.com)
6 * Alex Rønne Petersen (alexrp@xamarin.com)
8 * Copyright 2010 Novell, Inc (http://www.novell.com)
9 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
13 #include "../mini/jit.h"
14 #include <mono/metadata/profiler.h>
15 #include <mono/metadata/threads.h>
16 #include <mono/metadata/mono-gc.h>
17 #include <mono/metadata/debug-helpers.h>
18 #include <mono/metadata/mono-perfcounters.h>
19 #include <mono/metadata/appdomain.h>
20 #include <mono/metadata/assembly.h>
21 #include <mono/metadata/tokentype.h>
22 #include <mono/metadata/tabledefs.h>
23 #include <mono/utils/atomic.h>
24 #include <mono/utils/mono-membar.h>
25 #include <mono/utils/mono-counters.h>
26 #include <mono/utils/mono-mutex.h>
27 #include <mono/utils/mono-conc-hashtable.h>
28 #include <mono/utils/lock-free-queue.h>
38 #if defined(HOST_WIN32) || defined(DISABLE_SOCKETS)
39 #define DISABLE_HELPER_THREAD 1
48 #ifdef HAVE_EXECINFO_H
55 #ifndef DISABLE_HELPER_THREAD
56 #include <sys/types.h>
57 #include <sys/socket.h>
58 #include <netinet/in.h>
59 #include <sys/select.h>
68 #ifdef HAVE_SYS_STAT_H
75 #if defined (HAVE_SYS_ZLIB)
79 #if defined(__linux__)
82 #include <sys/syscall.h>
83 #include "perf_event.h"
85 #ifdef ENABLE_PERF_EVENTS
86 #define USE_PERF_EVENTS 1
88 static int read_perf_mmap (MonoProfiler* prof, int cpu);
93 #define BUFFER_SIZE (4096 * 16)
94 static int nocalls = 0;
95 static int notraces = 0;
96 static int use_zip = 0;
97 static int do_report = 0;
98 static int do_heap_shot = 0;
99 static int max_call_depth = 100;
100 static volatile int runtime_inited = 0;
101 static int need_helper_thread = 0;
102 static int command_port = 0;
103 static int heapshot_requested = 0;
104 static int sample_type = 0;
105 static int sample_freq = 0;
106 static int do_mono_sample = 0;
107 static int in_shutdown = 0;
108 static int do_debug = 0;
109 static int do_counters = 0;
110 static int do_coverage = 0;
111 static gboolean debug_coverage = FALSE;
112 static MonoProfileSamplingMode sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
114 typedef struct _LogBuffer LogBuffer;
120 * The file is composed by a header followed by 0 or more buffers.
121 * Each buffer contains events that happened on a thread: for a given thread
122 * buffers that appear later in the file are guaranteed to contain events
123 * that happened later in time. Buffers from separate threads could be interleaved,
125 * Buffers are not required to be aligned.
128 * [id: 4 bytes] constant value: LOG_HEADER_ID
129 * [major: 1 byte] [minor: 1 byte] major and minor version of the log profiler
130 * [format: 1 byte] version of the data format for the rest of the file
131 * [ptrsize: 1 byte] size in bytes of a pointer in the profiled program
132 * [startup time: 8 bytes] time in milliseconds since the unix epoch when the program started
133 * [timer overhead: 4 bytes] approximate overhead in nanoseconds of the timer
134 * [flags: 4 bytes] file format flags, should be 0 for now
135 * [pid: 4 bytes] pid of the profiled process
136 * [port: 2 bytes] tcp port for server if != 0
137 * [sysid: 2 bytes] operating system and architecture identifier
139 * The multiple byte integers are in little-endian format.
142 * [buffer header] [event]*
143 * Buffers have a fixed-size header followed by 0 or more bytes of event data.
144 * Timing information and other values in the event data are usually stored
145 * as uleb128 or sleb128 integers. To save space, as noted for each item below,
146 * some data is represented as a difference between the actual value and
147 * either the last value of the same type (like for timing information) or
148 * as the difference from a value stored in a buffer header.
150 * For timing information the data is stored as uleb128, since timing
151 * increases in a monotonic way in each thread: the value is the number of
152 * nanoseconds to add to the last seen timing data in a buffer. The first value
153 * in a buffer will be calculated from the time_base field in the buffer head.
155 * Object or heap sizes are stored as uleb128.
156 * Pointer differences are stored as sleb128, instead.
158 * If an unexpected value is found, the rest of the buffer should be ignored,
159 * as generally the later values need the former to be interpreted correctly.
161 * buffer header format:
162 * [bufid: 4 bytes] constant value: BUF_ID
163 * [len: 4 bytes] size of the data following the buffer header
164 * [time_base: 8 bytes] time base in nanoseconds since an unspecified epoch
165 * [ptr_base: 8 bytes] base value for pointers
166 * [obj_base: 8 bytes] base value for object addresses
167 * [thread id: 8 bytes] system-specific thread ID (pthread_t for example)
168 * [method_base: 8 bytes] base value for MonoMethod pointers
171 * [extended info: upper 4 bits] [type: lower 4 bits] [data]*
172 * The data that follows depends on type and the extended info.
173 * Type is one of the enum values in proflog.h: TYPE_ALLOC, TYPE_GC,
174 * TYPE_METADATA, TYPE_METHOD, TYPE_EXCEPTION, TYPE_MONITOR, TYPE_HEAP.
175 * The extended info bits are interpreted based on type, see
176 * each individual event description below.
177 * strings are represented as a 0-terminated utf8 sequence.
180 * [flags: uleb128] must be 0
181 * [num: uleb128] number of frames following
182 * [frame: sleb128]* num MonoMethod pointers as differences from ptr_base
186 * exinfo: flags: TYPE_ALLOC_BT
187 * [time diff: uleb128] nanoseconds since last timing
188 * [ptr: sleb128] class as a byte difference from ptr_base
189 * [obj: sleb128] object address as a byte difference from obj_base
190 * [size: uleb128] size of the object in the heap
191 * If the TYPE_ALLOC_BT flag is set, a backtrace follows.
195 * exinfo: one of TYPE_GC_EVENT, TYPE_GC_RESIZE, TYPE_GC_MOVE, TYPE_GC_HANDLE_CREATED,
196 * TYPE_GC_HANDLE_DESTROYED
197 * [time diff: uleb128] nanoseconds since last timing
198 * if exinfo == TYPE_GC_RESIZE
199 * [heap_size: uleb128] new heap size
200 * if exinfo == TYPE_GC_EVENT
201 * [event type: uleb128] GC event (MONO_GC_EVENT_* from profiler.h)
202 * [generation: uleb128] GC generation event refers to
203 * if exinfo == TYPE_GC_MOVE
204 * [num_objects: uleb128] number of object moves that follow
205 * [objaddr: sleb128]+ num_objects object pointer differences from obj_base
206 * num is always an even number: the even items are the old
207 * addresses, the odd numbers are the respective new object addresses
208 * if exinfo == TYPE_GC_HANDLE_CREATED
209 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
210 * upper bits reserved as flags
211 * [handle: uleb128] GC handle value
212 * [objaddr: sleb128] object pointer differences from obj_base
213 * if exinfo == TYPE_GC_HANDLE_DESTROYED
214 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
215 * upper bits reserved as flags
216 * [handle: uleb128] GC handle value
218 * type metadata format:
219 * type: TYPE_METADATA
220 * exinfo: one of: TYPE_END_LOAD, TYPE_END_UNLOAD (optional for TYPE_THREAD and TYPE_DOMAIN)
221 * [time diff: uleb128] nanoseconds since last timing
222 * [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
223 * TYPE_THREAD, TYPE_CONTEXT
224 * [pointer: sleb128] pointer of the metadata type depending on mtype
225 * [flags: uleb128] must be 0
226 * if mtype == TYPE_CLASS
227 * [image: sleb128] MonoImage* as a pointer difference from ptr_base
228 * [name: string] full class name
229 * if mtype == TYPE_IMAGE
230 * [name: string] image file name
231 * if mtype == TYPE_ASSEMBLY
232 * [name: string] assembly name
233 * if mtype == TYPE_DOMAIN && exinfo == 0
234 * [name: string] domain friendly name
235 * if mtype == TYPE_CONTEXT
236 * [domain: sleb128] domain id as pointer
237 * if mtype == TYPE_THREAD && (format_version < 11 || (format_version > 10 && exinfo == 0))
238 * [name: string] thread name
240 * type method format:
242 * exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
243 * [time diff: uleb128] nanoseconds since last timing
244 * [method: sleb128] MonoMethod* as a pointer difference from the last such
245 * pointer or the buffer method_base
246 * if exinfo == TYPE_JIT
247 * [code address: sleb128] pointer to the native code as a diff from ptr_base
248 * [code size: uleb128] size of the generated code
249 * [name: string] full method name
251 * type runtime format:
253 * exinfo: one of: TYPE_JITHELPER
254 * [time diff: uleb128] nanoseconds since last timing
255 * if exinfo == TYPE_JITHELPER
256 * [type: uleb128] MonoProfilerCodeBufferType enum value
257 * [buffer address: sleb128] pointer to the native code as a diff from ptr_base
258 * [buffer size: uleb128] size of the generated code
259 * if type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE
260 * [name: string] buffer description name
262 * type monitor format:
264 * exinfo: TYPE_MONITOR_BT flag and one of: MONO_PROFILER_MONITOR_(CONTENTION|FAIL|DONE)
265 * [time diff: uleb128] nanoseconds since last timing
266 * [object: sleb128] the lock object as a difference from obj_base
267 * if exinfo.low3bits == MONO_PROFILER_MONITOR_CONTENTION
268 * If the TYPE_MONITOR_BT flag is set, a backtrace follows.
272 * exinfo: one of TYPE_HEAP_START, TYPE_HEAP_END, TYPE_HEAP_OBJECT, TYPE_HEAP_ROOT
273 * if exinfo == TYPE_HEAP_START
274 * [time diff: uleb128] nanoseconds since last timing
275 * if exinfo == TYPE_HEAP_END
276 * [time diff: uleb128] nanoseconds since last timing
277 * if exinfo == TYPE_HEAP_OBJECT
278 * [object: sleb128] the object as a difference from obj_base
279 * [class: sleb128] the object MonoClass* as a difference from ptr_base
280 * [size: uleb128] size of the object on the heap
281 * [num_refs: uleb128] number of object references
282 * if (format version > 1) each referenced objref is preceded by a
283 * uleb128 encoded offset: the first offset is from the object address
284 * and each next offset is relative to the previous one
285 * [objrefs: sleb128]+ object referenced as a difference from obj_base
286 * The same object can appear multiple times, but only the first time
287 * with size != 0: in the other cases this data will only be used to
288 * provide additional referenced objects.
289 * if exinfo == TYPE_HEAP_ROOT
290 * [num_roots: uleb128] number of root references
291 * [num_gc: uleb128] number of major gcs
292 * [object: sleb128] the object as a difference from obj_base
293 * [root_type: uleb128] the root_type: MonoProfileGCRootType (profiler.h)
294 * [extra_info: uleb128] the extra_info value
295 * object, root_type and extra_info are repeated num_roots times
299 * exinfo: one of TYPE_SAMPLE_HIT, TYPE_SAMPLE_USYM, TYPE_SAMPLE_UBIN, TYPE_SAMPLE_COUNTERS_DESC, TYPE_SAMPLE_COUNTERS
300 * if exinfo == TYPE_SAMPLE_HIT
301 * [sample_type: uleb128] type of sample (SAMPLE_*)
302 * [timestamp: uleb128] nanoseconds since startup (note: different from other timestamps!)
303 * if (format_version > 10)
304 * [thread: sleb128] thread id as difference from ptr_base
305 * [count: uleb128] number of following instruction addresses
306 * [ip: sleb128]* instruction pointer as difference from ptr_base
307 * if (format_version > 5)
308 * [mbt_count: uleb128] number of managed backtrace info triplets (method + IL offset + native offset)
309 * [method: sleb128]* MonoMethod* as a pointer difference from the last such
310 * pointer or the buffer method_base (the first such method can be also indentified by ip, but this is not neccessarily true)
311 * [il_offset: sleb128]* IL offset inside method where the hit occurred
312 * [native_offset: sleb128]* native offset inside method where the hit occurred
313 * if exinfo == TYPE_SAMPLE_USYM
314 * [address: sleb128] symbol address as a difference from ptr_base
315 * [size: uleb128] symbol size (may be 0 if unknown)
316 * [name: string] symbol name
317 * if exinfo == TYPE_SAMPLE_UBIN
318 * [time diff: uleb128] nanoseconds since last timing
319 * [address: sleb128] address where binary has been loaded
320 * [offset: uleb128] file offset of mapping (the same file can be mapped multiple times)
321 * [size: uleb128] memory size
322 * [name: string] binary name
323 * if exinfo == TYPE_SAMPLE_COUNTERS_DESC
324 * [len: uleb128] number of counters
326 * [section: uleb128] section of counter
327 * if section == MONO_COUNTER_PERFCOUNTERS:
328 * [section_name: string] section name of counter
329 * [name: string] name of counter
330 * [type: uleb128] type of counter
331 * [unit: uleb128] unit of counter
332 * [variance: uleb128] variance of counter
333 * [index: uleb128] unique index of counter
334 * if exinfo == TYPE_SAMPLE_COUNTERS
335 * [timestamp: uleb128] sampling timestamp
337 * [index: uleb128] unique index of counter
340 * [type: uleb128] type of counter value
343 * [0: uleb128] 0 -> value is null
345 * [1: uleb128] 1 -> value is not null
346 * [value: string] counter value
348 * [value: uleb128/sleb128/double] counter value, can be sleb128, uleb128 or double (determined by using type)
350 * type coverage format
351 * type: TYPE_COVERAGE
352 * exinfo: one of TYPE_COVERAGE_METHOD, TYPE_COVERAGE_STATEMENT, TYPE_COVERAGE_ASSEMBLY, TYPE_COVERAGE_CLASS
353 * if exinfo == TYPE_COVERAGE_METHOD
354 * [assembly: string] name of assembly
355 * [class: string] name of the class
356 * [name: string] name of the method
357 * [signature: string] the signature of the method
358 * [filename: string] the file path of the file that contains this method
359 * [token: uleb128] the method token
360 * [method_id: uleb128] an ID for this data to associate with the buffers of TYPE_COVERAGE_STATEMENTS
361 * [len: uleb128] the number of TYPE_COVERAGE_BUFFERS associated with this method
362 * if exinfo == TYPE_COVERAGE_STATEMENTS
363 * [method_id: uleb128] an the TYPE_COVERAGE_METHOD buffer to associate this with
364 * [offset: uleb128] the il offset relative to the previous offset
365 * [counter: uleb128] the counter for this instruction
366 * [line: uleb128] the line of filename containing this instruction
367 * [column: uleb128] the column containing this instruction
368 * if exinfo == TYPE_COVERAGE_ASSEMBLY
369 * [name: string] assembly name
370 * [guid: string] assembly GUID
371 * [filename: string] assembly filename
372 * [number_of_methods: uleb128] the number of methods in this assembly
373 * [fully_covered: uleb128] the number of fully covered methods
374 * [partially_covered: uleb128] the number of partially covered methods
375 * currently partially_covered will always be 0, and fully_covered is the
376 * number of methods that are fully and partially covered.
377 * if exinfo == TYPE_COVERAGE_CLASS
378 * [name: string] assembly name
379 * [class: string] class name
380 * [number_of_methods: uleb128] the number of methods in this class
381 * [fully_covered: uleb128] the number of fully covered methods
382 * [partially_covered: uleb128] the number of partially covered methods
383 * currently partially_covered will always be 0, and fully_covered is the
384 * number of methods that are fully and partially covered.
388 * Format oddities that we ought to fix:
390 * - Methods written in emit_bt () should be based on the buffer's base
391 * method instead of the base pointer.
392 * - The TYPE_SAMPLE_HIT event contains (currently) pointless data like
393 * always-one unmanaged frame count and always-zero IL offsets.
395 * These are mostly small things and are not worth a format change by
396 * themselves. They should be done when some other major change has to
397 * be done to the format.
405 uintptr_t method_base;
406 uintptr_t last_method;
409 unsigned char* data_end;
414 unsigned char buf [1];
418 ign_res (int G_GNUC_UNUSED unused, ...)
422 #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++;}
423 #define EXIT_LOG(lb) (lb)->locked--;
425 typedef struct _StatBuffer StatBuffer;
434 typedef struct _BinaryObject BinaryObject;
436 struct _BinaryObject {
442 struct _MonoProfiler {
443 StatBuffer *stat_buffers;
445 #if defined (HAVE_SYS_ZLIB)
448 uint64_t startup_time;
450 int last_gc_gen_started;
455 pthread_t helper_thread;
456 pthread_t writer_thread;
458 volatile gint32 run_writer_thread;
459 MonoLockFreeQueue writer_queue;
460 MonoConcurrentHashTable *method_table;
461 mono_mutex_t method_table_mutex;
462 BinaryObject *binary_objects;
463 GPtrArray *coverage_filters;
464 GPtrArray *sorted_sample_events;
467 typedef struct _WriterQueueEntry WriterQueueEntry;
468 struct _WriterQueueEntry {
469 MonoLockFreeQueueNode node;
474 typedef struct _MethodInfo MethodInfo;
485 #define TLS_SET(x,y) (TlsSetValue (x, y))
486 #define TLS_GET(t,x) ((t *) TlsGetValue (x))
487 #define TLS_INIT(x) (x = TlsAlloc ())
488 static int tlsbuffer;
489 static int tlsmethodlist;
491 #define TLS_SET(x,y) (x = y)
492 #define TLS_GET(t,x) (x)
494 static __thread LogBuffer* tlsbuffer = NULL;
495 static __thread GPtrArray* tlsmethodlist = NULL;
497 #define TLS_SET(x,y) (pthread_setspecific (x, y))
498 #define TLS_GET(t,x) ((t *) pthread_getspecific (x))
499 #define TLS_INIT(x) (pthread_key_create (&x, NULL))
500 static pthread_key_t tlsbuffer;
501 static pthread_key_t tlsmethodlist;
504 static void safe_send (MonoProfiler *profiler, LogBuffer *logbuffer);
507 pstrdup (const char *s)
509 int len = strlen (s) + 1;
510 char *p = malloc (len);
516 create_stat_buffer (void)
518 StatBuffer* buf = alloc_buffer (BUFFER_SIZE);
519 buf->size = BUFFER_SIZE;
520 buf->data_end = (uintptr_t*)((unsigned char*)buf + buf->size);
521 buf->data = buf->buf;
528 LogBuffer* buf = alloc_buffer (BUFFER_SIZE);
529 buf->size = BUFFER_SIZE;
530 buf->time_base = current_time ();
531 buf->last_time = buf->time_base;
532 buf->data_end = (unsigned char*)buf + buf->size;
533 buf->data = buf->buf;
540 if (!TLS_GET (LogBuffer, tlsbuffer)) {
541 LogBuffer *logbuffer = create_buffer ();
542 TLS_SET (tlsbuffer, logbuffer);
543 logbuffer->thread_id = thread_id ();
545 if (!TLS_GET (GPtrArray, tlsmethodlist)) {
546 GPtrArray *methodlist = g_ptr_array_new ();
547 TLS_SET (tlsmethodlist, methodlist);
550 //printf ("thread %p at time %llu\n", (void*)logbuffer->thread_id, logbuffer->time_base);
554 ensure_logbuf_inner (LogBuffer *old, int bytes)
556 if (old && old->data + bytes + 100 < old->data_end)
559 LogBuffer *new = create_buffer ();
560 new->thread_id = thread_id ();
564 new->call_depth = old->call_depth;
570 ensure_logbuf (int bytes)
572 LogBuffer *old = TLS_GET (LogBuffer, tlsbuffer);
573 LogBuffer *new = ensure_logbuf_inner (old, bytes);
576 return old; // Still enough space.
578 TLS_SET (tlsbuffer, new);
585 emit_byte (LogBuffer *logbuffer, int value)
587 logbuffer->data [0] = value;
589 assert (logbuffer->data <= logbuffer->data_end);
593 emit_value (LogBuffer *logbuffer, int value)
595 encode_uleb128 (value, logbuffer->data, &logbuffer->data);
596 assert (logbuffer->data <= logbuffer->data_end);
600 emit_time (LogBuffer *logbuffer, uint64_t value)
602 uint64_t tdiff = value - logbuffer->last_time;
603 if (value < logbuffer->last_time)
604 printf ("time went backwards\n");
605 //if (tdiff > 1000000)
606 // printf ("large time offset: %llu\n", tdiff);
607 encode_uleb128 (tdiff, logbuffer->data, &logbuffer->data);
608 /*if (tdiff != decode_uleb128 (p, &p))
609 printf ("incorrect encoding: %llu\n", tdiff);*/
610 logbuffer->last_time = value;
611 assert (logbuffer->data <= logbuffer->data_end);
615 emit_svalue (LogBuffer *logbuffer, int64_t value)
617 encode_sleb128 (value, logbuffer->data, &logbuffer->data);
618 assert (logbuffer->data <= logbuffer->data_end);
622 emit_uvalue (LogBuffer *logbuffer, uint64_t value)
624 encode_uleb128 (value, logbuffer->data, &logbuffer->data);
625 assert (logbuffer->data <= logbuffer->data_end);
629 emit_ptr (LogBuffer *logbuffer, void *ptr)
631 if (!logbuffer->ptr_base)
632 logbuffer->ptr_base = (uintptr_t)ptr;
633 emit_svalue (logbuffer, (intptr_t)ptr - logbuffer->ptr_base);
634 assert (logbuffer->data <= logbuffer->data_end);
638 emit_method_inner (LogBuffer *logbuffer, void *method)
640 if (!logbuffer->method_base) {
641 logbuffer->method_base = (intptr_t)method;
642 logbuffer->last_method = (intptr_t)method;
644 encode_sleb128 ((intptr_t)((char*)method - (char*)logbuffer->last_method), logbuffer->data, &logbuffer->data);
645 logbuffer->last_method = (intptr_t)method;
646 assert (logbuffer->data <= logbuffer->data_end);
655 find_method (MonoDomain *domain, void *user_data)
657 MethodSearch *search = user_data;
662 MonoJitInfo *ji = mono_get_jit_info_from_method (domain, search->method);
664 // It could be AOT'd, so we need to get it from the AOT runtime's cache.
666 void *ip = mono_aot_get_method (domain, search->method);
668 // Avoid a slow path in mono_jit_info_table_find ().
670 ji = mono_jit_info_table_find (domain, ip);
678 register_method_local (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji)
680 if (!mono_conc_hashtable_lookup (prof->method_table, method)) {
682 MethodSearch search = { method, NULL };
684 mono_domain_foreach (find_method, &search);
691 MethodInfo *info = malloc (sizeof (MethodInfo));
693 info->method = method;
696 g_ptr_array_add (TLS_GET (GPtrArray, tlsmethodlist), info);
701 emit_method (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
703 register_method_local (prof, method, NULL);
704 emit_method_inner (logbuffer, method);
708 emit_method_as_ptr (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
710 register_method_local (prof, method, NULL);
711 emit_ptr (logbuffer, method);
715 emit_obj (LogBuffer *logbuffer, void *ptr)
717 if (!logbuffer->obj_base)
718 logbuffer->obj_base = (uintptr_t)ptr >> 3;
719 emit_svalue (logbuffer, ((uintptr_t)ptr >> 3) - logbuffer->obj_base);
720 assert (logbuffer->data <= logbuffer->data_end);
724 emit_string (LogBuffer *logbuffer, const char *str, size_t size)
728 for (; i < size; i++) {
731 emit_byte (logbuffer, str [i]);
734 emit_byte (logbuffer, '\0');
738 emit_double (LogBuffer *logbuffer, double value)
741 unsigned char buffer[8];
742 memcpy (buffer, &value, 8);
743 #if G_BYTE_ORDER == G_BIG_ENDIAN
744 for (i = 7; i >= 0; i--)
746 for (i = 0; i < 8; i++)
748 emit_byte (logbuffer, buffer[i]);
752 write_int16 (char *buf, int32_t value)
755 for (i = 0; i < 2; ++i) {
763 write_int32 (char *buf, int32_t value)
766 for (i = 0; i < 4; ++i) {
774 write_int64 (char *buf, int64_t value)
777 for (i = 0; i < 8; ++i) {
785 dump_header (MonoProfiler *profiler)
789 p = write_int32 (p, LOG_HEADER_ID);
790 *p++ = LOG_VERSION_MAJOR;
791 *p++ = LOG_VERSION_MINOR;
792 *p++ = LOG_DATA_VERSION;
793 *p++ = sizeof (void*);
794 p = write_int64 (p, ((uint64_t)time (NULL)) * 1000); /* startup time */
795 p = write_int32 (p, get_timer_overhead ()); /* timer overhead */
796 p = write_int32 (p, 0); /* flags */
797 p = write_int32 (p, process_id ()); /* pid */
798 p = write_int16 (p, profiler->command_port); /* port */
799 p = write_int16 (p, 0); /* opsystem */
800 #if defined (HAVE_SYS_ZLIB)
801 if (profiler->gzfile) {
802 gzwrite (profiler->gzfile, hbuf, p - hbuf);
804 fwrite (hbuf, p - hbuf, 1, profiler->file);
807 fwrite (hbuf, p - hbuf, 1, profiler->file);
808 fflush (profiler->file);
813 send_buffer (MonoProfiler *prof, GPtrArray *methods, LogBuffer *buffer)
815 WriterQueueEntry *entry = calloc (1, sizeof (WriterQueueEntry));
816 mono_lock_free_queue_node_init (&entry->node, FALSE);
817 entry->methods = methods;
818 entry->buffer = buffer;
819 mono_lock_free_queue_enqueue (&prof->writer_queue, &entry->node);
823 dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
828 dump_buffer (profiler, buf->next);
829 p = write_int32 (p, BUF_ID);
830 p = write_int32 (p, buf->data - buf->buf);
831 p = write_int64 (p, buf->time_base);
832 p = write_int64 (p, buf->ptr_base);
833 p = write_int64 (p, buf->obj_base);
834 p = write_int64 (p, buf->thread_id);
835 p = write_int64 (p, buf->method_base);
836 #if defined (HAVE_SYS_ZLIB)
837 if (profiler->gzfile) {
838 gzwrite (profiler->gzfile, hbuf, p - hbuf);
839 gzwrite (profiler->gzfile, buf->buf, buf->data - buf->buf);
842 fwrite (hbuf, p - hbuf, 1, profiler->file);
843 fwrite (buf->buf, buf->data - buf->buf, 1, profiler->file);
844 fflush (profiler->file);
845 #if defined (HAVE_SYS_ZLIB)
848 free_buffer (buf, buf->size);
852 process_requests (MonoProfiler *profiler)
854 if (heapshot_requested)
855 mono_gc_collect (mono_gc_max_generation ());
858 static void counters_init (MonoProfiler *profiler);
859 static void counters_sample (MonoProfiler *profiler, uint64_t timestamp);
862 * Can be called only at safe callback locations.
865 safe_send (MonoProfiler *profiler, LogBuffer *logbuffer)
867 /* We need the runtime initialized so that we have threads and hazard
868 * pointers available. Otherwise, the lock free queue will not work and
869 * there won't be a thread to process the data.
871 * While the runtime isn't initialized, we just accumulate data in the
872 * thread local buffer list.
874 if (!InterlockedRead (&runtime_inited))
877 int cd = logbuffer->call_depth;
879 send_buffer (profiler, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
881 TLS_SET (tlsbuffer, NULL);
882 TLS_SET (tlsmethodlist, NULL);
886 TLS_GET (LogBuffer, tlsbuffer)->call_depth = cd;
890 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
893 uintptr_t last_offset = 0;
894 //const char *name = mono_class_get_name (klass);
895 LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 10 + 10 + 10 + num * (10 + 10));
896 emit_byte (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
897 emit_obj (logbuffer, obj);
898 emit_ptr (logbuffer, klass);
899 /* account for object alignment in the heap */
902 emit_value (logbuffer, size);
903 emit_value (logbuffer, num);
904 for (i = 0; i < num; ++i) {
905 emit_value (logbuffer, offsets [i] - last_offset);
906 last_offset = offsets [i];
907 emit_obj (logbuffer, refs [i]);
910 // printf ("obj: %p, klass: %s, refs: %d, size: %d\n", obj, name, (int)num, (int)size);
914 static unsigned int hs_mode_ms = 0;
915 static unsigned int hs_mode_gc = 0;
916 static unsigned int hs_mode_ondemand = 0;
917 static unsigned int gc_count = 0;
918 static uint64_t last_hs_time = 0;
921 heap_walk (MonoProfiler *profiler)
925 LogBuffer *logbuffer;
928 logbuffer = ensure_logbuf (1 + 10);
929 now = current_time ();
930 if (hs_mode_ms && (now - last_hs_time)/1000000 >= hs_mode_ms)
932 else if (hs_mode_gc && (gc_count % hs_mode_gc) == 0)
934 else if (hs_mode_ondemand)
935 do_walk = heapshot_requested;
936 else if (!hs_mode_ms && !hs_mode_gc && profiler->last_gc_gen_started == mono_gc_max_generation ())
941 heapshot_requested = 0;
942 emit_byte (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
943 emit_time (logbuffer, now);
944 mono_gc_walk_heap (0, gc_reference, NULL);
945 logbuffer = ensure_logbuf (1 + 10);
946 now = current_time ();
947 emit_byte (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
948 emit_time (logbuffer, now);
953 gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation) {
955 LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 10 + 10);
956 now = current_time ();
957 ENTER_LOG (logbuffer, "gcevent");
958 emit_byte (logbuffer, TYPE_GC_EVENT | TYPE_GC);
959 emit_time (logbuffer, now);
960 emit_value (logbuffer, ev);
961 emit_value (logbuffer, generation);
962 /* to deal with nested gen1 after gen0 started */
963 if (ev == MONO_GC_EVENT_START) {
964 profiler->last_gc_gen_started = generation;
965 if (generation == mono_gc_max_generation ())
968 if (ev == MONO_GC_EVENT_PRE_START_WORLD)
969 heap_walk (profiler);
970 EXIT_LOG (logbuffer);
971 if (ev == MONO_GC_EVENT_POST_START_WORLD)
972 safe_send (profiler, logbuffer);
973 //printf ("gc event %d for generation %d\n", ev, generation);
977 gc_resize (MonoProfiler *profiler, int64_t new_size) {
979 LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 10);
980 now = current_time ();
981 ENTER_LOG (logbuffer, "gcresize");
982 emit_byte (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
983 emit_time (logbuffer, now);
984 emit_value (logbuffer, new_size);
985 //printf ("gc resized to %lld\n", new_size);
986 EXIT_LOG (logbuffer);
989 #define MAX_FRAMES 32
992 MonoMethod* methods [MAX_FRAMES];
993 int32_t il_offsets [MAX_FRAMES];
994 int32_t native_offsets [MAX_FRAMES];
996 static int num_frames = MAX_FRAMES;
999 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
1001 FrameData *frame = data;
1002 if (method && frame->count < num_frames) {
1003 frame->il_offsets [frame->count] = il_offset;
1004 frame->native_offsets [frame->count] = native_offset;
1005 frame->methods [frame->count++] = method;
1006 //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
1008 return frame->count == num_frames;
1012 * a note about stack walks: they can cause more profiler events to fire,
1013 * so we need to make sure they don't happen after we started emitting an
1014 * event, hence the collect_bt/emit_bt split.
1017 collect_bt (FrameData *data)
1020 mono_stack_walk_no_il (walk_stack, data);
1024 emit_bt (MonoProfiler *prof, LogBuffer *logbuffer, FrameData *data)
1026 /* FIXME: this is actually tons of data and we should
1027 * just output it the first time and use an id the next
1029 if (data->count > num_frames)
1030 printf ("bad num frames: %d\n", data->count);
1031 emit_value (logbuffer, 0); /* flags */
1032 emit_value (logbuffer, data->count);
1033 //if (*p != data.count) {
1034 // 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);}
1035 while (data->count) {
1036 emit_method_as_ptr (prof, logbuffer, data->methods [--data->count]);
1041 gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1045 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces)? TYPE_ALLOC_BT: 0;
1047 LogBuffer *logbuffer;
1048 len = mono_object_get_size (obj);
1049 /* account for object alignment in the heap */
1054 logbuffer = ensure_logbuf (1 + 10 + 10 + 10 + 10 + MAX_FRAMES * (10 + 10 + 10));
1055 now = current_time ();
1056 ENTER_LOG (logbuffer, "gcalloc");
1057 emit_byte (logbuffer, do_bt | TYPE_ALLOC);
1058 emit_time (logbuffer, now);
1059 emit_ptr (logbuffer, klass);
1060 emit_obj (logbuffer, obj);
1061 emit_value (logbuffer, len);
1063 emit_bt (prof, logbuffer, &data);
1064 EXIT_LOG (logbuffer);
1065 if (logbuffer->next)
1066 safe_send (prof, logbuffer);
1067 process_requests (prof);
1068 //printf ("gc alloc %s at %p\n", mono_class_get_name (klass), obj);
1072 gc_moves (MonoProfiler *prof, void **objects, int num)
1076 LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 10 + num * 10);
1077 now = current_time ();
1078 ENTER_LOG (logbuffer, "gcmove");
1079 emit_byte (logbuffer, TYPE_GC_MOVE | TYPE_GC);
1080 emit_time (logbuffer, now);
1081 emit_value (logbuffer, num);
1082 for (i = 0; i < num; ++i)
1083 emit_obj (logbuffer, objects [i]);
1084 //printf ("gc moved %d objects\n", num/2);
1085 EXIT_LOG (logbuffer);
1089 gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
1092 LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 10 + num * (10 + 10 + 10));
1093 ENTER_LOG (logbuffer, "gcroots");
1094 emit_byte (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
1095 emit_value (logbuffer, num);
1096 emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
1097 for (i = 0; i < num; ++i) {
1098 emit_obj (logbuffer, objects [i]);
1099 emit_value (logbuffer, root_types [i]);
1100 emit_value (logbuffer, extra_info [i]);
1102 EXIT_LOG (logbuffer);
1106 gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
1109 LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 10 + 10 + 10);
1110 now = current_time ();
1111 ENTER_LOG (logbuffer, "gchandle");
1112 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1113 emit_byte (logbuffer, TYPE_GC_HANDLE_CREATED | TYPE_GC);
1114 else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
1115 emit_byte (logbuffer, TYPE_GC_HANDLE_DESTROYED | TYPE_GC);
1118 emit_time (logbuffer, now);
1119 emit_value (logbuffer, type);
1120 emit_value (logbuffer, handle);
1121 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1122 emit_obj (logbuffer, obj);
1123 EXIT_LOG (logbuffer);
1124 process_requests (prof);
1128 push_nesting (char *p, MonoClass *klass)
1133 nesting = mono_class_get_nesting_type (klass);
1135 p = push_nesting (p, nesting);
1139 name = mono_class_get_name (klass);
1140 nspace = mono_class_get_namespace (klass);
1143 p += strlen (nspace);
1153 type_name (MonoClass *klass)
1157 push_nesting (buf, klass);
1158 p = malloc (strlen (buf) + 1);
1164 image_loaded (MonoProfiler *prof, MonoImage *image, int result)
1169 LogBuffer *logbuffer;
1170 if (result != MONO_PROFILE_OK)
1172 name = mono_image_get_filename (image);
1173 nlen = strlen (name) + 1;
1174 logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10 + nlen);
1175 now = current_time ();
1176 ENTER_LOG (logbuffer, "image");
1177 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1178 emit_time (logbuffer, now);
1179 emit_byte (logbuffer, TYPE_IMAGE);
1180 emit_ptr (logbuffer, image);
1181 emit_value (logbuffer, 0); /* flags */
1182 memcpy (logbuffer->data, name, nlen);
1183 logbuffer->data += nlen;
1184 //printf ("loaded image %p (%s)\n", image, name);
1185 EXIT_LOG (logbuffer);
1186 if (logbuffer->next)
1187 safe_send (prof, logbuffer);
1188 process_requests (prof);
1192 image_unloaded (MonoProfiler *prof, MonoImage *image)
1194 const char *name = mono_image_get_filename (image);
1195 int nlen = strlen (name) + 1;
1196 LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10 + nlen);
1197 uint64_t now = current_time ();
1199 ENTER_LOG (logbuffer, "image-unload");
1200 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1201 emit_time (logbuffer, now);
1202 emit_byte (logbuffer, TYPE_IMAGE);
1203 emit_ptr (logbuffer, image);
1204 emit_value (logbuffer, 0); /* flags */
1205 memcpy (logbuffer->data, name, nlen);
1206 logbuffer->data += nlen;
1207 EXIT_LOG (logbuffer);
1209 if (logbuffer->next)
1210 safe_send (prof, logbuffer);
1212 process_requests (prof);
1216 assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly, int result)
1218 if (result != MONO_PROFILE_OK)
1221 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1222 int nlen = strlen (name) + 1;
1223 LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10 + nlen);
1224 uint64_t now = current_time ();
1226 ENTER_LOG (logbuffer, "assembly-load");
1227 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1228 emit_time (logbuffer, now);
1229 emit_byte (logbuffer, TYPE_ASSEMBLY);
1230 emit_ptr (logbuffer, assembly);
1231 emit_value (logbuffer, 0); /* flags */
1232 memcpy (logbuffer->data, name, nlen);
1233 logbuffer->data += nlen;
1234 EXIT_LOG (logbuffer);
1238 if (logbuffer->next)
1239 safe_send (prof, logbuffer);
1241 process_requests (prof);
1245 assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
1247 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1248 int nlen = strlen (name) + 1;
1249 LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10 + nlen);
1250 uint64_t now = current_time ();
1252 ENTER_LOG (logbuffer, "assembly-unload");
1253 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1254 emit_time (logbuffer, now);
1255 emit_byte (logbuffer, TYPE_ASSEMBLY);
1256 emit_ptr (logbuffer, assembly);
1257 emit_value (logbuffer, 0); /* flags */
1258 memcpy (logbuffer->data, name, nlen);
1259 logbuffer->data += nlen;
1260 EXIT_LOG (logbuffer);
1264 if (logbuffer->next)
1265 safe_send (prof, logbuffer);
1267 process_requests (prof);
1271 class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
1277 LogBuffer *logbuffer;
1278 if (result != MONO_PROFILE_OK)
1280 if (InterlockedRead (&runtime_inited))
1281 name = mono_type_get_name (mono_class_get_type (klass));
1283 name = type_name (klass);
1284 nlen = strlen (name) + 1;
1285 image = mono_class_get_image (klass);
1286 logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10 + 10 + nlen);
1287 now = current_time ();
1288 ENTER_LOG (logbuffer, "class");
1289 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1290 emit_time (logbuffer, now);
1291 emit_byte (logbuffer, TYPE_CLASS);
1292 emit_ptr (logbuffer, klass);
1293 emit_ptr (logbuffer, image);
1294 emit_value (logbuffer, 0); /* flags */
1295 memcpy (logbuffer->data, name, nlen);
1296 logbuffer->data += nlen;
1297 //printf ("loaded class %p (%s)\n", klass, name);
1302 EXIT_LOG (logbuffer);
1303 if (logbuffer->next)
1304 safe_send (prof, logbuffer);
1305 process_requests (prof);
1309 class_unloaded (MonoProfiler *prof, MonoClass *klass)
1313 if (InterlockedRead (&runtime_inited))
1314 name = mono_type_get_name (mono_class_get_type (klass));
1316 name = type_name (klass);
1318 int nlen = strlen (name) + 1;
1319 MonoImage *image = mono_class_get_image (klass);
1320 LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10 + 10 + nlen);
1321 uint64_t now = current_time ();
1323 ENTER_LOG (logbuffer, "class-unload");
1324 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1325 emit_time (logbuffer, now);
1326 emit_byte (logbuffer, TYPE_CLASS);
1327 emit_ptr (logbuffer, klass);
1328 emit_ptr (logbuffer, image);
1329 emit_value (logbuffer, 0); /* flags */
1330 memcpy (logbuffer->data, name, nlen);
1331 logbuffer->data += nlen;
1332 EXIT_LOG (logbuffer);
1339 if (logbuffer->next)
1340 safe_send (prof, logbuffer);
1342 process_requests (prof);
1345 #ifndef DISABLE_HELPER_THREAD
1346 static void process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method);
1347 #endif /* DISABLE_HELPER_THREAD */
1350 method_enter (MonoProfiler *prof, MonoMethod *method)
1352 uint64_t now = current_time ();
1354 #ifndef DISABLE_HELPER_THREAD
1355 process_method_enter_coverage (prof, method);
1356 #endif /* DISABLE_HELPER_THREAD */
1358 LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 10);
1359 if (logbuffer->call_depth++ > max_call_depth)
1361 ENTER_LOG (logbuffer, "enter");
1362 emit_byte (logbuffer, TYPE_ENTER | TYPE_METHOD);
1363 emit_time (logbuffer, now);
1364 emit_method (prof, logbuffer, method);
1365 EXIT_LOG (logbuffer);
1367 process_requests (prof);
1371 method_leave (MonoProfiler *prof, MonoMethod *method)
1374 LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 10);
1375 if (--logbuffer->call_depth > max_call_depth)
1377 now = current_time ();
1378 ENTER_LOG (logbuffer, "leave");
1379 emit_byte (logbuffer, TYPE_LEAVE | TYPE_METHOD);
1380 emit_time (logbuffer, now);
1381 emit_method (prof, logbuffer, method);
1382 EXIT_LOG (logbuffer);
1383 if (logbuffer->next)
1384 safe_send (prof, logbuffer);
1385 process_requests (prof);
1389 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
1392 LogBuffer *logbuffer;
1395 logbuffer = ensure_logbuf (1 + 10 + 10);
1396 if (--logbuffer->call_depth > max_call_depth)
1398 now = current_time ();
1399 ENTER_LOG (logbuffer, "eleave");
1400 emit_byte (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
1401 emit_time (logbuffer, now);
1402 emit_method (prof, logbuffer, method);
1403 EXIT_LOG (logbuffer);
1404 process_requests (prof);
1408 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji, int result)
1410 if (result != MONO_PROFILE_OK)
1413 register_method_local (prof, method, ji);
1415 process_requests (prof);
1419 code_buffer_new (MonoProfiler *prof, void *buffer, int size, MonoProfilerCodeBufferType type, void *data)
1424 LogBuffer *logbuffer;
1425 if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
1427 nlen = strlen (name) + 1;
1432 logbuffer = ensure_logbuf (1 + 10 + 10 + 10 + 10 + nlen);
1433 now = current_time ();
1434 ENTER_LOG (logbuffer, "code buffer");
1435 emit_byte (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
1436 emit_time (logbuffer, now);
1437 emit_value (logbuffer, type);
1438 emit_ptr (logbuffer, buffer);
1439 emit_value (logbuffer, size);
1441 memcpy (logbuffer->data, name, nlen);
1442 logbuffer->data += nlen;
1444 EXIT_LOG (logbuffer);
1445 process_requests (prof);
1449 throw_exc (MonoProfiler *prof, MonoObject *object)
1451 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces)? TYPE_EXCEPTION_BT: 0;
1454 LogBuffer *logbuffer;
1457 logbuffer = ensure_logbuf (1 + 10 + 10 + MAX_FRAMES * (10 + 10 + 10));
1458 now = current_time ();
1459 ENTER_LOG (logbuffer, "throw");
1460 emit_byte (logbuffer, do_bt | TYPE_EXCEPTION);
1461 emit_time (logbuffer, now);
1462 emit_obj (logbuffer, object);
1464 emit_bt (prof, logbuffer, &data);
1465 EXIT_LOG (logbuffer);
1466 process_requests (prof);
1470 clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
1473 LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 10 + 10 + 10);
1474 now = current_time ();
1475 ENTER_LOG (logbuffer, "clause");
1476 emit_byte (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
1477 emit_time (logbuffer, now);
1478 emit_value (logbuffer, clause_type);
1479 emit_value (logbuffer, clause_num);
1480 emit_method (prof, logbuffer, method);
1481 EXIT_LOG (logbuffer);
1483 process_requests (prof);
1487 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
1489 int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION)? TYPE_MONITOR_BT: 0;
1492 LogBuffer *logbuffer;
1495 logbuffer = ensure_logbuf (1 + 10 + 10 + MAX_FRAMES * (10 + 10 + 10));
1496 now = current_time ();
1497 ENTER_LOG (logbuffer, "monitor");
1498 emit_byte (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
1499 emit_time (logbuffer, now);
1500 emit_obj (logbuffer, object);
1502 emit_bt (profiler, logbuffer, &data);
1503 EXIT_LOG (logbuffer);
1504 process_requests (profiler);
1508 thread_start (MonoProfiler *prof, uintptr_t tid)
1510 //printf ("thread start %p\n", (void*)tid);
1513 LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10);
1514 uint64_t now = current_time ();
1516 ENTER_LOG (logbuffer, "thread-start");
1517 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1518 emit_time (logbuffer, now);
1519 emit_byte (logbuffer, TYPE_THREAD);
1520 emit_ptr (logbuffer, (void*) tid);
1521 emit_value (logbuffer, 0); /* flags */
1522 EXIT_LOG (logbuffer);
1524 if (logbuffer->next)
1525 safe_send (prof, logbuffer);
1527 process_requests (prof);
1531 thread_end (MonoProfiler *prof, uintptr_t tid)
1533 if (TLS_GET (LogBuffer, tlsbuffer)) {
1534 LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10);
1535 uint64_t now = current_time ();
1537 ENTER_LOG (logbuffer, "thread-end");
1538 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1539 emit_time (logbuffer, now);
1540 emit_byte (logbuffer, TYPE_THREAD);
1541 emit_ptr (logbuffer, (void*) tid);
1542 emit_value (logbuffer, 0); /* flags */
1543 EXIT_LOG (logbuffer);
1545 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), logbuffer);
1547 /* Don't process requests as the thread is detached from the runtime. */
1550 TLS_SET (tlsbuffer, NULL);
1551 TLS_SET (tlsmethodlist, NULL);
1555 domain_loaded (MonoProfiler *prof, MonoDomain *domain, int result)
1557 if (result != MONO_PROFILE_OK)
1560 LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10);
1561 uint64_t now = current_time ();
1563 ENTER_LOG (logbuffer, "domain-start");
1564 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1565 emit_time (logbuffer, now);
1566 emit_byte (logbuffer, TYPE_DOMAIN);
1567 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1568 emit_value (logbuffer, 0); /* flags */
1569 EXIT_LOG (logbuffer);
1571 if (logbuffer->next)
1572 safe_send (prof, logbuffer);
1574 process_requests (prof);
1578 domain_unloaded (MonoProfiler *prof, MonoDomain *domain)
1580 LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10);
1581 uint64_t now = current_time ();
1583 ENTER_LOG (logbuffer, "domain-end");
1584 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1585 emit_time (logbuffer, now);
1586 emit_byte (logbuffer, TYPE_DOMAIN);
1587 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1588 emit_value (logbuffer, 0); /* flags */
1589 EXIT_LOG (logbuffer);
1591 if (logbuffer->next)
1592 safe_send (prof, logbuffer);
1594 process_requests (prof);
1598 domain_name (MonoProfiler *prof, MonoDomain *domain, const char *name)
1600 int nlen = strlen (name) + 1;
1601 LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10 + nlen);
1602 uint64_t now = current_time ();
1604 ENTER_LOG (logbuffer, "domain-name");
1605 emit_byte (logbuffer, TYPE_METADATA);
1606 emit_time (logbuffer, now);
1607 emit_byte (logbuffer, TYPE_DOMAIN);
1608 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1609 emit_value (logbuffer, 0); /* flags */
1610 memcpy (logbuffer->data, name, nlen);
1611 logbuffer->data += nlen;
1612 EXIT_LOG (logbuffer);
1614 if (logbuffer->next)
1615 safe_send (prof, logbuffer);
1617 process_requests (prof);
1621 context_loaded (MonoProfiler *prof, MonoAppContext *context)
1623 LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10 + 10);
1624 uint64_t now = current_time ();
1626 ENTER_LOG (logbuffer, "context-start");
1627 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1628 emit_time (logbuffer, now);
1629 emit_byte (logbuffer, TYPE_CONTEXT);
1630 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
1631 emit_value (logbuffer, 0); /* flags */
1632 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
1633 EXIT_LOG (logbuffer);
1635 if (logbuffer->next)
1636 safe_send (prof, logbuffer);
1638 process_requests (prof);
1642 context_unloaded (MonoProfiler *prof, MonoAppContext *context)
1644 LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10 + 10);
1645 uint64_t now = current_time ();
1647 ENTER_LOG (logbuffer, "context-end");
1648 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1649 emit_time (logbuffer, now);
1650 emit_byte (logbuffer, TYPE_CONTEXT);
1651 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
1652 emit_value (logbuffer, 0); /* flags */
1653 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
1654 EXIT_LOG (logbuffer);
1656 if (logbuffer->next)
1657 safe_send (prof, logbuffer);
1659 process_requests (prof);
1663 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
1665 int len = strlen (name) + 1;
1667 LogBuffer *logbuffer;
1668 logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10 + len);
1669 now = current_time ();
1670 ENTER_LOG (logbuffer, "tname");
1671 emit_byte (logbuffer, TYPE_METADATA);
1672 emit_time (logbuffer, now);
1673 emit_byte (logbuffer, TYPE_THREAD);
1674 emit_ptr (logbuffer, (void*)tid);
1675 emit_value (logbuffer, 0); /* flags */
1676 memcpy (logbuffer->data, name, len);
1677 logbuffer->data += len;
1678 EXIT_LOG (logbuffer);
1680 if (logbuffer->next)
1681 safe_send (prof, logbuffer);
1683 process_requests (prof);
1695 AsyncFrameInfo *data;
1699 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
1701 AsyncFrameData *frame = data;
1702 if (frame->count < num_frames) {
1703 frame->data [frame->count].method = method;
1704 frame->data [frame->count].domain = domain;
1705 frame->data [frame->count].base_address = base_address;
1706 frame->data [frame->count].offset = offset;
1707 // printf ("In %d at %p (dom %p) (native: %p)\n", frame->count, method, domain, base_address);
1710 return frame->count == num_frames;
1714 (type | frame count), tid, time, ip, [method, domain, base address, offset] * frames
1716 #define SAMPLE_EVENT_SIZE_IN_SLOTS(FRAMES) (4 + (FRAMES) * 4)
1719 mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
1722 AsyncFrameInfo frames [num_frames];
1723 AsyncFrameData bt_data = { 0, &frames [0]};
1725 uintptr_t *data, *new_data, *old_data;
1731 now = current_time ();
1733 mono_stack_walk_async_safe (&async_walk_stack, context, &bt_data);
1735 elapsed = (now - profiler->startup_time) / 10000;
1739 snprintf (buf, sizeof (buf), "hit at %p in thread %p after %llu ms\n", ip, (void*)thread_id (), (unsigned long long int)elapsed/100);
1741 ign_res (write (2, buf, len));
1743 sbuf = profiler->stat_buffers;
1746 /* flush the buffer at 1 second intervals */
1747 if (sbuf->data > sbuf->buf && (elapsed - sbuf->buf [2]) > 100000) {
1750 /* overflow: 400 slots is a big enough number to reduce the chance of losing this event if many
1751 * threads hit this same spot at the same time
1753 if (timedout || (sbuf->data + 400 >= sbuf->data_end)) {
1754 StatBuffer *oldsb, *foundsb;
1755 sbuf = create_stat_buffer ();
1757 oldsb = profiler->stat_buffers;
1759 foundsb = InterlockedCompareExchangePointer ((void * volatile*)&profiler->stat_buffers, sbuf, oldsb);
1760 } while (foundsb != oldsb);
1762 ign_res (write (2, "overflow\n", 9));
1763 /* notify the helper thread */
1764 if (sbuf->next->next) {
1766 ign_res (write (profiler->pipes [1], &c, 1));
1768 ign_res (write (2, "notify\n", 7));
1772 old_data = sbuf->data;
1773 new_data = old_data + SAMPLE_EVENT_SIZE_IN_SLOTS (bt_data.count);
1774 data = InterlockedCompareExchangePointer ((void * volatile*)&sbuf->data, new_data, old_data);
1775 } while (data != old_data);
1776 if (old_data >= sbuf->data_end)
1777 return; /* lost event */
1778 old_data [0] = 1 | (sample_type << 16) | (bt_data.count << 8);
1779 old_data [1] = thread_id ();
1780 old_data [2] = elapsed;
1781 old_data [3] = (uintptr_t)ip;
1782 for (i = 0; i < bt_data.count; ++i) {
1783 old_data [4 + 4 * i + 0] = (uintptr_t)frames [i].method;
1784 old_data [4 + 4 * i + 1] = (uintptr_t)frames [i].domain;
1785 old_data [4 + 4 * i + 2] = (uintptr_t)frames [i].base_address;
1786 old_data [4 + 4 * i + 3] = (uintptr_t)frames [i].offset;
1790 static uintptr_t *code_pages = 0;
1791 static int num_code_pages = 0;
1792 static int size_code_pages = 0;
1793 #define CPAGE_SHIFT (9)
1794 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
1795 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
1796 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
1799 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
1802 uintptr_t start_pos;
1803 start_pos = (page >> CPAGE_SHIFT) % hsize;
1806 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
1808 } else if (!hash [i]) {
1815 } while (i != start_pos);
1816 /* should not happen */
1817 printf ("failed code page store\n");
1822 add_code_pointer (uintptr_t ip)
1825 if (num_code_pages * 2 >= size_code_pages) {
1827 uintptr_t old_size = size_code_pages;
1828 size_code_pages *= 2;
1829 if (size_code_pages == 0)
1830 size_code_pages = 16;
1831 n = calloc (sizeof (uintptr_t) * size_code_pages, 1);
1832 for (i = 0; i < old_size; ++i) {
1834 add_code_page (n, size_code_pages, code_pages [i]);
1840 num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
1843 /* ELF code crashes on some systems. */
1844 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
1847 dump_ubin (const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
1850 LogBuffer *logbuffer;
1852 len = strlen (filename) + 1;
1853 now = current_time ();
1854 logbuffer = ensure_logbuf (1 + 10 + 10 + 10 + 10 + len);
1855 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
1856 emit_time (logbuffer, now);
1857 emit_svalue (logbuffer, load_addr);
1858 emit_uvalue (logbuffer, offset);
1859 emit_uvalue (logbuffer, size);
1860 memcpy (logbuffer->data, filename, len);
1861 logbuffer->data += len;
1866 dump_usym (const char *name, uintptr_t value, uintptr_t size)
1868 LogBuffer *logbuffer;
1870 len = strlen (name) + 1;
1871 logbuffer = ensure_logbuf (1 + 10 + 10 + len);
1872 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
1873 emit_ptr (logbuffer, (void*)value);
1874 emit_value (logbuffer, size);
1875 memcpy (logbuffer->data, name, len);
1876 logbuffer->data += len;
1879 /* ELF code crashes on some systems. */
1880 //#if defined(ELFMAG0)
1883 #if SIZEOF_VOID_P == 4
1884 #define ELF_WSIZE 32
1886 #define ELF_WSIZE 64
1889 #define ElfW(type) _ElfW (Elf, ELF_WSIZE, type)
1890 #define _ElfW(e,w,t) _ElfW_1 (e, w, _##t)
1891 #define _ElfW_1(e,w,t) e##w##t
1895 dump_elf_symbols (ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
1898 for (i = 0; i < num_symbols; ++i) {
1900 sym = strtab + symbols [i].st_name;
1901 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
1903 //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
1904 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
1909 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
1916 ElfW(Shdr) *sheader;
1917 ElfW(Shdr) *shstrtabh;
1918 ElfW(Shdr) *symtabh = NULL;
1919 ElfW(Shdr) *strtabh = NULL;
1920 ElfW(Sym) *symbols = NULL;
1924 fd = open (filename, O_RDONLY);
1927 if (fstat (fd, &statb) != 0) {
1931 file_size = statb.st_size;
1932 data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
1934 if (data == MAP_FAILED)
1937 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
1938 header->e_ident [EI_MAG1] != ELFMAG1 ||
1939 header->e_ident [EI_MAG2] != ELFMAG2 ||
1940 header->e_ident [EI_MAG3] != ELFMAG3 ) {
1941 munmap (data, file_size);
1944 sheader = (void*)((char*)data + header->e_shoff);
1945 shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
1946 strtab = (const char*)data + shstrtabh->sh_offset;
1947 for (i = 0; i < header->e_shnum; ++i) {
1948 //printf ("section header: %d\n", sheader->sh_type);
1949 if (sheader->sh_type == SHT_SYMTAB) {
1951 strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
1952 /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
1955 sheader = (void*)((char*)sheader + header->e_shentsize);
1957 if (!symtabh || !strtabh) {
1958 munmap (data, file_size);
1961 strtab = (const char*)data + strtabh->sh_offset;
1962 num_symbols = symtabh->sh_size / symtabh->sh_entsize;
1963 symbols = (void*)((char*)data + symtabh->sh_offset);
1964 dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
1965 munmap (data, file_size);
1970 /* ELF code crashes on some systems. */
1971 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
1974 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
1976 MonoProfiler *prof = data;
1978 const char *filename;
1980 char *a = (void*)info->dlpi_addr;
1982 ElfW(Dyn) *dyn = NULL;
1983 ElfW(Sym) *symtab = NULL;
1984 ElfW(Word) *hash_table = NULL;
1985 ElfW(Ehdr) *header = NULL;
1986 const char* strtab = NULL;
1987 for (obj = prof->binary_objects; obj; obj = obj->next) {
1991 filename = info->dlpi_name;
1994 if (!info->dlpi_addr && !filename [0]) {
1995 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
2001 obj = calloc (sizeof (BinaryObject), 1);
2002 obj->addr = (void*)info->dlpi_addr;
2003 obj->name = pstrdup (filename);
2004 obj->next = prof->binary_objects;
2005 prof->binary_objects = obj;
2006 //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
2008 for (i = 0; i < info->dlpi_phnum; ++i) {
2009 //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);
2010 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
2011 header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2012 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2013 header->e_ident [EI_MAG1] != ELFMAG1 ||
2014 header->e_ident [EI_MAG2] != ELFMAG2 ||
2015 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2018 dump_ubin (filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
2019 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
2020 dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2023 if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
2025 if (!info->dlpi_name || !info->dlpi_name[0])
2029 for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
2030 if (dyn [i].d_tag == DT_SYMTAB) {
2031 if (symtab && do_debug)
2032 printf ("multiple symtabs: %d\n", i);
2033 symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
2034 } else if (dyn [i].d_tag == DT_HASH) {
2035 hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
2036 } else if (dyn [i].d_tag == DT_STRTAB) {
2037 strtab = (const char*)(a + dyn [i].d_un.d_ptr);
2042 num_sym = hash_table [1];
2043 dump_elf_symbols (symtab, num_sym, strtab, (void*)info->dlpi_addr);
2048 load_binaries (MonoProfiler *prof)
2050 dl_iterate_phdr (elf_dl_callback, prof);
2055 load_binaries (MonoProfiler *prof)
2062 symbol_for (uintptr_t code)
2065 void *ip = (void*)code;
2067 if (dladdr (ip, &di)) {
2069 return di.dli_sname;
2072 names = backtrace_symbols (&ip, 1);
2074 const char* p = names [0];
2085 dump_unmanaged_coderefs (MonoProfiler *prof)
2088 const char* last_symbol;
2089 uintptr_t addr, page_end;
2091 if (load_binaries (prof))
2093 for (i = 0; i < size_code_pages; ++i) {
2095 if (!code_pages [i] || code_pages [i] & 1)
2098 addr = CPAGE_ADDR (code_pages [i]);
2099 page_end = addr + CPAGE_SIZE;
2100 code_pages [i] |= 1;
2101 /* we dump the symbols for the whole page */
2102 for (; addr < page_end; addr += 16) {
2103 sym = symbol_for (addr);
2104 if (sym && sym == last_symbol)
2109 dump_usym (sym, addr, 0); /* let's not guess the size */
2110 //printf ("found symbol at %p: %s\n", (void*)addr, sym);
2116 compare_sample_events (gconstpointer a, gconstpointer b)
2118 uintptr_t tid1 = (*(uintptr_t **) a) [1];
2119 uintptr_t tid2 = (*(uintptr_t **) b) [1];
2121 return tid1 > tid2 ? 1 :
2127 dump_sample_hits (MonoProfiler *prof, StatBuffer *sbuf)
2129 LogBuffer *logbuffer;
2133 dump_sample_hits (prof, sbuf->next);
2134 free_buffer (sbuf->next, sbuf->next->size);
2138 g_ptr_array_set_size (prof->sorted_sample_events, 0);
2140 for (uintptr_t *sample = sbuf->buf; sample < sbuf->data;) {
2141 int count = sample [0] & 0xff;
2142 int mbt_count = (sample [0] & 0xff00) >> 8;
2144 if (sample + SAMPLE_EVENT_SIZE_IN_SLOTS (mbt_count) > sbuf->data)
2147 g_ptr_array_add (prof->sorted_sample_events, sample);
2149 sample += count + 3 + 4 * mbt_count;
2152 g_ptr_array_sort (prof->sorted_sample_events, compare_sample_events);
2154 for (guint sidx = 0; sidx < prof->sorted_sample_events->len; sidx++) {
2155 uintptr_t *sample = g_ptr_array_index (prof->sorted_sample_events, sidx);
2156 int count = sample [0] & 0xff;
2157 int mbt_count = (sample [0] & 0xff00) >> 8;
2158 int type = sample [0] >> 16;
2159 uintptr_t *managed_sample_base = sample + count + 3;
2160 uintptr_t thread_id = sample [1];
2162 for (int i = 0; i < mbt_count; ++i) {
2163 MonoMethod *method = (MonoMethod*)managed_sample_base [i * 4 + 0];
2164 MonoDomain *domain = (MonoDomain*)managed_sample_base [i * 4 + 1];
2165 void *address = (void*)managed_sample_base [i * 4 + 2];
2168 MonoJitInfo *ji = mono_jit_info_table_find (domain, address);
2171 managed_sample_base [i * 4 + 0] = (uintptr_t)mono_jit_info_get_method (ji);
2175 logbuffer = ensure_logbuf (1 + 10 + 10 + 10 + 10 + 10 + 10 + mbt_count * (10 + 10 + 10));
2176 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
2177 emit_value (logbuffer, type);
2178 emit_uvalue (logbuffer, prof->startup_time + (uint64_t)sample [2] * (uint64_t)10000);
2179 emit_ptr (logbuffer, (void *) thread_id);
2180 emit_value (logbuffer, count);
2181 for (int i = 0; i < count; ++i) {
2182 emit_ptr (logbuffer, (void*)sample [i + 3]);
2183 add_code_pointer (sample [i + 3]);
2186 sample += count + 3;
2187 /* new in data version 6 */
2188 emit_uvalue (logbuffer, mbt_count);
2189 for (int i = 0; i < mbt_count; ++i) {
2190 MonoMethod *method = (MonoMethod *) sample [i * 4 + 0];
2191 uintptr_t native_offset = sample [i * 4 + 3];
2193 emit_method (prof, logbuffer, method);
2194 emit_svalue (logbuffer, 0); /* il offset will always be 0 from now on */
2195 emit_svalue (logbuffer, native_offset);
2199 dump_unmanaged_coderefs (prof);
2205 mono_cpu_count (void)
2208 #ifdef PLATFORM_ANDROID
2209 /* Android tries really hard to save power by powering off CPUs on SMP phones which
2210 * means the normal way to query cpu count returns a wrong value with userspace API.
2211 * Instead we use /sys entries to query the actual hardware CPU count.
2213 char buffer[8] = {'\0'};
2214 int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
2215 /* Format of the /sys entry is a cpulist of indexes which in the case
2216 * of present is always of the form "0-(n-1)" when there is more than
2217 * 1 core, n being the number of CPU cores in the system. Otherwise
2218 * the value is simply 0
2220 if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
2221 count = strtol (((char*)buffer) + 2, NULL, 10);
2227 #ifdef _SC_NPROCESSORS_ONLN
2228 count = sysconf (_SC_NPROCESSORS_ONLN);
2235 size_t len = sizeof (int);
2238 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
2245 GetSystemInfo (&info);
2246 return info.dwNumberOfProcessors;
2255 unsigned int prev_pos;
2257 struct perf_event_mmap_page *page_desc;
2260 static PerfData *perf_data = NULL;
2261 static int num_perf;
2262 #define PERF_PAGES_SHIFT 4
2263 static int num_pages = 1 << PERF_PAGES_SHIFT;
2264 static unsigned int mmap_mask;
2267 struct perf_event_header h;
2277 perf_event_syscall (struct perf_event_attr *attr, pid_t pid, int cpu, int group_fd, unsigned long flags)
2279 attr->size = PERF_ATTR_SIZE_VER0;
2280 //printf ("perf attr size: %d\n", attr->size);
2281 #if defined(__x86_64__)
2282 return syscall(/*__NR_perf_event_open*/ 298, attr, pid, cpu, group_fd, flags);
2283 #elif defined(__i386__)
2284 return syscall(/*__NR_perf_event_open*/ 336, attr, pid, cpu, group_fd, flags);
2285 #elif defined(__arm__) || defined (__aarch64__)
2286 return syscall(/*__NR_perf_event_open*/ 364, attr, pid, cpu, group_fd, flags);
2293 setup_perf_map (PerfData *perf)
2295 perf->mmap_base = mmap (NULL, (num_pages + 1) * getpagesize (), PROT_READ|PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
2296 if (perf->mmap_base == MAP_FAILED) {
2298 printf ("failed mmap\n");
2301 perf->page_desc = perf->mmap_base;
2303 printf ("mmap version: %d\n", perf->page_desc->version);
2308 dump_perf_hits (MonoProfiler *prof, void *buf, int size)
2310 LogBuffer *logbuffer;
2311 void *end = (char*)buf + size;
2313 int pid = getpid ();
2319 if (pid != s->pid) {
2321 printf ("event for different pid: %d\n", s->pid);
2322 buf = (char*)buf + s->h.size;
2325 /*ip = (void*)s->ip;
2326 printf ("sample: %d, size: %d, ip: %p (%s), timestamp: %llu, nframes: %llu\n",
2327 s->h.type, s->h.size, ip, symbol_for (ip), s->timestamp, s->nframes);*/
2328 logbuffer = ensure_logbuf (1 + 10 + 10 + 10 + 10 + 10);
2329 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
2330 emit_value (logbuffer, sample_type);
2331 emit_uvalue (logbuffer, s->timestamp - prof->startup_time);
2333 * No useful thread ID to write here, since throughout the
2334 * profiler we use pthread_self () but the ID we get from
2335 * perf is the kernel's thread ID.
2337 emit_ptr (logbuffer, 0);
2338 emit_value (logbuffer, 1); /* count */
2339 emit_ptr (logbuffer, (void*)(uintptr_t)s->ip);
2340 /* no support here yet for the managed backtrace */
2341 emit_uvalue (logbuffer, 0);
2342 add_code_pointer (s->ip);
2343 buf = (char*)buf + s->h.size;
2347 printf ("dumped %d samples\n", samples);
2348 dump_unmanaged_coderefs (prof);
2351 /* read events from the ring buffer */
2353 read_perf_mmap (MonoProfiler* prof, int cpu)
2355 PerfData *perf = perf_data + cpu;
2357 unsigned char *data = (unsigned char*)perf->mmap_base + getpagesize ();
2358 unsigned int head = perf->page_desc->data_head;
2362 mono_memory_read_barrier ();
2364 old = perf->prev_pos;
2368 printf ("lost mmap events: old: %d, head: %d\n", old, head);
2372 if ((old & mmap_mask) + size != (head & mmap_mask)) {
2373 buf = data + (old & mmap_mask);
2374 size = mmap_mask + 1 - (old & mmap_mask);
2376 /* size bytes at buf */
2378 printf ("found1 bytes of events: %d\n", size);
2379 dump_perf_hits (prof, buf, size);
2381 buf = data + (old & mmap_mask);
2383 /* size bytes at buf */
2385 printf ("found bytes of events: %d\n", size);
2386 dump_perf_hits (prof, buf, size);
2388 perf->prev_pos = old;
2389 perf->page_desc->data_tail = old;
2394 setup_perf_event_for_cpu (PerfData *perf, int cpu)
2396 struct perf_event_attr attr;
2397 memset (&attr, 0, sizeof (attr));
2398 attr.type = PERF_TYPE_HARDWARE;
2399 switch (sample_type) {
2400 case SAMPLE_CYCLES: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2401 case SAMPLE_INSTRUCTIONS: attr.config = PERF_COUNT_HW_INSTRUCTIONS; break;
2402 case SAMPLE_CACHE_MISSES: attr.config = PERF_COUNT_HW_CACHE_MISSES; break;
2403 case SAMPLE_CACHE_REFS: attr.config = PERF_COUNT_HW_CACHE_REFERENCES; break;
2404 case SAMPLE_BRANCHES: attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS; break;
2405 case SAMPLE_BRANCH_MISSES: attr.config = PERF_COUNT_HW_BRANCH_MISSES; break;
2406 default: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2408 attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD | PERF_SAMPLE_TIME;
2409 // attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
2410 attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING | PERF_FORMAT_ID;
2413 attr.sample_freq = sample_freq;
2415 perf->perf_fd = perf_event_syscall (&attr, getpid (), cpu, -1, 0);
2417 printf ("perf fd: %d, freq: %d, event: %llu\n", perf->perf_fd, sample_freq, attr.config);
2418 if (perf->perf_fd < 0) {
2419 if (perf->perf_fd == -EPERM) {
2420 fprintf (stderr, "Perf syscall denied, do \"echo 1 > /proc/sys/kernel/perf_event_paranoid\" as root to enable.\n");
2423 perror ("open perf event");
2427 if (!setup_perf_map (perf)) {
2428 close (perf->perf_fd);
2436 setup_perf_event (void)
2439 mmap_mask = num_pages * getpagesize () - 1;
2440 num_perf = mono_cpu_count ();
2441 perf_data = calloc (num_perf, sizeof (PerfData));
2442 for (i = 0; i < num_perf; ++i) {
2443 count += setup_perf_event_for_cpu (perf_data + i, i);
2452 #endif /* USE_PERF_EVENTS */
2454 #ifndef DISABLE_HELPER_THREAD
2456 typedef struct MonoCounterAgent {
2457 MonoCounter *counter;
2458 // MonoCounterAgent specific data :
2463 struct MonoCounterAgent *next;
2466 static MonoCounterAgent* counters;
2467 static gboolean counters_initialized = FALSE;
2468 static int counters_index = 1;
2469 static mono_mutex_t counters_mutex;
2472 counters_add_agent (MonoCounter *counter)
2474 MonoCounterAgent *agent, *item;
2476 if (!counters_initialized)
2479 mono_mutex_lock (&counters_mutex);
2481 for (agent = counters; agent; agent = agent->next) {
2482 if (agent->counter == counter) {
2483 agent->value_size = 0;
2485 free (agent->value);
2486 agent->value = NULL;
2488 mono_mutex_unlock (&counters_mutex);
2493 agent = malloc (sizeof (MonoCounterAgent));
2494 agent->counter = counter;
2495 agent->value = NULL;
2496 agent->value_size = 0;
2497 agent->index = counters_index++;
2510 mono_mutex_unlock (&counters_mutex);
2514 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
2516 counters_add_agent (counter);
2521 counters_init (MonoProfiler *profiler)
2523 assert (!counters_initialized);
2525 mono_mutex_init (&counters_mutex);
2527 counters_initialized = TRUE;
2529 mono_counters_on_register (&counters_add_agent);
2530 mono_counters_foreach (counters_init_foreach_callback, NULL);
2534 counters_emit (MonoProfiler *profiler)
2536 MonoCounterAgent *agent;
2537 LogBuffer *logbuffer;
2538 int size = 1 + 10, len = 0;
2540 if (!counters_initialized)
2543 mono_mutex_lock (&counters_mutex);
2545 for (agent = counters; agent; agent = agent->next) {
2549 size += 10 + strlen (mono_counter_get_name (agent->counter)) + 1 + 10 + 10 + 10 + 10;
2554 mono_mutex_unlock (&counters_mutex);
2558 logbuffer = ensure_logbuf (size);
2560 ENTER_LOG (logbuffer, "counters");
2561 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2562 emit_value (logbuffer, len);
2563 for (agent = counters; agent; agent = agent->next) {
2569 name = mono_counter_get_name (agent->counter);
2570 emit_value (logbuffer, mono_counter_get_section (agent->counter));
2571 emit_string (logbuffer, name, strlen (name) + 1);
2572 emit_value (logbuffer, mono_counter_get_type (agent->counter));
2573 emit_value (logbuffer, mono_counter_get_unit (agent->counter));
2574 emit_value (logbuffer, mono_counter_get_variance (agent->counter));
2575 emit_value (logbuffer, agent->index);
2579 EXIT_LOG (logbuffer);
2581 safe_send (profiler, logbuffer);
2583 mono_mutex_unlock (&counters_mutex);
2587 counters_sample (MonoProfiler *profiler, uint64_t timestamp)
2589 MonoCounterAgent *agent;
2590 MonoCounter *counter;
2591 LogBuffer *logbuffer;
2597 if (!counters_initialized)
2600 counters_emit (profiler);
2603 buffer = calloc (1, buffer_size);
2605 mono_mutex_lock (&counters_mutex);
2608 for (agent = counters; agent; agent = agent->next)
2609 size += 10 + 10 + mono_counter_get_size (agent->counter);
2612 logbuffer = ensure_logbuf (size);
2614 ENTER_LOG (logbuffer, "counters");
2615 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
2616 emit_uvalue (logbuffer, timestamp);
2617 for (agent = counters; agent; agent = agent->next) {
2620 counter = agent->counter;
2622 size = mono_counter_get_size (counter);
2624 continue; // FIXME error
2625 } else if (size > buffer_size) {
2627 buffer = realloc (buffer, buffer_size);
2630 memset (buffer, 0, buffer_size);
2632 if (mono_counters_sample (counter, buffer, size) < 0)
2633 continue; // FIXME error
2635 type = mono_counter_get_type (counter);
2637 if (!agent->value) {
2638 agent->value = calloc (1, size);
2639 agent->value_size = size;
2641 if (type == MONO_COUNTER_STRING) {
2642 if (strcmp (agent->value, buffer) == 0)
2645 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
2650 emit_uvalue (logbuffer, agent->index);
2651 emit_uvalue (logbuffer, type);
2653 case MONO_COUNTER_INT:
2654 #if SIZEOF_VOID_P == 4
2655 case MONO_COUNTER_WORD:
2657 emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
2659 case MONO_COUNTER_UINT:
2660 emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
2662 case MONO_COUNTER_TIME_INTERVAL:
2663 case MONO_COUNTER_LONG:
2664 #if SIZEOF_VOID_P == 8
2665 case MONO_COUNTER_WORD:
2667 emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
2669 case MONO_COUNTER_ULONG:
2670 emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
2672 case MONO_COUNTER_DOUBLE:
2673 emit_double (logbuffer, *(double*)buffer);
2675 case MONO_COUNTER_STRING:
2677 emit_byte (logbuffer, 0);
2679 emit_byte (logbuffer, 1);
2680 emit_string (logbuffer, (char*)buffer, size);
2687 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
2688 agent->value = realloc (agent->value, size);
2689 agent->value_size = size;
2693 memcpy (agent->value, buffer, size);
2697 emit_value (logbuffer, 0);
2698 EXIT_LOG (logbuffer);
2700 safe_send (profiler, logbuffer);
2702 mono_mutex_unlock (&counters_mutex);
2705 typedef struct _PerfCounterAgent PerfCounterAgent;
2706 struct _PerfCounterAgent {
2707 PerfCounterAgent *next;
2709 char *category_name;
2718 static PerfCounterAgent *perfcounters = NULL;
2721 perfcounters_emit (MonoProfiler *profiler)
2723 PerfCounterAgent *pcagent;
2724 LogBuffer *logbuffer;
2725 int size = 1 + 10, len = 0;
2727 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2728 if (pcagent->emitted)
2731 size += 10 + strlen (pcagent->category_name) + 1 + strlen (pcagent->name) + 1 + 10 + 10 + 10 + 10;
2738 logbuffer = ensure_logbuf (size);
2740 ENTER_LOG (logbuffer, "perfcounters");
2741 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2742 emit_value (logbuffer, len);
2743 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2744 if (pcagent->emitted)
2747 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
2748 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
2749 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
2750 emit_value (logbuffer, MONO_COUNTER_LONG);
2751 emit_value (logbuffer, MONO_COUNTER_RAW);
2752 emit_value (logbuffer, MONO_COUNTER_VARIABLE);
2753 emit_value (logbuffer, pcagent->index);
2755 pcagent->emitted = 1;
2757 EXIT_LOG (logbuffer);
2759 safe_send (profiler, logbuffer);
2763 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
2765 PerfCounterAgent *pcagent;
2767 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2768 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
2770 if (pcagent->value == value)
2773 pcagent->value = value;
2774 pcagent->updated = 1;
2775 pcagent->deleted = 0;
2779 pcagent = g_new0 (PerfCounterAgent, 1);
2780 pcagent->next = perfcounters;
2781 pcagent->index = counters_index++;
2782 pcagent->category_name = g_strdup (category_name);
2783 pcagent->name = g_strdup (name);
2784 pcagent->type = (int) type;
2785 pcagent->value = value;
2786 pcagent->emitted = 0;
2787 pcagent->updated = 1;
2788 pcagent->deleted = 0;
2790 perfcounters = pcagent;
2796 perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp)
2798 PerfCounterAgent *pcagent;
2799 LogBuffer *logbuffer;
2802 if (!counters_initialized)
2805 mono_mutex_lock (&counters_mutex);
2807 /* mark all perfcounters as deleted, foreach will unmark them as necessary */
2808 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
2809 pcagent->deleted = 1;
2811 mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
2813 perfcounters_emit (profiler);
2817 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2818 if (pcagent->deleted || !pcagent->updated)
2820 size += 10 + 10 + 10;
2824 logbuffer = ensure_logbuf (size);
2826 ENTER_LOG (logbuffer, "perfcounters");
2827 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
2828 emit_uvalue (logbuffer, timestamp);
2829 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2830 if (pcagent->deleted || !pcagent->updated)
2832 emit_uvalue (logbuffer, pcagent->index);
2833 emit_uvalue (logbuffer, MONO_COUNTER_LONG);
2834 emit_svalue (logbuffer, pcagent->value);
2836 pcagent->updated = 0;
2839 emit_value (logbuffer, 0);
2840 EXIT_LOG (logbuffer);
2842 safe_send (profiler, logbuffer);
2844 mono_mutex_unlock (&counters_mutex);
2848 counters_and_perfcounters_sample (MonoProfiler *prof)
2850 static uint64_t start = -1;
2854 start = current_time ();
2856 now = current_time ();
2857 counters_sample (prof, (now - start) / 1000/ 1000);
2858 perfcounters_sample (prof, (now - start) / 1000/ 1000);
2861 #define COVERAGE_DEBUG(x) if (debug_coverage) {x}
2862 static MonoConcurrentHashTable *coverage_methods = NULL;
2863 static mono_mutex_t coverage_methods_mutex;
2864 static MonoConcurrentHashTable *coverage_assemblies = NULL;
2865 static mono_mutex_t coverage_assemblies_mutex;
2866 static MonoConcurrentHashTable *coverage_classes = NULL;
2867 static mono_mutex_t coverage_classes_mutex;
2868 static MonoConcurrentHashTable *filtered_classes = NULL;
2869 static mono_mutex_t filtered_classes_mutex;
2870 static MonoConcurrentHashTable *entered_methods = NULL;
2871 static mono_mutex_t entered_methods_mutex;
2872 static MonoConcurrentHashTable *image_to_methods = NULL;
2873 static mono_mutex_t image_to_methods_mutex;
2874 static MonoConcurrentHashTable *suppressed_assemblies = NULL;
2875 static mono_mutex_t suppressed_assemblies_mutex;
2876 static gboolean coverage_initialized = FALSE;
2878 static GPtrArray *coverage_data = NULL;
2879 static int previous_offset = 0;
2881 typedef struct _MethodNode MethodNode;
2882 struct _MethodNode {
2883 MonoLockFreeQueueNode node;
2887 typedef struct _CoverageEntry CoverageEntry;
2888 struct _CoverageEntry {
2897 free_coverage_entry (gpointer data, gpointer userdata)
2899 CoverageEntry *entry = (CoverageEntry *)data;
2900 g_free (entry->filename);
2905 obtain_coverage_for_method (MonoProfiler *prof, const MonoProfileCoverageEntry *entry)
2907 int offset = entry->iloffset - previous_offset;
2908 CoverageEntry *e = g_new (CoverageEntry, 1);
2910 previous_offset = entry->iloffset;
2913 e->counter = entry->counter;
2914 e->filename = g_strdup(entry->filename ? entry->filename : "");
2915 e->line = entry->line;
2916 e->column = entry->col;
2918 g_ptr_array_add (coverage_data, e);
2922 parse_generic_type_names(char *name)
2924 char *new_name, *ret;
2925 int within_generic_declaration = 0, generic_members = 1;
2927 if (name == NULL || *name == '\0')
2928 return g_strdup ("");
2930 if (!(ret = new_name = calloc (strlen (name) * 4 + 1, sizeof (char))))
2936 within_generic_declaration = 1;
2940 within_generic_declaration = 0;
2942 if (*(name - 1) != '<') {
2944 *new_name++ = '0' + generic_members;
2946 memcpy (new_name, "<>", 8);
2950 generic_members = 0;
2958 if (!within_generic_declaration)
2959 *new_name++ = *name;
2968 static int method_id;
2970 build_method_buffer (gpointer key, gpointer value, gpointer userdata)
2972 MonoMethod *method = (MonoMethod *)value;
2973 MonoProfiler *prof = (MonoProfiler *)userdata;
2977 const char *image_name, *method_name, *sig, *first_filename;
2978 LogBuffer *logbuffer;
2982 previous_offset = 0;
2983 coverage_data = g_ptr_array_new ();
2985 mono_profiler_coverage_get (prof, method, obtain_coverage_for_method);
2987 klass = mono_method_get_class (method);
2988 image = mono_class_get_image (klass);
2989 image_name = mono_image_get_name (image);
2991 sig = mono_signature_get_desc (mono_method_signature (method), TRUE);
2992 class_name = parse_generic_type_names (mono_type_get_name (mono_class_get_type (klass)));
2993 method_name = mono_method_get_name (method);
2995 if (coverage_data->len != 0) {
2996 CoverageEntry *entry = coverage_data->pdata[0];
2997 first_filename = entry->filename ? entry->filename : "";
2999 first_filename = "";
3001 image_name = image_name ? image_name : "";
3002 sig = sig ? sig : "";
3003 method_name = method_name ? method_name : "";
3007 size += strlen (image_name) + 1;
3008 size += strlen (class_name) + 1;
3009 size += strlen (method_name) + 1;
3010 size += strlen (sig) + 1;
3011 size += strlen (first_filename) + 1;
3013 size += 10 + 10 + 10; /* token + method_id + n_entries*/
3015 logbuffer = ensure_logbuf (size);
3016 ENTER_LOG (logbuffer, "coverage-methods");
3018 emit_byte (logbuffer, TYPE_COVERAGE_METHOD | TYPE_COVERAGE);
3019 emit_string (logbuffer, image_name, strlen (image_name) + 1);
3020 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3021 emit_string (logbuffer, method_name, strlen (method_name) + 1);
3022 emit_string (logbuffer, sig, strlen (sig) + 1);
3023 emit_string (logbuffer, first_filename, strlen (first_filename) + 1);
3025 emit_uvalue (logbuffer, mono_method_get_token (method));
3026 emit_uvalue (logbuffer, method_id);
3027 emit_value (logbuffer, coverage_data->len);
3029 EXIT_LOG (logbuffer);
3030 safe_send (prof, logbuffer);
3032 for (i = 0; i < coverage_data->len; i++) {
3033 CoverageEntry *entry = coverage_data->pdata[i];
3035 logbuffer = ensure_logbuf (1 + 10 + 10 + 10 + 10 + 10);
3036 ENTER_LOG (logbuffer, "coverage-statement");
3038 emit_byte (logbuffer, TYPE_COVERAGE_STATEMENT | TYPE_COVERAGE);
3039 emit_uvalue (logbuffer, method_id);
3040 emit_uvalue (logbuffer, entry->offset);
3041 emit_uvalue (logbuffer, entry->counter);
3042 emit_uvalue (logbuffer, entry->line);
3043 emit_uvalue (logbuffer, entry->column);
3045 EXIT_LOG (logbuffer);
3046 safe_send (prof, logbuffer);
3051 g_free (class_name);
3053 g_ptr_array_foreach (coverage_data, free_coverage_entry, NULL);
3054 g_ptr_array_free (coverage_data, TRUE);
3055 coverage_data = NULL;
3058 /* This empties the queue */
3060 count_queue (MonoLockFreeQueue *queue)
3062 MonoLockFreeQueueNode *node;
3065 while ((node = mono_lock_free_queue_dequeue (queue))) {
3067 mono_lock_free_queue_node_free (node);
3074 build_class_buffer (gpointer key, gpointer value, gpointer userdata)
3076 MonoClass *klass = (MonoClass *)key;
3077 MonoLockFreeQueue *class_methods = (MonoLockFreeQueue *)value;
3078 MonoProfiler *prof = (MonoProfiler *)userdata;
3081 const char *assembly_name;
3082 int number_of_methods, partially_covered;
3083 guint fully_covered;
3084 LogBuffer *logbuffer;
3087 image = mono_class_get_image (klass);
3088 assembly_name = mono_image_get_name (image);
3089 class_name = mono_type_get_name (mono_class_get_type (klass));
3091 assembly_name = assembly_name ? assembly_name : "";
3092 number_of_methods = mono_class_num_methods (klass);
3093 fully_covered = count_queue (class_methods);
3094 /* We don't handle partial covered yet */
3095 partially_covered = 0;
3099 size += strlen (assembly_name) + 1;
3100 size += strlen (class_name) + 1;
3101 size += 10 + 10 + 10; /* number_of_methods, fully_covered, partially_covered */
3103 logbuffer = ensure_logbuf (size);
3105 ENTER_LOG (logbuffer, "coverage-class");
3106 emit_byte (logbuffer, TYPE_COVERAGE_CLASS | TYPE_COVERAGE);
3107 emit_string (logbuffer, assembly_name, strlen (assembly_name) + 1);
3108 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3109 emit_uvalue (logbuffer, number_of_methods);
3110 emit_uvalue (logbuffer, fully_covered);
3111 emit_uvalue (logbuffer, partially_covered);
3112 EXIT_LOG (logbuffer);
3114 safe_send (prof, logbuffer);
3116 g_free (class_name);
3120 get_coverage_for_image (MonoImage *image, int *number_of_methods, guint *fully_covered, int *partially_covered)
3122 MonoLockFreeQueue *image_methods = mono_conc_hashtable_lookup (image_to_methods, image);
3124 *number_of_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
3126 *fully_covered = count_queue (image_methods);
3130 // FIXME: We don't handle partially covered yet.
3131 *partially_covered = 0;
3135 build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
3137 MonoAssembly *assembly = (MonoAssembly *)value;
3138 MonoProfiler *prof = (MonoProfiler *)userdata;
3139 MonoImage *image = mono_assembly_get_image (assembly);
3140 LogBuffer *logbuffer;
3141 const char *name, *guid, *filename;
3143 int number_of_methods = 0, partially_covered = 0;
3144 guint fully_covered = 0;
3146 name = mono_image_get_name (image);
3147 guid = mono_image_get_guid (image);
3148 filename = mono_image_get_filename (image);
3150 name = name ? name : "";
3151 guid = guid ? guid : "";
3152 filename = filename ? filename : "";
3154 get_coverage_for_image (image, &number_of_methods, &fully_covered, &partially_covered);
3158 size += strlen (name) + 1;
3159 size += strlen (guid) + 1;
3160 size += strlen (filename) + 1;
3161 size += 10 + 10 + 10; /* number_of_methods, fully_covered, partially_covered */
3162 logbuffer = ensure_logbuf (size);
3164 ENTER_LOG (logbuffer, "coverage-assemblies");
3165 emit_byte (logbuffer, TYPE_COVERAGE_ASSEMBLY | TYPE_COVERAGE);
3166 emit_string (logbuffer, name, strlen (name) + 1);
3167 emit_string (logbuffer, guid, strlen (guid) + 1);
3168 emit_string (logbuffer, filename, strlen (filename) + 1);
3169 emit_uvalue (logbuffer, number_of_methods);
3170 emit_uvalue (logbuffer, fully_covered);
3171 emit_uvalue (logbuffer, partially_covered);
3172 EXIT_LOG (logbuffer);
3174 safe_send (prof, logbuffer);
3178 dump_coverage (MonoProfiler *prof)
3180 if (!coverage_initialized)
3183 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Started dump\n");)
3186 mono_conc_hashtable_foreach (coverage_assemblies, build_assembly_buffer, prof);
3187 mono_conc_hashtable_foreach (coverage_classes, build_class_buffer, prof);
3188 mono_conc_hashtable_foreach (coverage_methods, build_method_buffer, prof);
3190 COVERAGE_DEBUG(fprintf (stderr, "Coverage: Finished dump\n");)
3194 process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method)
3199 if (!coverage_initialized)
3202 klass = mono_method_get_class (method);
3203 image = mono_class_get_image (klass);
3205 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)))
3208 mono_conc_hashtable_insert (entered_methods, method, method);
3211 static MonoLockFreeQueueNode *
3212 create_method_node (MonoMethod *method)
3214 MethodNode *node = g_malloc (sizeof (MethodNode));
3215 mono_lock_free_queue_node_init ((MonoLockFreeQueueNode *) node, FALSE);
3216 node->method = method;
3218 return (MonoLockFreeQueueNode *) node;
3222 coverage_filter (MonoProfiler *prof, MonoMethod *method)
3226 MonoAssembly *assembly;
3227 MonoMethodHeader *header;
3228 guint32 iflags, flags, code_size;
3229 char *fqn, *classname;
3230 gboolean has_positive, found;
3231 MonoLockFreeQueue *image_methods, *class_methods;
3232 MonoLockFreeQueueNode *node;
3234 if (!coverage_initialized)
3237 COVERAGE_DEBUG(fprintf (stderr, "Coverage filter for %s\n", mono_method_get_name (method));)
3239 flags = mono_method_get_flags (method, &iflags);
3240 if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
3241 (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/)) {
3242 COVERAGE_DEBUG(fprintf (stderr, " Internal call or pinvoke - ignoring\n");)
3246 // Don't need to do anything else if we're already tracking this method
3247 if (mono_conc_hashtable_lookup (coverage_methods, method)) {
3248 COVERAGE_DEBUG(fprintf (stderr, " Already tracking\n");)
3252 klass = mono_method_get_class (method);
3253 image = mono_class_get_image (klass);
3255 // Don't handle coverage for the core assemblies
3256 if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)) != NULL)
3259 if (prof->coverage_filters) {
3260 /* Check already filtered classes first */
3261 if (mono_conc_hashtable_lookup (filtered_classes, klass)) {
3262 COVERAGE_DEBUG(fprintf (stderr, " Already filtered\n");)
3266 classname = mono_type_get_name (mono_class_get_type (klass));
3268 fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
3270 COVERAGE_DEBUG(fprintf (stderr, " Looking for %s in filter\n", fqn);)
3271 // Check positive filters first
3272 has_positive = FALSE;
3274 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3275 char *filter = g_ptr_array_index (prof->coverage_filters, i);
3277 if (filter [0] == '+') {
3278 filter = &filter [1];
3280 COVERAGE_DEBUG(fprintf (stderr, " Checking against +%s ...", filter);)
3282 if (strstr (fqn, filter) != NULL) {
3283 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3286 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3288 has_positive = TRUE;
3292 if (has_positive && !found) {
3293 COVERAGE_DEBUG(fprintf (stderr, " Positive match was not found\n");)
3295 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3302 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3303 // FIXME: Is substring search sufficient?
3304 char *filter = g_ptr_array_index (prof->coverage_filters, i);
3305 if (filter [0] == '+')
3309 filter = &filter [1];
3310 COVERAGE_DEBUG(fprintf (stderr, " Checking against -%s ...", filter);)
3312 if (strstr (fqn, filter) != NULL) {
3313 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3315 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3321 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3329 COVERAGE_DEBUG(fprintf (stderr, " Handling coverage for %s\n", mono_method_get_name (method));)
3330 header = mono_method_get_header (method);
3332 mono_method_header_get_code (header, &code_size, NULL);
3334 assembly = mono_image_get_assembly (image);
3336 mono_conc_hashtable_insert (coverage_methods, method, method);
3337 mono_conc_hashtable_insert (coverage_assemblies, assembly, assembly);
3339 image_methods = mono_conc_hashtable_lookup (image_to_methods, image);
3341 if (image_methods == NULL) {
3342 image_methods = g_malloc (sizeof (MonoLockFreeQueue));
3343 mono_lock_free_queue_init (image_methods);
3344 mono_conc_hashtable_insert (image_to_methods, image, image_methods);
3347 node = create_method_node (method);
3348 mono_lock_free_queue_enqueue (image_methods, node);
3350 class_methods = mono_conc_hashtable_lookup (coverage_classes, klass);
3352 if (class_methods == NULL) {
3353 class_methods = g_malloc (sizeof (MonoLockFreeQueue));
3354 mono_lock_free_queue_init (class_methods);
3355 mono_conc_hashtable_insert (coverage_classes, klass, class_methods);
3358 node = create_method_node (method);
3359 mono_lock_free_queue_enqueue (class_methods, node);
3364 #define LINE_BUFFER_SIZE 4096
3365 /* Max file limit of 128KB */
3366 #define MAX_FILE_SIZE 128 * 1024
3368 get_file_content (FILE *stream)
3373 int res, offset = 0;
3375 res = fseek (stream, 0, SEEK_END);
3379 filesize = ftell (stream);
3383 res = fseek (stream, 0, SEEK_SET);
3387 if (filesize > MAX_FILE_SIZE)
3390 buffer = g_malloc ((filesize + 1) * sizeof (char));
3391 while ((bytes_read = fread (buffer + offset, 1, LINE_BUFFER_SIZE, stream)) > 0)
3392 offset += bytes_read;
3394 /* NULL terminate our buffer */
3395 buffer[filesize] = '\0';
3400 get_next_line (char *contents, char **next_start)
3404 if (p == NULL || *p == '\0') {
3409 while (*p != '\n' && *p != '\0')
3414 *next_start = p + 1;
3422 init_suppressed_assemblies (void)
3428 mono_mutex_init (&suppressed_assemblies_mutex);
3429 suppressed_assemblies = mono_conc_hashtable_new (&suppressed_assemblies_mutex, g_str_hash, g_str_equal);
3430 sa_file = fopen (SUPPRESSION_DIR "/mono-profiler-log.suppression", "r");
3431 if (sa_file == NULL)
3434 /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
3435 content = get_file_content (sa_file);
3436 if (content == NULL) {
3437 g_error ("mono-profiler-log.suppression is greater than 128kb - aborting\n");
3440 while ((line = get_next_line (content, &content))) {
3441 line = g_strchomp (g_strchug (line));
3442 mono_conc_hashtable_insert (suppressed_assemblies, line, line);
3448 static MonoConcurrentHashTable *
3449 init_hashtable (mono_mutex_t *mutex)
3451 mono_mutex_init (mutex);
3452 return mono_conc_hashtable_new (mutex, NULL, NULL);
3456 destroy_hashtable (MonoConcurrentHashTable *hashtable, mono_mutex_t *mutex)
3458 mono_conc_hashtable_destroy (hashtable);
3459 mono_mutex_destroy (mutex);
3462 #endif /* DISABLE_HELPER_THREAD */
3465 coverage_init (MonoProfiler *prof)
3467 #ifndef DISABLE_HELPER_THREAD
3468 assert (!coverage_initialized);
3470 COVERAGE_DEBUG(fprintf (stderr, "Coverage initialized\n");)
3472 coverage_methods = init_hashtable (&coverage_methods_mutex);
3473 coverage_assemblies = init_hashtable (&coverage_assemblies_mutex);
3474 coverage_classes = init_hashtable (&coverage_classes_mutex);
3475 filtered_classes = init_hashtable (&filtered_classes_mutex);
3476 entered_methods = init_hashtable (&entered_methods_mutex);
3477 image_to_methods = init_hashtable (&image_to_methods_mutex);
3478 init_suppressed_assemblies ();
3480 coverage_initialized = TRUE;
3481 #endif /* DISABLE_HELPER_THREAD */
3485 log_shutdown (MonoProfiler *prof)
3490 #ifndef DISABLE_HELPER_THREAD
3491 counters_and_perfcounters_sample (prof);
3493 dump_coverage (prof);
3495 if (prof->command_port) {
3497 ign_res (write (prof->pipes [1], &c, 1));
3498 pthread_join (prof->helper_thread, &res);
3504 for (i = 0; i < num_perf; ++i)
3505 read_perf_mmap (prof, i);
3509 g_ptr_array_free (prof->sorted_sample_events, TRUE);
3511 if (TLS_GET (LogBuffer, tlsbuffer))
3512 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
3514 TLS_SET (tlsbuffer, NULL);
3515 TLS_SET (tlsmethodlist, NULL);
3517 InterlockedWrite (&prof->run_writer_thread, 0);
3518 pthread_join (prof->writer_thread, &res);
3520 #if defined (HAVE_SYS_ZLIB)
3522 gzclose (prof->gzfile);
3524 if (prof->pipe_output)
3525 pclose (prof->file);
3527 fclose (prof->file);
3529 destroy_hashtable (prof->method_table, &prof->method_table_mutex);
3531 if (coverage_initialized) {
3532 destroy_hashtable (coverage_methods, &coverage_methods_mutex);
3533 destroy_hashtable (coverage_assemblies, &coverage_assemblies_mutex);
3534 destroy_hashtable (coverage_classes, &coverage_classes_mutex);
3535 destroy_hashtable (filtered_classes, &filtered_classes_mutex);
3536 destroy_hashtable (entered_methods, &entered_methods_mutex);
3537 destroy_hashtable (image_to_methods, &image_to_methods_mutex);
3538 destroy_hashtable (suppressed_assemblies, &suppressed_assemblies_mutex);
3545 new_filename (const char* filename)
3547 time_t t = time (NULL);
3548 int pid = process_id ();
3553 int count_dates = 0;
3557 for (p = filename; *p; p++) {
3568 if (!count_dates && !count_pids)
3569 return pstrdup (filename);
3570 snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
3572 snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
3573 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
3574 s_date = strlen (time_buf);
3575 s_pid = strlen (pid_buf);
3576 d = res = malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
3577 for (p = filename; *p; p++) {
3584 strcpy (d, time_buf);
3587 } else if (*p == 'p') {
3588 strcpy (d, pid_buf);
3591 } else if (*p == '%') {
3603 //this is exposed by the JIT, but it's not meant to be a supported API for now.
3604 extern void mono_threads_attach_tools_thread (void);
3606 #ifndef DISABLE_HELPER_THREAD
3609 helper_thread (void* arg)
3611 MonoProfiler* prof = arg;
3615 MonoThread *thread = NULL;
3617 mono_threads_attach_tools_thread ();
3618 //fprintf (stderr, "Server listening\n");
3619 command_socket = -1;
3625 FD_SET (prof->server_socket, &rfds);
3626 max_fd = prof->server_socket;
3627 FD_SET (prof->pipes [0], &rfds);
3628 if (max_fd < prof->pipes [0])
3629 max_fd = prof->pipes [0];
3630 if (command_socket >= 0) {
3631 FD_SET (command_socket, &rfds);
3632 if (max_fd < command_socket)
3633 max_fd = command_socket;
3638 for ( i = 0; i < num_perf; ++i) {
3639 if (perf_data [i].perf_fd < 0)
3641 FD_SET (perf_data [i].perf_fd, &rfds);
3642 if (max_fd < perf_data [i].perf_fd)
3643 max_fd = perf_data [i].perf_fd;
3648 counters_and_perfcounters_sample (prof);
3652 len = select (max_fd + 1, &rfds, NULL, NULL, &tv);
3658 g_warning ("Error in proflog server: %s", strerror (errno));
3662 if (FD_ISSET (prof->pipes [0], &rfds)) {
3664 int r = read (prof->pipes [0], &c, 1);
3665 if (r == 1 && c == 0) {
3666 StatBuffer *sbufbase = prof->stat_buffers;
3668 if (!sbufbase->next)
3670 sbuf = sbufbase->next->next;
3671 sbufbase->next->next = NULL;
3673 fprintf (stderr, "stat buffer dump\n");
3675 dump_sample_hits (prof, sbuf);
3676 free_buffer (sbuf, sbuf->size);
3677 safe_send (prof, ensure_logbuf (0));
3681 /* time to shut down */
3682 dump_sample_hits (prof, prof->stat_buffers);
3684 mono_thread_detach (thread);
3686 fprintf (stderr, "helper shutdown\n");
3690 for ( i = 0; i < num_perf; ++i) {
3691 if (perf_data [i].perf_fd < 0)
3693 if (FD_ISSET (perf_data [i].perf_fd, &rfds))
3694 read_perf_mmap (prof, i);
3698 safe_send (prof, ensure_logbuf (0));
3704 for ( i = 0; i < num_perf; ++i) {
3705 if (perf_data [i].perf_fd < 0)
3707 if (FD_ISSET (perf_data [i].perf_fd, &rfds)) {
3708 read_perf_mmap (prof, i);
3709 safe_send (prof, ensure_logbuf (0));
3714 if (command_socket >= 0 && FD_ISSET (command_socket, &rfds)) {
3715 len = read (command_socket, buf, sizeof (buf) - 1);
3719 close (command_socket);
3720 command_socket = -1;
3724 if (strcmp (buf, "heapshot\n") == 0) {
3725 heapshot_requested = 1;
3726 //fprintf (stderr, "perform heapshot\n");
3727 if (InterlockedRead (&runtime_inited) && !thread) {
3728 thread = mono_thread_attach (mono_get_root_domain ());
3729 /*fprintf (stderr, "attached\n");*/
3732 process_requests (prof);
3733 mono_thread_detach (thread);
3739 if (!FD_ISSET (prof->server_socket, &rfds)) {
3742 command_socket = accept (prof->server_socket, NULL, NULL);
3743 if (command_socket < 0)
3745 //fprintf (stderr, "Accepted connection\n");
3751 start_helper_thread (MonoProfiler* prof)
3753 struct sockaddr_in server_address;
3756 if (pipe (prof->pipes) < 0) {
3757 fprintf (stderr, "Cannot create pipe\n");
3760 prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
3761 if (prof->server_socket < 0) {
3762 fprintf (stderr, "Cannot create server socket\n");
3765 memset (&server_address, 0, sizeof (server_address));
3766 server_address.sin_family = AF_INET;
3767 server_address.sin_addr.s_addr = INADDR_ANY;
3768 server_address.sin_port = htons (prof->command_port);
3769 if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) < 0) {
3770 fprintf (stderr, "Cannot bind server socket, port: %d: %s\n", prof->command_port, strerror (errno));
3771 close (prof->server_socket);
3774 if (listen (prof->server_socket, 1) < 0) {
3775 fprintf (stderr, "Cannot listen server socket\n");
3776 close (prof->server_socket);
3779 slen = sizeof (server_address);
3780 if (getsockname (prof->server_socket, (struct sockaddr *)&server_address, &slen) == 0) {
3781 prof->command_port = ntohs (server_address.sin_port);
3782 /*fprintf (stderr, "Assigned server port: %d\n", prof->command_port);*/
3785 r = pthread_create (&prof->helper_thread, NULL, helper_thread, prof);
3787 close (prof->server_socket);
3795 writer_thread (void *arg)
3797 MonoProfiler *prof = arg;
3799 mono_threads_attach_tools_thread ();
3803 while (InterlockedRead (&prof->run_writer_thread)) {
3804 WriterQueueEntry *entry;
3806 while ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&prof->writer_queue))) {
3807 LogBuffer *method_buffer = NULL;
3808 gboolean new_methods = FALSE;
3810 if (entry->methods->len)
3811 method_buffer = create_buffer ();
3814 * Encode the method events in a temporary log buffer that we
3815 * flush to disk before the main buffer, ensuring that all
3816 * methods have metadata emitted before they're referenced.
3818 for (guint i = 0; i < entry->methods->len; i++) {
3819 MethodInfo *info = g_ptr_array_index (entry->methods, i);
3821 if (mono_conc_hashtable_lookup (prof->method_table, info->method))
3827 * Other threads use this hash table to get a general
3828 * idea of whether a method has already been emitted to
3829 * the stream. Due to the way we add to this table, it
3830 * can easily happen that multiple threads queue up the
3831 * same methods, but that's OK since eventually all
3832 * methods will be in this table and the thread-local
3833 * method lists will just be empty for the rest of the
3836 mono_conc_hashtable_insert (prof->method_table, info->method, info->method);
3838 char *name = mono_method_full_name (info->method, 1);
3839 int nlen = strlen (name) + 1;
3840 uint64_t now = current_time ();
3842 method_buffer = ensure_logbuf_inner (method_buffer, 1 + 10 + 10 + 10 + 10 + nlen);
3844 emit_byte (method_buffer, TYPE_JIT | TYPE_METHOD);
3845 emit_time (method_buffer, now);
3846 emit_method_inner (method_buffer, info->method);
3847 emit_ptr (method_buffer, mono_jit_info_get_code_start (info->ji));
3848 emit_value (method_buffer, mono_jit_info_get_code_size (info->ji));
3850 memcpy (method_buffer->data, name, nlen);
3851 method_buffer->data += nlen;
3857 g_ptr_array_free (entry->methods, TRUE);
3860 dump_buffer (prof, method_buffer);
3861 else if (method_buffer)
3862 free_buffer (method_buffer, method_buffer->size);
3864 dump_buffer (prof, entry->buffer);
3874 start_writer_thread (MonoProfiler* prof)
3876 InterlockedWrite (&prof->run_writer_thread, 1);
3878 return !pthread_create (&prof->writer_thread, NULL, writer_thread, prof);
3882 runtime_initialized (MonoProfiler *profiler)
3884 #ifndef DISABLE_HELPER_THREAD
3885 if (hs_mode_ondemand || need_helper_thread) {
3886 if (!start_helper_thread (profiler))
3887 profiler->command_port = 0;
3891 start_writer_thread (profiler);
3893 InterlockedWrite (&runtime_inited, 1);
3894 #ifndef DISABLE_HELPER_THREAD
3895 counters_init (profiler);
3896 counters_sample (profiler, 0);
3898 /* ensure the main thread data and startup are available soon */
3899 safe_send (profiler, ensure_logbuf (0));
3902 static MonoProfiler*
3903 create_profiler (const char *filename, GPtrArray *filters)
3907 int force_delete = 0;
3908 prof = calloc (1, sizeof (MonoProfiler));
3910 prof->command_port = command_port;
3911 if (filename && *filename == '-') {
3917 filename = "|mprof-report -";
3919 filename = "output.mlpd";
3920 nf = (char*)filename;
3922 nf = new_filename (filename);
3924 int s = strlen (nf) + 32;
3925 char *p = malloc (s);
3926 snprintf (p, s, "|mprof-report '--out=%s' -", nf);
3932 prof->file = popen (nf + 1, "w");
3933 prof->pipe_output = 1;
3934 } else if (*nf == '#') {
3935 int fd = strtol (nf + 1, NULL, 10);
3936 prof->file = fdopen (fd, "a");
3940 prof->file = fopen (nf, "wb");
3943 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
3946 #if defined (HAVE_SYS_ZLIB)
3948 prof->gzfile = gzdopen (fileno (prof->file), "wb");
3951 if (sample_type && !do_mono_sample)
3952 need_helper_thread = setup_perf_event ();
3954 /* FIXME: warn if different freq or sample type */
3958 if (do_mono_sample) {
3959 prof->stat_buffers = create_stat_buffer ();
3960 need_helper_thread = 1;
3962 if (do_counters && !need_helper_thread) {
3963 need_helper_thread = 1;
3966 prof->sorted_sample_events = g_ptr_array_sized_new (BUFFER_SIZE / SAMPLE_EVENT_SIZE_IN_SLOTS (0));
3968 #ifdef DISABLE_HELPER_THREAD
3969 if (hs_mode_ondemand)
3970 fprintf (stderr, "Ondemand heapshot unavailable on this arch.\n");
3973 fprintf (stderr, "Coverage unavailable on this arch.\n");
3977 mono_lock_free_queue_init (&prof->writer_queue);
3978 mono_mutex_init (&prof->method_table_mutex);
3979 prof->method_table = mono_conc_hashtable_new (&prof->method_table_mutex, NULL, NULL);
3982 coverage_init (prof);
3983 prof->coverage_filters = filters;
3985 prof->startup_time = current_time ();
3992 printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
3993 printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
3994 printf ("Options:\n");
3995 printf ("\thelp show this usage info\n");
3996 printf ("\t[no]alloc enable/disable recording allocation info\n");
3997 printf ("\t[no]calls enable/disable recording enter/leave method events\n");
3998 printf ("\theapshot[=MODE] record heap shot info (by default at each major collection)\n");
3999 printf ("\t MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
4000 printf ("\tcounters sample counters every 1s\n");
4001 printf ("\tsample[=TYPE] use statistical sampling mode (by default cycles/1000)\n");
4002 printf ("\t TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
4003 printf ("\t TYPE can be followed by /FREQUENCY\n");
4004 printf ("\ttime=fast use a faster (but more inaccurate) timer\n");
4005 printf ("\tmaxframes=NUM collect up to NUM stack frames\n");
4006 printf ("\tcalldepth=NUM ignore method events for call chain depth bigger than NUM\n");
4007 printf ("\toutput=FILENAME write the data to file FILENAME (-FILENAME to overwrite)\n");
4008 printf ("\toutput=|PROGRAM write the data to the stdin of PROGRAM\n");
4009 printf ("\t %%t is subtituted with date and time, %%p with the pid\n");
4010 printf ("\treport create a report instead of writing the raw data to a file\n");
4011 printf ("\tzip compress the output data\n");
4012 printf ("\tport=PORTNUM use PORTNUM for the listening command server\n");
4013 printf ("\tcoverage enable collection of code coverage data\n");
4014 printf ("\tcovfilter=ASSEMBLY add an assembly to the code coverage filters\n");
4015 printf ("\t add a + to include the assembly or a - to exclude it\n");
4016 printf ("\t filter=-mscorlib\n");
4017 printf ("\tcovfilter-file=FILE use FILE to generate the list of assemblies to be filtered\n");
4023 match_option (const char* p, const char *opt, char **rval)
4025 int len = strlen (opt);
4026 if (strncmp (p, opt, len) == 0) {
4028 if (p [len] == '=' && p [len + 1]) {
4029 const char *opt = p + len + 1;
4030 const char *end = strchr (opt, ',');
4038 val = malloc (l + 1);
4039 memcpy (val, opt, l);
4044 if (p [len] == 0 || p [len] == ',') {
4046 return p + len + (p [len] == ',');
4064 static const SampleMode sample_modes [] = {
4065 {"cycles", SAMPLE_CYCLES},
4066 {"instr", SAMPLE_INSTRUCTIONS},
4067 {"cachemiss", SAMPLE_CACHE_MISSES},
4068 {"cacherefs", SAMPLE_CACHE_REFS},
4069 {"branches", SAMPLE_BRANCHES},
4070 {"branchmiss", SAMPLE_BRANCH_MISSES},
4075 set_sample_mode (char* val, int allow_empty)
4078 char *maybe_freq = NULL;
4080 const SampleMode *smode = sample_modes;
4081 #ifndef USE_PERF_EVENTS
4084 if (allow_empty && !val) {
4085 sample_type = SAMPLE_CYCLES;
4089 if (strcmp (val, "mono") == 0) {
4091 sample_type = SAMPLE_CYCLES;
4095 for (smode = sample_modes; smode->name; smode++) {
4096 int l = strlen (smode->name);
4097 if (strncmp (val, smode->name, l) == 0) {
4098 sample_type = smode->sample_mode;
4099 maybe_freq = val + l;
4105 if (*maybe_freq == '/') {
4106 count = strtoul (maybe_freq + 1, &end, 10);
4107 if (maybe_freq + 1 == end)
4109 sample_freq = count;
4110 } else if (*maybe_freq != 0) {
4119 set_hsmode (char* val, int allow_empty)
4123 if (allow_empty && !val)
4125 if (strcmp (val, "ondemand") == 0) {
4126 hs_mode_ondemand = 1;
4130 count = strtoul (val, &end, 10);
4133 if (strcmp (end, "ms") == 0)
4135 else if (strcmp (end, "gc") == 0)
4143 * declaration to silence the compiler: this is the entry point that
4144 * mono will load from the shared library and call.
4147 mono_profiler_startup (const char *desc);
4150 mono_profiler_startup_log (const char *desc);
4153 * this is the entry point that will be used when the profiler
4154 * is embedded inside the main executable.
4157 mono_profiler_startup_log (const char *desc)
4159 mono_profiler_startup (desc);
4163 mono_profiler_startup (const char *desc)
4166 GPtrArray *filters = NULL;
4167 char *filename = NULL;
4171 int calls_enabled = 0;
4172 int allocs_enabled = 0;
4173 int only_counters = 0;
4174 int only_coverage = 0;
4175 int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
4176 MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
4177 MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
4178 MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS|
4179 MONO_PROFILE_INS_COVERAGE|MONO_PROFILE_APPDOMAIN_EVENTS|MONO_PROFILE_CONTEXT_EVENTS|
4180 MONO_PROFILE_ASSEMBLY_EVENTS;
4183 if (strncmp (p, "log", 3))
4188 for (; *p; p = opt) {
4194 if ((opt = match_option (p, "help", NULL)) != p) {
4198 if ((opt = match_option (p, "calls", NULL)) != p) {
4202 if ((opt = match_option (p, "nocalls", NULL)) != p) {
4203 events &= ~MONO_PROFILE_ENTER_LEAVE;
4207 if ((opt = match_option (p, "alloc", NULL)) != p) {
4211 if ((opt = match_option (p, "noalloc", NULL)) != p) {
4212 events &= ~MONO_PROFILE_ALLOCATIONS;
4215 if ((opt = match_option (p, "time", &val)) != p) {
4216 if (strcmp (val, "fast") == 0)
4218 else if (strcmp (val, "null") == 0)
4225 if ((opt = match_option (p, "report", NULL)) != p) {
4229 if ((opt = match_option (p, "debug", NULL)) != p) {
4233 if ((opt = match_option (p, "sampling-real", NULL)) != p) {
4234 sampling_mode = MONO_PROFILER_STAT_MODE_REAL;
4237 if ((opt = match_option (p, "sampling-process", NULL)) != p) {
4238 sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
4241 if ((opt = match_option (p, "heapshot", &val)) != p) {
4242 events &= ~MONO_PROFILE_ALLOCATIONS;
4243 events &= ~MONO_PROFILE_ENTER_LEAVE;
4246 set_hsmode (val, 1);
4249 if ((opt = match_option (p, "sample", &val)) != p) {
4250 events &= ~MONO_PROFILE_ALLOCATIONS;
4251 events &= ~MONO_PROFILE_ENTER_LEAVE;
4253 set_sample_mode (val, 1);
4256 if ((opt = match_option (p, "hsmode", &val)) != p) {
4257 fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
4258 set_hsmode (val, 0);
4261 if ((opt = match_option (p, "zip", NULL)) != p) {
4265 if ((opt = match_option (p, "output", &val)) != p) {
4269 if ((opt = match_option (p, "port", &val)) != p) {
4271 command_port = strtoul (val, &end, 10);
4275 if ((opt = match_option (p, "maxframes", &val)) != p) {
4277 num_frames = strtoul (val, &end, 10);
4278 if (num_frames > MAX_FRAMES)
4279 num_frames = MAX_FRAMES;
4281 notraces = num_frames == 0;
4284 if ((opt = match_option (p, "calldepth", &val)) != p) {
4286 max_call_depth = strtoul (val, &end, 10);
4290 if ((opt = match_option (p, "counters", NULL)) != p) {
4294 if ((opt = match_option (p, "countersonly", NULL)) != p) {
4298 if ((opt = match_option (p, "coverage", NULL)) != p) {
4300 events |= MONO_PROFILE_ENTER_LEAVE;
4301 debug_coverage = (g_getenv ("MONO_PROFILER_DEBUG_COVERAGE") != NULL);
4304 if ((opt = match_option (p, "onlycoverage", NULL)) != p) {
4308 if ((opt = match_option (p, "covfilter-file", &val)) != p) {
4310 char *line, *content;
4312 if (filters == NULL)
4313 filters = g_ptr_array_new ();
4315 filter_file = fopen (val, "r");
4316 if (filter_file == NULL) {
4317 fprintf (stderr, "Unable to open %s\n", val);
4321 /* Don't need to free content as it is referred to by the lines stored in @filters */
4322 content = get_file_content (filter_file);
4323 if (content == NULL)
4324 fprintf (stderr, "WARNING: %s is greater than 128kb - ignoring\n", val);
4326 while ((line = get_next_line (content, &content)))
4327 g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
4329 fclose (filter_file);
4332 if ((opt = match_option (p, "covfilter", &val)) != p) {
4333 if (filters == NULL)
4334 filters = g_ptr_array_new ();
4336 g_ptr_array_add (filters, val);
4344 if (calls_enabled) {
4345 events |= MONO_PROFILE_ENTER_LEAVE;
4349 events |= MONO_PROFILE_ALLOCATIONS;
4353 events = MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_INS_COVERAGE;
4355 utils_init (fast_time);
4357 prof = create_profiler (filename, filters);
4362 mono_profiler_install (prof, log_shutdown);
4363 mono_profiler_install_gc (gc_event, gc_resize);
4364 mono_profiler_install_allocation (gc_alloc);
4365 mono_profiler_install_gc_moves (gc_moves);
4366 mono_profiler_install_gc_roots (gc_handle, gc_roots);
4367 mono_profiler_install_appdomain (NULL, domain_loaded, NULL, domain_unloaded);
4368 mono_profiler_install_appdomain_name (domain_name);
4369 mono_profiler_install_context (context_loaded, context_unloaded);
4370 mono_profiler_install_class (NULL, class_loaded, NULL, class_unloaded);
4371 mono_profiler_install_module (NULL, image_loaded, NULL, image_unloaded);
4372 mono_profiler_install_assembly (NULL, assembly_loaded, NULL, assembly_unloaded);
4373 mono_profiler_install_thread (thread_start, thread_end);
4374 mono_profiler_install_thread_name (thread_name);
4375 mono_profiler_install_enter_leave (method_enter, method_leave);
4376 mono_profiler_install_jit_end (method_jitted);
4377 mono_profiler_install_code_buffer_new (code_buffer_new);
4378 mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
4379 mono_profiler_install_monitor (monitor_event);
4380 mono_profiler_install_runtime_initialized (runtime_initialized);
4382 mono_profiler_install_coverage_filter (coverage_filter);
4384 if (do_mono_sample && sample_type == SAMPLE_CYCLES && !only_counters) {
4385 events |= MONO_PROFILE_STATISTICAL;
4386 mono_profiler_set_statistical_mode (sampling_mode, 1000000 / sample_freq);
4387 mono_profiler_install_statistical (mono_sample_hit);
4390 mono_profiler_set_events (events);
4392 TLS_INIT (tlsbuffer);
4393 TLS_INIT (tlsmethodlist);