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);
564 static GHashTable *coverage_hash = NULL;
566 MonoProfileCoverageInfo*
567 mono_profiler_coverage_alloc (MonoMethod *method, int entries)
569 MonoProfileCoverageInfo *res;
571 if (coverage_filter_cb)
572 if (! (*coverage_filter_cb) (current_profiler, method))
575 mono_profiler_coverage_lock ();
577 coverage_hash = g_hash_table_new (NULL, NULL);
579 res = g_malloc0 (sizeof (MonoProfileCoverageInfo) + sizeof (void*) * 2 * entries);
581 res->entries = entries;
583 g_hash_table_insert (coverage_hash, method, res);
584 mono_profiler_coverage_unlock ();
589 /* safe only when the method antive code has been unloaded */
591 mono_profiler_coverage_free (MonoMethod *method)
593 MonoProfileCoverageInfo* info;
595 mono_profiler_coverage_lock ();
596 if (!coverage_hash) {
597 mono_profiler_coverage_unlock ();
601 info = g_hash_table_lookup (coverage_hash, method);
604 g_hash_table_remove (coverage_hash, method);
606 mono_profiler_coverage_unlock ();
610 * mono_profiler_coverage_get:
611 * @prof: The profiler handle, installed with mono_profiler_install
612 * @method: the method to gather information from.
613 * @func: A routine that will be called back with the results
615 * If the MONO_PROFILER_INS_COVERAGE flag was active during JIT compilation
616 * it is posisble to obtain coverage information about a give method.
618 * The function @func will be invoked repeatedly with instances of the
619 * MonoProfileCoverageEntry structure.
622 mono_profiler_coverage_get (MonoProfiler *prof, MonoMethod *method, MonoProfileCoverageFunc func)
624 MonoProfileCoverageInfo* info;
627 const unsigned char *start, *end, *cil_code;
628 MonoMethodHeader *header;
629 MonoProfileCoverageEntry entry;
630 MonoDebugMethodInfo *debug_minfo;
632 mono_profiler_coverage_lock ();
633 info = g_hash_table_lookup (coverage_hash, method);
634 mono_profiler_coverage_unlock ();
639 header = mono_method_get_header (method);
640 start = mono_method_header_get_code (header, &code_size, NULL);
641 debug_minfo = mono_debug_lookup_method (method);
643 end = start + code_size;
644 for (i = 0; i < info->entries; ++i) {
645 cil_code = info->data [i].cil_code;
646 if (cil_code && cil_code >= start && cil_code < end) {
648 offset = cil_code - start;
649 entry.iloffset = offset;
650 entry.method = method;
651 entry.counter = info->data [i].count;
652 entry.line = entry.col = 1;
653 entry.filename = NULL;
655 MonoDebugSourceLocation *location;
657 location = mono_debug_symfile_lookup_location (debug_minfo, offset);
659 entry.line = location->row;
660 entry.col = location->column;
661 entry.filename = fname = g_strdup (location->source_file);
662 mono_debug_free_source_location (location);
672 #ifndef DISABLE_PROFILER
674 * Small profiler extracted from mint: we should move it in a loadable module
675 * and improve it to do graphs and more accurate timestamping with rdtsc.
678 static FILE* poutput = NULL;
681 #define USE_WIN32COUNTER 0
685 unsigned int lows, highs, lowe, highe;
688 #define rdtsc(low,high) \
689 __asm__ __volatile__("rdtsc" : "=a" (low), "=d" (high))
694 rdtsc_elapsed (MonoRdtscTimer *t)
696 unsigned long long diff;
697 unsigned int highe = t->highe;
698 if (t->lowe < t->lows)
700 diff = (((unsigned long long) highe - t->highs) << 32) + (t->lowe - t->lows);
701 return ((double)diff / freq) / 1000000; /* have to return the result in seconds */
712 if (!(cpuinfo = fopen ("/proc/cpuinfo", "r")))
714 while (fgets (buf, sizeof(buf), cpuinfo)) {
715 if (sscanf (buf, "cpu MHz : %f", &val) == 1) {
716 /*printf ("got mh: %f\n", val);*/
719 if (strncmp (buf, "flags", 5) == 0) {
720 if (strstr (buf, "tsc")) {
722 /*printf ("have tsc\n");*/
727 return have_flag? have_freq: 0;
730 #define MONO_TIMER_STARTUP \
731 if (!(freq = have_rdtsc ())) g_error ("Compiled with TSC support, but none found");
732 #define MONO_TIMER_TYPE MonoRdtscTimer
733 #define MONO_TIMER_INIT(t)
734 #define MONO_TIMER_DESTROY(t)
735 #define MONO_TIMER_START(t) rdtsc ((t).lows, (t).highs);
736 #define MONO_TIMER_STOP(t) rdtsc ((t).lowe, (t).highe);
737 #define MONO_TIMER_ELAPSED(t) rdtsc_elapsed (&(t))
739 #elif USE_WIN32COUNTER
743 LARGE_INTEGER start, stop;
749 win32_elapsed (MonoWin32Timer *t)
751 LONGLONG diff = t->stop.QuadPart - t->start.QuadPart;
752 return ((double)diff / freq) / 1000000; /* have to return the result in seconds */
756 have_win32counter (void) {
759 if (!QueryPerformanceFrequency (&f))
764 #define MONO_TIMER_STARTUP \
765 if (!(freq = have_win32counter ())) g_error ("Compiled with Win32 counter support, but none found");
766 #define MONO_TIMER_TYPE MonoWin32Timer
767 #define MONO_TIMER_INIT(t)
768 #define MONO_TIMER_DESTROY(t)
769 #define MONO_TIMER_START(t) QueryPerformanceCounter (&(t).start)
770 #define MONO_TIMER_STOP(t) QueryPerformanceCounter (&(t).stop)
771 #define MONO_TIMER_ELAPSED(t) win32_elapsed (&(t))
776 GTimeVal start, stop;
780 timeval_elapsed (MonoGLibTimer *t)
782 if (t->start.tv_usec > t->stop.tv_usec) {
783 t->stop.tv_usec += G_USEC_PER_SEC;
786 return (t->stop.tv_sec - t->start.tv_sec)
787 + ((double)(t->stop.tv_usec - t->start.tv_usec))/ G_USEC_PER_SEC;
790 #define MONO_TIMER_STARTUP
791 #define MONO_TIMER_TYPE MonoGLibTimer
792 #define MONO_TIMER_INIT(t)
793 #define MONO_TIMER_DESTROY(t)
794 #define MONO_TIMER_START(t) g_get_current_time (&(t).start)
795 #define MONO_TIMER_STOP(t) g_get_current_time (&(t).stop)
796 #define MONO_TIMER_ELAPSED(t) timeval_elapsed (&(t))
799 typedef struct _AllocInfo AllocInfo;
800 typedef struct _CallerInfo CallerInfo;
801 typedef struct _LastCallerInfo LastCallerInfo;
803 struct _MonoProfiler {
805 MonoMemPool *mempool;
807 /* info about JIT time */
808 MONO_TIMER_TYPE jit_timer;
811 MonoMethod *max_jit_method;
816 /* chain of callers for the current thread */
817 LastCallerInfo *callers;
818 /* LastCallerInfo nodes for faster allocation */
819 LastCallerInfo *cstorage;
826 AllocInfo *alloc_info;
827 CallerInfo *caller_info;
830 typedef struct _MethodCallProfile MethodCallProfile;
832 struct _MethodCallProfile {
833 MethodCallProfile *next;
834 MONO_TIMER_TYPE timer;
851 struct _LastCallerInfo {
852 LastCallerInfo *next;
854 MONO_TIMER_TYPE timer;
858 create_profiler (void)
860 MonoProfiler *prof = g_new0 (MonoProfiler, 1);
862 prof->methods = g_hash_table_new (mono_aligned_addr_hash, NULL);
863 MONO_TIMER_INIT (prof->jit_timer);
864 prof->mempool = mono_mempool_new ();
869 #ifdef HAVE_KW_THREAD
870 static __thread MonoProfiler * tls_profiler;
871 # define GET_PROFILER() tls_profiler
872 # define SET_PROFILER(x) tls_profiler = (x)
873 # define ALLOC_PROFILER() /* nop */
875 static guint32 profiler_thread_id = -1;
876 # define GET_PROFILER() ((MonoProfiler *)TlsGetValue (profiler_thread_id))
877 # define SET_PROFILER(x) TlsSetValue (profiler_thread_id, x);
878 # define ALLOC_PROFILER() profiler_thread_id = TlsAlloc ()
881 #define GET_THREAD_PROF(prof) do { \
882 MonoProfiler *_tprofiler = GET_PROFILER (); \
884 _tprofiler = create_profiler (); \
885 prof->per_thread = g_slist_prepend (prof->per_thread, _tprofiler); \
886 SET_PROFILER (_tprofiler); \
891 /* thread unsafe but faster variant */
892 #define GET_THREAD_PROF(prof)
896 compare_profile (MethodProfile *profa, MethodProfile *profb)
898 return (gint)((profb->total - profa->total)*1000);
902 build_profile (MonoMethod *m, MethodProfile *prof, GList **funcs)
905 *funcs = g_list_insert_sorted (*funcs, prof, (GCompareFunc)compare_profile);
909 method_get_name (MonoMethod* method)
913 sig = mono_signature_get_desc (mono_method_signature (method), FALSE);
914 res = g_strdup_printf ("%s%s%s::%s(%s)", method->klass->name_space,
915 method->klass->name_space ? "." : "", method->klass->name,
921 static void output_callers (MethodProfile *p);
923 /* This isn't defined on older glib versions and on some platforms */
924 #ifndef G_GUINT64_FORMAT
925 #define G_GUINT64_FORMAT "ul"
927 #ifndef G_GINT64_FORMAT
928 #define G_GINT64_FORMAT "lld"
932 output_profile (GList *funcs)
937 guint64 total_calls = 0;
940 fprintf (poutput, "Time(ms) Count P/call(ms) Method name\n");
941 for (tmp = funcs; tmp; tmp = tmp->next) {
943 total_calls += p->count;
944 if (!(gint)(p->total*1000))
946 m = method_get_name (p->method);
947 fprintf (poutput, "########################\n");
948 fprintf (poutput, "% 8.3f ", (double) (p->total * 1000));
949 fprintf (poutput, "%7" G_GUINT64_FORMAT " ", (guint64)p->count);
950 fprintf (poutput, "% 8.3f ", (double) (p->total * 1000)/(double)p->count);
951 fprintf (poutput, " %s\n", m);
957 fprintf (poutput, "Total number of calls: %" G_GINT64_FORMAT "\n", (gint64)total_calls);
966 compare_newobj_profile (NewobjProfile *profa, NewobjProfile *profb)
968 if (profb->count == profa->count)
971 return profb->count > profa->count ? 1 : -1;
975 build_newobj_profile (MonoClass *class, MethodProfile *mprof, GList **funcs)
977 NewobjProfile *prof = g_new (NewobjProfile, 1);
982 /* we use the total amount of memory to sort */
983 for (tmp = mprof->alloc_info; tmp; tmp = tmp->next)
986 *funcs = g_list_insert_sorted (*funcs, prof, (GCompareFunc)compare_newobj_profile);
990 compare_caller (CallerInfo *a, CallerInfo *b)
992 return b->count - a->count;
996 compare_alloc (AllocInfo *a, AllocInfo *b)
998 return b->mem - a->mem;
1002 sort_alloc_list (AllocInfo *ai)
1006 for (tmp = ai; tmp; tmp = tmp->next) {
1007 l = g_slist_insert_sorted (l, tmp, (GCompareFunc)compare_alloc);
1013 sort_caller_list (CallerInfo *ai)
1017 for (tmp = ai; tmp; tmp = tmp->next) {
1018 l = g_slist_insert_sorted (l, tmp, (GCompareFunc)compare_caller);
1024 output_callers (MethodProfile *p) {
1025 guint total_callers, percent;
1026 GSList *sorted, *tmps;
1030 fprintf (poutput, " Callers (with count) that contribute at least for 1%%:\n");
1032 for (cinfo = p->caller_info; cinfo; cinfo = cinfo->next) {
1033 total_callers += cinfo->count;
1035 sorted = sort_caller_list (p->caller_info);
1036 for (tmps = sorted; tmps; tmps = tmps->next) {
1038 percent = (cinfo->count * 100)/total_callers;
1041 m = method_get_name (cinfo->caller);
1042 fprintf (poutput, " %8d % 3d %% %s\n", cinfo->count, percent, m);
1048 output_newobj_profile (GList *proflist)
1055 const char* isarray;
1059 GSList *sorted, *tmps;
1061 fprintf (poutput, "\nAllocation profiler\n");
1064 fprintf (poutput, "%-9s %s\n", "Total mem", "Method");
1065 for (tmp = proflist; tmp; tmp = tmp->next) {
1068 if (p->count < 50000)
1071 m = method_get_name (mp->method);
1072 fprintf (poutput, "########################\n%8" G_GUINT64_FORMAT " KB %s\n", (p->count / 1024), m);
1074 sorted = sort_alloc_list (mp->alloc_info);
1075 for (tmps = sorted; tmps; tmps = tmps->next) {
1077 if (ainfo->mem < 50000)
1079 klass = ainfo->klass;
1082 klass = klass->element_class;
1086 g_snprintf (buf, sizeof (buf), "%s%s%s%s",
1087 klass->name_space, klass->name_space ? "." : "", klass->name, isarray);
1088 fprintf (poutput, " %8" G_GUINT64_FORMAT " KB %8" G_GUINT64_FORMAT " %-48s\n", (ainfo->mem / 1024), ainfo->count, buf);
1091 output_callers (mp);
1093 fprintf (poutput, "Total memory allocated: %" G_GUINT64_FORMAT " KB\n", total / 1024);
1097 merge_methods (MonoMethod *method, MethodProfile *profile, MonoProfiler *prof)
1099 MethodProfile *mprof;
1100 AllocInfo *talloc_info, *alloc_info;
1101 CallerInfo *tcaller_info, *caller_info;
1103 mprof = g_hash_table_lookup (prof->methods, method);
1105 /* the master thread didn't see this method, just transfer the info as is */
1106 g_hash_table_insert (prof->methods, method, profile);
1109 /* merge the info from profile into mprof */
1110 mprof->count += profile->count;
1111 mprof->total += profile->total;
1112 /* merge alloc info */
1113 for (talloc_info = profile->alloc_info; talloc_info; talloc_info = talloc_info->next) {
1114 for (alloc_info = mprof->alloc_info; alloc_info; alloc_info = alloc_info->next) {
1115 if (alloc_info->klass == talloc_info->klass) {
1116 /* mprof already has a record for the klass, merge */
1117 alloc_info->count += talloc_info->count;
1118 alloc_info->mem += talloc_info->mem;
1123 /* mprof didn't have the info, just copy it over */
1124 alloc_info = mono_mempool_alloc0 (prof->mempool, sizeof (AllocInfo));
1125 *alloc_info = *talloc_info;
1126 alloc_info->next = mprof->alloc_info;
1127 mprof->alloc_info = alloc_info->next;
1130 /* merge callers info */
1131 for (tcaller_info = profile->caller_info; tcaller_info; tcaller_info = tcaller_info->next) {
1132 for (caller_info = mprof->caller_info; caller_info; caller_info = caller_info->next) {
1133 if (caller_info->caller == tcaller_info->caller) {
1134 /* mprof already has a record for the caller method, merge */
1135 caller_info->count += tcaller_info->count;
1140 /* mprof didn't have the info, just copy it over */
1141 caller_info = mono_mempool_alloc0 (prof->mempool, sizeof (CallerInfo));
1142 *caller_info = *tcaller_info;
1143 caller_info->next = mprof->caller_info;
1144 mprof->caller_info = caller_info;
1150 merge_thread_data (MonoProfiler *master, MonoProfiler *tprof)
1152 master->jit_time += tprof->jit_time;
1153 master->methods_jitted += tprof->methods_jitted;
1154 if (master->max_jit_time < tprof->max_jit_time) {
1155 master->max_jit_time = tprof->max_jit_time;
1156 master->max_jit_method = tprof->max_jit_method;
1159 g_hash_table_foreach (tprof->methods, (GHFunc)merge_methods, master);
1163 simple_method_enter (MonoProfiler *prof, MonoMethod *method)
1165 MethodProfile *profile_info;
1166 LastCallerInfo *callinfo;
1167 GET_THREAD_PROF (prof);
1168 /*g_print ("enter %p %s::%s in %d (%p)\n", method, method->klass->name, method->name, GetCurrentThreadId (), prof);*/
1169 if (!(profile_info = g_hash_table_lookup (prof->methods, method))) {
1170 profile_info = mono_mempool_alloc0 (prof->mempool, sizeof (MethodProfile));
1171 MONO_TIMER_INIT (profile_info->u.timer);
1172 g_hash_table_insert (prof->methods, method, profile_info);
1174 profile_info->count++;
1175 if (prof->callers) {
1177 MonoMethod *caller = prof->callers->method;
1178 for (cinfo = profile_info->caller_info; cinfo; cinfo = cinfo->next) {
1179 if (cinfo->caller == caller)
1183 cinfo = mono_mempool_alloc0 (prof->mempool, sizeof (CallerInfo));
1184 cinfo->caller = caller;
1185 cinfo->next = profile_info->caller_info;
1186 profile_info->caller_info = cinfo;
1190 if (!(callinfo = prof->cstorage)) {
1191 callinfo = mono_mempool_alloc (prof->mempool, sizeof (LastCallerInfo));
1192 MONO_TIMER_INIT (callinfo->timer);
1194 prof->cstorage = prof->cstorage->next;
1196 callinfo->method = method;
1197 callinfo->next = prof->callers;
1198 prof->callers = callinfo;
1199 MONO_TIMER_START (callinfo->timer);
1203 simple_method_leave (MonoProfiler *prof, MonoMethod *method)
1205 MethodProfile *profile_info;
1206 LastCallerInfo *callinfo, *newcallinfo = NULL;
1208 GET_THREAD_PROF (prof);
1209 /*g_print ("leave %p %s::%s in %d (%p)\n", method, method->klass->name, method->name, GetCurrentThreadId (), prof);*/
1210 callinfo = prof->callers;
1211 /* should really not happen, but we don't catch exceptions events, yet ... */
1213 MONO_TIMER_STOP (callinfo->timer);
1214 profile_info = g_hash_table_lookup (prof->methods, callinfo->method);
1216 profile_info->total += MONO_TIMER_ELAPSED (callinfo->timer);
1217 newcallinfo = callinfo->next;
1218 callinfo->next = prof->cstorage;
1219 prof->cstorage = callinfo;
1220 if (callinfo->method == method)
1222 callinfo = newcallinfo;
1224 prof->callers = newcallinfo;
1228 simple_allocation (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1230 MethodProfile *profile_info;
1233 GET_THREAD_PROF (prof);
1234 if (prof->callers) {
1235 MonoMethod *caller = prof->callers->method;
1237 /* Otherwise all allocations are attributed to icall_wrapper_mono_object_new */
1238 if (caller->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && prof->callers->next)
1239 caller = prof->callers->next->method;
1241 if (!(profile_info = g_hash_table_lookup (prof->methods, caller)))
1242 g_assert_not_reached ();
1244 return; /* fine for now */
1247 for (tmp = profile_info->alloc_info; tmp; tmp = tmp->next) {
1248 if (tmp->klass == klass)
1252 tmp = mono_mempool_alloc0 (prof->mempool, sizeof (AllocInfo));
1254 tmp->next = profile_info->alloc_info;
1255 profile_info->alloc_info = tmp;
1258 tmp->mem += mono_object_get_size (obj);
1262 simple_method_jit (MonoProfiler *prof, MonoMethod *method)
1264 GET_THREAD_PROF (prof);
1265 prof->methods_jitted++;
1266 MONO_TIMER_START (prof->jit_timer);
1270 simple_method_end_jit (MonoProfiler *prof, MonoMethod *method, int result)
1273 GET_THREAD_PROF (prof);
1274 MONO_TIMER_STOP (prof->jit_timer);
1275 jtime = MONO_TIMER_ELAPSED (prof->jit_timer);
1276 prof->jit_time += jtime;
1277 if (jtime > prof->max_jit_time) {
1278 prof->max_jit_time = jtime;
1279 prof->max_jit_method = method;
1283 /* about 10 minutes of samples */
1284 #define MAX_PROF_SAMPLES (1000*60*10)
1285 static int prof_counts = 0;
1286 static int prof_ucounts = 0;
1287 static gpointer* prof_addresses = NULL;
1288 static GHashTable *prof_table = NULL;
1291 simple_stat_hit (MonoProfiler *prof, guchar *ip, void *context)
1295 if (prof_counts >= MAX_PROF_SAMPLES)
1297 pos = InterlockedIncrement (&prof_counts);
1298 prof_addresses [pos - 1] = ip;
1302 compare_methods_prof (gconstpointer a, gconstpointer b)
1304 int ca = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, a));
1305 int cb = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, b));
1310 prof_foreach (char *method, gpointer c, gpointer data)
1312 GList **list = data;
1313 *list = g_list_insert_sorted (*list, method, compare_methods_prof);
1316 typedef struct Addr2LineData Addr2LineData;
1318 struct Addr2LineData {
1319 Addr2LineData *next;
1326 static Addr2LineData *addr2line_pipes = NULL;
1329 try_addr2line (const char* binary, gpointer ip)
1333 Addr2LineData *addr2line;
1335 for (addr2line = addr2line_pipes; addr2line; addr2line = addr2line->next) {
1336 if (strcmp (binary, addr2line->binary) == 0)
1340 const char *addr_argv[] = {"addr2line", "-f", "-e", binary, NULL};
1344 char monobin [1024];
1345 /* non-linux platforms will need different code here */
1346 if (strcmp (binary, "mono") == 0) {
1347 int count = readlink ("/proc/self/exe", monobin, sizeof (monobin));
1348 if (count >= 0 && count < sizeof (monobin)) {
1349 monobin [count] = 0;
1350 addr_argv [3] = monobin;
1354 if (!g_spawn_async_with_pipes (NULL, (char**)addr_argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
1355 &child_pid, &ch_in, &ch_out, NULL, NULL)) {
1356 return g_strdup (binary);
1358 addr2line = g_new0 (Addr2LineData, 1);
1359 addr2line->child_pid = child_pid;
1360 addr2line->binary = g_strdup (binary);
1361 addr2line->pipein = fdopen (ch_in, "w");
1362 addr2line->pipeout = fdopen (ch_out, "r");
1363 addr2line->next = addr2line_pipes;
1364 addr2line_pipes = addr2line;
1366 fprintf (addr2line->pipein, "%p\n", ip);
1367 fflush (addr2line->pipein);
1368 /* we first get the func name and then file:lineno in a second line */
1369 if (fgets (buf, sizeof (buf), addr2line->pipeout) && buf [0] != '?') {
1370 char *end = strchr (buf, '\n');
1373 res = g_strdup_printf ("%s(%s", binary, buf);
1374 /* discard the filename/line info */
1375 fgets (buf, sizeof (buf), addr2line->pipeout);
1377 res = g_strdup (binary);
1383 stat_prof_report (MonoProfiler *prof)
1386 int count = prof_counts;
1390 GList *tmp, *sorted = NULL;
1392 int pcount = ++ prof_counts;
1394 prof_counts = MAX_PROF_SAMPLES;
1395 for (i = 0; i < count; ++i) {
1396 ip = prof_addresses [i];
1397 ji = mono_jit_info_table_find (mono_domain_get (), ip);
1400 for (l = prof->domains; l && !ji; l = l->next)
1401 ji = mono_jit_info_table_find (l->data, ip);
1405 mn = mono_method_full_name (ji->method, TRUE);
1407 #ifdef HAVE_BACKTRACE_SYMBOLS
1412 names = backtrace_symbols (&ip, 1);
1413 send = strchr (names [0], '+');
1420 send = strchr (names [0], '[');
1423 if (no_func && names [0][0]) {
1424 char *endp = strchr (names [0], 0);
1425 while (--endp >= names [0] && g_ascii_isspace (*endp))
1427 mn = try_addr2line (names [0], ip);
1429 mn = g_strdup (names [0]);
1434 mn = g_strdup_printf ("unmanaged [%p]", ip);
1437 c = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, mn));
1439 g_hash_table_insert (prof_table, mn, GUINT_TO_POINTER (c));
1443 fprintf (poutput, "prof counts: total/unmanaged: %d/%d\n", pcount, prof_ucounts);
1444 g_hash_table_foreach (prof_table, (GHFunc)prof_foreach, &sorted);
1445 for (tmp = sorted; tmp; tmp = tmp->next) {
1447 c = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, tmp->data));
1448 perc = c*100.0/count;
1449 fprintf (poutput, "%7d\t%5.2f %% %s\n", c, perc, (char*)tmp->data);
1451 g_list_free (sorted);
1455 simple_appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
1457 prof->domains = g_slist_prepend (prof->domains, domain);
1461 simple_appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
1463 /* FIXME: we should actually record partial data for each domain,
1464 * but at this point it's must easier using the new logging profiler.
1466 mono_profiler_shutdown ();
1469 static gint32 simple_shutdown_done = FALSE;
1472 simple_shutdown (MonoProfiler *prof)
1474 GList *profile = NULL;
1475 MonoProfiler *tprof;
1478 gint32 see_shutdown_done;
1480 #ifndef PLATFORM_WIN32
1481 mono_thread_attach(mono_get_root_domain());
1484 // Make sure we execute simple_shutdown only once
1485 see_shutdown_done = InterlockedExchange(& simple_shutdown_done, TRUE);
1486 if (see_shutdown_done)
1489 if (mono_profiler_events & MONO_PROFILE_STATISTICAL) {
1490 stat_prof_report (prof);
1493 // Stop all incoming events
1494 mono_profiler_set_events (0);
1496 for (tmp = prof->per_thread; tmp; tmp = tmp->next) {
1498 merge_thread_data (prof, tprof);
1501 fprintf (poutput, "Total time spent compiling %d methods (sec): %.4g\n", prof->methods_jitted, prof->jit_time);
1502 if (prof->max_jit_method) {
1503 str = method_get_name (prof->max_jit_method);
1504 fprintf (poutput, "Slowest method to compile (sec): %.4g: %s\n", prof->max_jit_time, str);
1507 g_hash_table_foreach (prof->methods, (GHFunc)build_profile, &profile);
1508 output_profile (profile);
1509 g_list_free (profile);
1512 g_hash_table_foreach (prof->methods, (GHFunc)build_newobj_profile, &profile);
1513 output_newobj_profile (profile);
1514 g_list_free (profile);
1516 g_free (prof_addresses);
1517 prof_addresses = NULL;
1518 g_hash_table_destroy (prof_table);
1522 mono_profiler_install_simple (const char *desc)
1525 gchar **args, **ptr;
1526 MonoProfileFlags flags = 0;
1532 desc = "alloc,time,jit";
1536 if (strstr (desc, ":"))
1537 desc = strstr (desc, ":") + 1;
1539 desc = "alloc,time,jit";
1540 args = g_strsplit (desc, ",", -1);
1542 for (ptr = args; ptr && *ptr; ptr++) {
1543 const char *arg = *ptr;
1545 // Alwais listen to appdomaon events to shutdown at the first unload
1546 flags |= MONO_PROFILE_APPDOMAIN_EVENTS;
1547 if (!strcmp (arg, "time"))
1548 flags |= MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_EXCEPTIONS;
1549 else if (!strcmp (arg, "alloc"))
1550 flags |= MONO_PROFILE_ALLOCATIONS;
1551 else if (!strcmp (arg, "stat"))
1552 flags |= MONO_PROFILE_STATISTICAL;
1553 else if (!strcmp (arg, "jit"))
1554 flags |= MONO_PROFILE_JIT_COMPILATION;
1555 else if (strncmp (arg, "file=", 5) == 0) {
1556 poutput = fopen (arg + 5, "wb");
1559 fprintf (stderr, "profiler : cannot open profile output file '%s'.\n", arg + 5);
1562 fprintf (stderr, "profiler : Unknown argument '%s'.\n", arg);
1567 if (flags & MONO_PROFILE_ALLOCATIONS)
1568 flags |= MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_EXCEPTIONS;
1570 flags = MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_ALLOCATIONS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_EXCEPTIONS;
1572 prof = create_profiler ();
1574 SET_PROFILER (prof);
1576 /* statistical profiler data */
1577 prof_addresses = g_new0 (gpointer, MAX_PROF_SAMPLES);
1578 prof_table = g_hash_table_new (g_str_hash, g_str_equal);
1580 mono_profiler_install (prof, simple_shutdown);
1581 mono_profiler_install_enter_leave (simple_method_enter, simple_method_leave);
1582 mono_profiler_install_exception (NULL, simple_method_leave, NULL);
1583 mono_profiler_install_jit_compile (simple_method_jit, simple_method_end_jit);
1584 mono_profiler_install_allocation (simple_allocation);
1585 mono_profiler_install_appdomain (NULL, simple_appdomain_load, simple_appdomain_unload, NULL);
1586 mono_profiler_install_statistical (simple_stat_hit);
1587 mono_profiler_set_events (flags);
1590 #endif /* DISABLE_PROFILER */
1592 typedef void (*ProfilerInitializer) (const char*);
1593 #define INITIALIZER_NAME "mono_profiler_startup"
1596 * mono_profiler_load:
1597 * @desc: arguments to configure the profiler
1599 * Invoke this method to initialize the profiler. This will drive the
1600 * loading of the internal ("default") or any external profilers.
1602 * This routine is invoked by Mono's driver, but must be called manually
1603 * if you embed Mono into your application.
1606 mono_profiler_load (const char *desc)
1608 mono_gc_base_init ();
1610 #ifndef DISABLE_PROFILER
1611 if (!desc || (strcmp ("default", desc) == 0) || (strncmp (desc, "default:", 8) == 0)) {
1612 mono_profiler_install_simple (desc);
1622 const char* col = strchr (desc, ':');
1629 mname = g_memdup (desc, col - desc + 1);
1630 mname [col - desc] = 0;
1632 mname = g_strdup (desc);
1634 libname = g_strdup_printf ("mono-profiler-%s", mname);
1637 while ((path = mono_dl_build_path (NULL, libname, &iter))) {
1639 pmodule = mono_dl_open (path, MONO_DL_LAZY, &err);
1641 ProfilerInitializer func;
1642 if ((err = mono_dl_symbol (pmodule, INITIALIZER_NAME, (gpointer *)&func))) {
1643 g_warning ("Cannot find initializer function %s in profiler module: %s (%s)", INITIALIZER_NAME, libname, err);
1654 g_warning ("Error loading profiler module '%s': %s", libname, err);