2 * profiler.c: Profiler interface for Mono
5 * Paolo Molaro (lupus@ximian.com)
7 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
8 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
12 #include "mono/metadata/profiler-private.h"
13 #include "mono/metadata/debug-helpers.h"
14 #include "mono/metadata/mono-debug.h"
15 #include "mono/metadata/debug-mono-symfile.h"
16 #include "mono/metadata/metadata-internals.h"
17 #include "mono/metadata/class-internals.h"
18 #include "mono/metadata/domain-internals.h"
19 #include "mono/metadata/gc-internal.h"
20 #include "mono/io-layer/io-layer.h"
21 #include "mono/utils/mono-dl.h"
26 #ifdef HAVE_SYS_TIME_H
29 #ifdef HAVE_BACKTRACE_SYMBOLS
33 static MonoProfiler * current_profiler = NULL;
35 static MonoProfileAppDomainFunc domain_start_load;
36 static MonoProfileAppDomainResult domain_end_load;
37 static MonoProfileAppDomainFunc domain_start_unload;
38 static MonoProfileAppDomainFunc domain_end_unload;
40 static MonoProfileAssemblyFunc assembly_start_load;
41 static MonoProfileAssemblyResult assembly_end_load;
42 static MonoProfileAssemblyFunc assembly_start_unload;
43 static MonoProfileAssemblyFunc assembly_end_unload;
45 static MonoProfileModuleFunc module_start_load;
46 static MonoProfileModuleResult module_end_load;
47 static MonoProfileModuleFunc module_start_unload;
48 static MonoProfileModuleFunc module_end_unload;
50 static MonoProfileClassFunc class_start_load;
51 static MonoProfileClassResult class_end_load;
52 static MonoProfileClassFunc class_start_unload;
53 static MonoProfileClassFunc class_end_unload;
55 static MonoProfileMethodFunc jit_start;
56 static MonoProfileMethodResult jit_end;
57 static MonoProfileJitResult jit_end2;
58 static MonoProfileMethodFunc method_free;
59 static MonoProfileMethodResult man_unman_transition;
60 static MonoProfileAllocFunc allocation_cb;
61 static MonoProfileMonitorFunc monitor_event_cb;
62 static MonoProfileStatFunc statistical_cb;
63 static MonoProfileStatCallChainFunc statistical_call_chain_cb;
64 static int statistical_call_chain_depth;
65 static MonoProfileMethodFunc method_enter;
66 static MonoProfileMethodFunc method_leave;
68 static MonoProfileExceptionFunc exception_throw_cb;
69 static MonoProfileMethodFunc exception_method_leave_cb;
70 static MonoProfileExceptionClauseFunc exception_clause_cb;
72 static MonoProfileThreadFunc thread_start;
73 static MonoProfileThreadFunc thread_end;
75 static MonoProfileCoverageFilterFunc coverage_filter_cb;
77 static MonoProfileFunc shutdown_callback;
79 static MonoProfileGCFunc gc_event;
80 static MonoProfileGCResizeFunc gc_heap_resize;
82 static MonoProfileFunc runtime_initialized_event;
84 #define mono_profiler_coverage_lock() EnterCriticalSection (&profiler_coverage_mutex)
85 #define mono_profiler_coverage_unlock() LeaveCriticalSection (&profiler_coverage_mutex)
86 static CRITICAL_SECTION profiler_coverage_mutex;
88 /* this is directly accessible to other mono libs. */
89 MonoProfileFlags mono_profiler_events;
92 * mono_profiler_install:
93 * @prof: a MonoProfiler structure pointer, or a pointer to a derived structure.
94 * @callback: the function to invoke at shutdown
96 * Use mono_profiler_install to activate profiling in the Mono runtime.
97 * Typically developers of new profilers will create a new structure whose
98 * first field is a MonoProfiler and put any extra information that they need
99 * to access from the various profiling callbacks there.
103 mono_profiler_install (MonoProfiler *prof, MonoProfileFunc callback)
105 if (current_profiler)
106 g_error ("profiler already setup");
107 current_profiler = prof;
108 shutdown_callback = callback;
109 InitializeCriticalSection (&profiler_coverage_mutex);
113 * mono_profiler_set_events:
114 * @events: an ORed set of values made up of MONO_PROFILER_ flags
116 * The events descriped in the @events argument is a set of flags
117 * that represent which profiling events must be triggered. For
118 * example if you have registered a set of methods for tracking
119 * JIT compilation start and end with mono_profiler_install_jit_compile,
120 * you will want to pass the MONO_PROFILE_JIT_COMPILATION flag to
123 * You can call mono_profile_set_events more than once and you can
124 * do this at runtime to modify which methods are invoked.
127 mono_profiler_set_events (MonoProfileFlags events)
129 mono_profiler_events = events;
133 * mono_profiler_get_events:
135 * Returns a list of active events that will be intercepted.
138 mono_profiler_get_events (void)
140 return mono_profiler_events;
144 * mono_profiler_install_enter_leave:
145 * @enter: the routine to be called on each method entry
146 * @fleave: the routine to be called each time a method returns
148 * Use this routine to install routines that will be called everytime
149 * a method enters and leaves. The routines will receive as an argument
150 * the MonoMethod representing the method that is entering or leaving.
153 mono_profiler_install_enter_leave (MonoProfileMethodFunc enter, MonoProfileMethodFunc fleave)
155 method_enter = enter;
156 method_leave = fleave;
160 * mono_profiler_install_jit_compile:
161 * @start: the routine to be called when the JIT process starts.
162 * @end: the routine to be called when the JIT process ends.
164 * Use this routine to install routines that will be called when JIT
165 * compilation of a method starts and completes.
168 mono_profiler_install_jit_compile (MonoProfileMethodFunc start, MonoProfileMethodResult end)
175 mono_profiler_install_jit_end (MonoProfileJitResult end)
181 mono_profiler_install_method_free (MonoProfileMethodFunc callback)
183 method_free = callback;
187 mono_profiler_install_thread (MonoProfileThreadFunc start, MonoProfileThreadFunc end)
189 thread_start = start;
194 mono_profiler_install_transition (MonoProfileMethodResult callback)
196 man_unman_transition = callback;
200 mono_profiler_install_allocation (MonoProfileAllocFunc callback)
202 allocation_cb = callback;
206 mono_profiler_install_monitor (MonoProfileMonitorFunc callback)
208 monitor_event_cb = callback;
212 mono_profiler_install_statistical (MonoProfileStatFunc callback)
214 statistical_cb = callback;
218 mono_profiler_install_statistical_call_chain (MonoProfileStatCallChainFunc callback, int call_chain_depth) {
219 statistical_call_chain_cb = callback;
220 statistical_call_chain_depth = call_chain_depth;
221 if (statistical_call_chain_depth > MONO_PROFILER_MAX_STAT_CALL_CHAIN_DEPTH) {
222 statistical_call_chain_depth = MONO_PROFILER_MAX_STAT_CALL_CHAIN_DEPTH;
227 mono_profiler_stat_get_call_chain_depth (void) {
228 if (statistical_call_chain_cb != NULL) {
229 return statistical_call_chain_depth;
235 void mono_profiler_install_exception (MonoProfileExceptionFunc throw_callback, MonoProfileMethodFunc exc_method_leave, MonoProfileExceptionClauseFunc clause_callback)
237 exception_throw_cb = throw_callback;
238 exception_method_leave_cb = exc_method_leave;
239 exception_clause_cb = clause_callback;
243 mono_profiler_install_coverage_filter (MonoProfileCoverageFilterFunc callback)
245 coverage_filter_cb = callback;
249 mono_profiler_install_appdomain (MonoProfileAppDomainFunc start_load, MonoProfileAppDomainResult end_load,
250 MonoProfileAppDomainFunc start_unload, MonoProfileAppDomainFunc end_unload)
253 domain_start_load = start_load;
254 domain_end_load = end_load;
255 domain_start_unload = start_unload;
256 domain_end_unload = end_unload;
260 mono_profiler_install_assembly (MonoProfileAssemblyFunc start_load, MonoProfileAssemblyResult end_load,
261 MonoProfileAssemblyFunc start_unload, MonoProfileAssemblyFunc end_unload)
263 assembly_start_load = start_load;
264 assembly_end_load = end_load;
265 assembly_start_unload = start_unload;
266 assembly_end_unload = end_unload;
270 mono_profiler_install_module (MonoProfileModuleFunc start_load, MonoProfileModuleResult end_load,
271 MonoProfileModuleFunc start_unload, MonoProfileModuleFunc end_unload)
273 module_start_load = start_load;
274 module_end_load = end_load;
275 module_start_unload = start_unload;
276 module_end_unload = end_unload;
280 mono_profiler_install_class (MonoProfileClassFunc start_load, MonoProfileClassResult end_load,
281 MonoProfileClassFunc start_unload, MonoProfileClassFunc end_unload)
283 class_start_load = start_load;
284 class_end_load = end_load;
285 class_start_unload = start_unload;
286 class_end_unload = end_unload;
290 mono_profiler_method_enter (MonoMethod *method)
292 if ((mono_profiler_events & MONO_PROFILE_ENTER_LEAVE) && method_enter)
293 method_enter (current_profiler, method);
297 mono_profiler_method_leave (MonoMethod *method)
299 if ((mono_profiler_events & MONO_PROFILE_ENTER_LEAVE) && method_leave)
300 method_leave (current_profiler, method);
304 mono_profiler_method_jit (MonoMethod *method)
306 if ((mono_profiler_events & MONO_PROFILE_JIT_COMPILATION) && jit_start)
307 jit_start (current_profiler, method);
311 mono_profiler_method_end_jit (MonoMethod *method, MonoJitInfo* jinfo, int result)
313 if ((mono_profiler_events & MONO_PROFILE_JIT_COMPILATION)) {
315 jit_end (current_profiler, method, result);
317 jit_end2 (current_profiler, method, jinfo, result);
322 mono_profiler_method_free (MonoMethod *method)
324 if ((mono_profiler_events & MONO_PROFILE_METHOD_EVENTS) && method_free)
325 method_free (current_profiler, method);
329 mono_profiler_code_transition (MonoMethod *method, int result)
331 if ((mono_profiler_events & MONO_PROFILE_TRANSITIONS) && man_unman_transition)
332 man_unman_transition (current_profiler, method, result);
336 mono_profiler_allocation (MonoObject *obj, MonoClass *klass)
338 if ((mono_profiler_events & MONO_PROFILE_ALLOCATIONS) && allocation_cb)
339 allocation_cb (current_profiler, obj, klass);
343 mono_profiler_monitor_event (MonoObject *obj, MonoProfilerMonitorEvent event) {
344 if ((mono_profiler_events & MONO_PROFILE_MONITOR_EVENTS) && monitor_event_cb) {
345 monitor_event_cb (current_profiler, obj, event);
350 mono_profiler_stat_hit (guchar *ip, void *context)
352 if ((mono_profiler_events & MONO_PROFILE_STATISTICAL) && statistical_cb)
353 statistical_cb (current_profiler, ip, context);
357 mono_profiler_stat_call_chain (int call_chain_depth, guchar **ips, void *context)
359 if ((mono_profiler_events & MONO_PROFILE_STATISTICAL) && statistical_call_chain_cb)
360 statistical_call_chain_cb (current_profiler, call_chain_depth, ips, context);
364 mono_profiler_exception_thrown (MonoObject *exception)
366 if ((mono_profiler_events & MONO_PROFILE_EXCEPTIONS) && exception_throw_cb)
367 exception_throw_cb (current_profiler, exception);
371 mono_profiler_exception_method_leave (MonoMethod *method)
373 if ((mono_profiler_events & MONO_PROFILE_EXCEPTIONS) && exception_method_leave_cb)
374 exception_method_leave_cb (current_profiler, method);
378 mono_profiler_exception_clause_handler (MonoMethod *method, int clause_type, int clause_num)
380 if ((mono_profiler_events & MONO_PROFILE_EXCEPTIONS) && exception_clause_cb)
381 exception_clause_cb (current_profiler, method, clause_type, clause_num);
385 mono_profiler_thread_start (gsize tid)
387 if ((mono_profiler_events & MONO_PROFILE_THREADS) && thread_start)
388 thread_start (current_profiler, tid);
392 mono_profiler_thread_end (gsize tid)
394 if ((mono_profiler_events & MONO_PROFILE_THREADS) && thread_end)
395 thread_end (current_profiler, tid);
399 mono_profiler_assembly_event (MonoAssembly *assembly, int code)
401 if (!(mono_profiler_events & MONO_PROFILE_ASSEMBLY_EVENTS))
405 case MONO_PROFILE_START_LOAD:
406 if (assembly_start_load)
407 assembly_start_load (current_profiler, assembly);
409 case MONO_PROFILE_START_UNLOAD:
410 if (assembly_start_unload)
411 assembly_start_unload (current_profiler, assembly);
413 case MONO_PROFILE_END_UNLOAD:
414 if (assembly_end_unload)
415 assembly_end_unload (current_profiler, assembly);
418 g_assert_not_reached ();
423 mono_profiler_assembly_loaded (MonoAssembly *assembly, int result)
425 if ((mono_profiler_events & MONO_PROFILE_ASSEMBLY_EVENTS) && assembly_end_load)
426 assembly_end_load (current_profiler, assembly, result);
430 mono_profiler_module_event (MonoImage *module, int code)
432 if (!(mono_profiler_events & MONO_PROFILE_MODULE_EVENTS))
436 case MONO_PROFILE_START_LOAD:
437 if (module_start_load)
438 module_start_load (current_profiler, module);
440 case MONO_PROFILE_START_UNLOAD:
441 if (module_start_unload)
442 module_start_unload (current_profiler, module);
444 case MONO_PROFILE_END_UNLOAD:
445 if (module_end_unload)
446 module_end_unload (current_profiler, module);
449 g_assert_not_reached ();
454 mono_profiler_module_loaded (MonoImage *module, int result)
456 if ((mono_profiler_events & MONO_PROFILE_MODULE_EVENTS) && module_end_load)
457 module_end_load (current_profiler, module, result);
461 mono_profiler_class_event (MonoClass *klass, int code)
463 if (!(mono_profiler_events & MONO_PROFILE_CLASS_EVENTS))
467 case MONO_PROFILE_START_LOAD:
468 if (class_start_load)
469 class_start_load (current_profiler, klass);
471 case MONO_PROFILE_START_UNLOAD:
472 if (class_start_unload)
473 class_start_unload (current_profiler, klass);
475 case MONO_PROFILE_END_UNLOAD:
476 if (class_end_unload)
477 class_end_unload (current_profiler, klass);
480 g_assert_not_reached ();
485 mono_profiler_class_loaded (MonoClass *klass, int result)
487 if ((mono_profiler_events & MONO_PROFILE_CLASS_EVENTS) && class_end_load)
488 class_end_load (current_profiler, klass, result);
492 mono_profiler_appdomain_event (MonoDomain *domain, int code)
494 if (!(mono_profiler_events & MONO_PROFILE_APPDOMAIN_EVENTS))
498 case MONO_PROFILE_START_LOAD:
499 if (domain_start_load)
500 domain_start_load (current_profiler, domain);
502 case MONO_PROFILE_START_UNLOAD:
503 if (domain_start_unload)
504 domain_start_unload (current_profiler, domain);
506 case MONO_PROFILE_END_UNLOAD:
507 if (domain_end_unload)
508 domain_end_unload (current_profiler, domain);
511 g_assert_not_reached ();
516 mono_profiler_appdomain_loaded (MonoDomain *domain, int result)
518 if ((mono_profiler_events & MONO_PROFILE_APPDOMAIN_EVENTS) && domain_end_load)
519 domain_end_load (current_profiler, domain, result);
523 mono_profiler_shutdown (void)
525 if (current_profiler && shutdown_callback)
526 shutdown_callback (current_profiler);
530 mono_profiler_gc_heap_resize (gint64 new_size)
532 if ((mono_profiler_events & MONO_PROFILE_GC) && gc_heap_resize)
533 gc_heap_resize (current_profiler, new_size);
537 mono_profiler_gc_event (MonoGCEvent event, int generation)
539 if ((mono_profiler_events & MONO_PROFILE_GC) && gc_event)
540 gc_event (current_profiler, event, generation);
544 mono_profiler_install_gc (MonoProfileGCFunc callback, MonoProfileGCResizeFunc heap_resize_callback)
546 mono_gc_enable_events ();
548 gc_heap_resize = heap_resize_callback;
552 mono_profiler_install_runtime_initialized (MonoProfileFunc runtime_initialized_callback)
554 runtime_initialized_event = runtime_initialized_callback;
558 mono_profiler_runtime_initialized (void) {
559 if (runtime_initialized_event)
560 runtime_initialized_event (current_profiler);
563 static MonoProfilerCodeChunkNew code_chunk_new = NULL;
565 mono_profiler_install_code_chunk_new (MonoProfilerCodeChunkNew callback) {
566 code_chunk_new = callback;
569 mono_profiler_code_chunk_new (gpointer chunk, int size) {
571 code_chunk_new (current_profiler, chunk, size);
574 static MonoProfilerCodeChunkDestroy code_chunk_destroy = NULL;
576 mono_profiler_install_code_chunk_destroy (MonoProfilerCodeChunkDestroy callback) {
577 code_chunk_destroy = callback;
580 mono_profiler_code_chunk_destroy (gpointer chunk) {
581 if (code_chunk_destroy)
582 code_chunk_destroy (current_profiler, chunk);
585 static MonoProfilerCodeBufferNew code_buffer_new = NULL;
587 mono_profiler_install_code_buffer_new (MonoProfilerCodeBufferNew callback) {
588 code_buffer_new = callback;
591 mono_profiler_code_buffer_new (gpointer buffer, int size, MonoProfilerCodeBufferType type, void *data) {
593 code_buffer_new (current_profiler, buffer, size, type, data);
596 static GHashTable *coverage_hash = NULL;
598 MonoProfileCoverageInfo*
599 mono_profiler_coverage_alloc (MonoMethod *method, int entries)
601 MonoProfileCoverageInfo *res;
603 if (coverage_filter_cb)
604 if (! (*coverage_filter_cb) (current_profiler, method))
607 mono_profiler_coverage_lock ();
609 coverage_hash = g_hash_table_new (NULL, NULL);
611 res = g_malloc0 (sizeof (MonoProfileCoverageInfo) + sizeof (void*) * 2 * entries);
613 res->entries = entries;
615 g_hash_table_insert (coverage_hash, method, res);
616 mono_profiler_coverage_unlock ();
621 /* safe only when the method antive code has been unloaded */
623 mono_profiler_coverage_free (MonoMethod *method)
625 MonoProfileCoverageInfo* info;
627 mono_profiler_coverage_lock ();
628 if (!coverage_hash) {
629 mono_profiler_coverage_unlock ();
633 info = g_hash_table_lookup (coverage_hash, method);
636 g_hash_table_remove (coverage_hash, method);
638 mono_profiler_coverage_unlock ();
642 * mono_profiler_coverage_get:
643 * @prof: The profiler handle, installed with mono_profiler_install
644 * @method: the method to gather information from.
645 * @func: A routine that will be called back with the results
647 * If the MONO_PROFILER_INS_COVERAGE flag was active during JIT compilation
648 * it is posisble to obtain coverage information about a give method.
650 * The function @func will be invoked repeatedly with instances of the
651 * MonoProfileCoverageEntry structure.
654 mono_profiler_coverage_get (MonoProfiler *prof, MonoMethod *method, MonoProfileCoverageFunc func)
656 MonoProfileCoverageInfo* info;
659 const unsigned char *start, *end, *cil_code;
660 MonoMethodHeader *header;
661 MonoProfileCoverageEntry entry;
662 MonoDebugMethodInfo *debug_minfo;
664 mono_profiler_coverage_lock ();
665 info = g_hash_table_lookup (coverage_hash, method);
666 mono_profiler_coverage_unlock ();
671 header = mono_method_get_header (method);
672 start = mono_method_header_get_code (header, &code_size, NULL);
673 debug_minfo = mono_debug_lookup_method (method);
675 end = start + code_size;
676 for (i = 0; i < info->entries; ++i) {
677 cil_code = info->data [i].cil_code;
678 if (cil_code && cil_code >= start && cil_code < end) {
680 offset = cil_code - start;
681 entry.iloffset = offset;
682 entry.method = method;
683 entry.counter = info->data [i].count;
684 entry.line = entry.col = 1;
685 entry.filename = NULL;
687 MonoDebugSourceLocation *location;
689 location = mono_debug_symfile_lookup_location (debug_minfo, offset);
691 entry.line = location->row;
692 entry.col = location->column;
693 entry.filename = fname = g_strdup (location->source_file);
694 mono_debug_free_source_location (location);
704 #ifndef DISABLE_PROFILER
706 * Small profiler extracted from mint: we should move it in a loadable module
707 * and improve it to do graphs and more accurate timestamping with rdtsc.
710 static FILE* poutput = NULL;
713 #define USE_WIN32COUNTER 0
717 unsigned int lows, highs, lowe, highe;
720 #define rdtsc(low,high) \
721 __asm__ __volatile__("rdtsc" : "=a" (low), "=d" (high))
726 rdtsc_elapsed (MonoRdtscTimer *t)
728 unsigned long long diff;
729 unsigned int highe = t->highe;
730 if (t->lowe < t->lows)
732 diff = (((unsigned long long) highe - t->highs) << 32) + (t->lowe - t->lows);
733 return ((double)diff / freq) / 1000000; /* have to return the result in seconds */
744 if (!(cpuinfo = fopen ("/proc/cpuinfo", "r")))
746 while (fgets (buf, sizeof(buf), cpuinfo)) {
747 if (sscanf (buf, "cpu MHz : %f", &val) == 1) {
748 /*printf ("got mh: %f\n", val);*/
751 if (strncmp (buf, "flags", 5) == 0) {
752 if (strstr (buf, "tsc")) {
754 /*printf ("have tsc\n");*/
759 return have_flag? have_freq: 0;
762 #define MONO_TIMER_STARTUP \
763 if (!(freq = have_rdtsc ())) g_error ("Compiled with TSC support, but none found");
764 #define MONO_TIMER_TYPE MonoRdtscTimer
765 #define MONO_TIMER_INIT(t)
766 #define MONO_TIMER_DESTROY(t)
767 #define MONO_TIMER_START(t) rdtsc ((t).lows, (t).highs);
768 #define MONO_TIMER_STOP(t) rdtsc ((t).lowe, (t).highe);
769 #define MONO_TIMER_ELAPSED(t) rdtsc_elapsed (&(t))
771 #elif USE_WIN32COUNTER
775 LARGE_INTEGER start, stop;
781 win32_elapsed (MonoWin32Timer *t)
783 LONGLONG diff = t->stop.QuadPart - t->start.QuadPart;
784 return ((double)diff / freq) / 1000000; /* have to return the result in seconds */
788 have_win32counter (void) {
791 if (!QueryPerformanceFrequency (&f))
796 #define MONO_TIMER_STARTUP \
797 if (!(freq = have_win32counter ())) g_error ("Compiled with Win32 counter support, but none found");
798 #define MONO_TIMER_TYPE MonoWin32Timer
799 #define MONO_TIMER_INIT(t)
800 #define MONO_TIMER_DESTROY(t)
801 #define MONO_TIMER_START(t) QueryPerformanceCounter (&(t).start)
802 #define MONO_TIMER_STOP(t) QueryPerformanceCounter (&(t).stop)
803 #define MONO_TIMER_ELAPSED(t) win32_elapsed (&(t))
808 GTimeVal start, stop;
812 timeval_elapsed (MonoGLibTimer *t)
814 if (t->start.tv_usec > t->stop.tv_usec) {
815 t->stop.tv_usec += G_USEC_PER_SEC;
818 return (t->stop.tv_sec - t->start.tv_sec)
819 + ((double)(t->stop.tv_usec - t->start.tv_usec))/ G_USEC_PER_SEC;
822 #define MONO_TIMER_STARTUP
823 #define MONO_TIMER_TYPE MonoGLibTimer
824 #define MONO_TIMER_INIT(t)
825 #define MONO_TIMER_DESTROY(t)
826 #define MONO_TIMER_START(t) g_get_current_time (&(t).start)
827 #define MONO_TIMER_STOP(t) g_get_current_time (&(t).stop)
828 #define MONO_TIMER_ELAPSED(t) timeval_elapsed (&(t))
831 typedef struct _AllocInfo AllocInfo;
832 typedef struct _CallerInfo CallerInfo;
833 typedef struct _LastCallerInfo LastCallerInfo;
835 struct _MonoProfiler {
837 MonoMemPool *mempool;
839 /* info about JIT time */
840 MONO_TIMER_TYPE jit_timer;
843 MonoMethod *max_jit_method;
848 /* chain of callers for the current thread */
849 LastCallerInfo *callers;
850 /* LastCallerInfo nodes for faster allocation */
851 LastCallerInfo *cstorage;
858 AllocInfo *alloc_info;
859 CallerInfo *caller_info;
862 typedef struct _MethodCallProfile MethodCallProfile;
864 struct _MethodCallProfile {
865 MethodCallProfile *next;
866 MONO_TIMER_TYPE timer;
883 struct _LastCallerInfo {
884 LastCallerInfo *next;
886 MONO_TIMER_TYPE timer;
890 create_profiler (void)
892 MonoProfiler *prof = g_new0 (MonoProfiler, 1);
894 prof->methods = g_hash_table_new (mono_aligned_addr_hash, NULL);
895 MONO_TIMER_INIT (prof->jit_timer);
896 prof->mempool = mono_mempool_new ();
901 #ifdef HAVE_KW_THREAD
902 static __thread MonoProfiler * tls_profiler;
903 # define GET_PROFILER() tls_profiler
904 # define SET_PROFILER(x) tls_profiler = (x)
905 # define ALLOC_PROFILER() /* nop */
907 static guint32 profiler_thread_id = -1;
908 # define GET_PROFILER() ((MonoProfiler *)TlsGetValue (profiler_thread_id))
909 # define SET_PROFILER(x) TlsSetValue (profiler_thread_id, x);
910 # define ALLOC_PROFILER() profiler_thread_id = TlsAlloc ()
913 #define GET_THREAD_PROF(prof) do { \
914 MonoProfiler *_tprofiler = GET_PROFILER (); \
916 _tprofiler = create_profiler (); \
917 prof->per_thread = g_slist_prepend (prof->per_thread, _tprofiler); \
918 SET_PROFILER (_tprofiler); \
923 /* thread unsafe but faster variant */
924 #define GET_THREAD_PROF(prof)
928 compare_profile (MethodProfile *profa, MethodProfile *profb)
930 return (gint)((profb->total - profa->total)*1000);
934 build_profile (MonoMethod *m, MethodProfile *prof, GList **funcs)
937 *funcs = g_list_insert_sorted (*funcs, prof, (GCompareFunc)compare_profile);
941 method_get_name (MonoMethod* method)
945 sig = mono_signature_get_desc (mono_method_signature (method), FALSE);
946 res = g_strdup_printf ("%s%s%s::%s(%s)", method->klass->name_space,
947 method->klass->name_space ? "." : "", method->klass->name,
953 static void output_callers (MethodProfile *p);
955 /* This isn't defined on older glib versions and on some platforms */
956 #ifndef G_GUINT64_FORMAT
957 #define G_GUINT64_FORMAT "ul"
959 #ifndef G_GINT64_FORMAT
960 #define G_GINT64_FORMAT "lld"
964 output_profile (GList *funcs)
969 guint64 total_calls = 0;
972 fprintf (poutput, "Time(ms) Count P/call(ms) Method name\n");
973 for (tmp = funcs; tmp; tmp = tmp->next) {
975 total_calls += p->count;
976 if (!(gint)(p->total*1000))
978 m = method_get_name (p->method);
979 fprintf (poutput, "########################\n");
980 fprintf (poutput, "% 8.3f ", (double) (p->total * 1000));
981 fprintf (poutput, "%7" G_GUINT64_FORMAT " ", (guint64)p->count);
982 fprintf (poutput, "% 8.3f ", (double) (p->total * 1000)/(double)p->count);
983 fprintf (poutput, " %s\n", m);
989 fprintf (poutput, "Total number of calls: %" G_GINT64_FORMAT "\n", (gint64)total_calls);
998 compare_newobj_profile (NewobjProfile *profa, NewobjProfile *profb)
1000 if (profb->count == profa->count)
1003 return profb->count > profa->count ? 1 : -1;
1007 build_newobj_profile (MonoClass *class, MethodProfile *mprof, GList **funcs)
1009 NewobjProfile *prof = g_new (NewobjProfile, 1);
1014 /* we use the total amount of memory to sort */
1015 for (tmp = mprof->alloc_info; tmp; tmp = tmp->next)
1017 prof->count = count;
1018 *funcs = g_list_insert_sorted (*funcs, prof, (GCompareFunc)compare_newobj_profile);
1022 compare_caller (CallerInfo *a, CallerInfo *b)
1024 return b->count - a->count;
1028 compare_alloc (AllocInfo *a, AllocInfo *b)
1030 return b->mem - a->mem;
1034 sort_alloc_list (AllocInfo *ai)
1038 for (tmp = ai; tmp; tmp = tmp->next) {
1039 l = g_slist_insert_sorted (l, tmp, (GCompareFunc)compare_alloc);
1045 sort_caller_list (CallerInfo *ai)
1049 for (tmp = ai; tmp; tmp = tmp->next) {
1050 l = g_slist_insert_sorted (l, tmp, (GCompareFunc)compare_caller);
1056 output_callers (MethodProfile *p) {
1057 guint total_callers, percent;
1058 GSList *sorted, *tmps;
1062 fprintf (poutput, " Callers (with count) that contribute at least for 1%%:\n");
1064 for (cinfo = p->caller_info; cinfo; cinfo = cinfo->next) {
1065 total_callers += cinfo->count;
1067 sorted = sort_caller_list (p->caller_info);
1068 for (tmps = sorted; tmps; tmps = tmps->next) {
1070 percent = (cinfo->count * 100)/total_callers;
1073 m = method_get_name (cinfo->caller);
1074 fprintf (poutput, " %8d % 3d %% %s\n", cinfo->count, percent, m);
1080 output_newobj_profile (GList *proflist)
1087 const char* isarray;
1091 GSList *sorted, *tmps;
1093 fprintf (poutput, "\nAllocation profiler\n");
1096 fprintf (poutput, "%-9s %s\n", "Total mem", "Method");
1097 for (tmp = proflist; tmp; tmp = tmp->next) {
1100 if (p->count < 50000)
1103 m = method_get_name (mp->method);
1104 fprintf (poutput, "########################\n%8" G_GUINT64_FORMAT " KB %s\n", (p->count / 1024), m);
1106 sorted = sort_alloc_list (mp->alloc_info);
1107 for (tmps = sorted; tmps; tmps = tmps->next) {
1109 if (ainfo->mem < 50000)
1111 klass = ainfo->klass;
1114 klass = klass->element_class;
1118 g_snprintf (buf, sizeof (buf), "%s%s%s%s",
1119 klass->name_space, klass->name_space ? "." : "", klass->name, isarray);
1120 fprintf (poutput, " %8" G_GUINT64_FORMAT " KB %8" G_GUINT64_FORMAT " %-48s\n", (ainfo->mem / 1024), ainfo->count, buf);
1123 output_callers (mp);
1125 fprintf (poutput, "Total memory allocated: %" G_GUINT64_FORMAT " KB\n", total / 1024);
1129 merge_methods (MonoMethod *method, MethodProfile *profile, MonoProfiler *prof)
1131 MethodProfile *mprof;
1132 AllocInfo *talloc_info, *alloc_info;
1133 CallerInfo *tcaller_info, *caller_info;
1135 mprof = g_hash_table_lookup (prof->methods, method);
1137 /* the master thread didn't see this method, just transfer the info as is */
1138 g_hash_table_insert (prof->methods, method, profile);
1141 /* merge the info from profile into mprof */
1142 mprof->count += profile->count;
1143 mprof->total += profile->total;
1144 /* merge alloc info */
1145 for (talloc_info = profile->alloc_info; talloc_info; talloc_info = talloc_info->next) {
1146 for (alloc_info = mprof->alloc_info; alloc_info; alloc_info = alloc_info->next) {
1147 if (alloc_info->klass == talloc_info->klass) {
1148 /* mprof already has a record for the klass, merge */
1149 alloc_info->count += talloc_info->count;
1150 alloc_info->mem += talloc_info->mem;
1155 /* mprof didn't have the info, just copy it over */
1156 alloc_info = mono_mempool_alloc0 (prof->mempool, sizeof (AllocInfo));
1157 *alloc_info = *talloc_info;
1158 alloc_info->next = mprof->alloc_info;
1159 mprof->alloc_info = alloc_info->next;
1162 /* merge callers info */
1163 for (tcaller_info = profile->caller_info; tcaller_info; tcaller_info = tcaller_info->next) {
1164 for (caller_info = mprof->caller_info; caller_info; caller_info = caller_info->next) {
1165 if (caller_info->caller == tcaller_info->caller) {
1166 /* mprof already has a record for the caller method, merge */
1167 caller_info->count += tcaller_info->count;
1172 /* mprof didn't have the info, just copy it over */
1173 caller_info = mono_mempool_alloc0 (prof->mempool, sizeof (CallerInfo));
1174 *caller_info = *tcaller_info;
1175 caller_info->next = mprof->caller_info;
1176 mprof->caller_info = caller_info;
1182 merge_thread_data (MonoProfiler *master, MonoProfiler *tprof)
1184 master->jit_time += tprof->jit_time;
1185 master->methods_jitted += tprof->methods_jitted;
1186 if (master->max_jit_time < tprof->max_jit_time) {
1187 master->max_jit_time = tprof->max_jit_time;
1188 master->max_jit_method = tprof->max_jit_method;
1191 g_hash_table_foreach (tprof->methods, (GHFunc)merge_methods, master);
1195 simple_method_enter (MonoProfiler *prof, MonoMethod *method)
1197 MethodProfile *profile_info;
1198 LastCallerInfo *callinfo;
1199 GET_THREAD_PROF (prof);
1200 /*g_print ("enter %p %s::%s in %d (%p)\n", method, method->klass->name, method->name, GetCurrentThreadId (), prof);*/
1201 if (!(profile_info = g_hash_table_lookup (prof->methods, method))) {
1202 profile_info = mono_mempool_alloc0 (prof->mempool, sizeof (MethodProfile));
1203 MONO_TIMER_INIT (profile_info->u.timer);
1204 g_hash_table_insert (prof->methods, method, profile_info);
1206 profile_info->count++;
1207 if (prof->callers) {
1209 MonoMethod *caller = prof->callers->method;
1210 for (cinfo = profile_info->caller_info; cinfo; cinfo = cinfo->next) {
1211 if (cinfo->caller == caller)
1215 cinfo = mono_mempool_alloc0 (prof->mempool, sizeof (CallerInfo));
1216 cinfo->caller = caller;
1217 cinfo->next = profile_info->caller_info;
1218 profile_info->caller_info = cinfo;
1222 if (!(callinfo = prof->cstorage)) {
1223 callinfo = mono_mempool_alloc (prof->mempool, sizeof (LastCallerInfo));
1224 MONO_TIMER_INIT (callinfo->timer);
1226 prof->cstorage = prof->cstorage->next;
1228 callinfo->method = method;
1229 callinfo->next = prof->callers;
1230 prof->callers = callinfo;
1231 MONO_TIMER_START (callinfo->timer);
1235 simple_method_leave (MonoProfiler *prof, MonoMethod *method)
1237 MethodProfile *profile_info;
1238 LastCallerInfo *callinfo, *newcallinfo = NULL;
1240 GET_THREAD_PROF (prof);
1241 /*g_print ("leave %p %s::%s in %d (%p)\n", method, method->klass->name, method->name, GetCurrentThreadId (), prof);*/
1242 callinfo = prof->callers;
1243 /* should really not happen, but we don't catch exceptions events, yet ... */
1245 MONO_TIMER_STOP (callinfo->timer);
1246 profile_info = g_hash_table_lookup (prof->methods, callinfo->method);
1248 profile_info->total += MONO_TIMER_ELAPSED (callinfo->timer);
1249 newcallinfo = callinfo->next;
1250 callinfo->next = prof->cstorage;
1251 prof->cstorage = callinfo;
1252 if (callinfo->method == method)
1254 callinfo = newcallinfo;
1256 prof->callers = newcallinfo;
1260 simple_allocation (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1262 MethodProfile *profile_info;
1265 GET_THREAD_PROF (prof);
1266 if (prof->callers) {
1267 MonoMethod *caller = prof->callers->method;
1269 /* Otherwise all allocations are attributed to icall_wrapper_mono_object_new */
1270 if (caller->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && prof->callers->next)
1271 caller = prof->callers->next->method;
1273 if (!(profile_info = g_hash_table_lookup (prof->methods, caller)))
1274 g_assert_not_reached ();
1276 return; /* fine for now */
1279 for (tmp = profile_info->alloc_info; tmp; tmp = tmp->next) {
1280 if (tmp->klass == klass)
1284 tmp = mono_mempool_alloc0 (prof->mempool, sizeof (AllocInfo));
1286 tmp->next = profile_info->alloc_info;
1287 profile_info->alloc_info = tmp;
1290 tmp->mem += mono_object_get_size (obj);
1294 simple_method_jit (MonoProfiler *prof, MonoMethod *method)
1296 GET_THREAD_PROF (prof);
1297 prof->methods_jitted++;
1298 MONO_TIMER_START (prof->jit_timer);
1302 simple_method_end_jit (MonoProfiler *prof, MonoMethod *method, int result)
1305 GET_THREAD_PROF (prof);
1306 MONO_TIMER_STOP (prof->jit_timer);
1307 jtime = MONO_TIMER_ELAPSED (prof->jit_timer);
1308 prof->jit_time += jtime;
1309 if (jtime > prof->max_jit_time) {
1310 prof->max_jit_time = jtime;
1311 prof->max_jit_method = method;
1315 /* about 10 minutes of samples */
1316 #define MAX_PROF_SAMPLES (1000*60*10)
1317 static int prof_counts = 0;
1318 static int prof_ucounts = 0;
1319 static gpointer* prof_addresses = NULL;
1320 static GHashTable *prof_table = NULL;
1323 simple_stat_hit (MonoProfiler *prof, guchar *ip, void *context)
1327 if (prof_counts >= MAX_PROF_SAMPLES)
1329 pos = InterlockedIncrement (&prof_counts);
1330 prof_addresses [pos - 1] = ip;
1334 compare_methods_prof (gconstpointer a, gconstpointer b)
1336 int ca = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, a));
1337 int cb = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, b));
1342 prof_foreach (char *method, gpointer c, gpointer data)
1344 GList **list = data;
1345 *list = g_list_insert_sorted (*list, method, compare_methods_prof);
1348 typedef struct Addr2LineData Addr2LineData;
1350 struct Addr2LineData {
1351 Addr2LineData *next;
1358 static Addr2LineData *addr2line_pipes = NULL;
1361 try_addr2line (const char* binary, gpointer ip)
1365 Addr2LineData *addr2line;
1367 for (addr2line = addr2line_pipes; addr2line; addr2line = addr2line->next) {
1368 if (strcmp (binary, addr2line->binary) == 0)
1372 const char *addr_argv[] = {"addr2line", "-f", "-e", binary, NULL};
1376 char monobin [1024];
1377 /* non-linux platforms will need different code here */
1378 if (strcmp (binary, "mono") == 0) {
1379 int count = readlink ("/proc/self/exe", monobin, sizeof (monobin));
1380 if (count >= 0 && count < sizeof (monobin)) {
1381 monobin [count] = 0;
1382 addr_argv [3] = monobin;
1386 if (!g_spawn_async_with_pipes (NULL, (char**)addr_argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
1387 &child_pid, &ch_in, &ch_out, NULL, NULL)) {
1388 return g_strdup (binary);
1390 addr2line = g_new0 (Addr2LineData, 1);
1391 addr2line->child_pid = child_pid;
1392 addr2line->binary = g_strdup (binary);
1393 addr2line->pipein = fdopen (ch_in, "w");
1394 addr2line->pipeout = fdopen (ch_out, "r");
1395 addr2line->next = addr2line_pipes;
1396 addr2line_pipes = addr2line;
1398 fprintf (addr2line->pipein, "%p\n", ip);
1399 fflush (addr2line->pipein);
1400 /* we first get the func name and then file:lineno in a second line */
1401 if (fgets (buf, sizeof (buf), addr2line->pipeout) && buf [0] != '?') {
1402 char *end = strchr (buf, '\n');
1405 res = g_strdup_printf ("%s(%s", binary, buf);
1406 /* discard the filename/line info */
1407 fgets (buf, sizeof (buf), addr2line->pipeout);
1409 res = g_strdup (binary);
1415 stat_prof_report (MonoProfiler *prof)
1418 int count = prof_counts;
1422 GList *tmp, *sorted = NULL;
1424 int pcount = ++ prof_counts;
1426 prof_counts = MAX_PROF_SAMPLES;
1427 for (i = 0; i < count; ++i) {
1428 ip = prof_addresses [i];
1429 ji = mono_jit_info_table_find (mono_domain_get (), ip);
1432 for (l = prof->domains; l && !ji; l = l->next)
1433 ji = mono_jit_info_table_find (l->data, ip);
1437 mn = mono_method_full_name (ji->method, TRUE);
1439 #ifdef HAVE_BACKTRACE_SYMBOLS
1444 names = backtrace_symbols (&ip, 1);
1445 send = strchr (names [0], '+');
1452 send = strchr (names [0], '[');
1455 if (no_func && names [0][0]) {
1456 char *endp = strchr (names [0], 0);
1457 while (--endp >= names [0] && g_ascii_isspace (*endp))
1459 mn = try_addr2line (names [0], ip);
1461 mn = g_strdup (names [0]);
1466 mn = g_strdup_printf ("unmanaged [%p]", ip);
1469 c = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, mn));
1471 g_hash_table_insert (prof_table, mn, GUINT_TO_POINTER (c));
1475 fprintf (poutput, "prof counts: total/unmanaged: %d/%d\n", pcount, prof_ucounts);
1476 g_hash_table_foreach (prof_table, (GHFunc)prof_foreach, &sorted);
1477 for (tmp = sorted; tmp; tmp = tmp->next) {
1479 c = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, tmp->data));
1480 perc = c*100.0/count;
1481 fprintf (poutput, "%7d\t%5.2f %% %s\n", c, perc, (char*)tmp->data);
1483 g_list_free (sorted);
1487 simple_appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
1489 prof->domains = g_slist_prepend (prof->domains, domain);
1493 simple_appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
1495 /* FIXME: we should actually record partial data for each domain,
1496 * but at this point it's must easier using the new logging profiler.
1498 mono_profiler_shutdown ();
1501 static gint32 simple_shutdown_done = FALSE;
1504 simple_shutdown (MonoProfiler *prof)
1506 GList *profile = NULL;
1507 MonoProfiler *tprof;
1510 gint32 see_shutdown_done;
1512 #ifndef PLATFORM_WIN32
1513 mono_thread_attach(mono_get_root_domain());
1516 // Make sure we execute simple_shutdown only once
1517 see_shutdown_done = InterlockedExchange(& simple_shutdown_done, TRUE);
1518 if (see_shutdown_done)
1521 if (mono_profiler_events & MONO_PROFILE_STATISTICAL) {
1522 stat_prof_report (prof);
1525 // Stop all incoming events
1526 mono_profiler_set_events (0);
1528 for (tmp = prof->per_thread; tmp; tmp = tmp->next) {
1530 merge_thread_data (prof, tprof);
1533 fprintf (poutput, "Total time spent compiling %d methods (sec): %.4g\n", prof->methods_jitted, prof->jit_time);
1534 if (prof->max_jit_method) {
1535 str = method_get_name (prof->max_jit_method);
1536 fprintf (poutput, "Slowest method to compile (sec): %.4g: %s\n", prof->max_jit_time, str);
1539 g_hash_table_foreach (prof->methods, (GHFunc)build_profile, &profile);
1540 output_profile (profile);
1541 g_list_free (profile);
1544 g_hash_table_foreach (prof->methods, (GHFunc)build_newobj_profile, &profile);
1545 output_newobj_profile (profile);
1546 g_list_free (profile);
1548 g_free (prof_addresses);
1549 prof_addresses = NULL;
1550 g_hash_table_destroy (prof_table);
1554 mono_profiler_install_simple (const char *desc)
1557 gchar **args, **ptr;
1558 MonoProfileFlags flags = 0;
1564 desc = "alloc,time,jit";
1568 if (strstr (desc, ":"))
1569 desc = strstr (desc, ":") + 1;
1571 desc = "alloc,time,jit";
1572 args = g_strsplit (desc, ",", -1);
1574 for (ptr = args; ptr && *ptr; ptr++) {
1575 const char *arg = *ptr;
1577 // Alwais listen to appdomaon events to shutdown at the first unload
1578 flags |= MONO_PROFILE_APPDOMAIN_EVENTS;
1579 if (!strcmp (arg, "time"))
1580 flags |= MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_EXCEPTIONS;
1581 else if (!strcmp (arg, "alloc"))
1582 flags |= MONO_PROFILE_ALLOCATIONS;
1583 else if (!strcmp (arg, "stat"))
1584 flags |= MONO_PROFILE_STATISTICAL;
1585 else if (!strcmp (arg, "jit"))
1586 flags |= MONO_PROFILE_JIT_COMPILATION;
1587 else if (strncmp (arg, "file=", 5) == 0) {
1588 poutput = fopen (arg + 5, "wb");
1591 fprintf (stderr, "profiler : cannot open profile output file '%s'.\n", arg + 5);
1594 fprintf (stderr, "profiler : Unknown argument '%s'.\n", arg);
1599 if (flags & MONO_PROFILE_ALLOCATIONS)
1600 flags |= MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_EXCEPTIONS;
1602 flags = MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_ALLOCATIONS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_EXCEPTIONS;
1604 prof = create_profiler ();
1606 SET_PROFILER (prof);
1608 /* statistical profiler data */
1609 prof_addresses = g_new0 (gpointer, MAX_PROF_SAMPLES);
1610 prof_table = g_hash_table_new (g_str_hash, g_str_equal);
1612 mono_profiler_install (prof, simple_shutdown);
1613 mono_profiler_install_enter_leave (simple_method_enter, simple_method_leave);
1614 mono_profiler_install_exception (NULL, simple_method_leave, NULL);
1615 mono_profiler_install_jit_compile (simple_method_jit, simple_method_end_jit);
1616 mono_profiler_install_allocation (simple_allocation);
1617 mono_profiler_install_appdomain (NULL, simple_appdomain_load, simple_appdomain_unload, NULL);
1618 mono_profiler_install_statistical (simple_stat_hit);
1619 mono_profiler_set_events (flags);
1622 #endif /* DISABLE_PROFILER */
1624 typedef void (*ProfilerInitializer) (const char*);
1625 #define INITIALIZER_NAME "mono_profiler_startup"
1628 * mono_profiler_load:
1629 * @desc: arguments to configure the profiler
1631 * Invoke this method to initialize the profiler. This will drive the
1632 * loading of the internal ("default") or any external profilers.
1634 * This routine is invoked by Mono's driver, but must be called manually
1635 * if you embed Mono into your application.
1638 mono_profiler_load (const char *desc)
1640 mono_gc_base_init ();
1642 #ifndef DISABLE_PROFILER
1643 if (!desc || (strcmp ("default", desc) == 0) || (strncmp (desc, "default:", 8) == 0)) {
1644 mono_profiler_install_simple (desc);
1653 MonoDl *pmodule = NULL;
1654 const char* col = strchr (desc, ':');
1661 mname = g_memdup (desc, col - desc + 1);
1662 mname [col - desc] = 0;
1664 mname = g_strdup (desc);
1666 libname = g_strdup_printf ("mono-profiler-%s", mname);
1669 while ((path = mono_dl_build_path (NULL, libname, &iter))) {
1671 pmodule = mono_dl_open (path, MONO_DL_LAZY, &err);
1673 ProfilerInitializer func;
1674 if ((err = mono_dl_symbol (pmodule, INITIALIZER_NAME, (gpointer *)&func))) {
1675 g_warning ("Cannot find initializer function %s in profiler module: %s (%s)", INITIALIZER_NAME, libname, err);
1686 g_warning ("Error loading profiler module '%s': %s", libname, err);