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;
499 if (value < logbuffer->last_time)
500 printf ("time went backwards\n");
501 //if (tdiff > 1000000)
502 // printf ("large time offset: %llu\n", tdiff);
503 encode_uleb128 (tdiff, logbuffer->data, &logbuffer->data);
504 /*if (tdiff != decode_uleb128 (p, &p))
505 printf ("incorrect encoding: %llu\n", tdiff);*/
506 logbuffer->last_time = value;
507 assert (logbuffer->data <= logbuffer->data_end);
511 emit_svalue (LogBuffer *logbuffer, int64_t value)
513 encode_sleb128 (value, logbuffer->data, &logbuffer->data);
514 assert (logbuffer->data <= logbuffer->data_end);
518 emit_uvalue (LogBuffer *logbuffer, uint64_t value)
520 encode_uleb128 (value, logbuffer->data, &logbuffer->data);
521 assert (logbuffer->data <= logbuffer->data_end);
525 emit_ptr (LogBuffer *logbuffer, void *ptr)
527 if (!logbuffer->ptr_base)
528 logbuffer->ptr_base = (uintptr_t)ptr;
529 emit_svalue (logbuffer, (intptr_t)ptr - logbuffer->ptr_base);
530 assert (logbuffer->data <= logbuffer->data_end);
534 emit_method (LogBuffer *logbuffer, void *method)
536 if (!logbuffer->method_base) {
537 logbuffer->method_base = (intptr_t)method;
538 logbuffer->last_method = (intptr_t)method;
540 encode_sleb128 ((intptr_t)((char*)method - (char*)logbuffer->last_method), logbuffer->data, &logbuffer->data);
541 logbuffer->last_method = (intptr_t)method;
542 assert (logbuffer->data <= logbuffer->data_end);
546 emit_obj (LogBuffer *logbuffer, void *ptr)
548 if (!logbuffer->obj_base)
549 logbuffer->obj_base = (uintptr_t)ptr >> 3;
550 emit_svalue (logbuffer, ((uintptr_t)ptr >> 3) - logbuffer->obj_base);
551 assert (logbuffer->data <= logbuffer->data_end);
555 emit_string (LogBuffer *logbuffer, const char *str, size_t size)
559 for (; i < size; i++) {
562 emit_byte (logbuffer, str [i]);
565 emit_byte (logbuffer, '\0');
569 emit_double (LogBuffer *logbuffer, double value)
572 unsigned char buffer[8];
573 memcpy (buffer, &value, 8);
574 #if G_BYTE_ORDER == G_BIG_ENDIAN
575 for (i = 7; i >= 0; i--)
577 for (i = 0; i < 8; i++)
579 emit_byte (logbuffer, buffer[i]);
583 write_int16 (char *buf, int32_t value)
586 for (i = 0; i < 2; ++i) {
594 write_int32 (char *buf, int32_t value)
597 for (i = 0; i < 4; ++i) {
605 write_int64 (char *buf, int64_t value)
608 for (i = 0; i < 8; ++i) {
616 dump_header (MonoProfiler *profiler)
620 p = write_int32 (p, LOG_HEADER_ID);
621 *p++ = LOG_VERSION_MAJOR;
622 *p++ = LOG_VERSION_MINOR;
623 *p++ = LOG_DATA_VERSION;
624 *p++ = sizeof (void*);
625 p = write_int64 (p, ((uint64_t)time (NULL)) * 1000); /* startup time */
626 p = write_int32 (p, get_timer_overhead ()); /* timer overhead */
627 p = write_int32 (p, 0); /* flags */
628 p = write_int32 (p, process_id ()); /* pid */
629 p = write_int16 (p, profiler->command_port); /* port */
630 p = write_int16 (p, 0); /* opsystem */
631 #if defined (HAVE_SYS_ZLIB)
632 if (profiler->gzfile) {
633 gzwrite (profiler->gzfile, hbuf, p - hbuf);
635 fwrite (hbuf, p - hbuf, 1, profiler->file);
638 fwrite (hbuf, p - hbuf, 1, profiler->file);
639 fflush (profiler->file);
644 dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
649 dump_buffer (profiler, buf->next);
650 p = write_int32 (p, BUF_ID);
651 p = write_int32 (p, buf->data - buf->buf);
652 p = write_int64 (p, buf->time_base);
653 p = write_int64 (p, buf->ptr_base);
654 p = write_int64 (p, buf->obj_base);
655 p = write_int64 (p, buf->thread_id);
656 p = write_int64 (p, buf->method_base);
657 #if defined (HAVE_SYS_ZLIB)
658 if (profiler->gzfile) {
659 gzwrite (profiler->gzfile, hbuf, p - hbuf);
660 gzwrite (profiler->gzfile, buf->buf, buf->data - buf->buf);
663 fwrite (hbuf, p - hbuf, 1, profiler->file);
664 fwrite (buf->buf, buf->data - buf->buf, 1, profiler->file);
665 fflush (profiler->file);
666 #if defined (HAVE_SYS_ZLIB)
669 free_buffer (buf, buf->size);
673 process_requests (MonoProfiler *profiler)
675 if (heapshot_requested)
676 mono_gc_collect (mono_gc_max_generation ());
679 static void counters_init (MonoProfiler *profiler);
680 static void counters_sample (MonoProfiler *profiler, uint64_t timestamp);
683 runtime_initialized (MonoProfiler *profiler)
686 #ifndef DISABLE_HELPER_THREAD
687 counters_init (profiler);
688 counters_sample (profiler, 0);
690 /* ensure the main thread data and startup are available soon */
691 safe_dump (profiler, ensure_logbuf (0));
695 * Can be called only at safe callback locations.
698 safe_dump (MonoProfiler *profiler, LogBuffer *logbuffer)
700 int cd = logbuffer->call_depth;
702 dump_buffer (profiler, TLS_GET (tlsbuffer));
704 TLS_SET (tlsbuffer, NULL);
706 TLS_GET (tlsbuffer)->call_depth = cd;
710 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
713 uintptr_t last_offset = 0;
714 //const char *name = mono_class_get_name (klass);
715 LogBuffer *logbuffer = ensure_logbuf (20 + num * 8);
716 emit_byte (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
717 emit_obj (logbuffer, obj);
718 emit_ptr (logbuffer, klass);
719 /* account for object alignment in the heap */
722 emit_value (logbuffer, size);
723 emit_value (logbuffer, num);
724 for (i = 0; i < num; ++i) {
725 emit_value (logbuffer, offsets [i] - last_offset);
726 last_offset = offsets [i];
727 emit_obj (logbuffer, refs [i]);
730 // printf ("obj: %p, klass: %s, refs: %d, size: %d\n", obj, name, (int)num, (int)size);
734 static unsigned int hs_mode_ms = 0;
735 static unsigned int hs_mode_gc = 0;
736 static unsigned int hs_mode_ondemand = 0;
737 static unsigned int gc_count = 0;
738 static uint64_t last_hs_time = 0;
741 heap_walk (MonoProfiler *profiler)
745 LogBuffer *logbuffer;
748 logbuffer = ensure_logbuf (10);
749 now = current_time ();
750 if (hs_mode_ms && (now - last_hs_time)/1000000 >= hs_mode_ms)
752 else if (hs_mode_gc && (gc_count % hs_mode_gc) == 0)
754 else if (hs_mode_ondemand)
755 do_walk = heapshot_requested;
756 else if (!hs_mode_ms && !hs_mode_gc && profiler->last_gc_gen_started == mono_gc_max_generation ())
761 heapshot_requested = 0;
762 emit_byte (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
763 emit_time (logbuffer, now);
764 mono_gc_walk_heap (0, gc_reference, NULL);
765 logbuffer = ensure_logbuf (10);
766 now = current_time ();
767 emit_byte (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
768 emit_time (logbuffer, now);
773 gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation) {
775 LogBuffer *logbuffer = ensure_logbuf (10);
776 now = current_time ();
777 ENTER_LOG (logbuffer, "gcevent");
778 emit_byte (logbuffer, TYPE_GC_EVENT | TYPE_GC);
779 emit_time (logbuffer, now);
780 emit_value (logbuffer, ev);
781 emit_value (logbuffer, generation);
782 /* to deal with nested gen1 after gen0 started */
783 if (ev == MONO_GC_EVENT_START) {
784 profiler->last_gc_gen_started = generation;
785 if (generation == mono_gc_max_generation ())
788 if (ev == MONO_GC_EVENT_PRE_START_WORLD)
789 heap_walk (profiler);
790 EXIT_LOG (logbuffer);
791 if (ev == MONO_GC_EVENT_POST_START_WORLD)
792 safe_dump (profiler, logbuffer);
793 //printf ("gc event %d for generation %d\n", ev, generation);
797 gc_resize (MonoProfiler *profiler, int64_t new_size) {
799 LogBuffer *logbuffer = ensure_logbuf (10);
800 now = current_time ();
801 ENTER_LOG (logbuffer, "gcresize");
802 emit_byte (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
803 emit_time (logbuffer, now);
804 emit_value (logbuffer, new_size);
805 //printf ("gc resized to %lld\n", new_size);
806 EXIT_LOG (logbuffer);
809 #define MAX_FRAMES 32
812 MonoMethod* methods [MAX_FRAMES];
813 int32_t il_offsets [MAX_FRAMES];
814 int32_t native_offsets [MAX_FRAMES];
816 static int num_frames = MAX_FRAMES;
819 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
821 FrameData *frame = data;
822 if (method && frame->count < num_frames) {
823 frame->il_offsets [frame->count] = il_offset;
824 frame->native_offsets [frame->count] = native_offset;
825 frame->methods [frame->count++] = method;
826 //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
828 return frame->count == num_frames;
832 * a note about stack walks: they can cause more profiler events to fire,
833 * so we need to make sure they don't happen after we started emitting an
834 * event, hence the collect_bt/emit_bt split.
837 collect_bt (FrameData *data)
840 mono_stack_walk_no_il (walk_stack, data);
844 emit_bt (LogBuffer *logbuffer, FrameData *data)
846 /* FIXME: this is actually tons of data and we should
847 * just output it the first time and use an id the next
849 if (data->count > num_frames)
850 printf ("bad num frames: %d\n", data->count);
851 emit_value (logbuffer, 0); /* flags */
852 emit_value (logbuffer, data->count);
853 //if (*p != data.count) {
854 // 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);}
855 while (data->count) {
856 emit_ptr (logbuffer, data->methods [--data->count]);
861 gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
865 int do_bt = (nocalls && runtime_inited && !notraces)? TYPE_ALLOC_BT: 0;
867 LogBuffer *logbuffer;
868 len = mono_object_get_size (obj);
869 /* account for object alignment in the heap */
874 logbuffer = ensure_logbuf (32 + MAX_FRAMES * 8);
875 now = current_time ();
876 ENTER_LOG (logbuffer, "gcalloc");
877 emit_byte (logbuffer, do_bt | TYPE_ALLOC);
878 emit_time (logbuffer, now);
879 emit_ptr (logbuffer, klass);
880 emit_obj (logbuffer, obj);
881 emit_value (logbuffer, len);
883 emit_bt (logbuffer, &data);
884 EXIT_LOG (logbuffer);
886 safe_dump (prof, logbuffer);
887 process_requests (prof);
888 //printf ("gc alloc %s at %p\n", mono_class_get_name (klass), obj);
892 gc_moves (MonoProfiler *prof, void **objects, int num)
896 LogBuffer *logbuffer = ensure_logbuf (10 + num * 8);
897 now = current_time ();
898 ENTER_LOG (logbuffer, "gcmove");
899 emit_byte (logbuffer, TYPE_GC_MOVE | TYPE_GC);
900 emit_time (logbuffer, now);
901 emit_value (logbuffer, num);
902 for (i = 0; i < num; ++i)
903 emit_obj (logbuffer, objects [i]);
904 //printf ("gc moved %d objects\n", num/2);
905 EXIT_LOG (logbuffer);
909 gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
912 LogBuffer *logbuffer = ensure_logbuf (5 + num * 18);
913 ENTER_LOG (logbuffer, "gcroots");
914 emit_byte (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
915 emit_value (logbuffer, num);
916 emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
917 for (i = 0; i < num; ++i) {
918 emit_obj (logbuffer, objects [i]);
919 emit_value (logbuffer, root_types [i]);
920 emit_value (logbuffer, extra_info [i]);
922 EXIT_LOG (logbuffer);
926 gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
929 LogBuffer *logbuffer = ensure_logbuf (16);
930 now = current_time ();
931 ENTER_LOG (logbuffer, "gchandle");
932 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
933 emit_byte (logbuffer, TYPE_GC_HANDLE_CREATED | TYPE_GC);
934 else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
935 emit_byte (logbuffer, TYPE_GC_HANDLE_DESTROYED | TYPE_GC);
938 emit_time (logbuffer, now);
939 emit_value (logbuffer, type);
940 emit_value (logbuffer, handle);
941 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
942 emit_obj (logbuffer, obj);
943 EXIT_LOG (logbuffer);
944 process_requests (prof);
948 push_nesting (char *p, MonoClass *klass)
953 nesting = mono_class_get_nesting_type (klass);
955 p = push_nesting (p, nesting);
959 name = mono_class_get_name (klass);
960 nspace = mono_class_get_namespace (klass);
963 p += strlen (nspace);
973 type_name (MonoClass *klass)
977 push_nesting (buf, klass);
978 p = malloc (strlen (buf) + 1);
984 image_loaded (MonoProfiler *prof, MonoImage *image, int result)
989 LogBuffer *logbuffer;
990 if (result != MONO_PROFILE_OK)
992 name = mono_image_get_filename (image);
993 nlen = strlen (name) + 1;
994 logbuffer = ensure_logbuf (16 + nlen);
995 now = current_time ();
996 ENTER_LOG (logbuffer, "image");
997 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
998 emit_time (logbuffer, now);
999 emit_byte (logbuffer, TYPE_IMAGE);
1000 emit_ptr (logbuffer, image);
1001 emit_value (logbuffer, 0); /* flags */
1002 memcpy (logbuffer->data, name, nlen);
1003 logbuffer->data += nlen;
1004 //printf ("loaded image %p (%s)\n", image, name);
1005 EXIT_LOG (logbuffer);
1006 if (logbuffer->next)
1007 safe_dump (prof, logbuffer);
1008 process_requests (prof);
1012 class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
1018 LogBuffer *logbuffer;
1019 if (result != MONO_PROFILE_OK)
1022 name = mono_type_get_name (mono_class_get_type (klass));
1024 name = type_name (klass);
1025 nlen = strlen (name) + 1;
1026 image = mono_class_get_image (klass);
1027 logbuffer = ensure_logbuf (24 + nlen);
1028 now = current_time ();
1029 ENTER_LOG (logbuffer, "class");
1030 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1031 emit_time (logbuffer, now);
1032 emit_byte (logbuffer, TYPE_CLASS);
1033 emit_ptr (logbuffer, klass);
1034 emit_ptr (logbuffer, image);
1035 emit_value (logbuffer, 0); /* flags */
1036 memcpy (logbuffer->data, name, nlen);
1037 logbuffer->data += nlen;
1038 //printf ("loaded class %p (%s)\n", klass, name);
1043 EXIT_LOG (logbuffer);
1044 if (logbuffer->next)
1045 safe_dump (prof, logbuffer);
1046 process_requests (prof);
1050 method_enter (MonoProfiler *prof, MonoMethod *method)
1053 LogBuffer *logbuffer = ensure_logbuf (16);
1054 if (logbuffer->call_depth++ > max_call_depth)
1056 now = current_time ();
1057 ENTER_LOG (logbuffer, "enter");
1058 emit_byte (logbuffer, TYPE_ENTER | TYPE_METHOD);
1059 emit_time (logbuffer, now);
1060 emit_method (logbuffer, method);
1061 EXIT_LOG (logbuffer);
1062 process_requests (prof);
1066 method_leave (MonoProfiler *prof, MonoMethod *method)
1069 LogBuffer *logbuffer = ensure_logbuf (16);
1070 if (--logbuffer->call_depth > max_call_depth)
1072 now = current_time ();
1073 ENTER_LOG (logbuffer, "leave");
1074 emit_byte (logbuffer, TYPE_LEAVE | TYPE_METHOD);
1075 emit_time (logbuffer, now);
1076 emit_method (logbuffer, method);
1077 EXIT_LOG (logbuffer);
1078 if (logbuffer->next)
1079 safe_dump (prof, logbuffer);
1080 process_requests (prof);
1084 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
1087 LogBuffer *logbuffer;
1090 logbuffer = ensure_logbuf (16);
1091 if (--logbuffer->call_depth > max_call_depth)
1093 now = current_time ();
1094 ENTER_LOG (logbuffer, "eleave");
1095 emit_byte (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
1096 emit_time (logbuffer, now);
1097 emit_method (logbuffer, method);
1098 EXIT_LOG (logbuffer);
1099 process_requests (prof);
1103 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo* jinfo, int result)
1108 LogBuffer *logbuffer;
1109 if (result != MONO_PROFILE_OK)
1111 name = mono_method_full_name (method, 1);
1112 nlen = strlen (name) + 1;
1113 logbuffer = ensure_logbuf (32 + nlen);
1114 now = current_time ();
1115 ENTER_LOG (logbuffer, "jit");
1116 emit_byte (logbuffer, TYPE_JIT | TYPE_METHOD);
1117 emit_time (logbuffer, now);
1118 emit_method (logbuffer, method);
1119 emit_ptr (logbuffer, mono_jit_info_get_code_start (jinfo));
1120 emit_value (logbuffer, mono_jit_info_get_code_size (jinfo));
1121 memcpy (logbuffer->data, name, nlen);
1122 logbuffer->data += nlen;
1124 EXIT_LOG (logbuffer);
1125 if (logbuffer->next)
1126 safe_dump (prof, logbuffer);
1127 process_requests (prof);
1131 code_buffer_new (MonoProfiler *prof, void *buffer, int size, MonoProfilerCodeBufferType type, void *data)
1136 LogBuffer *logbuffer;
1137 if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
1139 nlen = strlen (name) + 1;
1144 logbuffer = ensure_logbuf (32 + nlen);
1145 now = current_time ();
1146 ENTER_LOG (logbuffer, "code buffer");
1147 emit_byte (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
1148 emit_time (logbuffer, now);
1149 emit_value (logbuffer, type);
1150 emit_ptr (logbuffer, buffer);
1151 emit_value (logbuffer, size);
1153 memcpy (logbuffer->data, name, nlen);
1154 logbuffer->data += nlen;
1156 EXIT_LOG (logbuffer);
1157 process_requests (prof);
1161 throw_exc (MonoProfiler *prof, MonoObject *object)
1163 int do_bt = (nocalls && runtime_inited && !notraces)? TYPE_EXCEPTION_BT: 0;
1166 LogBuffer *logbuffer;
1169 logbuffer = ensure_logbuf (16 + MAX_FRAMES * 8);
1170 now = current_time ();
1171 ENTER_LOG (logbuffer, "throw");
1172 emit_byte (logbuffer, do_bt | TYPE_EXCEPTION);
1173 emit_time (logbuffer, now);
1174 emit_obj (logbuffer, object);
1176 emit_bt (logbuffer, &data);
1177 EXIT_LOG (logbuffer);
1178 process_requests (prof);
1182 clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
1185 LogBuffer *logbuffer = ensure_logbuf (16);
1186 now = current_time ();
1187 ENTER_LOG (logbuffer, "clause");
1188 emit_byte (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
1189 emit_time (logbuffer, now);
1190 emit_value (logbuffer, clause_type);
1191 emit_value (logbuffer, clause_num);
1192 emit_method (logbuffer, method);
1193 EXIT_LOG (logbuffer);
1197 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
1199 int do_bt = (nocalls && runtime_inited && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION)? TYPE_MONITOR_BT: 0;
1202 LogBuffer *logbuffer;
1205 logbuffer = ensure_logbuf (16 + MAX_FRAMES * 8);
1206 now = current_time ();
1207 ENTER_LOG (logbuffer, "monitor");
1208 emit_byte (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
1209 emit_time (logbuffer, now);
1210 emit_obj (logbuffer, object);
1212 emit_bt (logbuffer, &data);
1213 EXIT_LOG (logbuffer);
1214 process_requests (profiler);
1218 thread_start (MonoProfiler *prof, uintptr_t tid)
1220 //printf ("thread start %p\n", (void*)tid);
1225 thread_end (MonoProfiler *prof, uintptr_t tid)
1228 if (TLS_GET (tlsbuffer))
1229 dump_buffer (prof, TLS_GET (tlsbuffer));
1231 TLS_SET (tlsbuffer, NULL);
1235 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
1237 int len = strlen (name) + 1;
1239 LogBuffer *logbuffer;
1240 logbuffer = ensure_logbuf (10 + len);
1241 now = current_time ();
1242 ENTER_LOG (logbuffer, "tname");
1243 emit_byte (logbuffer, TYPE_METADATA);
1244 emit_time (logbuffer, now);
1245 emit_byte (logbuffer, TYPE_THREAD);
1246 emit_ptr (logbuffer, (void*)tid);
1247 emit_value (logbuffer, 0); /* flags */
1248 memcpy (logbuffer->data, name, len);
1249 logbuffer->data += len;
1250 EXIT_LOG (logbuffer);
1262 AsyncFrameInfo *data;
1266 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
1268 AsyncFrameData *frame = data;
1269 if (frame->count < num_frames) {
1270 frame->data [frame->count].method = method;
1271 frame->data [frame->count].domain = domain;
1272 frame->data [frame->count].base_address = base_address;
1273 frame->data [frame->count].offset = offset;
1274 // printf ("In %d at %p (dom %p) (native: %p)\n", frame->count, method, domain, base_address);
1277 return frame->count == num_frames;
1281 (type | frame count), tid, time, ip, [method, domain, base address, offset] * frames
1283 #define SAMPLE_EVENT_SIZE_IN_SLOTS(FRAMES) (4 + (FRAMES) * 4)
1286 mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
1289 AsyncFrameInfo frames [num_frames];
1290 AsyncFrameData bt_data = { 0, &frames [0]};
1292 uintptr_t *data, *new_data, *old_data;
1298 now = current_time ();
1300 mono_stack_walk_async_safe (&async_walk_stack, context, &bt_data);
1302 elapsed = (now - profiler->startup_time) / 10000;
1306 snprintf (buf, sizeof (buf), "hit at %p in thread %p after %llu ms\n", ip, (void*)thread_id (), (unsigned long long int)elapsed/100);
1308 ign_res (write (2, buf, len));
1310 sbuf = profiler->stat_buffers;
1313 /* flush the buffer at 1 second intervals */
1314 if (sbuf->data > sbuf->buf && (elapsed - sbuf->buf [2]) > 100000) {
1317 /* overflow: 400 slots is a big enough number to reduce the chance of losing this event if many
1318 * threads hit this same spot at the same time
1320 if (timedout || (sbuf->data + 400 >= sbuf->data_end)) {
1321 StatBuffer *oldsb, *foundsb;
1322 sbuf = create_stat_buffer ();
1324 oldsb = profiler->stat_buffers;
1326 foundsb = InterlockedCompareExchangePointer ((void * volatile*)&profiler->stat_buffers, sbuf, oldsb);
1327 } while (foundsb != oldsb);
1329 ign_res (write (2, "overflow\n", 9));
1330 /* notify the helper thread */
1331 if (sbuf->next->next) {
1333 ign_res (write (profiler->pipes [1], &c, 1));
1335 ign_res (write (2, "notify\n", 7));
1339 old_data = sbuf->data;
1340 new_data = old_data + SAMPLE_EVENT_SIZE_IN_SLOTS (bt_data.count);
1341 data = InterlockedCompareExchangePointer ((void * volatile*)&sbuf->data, new_data, old_data);
1342 } while (data != old_data);
1343 if (old_data >= sbuf->data_end)
1344 return; /* lost event */
1345 old_data [0] = 1 | (sample_type << 16) | (bt_data.count << 8);
1346 old_data [1] = thread_id ();
1347 old_data [2] = elapsed;
1348 old_data [3] = (uintptr_t)ip;
1349 for (i = 0; i < bt_data.count; ++i) {
1350 old_data [4 + 4 * i + 0] = (uintptr_t)frames [i].method;
1351 old_data [4 + 4 * i + 1] = (uintptr_t)frames [i].domain;
1352 old_data [4 + 4 * i + 2] = (uintptr_t)frames [i].base_address;
1353 old_data [4 + 4 * i + 3] = (uintptr_t)frames [i].offset;
1357 static uintptr_t *code_pages = 0;
1358 static int num_code_pages = 0;
1359 static int size_code_pages = 0;
1360 #define CPAGE_SHIFT (9)
1361 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
1362 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
1363 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
1366 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
1369 uintptr_t start_pos;
1370 start_pos = (page >> CPAGE_SHIFT) % hsize;
1373 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
1375 } else if (!hash [i]) {
1382 } while (i != start_pos);
1383 /* should not happen */
1384 printf ("failed code page store\n");
1389 add_code_pointer (uintptr_t ip)
1392 if (num_code_pages * 2 >= size_code_pages) {
1394 uintptr_t old_size = size_code_pages;
1395 size_code_pages *= 2;
1396 if (size_code_pages == 0)
1397 size_code_pages = 16;
1398 n = calloc (sizeof (uintptr_t) * size_code_pages, 1);
1399 for (i = 0; i < old_size; ++i) {
1401 add_code_page (n, size_code_pages, code_pages [i]);
1407 num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
1410 #if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
1412 dump_ubin (const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
1415 LogBuffer *logbuffer;
1417 len = strlen (filename) + 1;
1418 now = current_time ();
1419 logbuffer = ensure_logbuf (20 + len);
1420 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
1421 emit_time (logbuffer, now);
1422 emit_svalue (logbuffer, load_addr);
1423 emit_uvalue (logbuffer, offset);
1424 emit_uvalue (logbuffer, size);
1425 memcpy (logbuffer->data, filename, len);
1426 logbuffer->data += len;
1431 dump_usym (const char *name, uintptr_t value, uintptr_t size)
1433 LogBuffer *logbuffer;
1435 len = strlen (name) + 1;
1436 logbuffer = ensure_logbuf (20 + len);
1437 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
1438 emit_ptr (logbuffer, (void*)value);
1439 emit_value (logbuffer, size);
1440 memcpy (logbuffer->data, name, len);
1441 logbuffer->data += len;
1446 #if SIZEOF_VOID_P == 4
1447 #define ELF_WSIZE 32
1449 #define ELF_WSIZE 64
1452 #define ElfW(type) _ElfW (Elf, ELF_WSIZE, type)
1453 #define _ElfW(e,w,t) _ElfW_1 (e, w, _##t)
1454 #define _ElfW_1(e,w,t) e##w##t
1458 dump_elf_symbols (ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
1461 for (i = 0; i < num_symbols; ++i) {
1463 sym = strtab + symbols [i].st_name;
1464 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
1466 //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
1467 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
1472 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
1479 ElfW(Shdr) *sheader;
1480 ElfW(Shdr) *shstrtabh;
1481 ElfW(Shdr) *symtabh = NULL;
1482 ElfW(Shdr) *strtabh = NULL;
1483 ElfW(Sym) *symbols = NULL;
1487 fd = open (filename, O_RDONLY);
1490 if (fstat (fd, &statb) != 0) {
1494 file_size = statb.st_size;
1495 data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
1497 if (data == MAP_FAILED)
1500 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
1501 header->e_ident [EI_MAG1] != ELFMAG1 ||
1502 header->e_ident [EI_MAG2] != ELFMAG2 ||
1503 header->e_ident [EI_MAG3] != ELFMAG3 ) {
1504 munmap (data, file_size);
1507 sheader = (void*)((char*)data + header->e_shoff);
1508 shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
1509 strtab = (const char*)data + shstrtabh->sh_offset;
1510 for (i = 0; i < header->e_shnum; ++i) {
1511 //printf ("section header: %d\n", sheader->sh_type);
1512 if (sheader->sh_type == SHT_SYMTAB) {
1514 strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
1515 /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
1518 sheader = (void*)((char*)sheader + header->e_shentsize);
1520 if (!symtabh || !strtabh) {
1521 munmap (data, file_size);
1524 strtab = (const char*)data + strtabh->sh_offset;
1525 num_symbols = symtabh->sh_size / symtabh->sh_entsize;
1526 symbols = (void*)((char*)data + symtabh->sh_offset);
1527 dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
1528 munmap (data, file_size);
1533 #if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
1535 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
1537 MonoProfiler *prof = data;
1539 const char *filename;
1541 char *a = (void*)info->dlpi_addr;
1543 ElfW(Dyn) *dyn = NULL;
1544 ElfW(Sym) *symtab = NULL;
1545 ElfW(Word) *hash_table = NULL;
1546 ElfW(Ehdr) *header = NULL;
1547 const char* strtab = NULL;
1548 for (obj = prof->binary_objects; obj; obj = obj->next) {
1552 filename = info->dlpi_name;
1555 if (!info->dlpi_addr && !filename [0]) {
1556 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
1562 obj = calloc (sizeof (BinaryObject), 1);
1563 obj->addr = (void*)info->dlpi_addr;
1564 obj->name = pstrdup (filename);
1565 obj->next = prof->binary_objects;
1566 prof->binary_objects = obj;
1567 //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
1569 for (i = 0; i < info->dlpi_phnum; ++i) {
1570 //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);
1571 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
1572 header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
1573 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
1574 header->e_ident [EI_MAG1] != ELFMAG1 ||
1575 header->e_ident [EI_MAG2] != ELFMAG2 ||
1576 header->e_ident [EI_MAG3] != ELFMAG3 ) {
1579 dump_ubin (filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
1580 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
1581 dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
1584 if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
1586 if (!info->dlpi_name || !info->dlpi_name[0])
1590 for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
1591 if (dyn [i].d_tag == DT_SYMTAB) {
1592 if (symtab && do_debug)
1593 printf ("multiple symtabs: %d\n", i);
1594 symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
1595 } else if (dyn [i].d_tag == DT_HASH) {
1596 hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
1597 } else if (dyn [i].d_tag == DT_STRTAB) {
1598 strtab = (const char*)(a + dyn [i].d_un.d_ptr);
1603 num_sym = hash_table [1];
1604 dump_elf_symbols (symtab, num_sym, strtab, (void*)info->dlpi_addr);
1609 load_binaries (MonoProfiler *prof)
1611 dl_iterate_phdr (elf_dl_callback, prof);
1616 load_binaries (MonoProfiler *prof)
1623 symbol_for (uintptr_t code)
1626 void *ip = (void*)code;
1628 if (dladdr (ip, &di)) {
1630 return di.dli_sname;
1633 names = backtrace_symbols (&ip, 1);
1635 const char* p = names [0];
1646 dump_unmanaged_coderefs (MonoProfiler *prof)
1649 const char* last_symbol;
1650 uintptr_t addr, page_end;
1652 if (load_binaries (prof))
1654 for (i = 0; i < size_code_pages; ++i) {
1656 if (!code_pages [i] || code_pages [i] & 1)
1659 addr = CPAGE_ADDR (code_pages [i]);
1660 page_end = addr + CPAGE_SIZE;
1661 code_pages [i] |= 1;
1662 /* we dump the symbols for the whole page */
1663 for (; addr < page_end; addr += 16) {
1664 sym = symbol_for (addr);
1665 if (sym && sym == last_symbol)
1670 dump_usym (sym, addr, 0); /* let's not guess the size */
1671 //printf ("found symbol at %p: %s\n", (void*)addr, sym);
1677 dump_sample_hits_inner (MonoProfiler *prof, StatBuffer *sbuf, int recurse, GPtrArray **array);
1680 dump_sample_hits (MonoProfiler *prof, StatBuffer *sbuf, int recurse)
1682 GPtrArray *array = NULL;
1683 dump_sample_hits_inner (prof, sbuf, recurse, &array);
1687 g_ptr_array_sort (array, g_direct_equal);
1688 for (i = 0; i < array->len; ++i) {
1689 MonoJitInfo *cur = array->pdata [i];
1691 if (i > 0 && array->pdata [i - 1] == cur)
1693 method_jitted (prof, mono_jit_info_get_method (cur), cur, MONO_PROFILE_OK);
1699 dump_sample_hits_inner (MonoProfiler *prof, StatBuffer *sbuf, int recurse, GPtrArray **array)
1702 LogBuffer *logbuffer;
1705 if (recurse && sbuf->next) {
1706 dump_sample_hits_inner (prof, sbuf->next, 1, array);
1707 free_buffer (sbuf->next, sbuf->next->size);
1710 for (sample = sbuf->buf; sample < sbuf->data;) {
1712 int count = sample [0] & 0xff;
1713 int mbt_count = (sample [0] & 0xff00) >> 8;
1714 int type = sample [0] >> 16;
1715 uintptr_t *managed_sample_base = sample + count + 3;
1717 if (sample + SAMPLE_EVENT_SIZE_IN_SLOTS (mbt_count) > sbuf->data)
1720 for (i = 0; i < mbt_count; ++i) {
1721 MonoMethod *method = (MonoMethod*)managed_sample_base [i * 4 + 0];
1722 MonoDomain *domain = (MonoDomain*)managed_sample_base [i * 4 + 1];
1723 void *address = (void*)managed_sample_base [i * 4 + 2];
1726 MonoJitInfo *ji = mono_jit_info_table_find (domain, address);
1728 managed_sample_base [i * 4 + 0] = (uintptr_t)mono_jit_info_get_method (ji);
1730 *array = g_ptr_array_new ();
1731 g_ptr_array_add (*array, ji);
1735 logbuffer = ensure_logbuf (20 + count * 8);
1736 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
1737 emit_value (logbuffer, type);
1738 emit_uvalue (logbuffer, prof->startup_time + (uint64_t)sample [2] * (uint64_t)10000);
1739 emit_value (logbuffer, count);
1740 for (i = 0; i < count; ++i) {
1741 emit_ptr (logbuffer, (void*)sample [i + 3]);
1742 add_code_pointer (sample [i + 3]);
1745 sample += count + 3;
1746 /* new in data version 6 */
1747 emit_uvalue (logbuffer, mbt_count);
1748 for (i = 0; i < mbt_count; ++i) {
1749 emit_method (logbuffer, (void*)sample [i * 4]); /* method */
1750 emit_svalue (logbuffer, 0); /* il offset will always be 0 from now on */
1751 emit_svalue (logbuffer, sample [i * 4 + 3]); /* native offset */
1753 sample += 4 * mbt_count;
1755 dump_unmanaged_coderefs (prof);
1759 #ifndef __NR_perf_event_open
1761 #define __NR_perf_event_open 364
1763 #define __NR_perf_event_open 241
1768 mono_cpu_count (void)
1771 #ifdef PLATFORM_ANDROID
1772 /* Android tries really hard to save power by powering off CPUs on SMP phones which
1773 * means the normal way to query cpu count returns a wrong value with userspace API.
1774 * Instead we use /sys entries to query the actual hardware CPU count.
1776 char buffer[8] = {'\0'};
1777 int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
1778 /* Format of the /sys entry is a cpulist of indexes which in the case
1779 * of present is always of the form "0-(n-1)" when there is more than
1780 * 1 core, n being the number of CPU cores in the system. Otherwise
1781 * the value is simply 0
1783 if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
1784 count = strtol (((char*)buffer) + 2, NULL, 10);
1790 #ifdef _SC_NPROCESSORS_ONLN
1791 count = sysconf (_SC_NPROCESSORS_ONLN);
1798 size_t len = sizeof (int);
1801 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
1808 GetSystemInfo (&info);
1809 return info.dwNumberOfProcessors;
1818 unsigned int prev_pos;
1820 struct perf_event_mmap_page *page_desc;
1823 static PerfData *perf_data = NULL;
1824 static int num_perf;
1825 #define PERF_PAGES_SHIFT 4
1826 static int num_pages = 1 << PERF_PAGES_SHIFT;
1827 static unsigned int mmap_mask;
1830 struct perf_event_header h;
1840 perf_event_syscall (struct perf_event_attr *attr, pid_t pid, int cpu, int group_fd, unsigned long flags)
1842 attr->size = PERF_ATTR_SIZE_VER0;
1843 //printf ("perf attr size: %d\n", attr->size);
1844 #if defined(__x86_64__)
1845 return syscall(/*__NR_perf_event_open*/ 298, attr, pid, cpu, group_fd, flags);
1846 #elif defined(__i386__)
1847 return syscall(/*__NR_perf_event_open*/ 336, attr, pid, cpu, group_fd, flags);
1848 #elif defined(__arm__)
1849 return syscall(/*__NR_perf_event_open*/ 364, attr, pid, cpu, group_fd, flags);
1856 setup_perf_map (PerfData *perf)
1858 perf->mmap_base = mmap (NULL, (num_pages + 1) * getpagesize (), PROT_READ|PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
1859 if (perf->mmap_base == MAP_FAILED) {
1861 printf ("failed mmap\n");
1864 perf->page_desc = perf->mmap_base;
1866 printf ("mmap version: %d\n", perf->page_desc->version);
1871 dump_perf_hits (MonoProfiler *prof, void *buf, int size)
1873 LogBuffer *logbuffer;
1874 void *end = (char*)buf + size;
1876 int pid = getpid ();
1882 if (pid != s->pid) {
1884 printf ("event for different pid: %d\n", s->pid);
1885 buf = (char*)buf + s->h.size;
1888 /*ip = (void*)s->ip;
1889 printf ("sample: %d, size: %d, ip: %p (%s), timestamp: %llu, nframes: %llu\n",
1890 s->h.type, s->h.size, ip, symbol_for (ip), s->timestamp, s->nframes);*/
1891 logbuffer = ensure_logbuf (20 + s->nframes * 8);
1892 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
1893 emit_value (logbuffer, sample_type);
1894 emit_uvalue (logbuffer, s->timestamp - prof->startup_time);
1895 emit_value (logbuffer, 1); /* count */
1896 emit_ptr (logbuffer, (void*)(uintptr_t)s->ip);
1897 /* no support here yet for the managed backtrace */
1898 emit_uvalue (logbuffer, 0);
1899 add_code_pointer (s->ip);
1900 buf = (char*)buf + s->h.size;
1904 printf ("dumped %d samples\n", samples);
1905 dump_unmanaged_coderefs (prof);
1908 /* read events from the ring buffer */
1910 read_perf_mmap (MonoProfiler* prof, int cpu)
1912 PerfData *perf = perf_data + cpu;
1914 unsigned char *data = (unsigned char*)perf->mmap_base + getpagesize ();
1915 unsigned int head = perf->page_desc->data_head;
1919 mono_memory_read_barrier ();
1921 old = perf->prev_pos;
1925 printf ("lost mmap events: old: %d, head: %d\n", old, head);
1929 if ((old & mmap_mask) + size != (head & mmap_mask)) {
1930 buf = data + (old & mmap_mask);
1931 size = mmap_mask + 1 - (old & mmap_mask);
1933 /* size bytes at buf */
1935 printf ("found1 bytes of events: %d\n", size);
1936 dump_perf_hits (prof, buf, size);
1938 buf = data + (old & mmap_mask);
1940 /* size bytes at buf */
1942 printf ("found bytes of events: %d\n", size);
1943 dump_perf_hits (prof, buf, size);
1945 perf->prev_pos = old;
1946 perf->page_desc->data_tail = old;
1951 setup_perf_event_for_cpu (PerfData *perf, int cpu)
1953 struct perf_event_attr attr;
1954 memset (&attr, 0, sizeof (attr));
1955 attr.type = PERF_TYPE_HARDWARE;
1956 switch (sample_type) {
1957 case SAMPLE_CYCLES: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
1958 case SAMPLE_INSTRUCTIONS: attr.config = PERF_COUNT_HW_INSTRUCTIONS; break;
1959 case SAMPLE_CACHE_MISSES: attr.config = PERF_COUNT_HW_CACHE_MISSES; break;
1960 case SAMPLE_CACHE_REFS: attr.config = PERF_COUNT_HW_CACHE_REFERENCES; break;
1961 case SAMPLE_BRANCHES: attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS; break;
1962 case SAMPLE_BRANCH_MISSES: attr.config = PERF_COUNT_HW_BRANCH_MISSES; break;
1963 default: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
1965 attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD | PERF_SAMPLE_TIME;
1966 // attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
1967 attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING | PERF_FORMAT_ID;
1970 attr.sample_freq = sample_freq;
1972 perf->perf_fd = perf_event_syscall (&attr, getpid (), cpu, -1, 0);
1974 printf ("perf fd: %d, freq: %d, event: %llu\n", perf->perf_fd, sample_freq, attr.config);
1975 if (perf->perf_fd < 0) {
1976 if (perf->perf_fd == -EPERM) {
1977 fprintf (stderr, "Perf syscall denied, do \"echo 1 > /proc/sys/kernel/perf_event_paranoid\" as root to enable.\n");
1980 perror ("open perf event");
1984 if (!setup_perf_map (perf)) {
1985 close (perf->perf_fd);
1993 setup_perf_event (void)
1996 mmap_mask = num_pages * getpagesize () - 1;
1997 num_perf = mono_cpu_count ();
1998 perf_data = calloc (num_perf, sizeof (PerfData));
1999 for (i = 0; i < num_perf; ++i) {
2000 count += setup_perf_event_for_cpu (perf_data + i, i);
2009 #endif /* USE_PERF_EVENTS */
2011 #ifndef DISABLE_HELPER_THREAD
2013 typedef struct MonoCounterAgent {
2014 MonoCounter *counter;
2015 // MonoCounterAgent specific data :
2020 struct MonoCounterAgent *next;
2023 static MonoCounterAgent* counters;
2024 static gboolean counters_initialized = FALSE;
2025 static int counters_index = 1;
2026 static mono_mutex_t counters_mutex;
2029 counters_add_agent (MonoCounter *counter)
2031 MonoCounterAgent *agent, *item;
2033 if (!counters_initialized)
2036 mono_mutex_lock (&counters_mutex);
2038 for (agent = counters; agent; agent = agent->next) {
2039 if (agent->counter == counter) {
2040 agent->value_size = 0;
2042 free (agent->value);
2043 agent->value = NULL;
2045 mono_mutex_unlock (&counters_mutex);
2050 agent = malloc (sizeof (MonoCounterAgent));
2051 agent->counter = counter;
2052 agent->value = NULL;
2053 agent->value_size = 0;
2054 agent->index = counters_index++;
2067 mono_mutex_unlock (&counters_mutex);
2071 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
2073 counters_add_agent (counter);
2078 counters_init (MonoProfiler *profiler)
2080 assert (!counters_initialized);
2082 mono_mutex_init (&counters_mutex);
2084 counters_initialized = TRUE;
2086 mono_counters_on_register (&counters_add_agent);
2087 mono_counters_foreach (counters_init_foreach_callback, NULL);
2091 counters_emit (MonoProfiler *profiler)
2093 MonoCounterAgent *agent;
2094 LogBuffer *logbuffer;
2095 int size = 1 + 5, len = 0;
2097 if (!counters_initialized)
2100 mono_mutex_lock (&counters_mutex);
2102 for (agent = counters; agent; agent = agent->next) {
2106 size += strlen (mono_counter_get_name (agent->counter)) + 1 + 5 * 5;
2111 mono_mutex_unlock (&counters_mutex);
2115 logbuffer = ensure_logbuf (size);
2117 ENTER_LOG (logbuffer, "counters");
2118 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2119 emit_value (logbuffer, len);
2120 for (agent = counters; agent; agent = agent->next) {
2126 name = mono_counter_get_name (agent->counter);
2127 emit_value (logbuffer, mono_counter_get_section (agent->counter));
2128 emit_string (logbuffer, name, strlen (name) + 1);
2129 emit_value (logbuffer, mono_counter_get_type (agent->counter));
2130 emit_value (logbuffer, mono_counter_get_unit (agent->counter));
2131 emit_value (logbuffer, mono_counter_get_variance (agent->counter));
2132 emit_value (logbuffer, agent->index);
2136 EXIT_LOG (logbuffer);
2138 safe_dump (profiler, ensure_logbuf (0));
2140 mono_mutex_unlock (&counters_mutex);
2144 counters_sample (MonoProfiler *profiler, uint64_t timestamp)
2146 MonoCounterAgent *agent;
2147 MonoCounter *counter;
2148 LogBuffer *logbuffer;
2154 if (!counters_initialized)
2157 counters_emit (profiler);
2160 buffer = calloc (1, buffer_size);
2162 mono_mutex_lock (&counters_mutex);
2165 for (agent = counters; agent; agent = agent->next)
2166 size += 10 * 2 + mono_counter_get_size (agent->counter);
2168 logbuffer = ensure_logbuf (size);
2170 ENTER_LOG (logbuffer, "counters");
2171 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
2172 emit_uvalue (logbuffer, timestamp);
2173 for (agent = counters; agent; agent = agent->next) {
2176 counter = agent->counter;
2178 size = mono_counter_get_size (counter);
2180 continue; // FIXME error
2181 } else if (size > buffer_size) {
2183 buffer = realloc (buffer, buffer_size);
2186 memset (buffer, 0, buffer_size);
2188 if (mono_counters_sample (counter, buffer, size) < 0)
2189 continue; // FIXME error
2191 type = mono_counter_get_type (counter);
2193 if (!agent->value) {
2194 agent->value = calloc (1, size);
2195 agent->value_size = size;
2197 if (type == MONO_COUNTER_STRING) {
2198 if (strcmp (agent->value, buffer) == 0)
2201 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
2206 emit_uvalue (logbuffer, agent->index);
2207 emit_uvalue (logbuffer, type);
2209 case MONO_COUNTER_INT:
2210 #if SIZEOF_VOID_P == 4
2211 case MONO_COUNTER_WORD:
2213 emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
2215 case MONO_COUNTER_UINT:
2216 emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
2218 case MONO_COUNTER_TIME_INTERVAL:
2219 case MONO_COUNTER_LONG:
2220 #if SIZEOF_VOID_P == 8
2221 case MONO_COUNTER_WORD:
2223 emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
2225 case MONO_COUNTER_ULONG:
2226 emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
2228 case MONO_COUNTER_DOUBLE:
2229 emit_double (logbuffer, *(double*)buffer);
2231 case MONO_COUNTER_STRING:
2233 emit_byte (logbuffer, 0);
2235 emit_byte (logbuffer, 1);
2236 emit_string (logbuffer, (char*)buffer, size);
2243 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
2244 agent->value = realloc (agent->value, size);
2245 agent->value_size = size;
2249 memcpy (agent->value, buffer, size);
2253 emit_value (logbuffer, 0);
2254 EXIT_LOG (logbuffer);
2256 safe_dump (profiler, ensure_logbuf (0));
2258 mono_mutex_unlock (&counters_mutex);
2261 typedef struct _PerfCounterAgent PerfCounterAgent;
2262 struct _PerfCounterAgent {
2263 PerfCounterAgent *next;
2265 char *category_name;
2274 static PerfCounterAgent *perfcounters = NULL;
2277 perfcounters_emit (MonoProfiler *profiler)
2279 PerfCounterAgent *pcagent;
2280 LogBuffer *logbuffer;
2281 int size = 1 + 5, len = 0;
2283 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2284 if (pcagent->emitted)
2287 size += strlen (pcagent->name) + 1 + 5 * 5;
2294 logbuffer = ensure_logbuf (size);
2296 ENTER_LOG (logbuffer, "perfcounters");
2297 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2298 emit_value (logbuffer, len);
2299 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2300 if (pcagent->emitted)
2303 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
2304 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
2305 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
2306 emit_value (logbuffer, MONO_COUNTER_LONG);
2307 emit_value (logbuffer, MONO_COUNTER_RAW);
2308 emit_value (logbuffer, MONO_COUNTER_VARIABLE);
2309 emit_value (logbuffer, pcagent->index);
2311 pcagent->emitted = 1;
2313 EXIT_LOG (logbuffer);
2315 safe_dump (profiler, ensure_logbuf (0));
2319 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
2321 PerfCounterAgent *pcagent;
2323 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2324 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
2326 if (pcagent->value == value)
2329 pcagent->value = value;
2330 pcagent->updated = 1;
2331 pcagent->deleted = 0;
2335 pcagent = g_new0 (PerfCounterAgent, 1);
2336 pcagent->next = perfcounters;
2337 pcagent->index = counters_index++;
2338 pcagent->category_name = g_strdup (category_name);
2339 pcagent->name = g_strdup (name);
2340 pcagent->type = (int) type;
2341 pcagent->value = value;
2342 pcagent->emitted = 0;
2343 pcagent->updated = 1;
2344 pcagent->deleted = 0;
2346 perfcounters = pcagent;
2352 perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp)
2354 PerfCounterAgent *pcagent;
2355 LogBuffer *logbuffer;
2358 if (!counters_initialized)
2361 mono_mutex_lock (&counters_mutex);
2363 /* mark all perfcounters as deleted, foreach will unmark them as necessary */
2364 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
2365 pcagent->deleted = 1;
2367 mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
2369 perfcounters_emit (profiler);
2373 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2374 if (pcagent->deleted || !pcagent->updated)
2376 size += 10 * 2 + sizeof (gint64);
2379 logbuffer = ensure_logbuf (size);
2381 ENTER_LOG (logbuffer, "perfcounters");
2382 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
2383 emit_uvalue (logbuffer, timestamp);
2384 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2385 if (pcagent->deleted || !pcagent->updated)
2387 emit_uvalue (logbuffer, pcagent->index);
2388 emit_uvalue (logbuffer, MONO_COUNTER_LONG);
2389 emit_svalue (logbuffer, pcagent->value);
2391 pcagent->updated = 0;
2394 emit_value (logbuffer, 0);
2395 EXIT_LOG (logbuffer);
2397 safe_dump (profiler, ensure_logbuf (0));
2399 mono_mutex_unlock (&counters_mutex);
2403 counters_and_perfcounters_sample (MonoProfiler *prof)
2405 static uint64_t start = -1;
2409 start = current_time ();
2411 now = current_time ();
2412 counters_sample (prof, (now - start) / 1000/ 1000);
2413 perfcounters_sample (prof, (now - start) / 1000/ 1000);
2416 #endif /* DISABLE_HELPER_THREAD */
2419 log_shutdown (MonoProfiler *prof)
2422 #ifndef DISABLE_HELPER_THREAD
2423 counters_and_perfcounters_sample (prof);
2425 if (prof->command_port) {
2428 ign_res (write (prof->pipes [1], &c, 1));
2429 pthread_join (prof->helper_thread, &res);
2435 for (i = 0; i < num_perf; ++i)
2436 read_perf_mmap (prof, i);
2439 dump_sample_hits (prof, prof->stat_buffers, 1);
2441 if (TLS_GET (tlsbuffer))
2442 dump_buffer (prof, TLS_GET (tlsbuffer));
2443 TLS_SET (tlsbuffer, NULL);
2445 #if defined (HAVE_SYS_ZLIB)
2447 gzclose (prof->gzfile);
2449 if (prof->pipe_output)
2450 pclose (prof->file);
2452 fclose (prof->file);
2457 new_filename (const char* filename)
2459 time_t t = time (NULL);
2460 int pid = process_id ();
2465 int count_dates = 0;
2469 for (p = filename; *p; p++) {
2480 if (!count_dates && !count_pids)
2481 return pstrdup (filename);
2482 snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
2484 snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
2485 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
2486 s_date = strlen (time_buf);
2487 s_pid = strlen (pid_buf);
2488 d = res = malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
2489 for (p = filename; *p; p++) {
2496 strcpy (d, time_buf);
2499 } else if (*p == 'p') {
2500 strcpy (d, pid_buf);
2503 } else if (*p == '%') {
2515 #ifndef DISABLE_HELPER_THREAD
2517 //this is exposed by the JIT, but it's not meant to be a supported API for now.
2518 extern void mono_threads_attach_tools_thread (void);
2521 helper_thread (void* arg)
2523 MonoProfiler* prof = arg;
2527 MonoThread *thread = NULL;
2529 mono_threads_attach_tools_thread ();
2530 //fprintf (stderr, "Server listening\n");
2531 command_socket = -1;
2537 FD_SET (prof->server_socket, &rfds);
2538 max_fd = prof->server_socket;
2539 FD_SET (prof->pipes [0], &rfds);
2540 if (max_fd < prof->pipes [0])
2541 max_fd = prof->pipes [0];
2542 if (command_socket >= 0) {
2543 FD_SET (command_socket, &rfds);
2544 if (max_fd < command_socket)
2545 max_fd = command_socket;
2550 for ( i = 0; i < num_perf; ++i) {
2551 if (perf_data [i].perf_fd < 0)
2553 FD_SET (perf_data [i].perf_fd, &rfds);
2554 if (max_fd < perf_data [i].perf_fd)
2555 max_fd = perf_data [i].perf_fd;
2560 counters_and_perfcounters_sample (prof);
2564 len = select (max_fd + 1, &rfds, NULL, NULL, &tv);
2570 g_warning ("Error in proflog server: %s", strerror (errno));
2574 if (FD_ISSET (prof->pipes [0], &rfds)) {
2576 int r = read (prof->pipes [0], &c, 1);
2577 if (r == 1 && c == 0) {
2578 StatBuffer *sbufbase = prof->stat_buffers;
2580 if (!sbufbase->next)
2582 sbuf = sbufbase->next->next;
2583 sbufbase->next->next = NULL;
2585 fprintf (stderr, "stat buffer dump\n");
2587 dump_sample_hits (prof, sbuf, 1);
2588 free_buffer (sbuf, sbuf->size);
2589 safe_dump (prof, ensure_logbuf (0));
2593 /* time to shut down */
2595 mono_thread_detach (thread);
2597 fprintf (stderr, "helper shutdown\n");
2601 for ( i = 0; i < num_perf; ++i) {
2602 if (perf_data [i].perf_fd < 0)
2604 if (FD_ISSET (perf_data [i].perf_fd, &rfds))
2605 read_perf_mmap (prof, i);
2609 safe_dump (prof, ensure_logbuf (0));
2615 for ( i = 0; i < num_perf; ++i) {
2616 if (perf_data [i].perf_fd < 0)
2618 if (FD_ISSET (perf_data [i].perf_fd, &rfds)) {
2619 read_perf_mmap (prof, i);
2620 safe_dump (prof, ensure_logbuf (0));
2625 if (command_socket >= 0 && FD_ISSET (command_socket, &rfds)) {
2626 len = read (command_socket, buf, sizeof (buf) - 1);
2630 close (command_socket);
2631 command_socket = -1;
2635 if (strcmp (buf, "heapshot\n") == 0) {
2636 heapshot_requested = 1;
2637 //fprintf (stderr, "perform heapshot\n");
2638 if (runtime_inited && !thread) {
2639 thread = mono_thread_attach (mono_get_root_domain ());
2640 /*fprintf (stderr, "attached\n");*/
2643 process_requests (prof);
2644 mono_thread_detach (thread);
2650 if (!FD_ISSET (prof->server_socket, &rfds)) {
2653 command_socket = accept (prof->server_socket, NULL, NULL);
2654 if (command_socket < 0)
2656 //fprintf (stderr, "Accepted connection\n");
2662 start_helper_thread (MonoProfiler* prof)
2664 struct sockaddr_in server_address;
2667 if (pipe (prof->pipes) < 0) {
2668 fprintf (stderr, "Cannot create pipe\n");
2671 prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
2672 if (prof->server_socket < 0) {
2673 fprintf (stderr, "Cannot create server socket\n");
2676 memset (&server_address, 0, sizeof (server_address));
2677 server_address.sin_family = AF_INET;
2678 server_address.sin_addr.s_addr = INADDR_ANY;
2679 server_address.sin_port = htons (prof->command_port);
2680 if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) < 0) {
2681 fprintf (stderr, "Cannot bind server socket, port: %d: %s\n", prof->command_port, strerror (errno));
2682 close (prof->server_socket);
2685 if (listen (prof->server_socket, 1) < 0) {
2686 fprintf (stderr, "Cannot listen server socket\n");
2687 close (prof->server_socket);
2690 slen = sizeof (server_address);
2691 if (getsockname (prof->server_socket, (struct sockaddr *)&server_address, &slen) == 0) {
2692 prof->command_port = ntohs (server_address.sin_port);
2693 /*fprintf (stderr, "Assigned server port: %d\n", prof->command_port);*/
2696 r = pthread_create (&prof->helper_thread, NULL, helper_thread, prof);
2698 close (prof->server_socket);
2705 static MonoProfiler*
2706 create_profiler (const char *filename)
2710 int force_delete = 0;
2711 int need_helper_thread = 0;
2712 prof = calloc (1, sizeof (MonoProfiler));
2714 prof->command_port = command_port;
2715 if (filename && *filename == '-') {
2721 filename = "|mprof-report -";
2723 filename = "output.mlpd";
2724 nf = (char*)filename;
2726 nf = new_filename (filename);
2728 int s = strlen (nf) + 32;
2729 char *p = malloc (s);
2730 snprintf (p, s, "|mprof-report '--out=%s' -", nf);
2736 prof->file = popen (nf + 1, "w");
2737 prof->pipe_output = 1;
2738 } else if (*nf == '#') {
2739 int fd = strtol (nf + 1, NULL, 10);
2740 prof->file = fdopen (fd, "a");
2744 prof->file = fopen (nf, "wb");
2747 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
2750 #if defined (HAVE_SYS_ZLIB)
2752 prof->gzfile = gzdopen (fileno (prof->file), "wb");
2755 if (sample_type && !do_mono_sample)
2756 need_helper_thread = setup_perf_event ();
2758 /* FIXME: warn if different freq or sample type */
2762 if (do_mono_sample) {
2763 prof->stat_buffers = create_stat_buffer ();
2764 need_helper_thread = 1;
2766 if (do_counters && !need_helper_thread) {
2767 need_helper_thread = 1;
2769 #ifndef DISABLE_HELPER_THREAD
2770 if (hs_mode_ondemand || need_helper_thread) {
2771 if (!start_helper_thread (prof))
2772 prof->command_port = 0;
2775 if (hs_mode_ondemand)
2776 fprintf (stderr, "Ondemand heapshot unavailable on this arch.\n");
2778 prof->startup_time = current_time ();
2786 printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
2787 printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
2788 printf ("Options:\n");
2789 printf ("\thelp show this usage info\n");
2790 printf ("\t[no]alloc enable/disable recording allocation info\n");
2791 printf ("\t[no]calls enable/disable recording enter/leave method events\n");
2792 printf ("\theapshot[=MODE] record heap shot info (by default at each major collection)\n");
2793 printf ("\t MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
2794 printf ("\tcounters sample counters every 1s\n");
2795 printf ("\tsample[=TYPE] use statistical sampling mode (by default cycles/1000)\n");
2796 printf ("\t TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
2797 printf ("\t TYPE can be followed by /FREQUENCY\n");
2798 printf ("\ttime=fast use a faster (but more inaccurate) timer\n");
2799 printf ("\tmaxframes=NUM collect up to NUM stack frames\n");
2800 printf ("\tcalldepth=NUM ignore method events for call chain depth bigger than NUM\n");
2801 printf ("\toutput=FILENAME write the data to file FILENAME (-FILENAME to overwrite)\n");
2802 printf ("\toutput=|PROGRAM write the data to the stdin of PROGRAM\n");
2803 printf ("\t %%t is subtituted with date and time, %%p with the pid\n");
2804 printf ("\treport create a report instead of writing the raw data to a file\n");
2805 printf ("\tzip compress the output data\n");
2806 printf ("\tport=PORTNUM use PORTNUM for the listening command server\n");
2812 match_option (const char* p, const char *opt, char **rval)
2814 int len = strlen (opt);
2815 if (strncmp (p, opt, len) == 0) {
2817 if (p [len] == '=' && p [len + 1]) {
2818 const char *opt = p + len + 1;
2819 const char *end = strchr (opt, ',');
2827 val = malloc (l + 1);
2828 memcpy (val, opt, l);
2833 if (p [len] == 0 || p [len] == ',') {
2835 return p + len + (p [len] == ',');
2853 static const SampleMode sample_modes [] = {
2854 {"cycles", SAMPLE_CYCLES},
2855 {"instr", SAMPLE_INSTRUCTIONS},
2856 {"cachemiss", SAMPLE_CACHE_MISSES},
2857 {"cacherefs", SAMPLE_CACHE_REFS},
2858 {"branches", SAMPLE_BRANCHES},
2859 {"branchmiss", SAMPLE_BRANCH_MISSES},
2864 set_sample_mode (char* val, int allow_empty)
2867 char *maybe_freq = NULL;
2869 const SampleMode *smode = sample_modes;
2870 #ifndef USE_PERF_EVENTS
2873 if (allow_empty && !val) {
2874 sample_type = SAMPLE_CYCLES;
2878 if (strcmp (val, "mono") == 0) {
2880 sample_type = SAMPLE_CYCLES;
2884 for (smode = sample_modes; smode->name; smode++) {
2885 int l = strlen (smode->name);
2886 if (strncmp (val, smode->name, l) == 0) {
2887 sample_type = smode->sample_mode;
2888 maybe_freq = val + l;
2894 if (*maybe_freq == '/') {
2895 count = strtoul (maybe_freq + 1, &end, 10);
2896 if (maybe_freq + 1 == end)
2898 sample_freq = count;
2899 } else if (*maybe_freq != 0) {
2908 set_hsmode (char* val, int allow_empty)
2912 if (allow_empty && !val)
2914 if (strcmp (val, "ondemand") == 0) {
2915 hs_mode_ondemand = 1;
2919 count = strtoul (val, &end, 10);
2922 if (strcmp (end, "ms") == 0)
2924 else if (strcmp (end, "gc") == 0)
2932 * declaration to silence the compiler: this is the entry point that
2933 * mono will load from the shared library and call.
2936 mono_profiler_startup (const char *desc);
2939 mono_profiler_startup_log (const char *desc);
2942 * this is the entry point that will be used when the profiler
2943 * is embedded inside the main executable.
2946 mono_profiler_startup_log (const char *desc)
2948 mono_profiler_startup (desc);
2952 mono_profiler_startup (const char *desc)
2955 char *filename = NULL;
2959 int calls_enabled = 0;
2960 int allocs_enabled = 0;
2961 int only_counters = 0;
2962 int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
2963 MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
2964 MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
2965 MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS;
2968 if (strncmp (p, "log", 3))
2973 for (; *p; p = opt) {
2979 if ((opt = match_option (p, "help", NULL)) != p) {
2983 if ((opt = match_option (p, "calls", NULL)) != p) {
2987 if ((opt = match_option (p, "nocalls", NULL)) != p) {
2988 events &= ~MONO_PROFILE_ENTER_LEAVE;
2992 if ((opt = match_option (p, "alloc", NULL)) != p) {
2996 if ((opt = match_option (p, "noalloc", NULL)) != p) {
2997 events &= ~MONO_PROFILE_ALLOCATIONS;
3000 if ((opt = match_option (p, "time", &val)) != p) {
3001 if (strcmp (val, "fast") == 0)
3003 else if (strcmp (val, "null") == 0)
3010 if ((opt = match_option (p, "report", NULL)) != p) {
3014 if ((opt = match_option (p, "debug", NULL)) != p) {
3018 if ((opt = match_option (p, "sampling-real", NULL)) != p) {
3019 sampling_mode = MONO_PROFILER_STAT_MODE_REAL;
3022 if ((opt = match_option (p, "sampling-process", NULL)) != p) {
3023 sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
3026 if ((opt = match_option (p, "heapshot", &val)) != p) {
3027 events &= ~MONO_PROFILE_ALLOCATIONS;
3028 events &= ~MONO_PROFILE_ENTER_LEAVE;
3031 set_hsmode (val, 1);
3034 if ((opt = match_option (p, "sample", &val)) != p) {
3035 events &= ~MONO_PROFILE_ALLOCATIONS;
3036 events &= ~MONO_PROFILE_ENTER_LEAVE;
3038 set_sample_mode (val, 1);
3041 if ((opt = match_option (p, "hsmode", &val)) != p) {
3042 fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
3043 set_hsmode (val, 0);
3046 if ((opt = match_option (p, "zip", NULL)) != p) {
3050 if ((opt = match_option (p, "output", &val)) != p) {
3054 if ((opt = match_option (p, "port", &val)) != p) {
3056 command_port = strtoul (val, &end, 10);
3060 if ((opt = match_option (p, "maxframes", &val)) != p) {
3062 num_frames = strtoul (val, &end, 10);
3063 if (num_frames > MAX_FRAMES)
3064 num_frames = MAX_FRAMES;
3066 notraces = num_frames == 0;
3069 if ((opt = match_option (p, "calldepth", &val)) != p) {
3071 max_call_depth = strtoul (val, &end, 10);
3075 if ((opt = match_option (p, "counters", NULL)) != p) {
3079 if ((opt = match_option (p, "countersonly", NULL)) != p) {
3088 if (calls_enabled) {
3089 events |= MONO_PROFILE_ENTER_LEAVE;
3093 events |= MONO_PROFILE_ALLOCATIONS;
3096 utils_init (fast_time);
3098 prof = create_profiler (filename);
3103 mono_profiler_install (prof, log_shutdown);
3104 mono_profiler_install_gc (gc_event, gc_resize);
3105 mono_profiler_install_allocation (gc_alloc);
3106 mono_profiler_install_gc_moves (gc_moves);
3107 mono_profiler_install_gc_roots (gc_handle, gc_roots);
3108 mono_profiler_install_class (NULL, class_loaded, NULL, NULL);
3109 mono_profiler_install_module (NULL, image_loaded, NULL, NULL);
3110 mono_profiler_install_thread (thread_start, thread_end);
3111 mono_profiler_install_thread_name (thread_name);
3112 mono_profiler_install_enter_leave (method_enter, method_leave);
3113 mono_profiler_install_jit_end (method_jitted);
3114 mono_profiler_install_code_buffer_new (code_buffer_new);
3115 mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
3116 mono_profiler_install_monitor (monitor_event);
3117 mono_profiler_install_runtime_initialized (runtime_initialized);
3120 if (do_mono_sample && sample_type == SAMPLE_CYCLES && !only_counters) {
3121 events |= MONO_PROFILE_STATISTICAL;
3122 mono_profiler_set_statistical_mode (sampling_mode, 1000000 / sample_freq);
3123 mono_profiler_install_statistical (mono_sample_hit);
3126 mono_profiler_set_events (events);
3128 TLS_INIT (tlsbuffer);