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 MonoProfileMethodFunc method_enter;
63 static MonoProfileMethodFunc method_leave;
65 static MonoProfileExceptionFunc exception_throw_cb;
66 static MonoProfileMethodFunc exception_method_leave_cb;
67 static MonoProfileExceptionClauseFunc exception_clause_cb;
69 static MonoProfileThreadFunc thread_start;
70 static MonoProfileThreadFunc thread_end;
72 static MonoProfileCoverageFilterFunc coverage_filter_cb;
74 static MonoProfileFunc shutdown_callback;
76 static MonoProfileGCFunc gc_event;
77 static MonoProfileGCResizeFunc gc_heap_resize;
79 #define mono_profiler_coverage_lock() EnterCriticalSection (&profiler_coverage_mutex)
80 #define mono_profiler_coverage_unlock() LeaveCriticalSection (&profiler_coverage_mutex)
81 static CRITICAL_SECTION profiler_coverage_mutex;
83 /* this is directly accessible to other mono libs. */
84 MonoProfileFlags mono_profiler_events;
87 * mono_profiler_install:
88 * @prof: a MonoProfiler structure pointer, or a pointer to a derived structure.
89 * @callback: the function to invoke at shutdown
91 * Use mono_profiler_install to activate profiling in the Mono runtime.
92 * Typically developers of new profilers will create a new structure whose
93 * first field is a MonoProfiler and put any extra information that they need
94 * to access from the various profiling callbacks there.
98 mono_profiler_install (MonoProfiler *prof, MonoProfileFunc callback)
100 if (current_profiler)
101 g_error ("profiler already setup");
102 current_profiler = prof;
103 shutdown_callback = callback;
104 InitializeCriticalSection (&profiler_coverage_mutex);
108 * mono_profiler_set_events:
109 * @events: an ORed set of values made up of MONO_PROFILER_ flags
111 * The events descriped in the @events argument is a set of flags
112 * that represent which profiling events must be triggered. For
113 * example if you have registered a set of methods for tracking
114 * JIT compilation start and end with mono_profiler_install_jit_compile,
115 * you will want to pass the MONO_PROFILE_JIT_COMPILATION flag to
118 * You can call mono_profile_set_events more than once and you can
119 * do this at runtime to modify which methods are invoked.
122 mono_profiler_set_events (MonoProfileFlags events)
124 mono_profiler_events = events;
128 * mono_profiler_get_events:
130 * Returns a list of active events that will be intercepted.
133 mono_profiler_get_events (void)
135 return mono_profiler_events;
139 * mono_profiler_install_enter_leave:
140 * @enter: the routine to be called on each method entry
141 * @fleave: the routine to be called each time a method returns
143 * Use this routine to install routines that will be called everytime
144 * a method enters and leaves. The routines will receive as an argument
145 * the MonoMethod representing the method that is entering or leaving.
148 mono_profiler_install_enter_leave (MonoProfileMethodFunc enter, MonoProfileMethodFunc fleave)
150 method_enter = enter;
151 method_leave = fleave;
155 * mono_profiler_install_jit_compile:
156 * @start: the routine to be called when the JIT process starts.
157 * @end: the routine to be called when the JIT process ends.
159 * Use this routine to install routines that will be called when JIT
160 * compilation of a method starts and completes.
163 mono_profiler_install_jit_compile (MonoProfileMethodFunc start, MonoProfileMethodResult end)
170 mono_profiler_install_jit_end (MonoProfileJitResult end)
176 mono_profiler_install_method_free (MonoProfileMethodFunc callback)
178 method_free = callback;
182 mono_profiler_install_thread (MonoProfileThreadFunc start, MonoProfileThreadFunc end)
184 thread_start = start;
189 mono_profiler_install_transition (MonoProfileMethodResult callback)
191 man_unman_transition = callback;
195 mono_profiler_install_allocation (MonoProfileAllocFunc callback)
197 allocation_cb = callback;
201 mono_profiler_install_statistical (MonoProfileStatFunc callback)
203 statistical_cb = callback;
206 void mono_profiler_install_exception (MonoProfileExceptionFunc throw_callback, MonoProfileMethodFunc exc_method_leave, MonoProfileExceptionClauseFunc clause_callback)
208 exception_throw_cb = throw_callback;
209 exception_method_leave_cb = exc_method_leave;
210 exception_clause_cb = clause_callback;
214 mono_profiler_install_coverage_filter (MonoProfileCoverageFilterFunc callback)
216 coverage_filter_cb = callback;
220 mono_profiler_install_appdomain (MonoProfileAppDomainFunc start_load, MonoProfileAppDomainResult end_load,
221 MonoProfileAppDomainFunc start_unload, MonoProfileAppDomainFunc end_unload)
224 domain_start_load = start_load;
225 domain_end_load = end_load;
226 domain_start_unload = start_unload;
227 domain_end_unload = end_unload;
231 mono_profiler_install_assembly (MonoProfileAssemblyFunc start_load, MonoProfileAssemblyResult end_load,
232 MonoProfileAssemblyFunc start_unload, MonoProfileAssemblyFunc end_unload)
234 assembly_start_load = start_load;
235 assembly_end_load = end_load;
236 assembly_start_unload = start_unload;
237 assembly_end_unload = end_unload;
241 mono_profiler_install_module (MonoProfileModuleFunc start_load, MonoProfileModuleResult end_load,
242 MonoProfileModuleFunc start_unload, MonoProfileModuleFunc end_unload)
244 module_start_load = start_load;
245 module_end_load = end_load;
246 module_start_unload = start_unload;
247 module_end_unload = end_unload;
251 mono_profiler_install_class (MonoProfileClassFunc start_load, MonoProfileClassResult end_load,
252 MonoProfileClassFunc start_unload, MonoProfileClassFunc end_unload)
254 class_start_load = start_load;
255 class_end_load = end_load;
256 class_start_unload = start_unload;
257 class_end_unload = end_unload;
261 mono_profiler_method_enter (MonoMethod *method)
263 if ((mono_profiler_events & MONO_PROFILE_ENTER_LEAVE) && method_enter)
264 method_enter (current_profiler, method);
268 mono_profiler_method_leave (MonoMethod *method)
270 if ((mono_profiler_events & MONO_PROFILE_ENTER_LEAVE) && method_leave)
271 method_leave (current_profiler, method);
275 mono_profiler_method_jit (MonoMethod *method)
277 if ((mono_profiler_events & MONO_PROFILE_JIT_COMPILATION) && jit_start)
278 jit_start (current_profiler, method);
282 mono_profiler_method_end_jit (MonoMethod *method, MonoJitInfo* jinfo, int result)
284 if ((mono_profiler_events & MONO_PROFILE_JIT_COMPILATION)) {
286 jit_end (current_profiler, method, result);
288 jit_end2 (current_profiler, method, jinfo, result);
293 mono_profiler_method_free (MonoMethod *method)
295 if ((mono_profiler_events & MONO_PROFILE_METHOD_EVENTS) && method_free)
296 method_free (current_profiler, method);
300 mono_profiler_code_transition (MonoMethod *method, int result)
302 if ((mono_profiler_events & MONO_PROFILE_TRANSITIONS) && man_unman_transition)
303 man_unman_transition (current_profiler, method, result);
307 mono_profiler_allocation (MonoObject *obj, MonoClass *klass)
309 if ((mono_profiler_events & MONO_PROFILE_ALLOCATIONS) && allocation_cb)
310 allocation_cb (current_profiler, obj, klass);
314 mono_profiler_stat_hit (guchar *ip, void *context)
316 if ((mono_profiler_events & MONO_PROFILE_STATISTICAL) && statistical_cb)
317 statistical_cb (current_profiler, ip, context);
321 mono_profiler_exception_thrown (MonoObject *exception)
323 if ((mono_profiler_events & MONO_PROFILE_EXCEPTIONS) && exception_throw_cb)
324 exception_throw_cb (current_profiler, exception);
328 mono_profiler_exception_method_leave (MonoMethod *method)
330 if ((mono_profiler_events & MONO_PROFILE_EXCEPTIONS) && exception_method_leave_cb)
331 exception_method_leave_cb (current_profiler, method);
335 mono_profiler_exception_clause_handler (MonoMethod *method, int clause_type, int clause_num)
337 if ((mono_profiler_events & MONO_PROFILE_EXCEPTIONS) && exception_clause_cb)
338 exception_clause_cb (current_profiler, method, clause_type, clause_num);
342 mono_profiler_thread_start (gsize tid)
344 if ((mono_profiler_events & MONO_PROFILE_THREADS) && thread_start)
345 thread_start (current_profiler, tid);
349 mono_profiler_thread_end (gsize tid)
351 if ((mono_profiler_events & MONO_PROFILE_THREADS) && thread_end)
352 thread_end (current_profiler, tid);
356 mono_profiler_assembly_event (MonoAssembly *assembly, int code)
358 if (!(mono_profiler_events & MONO_PROFILE_ASSEMBLY_EVENTS))
362 case MONO_PROFILE_START_LOAD:
363 if (assembly_start_load)
364 assembly_start_load (current_profiler, assembly);
366 case MONO_PROFILE_START_UNLOAD:
367 if (assembly_start_unload)
368 assembly_start_unload (current_profiler, assembly);
370 case MONO_PROFILE_END_UNLOAD:
371 if (assembly_end_unload)
372 assembly_end_unload (current_profiler, assembly);
375 g_assert_not_reached ();
380 mono_profiler_assembly_loaded (MonoAssembly *assembly, int result)
382 if ((mono_profiler_events & MONO_PROFILE_ASSEMBLY_EVENTS) && assembly_end_load)
383 assembly_end_load (current_profiler, assembly, result);
387 mono_profiler_module_event (MonoImage *module, int code)
389 if (!(mono_profiler_events & MONO_PROFILE_MODULE_EVENTS))
393 case MONO_PROFILE_START_LOAD:
394 if (module_start_load)
395 module_start_load (current_profiler, module);
397 case MONO_PROFILE_START_UNLOAD:
398 if (module_start_unload)
399 module_start_unload (current_profiler, module);
401 case MONO_PROFILE_END_UNLOAD:
402 if (module_end_unload)
403 module_end_unload (current_profiler, module);
406 g_assert_not_reached ();
411 mono_profiler_module_loaded (MonoImage *module, int result)
413 if ((mono_profiler_events & MONO_PROFILE_MODULE_EVENTS) && module_end_load)
414 module_end_load (current_profiler, module, result);
418 mono_profiler_class_event (MonoClass *klass, int code)
420 if (!(mono_profiler_events & MONO_PROFILE_CLASS_EVENTS))
424 case MONO_PROFILE_START_LOAD:
425 if (class_start_load)
426 class_start_load (current_profiler, klass);
428 case MONO_PROFILE_START_UNLOAD:
429 if (class_start_unload)
430 class_start_unload (current_profiler, klass);
432 case MONO_PROFILE_END_UNLOAD:
433 if (class_end_unload)
434 class_end_unload (current_profiler, klass);
437 g_assert_not_reached ();
442 mono_profiler_class_loaded (MonoClass *klass, int result)
444 if ((mono_profiler_events & MONO_PROFILE_CLASS_EVENTS) && class_end_load)
445 class_end_load (current_profiler, klass, result);
449 mono_profiler_appdomain_event (MonoDomain *domain, int code)
451 if (!(mono_profiler_events & MONO_PROFILE_APPDOMAIN_EVENTS))
455 case MONO_PROFILE_START_LOAD:
456 if (domain_start_load)
457 domain_start_load (current_profiler, domain);
459 case MONO_PROFILE_START_UNLOAD:
460 if (domain_start_unload)
461 domain_start_unload (current_profiler, domain);
463 case MONO_PROFILE_END_UNLOAD:
464 if (domain_end_unload)
465 domain_end_unload (current_profiler, domain);
468 g_assert_not_reached ();
473 mono_profiler_appdomain_loaded (MonoDomain *domain, int result)
475 if ((mono_profiler_events & MONO_PROFILE_APPDOMAIN_EVENTS) && domain_end_load)
476 domain_end_load (current_profiler, domain, result);
480 mono_profiler_shutdown (void)
482 if (current_profiler && shutdown_callback)
483 shutdown_callback (current_profiler);
487 mono_profiler_gc_heap_resize (gint64 new_size)
489 if ((mono_profiler_events & MONO_PROFILE_GC) && gc_heap_resize)
490 gc_heap_resize (current_profiler, new_size);
494 mono_profiler_gc_event (MonoGCEvent event, int generation)
496 if ((mono_profiler_events & MONO_PROFILE_GC) && gc_event)
497 gc_event (current_profiler, event, generation);
501 mono_profiler_install_gc (MonoProfileGCFunc callback, MonoProfileGCResizeFunc heap_resize_callback)
503 mono_gc_enable_events ();
505 gc_heap_resize = heap_resize_callback;
508 static GHashTable *coverage_hash = NULL;
510 MonoProfileCoverageInfo*
511 mono_profiler_coverage_alloc (MonoMethod *method, int entries)
513 MonoProfileCoverageInfo *res;
515 if (coverage_filter_cb)
516 if (! (*coverage_filter_cb) (current_profiler, method))
519 mono_profiler_coverage_lock ();
521 coverage_hash = g_hash_table_new (NULL, NULL);
523 res = g_malloc0 (sizeof (MonoProfileCoverageInfo) + sizeof (void*) * 2 * entries);
525 res->entries = entries;
527 g_hash_table_insert (coverage_hash, method, res);
528 mono_profiler_coverage_unlock ();
533 /* safe only when the method antive code has been unloaded */
535 mono_profiler_coverage_free (MonoMethod *method)
537 MonoProfileCoverageInfo* info;
539 mono_profiler_coverage_lock ();
540 if (!coverage_hash) {
541 mono_profiler_coverage_unlock ();
545 info = g_hash_table_lookup (coverage_hash, method);
548 g_hash_table_remove (coverage_hash, method);
550 mono_profiler_coverage_unlock ();
554 * mono_profiler_coverage_get:
555 * @prof: The profiler handle, installed with mono_profiler_install
556 * @method: the method to gather information from.
557 * @func: A routine that will be called back with the results
559 * If the MONO_PROFILER_INS_COVERAGE flag was active during JIT compilation
560 * it is posisble to obtain coverage information about a give method.
562 * The function @func will be invoked repeatedly with instances of the
563 * MonoProfileCoverageEntry structure.
566 mono_profiler_coverage_get (MonoProfiler *prof, MonoMethod *method, MonoProfileCoverageFunc func)
568 MonoProfileCoverageInfo* info;
571 const unsigned char *start, *end, *cil_code;
572 MonoMethodHeader *header;
573 MonoProfileCoverageEntry entry;
574 MonoDebugMethodInfo *debug_minfo;
576 mono_profiler_coverage_lock ();
577 info = g_hash_table_lookup (coverage_hash, method);
578 mono_profiler_coverage_unlock ();
583 header = mono_method_get_header (method);
584 start = mono_method_header_get_code (header, &code_size, NULL);
585 debug_minfo = mono_debug_lookup_method (method);
587 end = start + code_size;
588 for (i = 0; i < info->entries; ++i) {
589 cil_code = info->data [i].cil_code;
590 if (cil_code && cil_code >= start && cil_code < end) {
592 offset = cil_code - start;
593 entry.iloffset = offset;
594 entry.method = method;
595 entry.counter = info->data [i].count;
596 entry.line = entry.col = 1;
597 entry.filename = NULL;
599 MonoDebugSourceLocation *location;
601 location = mono_debug_symfile_lookup_location (debug_minfo, offset);
603 entry.line = location->row;
604 entry.col = location->column;
605 entry.filename = fname = g_strdup (location->source_file);
606 mono_debug_free_source_location (location);
616 #ifndef DISABLE_PROFILER
618 * Small profiler extracted from mint: we should move it in a loadable module
619 * and improve it to do graphs and more accurate timestamping with rdtsc.
622 static FILE* poutput = NULL;
625 #define USE_WIN32COUNTER 0
629 unsigned int lows, highs, lowe, highe;
632 #define rdtsc(low,high) \
633 __asm__ __volatile__("rdtsc" : "=a" (low), "=d" (high))
638 rdtsc_elapsed (MonoRdtscTimer *t)
640 unsigned long long diff;
641 unsigned int highe = t->highe;
642 if (t->lowe < t->lows)
644 diff = (((unsigned long long) highe - t->highs) << 32) + (t->lowe - t->lows);
645 return ((double)diff / freq) / 1000000; /* have to return the result in seconds */
656 if (!(cpuinfo = fopen ("/proc/cpuinfo", "r")))
658 while (fgets (buf, sizeof(buf), cpuinfo)) {
659 if (sscanf (buf, "cpu MHz : %f", &val) == 1) {
660 /*printf ("got mh: %f\n", val);*/
663 if (strncmp (buf, "flags", 5) == 0) {
664 if (strstr (buf, "tsc")) {
666 /*printf ("have tsc\n");*/
671 return have_flag? have_freq: 0;
674 #define MONO_TIMER_STARTUP \
675 if (!(freq = have_rdtsc ())) g_error ("Compiled with TSC support, but none found");
676 #define MONO_TIMER_TYPE MonoRdtscTimer
677 #define MONO_TIMER_INIT(t)
678 #define MONO_TIMER_DESTROY(t)
679 #define MONO_TIMER_START(t) rdtsc ((t).lows, (t).highs);
680 #define MONO_TIMER_STOP(t) rdtsc ((t).lowe, (t).highe);
681 #define MONO_TIMER_ELAPSED(t) rdtsc_elapsed (&(t))
683 #elif USE_WIN32COUNTER
687 LARGE_INTEGER start, stop;
693 win32_elapsed (MonoWin32Timer *t)
695 LONGLONG diff = t->stop.QuadPart - t->start.QuadPart;
696 return ((double)diff / freq) / 1000000; /* have to return the result in seconds */
700 have_win32counter (void) {
703 if (!QueryPerformanceFrequency (&f))
708 #define MONO_TIMER_STARTUP \
709 if (!(freq = have_win32counter ())) g_error ("Compiled with Win32 counter support, but none found");
710 #define MONO_TIMER_TYPE MonoWin32Timer
711 #define MONO_TIMER_INIT(t)
712 #define MONO_TIMER_DESTROY(t)
713 #define MONO_TIMER_START(t) QueryPerformanceCounter (&(t).start)
714 #define MONO_TIMER_STOP(t) QueryPerformanceCounter (&(t).stop)
715 #define MONO_TIMER_ELAPSED(t) win32_elapsed (&(t))
720 GTimeVal start, stop;
724 timeval_elapsed (MonoGLibTimer *t)
726 if (t->start.tv_usec > t->stop.tv_usec) {
727 t->stop.tv_usec += G_USEC_PER_SEC;
730 return (t->stop.tv_sec - t->start.tv_sec)
731 + ((double)(t->stop.tv_usec - t->start.tv_usec))/ G_USEC_PER_SEC;
734 #define MONO_TIMER_STARTUP
735 #define MONO_TIMER_TYPE MonoGLibTimer
736 #define MONO_TIMER_INIT(t)
737 #define MONO_TIMER_DESTROY(t)
738 #define MONO_TIMER_START(t) g_get_current_time (&(t).start)
739 #define MONO_TIMER_STOP(t) g_get_current_time (&(t).stop)
740 #define MONO_TIMER_ELAPSED(t) timeval_elapsed (&(t))
743 typedef struct _AllocInfo AllocInfo;
744 typedef struct _CallerInfo CallerInfo;
745 typedef struct _LastCallerInfo LastCallerInfo;
747 struct _MonoProfiler {
749 MonoMemPool *mempool;
750 /* info about JIT time */
751 MONO_TIMER_TYPE jit_timer;
754 MonoMethod *max_jit_method;
759 /* chain of callers for the current thread */
760 LastCallerInfo *callers;
761 /* LastCallerInfo nodes for faster allocation */
762 LastCallerInfo *cstorage;
769 AllocInfo *alloc_info;
770 CallerInfo *caller_info;
773 typedef struct _MethodCallProfile MethodCallProfile;
775 struct _MethodCallProfile {
776 MethodCallProfile *next;
777 MONO_TIMER_TYPE timer;
794 struct _LastCallerInfo {
795 LastCallerInfo *next;
797 MONO_TIMER_TYPE timer;
801 create_profiler (void)
803 MonoProfiler *prof = g_new0 (MonoProfiler, 1);
805 prof->methods = g_hash_table_new (mono_aligned_addr_hash, NULL);
806 MONO_TIMER_INIT (prof->jit_timer);
807 prof->mempool = mono_mempool_new ();
812 #ifdef HAVE_KW_THREAD
813 static __thread MonoProfiler * tls_profiler;
814 # define GET_PROFILER() tls_profiler
815 # define SET_PROFILER(x) tls_profiler = (x)
816 # define ALLOC_PROFILER() /* nop */
818 static guint32 profiler_thread_id = -1;
819 # define GET_PROFILER() ((MonoProfiler *)TlsGetValue (profiler_thread_id))
820 # define SET_PROFILER(x) TlsSetValue (profiler_thread_id, x);
821 # define ALLOC_PROFILER() profiler_thread_id = TlsAlloc ()
824 #define GET_THREAD_PROF(prof) do { \
825 MonoProfiler *_tprofiler = GET_PROFILER (); \
827 _tprofiler = create_profiler (); \
828 prof->per_thread = g_slist_prepend (prof->per_thread, _tprofiler); \
829 SET_PROFILER (_tprofiler); \
834 /* thread unsafe but faster variant */
835 #define GET_THREAD_PROF(prof)
839 compare_profile (MethodProfile *profa, MethodProfile *profb)
841 return (gint)((profb->total - profa->total)*1000);
845 build_profile (MonoMethod *m, MethodProfile *prof, GList **funcs)
848 *funcs = g_list_insert_sorted (*funcs, prof, (GCompareFunc)compare_profile);
852 method_get_name (MonoMethod* method)
856 sig = mono_signature_get_desc (mono_method_signature (method), FALSE);
857 res = g_strdup_printf ("%s%s%s::%s(%s)", method->klass->name_space,
858 method->klass->name_space ? "." : "", method->klass->name,
864 static void output_callers (MethodProfile *p);
866 /* This isn't defined on older glib versions and on some platforms */
867 #ifndef G_GUINT64_FORMAT
868 #define G_GUINT64_FORMAT "ul"
870 #ifndef G_GINT64_FORMAT
871 #define G_GINT64_FORMAT "lld"
875 output_profile (GList *funcs)
880 guint64 total_calls = 0;
883 fprintf (poutput, "Time(ms) Count P/call(ms) Method name\n");
884 for (tmp = funcs; tmp; tmp = tmp->next) {
886 total_calls += p->count;
887 if (!(gint)(p->total*1000))
889 m = method_get_name (p->method);
890 fprintf (poutput, "########################\n");
891 fprintf (poutput, "% 8.3f ", (double) (p->total * 1000));
892 fprintf (poutput, "%7" G_GUINT64_FORMAT " ", (unsigned long long)p->count);
893 fprintf (poutput, "% 8.3f ", (double) (p->total * 1000)/(double)p->count);
894 fprintf (poutput, " %s\n", m);
900 fprintf (poutput, "Total number of calls: %" G_GINT64_FORMAT "\n", (long long)total_calls);
909 compare_newobj_profile (NewobjProfile *profa, NewobjProfile *profb)
911 if (profb->count == profa->count)
914 return profb->count > profa->count ? 1 : -1;
918 build_newobj_profile (MonoClass *class, MethodProfile *mprof, GList **funcs)
920 NewobjProfile *prof = g_new (NewobjProfile, 1);
925 /* we use the total amount of memory to sort */
926 for (tmp = mprof->alloc_info; tmp; tmp = tmp->next)
929 *funcs = g_list_insert_sorted (*funcs, prof, (GCompareFunc)compare_newobj_profile);
933 compare_caller (CallerInfo *a, CallerInfo *b)
935 return b->count - a->count;
939 compare_alloc (AllocInfo *a, AllocInfo *b)
941 return b->mem - a->mem;
945 sort_alloc_list (AllocInfo *ai)
949 for (tmp = ai; tmp; tmp = tmp->next) {
950 l = g_slist_insert_sorted (l, tmp, (GCompareFunc)compare_alloc);
956 sort_caller_list (CallerInfo *ai)
960 for (tmp = ai; tmp; tmp = tmp->next) {
961 l = g_slist_insert_sorted (l, tmp, (GCompareFunc)compare_caller);
967 output_callers (MethodProfile *p) {
968 guint total_callers, percent;
969 GSList *sorted, *tmps;
973 fprintf (poutput, " Callers (with count) that contribute at least for 1%%:\n");
975 for (cinfo = p->caller_info; cinfo; cinfo = cinfo->next) {
976 total_callers += cinfo->count;
978 sorted = sort_caller_list (p->caller_info);
979 for (tmps = sorted; tmps; tmps = tmps->next) {
981 percent = (cinfo->count * 100)/total_callers;
984 m = method_get_name (cinfo->caller);
985 fprintf (poutput, " %8d % 3d %% %s\n", cinfo->count, percent, m);
991 output_newobj_profile (GList *proflist)
1002 GSList *sorted, *tmps;
1004 fprintf (poutput, "\nAllocation profiler\n");
1007 fprintf (poutput, "%-9s %s\n", "Total mem", "Method");
1008 for (tmp = proflist; tmp; tmp = tmp->next) {
1011 if (p->count < 50000)
1014 m = method_get_name (mp->method);
1015 fprintf (poutput, "########################\n%8" G_GUINT64_FORMAT " KB %s\n", (p->count / 1024), m);
1017 sorted = sort_alloc_list (mp->alloc_info);
1018 for (tmps = sorted; tmps; tmps = tmps->next) {
1020 if (ainfo->mem < 50000)
1022 klass = ainfo->klass;
1025 klass = klass->element_class;
1029 g_snprintf (buf, sizeof (buf), "%s%s%s%s",
1030 klass->name_space, klass->name_space ? "." : "", klass->name, isarray);
1031 fprintf (poutput, " %8" G_GUINT64_FORMAT " KB %8" G_GUINT64_FORMAT " %-48s\n", (ainfo->mem / 1024), ainfo->count, buf);
1034 output_callers (mp);
1036 fprintf (poutput, "Total memory allocated: %" G_GUINT64_FORMAT " KB\n", total / 1024);
1040 merge_methods (MonoMethod *method, MethodProfile *profile, MonoProfiler *prof)
1042 MethodProfile *mprof;
1043 AllocInfo *talloc_info, *alloc_info;
1044 CallerInfo *tcaller_info, *caller_info;
1046 mprof = g_hash_table_lookup (prof->methods, method);
1048 /* the master thread didn't see this method, just transfer the info as is */
1049 g_hash_table_insert (prof->methods, method, profile);
1052 /* merge the info from profile into mprof */
1053 mprof->count += profile->count;
1054 mprof->total += profile->total;
1055 /* merge alloc info */
1056 for (talloc_info = profile->alloc_info; talloc_info; talloc_info = talloc_info->next) {
1057 for (alloc_info = mprof->alloc_info; alloc_info; alloc_info = alloc_info->next) {
1058 if (alloc_info->klass == talloc_info->klass) {
1059 /* mprof already has a record for the klass, merge */
1060 alloc_info->count += talloc_info->count;
1061 alloc_info->mem += talloc_info->mem;
1066 /* mprof didn't have the info, just copy it over */
1067 alloc_info = mono_mempool_alloc0 (prof->mempool, sizeof (AllocInfo));
1068 *alloc_info = *talloc_info;
1069 alloc_info->next = mprof->alloc_info;
1070 mprof->alloc_info = alloc_info->next;
1073 /* merge callers info */
1074 for (tcaller_info = profile->caller_info; tcaller_info; tcaller_info = tcaller_info->next) {
1075 for (caller_info = mprof->caller_info; caller_info; caller_info = caller_info->next) {
1076 if (caller_info->caller == tcaller_info->caller) {
1077 /* mprof already has a record for the caller method, merge */
1078 caller_info->count += tcaller_info->count;
1083 /* mprof didn't have the info, just copy it over */
1084 caller_info = mono_mempool_alloc0 (prof->mempool, sizeof (CallerInfo));
1085 *caller_info = *tcaller_info;
1086 caller_info->next = mprof->caller_info;
1087 mprof->caller_info = caller_info;
1093 merge_thread_data (MonoProfiler *master, MonoProfiler *tprof)
1095 master->jit_time += tprof->jit_time;
1096 master->methods_jitted += tprof->methods_jitted;
1097 if (master->max_jit_time < tprof->max_jit_time) {
1098 master->max_jit_time = tprof->max_jit_time;
1099 master->max_jit_method = tprof->max_jit_method;
1102 g_hash_table_foreach (tprof->methods, (GHFunc)merge_methods, master);
1106 simple_method_enter (MonoProfiler *prof, MonoMethod *method)
1108 MethodProfile *profile_info;
1109 LastCallerInfo *callinfo;
1110 GET_THREAD_PROF (prof);
1111 /*g_print ("enter %p %s::%s in %d (%p)\n", method, method->klass->name, method->name, GetCurrentThreadId (), prof);*/
1112 if (!(profile_info = g_hash_table_lookup (prof->methods, method))) {
1113 profile_info = mono_mempool_alloc0 (prof->mempool, sizeof (MethodProfile));
1114 MONO_TIMER_INIT (profile_info->u.timer);
1115 g_hash_table_insert (prof->methods, method, profile_info);
1117 profile_info->count++;
1118 if (prof->callers) {
1120 MonoMethod *caller = prof->callers->method;
1121 for (cinfo = profile_info->caller_info; cinfo; cinfo = cinfo->next) {
1122 if (cinfo->caller == caller)
1126 cinfo = mono_mempool_alloc0 (prof->mempool, sizeof (CallerInfo));
1127 cinfo->caller = caller;
1128 cinfo->next = profile_info->caller_info;
1129 profile_info->caller_info = cinfo;
1133 if (!(callinfo = prof->cstorage)) {
1134 callinfo = mono_mempool_alloc (prof->mempool, sizeof (LastCallerInfo));
1135 MONO_TIMER_INIT (callinfo->timer);
1137 prof->cstorage = prof->cstorage->next;
1139 callinfo->method = method;
1140 callinfo->next = prof->callers;
1141 prof->callers = callinfo;
1142 MONO_TIMER_START (callinfo->timer);
1146 simple_method_leave (MonoProfiler *prof, MonoMethod *method)
1148 MethodProfile *profile_info;
1149 LastCallerInfo *callinfo, *newcallinfo = NULL;
1151 GET_THREAD_PROF (prof);
1152 /*g_print ("leave %p %s::%s in %d (%p)\n", method, method->klass->name, method->name, GetCurrentThreadId (), prof);*/
1153 callinfo = prof->callers;
1154 /* should really not happen, but we don't catch exceptions events, yet ... */
1156 MONO_TIMER_STOP (callinfo->timer);
1157 profile_info = g_hash_table_lookup (prof->methods, callinfo->method);
1159 profile_info->total += MONO_TIMER_ELAPSED (callinfo->timer);
1160 newcallinfo = callinfo->next;
1161 callinfo->next = prof->cstorage;
1162 prof->cstorage = callinfo;
1163 if (callinfo->method == method)
1165 callinfo = newcallinfo;
1167 prof->callers = newcallinfo;
1171 simple_allocation (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1173 MethodProfile *profile_info;
1176 GET_THREAD_PROF (prof);
1177 if (prof->callers) {
1178 MonoMethod *caller = prof->callers->method;
1180 /* Otherwise all allocations are attributed to icall_wrapper_mono_object_new */
1181 if (caller->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
1182 caller = prof->callers->next->method;
1184 if (!(profile_info = g_hash_table_lookup (prof->methods, caller)))
1185 g_assert_not_reached ();
1187 return; /* fine for now */
1190 for (tmp = profile_info->alloc_info; tmp; tmp = tmp->next) {
1191 if (tmp->klass == klass)
1195 tmp = mono_mempool_alloc0 (prof->mempool, sizeof (AllocInfo));
1197 tmp->next = profile_info->alloc_info;
1198 profile_info->alloc_info = tmp;
1201 tmp->mem += mono_object_get_size (obj);
1205 simple_method_jit (MonoProfiler *prof, MonoMethod *method)
1207 GET_THREAD_PROF (prof);
1208 prof->methods_jitted++;
1209 MONO_TIMER_START (prof->jit_timer);
1213 simple_method_end_jit (MonoProfiler *prof, MonoMethod *method, int result)
1216 GET_THREAD_PROF (prof);
1217 MONO_TIMER_STOP (prof->jit_timer);
1218 jtime = MONO_TIMER_ELAPSED (prof->jit_timer);
1219 prof->jit_time += jtime;
1220 if (jtime > prof->max_jit_time) {
1221 prof->max_jit_time = jtime;
1222 prof->max_jit_method = method;
1226 /* about 10 minutes of samples */
1227 #define MAX_PROF_SAMPLES (1000*60*10)
1228 static int prof_counts = 0;
1229 static int prof_ucounts = 0;
1230 static gpointer* prof_addresses = NULL;
1231 static GHashTable *prof_table = NULL;
1234 simple_stat_hit (MonoProfiler *prof, guchar *ip, void *context)
1238 if (prof_counts >= MAX_PROF_SAMPLES)
1240 pos = InterlockedIncrement (&prof_counts);
1241 prof_addresses [pos - 1] = ip;
1245 compare_methods_prof (gconstpointer a, gconstpointer b)
1247 int ca = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, a));
1248 int cb = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, b));
1253 prof_foreach (char *method, gpointer c, gpointer data)
1255 GList **list = data;
1256 *list = g_list_insert_sorted (*list, method, compare_methods_prof);
1259 typedef struct Addr2LineData Addr2LineData;
1261 struct Addr2LineData {
1262 Addr2LineData *next;
1269 static Addr2LineData *addr2line_pipes = NULL;
1272 try_addr2line (const char* binary, gpointer ip)
1276 Addr2LineData *addr2line;
1278 for (addr2line = addr2line_pipes; addr2line; addr2line = addr2line->next) {
1279 if (strcmp (binary, addr2line->binary) == 0)
1283 const char *addr_argv[] = {"addr2line", "-f", "-e", binary, NULL};
1287 char monobin [1024];
1288 /* non-linux platforms will need different code here */
1289 if (strcmp (binary, "mono") == 0) {
1290 int count = readlink ("/proc/self/exe", monobin, sizeof (monobin));
1291 if (count >= 0 && count < sizeof (monobin)) {
1292 monobin [count] = 0;
1293 addr_argv [3] = monobin;
1297 if (!g_spawn_async_with_pipes (NULL, (char**)addr_argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
1298 &child_pid, &ch_in, &ch_out, NULL, NULL)) {
1299 return g_strdup (binary);
1301 addr2line = g_new0 (Addr2LineData, 1);
1302 addr2line->child_pid = child_pid;
1303 addr2line->binary = g_strdup (binary);
1304 addr2line->pipein = fdopen (ch_in, "w");
1305 addr2line->pipeout = fdopen (ch_out, "r");
1306 addr2line->next = addr2line_pipes;
1307 addr2line_pipes = addr2line;
1309 fprintf (addr2line->pipein, "%p\n", ip);
1310 fflush (addr2line->pipein);
1311 /* we first get the func name and then file:lineno in a second line */
1312 if (fgets (buf, sizeof (buf), addr2line->pipeout) && buf [0] != '?') {
1313 char *end = strchr (buf, '\n');
1316 res = g_strdup_printf ("%s(%s", binary, buf);
1317 /* discard the filename/line info */
1318 fgets (buf, sizeof (buf), addr2line->pipeout);
1320 res = g_strdup (binary);
1326 stat_prof_report (void)
1329 int count = prof_counts;
1333 GList *tmp, *sorted = NULL;
1334 int pcount = ++ prof_counts;
1336 prof_counts = MAX_PROF_SAMPLES;
1337 for (i = 0; i < count; ++i) {
1338 ip = prof_addresses [i];
1339 ji = mono_jit_info_table_find (mono_domain_get (), ip);
1341 mn = mono_method_full_name (ji->method, TRUE);
1343 #ifdef HAVE_BACKTRACE_SYMBOLS
1348 names = backtrace_symbols (&ip, 1);
1349 send = strchr (names [0], '+');
1356 send = strchr (names [0], '[');
1359 if (no_func && names [0][0]) {
1360 char *endp = strchr (names [0], 0);
1361 while (--endp >= names [0] && g_ascii_isspace (*endp))
1363 mn = try_addr2line (names [0], ip);
1365 mn = g_strdup (names [0]);
1370 mn = g_strdup_printf ("unmanaged [%p]", ip);
1373 c = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, mn));
1375 g_hash_table_insert (prof_table, mn, GUINT_TO_POINTER (c));
1379 fprintf (poutput, "prof counts: total/unmanaged: %d/%d\n", pcount, prof_ucounts);
1380 g_hash_table_foreach (prof_table, (GHFunc)prof_foreach, &sorted);
1381 for (tmp = sorted; tmp; tmp = tmp->next) {
1383 c = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, tmp->data));
1384 perc = c*100.0/count;
1385 fprintf (poutput, "%7d\t%5.2f %% %s\n", c, perc, (char*)tmp->data);
1387 g_list_free (sorted);
1391 simple_appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
1393 /* FIXME: we should actually record partial data for each domain,
1394 * but at this point it's must easier using the new logging profiler.
1396 mono_profiler_shutdown ();
1399 static gint32 simple_shutdown_done = FALSE;
1402 simple_shutdown (MonoProfiler *prof)
1404 GList *profile = NULL;
1405 MonoProfiler *tprof;
1408 gint32 see_shutdown_done;
1410 // Make sure we execute simple_shutdown only once
1411 see_shutdown_done = InterlockedExchange(& simple_shutdown_done, TRUE);
1412 if (see_shutdown_done)
1415 if (mono_profiler_events & MONO_PROFILE_STATISTICAL) {
1416 stat_prof_report ();
1419 // Stop all incoming events
1420 mono_profiler_set_events (0);
1422 for (tmp = prof->per_thread; tmp; tmp = tmp->next) {
1424 merge_thread_data (prof, tprof);
1427 fprintf (poutput, "Total time spent compiling %d methods (sec): %.4g\n", prof->methods_jitted, prof->jit_time);
1428 if (prof->max_jit_method) {
1429 str = method_get_name (prof->max_jit_method);
1430 fprintf (poutput, "Slowest method to compile (sec): %.4g: %s\n", prof->max_jit_time, str);
1433 g_hash_table_foreach (prof->methods, (GHFunc)build_profile, &profile);
1434 output_profile (profile);
1435 g_list_free (profile);
1438 g_hash_table_foreach (prof->methods, (GHFunc)build_newobj_profile, &profile);
1439 output_newobj_profile (profile);
1440 g_list_free (profile);
1442 g_free (prof_addresses);
1443 prof_addresses = NULL;
1444 g_hash_table_destroy (prof_table);
1448 mono_profiler_install_simple (const char *desc)
1451 gchar **args, **ptr;
1452 MonoProfileFlags flags = 0;
1458 desc = "alloc,time,jit";
1462 if (strstr (desc, ":"))
1463 desc = strstr (desc, ":") + 1;
1465 desc = "alloc,time,jit";
1466 args = g_strsplit (desc, ",", -1);
1468 for (ptr = args; ptr && *ptr; ptr++) {
1469 const char *arg = *ptr;
1471 // Alwais listen to appdomaon events to shutdown at the first unload
1472 flags |= MONO_PROFILE_APPDOMAIN_EVENTS;
1473 if (!strcmp (arg, "time"))
1474 flags |= MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_EXCEPTIONS;
1475 else if (!strcmp (arg, "alloc"))
1476 flags |= MONO_PROFILE_ALLOCATIONS;
1477 else if (!strcmp (arg, "stat"))
1478 flags |= MONO_PROFILE_STATISTICAL;
1479 else if (!strcmp (arg, "jit"))
1480 flags |= MONO_PROFILE_JIT_COMPILATION;
1481 else if (strncmp (arg, "file=", 5) == 0) {
1482 poutput = fopen (arg + 5, "wb");
1485 fprintf (stderr, "profiler : cannot open profile output file '%s'.\n", arg + 5);
1488 fprintf (stderr, "profiler : Unknown argument '%s'.\n", arg);
1493 if (flags & MONO_PROFILE_ALLOCATIONS)
1494 flags |= MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_EXCEPTIONS;
1496 flags = MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_ALLOCATIONS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_EXCEPTIONS;
1498 prof = create_profiler ();
1500 SET_PROFILER (prof);
1502 /* statistical profiler data */
1503 prof_addresses = g_new0 (gpointer, MAX_PROF_SAMPLES);
1504 prof_table = g_hash_table_new (g_str_hash, g_str_equal);
1506 mono_profiler_install (prof, simple_shutdown);
1507 mono_profiler_install_enter_leave (simple_method_enter, simple_method_leave);
1508 mono_profiler_install_exception (NULL, simple_method_leave, NULL);
1509 mono_profiler_install_jit_compile (simple_method_jit, simple_method_end_jit);
1510 mono_profiler_install_allocation (simple_allocation);
1511 mono_profiler_install_appdomain (NULL, NULL, simple_appdomain_unload, NULL);
1512 mono_profiler_install_statistical (simple_stat_hit);
1513 mono_profiler_set_events (flags);
1516 #endif /* DISABLE_PROFILER */
1518 typedef void (*ProfilerInitializer) (const char*);
1519 #define INITIALIZER_NAME "mono_profiler_startup"
1522 * mono_profiler_load:
1523 * @desc: arguments to configure the profiler
1525 * Invoke this method to initialize the profiler. This will drive the
1526 * loading of the internal ("default") or any external profilers.
1528 * This routine is invoked by Mono's driver, but must be called manually
1529 * if you embed Mono into your application.
1532 mono_profiler_load (const char *desc)
1534 #ifndef DISABLE_PROFILER
1535 if (!desc || (strcmp ("default", desc) == 0) || (strncmp (desc, "default:", 8) == 0)) {
1536 mono_profiler_install_simple (desc);
1546 const char* col = strchr (desc, ':');
1553 mname = g_memdup (desc, col - desc + 1);
1554 mname [col - desc] = 0;
1556 mname = g_strdup (desc);
1558 libname = g_strdup_printf ("mono-profiler-%s", mname);
1561 while ((path = mono_dl_build_path (NULL, libname, &iter))) {
1563 pmodule = mono_dl_open (path, MONO_DL_LAZY, &err);
1565 ProfilerInitializer func;
1566 if ((err = mono_dl_symbol (pmodule, INITIALIZER_NAME, (gpointer *)&func))) {
1567 g_warning ("Cannot find initializer function %s in profiler module: %s (%s)", INITIALIZER_NAME, libname, err);
1578 g_warning ("Error loading profiler module '%s': %s", libname, err);