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 exception format:
245 * type: TYPE_EXCEPTION
246 * exinfo: TYPE_EXCEPTION_BT flag and one of: TYPE_THROW, TYPE_CLAUSE
247 * [time diff: uleb128] nanoseconds since last timing
248 * if exinfo.low3bits == TYPE_CLAUSE
249 * [clause type: uleb128] finally/catch/fault/filter
250 * [clause num: uleb128] the clause number in the method header
251 * [method: sleb128] MonoMethod* as a pointer difference from the last such
252 * pointer or the buffer method_base
253 * if exinfo.low3bits == TYPE_THROW
254 * [object: sleb128] the object that was thrown as a difference from obj_base
255 * If the TYPE_EXCEPTION_BT flag is set, a backtrace follows.
257 * type monitor format:
259 * exinfo: TYPE_MONITOR_BT flag and one of: MONO_PROFILER_MONITOR_(CONTENTION|FAIL|DONE)
260 * [time diff: uleb128] nanoseconds since last timing
261 * [object: sleb128] the lock object as a difference from obj_base
262 * if exinfo.low3bits == MONO_PROFILER_MONITOR_CONTENTION
263 * If the TYPE_MONITOR_BT flag is set, a backtrace follows.
267 * exinfo: one of TYPE_HEAP_START, TYPE_HEAP_END, TYPE_HEAP_OBJECT, TYPE_HEAP_ROOT
268 * if exinfo == TYPE_HEAP_START
269 * [time diff: uleb128] nanoseconds since last timing
270 * if exinfo == TYPE_HEAP_END
271 * [time diff: uleb128] nanoseconds since last timing
272 * if exinfo == TYPE_HEAP_OBJECT
273 * [object: sleb128] the object as a difference from obj_base
274 * [class: sleb128] the object MonoClass* as a difference from ptr_base
275 * [size: uleb128] size of the object on the heap
276 * [num_refs: uleb128] number of object references
277 * if (format version > 1) each referenced objref is preceded by a
278 * uleb128 encoded offset: the first offset is from the object address
279 * and each next offset is relative to the previous one
280 * [objrefs: sleb128]+ object referenced as a difference from obj_base
281 * The same object can appear multiple times, but only the first time
282 * with size != 0: in the other cases this data will only be used to
283 * provide additional referenced objects.
284 * if exinfo == TYPE_HEAP_ROOT
285 * [num_roots: uleb128] number of root references
286 * [num_gc: uleb128] number of major gcs
287 * [object: sleb128] the object as a difference from obj_base
288 * [root_type: uleb128] the root_type: MonoProfileGCRootType (profiler.h)
289 * [extra_info: uleb128] the extra_info value
290 * object, root_type and extra_info are repeated num_roots times
294 * exinfo: one of TYPE_SAMPLE_HIT, TYPE_SAMPLE_USYM, TYPE_SAMPLE_UBIN, TYPE_SAMPLE_COUNTERS_DESC, TYPE_SAMPLE_COUNTERS
295 * if exinfo == TYPE_SAMPLE_HIT
296 * [sample_type: uleb128] type of sample (SAMPLE_*)
297 * [timestamp: uleb128] nanoseconds since startup (note: different from other timestamps!)
298 * [count: uleb128] number of following instruction addresses
299 * [ip: sleb128]* instruction pointer as difference from ptr_base
300 * if (format_version > 5)
301 * [mbt_count: uleb128] number of managed backtrace info triplets (method + IL offset + native offset)
302 * [method: sleb128]* MonoMethod* as a pointer difference from the last such
303 * pointer or the buffer method_base (the first such method can be also indentified by ip, but this is not neccessarily true)
304 * [il_offset: sleb128]* IL offset inside method where the hit occurred
305 * [native_offset: sleb128]* native offset inside method where the hit occurred
306 * if exinfo == TYPE_SAMPLE_USYM
307 * [address: sleb128] symbol address as a difference from ptr_base
308 * [size: uleb128] symbol size (may be 0 if unknown)
309 * [name: string] symbol name
310 * if exinfo == TYPE_SAMPLE_UBIN
311 * [time diff: uleb128] nanoseconds since last timing
312 * [address: sleb128] address where binary has been loaded
313 * [offset: uleb128] file offset of mapping (the same file can be mapped multiple times)
314 * [size: uleb128] memory size
315 * [name: string] binary name
316 * if exinfo == TYPE_SAMPLE_COUNTERS_DESC
317 * [len: uleb128] number of counters
319 * [section: uleb128] section of counter
320 * if section == MONO_COUNTER_PERFCOUNTERS:
321 * [section_name: string] section name of counter
322 * [name: string] name of counter
323 * [type: uleb128] type of counter
324 * [unit: uleb128] unit of counter
325 * [variance: uleb128] variance of counter
326 * [index: uleb128] unique index of counter
327 * if exinfo == TYPE_SAMPLE_COUNTERS
328 * [timestamp: uleb128] sampling timestamp
330 * [index: uleb128] unique index of counter
333 * [type: uleb128] type of counter value
336 * [0: uleb128] 0 -> value is null
338 * [1: uleb128] 1 -> value is not null
339 * [value: string] counter value
341 * [value: uleb128/sleb128/double] counter value, can be sleb128, uleb128 or double (determined by using type)
349 uintptr_t method_base;
350 uintptr_t last_method;
353 unsigned char* data_end;
358 unsigned char buf [1];
362 ign_res (int G_GNUC_UNUSED unused, ...)
366 #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++;}
367 #define EXIT_LOG(lb) (lb)->locked--;
369 typedef struct _StatBuffer StatBuffer;
378 typedef struct _BinaryObject BinaryObject;
380 struct _BinaryObject {
386 struct _MonoProfiler {
388 StatBuffer *stat_buffers;
390 #if defined (HAVE_SYS_ZLIB)
393 uint64_t startup_time;
395 int last_gc_gen_started;
400 pthread_t helper_thread;
402 BinaryObject *binary_objects;
406 #define TLS_SET(x,y) TlsSetValue(x, y)
407 #define TLS_GET(x) ((LogBuffer *) TlsGetValue(x))
408 #define TLS_INIT(x) x = TlsAlloc ()
409 static int tlsbuffer;
411 #define TLS_SET(x,y) x = y
414 static __thread LogBuffer* tlsbuffer = NULL;
416 #define TLS_SET(x,y) pthread_setspecific(x, y)
417 #define TLS_GET(x) ((LogBuffer *) pthread_getspecific(x))
418 #define TLS_INIT(x) pthread_key_create(&x, NULL)
419 static pthread_key_t tlsbuffer;
422 static void safe_dump (MonoProfiler *profiler, LogBuffer *logbuffer);
425 pstrdup (const char *s)
427 int len = strlen (s) + 1;
428 char *p = malloc (len);
434 create_stat_buffer (void)
436 StatBuffer* buf = alloc_buffer (BUFFER_SIZE);
437 buf->size = BUFFER_SIZE;
438 buf->data_end = (uintptr_t*)((unsigned char*)buf + buf->size);
439 buf->data = buf->buf;
446 LogBuffer* buf = alloc_buffer (BUFFER_SIZE);
447 buf->size = BUFFER_SIZE;
448 buf->time_base = current_time ();
449 buf->last_time = buf->time_base;
450 buf->data_end = (unsigned char*)buf + buf->size;
451 buf->data = buf->buf;
458 LogBuffer *logbuffer;
459 if (TLS_GET (tlsbuffer))
461 logbuffer = create_buffer ();
462 TLS_SET (tlsbuffer, logbuffer);
463 logbuffer->thread_id = thread_id ();
464 //printf ("thread %p at time %llu\n", (void*)logbuffer->thread_id, logbuffer->time_base);
468 ensure_logbuf (int bytes)
470 LogBuffer *old = TLS_GET (tlsbuffer);
471 if (old && old->data + bytes + 100 < old->data_end)
473 TLS_SET (tlsbuffer, NULL);
475 TLS_GET (tlsbuffer)->next = old;
477 TLS_GET (tlsbuffer)->call_depth = old->call_depth;
478 //printf ("new logbuffer\n");
479 return TLS_GET (tlsbuffer);
483 emit_byte (LogBuffer *logbuffer, int value)
485 logbuffer->data [0] = value;
487 assert (logbuffer->data <= logbuffer->data_end);
491 emit_value (LogBuffer *logbuffer, int value)
493 encode_uleb128 (value, logbuffer->data, &logbuffer->data);
494 assert (logbuffer->data <= logbuffer->data_end);
498 emit_time (LogBuffer *logbuffer, uint64_t value)
500 uint64_t tdiff = value - logbuffer->last_time;
502 if (value < logbuffer->last_time)
503 printf ("time went backwards\n");
504 //if (tdiff > 1000000)
505 // printf ("large time offset: %llu\n", tdiff);
507 encode_uleb128 (tdiff, logbuffer->data, &logbuffer->data);
508 /*if (tdiff != decode_uleb128 (p, &p))
509 printf ("incorrect encoding: %llu\n", tdiff);*/
510 logbuffer->last_time = value;
511 assert (logbuffer->data <= logbuffer->data_end);
515 emit_svalue (LogBuffer *logbuffer, int64_t value)
517 encode_sleb128 (value, logbuffer->data, &logbuffer->data);
518 assert (logbuffer->data <= logbuffer->data_end);
522 emit_uvalue (LogBuffer *logbuffer, uint64_t value)
524 encode_uleb128 (value, logbuffer->data, &logbuffer->data);
525 assert (logbuffer->data <= logbuffer->data_end);
529 emit_ptr (LogBuffer *logbuffer, void *ptr)
531 if (!logbuffer->ptr_base)
532 logbuffer->ptr_base = (uintptr_t)ptr;
533 emit_svalue (logbuffer, (intptr_t)ptr - logbuffer->ptr_base);
534 assert (logbuffer->data <= logbuffer->data_end);
538 emit_method (LogBuffer *logbuffer, void *method)
540 if (!logbuffer->method_base) {
541 logbuffer->method_base = (intptr_t)method;
542 logbuffer->last_method = (intptr_t)method;
544 encode_sleb128 ((intptr_t)((char*)method - (char*)logbuffer->last_method), logbuffer->data, &logbuffer->data);
545 logbuffer->last_method = (intptr_t)method;
546 assert (logbuffer->data <= logbuffer->data_end);
550 emit_obj (LogBuffer *logbuffer, void *ptr)
552 if (!logbuffer->obj_base)
553 logbuffer->obj_base = (uintptr_t)ptr >> 3;
554 emit_svalue (logbuffer, ((uintptr_t)ptr >> 3) - logbuffer->obj_base);
555 assert (logbuffer->data <= logbuffer->data_end);
559 emit_string (LogBuffer *logbuffer, const char *str, size_t size)
563 for (; i < size; i++) {
566 emit_byte (logbuffer, str [i]);
569 emit_byte (logbuffer, '\0');
573 emit_double (LogBuffer *logbuffer, double value)
576 unsigned char buffer[8];
577 memcpy (buffer, &value, 8);
578 #if G_BYTE_ORDER == G_BIG_ENDIAN
579 for (i = 7; i >= 0; i--)
581 for (i = 0; i < 8; i++)
583 emit_byte (logbuffer, buffer[i]);
587 write_int16 (char *buf, int32_t value)
590 for (i = 0; i < 2; ++i) {
598 write_int32 (char *buf, int32_t value)
601 for (i = 0; i < 4; ++i) {
609 write_int64 (char *buf, int64_t value)
612 for (i = 0; i < 8; ++i) {
620 dump_header (MonoProfiler *profiler)
624 p = write_int32 (p, LOG_HEADER_ID);
625 *p++ = LOG_VERSION_MAJOR;
626 *p++ = LOG_VERSION_MINOR;
627 *p++ = LOG_DATA_VERSION;
628 *p++ = sizeof (void*);
629 p = write_int64 (p, ((uint64_t)time (NULL)) * 1000); /* startup time */
630 p = write_int32 (p, get_timer_overhead ()); /* timer overhead */
631 p = write_int32 (p, 0); /* flags */
632 p = write_int32 (p, process_id ()); /* pid */
633 p = write_int16 (p, profiler->command_port); /* port */
634 p = write_int16 (p, 0); /* opsystem */
635 #if defined (HAVE_SYS_ZLIB)
636 if (profiler->gzfile) {
637 gzwrite (profiler->gzfile, hbuf, p - hbuf);
639 fwrite (hbuf, p - hbuf, 1, profiler->file);
642 fwrite (hbuf, p - hbuf, 1, profiler->file);
643 fflush (profiler->file);
648 dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
653 dump_buffer (profiler, buf->next);
654 p = write_int32 (p, BUF_ID);
655 p = write_int32 (p, buf->data - buf->buf);
656 p = write_int64 (p, buf->time_base);
657 p = write_int64 (p, buf->ptr_base);
658 p = write_int64 (p, buf->obj_base);
659 p = write_int64 (p, buf->thread_id);
660 p = write_int64 (p, buf->method_base);
661 #if defined (HAVE_SYS_ZLIB)
662 if (profiler->gzfile) {
663 gzwrite (profiler->gzfile, hbuf, p - hbuf);
664 gzwrite (profiler->gzfile, buf->buf, buf->data - buf->buf);
667 fwrite (hbuf, p - hbuf, 1, profiler->file);
668 fwrite (buf->buf, buf->data - buf->buf, 1, profiler->file);
669 fflush (profiler->file);
670 #if defined (HAVE_SYS_ZLIB)
673 free_buffer (buf, buf->size);
677 process_requests (MonoProfiler *profiler)
679 if (heapshot_requested)
680 mono_gc_collect (mono_gc_max_generation ());
683 static void counters_init (MonoProfiler *profiler);
684 static void counters_sample (MonoProfiler *profiler, uint64_t timestamp);
687 runtime_initialized (MonoProfiler *profiler)
690 #ifndef DISABLE_HELPER_THREAD
691 counters_init (profiler);
692 counters_sample (profiler, 0);
694 /* ensure the main thread data and startup are available soon */
695 safe_dump (profiler, ensure_logbuf (0));
699 * Can be called only at safe callback locations.
702 safe_dump (MonoProfiler *profiler, LogBuffer *logbuffer)
704 int cd = logbuffer->call_depth;
706 dump_buffer (profiler, TLS_GET (tlsbuffer));
708 TLS_SET (tlsbuffer, NULL);
710 TLS_GET (tlsbuffer)->call_depth = cd;
714 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
717 uintptr_t last_offset = 0;
718 //const char *name = mono_class_get_name (klass);
719 LogBuffer *logbuffer = ensure_logbuf (20 + num * 8);
720 emit_byte (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
721 emit_obj (logbuffer, obj);
722 emit_ptr (logbuffer, klass);
723 /* account for object alignment in the heap */
726 emit_value (logbuffer, size);
727 emit_value (logbuffer, num);
728 for (i = 0; i < num; ++i) {
729 emit_value (logbuffer, offsets [i] - last_offset);
730 last_offset = offsets [i];
731 emit_obj (logbuffer, refs [i]);
734 // printf ("obj: %p, klass: %s, refs: %d, size: %d\n", obj, name, (int)num, (int)size);
738 static unsigned int hs_mode_ms = 0;
739 static unsigned int hs_mode_gc = 0;
740 static unsigned int hs_mode_ondemand = 0;
741 static unsigned int gc_count = 0;
742 static uint64_t last_hs_time = 0;
745 heap_walk (MonoProfiler *profiler)
749 LogBuffer *logbuffer;
752 logbuffer = ensure_logbuf (10);
753 now = current_time ();
754 if (hs_mode_ms && (now - last_hs_time)/1000000 >= hs_mode_ms)
756 else if (hs_mode_gc && (gc_count % hs_mode_gc) == 0)
758 else if (hs_mode_ondemand)
759 do_walk = heapshot_requested;
760 else if (!hs_mode_ms && !hs_mode_gc && profiler->last_gc_gen_started == mono_gc_max_generation ())
765 heapshot_requested = 0;
766 emit_byte (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
767 emit_time (logbuffer, now);
768 mono_gc_walk_heap (0, gc_reference, NULL);
769 logbuffer = ensure_logbuf (10);
770 now = current_time ();
771 emit_byte (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
772 emit_time (logbuffer, now);
777 gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation) {
779 LogBuffer *logbuffer = ensure_logbuf (10);
780 now = current_time ();
781 ENTER_LOG (logbuffer, "gcevent");
782 emit_byte (logbuffer, TYPE_GC_EVENT | TYPE_GC);
783 emit_time (logbuffer, now);
784 emit_value (logbuffer, ev);
785 emit_value (logbuffer, generation);
786 /* to deal with nested gen1 after gen0 started */
787 if (ev == MONO_GC_EVENT_START) {
788 profiler->last_gc_gen_started = generation;
789 if (generation == mono_gc_max_generation ())
792 if (ev == MONO_GC_EVENT_PRE_START_WORLD)
793 heap_walk (profiler);
794 EXIT_LOG (logbuffer);
795 if (ev == MONO_GC_EVENT_POST_START_WORLD)
796 safe_dump (profiler, logbuffer);
797 //printf ("gc event %d for generation %d\n", ev, generation);
801 gc_resize (MonoProfiler *profiler, int64_t new_size) {
803 LogBuffer *logbuffer = ensure_logbuf (10);
804 now = current_time ();
805 ENTER_LOG (logbuffer, "gcresize");
806 emit_byte (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
807 emit_time (logbuffer, now);
808 emit_value (logbuffer, new_size);
809 //printf ("gc resized to %lld\n", new_size);
810 EXIT_LOG (logbuffer);
813 #define MAX_FRAMES 32
816 MonoMethod* methods [MAX_FRAMES];
817 int32_t il_offsets [MAX_FRAMES];
818 int32_t native_offsets [MAX_FRAMES];
820 static int num_frames = MAX_FRAMES;
823 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
825 FrameData *frame = data;
826 if (method && frame->count < num_frames) {
827 frame->il_offsets [frame->count] = il_offset;
828 frame->native_offsets [frame->count] = native_offset;
829 frame->methods [frame->count++] = method;
830 //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
832 return frame->count == num_frames;
836 * a note about stack walks: they can cause more profiler events to fire,
837 * so we need to make sure they don't happen after we started emitting an
838 * event, hence the collect_bt/emit_bt split.
841 collect_bt (FrameData *data)
844 mono_stack_walk_no_il (walk_stack, data);
848 emit_bt (LogBuffer *logbuffer, FrameData *data)
850 /* FIXME: this is actually tons of data and we should
851 * just output it the first time and use an id the next
853 if (data->count > num_frames)
854 printf ("bad num frames: %d\n", data->count);
855 emit_value (logbuffer, 0); /* flags */
856 emit_value (logbuffer, data->count);
857 //if (*p != data.count) {
858 // 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);}
859 while (data->count) {
860 emit_ptr (logbuffer, data->methods [--data->count]);
865 gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
869 int do_bt = (nocalls && runtime_inited && !notraces)? TYPE_ALLOC_BT: 0;
871 LogBuffer *logbuffer;
872 len = mono_object_get_size (obj);
873 /* account for object alignment in the heap */
878 logbuffer = ensure_logbuf (32 + MAX_FRAMES * 8);
879 now = current_time ();
880 ENTER_LOG (logbuffer, "gcalloc");
881 emit_byte (logbuffer, do_bt | TYPE_ALLOC);
882 emit_time (logbuffer, now);
883 emit_ptr (logbuffer, klass);
884 emit_obj (logbuffer, obj);
885 emit_value (logbuffer, len);
887 emit_bt (logbuffer, &data);
888 EXIT_LOG (logbuffer);
890 safe_dump (prof, logbuffer);
891 process_requests (prof);
892 //printf ("gc alloc %s at %p\n", mono_class_get_name (klass), obj);
896 gc_moves (MonoProfiler *prof, void **objects, int num)
900 LogBuffer *logbuffer = ensure_logbuf (10 + num * 8);
901 now = current_time ();
902 ENTER_LOG (logbuffer, "gcmove");
903 emit_byte (logbuffer, TYPE_GC_MOVE | TYPE_GC);
904 emit_time (logbuffer, now);
905 emit_value (logbuffer, num);
906 for (i = 0; i < num; ++i)
907 emit_obj (logbuffer, objects [i]);
908 //printf ("gc moved %d objects\n", num/2);
909 EXIT_LOG (logbuffer);
913 gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
916 LogBuffer *logbuffer = ensure_logbuf (5 + num * 18);
917 ENTER_LOG (logbuffer, "gcroots");
918 emit_byte (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
919 emit_value (logbuffer, num);
920 emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
921 for (i = 0; i < num; ++i) {
922 emit_obj (logbuffer, objects [i]);
923 emit_value (logbuffer, root_types [i]);
924 emit_value (logbuffer, extra_info [i]);
926 EXIT_LOG (logbuffer);
930 gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
933 LogBuffer *logbuffer = ensure_logbuf (16);
934 now = current_time ();
935 ENTER_LOG (logbuffer, "gchandle");
936 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
937 emit_byte (logbuffer, TYPE_GC_HANDLE_CREATED | TYPE_GC);
938 else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
939 emit_byte (logbuffer, TYPE_GC_HANDLE_DESTROYED | TYPE_GC);
942 emit_time (logbuffer, now);
943 emit_value (logbuffer, type);
944 emit_value (logbuffer, handle);
945 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
946 emit_obj (logbuffer, obj);
947 EXIT_LOG (logbuffer);
948 process_requests (prof);
952 push_nesting (char *p, MonoClass *klass)
957 nesting = mono_class_get_nesting_type (klass);
959 p = push_nesting (p, nesting);
963 name = mono_class_get_name (klass);
964 nspace = mono_class_get_namespace (klass);
967 p += strlen (nspace);
977 type_name (MonoClass *klass)
981 push_nesting (buf, klass);
982 p = malloc (strlen (buf) + 1);
988 image_loaded (MonoProfiler *prof, MonoImage *image, int result)
993 LogBuffer *logbuffer;
994 if (result != MONO_PROFILE_OK)
996 name = mono_image_get_filename (image);
997 nlen = strlen (name) + 1;
998 logbuffer = ensure_logbuf (16 + nlen);
999 now = current_time ();
1000 ENTER_LOG (logbuffer, "image");
1001 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1002 emit_time (logbuffer, now);
1003 emit_byte (logbuffer, TYPE_IMAGE);
1004 emit_ptr (logbuffer, image);
1005 emit_value (logbuffer, 0); /* flags */
1006 memcpy (logbuffer->data, name, nlen);
1007 logbuffer->data += nlen;
1008 //printf ("loaded image %p (%s)\n", image, name);
1009 EXIT_LOG (logbuffer);
1010 if (logbuffer->next)
1011 safe_dump (prof, logbuffer);
1012 process_requests (prof);
1016 class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
1022 LogBuffer *logbuffer;
1023 if (result != MONO_PROFILE_OK)
1026 name = mono_type_get_name (mono_class_get_type (klass));
1028 name = type_name (klass);
1029 nlen = strlen (name) + 1;
1030 image = mono_class_get_image (klass);
1031 logbuffer = ensure_logbuf (24 + nlen);
1032 now = current_time ();
1033 ENTER_LOG (logbuffer, "class");
1034 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1035 emit_time (logbuffer, now);
1036 emit_byte (logbuffer, TYPE_CLASS);
1037 emit_ptr (logbuffer, klass);
1038 emit_ptr (logbuffer, image);
1039 emit_value (logbuffer, 0); /* flags */
1040 memcpy (logbuffer->data, name, nlen);
1041 logbuffer->data += nlen;
1042 //printf ("loaded class %p (%s)\n", klass, name);
1047 EXIT_LOG (logbuffer);
1048 if (logbuffer->next)
1049 safe_dump (prof, logbuffer);
1050 process_requests (prof);
1054 method_enter (MonoProfiler *prof, MonoMethod *method)
1057 LogBuffer *logbuffer = ensure_logbuf (16);
1058 if (logbuffer->call_depth++ > max_call_depth)
1060 now = current_time ();
1061 ENTER_LOG (logbuffer, "enter");
1062 emit_byte (logbuffer, TYPE_ENTER | TYPE_METHOD);
1063 emit_time (logbuffer, now);
1064 emit_method (logbuffer, method);
1065 EXIT_LOG (logbuffer);
1066 process_requests (prof);
1070 method_leave (MonoProfiler *prof, MonoMethod *method)
1073 LogBuffer *logbuffer = ensure_logbuf (16);
1074 if (--logbuffer->call_depth > max_call_depth)
1076 now = current_time ();
1077 ENTER_LOG (logbuffer, "leave");
1078 emit_byte (logbuffer, TYPE_LEAVE | TYPE_METHOD);
1079 emit_time (logbuffer, now);
1080 emit_method (logbuffer, method);
1081 EXIT_LOG (logbuffer);
1082 if (logbuffer->next)
1083 safe_dump (prof, logbuffer);
1084 process_requests (prof);
1088 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
1091 LogBuffer *logbuffer;
1094 logbuffer = ensure_logbuf (16);
1095 if (--logbuffer->call_depth > max_call_depth)
1097 now = current_time ();
1098 ENTER_LOG (logbuffer, "eleave");
1099 emit_byte (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
1100 emit_time (logbuffer, now);
1101 emit_method (logbuffer, method);
1102 EXIT_LOG (logbuffer);
1103 process_requests (prof);
1107 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo* jinfo, int result)
1112 LogBuffer *logbuffer;
1113 if (result != MONO_PROFILE_OK)
1115 name = mono_method_full_name (method, 1);
1116 nlen = strlen (name) + 1;
1117 logbuffer = ensure_logbuf (32 + nlen);
1118 now = current_time ();
1119 ENTER_LOG (logbuffer, "jit");
1120 emit_byte (logbuffer, TYPE_JIT | TYPE_METHOD);
1121 emit_time (logbuffer, now);
1122 emit_method (logbuffer, method);
1123 emit_ptr (logbuffer, mono_jit_info_get_code_start (jinfo));
1124 emit_value (logbuffer, mono_jit_info_get_code_size (jinfo));
1125 memcpy (logbuffer->data, name, nlen);
1126 logbuffer->data += nlen;
1128 EXIT_LOG (logbuffer);
1129 if (logbuffer->next)
1130 safe_dump (prof, logbuffer);
1131 process_requests (prof);
1135 throw_exc (MonoProfiler *prof, MonoObject *object)
1137 int do_bt = (nocalls && runtime_inited && !notraces)? TYPE_EXCEPTION_BT: 0;
1140 LogBuffer *logbuffer;
1143 logbuffer = ensure_logbuf (16 + MAX_FRAMES * 8);
1144 now = current_time ();
1145 ENTER_LOG (logbuffer, "throw");
1146 emit_byte (logbuffer, do_bt | TYPE_EXCEPTION);
1147 emit_time (logbuffer, now);
1148 emit_obj (logbuffer, object);
1150 emit_bt (logbuffer, &data);
1151 EXIT_LOG (logbuffer);
1152 process_requests (prof);
1156 clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
1159 LogBuffer *logbuffer = ensure_logbuf (16);
1160 now = current_time ();
1161 ENTER_LOG (logbuffer, "clause");
1162 emit_byte (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
1163 emit_time (logbuffer, now);
1164 emit_value (logbuffer, clause_type);
1165 emit_value (logbuffer, clause_num);
1166 emit_method (logbuffer, method);
1167 EXIT_LOG (logbuffer);
1171 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
1173 int do_bt = (nocalls && runtime_inited && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION)? TYPE_MONITOR_BT: 0;
1176 LogBuffer *logbuffer;
1179 logbuffer = ensure_logbuf (16 + MAX_FRAMES * 8);
1180 now = current_time ();
1181 ENTER_LOG (logbuffer, "monitor");
1182 emit_byte (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
1183 emit_time (logbuffer, now);
1184 emit_obj (logbuffer, object);
1186 emit_bt (logbuffer, &data);
1187 EXIT_LOG (logbuffer);
1188 process_requests (profiler);
1192 thread_start (MonoProfiler *prof, uintptr_t tid)
1194 //printf ("thread start %p\n", (void*)tid);
1199 thread_end (MonoProfiler *prof, uintptr_t tid)
1202 if (TLS_GET (tlsbuffer))
1203 dump_buffer (prof, TLS_GET (tlsbuffer));
1205 TLS_SET (tlsbuffer, NULL);
1209 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
1211 int len = strlen (name) + 1;
1213 LogBuffer *logbuffer;
1214 logbuffer = ensure_logbuf (10 + len);
1215 now = current_time ();
1216 ENTER_LOG (logbuffer, "tname");
1217 emit_byte (logbuffer, TYPE_METADATA);
1218 emit_time (logbuffer, now);
1219 emit_byte (logbuffer, TYPE_THREAD);
1220 emit_ptr (logbuffer, (void*)tid);
1221 emit_value (logbuffer, 0); /* flags */
1222 memcpy (logbuffer->data, name, len);
1223 logbuffer->data += len;
1224 EXIT_LOG (logbuffer);
1236 AsyncFrameInfo *data;
1240 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
1242 AsyncFrameData *frame = data;
1243 if (frame->count < num_frames) {
1244 frame->data [frame->count].method = method;
1245 frame->data [frame->count].domain = domain;
1246 frame->data [frame->count].base_address = base_address;
1247 frame->data [frame->count].offset = offset;
1248 // printf ("In %d at %p (dom %p) (native: %p)\n", frame->count, method, domain, base_address);
1251 return frame->count == num_frames;
1255 (type | frame count), tid, time, ip, [method, domain, base address, offset] * frames
1257 #define SAMPLE_EVENT_SIZE_IN_SLOTS(FRAMES) (4 + (FRAMES) * 4)
1260 mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
1263 AsyncFrameInfo frames [num_frames];
1264 AsyncFrameData bt_data = { 0, &frames [0]};
1266 uintptr_t *data, *new_data, *old_data;
1272 now = current_time ();
1274 mono_stack_walk_async_safe (&async_walk_stack, context, &bt_data);
1276 elapsed = (now - profiler->startup_time) / 10000;
1280 snprintf (buf, sizeof (buf), "hit at %p in thread %p after %llu ms\n", ip, (void*)thread_id (), (unsigned long long int)elapsed/100);
1282 ign_res (write (2, buf, len));
1284 sbuf = profiler->stat_buffers;
1287 /* flush the buffer at 1 second intervals */
1288 if (sbuf->data > sbuf->buf && (elapsed - sbuf->buf [2]) > 100000) {
1291 /* overflow: 400 slots is a big enough number to reduce the chance of losing this event if many
1292 * threads hit this same spot at the same time
1294 if (timedout || (sbuf->data + 400 >= sbuf->data_end)) {
1295 StatBuffer *oldsb, *foundsb;
1296 sbuf = create_stat_buffer ();
1298 oldsb = profiler->stat_buffers;
1300 foundsb = InterlockedCompareExchangePointer ((void * volatile*)&profiler->stat_buffers, sbuf, oldsb);
1301 } while (foundsb != oldsb);
1303 ign_res (write (2, "overflow\n", 9));
1304 /* notify the helper thread */
1305 if (sbuf->next->next) {
1307 ign_res (write (profiler->pipes [1], &c, 1));
1309 ign_res (write (2, "notify\n", 7));
1313 old_data = sbuf->data;
1314 new_data = old_data + SAMPLE_EVENT_SIZE_IN_SLOTS (bt_data.count);
1315 data = InterlockedCompareExchangePointer ((void * volatile*)&sbuf->data, new_data, old_data);
1316 } while (data != old_data);
1317 if (old_data >= sbuf->data_end)
1318 return; /* lost event */
1319 old_data [0] = 1 | (sample_type << 16) | (bt_data.count << 8);
1320 old_data [1] = thread_id ();
1321 old_data [2] = elapsed;
1322 old_data [3] = (uintptr_t)ip;
1323 for (i = 0; i < bt_data.count; ++i) {
1324 old_data [4 + 4 * i + 0] = (uintptr_t)frames [i].method;
1325 old_data [4 + 4 * i + 1] = (uintptr_t)frames [i].domain;
1326 old_data [4 + 4 * i + 2] = (uintptr_t)frames [i].base_address;
1327 old_data [4 + 4 * i + 3] = (uintptr_t)frames [i].offset;
1331 static uintptr_t *code_pages = 0;
1332 static int num_code_pages = 0;
1333 static int size_code_pages = 0;
1334 #define CPAGE_SHIFT (9)
1335 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
1336 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
1337 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
1340 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
1343 uintptr_t start_pos;
1344 start_pos = (page >> CPAGE_SHIFT) % hsize;
1347 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
1349 } else if (!hash [i]) {
1356 } while (i != start_pos);
1357 /* should not happen */
1358 printf ("failed code page store\n");
1363 add_code_pointer (uintptr_t ip)
1366 if (num_code_pages * 2 >= size_code_pages) {
1368 uintptr_t old_size = size_code_pages;
1369 size_code_pages *= 2;
1370 if (size_code_pages == 0)
1371 size_code_pages = 16;
1372 n = calloc (sizeof (uintptr_t) * size_code_pages, 1);
1373 for (i = 0; i < old_size; ++i) {
1375 add_code_page (n, size_code_pages, code_pages [i]);
1381 num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
1384 #if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
1386 dump_ubin (const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
1389 LogBuffer *logbuffer;
1391 len = strlen (filename) + 1;
1392 now = current_time ();
1393 logbuffer = ensure_logbuf (20 + len);
1394 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
1395 emit_time (logbuffer, now);
1396 emit_svalue (logbuffer, load_addr);
1397 emit_uvalue (logbuffer, offset);
1398 emit_uvalue (logbuffer, size);
1399 memcpy (logbuffer->data, filename, len);
1400 logbuffer->data += len;
1405 dump_usym (const char *name, uintptr_t value, uintptr_t size)
1407 LogBuffer *logbuffer;
1409 len = strlen (name) + 1;
1410 logbuffer = ensure_logbuf (20 + len);
1411 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
1412 emit_ptr (logbuffer, (void*)value);
1413 emit_value (logbuffer, size);
1414 memcpy (logbuffer->data, name, len);
1415 logbuffer->data += len;
1420 #if SIZEOF_VOID_P == 4
1421 #define ELF_WSIZE 32
1423 #define ELF_WSIZE 64
1426 #define ElfW(type) _ElfW (Elf, ELF_WSIZE, type)
1427 #define _ElfW(e,w,t) _ElfW_1 (e, w, _##t)
1428 #define _ElfW_1(e,w,t) e##w##t
1432 dump_elf_symbols (ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
1435 for (i = 0; i < num_symbols; ++i) {
1437 sym = strtab + symbols [i].st_name;
1438 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
1440 //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
1441 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
1446 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
1453 ElfW(Shdr) *sheader;
1454 ElfW(Shdr) *shstrtabh;
1455 ElfW(Shdr) *symtabh = NULL;
1456 ElfW(Shdr) *strtabh = NULL;
1457 ElfW(Sym) *symbols = NULL;
1461 fd = open (filename, O_RDONLY);
1464 if (fstat (fd, &statb) != 0) {
1468 file_size = statb.st_size;
1469 data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
1471 if (data == MAP_FAILED)
1474 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
1475 header->e_ident [EI_MAG1] != ELFMAG1 ||
1476 header->e_ident [EI_MAG2] != ELFMAG2 ||
1477 header->e_ident [EI_MAG3] != ELFMAG3 ) {
1478 munmap (data, file_size);
1481 sheader = (void*)((char*)data + header->e_shoff);
1482 shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
1483 strtab = (const char*)data + shstrtabh->sh_offset;
1484 for (i = 0; i < header->e_shnum; ++i) {
1485 //printf ("section header: %d\n", sheader->sh_type);
1486 if (sheader->sh_type == SHT_SYMTAB) {
1488 strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
1489 /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
1492 sheader = (void*)((char*)sheader + header->e_shentsize);
1494 if (!symtabh || !strtabh) {
1495 munmap (data, file_size);
1498 strtab = (const char*)data + strtabh->sh_offset;
1499 num_symbols = symtabh->sh_size / symtabh->sh_entsize;
1500 symbols = (void*)((char*)data + symtabh->sh_offset);
1501 dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
1502 munmap (data, file_size);
1507 #if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
1509 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
1511 MonoProfiler *prof = data;
1513 const char *filename;
1515 char *a = (void*)info->dlpi_addr;
1517 ElfW(Dyn) *dyn = NULL;
1518 ElfW(Sym) *symtab = NULL;
1519 ElfW(Word) *hash_table = NULL;
1520 ElfW(Ehdr) *header = NULL;
1521 const char* strtab = NULL;
1522 for (obj = prof->binary_objects; obj; obj = obj->next) {
1526 filename = info->dlpi_name;
1529 if (!info->dlpi_addr && !filename [0]) {
1530 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
1536 obj = calloc (sizeof (BinaryObject), 1);
1537 obj->addr = (void*)info->dlpi_addr;
1538 obj->name = pstrdup (filename);
1539 obj->next = prof->binary_objects;
1540 prof->binary_objects = obj;
1541 //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
1543 for (i = 0; i < info->dlpi_phnum; ++i) {
1544 //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);
1545 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
1546 header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
1547 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
1548 header->e_ident [EI_MAG1] != ELFMAG1 ||
1549 header->e_ident [EI_MAG2] != ELFMAG2 ||
1550 header->e_ident [EI_MAG3] != ELFMAG3 ) {
1553 dump_ubin (filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
1554 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
1555 dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
1558 if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
1560 if (!info->dlpi_name || !info->dlpi_name[0])
1564 for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
1565 if (dyn [i].d_tag == DT_SYMTAB) {
1566 if (symtab && do_debug)
1567 printf ("multiple symtabs: %d\n", i);
1568 symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
1569 } else if (dyn [i].d_tag == DT_HASH) {
1570 hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
1571 } else if (dyn [i].d_tag == DT_STRTAB) {
1572 strtab = (const char*)(a + dyn [i].d_un.d_ptr);
1577 num_sym = hash_table [1];
1578 dump_elf_symbols (symtab, num_sym, strtab, (void*)info->dlpi_addr);
1583 load_binaries (MonoProfiler *prof)
1585 dl_iterate_phdr (elf_dl_callback, prof);
1590 load_binaries (MonoProfiler *prof)
1597 symbol_for (uintptr_t code)
1600 void *ip = (void*)code;
1602 if (dladdr (ip, &di)) {
1604 return di.dli_sname;
1607 names = backtrace_symbols (&ip, 1);
1609 const char* p = names [0];
1620 dump_unmanaged_coderefs (MonoProfiler *prof)
1623 const char* last_symbol;
1624 uintptr_t addr, page_end;
1626 if (load_binaries (prof))
1628 for (i = 0; i < size_code_pages; ++i) {
1630 if (!code_pages [i] || code_pages [i] & 1)
1633 addr = CPAGE_ADDR (code_pages [i]);
1634 page_end = addr + CPAGE_SIZE;
1635 code_pages [i] |= 1;
1636 /* we dump the symbols for the whole page */
1637 for (; addr < page_end; addr += 16) {
1638 sym = symbol_for (addr);
1639 if (sym && sym == last_symbol)
1644 dump_usym (sym, addr, 0); /* let's not guess the size */
1645 //printf ("found symbol at %p: %s\n", (void*)addr, sym);
1651 dump_sample_hits (MonoProfiler *prof, StatBuffer *sbuf, int recurse)
1654 LogBuffer *logbuffer;
1657 if (recurse && sbuf->next) {
1658 dump_sample_hits (prof, sbuf->next, 1);
1659 free_buffer (sbuf->next, sbuf->next->size);
1662 for (sample = sbuf->buf; sample < sbuf->data;) {
1664 int count = sample [0] & 0xff;
1665 int mbt_count = (sample [0] & 0xff00) >> 8;
1666 int type = sample [0] >> 16;
1667 uintptr_t *managed_sample_base = sample + count + 3;
1669 if (sample + SAMPLE_EVENT_SIZE_IN_SLOTS (mbt_count) > sbuf->data)
1672 for (i = 0; i < mbt_count; ++i) {
1673 MonoMethod *method = (MonoMethod*)managed_sample_base [i * 4 + 0];
1674 MonoDomain *domain = (MonoDomain*)managed_sample_base [i * 4 + 1];
1675 void *address = (void*)managed_sample_base [i * 4 + 2];
1678 MonoJitInfo *ji = mono_jit_info_table_find (domain, address);
1680 managed_sample_base [i * 4 + 0] = (uintptr_t)mono_jit_info_get_method (ji);
1683 logbuffer = ensure_logbuf (20 + count * 8);
1684 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
1685 emit_value (logbuffer, type);
1686 emit_uvalue (logbuffer, prof->startup_time + (uint64_t)sample [2] * (uint64_t)10000);
1687 emit_value (logbuffer, count);
1688 for (i = 0; i < count; ++i) {
1689 emit_ptr (logbuffer, (void*)sample [i + 3]);
1690 add_code_pointer (sample [i + 3]);
1693 sample += count + 3;
1694 /* new in data version 6 */
1695 emit_uvalue (logbuffer, mbt_count);
1696 for (i = 0; i < mbt_count; ++i) {
1697 emit_method (logbuffer, (void*)sample [i * 4]); /* method */
1698 emit_svalue (logbuffer, 0); /* il offset will always be 0 from now on */
1699 emit_svalue (logbuffer, sample [i * 4 + 3]); /* native offset */
1701 sample += 4 * mbt_count;
1703 dump_unmanaged_coderefs (prof);
1707 #ifndef __NR_perf_event_open
1709 #define __NR_perf_event_open 364
1711 #define __NR_perf_event_open 241
1716 mono_cpu_count (void)
1719 #ifdef PLATFORM_ANDROID
1720 /* Android tries really hard to save power by powering off CPUs on SMP phones which
1721 * means the normal way to query cpu count returns a wrong value with userspace API.
1722 * Instead we use /sys entries to query the actual hardware CPU count.
1724 char buffer[8] = {'\0'};
1725 int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
1726 /* Format of the /sys entry is a cpulist of indexes which in the case
1727 * of present is always of the form "0-(n-1)" when there is more than
1728 * 1 core, n being the number of CPU cores in the system. Otherwise
1729 * the value is simply 0
1731 if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
1732 count = strtol (((char*)buffer) + 2, NULL, 10);
1738 #ifdef _SC_NPROCESSORS_ONLN
1739 count = sysconf (_SC_NPROCESSORS_ONLN);
1746 size_t len = sizeof (int);
1749 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
1756 GetSystemInfo (&info);
1757 return info.dwNumberOfProcessors;
1766 unsigned int prev_pos;
1768 struct perf_event_mmap_page *page_desc;
1771 static PerfData *perf_data = NULL;
1772 static int num_perf;
1773 #define PERF_PAGES_SHIFT 4
1774 static int num_pages = 1 << PERF_PAGES_SHIFT;
1775 static unsigned int mmap_mask;
1778 struct perf_event_header h;
1788 perf_event_syscall (struct perf_event_attr *attr, pid_t pid, int cpu, int group_fd, unsigned long flags)
1790 attr->size = PERF_ATTR_SIZE_VER0;
1791 //printf ("perf attr size: %d\n", attr->size);
1792 #if defined(__x86_64__)
1793 return syscall(/*__NR_perf_event_open*/ 298, attr, pid, cpu, group_fd, flags);
1794 #elif defined(__i386__)
1795 return syscall(/*__NR_perf_event_open*/ 336, attr, pid, cpu, group_fd, flags);
1796 #elif defined(__arm__)
1797 return syscall(/*__NR_perf_event_open*/ 364, attr, pid, cpu, group_fd, flags);
1804 setup_perf_map (PerfData *perf)
1806 perf->mmap_base = mmap (NULL, (num_pages + 1) * getpagesize (), PROT_READ|PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
1807 if (perf->mmap_base == MAP_FAILED) {
1809 printf ("failed mmap\n");
1812 perf->page_desc = perf->mmap_base;
1814 printf ("mmap version: %d\n", perf->page_desc->version);
1819 dump_perf_hits (MonoProfiler *prof, void *buf, int size)
1821 LogBuffer *logbuffer;
1822 void *end = (char*)buf + size;
1824 int pid = getpid ();
1830 if (pid != s->pid) {
1832 printf ("event for different pid: %d\n", s->pid);
1833 buf = (char*)buf + s->h.size;
1836 /*ip = (void*)s->ip;
1837 printf ("sample: %d, size: %d, ip: %p (%s), timestamp: %llu, nframes: %llu\n",
1838 s->h.type, s->h.size, ip, symbol_for (ip), s->timestamp, s->nframes);*/
1839 logbuffer = ensure_logbuf (20 + s->nframes * 8);
1840 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
1841 emit_value (logbuffer, sample_type);
1842 emit_uvalue (logbuffer, s->timestamp - prof->startup_time);
1843 emit_value (logbuffer, 1); /* count */
1844 emit_ptr (logbuffer, (void*)(uintptr_t)s->ip);
1845 /* no support here yet for the managed backtrace */
1846 emit_uvalue (logbuffer, 0);
1847 add_code_pointer (s->ip);
1848 buf = (char*)buf + s->h.size;
1852 printf ("dumped %d samples\n", samples);
1853 dump_unmanaged_coderefs (prof);
1856 /* read events from the ring buffer */
1858 read_perf_mmap (MonoProfiler* prof, int cpu)
1860 PerfData *perf = perf_data + cpu;
1862 unsigned char *data = (unsigned char*)perf->mmap_base + getpagesize ();
1863 unsigned int head = perf->page_desc->data_head;
1867 mono_memory_read_barrier ();
1869 old = perf->prev_pos;
1873 printf ("lost mmap events: old: %d, head: %d\n", old, head);
1877 if ((old & mmap_mask) + size != (head & mmap_mask)) {
1878 buf = data + (old & mmap_mask);
1879 size = mmap_mask + 1 - (old & mmap_mask);
1881 /* size bytes at buf */
1883 printf ("found1 bytes of events: %d\n", size);
1884 dump_perf_hits (prof, buf, size);
1886 buf = data + (old & mmap_mask);
1888 /* size bytes at buf */
1890 printf ("found bytes of events: %d\n", size);
1891 dump_perf_hits (prof, buf, size);
1893 perf->prev_pos = old;
1894 perf->page_desc->data_tail = old;
1899 setup_perf_event_for_cpu (PerfData *perf, int cpu)
1901 struct perf_event_attr attr;
1902 memset (&attr, 0, sizeof (attr));
1903 attr.type = PERF_TYPE_HARDWARE;
1904 switch (sample_type) {
1905 case SAMPLE_CYCLES: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
1906 case SAMPLE_INSTRUCTIONS: attr.config = PERF_COUNT_HW_INSTRUCTIONS; break;
1907 case SAMPLE_CACHE_MISSES: attr.config = PERF_COUNT_HW_CACHE_MISSES; break;
1908 case SAMPLE_CACHE_REFS: attr.config = PERF_COUNT_HW_CACHE_REFERENCES; break;
1909 case SAMPLE_BRANCHES: attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS; break;
1910 case SAMPLE_BRANCH_MISSES: attr.config = PERF_COUNT_HW_BRANCH_MISSES; break;
1911 default: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
1913 attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD | PERF_SAMPLE_TIME;
1914 // attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
1915 attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING | PERF_FORMAT_ID;
1918 attr.sample_freq = sample_freq;
1920 perf->perf_fd = perf_event_syscall (&attr, getpid (), cpu, -1, 0);
1922 printf ("perf fd: %d, freq: %d, event: %llu\n", perf->perf_fd, sample_freq, attr.config);
1923 if (perf->perf_fd < 0) {
1924 if (perf->perf_fd == -EPERM) {
1925 fprintf (stderr, "Perf syscall denied, do \"echo 1 > /proc/sys/kernel/perf_event_paranoid\" as root to enable.\n");
1928 perror ("open perf event");
1932 if (!setup_perf_map (perf)) {
1933 close (perf->perf_fd);
1941 setup_perf_event (void)
1944 mmap_mask = num_pages * getpagesize () - 1;
1945 num_perf = mono_cpu_count ();
1946 perf_data = calloc (num_perf, sizeof (PerfData));
1947 for (i = 0; i < num_perf; ++i) {
1948 count += setup_perf_event_for_cpu (perf_data + i, i);
1957 #endif /* USE_PERF_EVENTS */
1959 #ifndef DISABLE_HELPER_THREAD
1961 typedef struct MonoCounterAgent {
1962 MonoCounter *counter;
1963 // MonoCounterAgent specific data :
1968 struct MonoCounterAgent *next;
1971 static MonoCounterAgent* counters;
1972 static gboolean counters_initialized = FALSE;
1973 static int counters_index = 1;
1974 static mono_mutex_t counters_mutex;
1977 counters_add_agent (MonoCounter *counter)
1979 MonoCounterAgent *agent, *item;
1981 if (!counters_initialized)
1984 mono_mutex_lock (&counters_mutex);
1986 for (agent = counters; agent; agent = agent->next) {
1987 if (agent->counter == counter) {
1988 agent->value_size = 0;
1990 free (agent->value);
1991 agent->value = NULL;
1993 mono_mutex_unlock (&counters_mutex);
1998 agent = malloc (sizeof (MonoCounterAgent));
1999 agent->counter = counter;
2000 agent->value = NULL;
2001 agent->value_size = 0;
2002 agent->index = counters_index++;
2015 mono_mutex_unlock (&counters_mutex);
2019 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
2021 counters_add_agent (counter);
2026 counters_init (MonoProfiler *profiler)
2028 assert (!counters_initialized);
2030 mono_mutex_init (&counters_mutex);
2032 counters_initialized = TRUE;
2034 mono_counters_on_register (&counters_add_agent);
2035 mono_counters_foreach (counters_init_foreach_callback, NULL);
2039 counters_emit (MonoProfiler *profiler)
2041 MonoCounterAgent *agent;
2042 LogBuffer *logbuffer;
2043 int size = 1 + 5, len = 0;
2045 if (!counters_initialized)
2048 mono_mutex_lock (&counters_mutex);
2050 for (agent = counters; agent; agent = agent->next) {
2054 size += strlen (mono_counter_get_name (agent->counter)) + 1 + 5 * 5;
2059 mono_mutex_unlock (&counters_mutex);
2063 logbuffer = ensure_logbuf (size);
2065 ENTER_LOG (logbuffer, "counters");
2066 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2067 emit_value (logbuffer, len);
2068 for (agent = counters; agent; agent = agent->next) {
2072 const char *name = mono_counter_get_name (agent->counter);
2073 emit_value (logbuffer, mono_counter_get_section (agent->counter));
2074 emit_string (logbuffer, name, strlen (name) + 1);
2075 emit_value (logbuffer, mono_counter_get_type (agent->counter));
2076 emit_value (logbuffer, mono_counter_get_unit (agent->counter));
2077 emit_value (logbuffer, mono_counter_get_variance (agent->counter));
2078 emit_value (logbuffer, agent->index);
2082 EXIT_LOG (logbuffer);
2084 safe_dump (profiler, ensure_logbuf (0));
2086 mono_mutex_unlock (&counters_mutex);
2090 counters_sample (MonoProfiler *profiler, uint64_t timestamp)
2092 MonoCounterAgent *agent;
2093 MonoCounter *counter;
2094 LogBuffer *logbuffer;
2100 if (!counters_initialized)
2103 counters_emit (profiler);
2106 buffer = calloc (1, buffer_size);
2108 mono_mutex_lock (&counters_mutex);
2111 for (agent = counters; agent; agent = agent->next)
2112 size += 10 * 2 + mono_counter_get_size (agent->counter);
2114 logbuffer = ensure_logbuf (size);
2116 ENTER_LOG (logbuffer, "counters");
2117 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
2118 emit_uvalue (logbuffer, timestamp);
2119 for (agent = counters; agent; agent = agent->next) {
2122 counter = agent->counter;
2124 size = mono_counter_get_size (counter);
2126 continue; // FIXME error
2127 } else if (size > buffer_size) {
2129 buffer = realloc (buffer, buffer_size);
2132 memset (buffer, 0, buffer_size);
2134 if (mono_counters_sample (counter, buffer, size) < 0)
2135 continue; // FIXME error
2137 type = mono_counter_get_type (counter);
2139 if (!agent->value) {
2140 agent->value = calloc (1, size);
2141 agent->value_size = size;
2143 if (type == MONO_COUNTER_STRING) {
2144 if (strcmp (agent->value, buffer) == 0)
2147 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
2152 emit_uvalue (logbuffer, agent->index);
2153 emit_uvalue (logbuffer, type);
2155 case MONO_COUNTER_INT:
2156 #if SIZEOF_VOID_P == 4
2157 case MONO_COUNTER_WORD:
2159 emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
2161 case MONO_COUNTER_UINT:
2162 emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
2164 case MONO_COUNTER_TIME_INTERVAL:
2165 case MONO_COUNTER_LONG:
2166 #if SIZEOF_VOID_P == 8
2167 case MONO_COUNTER_WORD:
2169 emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
2171 case MONO_COUNTER_ULONG:
2172 emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
2174 case MONO_COUNTER_DOUBLE:
2175 emit_double (logbuffer, *(double*)buffer);
2177 case MONO_COUNTER_STRING:
2179 emit_byte (logbuffer, 0);
2181 emit_byte (logbuffer, 1);
2182 emit_string (logbuffer, (char*)buffer, size);
2189 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
2190 agent->value = realloc (agent->value, size);
2191 agent->value_size = size;
2195 memcpy (agent->value, buffer, size);
2199 emit_value (logbuffer, 0);
2200 EXIT_LOG (logbuffer);
2202 safe_dump (profiler, ensure_logbuf (0));
2204 mono_mutex_unlock (&counters_mutex);
2207 typedef struct _PerfCounterAgent PerfCounterAgent;
2208 struct _PerfCounterAgent {
2209 PerfCounterAgent *next;
2211 char *category_name;
2220 static PerfCounterAgent *perfcounters = NULL;
2223 perfcounters_emit (MonoProfiler *profiler)
2225 PerfCounterAgent *pcagent;
2226 LogBuffer *logbuffer;
2227 int size = 1 + 5, len = 0;
2229 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2230 if (pcagent->emitted)
2233 size += strlen (pcagent->name) + 1 + 5 * 5;
2240 logbuffer = ensure_logbuf (size);
2242 ENTER_LOG (logbuffer, "perfcounters");
2243 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2244 emit_value (logbuffer, len);
2245 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2246 if (pcagent->emitted)
2249 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
2250 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
2251 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
2252 emit_value (logbuffer, MONO_COUNTER_LONG);
2253 emit_value (logbuffer, MONO_COUNTER_RAW);
2254 emit_value (logbuffer, MONO_COUNTER_VARIABLE);
2255 emit_value (logbuffer, pcagent->index);
2257 pcagent->emitted = 1;
2259 EXIT_LOG (logbuffer);
2261 safe_dump (profiler, ensure_logbuf (0));
2265 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
2267 PerfCounterAgent *pcagent;
2269 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2270 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
2272 if (pcagent->value == value)
2275 pcagent->value = value;
2276 pcagent->updated = 1;
2277 pcagent->deleted = 0;
2281 pcagent = g_new0 (PerfCounterAgent, 1);
2282 pcagent->next = perfcounters;
2283 pcagent->index = counters_index++;
2284 pcagent->category_name = g_strdup (category_name);
2285 pcagent->name = g_strdup (name);
2286 pcagent->type = (int) type;
2287 pcagent->value = value;
2288 pcagent->emitted = 0;
2289 pcagent->updated = 1;
2290 pcagent->deleted = 0;
2292 perfcounters = pcagent;
2298 perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp)
2300 PerfCounterAgent *pcagent;
2301 LogBuffer *logbuffer;
2304 if (!counters_initialized)
2307 mono_mutex_lock (&counters_mutex);
2309 /* mark all perfcounters as deleted, foreach will unmark them as necessary */
2310 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
2311 pcagent->deleted = 1;
2313 mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
2315 perfcounters_emit (profiler);
2319 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2320 if (pcagent->deleted || !pcagent->updated)
2322 size += 10 * 2 + sizeof (gint64);
2325 logbuffer = ensure_logbuf (size);
2327 ENTER_LOG (logbuffer, "perfcounters");
2328 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
2329 emit_uvalue (logbuffer, timestamp);
2330 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2331 if (pcagent->deleted || !pcagent->updated)
2333 emit_uvalue (logbuffer, pcagent->index);
2334 emit_uvalue (logbuffer, MONO_COUNTER_LONG);
2335 emit_svalue (logbuffer, pcagent->value);
2337 pcagent->updated = 0;
2340 emit_value (logbuffer, 0);
2341 EXIT_LOG (logbuffer);
2343 safe_dump (profiler, ensure_logbuf (0));
2345 mono_mutex_unlock (&counters_mutex);
2349 counters_and_perfcounters_sample (MonoProfiler *prof)
2351 static uint64_t start = -1;
2355 start = current_time ();
2357 now = current_time ();
2358 counters_sample (prof, (now - start) / 1000/ 1000);
2359 perfcounters_sample (prof, (now - start) / 1000/ 1000);
2362 #endif /* DISABLE_HELPER_THREAD */
2365 log_shutdown (MonoProfiler *prof)
2368 #ifndef DISABLE_HELPER_THREAD
2369 counters_and_perfcounters_sample (prof);
2371 if (prof->command_port) {
2374 ign_res (write (prof->pipes [1], &c, 1));
2375 pthread_join (prof->helper_thread, &res);
2381 for (i = 0; i < num_perf; ++i)
2382 read_perf_mmap (prof, i);
2385 dump_sample_hits (prof, prof->stat_buffers, 1);
2387 if (TLS_GET (tlsbuffer))
2388 dump_buffer (prof, TLS_GET (tlsbuffer));
2389 TLS_SET (tlsbuffer, NULL);
2391 #if defined (HAVE_SYS_ZLIB)
2393 gzclose (prof->gzfile);
2395 if (prof->pipe_output)
2396 pclose (prof->file);
2398 fclose (prof->file);
2403 new_filename (const char* filename)
2405 time_t t = time (NULL);
2406 int pid = process_id ();
2411 int count_dates = 0;
2415 for (p = filename; *p; p++) {
2426 if (!count_dates && !count_pids)
2427 return pstrdup (filename);
2428 snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
2430 snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
2431 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
2432 s_date = strlen (time_buf);
2433 s_pid = strlen (pid_buf);
2434 d = res = malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
2435 for (p = filename; *p; p++) {
2442 strcpy (d, time_buf);
2445 } else if (*p == 'p') {
2446 strcpy (d, pid_buf);
2449 } else if (*p == '%') {
2461 #ifndef DISABLE_HELPER_THREAD
2463 //this is exposed by the JIT, but it's not meant to be a supported API for now.
2464 extern void mono_threads_attach_tools_thread (void);
2467 helper_thread (void* arg)
2469 MonoProfiler* prof = arg;
2473 MonoThread *thread = NULL;
2475 mono_threads_attach_tools_thread ();
2476 //fprintf (stderr, "Server listening\n");
2477 command_socket = -1;
2483 FD_SET (prof->server_socket, &rfds);
2484 max_fd = prof->server_socket;
2485 FD_SET (prof->pipes [0], &rfds);
2486 if (max_fd < prof->pipes [0])
2487 max_fd = prof->pipes [0];
2488 if (command_socket >= 0) {
2489 FD_SET (command_socket, &rfds);
2490 if (max_fd < command_socket)
2491 max_fd = command_socket;
2496 for ( i = 0; i < num_perf; ++i) {
2497 if (perf_data [i].perf_fd < 0)
2499 FD_SET (perf_data [i].perf_fd, &rfds);
2500 if (max_fd < perf_data [i].perf_fd)
2501 max_fd = perf_data [i].perf_fd;
2506 counters_and_perfcounters_sample (prof);
2510 len = select (max_fd + 1, &rfds, NULL, NULL, &tv);
2516 g_warning ("Error in proflog server: %s", strerror (errno));
2520 if (FD_ISSET (prof->pipes [0], &rfds)) {
2522 int r = read (prof->pipes [0], &c, 1);
2523 if (r == 1 && c == 0) {
2524 StatBuffer *sbufbase = prof->stat_buffers;
2526 if (!sbufbase->next)
2528 sbuf = sbufbase->next->next;
2529 sbufbase->next->next = NULL;
2531 fprintf (stderr, "stat buffer dump\n");
2533 dump_sample_hits (prof, sbuf, 1);
2534 free_buffer (sbuf, sbuf->size);
2535 safe_dump (prof, ensure_logbuf (0));
2539 /* time to shut down */
2541 mono_thread_detach (thread);
2543 fprintf (stderr, "helper shutdown\n");
2547 for ( i = 0; i < num_perf; ++i) {
2548 if (perf_data [i].perf_fd < 0)
2550 if (FD_ISSET (perf_data [i].perf_fd, &rfds))
2551 read_perf_mmap (prof, i);
2555 safe_dump (prof, ensure_logbuf (0));
2561 for ( i = 0; i < num_perf; ++i) {
2562 if (perf_data [i].perf_fd < 0)
2564 if (FD_ISSET (perf_data [i].perf_fd, &rfds)) {
2565 read_perf_mmap (prof, i);
2566 safe_dump (prof, ensure_logbuf (0));
2571 if (command_socket >= 0 && FD_ISSET (command_socket, &rfds)) {
2572 len = read (command_socket, buf, sizeof (buf) - 1);
2576 close (command_socket);
2577 command_socket = -1;
2581 if (strcmp (buf, "heapshot\n") == 0) {
2582 heapshot_requested = 1;
2583 //fprintf (stderr, "perform heapshot\n");
2584 if (runtime_inited && !thread) {
2585 thread = mono_thread_attach (mono_get_root_domain ());
2586 /*fprintf (stderr, "attached\n");*/
2589 process_requests (prof);
2590 mono_thread_detach (thread);
2596 if (!FD_ISSET (prof->server_socket, &rfds)) {
2599 command_socket = accept (prof->server_socket, NULL, NULL);
2600 if (command_socket < 0)
2602 //fprintf (stderr, "Accepted connection\n");
2608 start_helper_thread (MonoProfiler* prof)
2610 struct sockaddr_in server_address;
2613 if (pipe (prof->pipes) < 0) {
2614 fprintf (stderr, "Cannot create pipe\n");
2617 prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
2618 if (prof->server_socket < 0) {
2619 fprintf (stderr, "Cannot create server socket\n");
2622 memset (&server_address, 0, sizeof (server_address));
2623 server_address.sin_family = AF_INET;
2624 server_address.sin_addr.s_addr = INADDR_ANY;
2625 server_address.sin_port = htons (prof->command_port);
2626 if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) < 0) {
2627 fprintf (stderr, "Cannot bind server socket, port: %d: %s\n", prof->command_port, strerror (errno));
2628 close (prof->server_socket);
2631 if (listen (prof->server_socket, 1) < 0) {
2632 fprintf (stderr, "Cannot listen server socket\n");
2633 close (prof->server_socket);
2636 slen = sizeof (server_address);
2637 if (getsockname (prof->server_socket, (struct sockaddr *)&server_address, &slen) == 0) {
2638 prof->command_port = ntohs (server_address.sin_port);
2639 /*fprintf (stderr, "Assigned server port: %d\n", prof->command_port);*/
2642 r = pthread_create (&prof->helper_thread, NULL, helper_thread, prof);
2644 close (prof->server_socket);
2651 static MonoProfiler*
2652 create_profiler (const char *filename)
2656 int force_delete = 0;
2657 int need_helper_thread = 0;
2658 prof = calloc (1, sizeof (MonoProfiler));
2660 prof->command_port = command_port;
2661 if (filename && *filename == '-') {
2667 filename = "|mprof-report -";
2669 filename = "output.mlpd";
2670 nf = (char*)filename;
2672 nf = new_filename (filename);
2674 int s = strlen (nf) + 32;
2675 char *p = malloc (s);
2676 snprintf (p, s, "|mprof-report '--out=%s' -", nf);
2682 prof->file = popen (nf + 1, "w");
2683 prof->pipe_output = 1;
2684 } else if (*nf == '#') {
2685 int fd = strtol (nf + 1, NULL, 10);
2686 prof->file = fdopen (fd, "a");
2691 if ((f = fopen (nf, "r"))) {
2693 fprintf (stderr, "The Mono profiler won't overwrite existing filename: %s.\n", nf);
2694 fprintf (stderr, "Profiling disabled: use a different name or -FILENAME to force overwrite.\n");
2698 prof->file = fopen (nf, "wb");
2701 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
2704 #if defined (HAVE_SYS_ZLIB)
2706 prof->gzfile = gzdopen (fileno (prof->file), "wb");
2709 if (sample_type && !do_mono_sample)
2710 need_helper_thread = setup_perf_event ();
2712 /* FIXME: warn if different freq or sample type */
2716 if (do_mono_sample) {
2717 prof->stat_buffers = create_stat_buffer ();
2718 need_helper_thread = 1;
2720 if (do_counters && !need_helper_thread) {
2721 need_helper_thread = 1;
2723 #ifndef DISABLE_HELPER_THREAD
2724 if (hs_mode_ondemand || need_helper_thread) {
2725 if (!start_helper_thread (prof))
2726 prof->command_port = 0;
2729 if (hs_mode_ondemand)
2730 fprintf (stderr, "Ondemand heapshot unavailable on this arch.\n");
2732 prof->startup_time = current_time ();
2740 printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
2741 printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
2742 printf ("Options:\n");
2743 printf ("\thelp show this usage info\n");
2744 printf ("\t[no]alloc enable/disable recording allocation info\n");
2745 printf ("\t[no]calls enable/disable recording enter/leave method events\n");
2746 printf ("\theapshot[=MODE] record heap shot info (by default at each major collection)\n");
2747 printf ("\t MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
2748 printf ("\tcounters sample counters every 1s\n");
2749 printf ("\tsample[=TYPE] use statistical sampling mode (by default cycles/1000)\n");
2750 printf ("\t TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
2751 printf ("\t TYPE can be followed by /FREQUENCY\n");
2752 printf ("\ttime=fast use a faster (but more inaccurate) timer\n");
2753 printf ("\tmaxframes=NUM collect up to NUM stack frames\n");
2754 printf ("\tcalldepth=NUM ignore method events for call chain depth bigger than NUM\n");
2755 printf ("\toutput=FILENAME write the data to file FILENAME (-FILENAME to overwrite)\n");
2756 printf ("\toutput=|PROGRAM write the data to the stdin of PROGRAM\n");
2757 printf ("\t %%t is subtituted with date and time, %%p with the pid\n");
2758 printf ("\treport create a report instead of writing the raw data to a file\n");
2759 printf ("\tzip compress the output data\n");
2760 printf ("\tport=PORTNUM use PORTNUM for the listening command server\n");
2766 match_option (const char* p, const char *opt, char **rval)
2768 int len = strlen (opt);
2769 if (strncmp (p, opt, len) == 0) {
2771 if (p [len] == '=' && p [len + 1]) {
2772 const char *opt = p + len + 1;
2773 const char *end = strchr (opt, ',');
2781 val = malloc (l + 1);
2782 memcpy (val, opt, l);
2787 if (p [len] == 0 || p [len] == ',') {
2789 return p + len + (p [len] == ',');
2807 static const SampleMode sample_modes [] = {
2808 {"cycles", SAMPLE_CYCLES},
2809 {"instr", SAMPLE_INSTRUCTIONS},
2810 {"cachemiss", SAMPLE_CACHE_MISSES},
2811 {"cacherefs", SAMPLE_CACHE_REFS},
2812 {"branches", SAMPLE_BRANCHES},
2813 {"branchmiss", SAMPLE_BRANCH_MISSES},
2818 set_sample_mode (char* val, int allow_empty)
2821 char *maybe_freq = NULL;
2823 const SampleMode *smode = sample_modes;
2824 #ifndef USE_PERF_EVENTS
2827 if (allow_empty && !val) {
2828 sample_type = SAMPLE_CYCLES;
2832 if (strcmp (val, "mono") == 0) {
2834 sample_type = SAMPLE_CYCLES;
2838 for (smode = sample_modes; smode->name; smode++) {
2839 int l = strlen (smode->name);
2840 if (strncmp (val, smode->name, l) == 0) {
2841 sample_type = smode->sample_mode;
2842 maybe_freq = val + l;
2848 if (*maybe_freq == '/') {
2849 count = strtoul (maybe_freq + 1, &end, 10);
2850 if (maybe_freq + 1 == end)
2852 sample_freq = count;
2853 } else if (*maybe_freq != 0) {
2862 set_hsmode (char* val, int allow_empty)
2866 if (allow_empty && !val)
2868 if (strcmp (val, "ondemand") == 0) {
2869 hs_mode_ondemand = 1;
2873 count = strtoul (val, &end, 10);
2876 if (strcmp (end, "ms") == 0)
2878 else if (strcmp (end, "gc") == 0)
2886 * declaration to silence the compiler: this is the entry point that
2887 * mono will load from the shared library and call.
2890 mono_profiler_startup (const char *desc);
2893 mono_profiler_startup_log (const char *desc);
2896 * this is the entry point that will be used when the profiler
2897 * is embedded inside the main executable.
2900 mono_profiler_startup_log (const char *desc)
2902 mono_profiler_startup (desc);
2906 mono_profiler_startup (const char *desc)
2909 char *filename = NULL;
2913 int calls_enabled = 0;
2914 int allocs_enabled = 0;
2915 int only_counters = 0;
2916 int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
2917 MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
2918 MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
2919 MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS;
2922 if (strncmp (p, "log", 3))
2927 for (; *p; p = opt) {
2933 if ((opt = match_option (p, "help", NULL)) != p) {
2937 if ((opt = match_option (p, "calls", NULL)) != p) {
2941 if ((opt = match_option (p, "nocalls", NULL)) != p) {
2942 events &= ~MONO_PROFILE_ENTER_LEAVE;
2946 if ((opt = match_option (p, "alloc", NULL)) != p) {
2950 if ((opt = match_option (p, "noalloc", NULL)) != p) {
2951 events &= ~MONO_PROFILE_ALLOCATIONS;
2954 if ((opt = match_option (p, "time", &val)) != p) {
2955 if (strcmp (val, "fast") == 0)
2957 else if (strcmp (val, "null") == 0)
2964 if ((opt = match_option (p, "report", NULL)) != p) {
2968 if ((opt = match_option (p, "debug", NULL)) != p) {
2972 if ((opt = match_option (p, "sampling-real", NULL)) != p) {
2973 sampling_mode = MONO_PROFILER_STAT_MODE_REAL;
2976 if ((opt = match_option (p, "sampling-process", NULL)) != p) {
2977 sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
2980 if ((opt = match_option (p, "heapshot", &val)) != p) {
2981 events &= ~MONO_PROFILE_ALLOCATIONS;
2982 events &= ~MONO_PROFILE_ENTER_LEAVE;
2985 set_hsmode (val, 1);
2988 if ((opt = match_option (p, "sample", &val)) != p) {
2989 events &= ~MONO_PROFILE_ALLOCATIONS;
2990 events &= ~MONO_PROFILE_ENTER_LEAVE;
2992 set_sample_mode (val, 1);
2995 if ((opt = match_option (p, "hsmode", &val)) != p) {
2996 fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
2997 set_hsmode (val, 0);
3000 if ((opt = match_option (p, "zip", NULL)) != p) {
3004 if ((opt = match_option (p, "output", &val)) != p) {
3008 if ((opt = match_option (p, "port", &val)) != p) {
3010 command_port = strtoul (val, &end, 10);
3014 if ((opt = match_option (p, "maxframes", &val)) != p) {
3016 num_frames = strtoul (val, &end, 10);
3017 if (num_frames > MAX_FRAMES)
3018 num_frames = MAX_FRAMES;
3020 notraces = num_frames == 0;
3023 if ((opt = match_option (p, "calldepth", &val)) != p) {
3025 max_call_depth = strtoul (val, &end, 10);
3029 if ((opt = match_option (p, "counters", NULL)) != p) {
3033 if ((opt = match_option (p, "countersonly", NULL)) != p) {
3042 if (calls_enabled) {
3043 events |= MONO_PROFILE_ENTER_LEAVE;
3047 events |= MONO_PROFILE_ALLOCATIONS;
3050 utils_init (fast_time);
3052 prof = create_profiler (filename);
3057 mono_profiler_install (prof, log_shutdown);
3058 mono_profiler_install_gc (gc_event, gc_resize);
3059 mono_profiler_install_allocation (gc_alloc);
3060 mono_profiler_install_gc_moves (gc_moves);
3061 mono_profiler_install_gc_roots (gc_handle, gc_roots);
3062 mono_profiler_install_class (NULL, class_loaded, NULL, NULL);
3063 mono_profiler_install_module (NULL, image_loaded, NULL, NULL);
3064 mono_profiler_install_thread (thread_start, thread_end);
3065 mono_profiler_install_thread_name (thread_name);
3066 mono_profiler_install_enter_leave (method_enter, method_leave);
3067 mono_profiler_install_jit_end (method_jitted);
3068 mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
3069 mono_profiler_install_monitor (monitor_event);
3070 mono_profiler_install_runtime_initialized (runtime_initialized);
3073 if (do_mono_sample && sample_type == SAMPLE_CYCLES && !only_counters) {
3074 events |= MONO_PROFILE_STATISTICAL;
3075 mono_profiler_set_statistical_mode (sampling_mode, 1000000 / sample_freq);
3076 mono_profiler_install_statistical (mono_sample_hit);
3079 mono_profiler_set_events (events);
3081 TLS_INIT (tlsbuffer);