2 * profiler.c: Profiler interface for Mono
5 * Paolo Molaro (lupus@ximian.com)
7 * (C) 2001-2003 Ximian, Inc.
8 * (C) 2003-2006 Novell, Inc.
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 MonoProfileStatFunc statistical_cb;
62 static MonoProfileStatCallChainFunc statistical_call_chain_cb;
63 static int statistical_call_chain_depth;
64 static MonoProfileMethodFunc method_enter;
65 static MonoProfileMethodFunc method_leave;
67 static MonoProfileExceptionFunc exception_throw_cb;
68 static MonoProfileMethodFunc exception_method_leave_cb;
69 static MonoProfileExceptionClauseFunc exception_clause_cb;
71 static MonoProfileThreadFunc thread_start;
72 static MonoProfileThreadFunc thread_end;
74 static MonoProfileCoverageFilterFunc coverage_filter_cb;
76 static MonoProfileFunc shutdown_callback;
78 static MonoProfileGCFunc gc_event;
79 static MonoProfileGCResizeFunc gc_heap_resize;
81 static MonoProfileFunc runtime_initialized_event;
83 #define mono_profiler_coverage_lock() EnterCriticalSection (&profiler_coverage_mutex)
84 #define mono_profiler_coverage_unlock() LeaveCriticalSection (&profiler_coverage_mutex)
85 static CRITICAL_SECTION profiler_coverage_mutex;
87 /* this is directly accessible to other mono libs. */
88 MonoProfileFlags mono_profiler_events;
91 * mono_profiler_install:
92 * @prof: a MonoProfiler structure pointer, or a pointer to a derived structure.
93 * @callback: the function to invoke at shutdown
95 * Use mono_profiler_install to activate profiling in the Mono runtime.
96 * Typically developers of new profilers will create a new structure whose
97 * first field is a MonoProfiler and put any extra information that they need
98 * to access from the various profiling callbacks there.
102 mono_profiler_install (MonoProfiler *prof, MonoProfileFunc callback)
104 if (current_profiler)
105 g_error ("profiler already setup");
106 current_profiler = prof;
107 shutdown_callback = callback;
108 InitializeCriticalSection (&profiler_coverage_mutex);
112 * mono_profiler_set_events:
113 * @events: an ORed set of values made up of MONO_PROFILER_ flags
115 * The events descriped in the @events argument is a set of flags
116 * that represent which profiling events must be triggered. For
117 * example if you have registered a set of methods for tracking
118 * JIT compilation start and end with mono_profiler_install_jit_compile,
119 * you will want to pass the MONO_PROFILE_JIT_COMPILATION flag to
122 * You can call mono_profile_set_events more than once and you can
123 * do this at runtime to modify which methods are invoked.
126 mono_profiler_set_events (MonoProfileFlags events)
128 mono_profiler_events = events;
132 * mono_profiler_get_events:
134 * Returns a list of active events that will be intercepted.
137 mono_profiler_get_events (void)
139 return mono_profiler_events;
143 * mono_profiler_install_enter_leave:
144 * @enter: the routine to be called on each method entry
145 * @fleave: the routine to be called each time a method returns
147 * Use this routine to install routines that will be called everytime
148 * a method enters and leaves. The routines will receive as an argument
149 * the MonoMethod representing the method that is entering or leaving.
152 mono_profiler_install_enter_leave (MonoProfileMethodFunc enter, MonoProfileMethodFunc fleave)
154 method_enter = enter;
155 method_leave = fleave;
159 * mono_profiler_install_jit_compile:
160 * @start: the routine to be called when the JIT process starts.
161 * @end: the routine to be called when the JIT process ends.
163 * Use this routine to install routines that will be called when JIT
164 * compilation of a method starts and completes.
167 mono_profiler_install_jit_compile (MonoProfileMethodFunc start, MonoProfileMethodResult end)
174 mono_profiler_install_jit_end (MonoProfileJitResult end)
180 mono_profiler_install_method_free (MonoProfileMethodFunc callback)
182 method_free = callback;
186 mono_profiler_install_thread (MonoProfileThreadFunc start, MonoProfileThreadFunc end)
188 thread_start = start;
193 mono_profiler_install_transition (MonoProfileMethodResult callback)
195 man_unman_transition = callback;
199 mono_profiler_install_allocation (MonoProfileAllocFunc callback)
201 allocation_cb = callback;
205 mono_profiler_install_statistical (MonoProfileStatFunc callback)
207 statistical_cb = callback;
211 mono_profiler_install_statistical_call_chain (MonoProfileStatCallChainFunc callback, int call_chain_depth) {
212 statistical_call_chain_cb = callback;
213 statistical_call_chain_depth = call_chain_depth;
214 if (statistical_call_chain_depth > MONO_PROFILER_MAX_STAT_CALL_CHAIN_DEPTH) {
215 statistical_call_chain_depth = MONO_PROFILER_MAX_STAT_CALL_CHAIN_DEPTH;
220 mono_profiler_stat_get_call_chain_depth (void) {
221 if (statistical_call_chain_cb != NULL) {
222 return statistical_call_chain_depth;
228 void mono_profiler_install_exception (MonoProfileExceptionFunc throw_callback, MonoProfileMethodFunc exc_method_leave, MonoProfileExceptionClauseFunc clause_callback)
230 exception_throw_cb = throw_callback;
231 exception_method_leave_cb = exc_method_leave;
232 exception_clause_cb = clause_callback;
236 mono_profiler_install_coverage_filter (MonoProfileCoverageFilterFunc callback)
238 coverage_filter_cb = callback;
242 mono_profiler_install_appdomain (MonoProfileAppDomainFunc start_load, MonoProfileAppDomainResult end_load,
243 MonoProfileAppDomainFunc start_unload, MonoProfileAppDomainFunc end_unload)
246 domain_start_load = start_load;
247 domain_end_load = end_load;
248 domain_start_unload = start_unload;
249 domain_end_unload = end_unload;
253 mono_profiler_install_assembly (MonoProfileAssemblyFunc start_load, MonoProfileAssemblyResult end_load,
254 MonoProfileAssemblyFunc start_unload, MonoProfileAssemblyFunc end_unload)
256 assembly_start_load = start_load;
257 assembly_end_load = end_load;
258 assembly_start_unload = start_unload;
259 assembly_end_unload = end_unload;
263 mono_profiler_install_module (MonoProfileModuleFunc start_load, MonoProfileModuleResult end_load,
264 MonoProfileModuleFunc start_unload, MonoProfileModuleFunc end_unload)
266 module_start_load = start_load;
267 module_end_load = end_load;
268 module_start_unload = start_unload;
269 module_end_unload = end_unload;
273 mono_profiler_install_class (MonoProfileClassFunc start_load, MonoProfileClassResult end_load,
274 MonoProfileClassFunc start_unload, MonoProfileClassFunc end_unload)
276 class_start_load = start_load;
277 class_end_load = end_load;
278 class_start_unload = start_unload;
279 class_end_unload = end_unload;
283 mono_profiler_method_enter (MonoMethod *method)
285 if ((mono_profiler_events & MONO_PROFILE_ENTER_LEAVE) && method_enter)
286 method_enter (current_profiler, method);
290 mono_profiler_method_leave (MonoMethod *method)
292 if ((mono_profiler_events & MONO_PROFILE_ENTER_LEAVE) && method_leave)
293 method_leave (current_profiler, method);
297 mono_profiler_method_jit (MonoMethod *method)
299 if ((mono_profiler_events & MONO_PROFILE_JIT_COMPILATION) && jit_start)
300 jit_start (current_profiler, method);
304 mono_profiler_method_end_jit (MonoMethod *method, MonoJitInfo* jinfo, int result)
306 if ((mono_profiler_events & MONO_PROFILE_JIT_COMPILATION)) {
308 jit_end (current_profiler, method, result);
310 jit_end2 (current_profiler, method, jinfo, result);
315 mono_profiler_method_free (MonoMethod *method)
317 if ((mono_profiler_events & MONO_PROFILE_METHOD_EVENTS) && method_free)
318 method_free (current_profiler, method);
322 mono_profiler_code_transition (MonoMethod *method, int result)
324 if ((mono_profiler_events & MONO_PROFILE_TRANSITIONS) && man_unman_transition)
325 man_unman_transition (current_profiler, method, result);
329 mono_profiler_allocation (MonoObject *obj, MonoClass *klass)
331 if ((mono_profiler_events & MONO_PROFILE_ALLOCATIONS) && allocation_cb)
332 allocation_cb (current_profiler, obj, klass);
336 mono_profiler_stat_hit (guchar *ip, void *context)
338 if ((mono_profiler_events & MONO_PROFILE_STATISTICAL) && statistical_cb)
339 statistical_cb (current_profiler, ip, context);
343 mono_profiler_stat_call_chain (int call_chain_depth, guchar **ips, void *context)
345 if ((mono_profiler_events & MONO_PROFILE_STATISTICAL) && statistical_call_chain_cb)
346 statistical_call_chain_cb (current_profiler, call_chain_depth, ips, context);
350 mono_profiler_exception_thrown (MonoObject *exception)
352 if ((mono_profiler_events & MONO_PROFILE_EXCEPTIONS) && exception_throw_cb)
353 exception_throw_cb (current_profiler, exception);
357 mono_profiler_exception_method_leave (MonoMethod *method)
359 if ((mono_profiler_events & MONO_PROFILE_EXCEPTIONS) && exception_method_leave_cb)
360 exception_method_leave_cb (current_profiler, method);
364 mono_profiler_exception_clause_handler (MonoMethod *method, int clause_type, int clause_num)
366 if ((mono_profiler_events & MONO_PROFILE_EXCEPTIONS) && exception_clause_cb)
367 exception_clause_cb (current_profiler, method, clause_type, clause_num);
371 mono_profiler_thread_start (gsize tid)
373 if ((mono_profiler_events & MONO_PROFILE_THREADS) && thread_start)
374 thread_start (current_profiler, tid);
378 mono_profiler_thread_end (gsize tid)
380 if ((mono_profiler_events & MONO_PROFILE_THREADS) && thread_end)
381 thread_end (current_profiler, tid);
385 mono_profiler_assembly_event (MonoAssembly *assembly, int code)
387 if (!(mono_profiler_events & MONO_PROFILE_ASSEMBLY_EVENTS))
391 case MONO_PROFILE_START_LOAD:
392 if (assembly_start_load)
393 assembly_start_load (current_profiler, assembly);
395 case MONO_PROFILE_START_UNLOAD:
396 if (assembly_start_unload)
397 assembly_start_unload (current_profiler, assembly);
399 case MONO_PROFILE_END_UNLOAD:
400 if (assembly_end_unload)
401 assembly_end_unload (current_profiler, assembly);
404 g_assert_not_reached ();
409 mono_profiler_assembly_loaded (MonoAssembly *assembly, int result)
411 if ((mono_profiler_events & MONO_PROFILE_ASSEMBLY_EVENTS) && assembly_end_load)
412 assembly_end_load (current_profiler, assembly, result);
416 mono_profiler_module_event (MonoImage *module, int code)
418 if (!(mono_profiler_events & MONO_PROFILE_MODULE_EVENTS))
422 case MONO_PROFILE_START_LOAD:
423 if (module_start_load)
424 module_start_load (current_profiler, module);
426 case MONO_PROFILE_START_UNLOAD:
427 if (module_start_unload)
428 module_start_unload (current_profiler, module);
430 case MONO_PROFILE_END_UNLOAD:
431 if (module_end_unload)
432 module_end_unload (current_profiler, module);
435 g_assert_not_reached ();
440 mono_profiler_module_loaded (MonoImage *module, int result)
442 if ((mono_profiler_events & MONO_PROFILE_MODULE_EVENTS) && module_end_load)
443 module_end_load (current_profiler, module, result);
447 mono_profiler_class_event (MonoClass *klass, int code)
449 if (!(mono_profiler_events & MONO_PROFILE_CLASS_EVENTS))
453 case MONO_PROFILE_START_LOAD:
454 if (class_start_load)
455 class_start_load (current_profiler, klass);
457 case MONO_PROFILE_START_UNLOAD:
458 if (class_start_unload)
459 class_start_unload (current_profiler, klass);
461 case MONO_PROFILE_END_UNLOAD:
462 if (class_end_unload)
463 class_end_unload (current_profiler, klass);
466 g_assert_not_reached ();
471 mono_profiler_class_loaded (MonoClass *klass, int result)
473 if ((mono_profiler_events & MONO_PROFILE_CLASS_EVENTS) && class_end_load)
474 class_end_load (current_profiler, klass, result);
478 mono_profiler_appdomain_event (MonoDomain *domain, int code)
480 if (!(mono_profiler_events & MONO_PROFILE_APPDOMAIN_EVENTS))
484 case MONO_PROFILE_START_LOAD:
485 if (domain_start_load)
486 domain_start_load (current_profiler, domain);
488 case MONO_PROFILE_START_UNLOAD:
489 if (domain_start_unload)
490 domain_start_unload (current_profiler, domain);
492 case MONO_PROFILE_END_UNLOAD:
493 if (domain_end_unload)
494 domain_end_unload (current_profiler, domain);
497 g_assert_not_reached ();
502 mono_profiler_appdomain_loaded (MonoDomain *domain, int result)
504 if ((mono_profiler_events & MONO_PROFILE_APPDOMAIN_EVENTS) && domain_end_load)
505 domain_end_load (current_profiler, domain, result);
509 mono_profiler_shutdown (void)
511 if (current_profiler && shutdown_callback)
512 shutdown_callback (current_profiler);
516 mono_profiler_gc_heap_resize (gint64 new_size)
518 if ((mono_profiler_events & MONO_PROFILE_GC) && gc_heap_resize)
519 gc_heap_resize (current_profiler, new_size);
523 mono_profiler_gc_event (MonoGCEvent event, int generation)
525 if ((mono_profiler_events & MONO_PROFILE_GC) && gc_event)
526 gc_event (current_profiler, event, generation);
530 mono_profiler_install_gc (MonoProfileGCFunc callback, MonoProfileGCResizeFunc heap_resize_callback)
532 mono_gc_enable_events ();
534 gc_heap_resize = heap_resize_callback;
538 mono_profiler_install_runtime_initialized (MonoProfileFunc runtime_initialized_callback)
540 runtime_initialized_event = runtime_initialized_callback;
544 mono_profiler_runtime_initialized (void) {
545 if (runtime_initialized_event)
546 runtime_initialized_event (current_profiler);
550 static GHashTable *coverage_hash = NULL;
552 MonoProfileCoverageInfo*
553 mono_profiler_coverage_alloc (MonoMethod *method, int entries)
555 MonoProfileCoverageInfo *res;
557 if (coverage_filter_cb)
558 if (! (*coverage_filter_cb) (current_profiler, method))
561 mono_profiler_coverage_lock ();
563 coverage_hash = g_hash_table_new (NULL, NULL);
565 res = g_malloc0 (sizeof (MonoProfileCoverageInfo) + sizeof (void*) * 2 * entries);
567 res->entries = entries;
569 g_hash_table_insert (coverage_hash, method, res);
570 mono_profiler_coverage_unlock ();
575 /* safe only when the method antive code has been unloaded */
577 mono_profiler_coverage_free (MonoMethod *method)
579 MonoProfileCoverageInfo* info;
581 mono_profiler_coverage_lock ();
582 if (!coverage_hash) {
583 mono_profiler_coverage_unlock ();
587 info = g_hash_table_lookup (coverage_hash, method);
590 g_hash_table_remove (coverage_hash, method);
592 mono_profiler_coverage_unlock ();
596 * mono_profiler_coverage_get:
597 * @prof: The profiler handle, installed with mono_profiler_install
598 * @method: the method to gather information from.
599 * @func: A routine that will be called back with the results
601 * If the MONO_PROFILER_INS_COVERAGE flag was active during JIT compilation
602 * it is posisble to obtain coverage information about a give method.
604 * The function @func will be invoked repeatedly with instances of the
605 * MonoProfileCoverageEntry structure.
608 mono_profiler_coverage_get (MonoProfiler *prof, MonoMethod *method, MonoProfileCoverageFunc func)
610 MonoProfileCoverageInfo* info;
613 const unsigned char *start, *end, *cil_code;
614 MonoMethodHeader *header;
615 MonoProfileCoverageEntry entry;
616 MonoDebugMethodInfo *debug_minfo;
618 mono_profiler_coverage_lock ();
619 info = g_hash_table_lookup (coverage_hash, method);
620 mono_profiler_coverage_unlock ();
625 header = mono_method_get_header (method);
626 start = mono_method_header_get_code (header, &code_size, NULL);
627 debug_minfo = mono_debug_lookup_method (method);
629 end = start + code_size;
630 for (i = 0; i < info->entries; ++i) {
631 cil_code = info->data [i].cil_code;
632 if (cil_code && cil_code >= start && cil_code < end) {
634 offset = cil_code - start;
635 entry.iloffset = offset;
636 entry.method = method;
637 entry.counter = info->data [i].count;
638 entry.line = entry.col = 1;
639 entry.filename = NULL;
641 MonoDebugSourceLocation *location;
643 location = mono_debug_symfile_lookup_location (debug_minfo, offset);
645 entry.line = location->row;
646 entry.col = location->column;
647 entry.filename = fname = g_strdup (location->source_file);
648 mono_debug_free_source_location (location);
658 #ifndef DISABLE_PROFILER
660 * Small profiler extracted from mint: we should move it in a loadable module
661 * and improve it to do graphs and more accurate timestamping with rdtsc.
664 static FILE* poutput = NULL;
667 #define USE_WIN32COUNTER 0
671 unsigned int lows, highs, lowe, highe;
674 #define rdtsc(low,high) \
675 __asm__ __volatile__("rdtsc" : "=a" (low), "=d" (high))
680 rdtsc_elapsed (MonoRdtscTimer *t)
682 unsigned long long diff;
683 unsigned int highe = t->highe;
684 if (t->lowe < t->lows)
686 diff = (((unsigned long long) highe - t->highs) << 32) + (t->lowe - t->lows);
687 return ((double)diff / freq) / 1000000; /* have to return the result in seconds */
698 if (!(cpuinfo = fopen ("/proc/cpuinfo", "r")))
700 while (fgets (buf, sizeof(buf), cpuinfo)) {
701 if (sscanf (buf, "cpu MHz : %f", &val) == 1) {
702 /*printf ("got mh: %f\n", val);*/
705 if (strncmp (buf, "flags", 5) == 0) {
706 if (strstr (buf, "tsc")) {
708 /*printf ("have tsc\n");*/
713 return have_flag? have_freq: 0;
716 #define MONO_TIMER_STARTUP \
717 if (!(freq = have_rdtsc ())) g_error ("Compiled with TSC support, but none found");
718 #define MONO_TIMER_TYPE MonoRdtscTimer
719 #define MONO_TIMER_INIT(t)
720 #define MONO_TIMER_DESTROY(t)
721 #define MONO_TIMER_START(t) rdtsc ((t).lows, (t).highs);
722 #define MONO_TIMER_STOP(t) rdtsc ((t).lowe, (t).highe);
723 #define MONO_TIMER_ELAPSED(t) rdtsc_elapsed (&(t))
725 #elif USE_WIN32COUNTER
729 LARGE_INTEGER start, stop;
735 win32_elapsed (MonoWin32Timer *t)
737 LONGLONG diff = t->stop.QuadPart - t->start.QuadPart;
738 return ((double)diff / freq) / 1000000; /* have to return the result in seconds */
742 have_win32counter (void) {
745 if (!QueryPerformanceFrequency (&f))
750 #define MONO_TIMER_STARTUP \
751 if (!(freq = have_win32counter ())) g_error ("Compiled with Win32 counter support, but none found");
752 #define MONO_TIMER_TYPE MonoWin32Timer
753 #define MONO_TIMER_INIT(t)
754 #define MONO_TIMER_DESTROY(t)
755 #define MONO_TIMER_START(t) QueryPerformanceCounter (&(t).start)
756 #define MONO_TIMER_STOP(t) QueryPerformanceCounter (&(t).stop)
757 #define MONO_TIMER_ELAPSED(t) win32_elapsed (&(t))
762 GTimeVal start, stop;
766 timeval_elapsed (MonoGLibTimer *t)
768 if (t->start.tv_usec > t->stop.tv_usec) {
769 t->stop.tv_usec += G_USEC_PER_SEC;
772 return (t->stop.tv_sec - t->start.tv_sec)
773 + ((double)(t->stop.tv_usec - t->start.tv_usec))/ G_USEC_PER_SEC;
776 #define MONO_TIMER_STARTUP
777 #define MONO_TIMER_TYPE MonoGLibTimer
778 #define MONO_TIMER_INIT(t)
779 #define MONO_TIMER_DESTROY(t)
780 #define MONO_TIMER_START(t) g_get_current_time (&(t).start)
781 #define MONO_TIMER_STOP(t) g_get_current_time (&(t).stop)
782 #define MONO_TIMER_ELAPSED(t) timeval_elapsed (&(t))
785 typedef struct _AllocInfo AllocInfo;
786 typedef struct _CallerInfo CallerInfo;
787 typedef struct _LastCallerInfo LastCallerInfo;
789 struct _MonoProfiler {
791 MonoMemPool *mempool;
792 /* info about JIT time */
793 MONO_TIMER_TYPE jit_timer;
796 MonoMethod *max_jit_method;
801 /* chain of callers for the current thread */
802 LastCallerInfo *callers;
803 /* LastCallerInfo nodes for faster allocation */
804 LastCallerInfo *cstorage;
811 AllocInfo *alloc_info;
812 CallerInfo *caller_info;
815 typedef struct _MethodCallProfile MethodCallProfile;
817 struct _MethodCallProfile {
818 MethodCallProfile *next;
819 MONO_TIMER_TYPE timer;
836 struct _LastCallerInfo {
837 LastCallerInfo *next;
839 MONO_TIMER_TYPE timer;
843 create_profiler (void)
845 MonoProfiler *prof = g_new0 (MonoProfiler, 1);
847 prof->methods = g_hash_table_new (mono_aligned_addr_hash, NULL);
848 MONO_TIMER_INIT (prof->jit_timer);
849 prof->mempool = mono_mempool_new ();
854 #ifdef HAVE_KW_THREAD
855 static __thread MonoProfiler * tls_profiler;
856 # define GET_PROFILER() tls_profiler
857 # define SET_PROFILER(x) tls_profiler = (x)
858 # define ALLOC_PROFILER() /* nop */
860 static guint32 profiler_thread_id = -1;
861 # define GET_PROFILER() ((MonoProfiler *)TlsGetValue (profiler_thread_id))
862 # define SET_PROFILER(x) TlsSetValue (profiler_thread_id, x);
863 # define ALLOC_PROFILER() profiler_thread_id = TlsAlloc ()
866 #define GET_THREAD_PROF(prof) do { \
867 MonoProfiler *_tprofiler = GET_PROFILER (); \
869 _tprofiler = create_profiler (); \
870 prof->per_thread = g_slist_prepend (prof->per_thread, _tprofiler); \
871 SET_PROFILER (_tprofiler); \
876 /* thread unsafe but faster variant */
877 #define GET_THREAD_PROF(prof)
881 compare_profile (MethodProfile *profa, MethodProfile *profb)
883 return (gint)((profb->total - profa->total)*1000);
887 build_profile (MonoMethod *m, MethodProfile *prof, GList **funcs)
890 *funcs = g_list_insert_sorted (*funcs, prof, (GCompareFunc)compare_profile);
894 method_get_name (MonoMethod* method)
898 sig = mono_signature_get_desc (mono_method_signature (method), FALSE);
899 res = g_strdup_printf ("%s%s%s::%s(%s)", method->klass->name_space,
900 method->klass->name_space ? "." : "", method->klass->name,
906 static void output_callers (MethodProfile *p);
908 /* This isn't defined on older glib versions and on some platforms */
909 #ifndef G_GUINT64_FORMAT
910 #define G_GUINT64_FORMAT "ul"
912 #ifndef G_GINT64_FORMAT
913 #define G_GINT64_FORMAT "lld"
917 output_profile (GList *funcs)
922 guint64 total_calls = 0;
925 fprintf (poutput, "Time(ms) Count P/call(ms) Method name\n");
926 for (tmp = funcs; tmp; tmp = tmp->next) {
928 total_calls += p->count;
929 if (!(gint)(p->total*1000))
931 m = method_get_name (p->method);
932 fprintf (poutput, "########################\n");
933 fprintf (poutput, "% 8.3f ", (double) (p->total * 1000));
934 fprintf (poutput, "%7" G_GUINT64_FORMAT " ", (guint64)p->count);
935 fprintf (poutput, "% 8.3f ", (double) (p->total * 1000)/(double)p->count);
936 fprintf (poutput, " %s\n", m);
942 fprintf (poutput, "Total number of calls: %" G_GINT64_FORMAT "\n", (gint64)total_calls);
951 compare_newobj_profile (NewobjProfile *profa, NewobjProfile *profb)
953 if (profb->count == profa->count)
956 return profb->count > profa->count ? 1 : -1;
960 build_newobj_profile (MonoClass *class, MethodProfile *mprof, GList **funcs)
962 NewobjProfile *prof = g_new (NewobjProfile, 1);
967 /* we use the total amount of memory to sort */
968 for (tmp = mprof->alloc_info; tmp; tmp = tmp->next)
971 *funcs = g_list_insert_sorted (*funcs, prof, (GCompareFunc)compare_newobj_profile);
975 compare_caller (CallerInfo *a, CallerInfo *b)
977 return b->count - a->count;
981 compare_alloc (AllocInfo *a, AllocInfo *b)
983 return b->mem - a->mem;
987 sort_alloc_list (AllocInfo *ai)
991 for (tmp = ai; tmp; tmp = tmp->next) {
992 l = g_slist_insert_sorted (l, tmp, (GCompareFunc)compare_alloc);
998 sort_caller_list (CallerInfo *ai)
1002 for (tmp = ai; tmp; tmp = tmp->next) {
1003 l = g_slist_insert_sorted (l, tmp, (GCompareFunc)compare_caller);
1009 output_callers (MethodProfile *p) {
1010 guint total_callers, percent;
1011 GSList *sorted, *tmps;
1015 fprintf (poutput, " Callers (with count) that contribute at least for 1%%:\n");
1017 for (cinfo = p->caller_info; cinfo; cinfo = cinfo->next) {
1018 total_callers += cinfo->count;
1020 sorted = sort_caller_list (p->caller_info);
1021 for (tmps = sorted; tmps; tmps = tmps->next) {
1023 percent = (cinfo->count * 100)/total_callers;
1026 m = method_get_name (cinfo->caller);
1027 fprintf (poutput, " %8d % 3d %% %s\n", cinfo->count, percent, m);
1033 output_newobj_profile (GList *proflist)
1040 const char* isarray;
1044 GSList *sorted, *tmps;
1046 fprintf (poutput, "\nAllocation profiler\n");
1049 fprintf (poutput, "%-9s %s\n", "Total mem", "Method");
1050 for (tmp = proflist; tmp; tmp = tmp->next) {
1053 if (p->count < 50000)
1056 m = method_get_name (mp->method);
1057 fprintf (poutput, "########################\n%8" G_GUINT64_FORMAT " KB %s\n", (p->count / 1024), m);
1059 sorted = sort_alloc_list (mp->alloc_info);
1060 for (tmps = sorted; tmps; tmps = tmps->next) {
1062 if (ainfo->mem < 50000)
1064 klass = ainfo->klass;
1067 klass = klass->element_class;
1071 g_snprintf (buf, sizeof (buf), "%s%s%s%s",
1072 klass->name_space, klass->name_space ? "." : "", klass->name, isarray);
1073 fprintf (poutput, " %8" G_GUINT64_FORMAT " KB %8" G_GUINT64_FORMAT " %-48s\n", (ainfo->mem / 1024), ainfo->count, buf);
1076 output_callers (mp);
1078 fprintf (poutput, "Total memory allocated: %" G_GUINT64_FORMAT " KB\n", total / 1024);
1082 merge_methods (MonoMethod *method, MethodProfile *profile, MonoProfiler *prof)
1084 MethodProfile *mprof;
1085 AllocInfo *talloc_info, *alloc_info;
1086 CallerInfo *tcaller_info, *caller_info;
1088 mprof = g_hash_table_lookup (prof->methods, method);
1090 /* the master thread didn't see this method, just transfer the info as is */
1091 g_hash_table_insert (prof->methods, method, profile);
1094 /* merge the info from profile into mprof */
1095 mprof->count += profile->count;
1096 mprof->total += profile->total;
1097 /* merge alloc info */
1098 for (talloc_info = profile->alloc_info; talloc_info; talloc_info = talloc_info->next) {
1099 for (alloc_info = mprof->alloc_info; alloc_info; alloc_info = alloc_info->next) {
1100 if (alloc_info->klass == talloc_info->klass) {
1101 /* mprof already has a record for the klass, merge */
1102 alloc_info->count += talloc_info->count;
1103 alloc_info->mem += talloc_info->mem;
1108 /* mprof didn't have the info, just copy it over */
1109 alloc_info = mono_mempool_alloc0 (prof->mempool, sizeof (AllocInfo));
1110 *alloc_info = *talloc_info;
1111 alloc_info->next = mprof->alloc_info;
1112 mprof->alloc_info = alloc_info->next;
1115 /* merge callers info */
1116 for (tcaller_info = profile->caller_info; tcaller_info; tcaller_info = tcaller_info->next) {
1117 for (caller_info = mprof->caller_info; caller_info; caller_info = caller_info->next) {
1118 if (caller_info->caller == tcaller_info->caller) {
1119 /* mprof already has a record for the caller method, merge */
1120 caller_info->count += tcaller_info->count;
1125 /* mprof didn't have the info, just copy it over */
1126 caller_info = mono_mempool_alloc0 (prof->mempool, sizeof (CallerInfo));
1127 *caller_info = *tcaller_info;
1128 caller_info->next = mprof->caller_info;
1129 mprof->caller_info = caller_info;
1135 merge_thread_data (MonoProfiler *master, MonoProfiler *tprof)
1137 master->jit_time += tprof->jit_time;
1138 master->methods_jitted += tprof->methods_jitted;
1139 if (master->max_jit_time < tprof->max_jit_time) {
1140 master->max_jit_time = tprof->max_jit_time;
1141 master->max_jit_method = tprof->max_jit_method;
1144 g_hash_table_foreach (tprof->methods, (GHFunc)merge_methods, master);
1148 simple_method_enter (MonoProfiler *prof, MonoMethod *method)
1150 MethodProfile *profile_info;
1151 LastCallerInfo *callinfo;
1152 GET_THREAD_PROF (prof);
1153 /*g_print ("enter %p %s::%s in %d (%p)\n", method, method->klass->name, method->name, GetCurrentThreadId (), prof);*/
1154 if (!(profile_info = g_hash_table_lookup (prof->methods, method))) {
1155 profile_info = mono_mempool_alloc0 (prof->mempool, sizeof (MethodProfile));
1156 MONO_TIMER_INIT (profile_info->u.timer);
1157 g_hash_table_insert (prof->methods, method, profile_info);
1159 profile_info->count++;
1160 if (prof->callers) {
1162 MonoMethod *caller = prof->callers->method;
1163 for (cinfo = profile_info->caller_info; cinfo; cinfo = cinfo->next) {
1164 if (cinfo->caller == caller)
1168 cinfo = mono_mempool_alloc0 (prof->mempool, sizeof (CallerInfo));
1169 cinfo->caller = caller;
1170 cinfo->next = profile_info->caller_info;
1171 profile_info->caller_info = cinfo;
1175 if (!(callinfo = prof->cstorage)) {
1176 callinfo = mono_mempool_alloc (prof->mempool, sizeof (LastCallerInfo));
1177 MONO_TIMER_INIT (callinfo->timer);
1179 prof->cstorage = prof->cstorage->next;
1181 callinfo->method = method;
1182 callinfo->next = prof->callers;
1183 prof->callers = callinfo;
1184 MONO_TIMER_START (callinfo->timer);
1188 simple_method_leave (MonoProfiler *prof, MonoMethod *method)
1190 MethodProfile *profile_info;
1191 LastCallerInfo *callinfo, *newcallinfo = NULL;
1193 GET_THREAD_PROF (prof);
1194 /*g_print ("leave %p %s::%s in %d (%p)\n", method, method->klass->name, method->name, GetCurrentThreadId (), prof);*/
1195 callinfo = prof->callers;
1196 /* should really not happen, but we don't catch exceptions events, yet ... */
1198 MONO_TIMER_STOP (callinfo->timer);
1199 profile_info = g_hash_table_lookup (prof->methods, callinfo->method);
1201 profile_info->total += MONO_TIMER_ELAPSED (callinfo->timer);
1202 newcallinfo = callinfo->next;
1203 callinfo->next = prof->cstorage;
1204 prof->cstorage = callinfo;
1205 if (callinfo->method == method)
1207 callinfo = newcallinfo;
1209 prof->callers = newcallinfo;
1213 simple_allocation (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1215 MethodProfile *profile_info;
1218 GET_THREAD_PROF (prof);
1219 if (prof->callers) {
1220 MonoMethod *caller = prof->callers->method;
1222 /* Otherwise all allocations are attributed to icall_wrapper_mono_object_new */
1223 if (caller->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
1224 caller = prof->callers->next->method;
1226 if (!(profile_info = g_hash_table_lookup (prof->methods, caller)))
1227 g_assert_not_reached ();
1229 return; /* fine for now */
1232 for (tmp = profile_info->alloc_info; tmp; tmp = tmp->next) {
1233 if (tmp->klass == klass)
1237 tmp = mono_mempool_alloc0 (prof->mempool, sizeof (AllocInfo));
1239 tmp->next = profile_info->alloc_info;
1240 profile_info->alloc_info = tmp;
1243 tmp->mem += mono_object_get_size (obj);
1247 simple_method_jit (MonoProfiler *prof, MonoMethod *method)
1249 GET_THREAD_PROF (prof);
1250 prof->methods_jitted++;
1251 MONO_TIMER_START (prof->jit_timer);
1255 simple_method_end_jit (MonoProfiler *prof, MonoMethod *method, int result)
1258 GET_THREAD_PROF (prof);
1259 MONO_TIMER_STOP (prof->jit_timer);
1260 jtime = MONO_TIMER_ELAPSED (prof->jit_timer);
1261 prof->jit_time += jtime;
1262 if (jtime > prof->max_jit_time) {
1263 prof->max_jit_time = jtime;
1264 prof->max_jit_method = method;
1268 /* about 10 minutes of samples */
1269 #define MAX_PROF_SAMPLES (1000*60*10)
1270 static int prof_counts = 0;
1271 static int prof_ucounts = 0;
1272 static gpointer* prof_addresses = NULL;
1273 static GHashTable *prof_table = NULL;
1276 simple_stat_hit (MonoProfiler *prof, guchar *ip, void *context)
1280 if (prof_counts >= MAX_PROF_SAMPLES)
1282 pos = InterlockedIncrement (&prof_counts);
1283 prof_addresses [pos - 1] = ip;
1287 compare_methods_prof (gconstpointer a, gconstpointer b)
1289 int ca = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, a));
1290 int cb = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, b));
1295 prof_foreach (char *method, gpointer c, gpointer data)
1297 GList **list = data;
1298 *list = g_list_insert_sorted (*list, method, compare_methods_prof);
1301 typedef struct Addr2LineData Addr2LineData;
1303 struct Addr2LineData {
1304 Addr2LineData *next;
1311 static Addr2LineData *addr2line_pipes = NULL;
1314 try_addr2line (const char* binary, gpointer ip)
1318 Addr2LineData *addr2line;
1320 for (addr2line = addr2line_pipes; addr2line; addr2line = addr2line->next) {
1321 if (strcmp (binary, addr2line->binary) == 0)
1325 const char *addr_argv[] = {"addr2line", "-f", "-e", binary, NULL};
1329 char monobin [1024];
1330 /* non-linux platforms will need different code here */
1331 if (strcmp (binary, "mono") == 0) {
1332 int count = readlink ("/proc/self/exe", monobin, sizeof (monobin));
1333 if (count >= 0 && count < sizeof (monobin)) {
1334 monobin [count] = 0;
1335 addr_argv [3] = monobin;
1339 if (!g_spawn_async_with_pipes (NULL, (char**)addr_argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
1340 &child_pid, &ch_in, &ch_out, NULL, NULL)) {
1341 return g_strdup (binary);
1343 addr2line = g_new0 (Addr2LineData, 1);
1344 addr2line->child_pid = child_pid;
1345 addr2line->binary = g_strdup (binary);
1346 addr2line->pipein = fdopen (ch_in, "w");
1347 addr2line->pipeout = fdopen (ch_out, "r");
1348 addr2line->next = addr2line_pipes;
1349 addr2line_pipes = addr2line;
1351 fprintf (addr2line->pipein, "%p\n", ip);
1352 fflush (addr2line->pipein);
1353 /* we first get the func name and then file:lineno in a second line */
1354 if (fgets (buf, sizeof (buf), addr2line->pipeout) && buf [0] != '?') {
1355 char *end = strchr (buf, '\n');
1358 res = g_strdup_printf ("%s(%s", binary, buf);
1359 /* discard the filename/line info */
1360 fgets (buf, sizeof (buf), addr2line->pipeout);
1362 res = g_strdup (binary);
1368 stat_prof_report (void)
1371 int count = prof_counts;
1375 GList *tmp, *sorted = NULL;
1376 int pcount = ++ prof_counts;
1378 prof_counts = MAX_PROF_SAMPLES;
1379 for (i = 0; i < count; ++i) {
1380 ip = prof_addresses [i];
1381 ji = mono_jit_info_table_find (mono_domain_get (), ip);
1383 mn = mono_method_full_name (ji->method, TRUE);
1385 #ifdef HAVE_BACKTRACE_SYMBOLS
1390 names = backtrace_symbols (&ip, 1);
1391 send = strchr (names [0], '+');
1398 send = strchr (names [0], '[');
1401 if (no_func && names [0][0]) {
1402 char *endp = strchr (names [0], 0);
1403 while (--endp >= names [0] && g_ascii_isspace (*endp))
1405 mn = try_addr2line (names [0], ip);
1407 mn = g_strdup (names [0]);
1412 mn = g_strdup_printf ("unmanaged [%p]", ip);
1415 c = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, mn));
1417 g_hash_table_insert (prof_table, mn, GUINT_TO_POINTER (c));
1421 fprintf (poutput, "prof counts: total/unmanaged: %d/%d\n", pcount, prof_ucounts);
1422 g_hash_table_foreach (prof_table, (GHFunc)prof_foreach, &sorted);
1423 for (tmp = sorted; tmp; tmp = tmp->next) {
1425 c = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, tmp->data));
1426 perc = c*100.0/count;
1427 fprintf (poutput, "%7d\t%5.2f %% %s\n", c, perc, (char*)tmp->data);
1429 g_list_free (sorted);
1433 simple_appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
1435 /* FIXME: we should actually record partial data for each domain,
1436 * but at this point it's must easier using the new logging profiler.
1438 mono_profiler_shutdown ();
1441 static gint32 simple_shutdown_done = FALSE;
1444 simple_shutdown (MonoProfiler *prof)
1446 GList *profile = NULL;
1447 MonoProfiler *tprof;
1450 gint32 see_shutdown_done;
1452 mono_thread_attach(mono_get_root_domain());
1454 // Make sure we execute simple_shutdown only once
1455 see_shutdown_done = InterlockedExchange(& simple_shutdown_done, TRUE);
1456 if (see_shutdown_done)
1459 if (mono_profiler_events & MONO_PROFILE_STATISTICAL) {
1460 stat_prof_report ();
1463 // Stop all incoming events
1464 mono_profiler_set_events (0);
1466 for (tmp = prof->per_thread; tmp; tmp = tmp->next) {
1468 merge_thread_data (prof, tprof);
1471 fprintf (poutput, "Total time spent compiling %d methods (sec): %.4g\n", prof->methods_jitted, prof->jit_time);
1472 if (prof->max_jit_method) {
1473 str = method_get_name (prof->max_jit_method);
1474 fprintf (poutput, "Slowest method to compile (sec): %.4g: %s\n", prof->max_jit_time, str);
1477 g_hash_table_foreach (prof->methods, (GHFunc)build_profile, &profile);
1478 output_profile (profile);
1479 g_list_free (profile);
1482 g_hash_table_foreach (prof->methods, (GHFunc)build_newobj_profile, &profile);
1483 output_newobj_profile (profile);
1484 g_list_free (profile);
1486 g_free (prof_addresses);
1487 prof_addresses = NULL;
1488 g_hash_table_destroy (prof_table);
1492 mono_profiler_install_simple (const char *desc)
1495 gchar **args, **ptr;
1496 MonoProfileFlags flags = 0;
1502 desc = "alloc,time,jit";
1506 if (strstr (desc, ":"))
1507 desc = strstr (desc, ":") + 1;
1509 desc = "alloc,time,jit";
1510 args = g_strsplit (desc, ",", -1);
1512 for (ptr = args; ptr && *ptr; ptr++) {
1513 const char *arg = *ptr;
1515 // Alwais listen to appdomaon events to shutdown at the first unload
1516 flags |= MONO_PROFILE_APPDOMAIN_EVENTS;
1517 if (!strcmp (arg, "time"))
1518 flags |= MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_EXCEPTIONS;
1519 else if (!strcmp (arg, "alloc"))
1520 flags |= MONO_PROFILE_ALLOCATIONS;
1521 else if (!strcmp (arg, "stat"))
1522 flags |= MONO_PROFILE_STATISTICAL;
1523 else if (!strcmp (arg, "jit"))
1524 flags |= MONO_PROFILE_JIT_COMPILATION;
1525 else if (strncmp (arg, "file=", 5) == 0) {
1526 poutput = fopen (arg + 5, "wb");
1529 fprintf (stderr, "profiler : cannot open profile output file '%s'.\n", arg + 5);
1532 fprintf (stderr, "profiler : Unknown argument '%s'.\n", arg);
1537 if (flags & MONO_PROFILE_ALLOCATIONS)
1538 flags |= MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_EXCEPTIONS;
1540 flags = MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_ALLOCATIONS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_EXCEPTIONS;
1542 prof = create_profiler ();
1544 SET_PROFILER (prof);
1546 /* statistical profiler data */
1547 prof_addresses = g_new0 (gpointer, MAX_PROF_SAMPLES);
1548 prof_table = g_hash_table_new (g_str_hash, g_str_equal);
1550 mono_profiler_install (prof, simple_shutdown);
1551 mono_profiler_install_enter_leave (simple_method_enter, simple_method_leave);
1552 mono_profiler_install_exception (NULL, simple_method_leave, NULL);
1553 mono_profiler_install_jit_compile (simple_method_jit, simple_method_end_jit);
1554 mono_profiler_install_allocation (simple_allocation);
1555 mono_profiler_install_appdomain (NULL, NULL, simple_appdomain_unload, NULL);
1556 mono_profiler_install_statistical (simple_stat_hit);
1557 mono_profiler_set_events (flags);
1560 #endif /* DISABLE_PROFILER */
1562 typedef void (*ProfilerInitializer) (const char*);
1563 #define INITIALIZER_NAME "mono_profiler_startup"
1566 * mono_profiler_load:
1567 * @desc: arguments to configure the profiler
1569 * Invoke this method to initialize the profiler. This will drive the
1570 * loading of the internal ("default") or any external profilers.
1572 * This routine is invoked by Mono's driver, but must be called manually
1573 * if you embed Mono into your application.
1576 mono_profiler_load (const char *desc)
1578 #ifndef DISABLE_PROFILER
1579 if (!desc || (strcmp ("default", desc) == 0) || (strncmp (desc, "default:", 8) == 0)) {
1580 mono_profiler_install_simple (desc);
1590 const char* col = strchr (desc, ':');
1597 mname = g_memdup (desc, col - desc + 1);
1598 mname [col - desc] = 0;
1600 mname = g_strdup (desc);
1602 libname = g_strdup_printf ("mono-profiler-%s", mname);
1605 while ((path = mono_dl_build_path (NULL, libname, &iter))) {
1607 pmodule = mono_dl_open (path, MONO_DL_LAZY, &err);
1609 ProfilerInitializer func;
1610 if ((err = mono_dl_symbol (pmodule, INITIALIZER_NAME, (gpointer *)&func))) {
1611 g_warning ("Cannot find initializer function %s in profiler module: %s (%s)", INITIALIZER_NAME, libname, err);
1622 g_warning ("Error loading profiler module '%s': %s", libname, err);