2 * proflog.c: mono log profiler
5 * Paolo Molaro (lupus@ximian.com)
7 * Copyright 2010 Novell, Inc (http://www.novell.com)
8 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
12 #include <mono/metadata/profiler.h>
13 #include <mono/metadata/threads.h>
14 #include <mono/metadata/mono-gc.h>
15 #include <mono/metadata/debug-helpers.h>
16 #include <mono/metadata/mono-perfcounters.h>
17 #include <mono/utils/atomic.h>
18 #include <mono/utils/mono-membar.h>
19 #include <mono/utils/mono-counters.h>
20 #include <mono/utils/mono-mutex.h>
30 #if defined(HOST_WIN32) || defined(DISABLE_SOCKETS)
31 #define DISABLE_HELPER_THREAD 1
40 #ifdef HAVE_EXECINFO_H
47 #ifndef DISABLE_HELPER_THREAD
48 #include <sys/types.h>
49 #include <sys/socket.h>
50 #include <netinet/in.h>
51 #include <sys/select.h>
60 #ifdef HAVE_SYS_STAT_H
67 #if defined (HAVE_SYS_ZLIB)
71 #if defined(__linux__)
73 #include <sys/syscall.h>
74 #include "perf_event.h"
75 #define USE_PERF_EVENTS 1
76 static int read_perf_mmap (MonoProfiler* prof, int cpu);
79 #define BUFFER_SIZE (4096 * 16)
80 static int nocalls = 0;
81 static int notraces = 0;
82 static int use_zip = 0;
83 static int do_report = 0;
84 static int do_heap_shot = 0;
85 static int max_call_depth = 100;
86 static int runtime_inited = 0;
87 static int command_port = 0;
88 static int heapshot_requested = 0;
89 static int sample_type = 0;
90 static int sample_freq = 0;
91 static int do_mono_sample = 0;
92 static int in_shutdown = 0;
93 static int do_debug = 0;
94 static int do_counters = 0;
95 static MonoProfileSamplingMode sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
97 /* For linux compile with:
98 * gcc -fPIC -shared -o libmono-profiler-log.so proflog.c utils.c -Wall -g -lz `pkg-config --cflags --libs mono-2`
99 * gcc -o mprof-report decode.c utils.c -Wall -g -lz -lrt -lpthread `pkg-config --cflags mono-2`
101 * For osx compile with:
102 * gcc -m32 -Dmono_free=free shared -o libmono-profiler-log.dylib proflog.c utils.c -Wall -g -lz `pkg-config --cflags mono-2` -undefined suppress -flat_namespace
103 * gcc -m32 -o mprof-report decode.c utils.c -Wall -g -lz -lrt -lpthread `pkg-config --cflags mono-2`
106 * sudo cp mprof-report /usr/local/bin
107 * sudo cp libmono-profiler-log.so /usr/local/lib
111 typedef struct _LogBuffer LogBuffer;
117 * The file is composed by a header followed by 0 or more buffers.
118 * Each buffer contains events that happened on a thread: for a given thread
119 * buffers that appear later in the file are guaranteed to contain events
120 * that happened later in time. Buffers from separate threads could be interleaved,
122 * Buffers are not required to be aligned.
125 * [id: 4 bytes] constant value: LOG_HEADER_ID
126 * [major: 1 byte] [minor: 1 byte] major and minor version of the log profiler
127 * [format: 1 byte] version of the data format for the rest of the file
128 * [ptrsize: 1 byte] size in bytes of a pointer in the profiled program
129 * [startup time: 8 bytes] time in milliseconds since the unix epoch when the program started
130 * [timer overhead: 4 bytes] approximate overhead in nanoseconds of the timer
131 * [flags: 4 bytes] file format flags, should be 0 for now
132 * [pid: 4 bytes] pid of the profiled process
133 * [port: 2 bytes] tcp port for server if != 0
134 * [sysid: 2 bytes] operating system and architecture identifier
136 * The multiple byte integers are in little-endian format.
139 * [buffer header] [event]*
140 * Buffers have a fixed-size header followed by 0 or more bytes of event data.
141 * Timing information and other values in the event data are usually stored
142 * as uleb128 or sleb128 integers. To save space, as noted for each item below,
143 * some data is represented as a difference between the actual value and
144 * either the last value of the same type (like for timing information) or
145 * as the difference from a value stored in a buffer header.
147 * For timing information the data is stored as uleb128, since timing
148 * increases in a monotonic way in each thread: the value is the number of
149 * nanoseconds to add to the last seen timing data in a buffer. The first value
150 * in a buffer will be calculated from the time_base field in the buffer head.
152 * Object or heap sizes are stored as uleb128.
153 * Pointer differences are stored as sleb128, instead.
155 * If an unexpected value is found, the rest of the buffer should be ignored,
156 * as generally the later values need the former to be interpreted correctly.
158 * buffer header format:
159 * [bufid: 4 bytes] constant value: BUF_ID
160 * [len: 4 bytes] size of the data following the buffer header
161 * [time_base: 8 bytes] time base in nanoseconds since an unspecified epoch
162 * [ptr_base: 8 bytes] base value for pointers
163 * [obj_base: 8 bytes] base value for object addresses
164 * [thread id: 8 bytes] system-specific thread ID (pthread_t for example)
165 * [method_base: 8 bytes] base value for MonoMethod pointers
168 * [extended info: upper 4 bits] [type: lower 4 bits] [data]*
169 * The data that follows depends on type and the extended info.
170 * Type is one of the enum values in proflog.h: TYPE_ALLOC, TYPE_GC,
171 * TYPE_METADATA, TYPE_METHOD, TYPE_EXCEPTION, TYPE_MONITOR, TYPE_HEAP.
172 * The extended info bits are interpreted based on type, see
173 * each individual event description below.
174 * strings are represented as a 0-terminated utf8 sequence.
177 * [flags: uleb128] must be 0
178 * [num: uleb128] number of frames following
179 * [frame: sleb128]* num MonoMethod pointers as differences from ptr_base
183 * exinfo: flags: TYPE_ALLOC_BT
184 * [time diff: uleb128] nanoseconds since last timing
185 * [ptr: sleb128] class as a byte difference from ptr_base
186 * [obj: sleb128] object address as a byte difference from obj_base
187 * [size: uleb128] size of the object in the heap
188 * If the TYPE_ALLOC_BT flag is set, a backtrace follows.
192 * exinfo: one of TYPE_GC_EVENT, TYPE_GC_RESIZE, TYPE_GC_MOVE, TYPE_GC_HANDLE_CREATED,
193 * TYPE_GC_HANDLE_DESTROYED
194 * [time diff: uleb128] nanoseconds since last timing
195 * if exinfo == TYPE_GC_RESIZE
196 * [heap_size: uleb128] new heap size
197 * if exinfo == TYPE_GC_EVENT
198 * [event type: uleb128] GC event (MONO_GC_EVENT_* from profiler.h)
199 * [generation: uleb128] GC generation event refers to
200 * if exinfo == TYPE_GC_MOVE
201 * [num_objects: uleb128] number of object moves that follow
202 * [objaddr: sleb128]+ num_objects object pointer differences from obj_base
203 * num is always an even number: the even items are the old
204 * addresses, the odd numbers are the respective new object addresses
205 * if exinfo == TYPE_GC_HANDLE_CREATED
206 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
207 * upper bits reserved as flags
208 * [handle: uleb128] GC handle value
209 * [objaddr: sleb128] object pointer differences from obj_base
210 * if exinfo == TYPE_GC_HANDLE_DESTROYED
211 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
212 * upper bits reserved as flags
213 * [handle: uleb128] GC handle value
215 * type metadata format:
216 * type: TYPE_METADATA
217 * exinfo: flags: TYPE_LOAD_ERR
218 * [time diff: uleb128] nanoseconds since last timing
219 * [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
221 * [pointer: sleb128] pointer of the metadata type depending on mtype
222 * if mtype == TYPE_CLASS
223 * [image: sleb128] MonoImage* as a pointer difference from ptr_base
224 * [flags: uleb128] must be 0
225 * [name: string] full class name
226 * if mtype == TYPE_IMAGE
227 * [flags: uleb128] must be 0
228 * [name: string] image file name
229 * if mtype == TYPE_THREAD
230 * [flags: uleb128] must be 0
231 * [name: string] thread name
233 * type method format:
235 * exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
236 * [time diff: uleb128] nanoseconds since last timing
237 * [method: sleb128] MonoMethod* as a pointer difference from the last such
238 * pointer or the buffer method_base
239 * if exinfo == TYPE_JIT
240 * [code address: sleb128] pointer to the native code as a diff from ptr_base
241 * [code size: uleb128] size of the generated code
242 * [name: string] full method name
244 * type runtime format:
246 * exinfo: one of: TYPE_JITHELPER
247 * [time diff: uleb128] nanoseconds since last timing
248 * if exinfo == TYPE_JITHELPER
249 * [type: uleb128] MonoProfilerCodeBufferType enum value
250 * [buffer address: sleb128] pointer to the native code as a diff from ptr_base
251 * [buffer size: uleb128] size of the generated code
252 * if type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE
253 * [name: string] buffer description name
255 * type monitor format:
257 * exinfo: TYPE_MONITOR_BT flag and one of: MONO_PROFILER_MONITOR_(CONTENTION|FAIL|DONE)
258 * [time diff: uleb128] nanoseconds since last timing
259 * [object: sleb128] the lock object as a difference from obj_base
260 * if exinfo.low3bits == MONO_PROFILER_MONITOR_CONTENTION
261 * If the TYPE_MONITOR_BT flag is set, a backtrace follows.
265 * exinfo: one of TYPE_HEAP_START, TYPE_HEAP_END, TYPE_HEAP_OBJECT, TYPE_HEAP_ROOT
266 * if exinfo == TYPE_HEAP_START
267 * [time diff: uleb128] nanoseconds since last timing
268 * if exinfo == TYPE_HEAP_END
269 * [time diff: uleb128] nanoseconds since last timing
270 * if exinfo == TYPE_HEAP_OBJECT
271 * [object: sleb128] the object as a difference from obj_base
272 * [class: sleb128] the object MonoClass* as a difference from ptr_base
273 * [size: uleb128] size of the object on the heap
274 * [num_refs: uleb128] number of object references
275 * if (format version > 1) each referenced objref is preceded by a
276 * uleb128 encoded offset: the first offset is from the object address
277 * and each next offset is relative to the previous one
278 * [objrefs: sleb128]+ object referenced as a difference from obj_base
279 * The same object can appear multiple times, but only the first time
280 * with size != 0: in the other cases this data will only be used to
281 * provide additional referenced objects.
282 * if exinfo == TYPE_HEAP_ROOT
283 * [num_roots: uleb128] number of root references
284 * [num_gc: uleb128] number of major gcs
285 * [object: sleb128] the object as a difference from obj_base
286 * [root_type: uleb128] the root_type: MonoProfileGCRootType (profiler.h)
287 * [extra_info: uleb128] the extra_info value
288 * object, root_type and extra_info are repeated num_roots times
292 * exinfo: one of TYPE_SAMPLE_HIT, TYPE_SAMPLE_USYM, TYPE_SAMPLE_UBIN, TYPE_SAMPLE_COUNTERS_DESC, TYPE_SAMPLE_COUNTERS
293 * if exinfo == TYPE_SAMPLE_HIT
294 * [sample_type: uleb128] type of sample (SAMPLE_*)
295 * [timestamp: uleb128] nanoseconds since startup (note: different from other timestamps!)
296 * [count: uleb128] number of following instruction addresses
297 * [ip: sleb128]* instruction pointer as difference from ptr_base
298 * if (format_version > 5)
299 * [mbt_count: uleb128] number of managed backtrace info triplets (method + IL offset + native offset)
300 * [method: sleb128]* MonoMethod* as a pointer difference from the last such
301 * pointer or the buffer method_base (the first such method can be also indentified by ip, but this is not neccessarily true)
302 * [il_offset: sleb128]* IL offset inside method where the hit occurred
303 * [native_offset: sleb128]* native offset inside method where the hit occurred
304 * if exinfo == TYPE_SAMPLE_USYM
305 * [address: sleb128] symbol address as a difference from ptr_base
306 * [size: uleb128] symbol size (may be 0 if unknown)
307 * [name: string] symbol name
308 * if exinfo == TYPE_SAMPLE_UBIN
309 * [time diff: uleb128] nanoseconds since last timing
310 * [address: sleb128] address where binary has been loaded
311 * [offset: uleb128] file offset of mapping (the same file can be mapped multiple times)
312 * [size: uleb128] memory size
313 * [name: string] binary name
314 * if exinfo == TYPE_SAMPLE_COUNTERS_DESC
315 * [len: uleb128] number of counters
317 * [section: uleb128] section of counter
318 * if section == MONO_COUNTER_PERFCOUNTERS:
319 * [section_name: string] section name of counter
320 * [name: string] name of counter
321 * [type: uleb128] type of counter
322 * [unit: uleb128] unit of counter
323 * [variance: uleb128] variance of counter
324 * [index: uleb128] unique index of counter
325 * if exinfo == TYPE_SAMPLE_COUNTERS
326 * [timestamp: uleb128] sampling timestamp
328 * [index: uleb128] unique index of counter
331 * [type: uleb128] type of counter value
334 * [0: uleb128] 0 -> value is null
336 * [1: uleb128] 1 -> value is not null
337 * [value: string] counter value
339 * [value: uleb128/sleb128/double] counter value, can be sleb128, uleb128 or double (determined by using type)
347 uintptr_t method_base;
348 uintptr_t last_method;
351 unsigned char* data_end;
356 unsigned char buf [1];
360 ign_res (int G_GNUC_UNUSED unused, ...)
364 #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++;}
365 #define EXIT_LOG(lb) (lb)->locked--;
367 typedef struct _StatBuffer StatBuffer;
376 typedef struct _BinaryObject BinaryObject;
378 struct _BinaryObject {
384 struct _MonoProfiler {
386 StatBuffer *stat_buffers;
388 #if defined (HAVE_SYS_ZLIB)
391 uint64_t startup_time;
393 int last_gc_gen_started;
398 pthread_t helper_thread;
400 BinaryObject *binary_objects;
404 #define TLS_SET(x,y) TlsSetValue(x, y)
405 #define TLS_GET(x) ((LogBuffer *) TlsGetValue(x))
406 #define TLS_INIT(x) x = TlsAlloc ()
407 static int tlsbuffer;
409 #define TLS_SET(x,y) x = y
412 static __thread LogBuffer* tlsbuffer = NULL;
414 #define TLS_SET(x,y) pthread_setspecific(x, y)
415 #define TLS_GET(x) ((LogBuffer *) pthread_getspecific(x))
416 #define TLS_INIT(x) pthread_key_create(&x, NULL)
417 static pthread_key_t tlsbuffer;
420 static void safe_dump (MonoProfiler *profiler, LogBuffer *logbuffer);
423 pstrdup (const char *s)
425 int len = strlen (s) + 1;
426 char *p = malloc (len);
432 create_stat_buffer (void)
434 StatBuffer* buf = alloc_buffer (BUFFER_SIZE);
435 buf->size = BUFFER_SIZE;
436 buf->data_end = (uintptr_t*)((unsigned char*)buf + buf->size);
437 buf->data = buf->buf;
444 LogBuffer* buf = alloc_buffer (BUFFER_SIZE);
445 buf->size = BUFFER_SIZE;
446 buf->time_base = current_time ();
447 buf->last_time = buf->time_base;
448 buf->data_end = (unsigned char*)buf + buf->size;
449 buf->data = buf->buf;
456 LogBuffer *logbuffer;
457 if (TLS_GET (tlsbuffer))
459 logbuffer = create_buffer ();
460 TLS_SET (tlsbuffer, logbuffer);
461 logbuffer->thread_id = thread_id ();
462 //printf ("thread %p at time %llu\n", (void*)logbuffer->thread_id, logbuffer->time_base);
466 ensure_logbuf (int bytes)
468 LogBuffer *old = TLS_GET (tlsbuffer);
469 if (old && old->data + bytes + 100 < old->data_end)
471 TLS_SET (tlsbuffer, NULL);
473 TLS_GET (tlsbuffer)->next = old;
475 TLS_GET (tlsbuffer)->call_depth = old->call_depth;
476 //printf ("new logbuffer\n");
477 return TLS_GET (tlsbuffer);
481 emit_byte (LogBuffer *logbuffer, int value)
483 logbuffer->data [0] = value;
485 assert (logbuffer->data <= logbuffer->data_end);
489 emit_value (LogBuffer *logbuffer, int value)
491 encode_uleb128 (value, logbuffer->data, &logbuffer->data);
492 assert (logbuffer->data <= logbuffer->data_end);
496 emit_time (LogBuffer *logbuffer, uint64_t value)
498 uint64_t tdiff = value - logbuffer->last_time;
500 if (value < logbuffer->last_time)
501 printf ("time went backwards\n");
502 //if (tdiff > 1000000)
503 // printf ("large time offset: %llu\n", tdiff);
505 encode_uleb128 (tdiff, logbuffer->data, &logbuffer->data);
506 /*if (tdiff != decode_uleb128 (p, &p))
507 printf ("incorrect encoding: %llu\n", tdiff);*/
508 logbuffer->last_time = value;
509 assert (logbuffer->data <= logbuffer->data_end);
513 emit_svalue (LogBuffer *logbuffer, int64_t value)
515 encode_sleb128 (value, logbuffer->data, &logbuffer->data);
516 assert (logbuffer->data <= logbuffer->data_end);
520 emit_uvalue (LogBuffer *logbuffer, uint64_t value)
522 encode_uleb128 (value, logbuffer->data, &logbuffer->data);
523 assert (logbuffer->data <= logbuffer->data_end);
527 emit_ptr (LogBuffer *logbuffer, void *ptr)
529 if (!logbuffer->ptr_base)
530 logbuffer->ptr_base = (uintptr_t)ptr;
531 emit_svalue (logbuffer, (intptr_t)ptr - logbuffer->ptr_base);
532 assert (logbuffer->data <= logbuffer->data_end);
536 emit_method (LogBuffer *logbuffer, void *method)
538 if (!logbuffer->method_base) {
539 logbuffer->method_base = (intptr_t)method;
540 logbuffer->last_method = (intptr_t)method;
542 encode_sleb128 ((intptr_t)((char*)method - (char*)logbuffer->last_method), logbuffer->data, &logbuffer->data);
543 logbuffer->last_method = (intptr_t)method;
544 assert (logbuffer->data <= logbuffer->data_end);
548 emit_obj (LogBuffer *logbuffer, void *ptr)
550 if (!logbuffer->obj_base)
551 logbuffer->obj_base = (uintptr_t)ptr >> 3;
552 emit_svalue (logbuffer, ((uintptr_t)ptr >> 3) - logbuffer->obj_base);
553 assert (logbuffer->data <= logbuffer->data_end);
557 emit_string (LogBuffer *logbuffer, const char *str, size_t size)
561 for (; i < size; i++) {
564 emit_byte (logbuffer, str [i]);
567 emit_byte (logbuffer, '\0');
571 emit_double (LogBuffer *logbuffer, double value)
574 unsigned char buffer[8];
575 memcpy (buffer, &value, 8);
576 #if G_BYTE_ORDER == G_BIG_ENDIAN
577 for (i = 7; i >= 0; i--)
579 for (i = 0; i < 8; i++)
581 emit_byte (logbuffer, buffer[i]);
585 write_int16 (char *buf, int32_t value)
588 for (i = 0; i < 2; ++i) {
596 write_int32 (char *buf, int32_t value)
599 for (i = 0; i < 4; ++i) {
607 write_int64 (char *buf, int64_t value)
610 for (i = 0; i < 8; ++i) {
618 dump_header (MonoProfiler *profiler)
622 p = write_int32 (p, LOG_HEADER_ID);
623 *p++ = LOG_VERSION_MAJOR;
624 *p++ = LOG_VERSION_MINOR;
625 *p++ = LOG_DATA_VERSION;
626 *p++ = sizeof (void*);
627 p = write_int64 (p, ((uint64_t)time (NULL)) * 1000); /* startup time */
628 p = write_int32 (p, get_timer_overhead ()); /* timer overhead */
629 p = write_int32 (p, 0); /* flags */
630 p = write_int32 (p, process_id ()); /* pid */
631 p = write_int16 (p, profiler->command_port); /* port */
632 p = write_int16 (p, 0); /* opsystem */
633 #if defined (HAVE_SYS_ZLIB)
634 if (profiler->gzfile) {
635 gzwrite (profiler->gzfile, hbuf, p - hbuf);
637 fwrite (hbuf, p - hbuf, 1, profiler->file);
640 fwrite (hbuf, p - hbuf, 1, profiler->file);
641 fflush (profiler->file);
646 dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
651 dump_buffer (profiler, buf->next);
652 p = write_int32 (p, BUF_ID);
653 p = write_int32 (p, buf->data - buf->buf);
654 p = write_int64 (p, buf->time_base);
655 p = write_int64 (p, buf->ptr_base);
656 p = write_int64 (p, buf->obj_base);
657 p = write_int64 (p, buf->thread_id);
658 p = write_int64 (p, buf->method_base);
659 #if defined (HAVE_SYS_ZLIB)
660 if (profiler->gzfile) {
661 gzwrite (profiler->gzfile, hbuf, p - hbuf);
662 gzwrite (profiler->gzfile, buf->buf, buf->data - buf->buf);
665 fwrite (hbuf, p - hbuf, 1, profiler->file);
666 fwrite (buf->buf, buf->data - buf->buf, 1, profiler->file);
667 fflush (profiler->file);
668 #if defined (HAVE_SYS_ZLIB)
671 free_buffer (buf, buf->size);
675 process_requests (MonoProfiler *profiler)
677 if (heapshot_requested)
678 mono_gc_collect (mono_gc_max_generation ());
681 static void counters_init (MonoProfiler *profiler);
682 static void counters_sample (MonoProfiler *profiler, uint64_t timestamp);
685 runtime_initialized (MonoProfiler *profiler)
688 #ifndef DISABLE_HELPER_THREAD
689 counters_init (profiler);
690 counters_sample (profiler, 0);
692 /* ensure the main thread data and startup are available soon */
693 safe_dump (profiler, ensure_logbuf (0));
697 * Can be called only at safe callback locations.
700 safe_dump (MonoProfiler *profiler, LogBuffer *logbuffer)
702 int cd = logbuffer->call_depth;
704 dump_buffer (profiler, TLS_GET (tlsbuffer));
706 TLS_SET (tlsbuffer, NULL);
708 TLS_GET (tlsbuffer)->call_depth = cd;
712 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
715 uintptr_t last_offset = 0;
716 //const char *name = mono_class_get_name (klass);
717 LogBuffer *logbuffer = ensure_logbuf (20 + num * 8);
718 emit_byte (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
719 emit_obj (logbuffer, obj);
720 emit_ptr (logbuffer, klass);
721 /* account for object alignment in the heap */
724 emit_value (logbuffer, size);
725 emit_value (logbuffer, num);
726 for (i = 0; i < num; ++i) {
727 emit_value (logbuffer, offsets [i] - last_offset);
728 last_offset = offsets [i];
729 emit_obj (logbuffer, refs [i]);
732 // printf ("obj: %p, klass: %s, refs: %d, size: %d\n", obj, name, (int)num, (int)size);
736 static unsigned int hs_mode_ms = 0;
737 static unsigned int hs_mode_gc = 0;
738 static unsigned int hs_mode_ondemand = 0;
739 static unsigned int gc_count = 0;
740 static uint64_t last_hs_time = 0;
743 heap_walk (MonoProfiler *profiler)
747 LogBuffer *logbuffer;
750 logbuffer = ensure_logbuf (10);
751 now = current_time ();
752 if (hs_mode_ms && (now - last_hs_time)/1000000 >= hs_mode_ms)
754 else if (hs_mode_gc && (gc_count % hs_mode_gc) == 0)
756 else if (hs_mode_ondemand)
757 do_walk = heapshot_requested;
758 else if (!hs_mode_ms && !hs_mode_gc && profiler->last_gc_gen_started == mono_gc_max_generation ())
763 heapshot_requested = 0;
764 emit_byte (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
765 emit_time (logbuffer, now);
766 mono_gc_walk_heap (0, gc_reference, NULL);
767 logbuffer = ensure_logbuf (10);
768 now = current_time ();
769 emit_byte (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
770 emit_time (logbuffer, now);
775 gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation) {
777 LogBuffer *logbuffer = ensure_logbuf (10);
778 now = current_time ();
779 ENTER_LOG (logbuffer, "gcevent");
780 emit_byte (logbuffer, TYPE_GC_EVENT | TYPE_GC);
781 emit_time (logbuffer, now);
782 emit_value (logbuffer, ev);
783 emit_value (logbuffer, generation);
784 /* to deal with nested gen1 after gen0 started */
785 if (ev == MONO_GC_EVENT_START) {
786 profiler->last_gc_gen_started = generation;
787 if (generation == mono_gc_max_generation ())
790 if (ev == MONO_GC_EVENT_PRE_START_WORLD)
791 heap_walk (profiler);
792 EXIT_LOG (logbuffer);
793 if (ev == MONO_GC_EVENT_POST_START_WORLD)
794 safe_dump (profiler, logbuffer);
795 //printf ("gc event %d for generation %d\n", ev, generation);
799 gc_resize (MonoProfiler *profiler, int64_t new_size) {
801 LogBuffer *logbuffer = ensure_logbuf (10);
802 now = current_time ();
803 ENTER_LOG (logbuffer, "gcresize");
804 emit_byte (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
805 emit_time (logbuffer, now);
806 emit_value (logbuffer, new_size);
807 //printf ("gc resized to %lld\n", new_size);
808 EXIT_LOG (logbuffer);
811 #define MAX_FRAMES 32
814 MonoMethod* methods [MAX_FRAMES];
815 int32_t il_offsets [MAX_FRAMES];
816 int32_t native_offsets [MAX_FRAMES];
818 static int num_frames = MAX_FRAMES;
821 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
823 FrameData *frame = data;
824 if (method && frame->count < num_frames) {
825 frame->il_offsets [frame->count] = il_offset;
826 frame->native_offsets [frame->count] = native_offset;
827 frame->methods [frame->count++] = method;
828 //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
830 return frame->count == num_frames;
834 * a note about stack walks: they can cause more profiler events to fire,
835 * so we need to make sure they don't happen after we started emitting an
836 * event, hence the collect_bt/emit_bt split.
839 collect_bt (FrameData *data)
842 mono_stack_walk_no_il (walk_stack, data);
846 emit_bt (LogBuffer *logbuffer, FrameData *data)
848 /* FIXME: this is actually tons of data and we should
849 * just output it the first time and use an id the next
851 if (data->count > num_frames)
852 printf ("bad num frames: %d\n", data->count);
853 emit_value (logbuffer, 0); /* flags */
854 emit_value (logbuffer, data->count);
855 //if (*p != data.count) {
856 // 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);}
857 while (data->count) {
858 emit_ptr (logbuffer, data->methods [--data->count]);
863 gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
867 int do_bt = (nocalls && runtime_inited && !notraces)? TYPE_ALLOC_BT: 0;
869 LogBuffer *logbuffer;
870 len = mono_object_get_size (obj);
871 /* account for object alignment in the heap */
876 logbuffer = ensure_logbuf (32 + MAX_FRAMES * 8);
877 now = current_time ();
878 ENTER_LOG (logbuffer, "gcalloc");
879 emit_byte (logbuffer, do_bt | TYPE_ALLOC);
880 emit_time (logbuffer, now);
881 emit_ptr (logbuffer, klass);
882 emit_obj (logbuffer, obj);
883 emit_value (logbuffer, len);
885 emit_bt (logbuffer, &data);
886 EXIT_LOG (logbuffer);
888 safe_dump (prof, logbuffer);
889 process_requests (prof);
890 //printf ("gc alloc %s at %p\n", mono_class_get_name (klass), obj);
894 gc_moves (MonoProfiler *prof, void **objects, int num)
898 LogBuffer *logbuffer = ensure_logbuf (10 + num * 8);
899 now = current_time ();
900 ENTER_LOG (logbuffer, "gcmove");
901 emit_byte (logbuffer, TYPE_GC_MOVE | TYPE_GC);
902 emit_time (logbuffer, now);
903 emit_value (logbuffer, num);
904 for (i = 0; i < num; ++i)
905 emit_obj (logbuffer, objects [i]);
906 //printf ("gc moved %d objects\n", num/2);
907 EXIT_LOG (logbuffer);
911 gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
914 LogBuffer *logbuffer = ensure_logbuf (5 + num * 18);
915 ENTER_LOG (logbuffer, "gcroots");
916 emit_byte (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
917 emit_value (logbuffer, num);
918 emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
919 for (i = 0; i < num; ++i) {
920 emit_obj (logbuffer, objects [i]);
921 emit_value (logbuffer, root_types [i]);
922 emit_value (logbuffer, extra_info [i]);
924 EXIT_LOG (logbuffer);
928 gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
931 LogBuffer *logbuffer = ensure_logbuf (16);
932 now = current_time ();
933 ENTER_LOG (logbuffer, "gchandle");
934 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
935 emit_byte (logbuffer, TYPE_GC_HANDLE_CREATED | TYPE_GC);
936 else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
937 emit_byte (logbuffer, TYPE_GC_HANDLE_DESTROYED | TYPE_GC);
940 emit_time (logbuffer, now);
941 emit_value (logbuffer, type);
942 emit_value (logbuffer, handle);
943 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
944 emit_obj (logbuffer, obj);
945 EXIT_LOG (logbuffer);
946 process_requests (prof);
950 push_nesting (char *p, MonoClass *klass)
955 nesting = mono_class_get_nesting_type (klass);
957 p = push_nesting (p, nesting);
961 name = mono_class_get_name (klass);
962 nspace = mono_class_get_namespace (klass);
965 p += strlen (nspace);
975 type_name (MonoClass *klass)
979 push_nesting (buf, klass);
980 p = malloc (strlen (buf) + 1);
986 image_loaded (MonoProfiler *prof, MonoImage *image, int result)
991 LogBuffer *logbuffer;
992 if (result != MONO_PROFILE_OK)
994 name = mono_image_get_filename (image);
995 nlen = strlen (name) + 1;
996 logbuffer = ensure_logbuf (16 + nlen);
997 now = current_time ();
998 ENTER_LOG (logbuffer, "image");
999 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1000 emit_time (logbuffer, now);
1001 emit_byte (logbuffer, TYPE_IMAGE);
1002 emit_ptr (logbuffer, image);
1003 emit_value (logbuffer, 0); /* flags */
1004 memcpy (logbuffer->data, name, nlen);
1005 logbuffer->data += nlen;
1006 //printf ("loaded image %p (%s)\n", image, name);
1007 EXIT_LOG (logbuffer);
1008 if (logbuffer->next)
1009 safe_dump (prof, logbuffer);
1010 process_requests (prof);
1014 class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
1020 LogBuffer *logbuffer;
1021 if (result != MONO_PROFILE_OK)
1024 name = mono_type_get_name (mono_class_get_type (klass));
1026 name = type_name (klass);
1027 nlen = strlen (name) + 1;
1028 image = mono_class_get_image (klass);
1029 logbuffer = ensure_logbuf (24 + nlen);
1030 now = current_time ();
1031 ENTER_LOG (logbuffer, "class");
1032 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1033 emit_time (logbuffer, now);
1034 emit_byte (logbuffer, TYPE_CLASS);
1035 emit_ptr (logbuffer, klass);
1036 emit_ptr (logbuffer, image);
1037 emit_value (logbuffer, 0); /* flags */
1038 memcpy (logbuffer->data, name, nlen);
1039 logbuffer->data += nlen;
1040 //printf ("loaded class %p (%s)\n", klass, name);
1045 EXIT_LOG (logbuffer);
1046 if (logbuffer->next)
1047 safe_dump (prof, logbuffer);
1048 process_requests (prof);
1052 method_enter (MonoProfiler *prof, MonoMethod *method)
1055 LogBuffer *logbuffer = ensure_logbuf (16);
1056 if (logbuffer->call_depth++ > max_call_depth)
1058 now = current_time ();
1059 ENTER_LOG (logbuffer, "enter");
1060 emit_byte (logbuffer, TYPE_ENTER | TYPE_METHOD);
1061 emit_time (logbuffer, now);
1062 emit_method (logbuffer, method);
1063 EXIT_LOG (logbuffer);
1064 process_requests (prof);
1068 method_leave (MonoProfiler *prof, MonoMethod *method)
1071 LogBuffer *logbuffer = ensure_logbuf (16);
1072 if (--logbuffer->call_depth > max_call_depth)
1074 now = current_time ();
1075 ENTER_LOG (logbuffer, "leave");
1076 emit_byte (logbuffer, TYPE_LEAVE | TYPE_METHOD);
1077 emit_time (logbuffer, now);
1078 emit_method (logbuffer, method);
1079 EXIT_LOG (logbuffer);
1080 if (logbuffer->next)
1081 safe_dump (prof, logbuffer);
1082 process_requests (prof);
1086 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
1089 LogBuffer *logbuffer;
1092 logbuffer = ensure_logbuf (16);
1093 if (--logbuffer->call_depth > max_call_depth)
1095 now = current_time ();
1096 ENTER_LOG (logbuffer, "eleave");
1097 emit_byte (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
1098 emit_time (logbuffer, now);
1099 emit_method (logbuffer, method);
1100 EXIT_LOG (logbuffer);
1101 process_requests (prof);
1105 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo* jinfo, int result)
1110 LogBuffer *logbuffer;
1111 if (result != MONO_PROFILE_OK)
1113 name = mono_method_full_name (method, 1);
1114 nlen = strlen (name) + 1;
1115 logbuffer = ensure_logbuf (32 + nlen);
1116 now = current_time ();
1117 ENTER_LOG (logbuffer, "jit");
1118 emit_byte (logbuffer, TYPE_JIT | TYPE_METHOD);
1119 emit_time (logbuffer, now);
1120 emit_method (logbuffer, method);
1121 emit_ptr (logbuffer, mono_jit_info_get_code_start (jinfo));
1122 emit_value (logbuffer, mono_jit_info_get_code_size (jinfo));
1123 memcpy (logbuffer->data, name, nlen);
1124 logbuffer->data += nlen;
1126 EXIT_LOG (logbuffer);
1127 if (logbuffer->next)
1128 safe_dump (prof, logbuffer);
1129 process_requests (prof);
1133 code_buffer_new (MonoProfiler *prof, void *buffer, int size, MonoProfilerCodeBufferType type, void *data)
1138 LogBuffer *logbuffer;
1139 if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
1141 nlen = strlen (name) + 1;
1146 logbuffer = ensure_logbuf (32 + nlen);
1147 now = current_time ();
1148 ENTER_LOG (logbuffer, "code buffer");
1149 emit_byte (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
1150 emit_time (logbuffer, now);
1151 emit_value (logbuffer, type);
1152 emit_ptr (logbuffer, buffer);
1153 emit_value (logbuffer, size);
1155 memcpy (logbuffer->data, name, nlen);
1156 logbuffer->data += nlen;
1158 EXIT_LOG (logbuffer);
1159 process_requests (prof);
1163 throw_exc (MonoProfiler *prof, MonoObject *object)
1165 int do_bt = (nocalls && runtime_inited && !notraces)? TYPE_EXCEPTION_BT: 0;
1168 LogBuffer *logbuffer;
1171 logbuffer = ensure_logbuf (16 + MAX_FRAMES * 8);
1172 now = current_time ();
1173 ENTER_LOG (logbuffer, "throw");
1174 emit_byte (logbuffer, do_bt | TYPE_EXCEPTION);
1175 emit_time (logbuffer, now);
1176 emit_obj (logbuffer, object);
1178 emit_bt (logbuffer, &data);
1179 EXIT_LOG (logbuffer);
1180 process_requests (prof);
1184 clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
1187 LogBuffer *logbuffer = ensure_logbuf (16);
1188 now = current_time ();
1189 ENTER_LOG (logbuffer, "clause");
1190 emit_byte (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
1191 emit_time (logbuffer, now);
1192 emit_value (logbuffer, clause_type);
1193 emit_value (logbuffer, clause_num);
1194 emit_method (logbuffer, method);
1195 EXIT_LOG (logbuffer);
1199 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
1201 int do_bt = (nocalls && runtime_inited && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION)? TYPE_MONITOR_BT: 0;
1204 LogBuffer *logbuffer;
1207 logbuffer = ensure_logbuf (16 + MAX_FRAMES * 8);
1208 now = current_time ();
1209 ENTER_LOG (logbuffer, "monitor");
1210 emit_byte (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
1211 emit_time (logbuffer, now);
1212 emit_obj (logbuffer, object);
1214 emit_bt (logbuffer, &data);
1215 EXIT_LOG (logbuffer);
1216 process_requests (profiler);
1220 thread_start (MonoProfiler *prof, uintptr_t tid)
1222 //printf ("thread start %p\n", (void*)tid);
1227 thread_end (MonoProfiler *prof, uintptr_t tid)
1230 if (TLS_GET (tlsbuffer))
1231 dump_buffer (prof, TLS_GET (tlsbuffer));
1233 TLS_SET (tlsbuffer, NULL);
1237 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
1239 int len = strlen (name) + 1;
1241 LogBuffer *logbuffer;
1242 logbuffer = ensure_logbuf (10 + len);
1243 now = current_time ();
1244 ENTER_LOG (logbuffer, "tname");
1245 emit_byte (logbuffer, TYPE_METADATA);
1246 emit_time (logbuffer, now);
1247 emit_byte (logbuffer, TYPE_THREAD);
1248 emit_ptr (logbuffer, (void*)tid);
1249 emit_value (logbuffer, 0); /* flags */
1250 memcpy (logbuffer->data, name, len);
1251 logbuffer->data += len;
1252 EXIT_LOG (logbuffer);
1264 AsyncFrameInfo *data;
1268 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
1270 AsyncFrameData *frame = data;
1271 if (frame->count < num_frames) {
1272 frame->data [frame->count].method = method;
1273 frame->data [frame->count].domain = domain;
1274 frame->data [frame->count].base_address = base_address;
1275 frame->data [frame->count].offset = offset;
1276 // printf ("In %d at %p (dom %p) (native: %p)\n", frame->count, method, domain, base_address);
1279 return frame->count == num_frames;
1283 (type | frame count), tid, time, ip, [method, domain, base address, offset] * frames
1285 #define SAMPLE_EVENT_SIZE_IN_SLOTS(FRAMES) (4 + (FRAMES) * 4)
1288 mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
1291 AsyncFrameInfo frames [num_frames];
1292 AsyncFrameData bt_data = { 0, &frames [0]};
1294 uintptr_t *data, *new_data, *old_data;
1300 now = current_time ();
1302 mono_stack_walk_async_safe (&async_walk_stack, context, &bt_data);
1304 elapsed = (now - profiler->startup_time) / 10000;
1308 snprintf (buf, sizeof (buf), "hit at %p in thread %p after %llu ms\n", ip, (void*)thread_id (), (unsigned long long int)elapsed/100);
1310 ign_res (write (2, buf, len));
1312 sbuf = profiler->stat_buffers;
1315 /* flush the buffer at 1 second intervals */
1316 if (sbuf->data > sbuf->buf && (elapsed - sbuf->buf [2]) > 100000) {
1319 /* overflow: 400 slots is a big enough number to reduce the chance of losing this event if many
1320 * threads hit this same spot at the same time
1322 if (timedout || (sbuf->data + 400 >= sbuf->data_end)) {
1323 StatBuffer *oldsb, *foundsb;
1324 sbuf = create_stat_buffer ();
1326 oldsb = profiler->stat_buffers;
1328 foundsb = InterlockedCompareExchangePointer ((void * volatile*)&profiler->stat_buffers, sbuf, oldsb);
1329 } while (foundsb != oldsb);
1331 ign_res (write (2, "overflow\n", 9));
1332 /* notify the helper thread */
1333 if (sbuf->next->next) {
1335 ign_res (write (profiler->pipes [1], &c, 1));
1337 ign_res (write (2, "notify\n", 7));
1341 old_data = sbuf->data;
1342 new_data = old_data + SAMPLE_EVENT_SIZE_IN_SLOTS (bt_data.count);
1343 data = InterlockedCompareExchangePointer ((void * volatile*)&sbuf->data, new_data, old_data);
1344 } while (data != old_data);
1345 if (old_data >= sbuf->data_end)
1346 return; /* lost event */
1347 old_data [0] = 1 | (sample_type << 16) | (bt_data.count << 8);
1348 old_data [1] = thread_id ();
1349 old_data [2] = elapsed;
1350 old_data [3] = (uintptr_t)ip;
1351 for (i = 0; i < bt_data.count; ++i) {
1352 old_data [4 + 4 * i + 0] = (uintptr_t)frames [i].method;
1353 old_data [4 + 4 * i + 1] = (uintptr_t)frames [i].domain;
1354 old_data [4 + 4 * i + 2] = (uintptr_t)frames [i].base_address;
1355 old_data [4 + 4 * i + 3] = (uintptr_t)frames [i].offset;
1359 static uintptr_t *code_pages = 0;
1360 static int num_code_pages = 0;
1361 static int size_code_pages = 0;
1362 #define CPAGE_SHIFT (9)
1363 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
1364 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
1365 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
1368 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
1371 uintptr_t start_pos;
1372 start_pos = (page >> CPAGE_SHIFT) % hsize;
1375 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
1377 } else if (!hash [i]) {
1384 } while (i != start_pos);
1385 /* should not happen */
1386 printf ("failed code page store\n");
1391 add_code_pointer (uintptr_t ip)
1394 if (num_code_pages * 2 >= size_code_pages) {
1396 uintptr_t old_size = size_code_pages;
1397 size_code_pages *= 2;
1398 if (size_code_pages == 0)
1399 size_code_pages = 16;
1400 n = calloc (sizeof (uintptr_t) * size_code_pages, 1);
1401 for (i = 0; i < old_size; ++i) {
1403 add_code_page (n, size_code_pages, code_pages [i]);
1409 num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
1412 #if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
1414 dump_ubin (const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
1417 LogBuffer *logbuffer;
1419 len = strlen (filename) + 1;
1420 now = current_time ();
1421 logbuffer = ensure_logbuf (20 + len);
1422 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
1423 emit_time (logbuffer, now);
1424 emit_svalue (logbuffer, load_addr);
1425 emit_uvalue (logbuffer, offset);
1426 emit_uvalue (logbuffer, size);
1427 memcpy (logbuffer->data, filename, len);
1428 logbuffer->data += len;
1433 dump_usym (const char *name, uintptr_t value, uintptr_t size)
1435 LogBuffer *logbuffer;
1437 len = strlen (name) + 1;
1438 logbuffer = ensure_logbuf (20 + len);
1439 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
1440 emit_ptr (logbuffer, (void*)value);
1441 emit_value (logbuffer, size);
1442 memcpy (logbuffer->data, name, len);
1443 logbuffer->data += len;
1448 #if SIZEOF_VOID_P == 4
1449 #define ELF_WSIZE 32
1451 #define ELF_WSIZE 64
1454 #define ElfW(type) _ElfW (Elf, ELF_WSIZE, type)
1455 #define _ElfW(e,w,t) _ElfW_1 (e, w, _##t)
1456 #define _ElfW_1(e,w,t) e##w##t
1460 dump_elf_symbols (ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
1463 for (i = 0; i < num_symbols; ++i) {
1465 sym = strtab + symbols [i].st_name;
1466 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
1468 //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
1469 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
1474 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
1481 ElfW(Shdr) *sheader;
1482 ElfW(Shdr) *shstrtabh;
1483 ElfW(Shdr) *symtabh = NULL;
1484 ElfW(Shdr) *strtabh = NULL;
1485 ElfW(Sym) *symbols = NULL;
1489 fd = open (filename, O_RDONLY);
1492 if (fstat (fd, &statb) != 0) {
1496 file_size = statb.st_size;
1497 data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
1499 if (data == MAP_FAILED)
1502 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
1503 header->e_ident [EI_MAG1] != ELFMAG1 ||
1504 header->e_ident [EI_MAG2] != ELFMAG2 ||
1505 header->e_ident [EI_MAG3] != ELFMAG3 ) {
1506 munmap (data, file_size);
1509 sheader = (void*)((char*)data + header->e_shoff);
1510 shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
1511 strtab = (const char*)data + shstrtabh->sh_offset;
1512 for (i = 0; i < header->e_shnum; ++i) {
1513 //printf ("section header: %d\n", sheader->sh_type);
1514 if (sheader->sh_type == SHT_SYMTAB) {
1516 strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
1517 /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
1520 sheader = (void*)((char*)sheader + header->e_shentsize);
1522 if (!symtabh || !strtabh) {
1523 munmap (data, file_size);
1526 strtab = (const char*)data + strtabh->sh_offset;
1527 num_symbols = symtabh->sh_size / symtabh->sh_entsize;
1528 symbols = (void*)((char*)data + symtabh->sh_offset);
1529 dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
1530 munmap (data, file_size);
1535 #if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
1537 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
1539 MonoProfiler *prof = data;
1541 const char *filename;
1543 char *a = (void*)info->dlpi_addr;
1545 ElfW(Dyn) *dyn = NULL;
1546 ElfW(Sym) *symtab = NULL;
1547 ElfW(Word) *hash_table = NULL;
1548 ElfW(Ehdr) *header = NULL;
1549 const char* strtab = NULL;
1550 for (obj = prof->binary_objects; obj; obj = obj->next) {
1554 filename = info->dlpi_name;
1557 if (!info->dlpi_addr && !filename [0]) {
1558 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
1564 obj = calloc (sizeof (BinaryObject), 1);
1565 obj->addr = (void*)info->dlpi_addr;
1566 obj->name = pstrdup (filename);
1567 obj->next = prof->binary_objects;
1568 prof->binary_objects = obj;
1569 //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
1571 for (i = 0; i < info->dlpi_phnum; ++i) {
1572 //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);
1573 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
1574 header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
1575 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
1576 header->e_ident [EI_MAG1] != ELFMAG1 ||
1577 header->e_ident [EI_MAG2] != ELFMAG2 ||
1578 header->e_ident [EI_MAG3] != ELFMAG3 ) {
1581 dump_ubin (filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
1582 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
1583 dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
1586 if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
1588 if (!info->dlpi_name || !info->dlpi_name[0])
1592 for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
1593 if (dyn [i].d_tag == DT_SYMTAB) {
1594 if (symtab && do_debug)
1595 printf ("multiple symtabs: %d\n", i);
1596 symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
1597 } else if (dyn [i].d_tag == DT_HASH) {
1598 hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
1599 } else if (dyn [i].d_tag == DT_STRTAB) {
1600 strtab = (const char*)(a + dyn [i].d_un.d_ptr);
1605 num_sym = hash_table [1];
1606 dump_elf_symbols (symtab, num_sym, strtab, (void*)info->dlpi_addr);
1611 load_binaries (MonoProfiler *prof)
1613 dl_iterate_phdr (elf_dl_callback, prof);
1618 load_binaries (MonoProfiler *prof)
1625 symbol_for (uintptr_t code)
1628 void *ip = (void*)code;
1630 if (dladdr (ip, &di)) {
1632 return di.dli_sname;
1635 names = backtrace_symbols (&ip, 1);
1637 const char* p = names [0];
1648 dump_unmanaged_coderefs (MonoProfiler *prof)
1651 const char* last_symbol;
1652 uintptr_t addr, page_end;
1654 if (load_binaries (prof))
1656 for (i = 0; i < size_code_pages; ++i) {
1658 if (!code_pages [i] || code_pages [i] & 1)
1661 addr = CPAGE_ADDR (code_pages [i]);
1662 page_end = addr + CPAGE_SIZE;
1663 code_pages [i] |= 1;
1664 /* we dump the symbols for the whole page */
1665 for (; addr < page_end; addr += 16) {
1666 sym = symbol_for (addr);
1667 if (sym && sym == last_symbol)
1672 dump_usym (sym, addr, 0); /* let's not guess the size */
1673 //printf ("found symbol at %p: %s\n", (void*)addr, sym);
1679 dump_sample_hits_inner (MonoProfiler *prof, StatBuffer *sbuf, int recurse, GPtrArray **array);
1682 dump_sample_hits (MonoProfiler *prof, StatBuffer *sbuf, int recurse)
1684 GPtrArray *array = NULL;
1685 dump_sample_hits_inner (prof, sbuf, recurse, &array);
1689 g_ptr_array_sort (array, g_direct_equal);
1690 for (i = 0; i < array->len; ++i) {
1691 MonoJitInfo *cur = array->pdata [i];
1693 if (i > 0 && array->pdata [i - 1] == cur)
1695 method_jitted (prof, mono_jit_info_get_method (cur), cur, MONO_PROFILE_OK);
1701 dump_sample_hits_inner (MonoProfiler *prof, StatBuffer *sbuf, int recurse, GPtrArray **array)
1704 LogBuffer *logbuffer;
1707 if (recurse && sbuf->next) {
1708 dump_sample_hits_inner (prof, sbuf->next, 1, array);
1709 free_buffer (sbuf->next, sbuf->next->size);
1712 for (sample = sbuf->buf; sample < sbuf->data;) {
1714 int count = sample [0] & 0xff;
1715 int mbt_count = (sample [0] & 0xff00) >> 8;
1716 int type = sample [0] >> 16;
1717 uintptr_t *managed_sample_base = sample + count + 3;
1719 if (sample + SAMPLE_EVENT_SIZE_IN_SLOTS (mbt_count) > sbuf->data)
1722 for (i = 0; i < mbt_count; ++i) {
1723 MonoMethod *method = (MonoMethod*)managed_sample_base [i * 4 + 0];
1724 MonoDomain *domain = (MonoDomain*)managed_sample_base [i * 4 + 1];
1725 void *address = (void*)managed_sample_base [i * 4 + 2];
1728 MonoJitInfo *ji = mono_jit_info_table_find (domain, address);
1730 managed_sample_base [i * 4 + 0] = (uintptr_t)mono_jit_info_get_method (ji);
1732 *array = g_ptr_array_new ();
1733 g_ptr_array_add (*array, ji);
1737 logbuffer = ensure_logbuf (20 + count * 8);
1738 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
1739 emit_value (logbuffer, type);
1740 emit_uvalue (logbuffer, prof->startup_time + (uint64_t)sample [2] * (uint64_t)10000);
1741 emit_value (logbuffer, count);
1742 for (i = 0; i < count; ++i) {
1743 emit_ptr (logbuffer, (void*)sample [i + 3]);
1744 add_code_pointer (sample [i + 3]);
1747 sample += count + 3;
1748 /* new in data version 6 */
1749 emit_uvalue (logbuffer, mbt_count);
1750 for (i = 0; i < mbt_count; ++i) {
1751 emit_method (logbuffer, (void*)sample [i * 4]); /* method */
1752 emit_svalue (logbuffer, 0); /* il offset will always be 0 from now on */
1753 emit_svalue (logbuffer, sample [i * 4 + 3]); /* native offset */
1755 sample += 4 * mbt_count;
1757 dump_unmanaged_coderefs (prof);
1761 #ifndef __NR_perf_event_open
1763 #define __NR_perf_event_open 364
1765 #define __NR_perf_event_open 241
1770 mono_cpu_count (void)
1773 #ifdef PLATFORM_ANDROID
1774 /* Android tries really hard to save power by powering off CPUs on SMP phones which
1775 * means the normal way to query cpu count returns a wrong value with userspace API.
1776 * Instead we use /sys entries to query the actual hardware CPU count.
1778 char buffer[8] = {'\0'};
1779 int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
1780 /* Format of the /sys entry is a cpulist of indexes which in the case
1781 * of present is always of the form "0-(n-1)" when there is more than
1782 * 1 core, n being the number of CPU cores in the system. Otherwise
1783 * the value is simply 0
1785 if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
1786 count = strtol (((char*)buffer) + 2, NULL, 10);
1792 #ifdef _SC_NPROCESSORS_ONLN
1793 count = sysconf (_SC_NPROCESSORS_ONLN);
1800 size_t len = sizeof (int);
1803 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
1810 GetSystemInfo (&info);
1811 return info.dwNumberOfProcessors;
1820 unsigned int prev_pos;
1822 struct perf_event_mmap_page *page_desc;
1825 static PerfData *perf_data = NULL;
1826 static int num_perf;
1827 #define PERF_PAGES_SHIFT 4
1828 static int num_pages = 1 << PERF_PAGES_SHIFT;
1829 static unsigned int mmap_mask;
1832 struct perf_event_header h;
1842 perf_event_syscall (struct perf_event_attr *attr, pid_t pid, int cpu, int group_fd, unsigned long flags)
1844 attr->size = PERF_ATTR_SIZE_VER0;
1845 //printf ("perf attr size: %d\n", attr->size);
1846 #if defined(__x86_64__)
1847 return syscall(/*__NR_perf_event_open*/ 298, attr, pid, cpu, group_fd, flags);
1848 #elif defined(__i386__)
1849 return syscall(/*__NR_perf_event_open*/ 336, attr, pid, cpu, group_fd, flags);
1850 #elif defined(__arm__)
1851 return syscall(/*__NR_perf_event_open*/ 364, attr, pid, cpu, group_fd, flags);
1858 setup_perf_map (PerfData *perf)
1860 perf->mmap_base = mmap (NULL, (num_pages + 1) * getpagesize (), PROT_READ|PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
1861 if (perf->mmap_base == MAP_FAILED) {
1863 printf ("failed mmap\n");
1866 perf->page_desc = perf->mmap_base;
1868 printf ("mmap version: %d\n", perf->page_desc->version);
1873 dump_perf_hits (MonoProfiler *prof, void *buf, int size)
1875 LogBuffer *logbuffer;
1876 void *end = (char*)buf + size;
1878 int pid = getpid ();
1884 if (pid != s->pid) {
1886 printf ("event for different pid: %d\n", s->pid);
1887 buf = (char*)buf + s->h.size;
1890 /*ip = (void*)s->ip;
1891 printf ("sample: %d, size: %d, ip: %p (%s), timestamp: %llu, nframes: %llu\n",
1892 s->h.type, s->h.size, ip, symbol_for (ip), s->timestamp, s->nframes);*/
1893 logbuffer = ensure_logbuf (20 + s->nframes * 8);
1894 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
1895 emit_value (logbuffer, sample_type);
1896 emit_uvalue (logbuffer, s->timestamp - prof->startup_time);
1897 emit_value (logbuffer, 1); /* count */
1898 emit_ptr (logbuffer, (void*)(uintptr_t)s->ip);
1899 /* no support here yet for the managed backtrace */
1900 emit_uvalue (logbuffer, 0);
1901 add_code_pointer (s->ip);
1902 buf = (char*)buf + s->h.size;
1906 printf ("dumped %d samples\n", samples);
1907 dump_unmanaged_coderefs (prof);
1910 /* read events from the ring buffer */
1912 read_perf_mmap (MonoProfiler* prof, int cpu)
1914 PerfData *perf = perf_data + cpu;
1916 unsigned char *data = (unsigned char*)perf->mmap_base + getpagesize ();
1917 unsigned int head = perf->page_desc->data_head;
1921 mono_memory_read_barrier ();
1923 old = perf->prev_pos;
1927 printf ("lost mmap events: old: %d, head: %d\n", old, head);
1931 if ((old & mmap_mask) + size != (head & mmap_mask)) {
1932 buf = data + (old & mmap_mask);
1933 size = mmap_mask + 1 - (old & mmap_mask);
1935 /* size bytes at buf */
1937 printf ("found1 bytes of events: %d\n", size);
1938 dump_perf_hits (prof, buf, size);
1940 buf = data + (old & mmap_mask);
1942 /* size bytes at buf */
1944 printf ("found bytes of events: %d\n", size);
1945 dump_perf_hits (prof, buf, size);
1947 perf->prev_pos = old;
1948 perf->page_desc->data_tail = old;
1953 setup_perf_event_for_cpu (PerfData *perf, int cpu)
1955 struct perf_event_attr attr;
1956 memset (&attr, 0, sizeof (attr));
1957 attr.type = PERF_TYPE_HARDWARE;
1958 switch (sample_type) {
1959 case SAMPLE_CYCLES: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
1960 case SAMPLE_INSTRUCTIONS: attr.config = PERF_COUNT_HW_INSTRUCTIONS; break;
1961 case SAMPLE_CACHE_MISSES: attr.config = PERF_COUNT_HW_CACHE_MISSES; break;
1962 case SAMPLE_CACHE_REFS: attr.config = PERF_COUNT_HW_CACHE_REFERENCES; break;
1963 case SAMPLE_BRANCHES: attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS; break;
1964 case SAMPLE_BRANCH_MISSES: attr.config = PERF_COUNT_HW_BRANCH_MISSES; break;
1965 default: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
1967 attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD | PERF_SAMPLE_TIME;
1968 // attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
1969 attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING | PERF_FORMAT_ID;
1972 attr.sample_freq = sample_freq;
1974 perf->perf_fd = perf_event_syscall (&attr, getpid (), cpu, -1, 0);
1976 printf ("perf fd: %d, freq: %d, event: %llu\n", perf->perf_fd, sample_freq, attr.config);
1977 if (perf->perf_fd < 0) {
1978 if (perf->perf_fd == -EPERM) {
1979 fprintf (stderr, "Perf syscall denied, do \"echo 1 > /proc/sys/kernel/perf_event_paranoid\" as root to enable.\n");
1982 perror ("open perf event");
1986 if (!setup_perf_map (perf)) {
1987 close (perf->perf_fd);
1995 setup_perf_event (void)
1998 mmap_mask = num_pages * getpagesize () - 1;
1999 num_perf = mono_cpu_count ();
2000 perf_data = calloc (num_perf, sizeof (PerfData));
2001 for (i = 0; i < num_perf; ++i) {
2002 count += setup_perf_event_for_cpu (perf_data + i, i);
2011 #endif /* USE_PERF_EVENTS */
2013 #ifndef DISABLE_HELPER_THREAD
2015 typedef struct MonoCounterAgent {
2016 MonoCounter *counter;
2017 // MonoCounterAgent specific data :
2022 struct MonoCounterAgent *next;
2025 static MonoCounterAgent* counters;
2026 static gboolean counters_initialized = FALSE;
2027 static int counters_index = 1;
2028 static mono_mutex_t counters_mutex;
2031 counters_add_agent (MonoCounter *counter)
2033 MonoCounterAgent *agent, *item;
2035 if (!counters_initialized)
2038 mono_mutex_lock (&counters_mutex);
2040 for (agent = counters; agent; agent = agent->next) {
2041 if (agent->counter == counter) {
2042 agent->value_size = 0;
2044 free (agent->value);
2045 agent->value = NULL;
2047 mono_mutex_unlock (&counters_mutex);
2052 agent = malloc (sizeof (MonoCounterAgent));
2053 agent->counter = counter;
2054 agent->value = NULL;
2055 agent->value_size = 0;
2056 agent->index = counters_index++;
2069 mono_mutex_unlock (&counters_mutex);
2073 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
2075 counters_add_agent (counter);
2080 counters_init (MonoProfiler *profiler)
2082 assert (!counters_initialized);
2084 mono_mutex_init (&counters_mutex);
2086 counters_initialized = TRUE;
2088 mono_counters_on_register (&counters_add_agent);
2089 mono_counters_foreach (counters_init_foreach_callback, NULL);
2093 counters_emit (MonoProfiler *profiler)
2095 MonoCounterAgent *agent;
2096 LogBuffer *logbuffer;
2097 int size = 1 + 5, len = 0;
2099 if (!counters_initialized)
2102 mono_mutex_lock (&counters_mutex);
2104 for (agent = counters; agent; agent = agent->next) {
2108 size += strlen (mono_counter_get_name (agent->counter)) + 1 + 5 * 5;
2113 mono_mutex_unlock (&counters_mutex);
2117 logbuffer = ensure_logbuf (size);
2119 ENTER_LOG (logbuffer, "counters");
2120 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2121 emit_value (logbuffer, len);
2122 for (agent = counters; agent; agent = agent->next) {
2128 name = mono_counter_get_name (agent->counter);
2129 emit_value (logbuffer, mono_counter_get_section (agent->counter));
2130 emit_string (logbuffer, name, strlen (name) + 1);
2131 emit_value (logbuffer, mono_counter_get_type (agent->counter));
2132 emit_value (logbuffer, mono_counter_get_unit (agent->counter));
2133 emit_value (logbuffer, mono_counter_get_variance (agent->counter));
2134 emit_value (logbuffer, agent->index);
2138 EXIT_LOG (logbuffer);
2140 safe_dump (profiler, ensure_logbuf (0));
2142 mono_mutex_unlock (&counters_mutex);
2146 counters_sample (MonoProfiler *profiler, uint64_t timestamp)
2148 MonoCounterAgent *agent;
2149 MonoCounter *counter;
2150 LogBuffer *logbuffer;
2156 if (!counters_initialized)
2159 counters_emit (profiler);
2162 buffer = calloc (1, buffer_size);
2164 mono_mutex_lock (&counters_mutex);
2167 for (agent = counters; agent; agent = agent->next)
2168 size += 10 * 2 + mono_counter_get_size (agent->counter);
2170 logbuffer = ensure_logbuf (size);
2172 ENTER_LOG (logbuffer, "counters");
2173 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
2174 emit_uvalue (logbuffer, timestamp);
2175 for (agent = counters; agent; agent = agent->next) {
2178 counter = agent->counter;
2180 size = mono_counter_get_size (counter);
2182 continue; // FIXME error
2183 } else if (size > buffer_size) {
2185 buffer = realloc (buffer, buffer_size);
2188 memset (buffer, 0, buffer_size);
2190 if (mono_counters_sample (counter, buffer, size) < 0)
2191 continue; // FIXME error
2193 type = mono_counter_get_type (counter);
2195 if (!agent->value) {
2196 agent->value = calloc (1, size);
2197 agent->value_size = size;
2199 if (type == MONO_COUNTER_STRING) {
2200 if (strcmp (agent->value, buffer) == 0)
2203 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
2208 emit_uvalue (logbuffer, agent->index);
2209 emit_uvalue (logbuffer, type);
2211 case MONO_COUNTER_INT:
2212 #if SIZEOF_VOID_P == 4
2213 case MONO_COUNTER_WORD:
2215 emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
2217 case MONO_COUNTER_UINT:
2218 emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
2220 case MONO_COUNTER_TIME_INTERVAL:
2221 case MONO_COUNTER_LONG:
2222 #if SIZEOF_VOID_P == 8
2223 case MONO_COUNTER_WORD:
2225 emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
2227 case MONO_COUNTER_ULONG:
2228 emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
2230 case MONO_COUNTER_DOUBLE:
2231 emit_double (logbuffer, *(double*)buffer);
2233 case MONO_COUNTER_STRING:
2235 emit_byte (logbuffer, 0);
2237 emit_byte (logbuffer, 1);
2238 emit_string (logbuffer, (char*)buffer, size);
2245 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
2246 agent->value = realloc (agent->value, size);
2247 agent->value_size = size;
2251 memcpy (agent->value, buffer, size);
2255 emit_value (logbuffer, 0);
2256 EXIT_LOG (logbuffer);
2258 safe_dump (profiler, ensure_logbuf (0));
2260 mono_mutex_unlock (&counters_mutex);
2263 typedef struct _PerfCounterAgent PerfCounterAgent;
2264 struct _PerfCounterAgent {
2265 PerfCounterAgent *next;
2267 char *category_name;
2276 static PerfCounterAgent *perfcounters = NULL;
2279 perfcounters_emit (MonoProfiler *profiler)
2281 PerfCounterAgent *pcagent;
2282 LogBuffer *logbuffer;
2283 int size = 1 + 5, len = 0;
2285 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2286 if (pcagent->emitted)
2289 size += strlen (pcagent->name) + 1 + 5 * 5;
2296 logbuffer = ensure_logbuf (size);
2298 ENTER_LOG (logbuffer, "perfcounters");
2299 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2300 emit_value (logbuffer, len);
2301 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2302 if (pcagent->emitted)
2305 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
2306 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
2307 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
2308 emit_value (logbuffer, MONO_COUNTER_LONG);
2309 emit_value (logbuffer, MONO_COUNTER_RAW);
2310 emit_value (logbuffer, MONO_COUNTER_VARIABLE);
2311 emit_value (logbuffer, pcagent->index);
2313 pcagent->emitted = 1;
2315 EXIT_LOG (logbuffer);
2317 safe_dump (profiler, ensure_logbuf (0));
2321 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
2323 PerfCounterAgent *pcagent;
2325 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2326 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
2328 if (pcagent->value == value)
2331 pcagent->value = value;
2332 pcagent->updated = 1;
2333 pcagent->deleted = 0;
2337 pcagent = g_new0 (PerfCounterAgent, 1);
2338 pcagent->next = perfcounters;
2339 pcagent->index = counters_index++;
2340 pcagent->category_name = g_strdup (category_name);
2341 pcagent->name = g_strdup (name);
2342 pcagent->type = (int) type;
2343 pcagent->value = value;
2344 pcagent->emitted = 0;
2345 pcagent->updated = 1;
2346 pcagent->deleted = 0;
2348 perfcounters = pcagent;
2354 perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp)
2356 PerfCounterAgent *pcagent;
2357 LogBuffer *logbuffer;
2360 if (!counters_initialized)
2363 mono_mutex_lock (&counters_mutex);
2365 /* mark all perfcounters as deleted, foreach will unmark them as necessary */
2366 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
2367 pcagent->deleted = 1;
2369 mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
2371 perfcounters_emit (profiler);
2375 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2376 if (pcagent->deleted || !pcagent->updated)
2378 size += 10 * 2 + sizeof (gint64);
2381 logbuffer = ensure_logbuf (size);
2383 ENTER_LOG (logbuffer, "perfcounters");
2384 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
2385 emit_uvalue (logbuffer, timestamp);
2386 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2387 if (pcagent->deleted || !pcagent->updated)
2389 emit_uvalue (logbuffer, pcagent->index);
2390 emit_uvalue (logbuffer, MONO_COUNTER_LONG);
2391 emit_svalue (logbuffer, pcagent->value);
2393 pcagent->updated = 0;
2396 emit_value (logbuffer, 0);
2397 EXIT_LOG (logbuffer);
2399 safe_dump (profiler, ensure_logbuf (0));
2401 mono_mutex_unlock (&counters_mutex);
2405 counters_and_perfcounters_sample (MonoProfiler *prof)
2407 static uint64_t start = -1;
2411 start = current_time ();
2413 now = current_time ();
2414 counters_sample (prof, (now - start) / 1000/ 1000);
2415 perfcounters_sample (prof, (now - start) / 1000/ 1000);
2418 #endif /* DISABLE_HELPER_THREAD */
2421 log_shutdown (MonoProfiler *prof)
2424 #ifndef DISABLE_HELPER_THREAD
2425 counters_and_perfcounters_sample (prof);
2427 if (prof->command_port) {
2430 ign_res (write (prof->pipes [1], &c, 1));
2431 pthread_join (prof->helper_thread, &res);
2437 for (i = 0; i < num_perf; ++i)
2438 read_perf_mmap (prof, i);
2441 dump_sample_hits (prof, prof->stat_buffers, 1);
2443 if (TLS_GET (tlsbuffer))
2444 dump_buffer (prof, TLS_GET (tlsbuffer));
2445 TLS_SET (tlsbuffer, NULL);
2447 #if defined (HAVE_SYS_ZLIB)
2449 gzclose (prof->gzfile);
2451 if (prof->pipe_output)
2452 pclose (prof->file);
2454 fclose (prof->file);
2459 new_filename (const char* filename)
2461 time_t t = time (NULL);
2462 int pid = process_id ();
2467 int count_dates = 0;
2471 for (p = filename; *p; p++) {
2482 if (!count_dates && !count_pids)
2483 return pstrdup (filename);
2484 snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
2486 snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
2487 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
2488 s_date = strlen (time_buf);
2489 s_pid = strlen (pid_buf);
2490 d = res = malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
2491 for (p = filename; *p; p++) {
2498 strcpy (d, time_buf);
2501 } else if (*p == 'p') {
2502 strcpy (d, pid_buf);
2505 } else if (*p == '%') {
2517 #ifndef DISABLE_HELPER_THREAD
2519 //this is exposed by the JIT, but it's not meant to be a supported API for now.
2520 extern void mono_threads_attach_tools_thread (void);
2523 helper_thread (void* arg)
2525 MonoProfiler* prof = arg;
2529 MonoThread *thread = NULL;
2531 mono_threads_attach_tools_thread ();
2532 //fprintf (stderr, "Server listening\n");
2533 command_socket = -1;
2539 FD_SET (prof->server_socket, &rfds);
2540 max_fd = prof->server_socket;
2541 FD_SET (prof->pipes [0], &rfds);
2542 if (max_fd < prof->pipes [0])
2543 max_fd = prof->pipes [0];
2544 if (command_socket >= 0) {
2545 FD_SET (command_socket, &rfds);
2546 if (max_fd < command_socket)
2547 max_fd = command_socket;
2552 for ( i = 0; i < num_perf; ++i) {
2553 if (perf_data [i].perf_fd < 0)
2555 FD_SET (perf_data [i].perf_fd, &rfds);
2556 if (max_fd < perf_data [i].perf_fd)
2557 max_fd = perf_data [i].perf_fd;
2562 counters_and_perfcounters_sample (prof);
2566 len = select (max_fd + 1, &rfds, NULL, NULL, &tv);
2572 g_warning ("Error in proflog server: %s", strerror (errno));
2576 if (FD_ISSET (prof->pipes [0], &rfds)) {
2578 int r = read (prof->pipes [0], &c, 1);
2579 if (r == 1 && c == 0) {
2580 StatBuffer *sbufbase = prof->stat_buffers;
2582 if (!sbufbase->next)
2584 sbuf = sbufbase->next->next;
2585 sbufbase->next->next = NULL;
2587 fprintf (stderr, "stat buffer dump\n");
2589 dump_sample_hits (prof, sbuf, 1);
2590 free_buffer (sbuf, sbuf->size);
2591 safe_dump (prof, ensure_logbuf (0));
2595 /* time to shut down */
2597 mono_thread_detach (thread);
2599 fprintf (stderr, "helper shutdown\n");
2603 for ( i = 0; i < num_perf; ++i) {
2604 if (perf_data [i].perf_fd < 0)
2606 if (FD_ISSET (perf_data [i].perf_fd, &rfds))
2607 read_perf_mmap (prof, i);
2611 safe_dump (prof, ensure_logbuf (0));
2617 for ( i = 0; i < num_perf; ++i) {
2618 if (perf_data [i].perf_fd < 0)
2620 if (FD_ISSET (perf_data [i].perf_fd, &rfds)) {
2621 read_perf_mmap (prof, i);
2622 safe_dump (prof, ensure_logbuf (0));
2627 if (command_socket >= 0 && FD_ISSET (command_socket, &rfds)) {
2628 len = read (command_socket, buf, sizeof (buf) - 1);
2632 close (command_socket);
2633 command_socket = -1;
2637 if (strcmp (buf, "heapshot\n") == 0) {
2638 heapshot_requested = 1;
2639 //fprintf (stderr, "perform heapshot\n");
2640 if (runtime_inited && !thread) {
2641 thread = mono_thread_attach (mono_get_root_domain ());
2642 /*fprintf (stderr, "attached\n");*/
2645 process_requests (prof);
2646 mono_thread_detach (thread);
2652 if (!FD_ISSET (prof->server_socket, &rfds)) {
2655 command_socket = accept (prof->server_socket, NULL, NULL);
2656 if (command_socket < 0)
2658 //fprintf (stderr, "Accepted connection\n");
2664 start_helper_thread (MonoProfiler* prof)
2666 struct sockaddr_in server_address;
2669 if (pipe (prof->pipes) < 0) {
2670 fprintf (stderr, "Cannot create pipe\n");
2673 prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
2674 if (prof->server_socket < 0) {
2675 fprintf (stderr, "Cannot create server socket\n");
2678 memset (&server_address, 0, sizeof (server_address));
2679 server_address.sin_family = AF_INET;
2680 server_address.sin_addr.s_addr = INADDR_ANY;
2681 server_address.sin_port = htons (prof->command_port);
2682 if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) < 0) {
2683 fprintf (stderr, "Cannot bind server socket, port: %d: %s\n", prof->command_port, strerror (errno));
2684 close (prof->server_socket);
2687 if (listen (prof->server_socket, 1) < 0) {
2688 fprintf (stderr, "Cannot listen server socket\n");
2689 close (prof->server_socket);
2692 slen = sizeof (server_address);
2693 if (getsockname (prof->server_socket, (struct sockaddr *)&server_address, &slen) == 0) {
2694 prof->command_port = ntohs (server_address.sin_port);
2695 /*fprintf (stderr, "Assigned server port: %d\n", prof->command_port);*/
2698 r = pthread_create (&prof->helper_thread, NULL, helper_thread, prof);
2700 close (prof->server_socket);
2707 static MonoProfiler*
2708 create_profiler (const char *filename)
2712 int force_delete = 0;
2713 int need_helper_thread = 0;
2714 prof = calloc (1, sizeof (MonoProfiler));
2716 prof->command_port = command_port;
2717 if (filename && *filename == '-') {
2723 filename = "|mprof-report -";
2725 filename = "output.mlpd";
2726 nf = (char*)filename;
2728 nf = new_filename (filename);
2730 int s = strlen (nf) + 32;
2731 char *p = malloc (s);
2732 snprintf (p, s, "|mprof-report '--out=%s' -", nf);
2738 prof->file = popen (nf + 1, "w");
2739 prof->pipe_output = 1;
2740 } else if (*nf == '#') {
2741 int fd = strtol (nf + 1, NULL, 10);
2742 prof->file = fdopen (fd, "a");
2747 prof->file = fopen (nf, "wb");
2750 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
2753 #if defined (HAVE_SYS_ZLIB)
2755 prof->gzfile = gzdopen (fileno (prof->file), "wb");
2758 if (sample_type && !do_mono_sample)
2759 need_helper_thread = setup_perf_event ();
2761 /* FIXME: warn if different freq or sample type */
2765 if (do_mono_sample) {
2766 prof->stat_buffers = create_stat_buffer ();
2767 need_helper_thread = 1;
2769 if (do_counters && !need_helper_thread) {
2770 need_helper_thread = 1;
2772 #ifndef DISABLE_HELPER_THREAD
2773 if (hs_mode_ondemand || need_helper_thread) {
2774 if (!start_helper_thread (prof))
2775 prof->command_port = 0;
2778 if (hs_mode_ondemand)
2779 fprintf (stderr, "Ondemand heapshot unavailable on this arch.\n");
2781 prof->startup_time = current_time ();
2789 printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
2790 printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
2791 printf ("Options:\n");
2792 printf ("\thelp show this usage info\n");
2793 printf ("\t[no]alloc enable/disable recording allocation info\n");
2794 printf ("\t[no]calls enable/disable recording enter/leave method events\n");
2795 printf ("\theapshot[=MODE] record heap shot info (by default at each major collection)\n");
2796 printf ("\t MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
2797 printf ("\tcounters sample counters every 1s\n");
2798 printf ("\tsample[=TYPE] use statistical sampling mode (by default cycles/1000)\n");
2799 printf ("\t TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
2800 printf ("\t TYPE can be followed by /FREQUENCY\n");
2801 printf ("\ttime=fast use a faster (but more inaccurate) timer\n");
2802 printf ("\tmaxframes=NUM collect up to NUM stack frames\n");
2803 printf ("\tcalldepth=NUM ignore method events for call chain depth bigger than NUM\n");
2804 printf ("\toutput=FILENAME write the data to file FILENAME (-FILENAME to overwrite)\n");
2805 printf ("\toutput=|PROGRAM write the data to the stdin of PROGRAM\n");
2806 printf ("\t %%t is subtituted with date and time, %%p with the pid\n");
2807 printf ("\treport create a report instead of writing the raw data to a file\n");
2808 printf ("\tzip compress the output data\n");
2809 printf ("\tport=PORTNUM use PORTNUM for the listening command server\n");
2815 match_option (const char* p, const char *opt, char **rval)
2817 int len = strlen (opt);
2818 if (strncmp (p, opt, len) == 0) {
2820 if (p [len] == '=' && p [len + 1]) {
2821 const char *opt = p + len + 1;
2822 const char *end = strchr (opt, ',');
2830 val = malloc (l + 1);
2831 memcpy (val, opt, l);
2836 if (p [len] == 0 || p [len] == ',') {
2838 return p + len + (p [len] == ',');
2856 static const SampleMode sample_modes [] = {
2857 {"cycles", SAMPLE_CYCLES},
2858 {"instr", SAMPLE_INSTRUCTIONS},
2859 {"cachemiss", SAMPLE_CACHE_MISSES},
2860 {"cacherefs", SAMPLE_CACHE_REFS},
2861 {"branches", SAMPLE_BRANCHES},
2862 {"branchmiss", SAMPLE_BRANCH_MISSES},
2867 set_sample_mode (char* val, int allow_empty)
2870 char *maybe_freq = NULL;
2872 const SampleMode *smode = sample_modes;
2873 #ifndef USE_PERF_EVENTS
2876 if (allow_empty && !val) {
2877 sample_type = SAMPLE_CYCLES;
2881 if (strcmp (val, "mono") == 0) {
2883 sample_type = SAMPLE_CYCLES;
2887 for (smode = sample_modes; smode->name; smode++) {
2888 int l = strlen (smode->name);
2889 if (strncmp (val, smode->name, l) == 0) {
2890 sample_type = smode->sample_mode;
2891 maybe_freq = val + l;
2897 if (*maybe_freq == '/') {
2898 count = strtoul (maybe_freq + 1, &end, 10);
2899 if (maybe_freq + 1 == end)
2901 sample_freq = count;
2902 } else if (*maybe_freq != 0) {
2911 set_hsmode (char* val, int allow_empty)
2915 if (allow_empty && !val)
2917 if (strcmp (val, "ondemand") == 0) {
2918 hs_mode_ondemand = 1;
2922 count = strtoul (val, &end, 10);
2925 if (strcmp (end, "ms") == 0)
2927 else if (strcmp (end, "gc") == 0)
2935 * declaration to silence the compiler: this is the entry point that
2936 * mono will load from the shared library and call.
2939 mono_profiler_startup (const char *desc);
2942 mono_profiler_startup_log (const char *desc);
2945 * this is the entry point that will be used when the profiler
2946 * is embedded inside the main executable.
2949 mono_profiler_startup_log (const char *desc)
2951 mono_profiler_startup (desc);
2955 mono_profiler_startup (const char *desc)
2958 char *filename = NULL;
2962 int calls_enabled = 0;
2963 int allocs_enabled = 0;
2964 int only_counters = 0;
2965 int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
2966 MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
2967 MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
2968 MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS;
2971 if (strncmp (p, "log", 3))
2976 for (; *p; p = opt) {
2982 if ((opt = match_option (p, "help", NULL)) != p) {
2986 if ((opt = match_option (p, "calls", NULL)) != p) {
2990 if ((opt = match_option (p, "nocalls", NULL)) != p) {
2991 events &= ~MONO_PROFILE_ENTER_LEAVE;
2995 if ((opt = match_option (p, "alloc", NULL)) != p) {
2999 if ((opt = match_option (p, "noalloc", NULL)) != p) {
3000 events &= ~MONO_PROFILE_ALLOCATIONS;
3003 if ((opt = match_option (p, "time", &val)) != p) {
3004 if (strcmp (val, "fast") == 0)
3006 else if (strcmp (val, "null") == 0)
3013 if ((opt = match_option (p, "report", NULL)) != p) {
3017 if ((opt = match_option (p, "debug", NULL)) != p) {
3021 if ((opt = match_option (p, "sampling-real", NULL)) != p) {
3022 sampling_mode = MONO_PROFILER_STAT_MODE_REAL;
3025 if ((opt = match_option (p, "sampling-process", NULL)) != p) {
3026 sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
3029 if ((opt = match_option (p, "heapshot", &val)) != p) {
3030 events &= ~MONO_PROFILE_ALLOCATIONS;
3031 events &= ~MONO_PROFILE_ENTER_LEAVE;
3034 set_hsmode (val, 1);
3037 if ((opt = match_option (p, "sample", &val)) != p) {
3038 events &= ~MONO_PROFILE_ALLOCATIONS;
3039 events &= ~MONO_PROFILE_ENTER_LEAVE;
3041 set_sample_mode (val, 1);
3044 if ((opt = match_option (p, "hsmode", &val)) != p) {
3045 fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
3046 set_hsmode (val, 0);
3049 if ((opt = match_option (p, "zip", NULL)) != p) {
3053 if ((opt = match_option (p, "output", &val)) != p) {
3057 if ((opt = match_option (p, "port", &val)) != p) {
3059 command_port = strtoul (val, &end, 10);
3063 if ((opt = match_option (p, "maxframes", &val)) != p) {
3065 num_frames = strtoul (val, &end, 10);
3066 if (num_frames > MAX_FRAMES)
3067 num_frames = MAX_FRAMES;
3069 notraces = num_frames == 0;
3072 if ((opt = match_option (p, "calldepth", &val)) != p) {
3074 max_call_depth = strtoul (val, &end, 10);
3078 if ((opt = match_option (p, "counters", NULL)) != p) {
3082 if ((opt = match_option (p, "countersonly", NULL)) != p) {
3091 if (calls_enabled) {
3092 events |= MONO_PROFILE_ENTER_LEAVE;
3096 events |= MONO_PROFILE_ALLOCATIONS;
3099 utils_init (fast_time);
3101 prof = create_profiler (filename);
3106 mono_profiler_install (prof, log_shutdown);
3107 mono_profiler_install_gc (gc_event, gc_resize);
3108 mono_profiler_install_allocation (gc_alloc);
3109 mono_profiler_install_gc_moves (gc_moves);
3110 mono_profiler_install_gc_roots (gc_handle, gc_roots);
3111 mono_profiler_install_class (NULL, class_loaded, NULL, NULL);
3112 mono_profiler_install_module (NULL, image_loaded, NULL, NULL);
3113 mono_profiler_install_thread (thread_start, thread_end);
3114 mono_profiler_install_thread_name (thread_name);
3115 mono_profiler_install_enter_leave (method_enter, method_leave);
3116 mono_profiler_install_jit_end (method_jitted);
3117 mono_profiler_install_code_buffer_new (code_buffer_new);
3118 mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
3119 mono_profiler_install_monitor (monitor_event);
3120 mono_profiler_install_runtime_initialized (runtime_initialized);
3123 if (do_mono_sample && sample_type == SAMPLE_CYCLES && !only_counters) {
3124 events |= MONO_PROFILE_STATISTICAL;
3125 mono_profiler_set_statistical_mode (sampling_mode, 1000000 / sample_freq);
3126 mono_profiler_install_statistical (mono_sample_hit);
3129 mono_profiler_set_events (events);
3131 TLS_INIT (tlsbuffer);