3 #include "mono/metadata/profiler-private.h"
4 #include "mono/metadata/debug-helpers.h"
5 #include "mono/metadata/mono-debug.h"
6 #include "mono/metadata/class-internals.h"
7 #include "mono/metadata/domain-internals.h"
8 #include "mono/metadata/gc-internal.h"
9 #include "mono/io-layer/io-layer.h"
13 #ifdef HAVE_BACKTRACE_SYMBOLS
17 static MonoProfiler * current_profiler = NULL;
19 static MonoProfileAppDomainFunc domain_start_load;
20 static MonoProfileAppDomainResult domain_end_load;
21 static MonoProfileAppDomainFunc domain_start_unload;
22 static MonoProfileAppDomainFunc domain_end_unload;
24 static MonoProfileAssemblyFunc assembly_start_load;
25 static MonoProfileAssemblyResult assembly_end_load;
26 static MonoProfileAssemblyFunc assembly_start_unload;
27 static MonoProfileAssemblyFunc assembly_end_unload;
29 static MonoProfileModuleFunc module_start_load;
30 static MonoProfileModuleResult module_end_load;
31 static MonoProfileModuleFunc module_start_unload;
32 static MonoProfileModuleFunc module_end_unload;
34 static MonoProfileClassFunc class_start_load;
35 static MonoProfileClassResult class_end_load;
36 static MonoProfileClassFunc class_start_unload;
37 static MonoProfileClassFunc class_end_unload;
39 static MonoProfileMethodFunc jit_start;
40 static MonoProfileMethodResult jit_end;
41 static MonoProfileMethodResult man_unman_transition;
42 static MonoProfileAllocFunc allocation_cb;
43 static MonoProfileStatFunc statistical_cb;
44 static MonoProfileMethodFunc method_enter;
45 static MonoProfileMethodFunc method_leave;
47 static MonoProfileThreadFunc thread_start;
48 static MonoProfileThreadFunc thread_end;
50 static MonoProfileCoverageFilterFunc coverage_filter_cb;
52 static MonoProfileFunc shutdown_callback;
54 static MonoProfileGCFunc gc_event;
55 static MonoProfileGCResizeFunc gc_heap_resize;
57 #define mono_profiler_coverage_lock() EnterCriticalSection (&profiler_coverage_mutex)
58 #define mono_profiler_coverage_unlock() LeaveCriticalSection (&profiler_coverage_mutex)
59 static CRITICAL_SECTION profiler_coverage_mutex;
61 /* this is directly accessible to other mono libs. */
62 MonoProfileFlags mono_profiler_events;
65 mono_profiler_install (MonoProfiler *prof, MonoProfileFunc callback)
68 g_error ("profiler already setup");
69 current_profiler = prof;
70 shutdown_callback = callback;
71 InitializeCriticalSection (&profiler_coverage_mutex);
75 mono_profiler_set_events (MonoProfileFlags events)
77 mono_profiler_events = events;
81 mono_profiler_get_events (void)
83 return mono_profiler_events;
87 mono_profiler_install_enter_leave (MonoProfileMethodFunc enter, MonoProfileMethodFunc fleave)
90 method_leave = fleave;
94 mono_profiler_install_jit_compile (MonoProfileMethodFunc start, MonoProfileMethodResult end)
101 mono_profiler_install_thread (MonoProfileThreadFunc start, MonoProfileThreadFunc end)
103 thread_start = start;
108 mono_profiler_install_transition (MonoProfileMethodResult callback)
110 man_unman_transition = callback;
114 mono_profiler_install_allocation (MonoProfileAllocFunc callback)
116 allocation_cb = callback;
120 mono_profiler_install_statistical (MonoProfileStatFunc callback)
122 statistical_cb = callback;
126 mono_profiler_install_coverage_filter (MonoProfileCoverageFilterFunc callback)
128 coverage_filter_cb = callback;
132 mono_profiler_install_appdomain (MonoProfileAppDomainFunc start_load, MonoProfileAppDomainResult end_load,
133 MonoProfileAppDomainFunc start_unload, MonoProfileAppDomainFunc end_unload)
136 domain_start_load = start_load;
137 domain_end_load = end_load;
138 domain_start_unload = start_unload;
139 domain_end_unload = end_unload;
143 mono_profiler_install_assembly (MonoProfileAssemblyFunc start_load, MonoProfileAssemblyResult end_load,
144 MonoProfileAssemblyFunc start_unload, MonoProfileAssemblyFunc end_unload)
146 assembly_start_load = start_load;
147 assembly_end_load = end_load;
148 assembly_start_unload = start_unload;
149 assembly_end_unload = end_unload;
153 mono_profiler_install_module (MonoProfileModuleFunc start_load, MonoProfileModuleResult end_load,
154 MonoProfileModuleFunc start_unload, MonoProfileModuleFunc end_unload)
156 module_start_load = start_load;
157 module_end_load = end_load;
158 module_start_unload = start_unload;
159 module_end_unload = end_unload;
163 mono_profiler_install_class (MonoProfileClassFunc start_load, MonoProfileClassResult end_load,
164 MonoProfileClassFunc start_unload, MonoProfileClassFunc end_unload)
166 class_start_load = start_load;
167 class_end_load = end_load;
168 class_start_unload = start_unload;
169 class_end_unload = end_unload;
173 mono_profiler_method_enter (MonoMethod *method)
175 if ((mono_profiler_events & MONO_PROFILE_ENTER_LEAVE) && method_enter)
176 method_enter (current_profiler, method);
180 mono_profiler_method_leave (MonoMethod *method)
182 if ((mono_profiler_events & MONO_PROFILE_ENTER_LEAVE) && method_leave)
183 method_leave (current_profiler, method);
187 mono_profiler_method_jit (MonoMethod *method)
189 if ((mono_profiler_events & MONO_PROFILE_JIT_COMPILATION) && jit_start)
190 jit_start (current_profiler, method);
194 mono_profiler_method_end_jit (MonoMethod *method, int result)
196 if ((mono_profiler_events & MONO_PROFILE_JIT_COMPILATION) && jit_end)
197 jit_end (current_profiler, method, result);
201 mono_profiler_code_transition (MonoMethod *method, int result)
203 if ((mono_profiler_events & MONO_PROFILE_TRANSITIONS) && man_unman_transition)
204 man_unman_transition (current_profiler, method, result);
208 mono_profiler_allocation (MonoObject *obj, MonoClass *klass)
210 if ((mono_profiler_events & MONO_PROFILE_ALLOCATIONS) && allocation_cb)
211 allocation_cb (current_profiler, obj, klass);
215 mono_profiler_stat_hit (guchar *ip, void *context)
217 if ((mono_profiler_events & MONO_PROFILE_STATISTICAL) && statistical_cb)
218 statistical_cb (current_profiler, ip, context);
222 mono_profiler_thread_start (gsize tid)
224 if ((mono_profiler_events & MONO_PROFILE_THREADS) && thread_start)
225 thread_start (current_profiler, tid);
229 mono_profiler_thread_end (gsize tid)
231 if ((mono_profiler_events & MONO_PROFILE_THREADS) && thread_end)
232 thread_end (current_profiler, tid);
236 mono_profiler_assembly_event (MonoAssembly *assembly, int code)
238 if (!(mono_profiler_events & MONO_PROFILE_ASSEMBLY_EVENTS))
242 case MONO_PROFILE_START_LOAD:
243 if (assembly_start_load)
244 assembly_start_load (current_profiler, assembly);
246 case MONO_PROFILE_START_UNLOAD:
247 if (assembly_start_unload)
248 assembly_start_unload (current_profiler, assembly);
250 case MONO_PROFILE_END_UNLOAD:
251 if (assembly_end_unload)
252 assembly_end_unload (current_profiler, assembly);
255 g_assert_not_reached ();
260 mono_profiler_assembly_loaded (MonoAssembly *assembly, int result)
262 if ((mono_profiler_events & MONO_PROFILE_ASSEMBLY_EVENTS) && assembly_end_load)
263 assembly_end_load (current_profiler, assembly, result);
267 mono_profiler_module_event (MonoImage *module, int code)
269 if (!(mono_profiler_events & MONO_PROFILE_MODULE_EVENTS))
273 case MONO_PROFILE_START_LOAD:
274 if (module_start_load)
275 module_start_load (current_profiler, module);
277 case MONO_PROFILE_START_UNLOAD:
278 if (module_start_unload)
279 module_start_unload (current_profiler, module);
281 case MONO_PROFILE_END_UNLOAD:
282 if (module_end_unload)
283 module_end_unload (current_profiler, module);
286 g_assert_not_reached ();
291 mono_profiler_module_loaded (MonoImage *module, int result)
293 if ((mono_profiler_events & MONO_PROFILE_MODULE_EVENTS) && module_end_load)
294 module_end_load (current_profiler, module, result);
298 mono_profiler_class_event (MonoClass *klass, int code)
300 if (!(mono_profiler_events & MONO_PROFILE_CLASS_EVENTS))
304 case MONO_PROFILE_START_LOAD:
305 if (class_start_load)
306 class_start_load (current_profiler, klass);
308 case MONO_PROFILE_START_UNLOAD:
309 if (class_start_unload)
310 class_start_unload (current_profiler, klass);
312 case MONO_PROFILE_END_UNLOAD:
313 if (class_end_unload)
314 class_end_unload (current_profiler, klass);
317 g_assert_not_reached ();
322 mono_profiler_class_loaded (MonoClass *klass, int result)
324 if ((mono_profiler_events & MONO_PROFILE_CLASS_EVENTS) && class_end_load)
325 class_end_load (current_profiler, klass, result);
329 mono_profiler_appdomain_event (MonoDomain *domain, int code)
331 if (!(mono_profiler_events & MONO_PROFILE_APPDOMAIN_EVENTS))
335 case MONO_PROFILE_START_LOAD:
336 if (domain_start_load)
337 domain_start_load (current_profiler, domain);
339 case MONO_PROFILE_START_UNLOAD:
340 if (domain_start_unload)
341 domain_start_unload (current_profiler, domain);
343 case MONO_PROFILE_END_UNLOAD:
344 if (domain_end_unload)
345 domain_end_unload (current_profiler, domain);
348 g_assert_not_reached ();
353 mono_profiler_appdomain_loaded (MonoDomain *domain, int result)
355 if ((mono_profiler_events & MONO_PROFILE_APPDOMAIN_EVENTS) && domain_end_load)
356 domain_end_load (current_profiler, domain, result);
360 mono_profiler_shutdown (void)
362 if (current_profiler && shutdown_callback)
363 shutdown_callback (current_profiler);
367 mono_profiler_gc_heap_resize (gint64 new_size)
369 if ((mono_profiler_events & MONO_PROFILE_GC) && gc_heap_resize)
370 gc_heap_resize (current_profiler, new_size);
374 mono_profiler_gc_event (MonoGCEvent event, int generation)
376 if ((mono_profiler_events & MONO_PROFILE_GC) && gc_event)
377 gc_event (current_profiler, event, generation);
381 mono_profiler_install_gc (MonoProfileGCFunc callback, MonoProfileGCResizeFunc heap_resize_callback)
383 mono_gc_enable_events ();
385 gc_heap_resize = heap_resize_callback;
388 static GHashTable *coverage_hash = NULL;
390 MonoProfileCoverageInfo*
391 mono_profiler_coverage_alloc (MonoMethod *method, int entries)
393 MonoProfileCoverageInfo *res;
395 if (coverage_filter_cb)
396 if (! (*coverage_filter_cb) (current_profiler, method))
399 mono_profiler_coverage_lock ();
401 coverage_hash = g_hash_table_new (NULL, NULL);
403 res = g_malloc0 (sizeof (MonoProfileCoverageInfo) + sizeof (void*) * 2 * entries);
405 res->entries = entries;
407 g_hash_table_insert (coverage_hash, method, res);
408 mono_profiler_coverage_unlock ();
413 /* safe only when the method antive code has been unloaded */
415 mono_profiler_coverage_free (MonoMethod *method)
417 MonoProfileCoverageInfo* info;
419 mono_profiler_coverage_lock ();
420 if (!coverage_hash) {
421 mono_profiler_coverage_unlock ();
425 info = g_hash_table_lookup (coverage_hash, method);
428 g_hash_table_remove (coverage_hash, method);
430 mono_profiler_coverage_unlock ();
434 mono_profiler_coverage_get (MonoProfiler *prof, MonoMethod *method, MonoProfileCoverageFunc func)
436 MonoProfileCoverageInfo* info;
439 unsigned char *start, *end, *cil_code;
440 MonoMethodHeader *header;
441 MonoProfileCoverageEntry entry;
443 mono_profiler_coverage_lock ();
444 info = g_hash_table_lookup (coverage_hash, method);
445 mono_profiler_coverage_unlock ();
450 header = mono_method_get_header (method);
451 start = (unsigned char*)header->code;
452 end = start + header->code_size;
453 for (i = 0; i < info->entries; ++i) {
454 cil_code = info->data [i].cil_code;
455 if (cil_code && cil_code >= start && cil_code < end) {
456 offset = cil_code - start;
457 entry.iloffset = offset;
458 entry.method = method;
459 entry.counter = info->data [i].count;
460 /* the debug interface doesn't support column info, sigh */
462 entry.filename = mono_debug_source_location_from_il_offset (method, offset, &line);
470 #ifndef DISABLE_PROFILER
472 * Small profiler extracted from mint: we should move it in a loadable module
473 * and improve it to do graphs and more accurate timestamping with rdtsc.
477 #define USE_WIN32COUNTER 0
481 unsigned int lows, highs, lowe, highe;
484 #define rdtsc(low,high) \
485 __asm__ __volatile__("rdtsc" : "=a" (low), "=d" (high))
490 rdtsc_elapsed (MonoRdtscTimer *t)
492 unsigned long long diff;
493 unsigned int highe = t->highe;
494 if (t->lowe < t->lows)
496 diff = (((unsigned long long) highe - t->highs) << 32) + (t->lowe - t->lows);
497 return ((double)diff / freq) / 1000000; /* have to return the result in seconds */
508 if (!(cpuinfo = fopen ("/proc/cpuinfo", "r")))
510 while (fgets (buf, sizeof(buf), cpuinfo)) {
511 if (sscanf (buf, "cpu MHz : %f", &val) == 1) {
512 /*printf ("got mh: %f\n", val);*/
515 if (strncmp (buf, "flags", 5) == 0) {
516 if (strstr (buf, "tsc")) {
518 /*printf ("have tsc\n");*/
523 return have_flag? have_freq: 0;
526 #define MONO_TIMER_STARTUP \
527 if (!(freq = have_rdtsc ())) g_error ("Compiled with TSC support, but none found");
528 #define MONO_TIMER_TYPE MonoRdtscTimer
529 #define MONO_TIMER_INIT(t)
530 #define MONO_TIMER_DESTROY(t)
531 #define MONO_TIMER_START(t) rdtsc ((t).lows, (t).highs);
532 #define MONO_TIMER_STOP(t) rdtsc ((t).lowe, (t).highe);
533 #define MONO_TIMER_ELAPSED(t) rdtsc_elapsed (&(t))
535 #elif USE_WIN32COUNTER
539 LARGE_INTEGER start, stop;
545 win32_elapsed (MonoWin32Timer *t)
547 LONGLONG diff = t->stop.QuadPart - t->start.QuadPart;
548 return ((double)diff / freq) / 1000000; /* have to return the result in seconds */
552 have_win32counter (void) {
555 if (!QueryPerformanceFrequency (&f))
560 #define MONO_TIMER_STARTUP \
561 if (!(freq = have_win32counter ())) g_error ("Compiled with Win32 counter support, but none found");
562 #define MONO_TIMER_TYPE MonoWin32Timer
563 #define MONO_TIMER_INIT(t)
564 #define MONO_TIMER_DESTROY(t)
565 #define MONO_TIMER_START(t) QueryPerformanceCounter (&(t).start)
566 #define MONO_TIMER_STOP(t) QueryPerformanceCounter (&(t).stop)
567 #define MONO_TIMER_ELAPSED(t) win32_elapsed (&(t))
572 GTimeVal start, stop;
576 timeval_elapsed (MonoGLibTimer *t)
578 if (t->start.tv_usec > t->stop.tv_usec) {
579 t->stop.tv_usec += G_USEC_PER_SEC;
582 return (t->stop.tv_sec - t->start.tv_sec)
583 + ((double)(t->stop.tv_usec - t->start.tv_usec))/ G_USEC_PER_SEC;
586 #define MONO_TIMER_STARTUP
587 #define MONO_TIMER_TYPE MonoGLibTimer
588 #define MONO_TIMER_INIT(t)
589 #define MONO_TIMER_DESTROY(t)
590 #define MONO_TIMER_START(t) g_get_current_time (&(t).start)
591 #define MONO_TIMER_STOP(t) g_get_current_time (&(t).stop)
592 #define MONO_TIMER_ELAPSED(t) timeval_elapsed (&(t))
595 typedef struct _AllocInfo AllocInfo;
596 typedef struct _CallerInfo CallerInfo;
597 typedef struct _LastCallerInfo LastCallerInfo;
599 struct _MonoProfiler {
601 MonoMemPool *mempool;
602 /* info about JIT time */
603 MONO_TIMER_TYPE jit_timer;
606 MonoMethod *max_jit_method;
611 /* chain of callers for the current thread */
612 LastCallerInfo *callers;
613 /* LastCallerInfo nodes for faster allocation */
614 LastCallerInfo *cstorage;
621 AllocInfo *alloc_info;
622 CallerInfo *caller_info;
625 typedef struct _MethodCallProfile MethodCallProfile;
627 struct _MethodCallProfile {
628 MethodCallProfile *next;
629 MONO_TIMER_TYPE timer;
646 struct _LastCallerInfo {
647 LastCallerInfo *next;
649 MONO_TIMER_TYPE timer;
653 create_profiler (void)
655 MonoProfiler *prof = g_new0 (MonoProfiler, 1);
657 prof->methods = g_hash_table_new (NULL, NULL);
658 MONO_TIMER_INIT (prof->jit_timer);
659 prof->mempool = mono_mempool_new ();
664 #ifdef HAVE_KW_THREAD
665 static __thread MonoProfiler * tls_profiler;
666 # define GET_PROFILER() tls_profiler
667 # define SET_PROFILER(x) tls_profiler = (x)
668 # define ALLOC_PROFILER() /* nop */
670 static guint32 profiler_thread_id = -1;
671 # define GET_PROFILER() ((MonoProfiler *)TlsGetValue (profiler_thread_id))
672 # define SET_PROFILER(x) TlsSetValue (profiler_thread_id, x);
673 # define ALLOC_PROFILER() profiler_thread_id = TlsAlloc ()
676 #define GET_THREAD_PROF(prof) do { \
677 MonoProfiler *_tprofiler = GET_PROFILER (); \
679 _tprofiler = create_profiler (); \
680 prof->per_thread = g_slist_prepend (prof->per_thread, _tprofiler); \
681 SET_PROFILER (_tprofiler); \
686 /* thread unsafe but faster variant */
687 #define GET_THREAD_PROF(prof)
691 compare_profile (MethodProfile *profa, MethodProfile *profb)
693 return (gint)((profb->total - profa->total)*1000);
697 build_profile (MonoMethod *m, MethodProfile *prof, GList **funcs)
700 *funcs = g_list_insert_sorted (*funcs, prof, (GCompareFunc)compare_profile);
704 method_get_name (MonoMethod* method)
708 sig = mono_signature_get_desc (mono_method_signature (method), FALSE);
709 res = g_strdup_printf ("%s%s%s::%s(%s)", method->klass->name_space,
710 method->klass->name_space ? "." : "", method->klass->name,
716 static void output_callers (MethodProfile *p);
719 output_profile (GList *funcs)
724 guint64 total_calls = 0;
727 g_print ("Time(ms) Count P/call(ms) Method name\n");
728 for (tmp = funcs; tmp; tmp = tmp->next) {
730 total_calls += p->count;
731 if (!(gint)(p->total*1000))
733 m = method_get_name (p->method);
734 printf ("########################\n");
735 printf ("% 8.3f ", (double) (p->total * 1000));
736 printf ("%7llu ", (unsigned long long)p->count);
737 printf ("% 8.3f ", (double) (p->total * 1000)/(double)p->count);
744 printf ("Total number of calls: %lld\n", (long long)total_calls);
753 compare_newobj_profile (NewobjProfile *profa, NewobjProfile *profb)
755 if (profb->count == profa->count)
758 return profb->count > profa->count ? 1 : -1;
762 build_newobj_profile (MonoClass *class, MethodProfile *mprof, GList **funcs)
764 NewobjProfile *prof = g_new (NewobjProfile, 1);
769 /* we use the total amount of memory to sort */
770 for (tmp = mprof->alloc_info; tmp; tmp = tmp->next)
773 *funcs = g_list_insert_sorted (*funcs, prof, (GCompareFunc)compare_newobj_profile);
777 compare_caller (CallerInfo *a, CallerInfo *b)
779 return b->count - a->count;
783 compare_alloc (AllocInfo *a, AllocInfo *b)
785 return b->mem - a->mem;
789 sort_alloc_list (AllocInfo *ai)
793 for (tmp = ai; tmp; tmp = tmp->next) {
794 l = g_slist_insert_sorted (l, tmp, (GCompareFunc)compare_alloc);
800 sort_caller_list (CallerInfo *ai)
804 for (tmp = ai; tmp; tmp = tmp->next) {
805 l = g_slist_insert_sorted (l, tmp, (GCompareFunc)compare_caller);
811 output_callers (MethodProfile *p) {
812 guint total_callers, percent;
813 GSList *sorted, *tmps;
817 g_print (" Callers (with count) that contribute at least for 1%%:\n");
819 for (cinfo = p->caller_info; cinfo; cinfo = cinfo->next) {
820 total_callers += cinfo->count;
822 sorted = sort_caller_list (p->caller_info);
823 for (tmps = sorted; tmps; tmps = tmps->next) {
825 percent = (cinfo->count * 100)/total_callers;
828 m = method_get_name (cinfo->caller);
829 g_print (" %8d % 3d %% %s\n", cinfo->count, percent, m);
834 /* This isn't defined on older glib versions and on some platforms */
835 #ifndef G_GUINT64_FORMAT
836 #define G_GUINT64_FORMAT "ul"
840 output_newobj_profile (GList *proflist)
851 GSList *sorted, *tmps;
853 g_print ("\nAllocation profiler\n");
856 g_print ("%-9s %s\n", "Total mem", "Method");
857 for (tmp = proflist; tmp; tmp = tmp->next) {
860 if (p->count < 50000)
863 m = method_get_name (mp->method);
864 g_print ("########################\n%8" G_GUINT64_FORMAT " KB %s\n", (p->count / 1024), m);
866 sorted = sort_alloc_list (mp->alloc_info);
867 for (tmps = sorted; tmps; tmps = tmps->next) {
869 if (ainfo->mem < 50000)
871 klass = ainfo->klass;
874 klass = klass->element_class;
878 g_snprintf (buf, sizeof (buf), "%s%%s%s",
879 klass->name_space, klass->name_space ? "." : "", klass->name, isarray);
880 g_print (" %8" G_GUINT64_FORMAT " KB %8" G_GUINT64_FORMAT " %-48s\n", (ainfo->mem / 1024), ainfo->count, buf);
885 g_print ("Total memory allocated: %" G_GUINT64_FORMAT " KB\n", total / 1024);
889 merge_methods (MonoMethod *method, MethodProfile *profile, MonoProfiler *prof)
891 MethodProfile *mprof;
892 AllocInfo *talloc_info, *alloc_info;
893 CallerInfo *tcaller_info, *caller_info;
895 mprof = g_hash_table_lookup (prof->methods, method);
897 /* the master thread didn't see this method, just transfer the info as is */
898 g_hash_table_insert (prof->methods, method, profile);
901 /* merge the info from profile into mprof */
902 mprof->count += profile->count;
903 mprof->total += profile->total;
904 /* merge alloc info */
905 for (talloc_info = profile->alloc_info; talloc_info; talloc_info = talloc_info->next) {
906 for (alloc_info = mprof->alloc_info; alloc_info; alloc_info = alloc_info->next) {
907 if (alloc_info->klass == talloc_info->klass) {
908 /* mprof already has a record for the klass, merge */
909 alloc_info->count += talloc_info->count;
910 alloc_info->mem += talloc_info->mem;
915 /* mprof didn't have the info, just copy it over */
916 alloc_info = mono_mempool_alloc0 (prof->mempool, sizeof (AllocInfo));
917 *alloc_info = *talloc_info;
918 alloc_info->next = mprof->alloc_info;
919 mprof->alloc_info = alloc_info->next;
922 /* merge callers info */
923 for (tcaller_info = profile->caller_info; tcaller_info; tcaller_info = tcaller_info->next) {
924 for (caller_info = mprof->caller_info; caller_info; caller_info = caller_info->next) {
925 if (caller_info->caller == tcaller_info->caller) {
926 /* mprof already has a record for the caller method, merge */
927 caller_info->count += tcaller_info->count;
932 /* mprof didn't have the info, just copy it over */
933 caller_info = mono_mempool_alloc0 (prof->mempool, sizeof (CallerInfo));
934 *caller_info = *tcaller_info;
935 caller_info->next = mprof->caller_info;
936 mprof->caller_info = caller_info;
942 merge_thread_data (MonoProfiler *master, MonoProfiler *tprof)
944 master->jit_time += tprof->jit_time;
945 master->methods_jitted += tprof->methods_jitted;
946 if (master->max_jit_time < tprof->max_jit_time) {
947 master->max_jit_time = tprof->max_jit_time;
948 master->max_jit_method = tprof->max_jit_method;
951 g_hash_table_foreach (tprof->methods, (GHFunc)merge_methods, master);
955 simple_method_enter (MonoProfiler *prof, MonoMethod *method)
957 MethodProfile *profile_info;
958 LastCallerInfo *callinfo;
959 GET_THREAD_PROF (prof);
960 /*g_print ("enter %p %s::%s in %d (%p)\n", method, method->klass->name, method->name, GetCurrentThreadId (), prof);*/
961 if (!(profile_info = g_hash_table_lookup (prof->methods, method))) {
962 profile_info = mono_mempool_alloc0 (prof->mempool, sizeof (MethodProfile));
963 MONO_TIMER_INIT (profile_info->u.timer);
964 g_hash_table_insert (prof->methods, method, profile_info);
966 profile_info->count++;
969 MonoMethod *caller = prof->callers->method;
970 for (cinfo = profile_info->caller_info; cinfo; cinfo = cinfo->next) {
971 if (cinfo->caller == caller)
975 cinfo = mono_mempool_alloc0 (prof->mempool, sizeof (CallerInfo));
976 cinfo->caller = caller;
977 cinfo->next = profile_info->caller_info;
978 profile_info->caller_info = cinfo;
982 if (!(callinfo = prof->cstorage)) {
983 callinfo = mono_mempool_alloc (prof->mempool, sizeof (LastCallerInfo));
984 MONO_TIMER_INIT (callinfo->timer);
986 prof->cstorage = prof->cstorage->next;
988 callinfo->method = method;
989 callinfo->next = prof->callers;
990 prof->callers = callinfo;
991 MONO_TIMER_START (callinfo->timer);
995 simple_method_leave (MonoProfiler *prof, MonoMethod *method)
997 MethodProfile *profile_info;
998 LastCallerInfo *callinfo, *newcallinfo = NULL;
1000 GET_THREAD_PROF (prof);
1001 /*g_print ("leave %p %s::%s in %d (%p)\n", method, method->klass->name, method->name, GetCurrentThreadId (), prof);*/
1002 callinfo = prof->callers;
1003 /* should really not happen, but we don't catch exceptions events, yet ... */
1005 MONO_TIMER_STOP (callinfo->timer);
1006 profile_info = g_hash_table_lookup (prof->methods, callinfo->method);
1008 profile_info->total += MONO_TIMER_ELAPSED (callinfo->timer);
1009 newcallinfo = callinfo->next;
1010 callinfo->next = prof->cstorage;
1011 prof->cstorage = callinfo;
1012 if (callinfo->method == method)
1014 callinfo = newcallinfo;
1016 prof->callers = newcallinfo;
1020 simple_allocation (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1022 MethodProfile *profile_info;
1025 GET_THREAD_PROF (prof);
1026 if (prof->callers) {
1027 MonoMethod *caller = prof->callers->method;
1029 /* Otherwise all allocations are attributed to icall_wrapper_mono_object_new */
1030 if (caller->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
1031 caller = prof->callers->next->method;
1033 if (!(profile_info = g_hash_table_lookup (prof->methods, caller)))
1034 g_assert_not_reached ();
1036 return; /* fine for now */
1039 for (tmp = profile_info->alloc_info; tmp; tmp = tmp->next) {
1040 if (tmp->klass == klass)
1044 tmp = mono_mempool_alloc0 (prof->mempool, sizeof (AllocInfo));
1046 tmp->next = profile_info->alloc_info;
1047 profile_info->alloc_info = tmp;
1050 tmp->mem += mono_object_get_size (obj);
1054 simple_method_jit (MonoProfiler *prof, MonoMethod *method)
1056 GET_THREAD_PROF (prof);
1057 prof->methods_jitted++;
1058 MONO_TIMER_START (prof->jit_timer);
1062 simple_method_end_jit (MonoProfiler *prof, MonoMethod *method, int result)
1065 GET_THREAD_PROF (prof);
1066 MONO_TIMER_STOP (prof->jit_timer);
1067 jtime = MONO_TIMER_ELAPSED (prof->jit_timer);
1068 prof->jit_time += jtime;
1069 if (jtime > prof->max_jit_time) {
1070 prof->max_jit_time = jtime;
1071 prof->max_jit_method = method;
1075 /* about 10 minutes of samples */
1076 #define MAX_PROF_SAMPLES (1000*60*10)
1077 static int prof_counts = 0;
1078 static int prof_ucounts = 0;
1079 static gpointer* prof_addresses = NULL;
1080 static GHashTable *prof_table = NULL;
1083 simple_stat_hit (MonoProfiler *prof, guchar *ip, void *context)
1087 if (prof_counts >= MAX_PROF_SAMPLES)
1089 pos = InterlockedIncrement (&prof_counts);
1090 prof_addresses [pos - 1] = ip;
1094 compare_methods_prof (gconstpointer a, gconstpointer b)
1096 int ca = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, a));
1097 int cb = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, b));
1102 prof_foreach (char *method, gpointer c, gpointer data)
1104 GList **list = data;
1105 *list = g_list_insert_sorted (*list, method, compare_methods_prof);
1108 typedef struct Addr2LineData Addr2LineData;
1110 struct Addr2LineData {
1111 Addr2LineData *next;
1118 static Addr2LineData *addr2line_pipes = NULL;
1121 try_addr2line (const char* binary, gpointer ip)
1125 Addr2LineData *addr2line;
1127 for (addr2line = addr2line_pipes; addr2line; addr2line = addr2line->next) {
1128 if (strcmp (binary, addr2line->binary) == 0)
1132 const char *addr_argv[] = {"addr2line", "-f", "-e", binary, NULL};
1135 if (!g_spawn_async_with_pipes (NULL, (char**)addr_argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
1136 &child_pid, &ch_in, &ch_out, NULL, NULL)) {
1137 return g_strdup (binary);
1139 addr2line = g_new0 (Addr2LineData, 1);
1140 addr2line->child_pid = child_pid;
1141 addr2line->binary = g_strdup (binary);
1142 addr2line->pipein = fdopen (ch_in, "w");
1143 addr2line->pipeout = fdopen (ch_out, "r");
1144 addr2line->next = addr2line_pipes;
1145 addr2line_pipes = addr2line;
1147 fprintf (addr2line->pipein, "%p\n", ip);
1148 fflush (addr2line->pipein);
1149 /* we first get the func name and then file:lineno in a second line */
1150 if (fgets (buf, sizeof (buf), addr2line->pipeout) && buf [0] != '?') {
1151 char *end = strchr (buf, '\n');
1154 res = g_strdup_printf ("%s(%s", binary, buf);
1155 /* discard the filename/line info */
1156 fgets (buf, sizeof (buf), addr2line->pipeout);
1158 res = g_strdup (binary);
1164 stat_prof_report (void)
1167 int count = prof_counts;
1171 GList *tmp, *sorted = NULL;
1172 int pcount = ++ prof_counts;
1174 prof_counts = MAX_PROF_SAMPLES;
1175 for (i = 0; i < count; ++i) {
1176 ip = prof_addresses [i];
1177 ji = mono_jit_info_table_find (mono_domain_get (), ip);
1179 mn = mono_method_full_name (ji->method, TRUE);
1181 #ifdef HAVE_BACKTRACE_SYMBOLS
1186 names = backtrace_symbols (&ip, 1);
1187 send = strchr (names [0], '+');
1194 send = strchr (names [0], '[');
1197 if (no_func && names [0][0]) {
1198 char *endp = strchr (names [0], 0);
1199 while (--endp >= names [0] && g_ascii_isspace (*endp))
1201 mn = try_addr2line (names [0], ip);
1203 mn = g_strdup (names [0]);
1208 mn = g_strdup_printf ("unmanaged [%p]", ip);
1211 c = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, mn));
1213 g_hash_table_insert (prof_table, mn, GUINT_TO_POINTER (c));
1217 g_print ("prof counts: total/unmanaged: %d/%d\n", pcount, prof_ucounts);
1218 g_hash_table_foreach (prof_table, (GHFunc)prof_foreach, &sorted);
1219 for (tmp = sorted; tmp; tmp = tmp->next) {
1221 c = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, tmp->data));
1222 perc = c*100.0/count;
1223 g_print ("%7d\t%5.2f %% %s\n", c, perc, (char*)tmp->data);
1225 g_list_free (sorted);
1229 simple_appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
1231 /* FIXME: we should actually record partial data for each domain,
1232 * since the ip->ji->method mappings are going away at domain unload time.
1234 if (domain == mono_get_root_domain ())
1235 stat_prof_report ();
1239 simple_shutdown (MonoProfiler *prof)
1241 GList *profile = NULL;
1242 MonoProfiler *tprof;
1246 for (tmp = prof->per_thread; tmp; tmp = tmp->next) {
1248 merge_thread_data (prof, tprof);
1251 printf("Total time spent compiling %d methods (sec): %.4g\n", prof->methods_jitted, prof->jit_time);
1252 if (prof->max_jit_method) {
1253 str = method_get_name (prof->max_jit_method);
1254 printf("Slowest method to compile (sec): %.4g: %s\n", prof->max_jit_time, str);
1257 g_hash_table_foreach (prof->methods, (GHFunc)build_profile, &profile);
1258 output_profile (profile);
1259 g_list_free (profile);
1262 g_hash_table_foreach (prof->methods, (GHFunc)build_newobj_profile, &profile);
1263 output_newobj_profile (profile);
1264 g_list_free (profile);
1266 g_free (prof_addresses);
1267 prof_addresses = NULL;
1268 g_hash_table_destroy (prof_table);
1272 mono_profiler_install_simple (const char *desc)
1275 gchar **args, **ptr;
1276 MonoProfileFlags flags = 0;
1281 desc = "alloc,time,jit";
1285 if (strstr (desc, ":"))
1286 desc = strstr (desc, ":") + 1;
1288 desc = "alloc,time,jit";
1289 args = g_strsplit (desc, ",", -1);
1291 for (ptr = args; ptr && *ptr; ptr++) {
1292 const char *arg = *ptr;
1294 if (!strcmp (arg, "time"))
1295 flags |= MONO_PROFILE_ENTER_LEAVE;
1296 else if (!strcmp (arg, "alloc"))
1297 flags |= MONO_PROFILE_ALLOCATIONS;
1298 else if (!strcmp (arg, "stat"))
1299 flags |= MONO_PROFILE_STATISTICAL | MONO_PROFILE_APPDOMAIN_EVENTS;
1300 else if (!strcmp (arg, "jit"))
1301 flags |= MONO_PROFILE_JIT_COMPILATION;
1303 fprintf (stderr, "profiler : Unknown argument '%s'.\n", arg);
1309 prof = create_profiler ();
1311 SET_PROFILER (prof);
1313 /* statistical profiler data */
1314 prof_addresses = g_new0 (gpointer, MAX_PROF_SAMPLES);
1315 prof_table = g_hash_table_new (g_str_hash, g_str_equal);
1317 mono_profiler_install (prof, simple_shutdown);
1318 mono_profiler_install_enter_leave (simple_method_enter, simple_method_leave);
1319 mono_profiler_install_jit_compile (simple_method_jit, simple_method_end_jit);
1320 mono_profiler_install_allocation (simple_allocation);
1321 mono_profiler_install_appdomain (NULL, NULL, simple_appdomain_unload, NULL);
1322 mono_profiler_install_statistical (simple_stat_hit);
1323 mono_profiler_set_events (flags);
1326 #endif /* DISABLE_PROFILER */
1328 typedef void (*ProfilerInitializer) (const char*);
1329 #define INITIALIZER_NAME "mono_profiler_startup"
1332 mono_profiler_load (const char *desc)
1334 #ifndef DISABLE_PROFILER
1335 if (!desc || (strcmp ("default", desc) == 0) || (strncmp (desc, "default:", 8) == 0)) {
1336 mono_profiler_install_simple (desc);
1346 const char* col = strchr (desc, ':');
1351 mname = g_memdup (desc, col - desc);
1352 mname [col - desc] = 0;
1354 mname = g_strdup (desc);
1356 libname = g_strdup_printf ("mono-profiler-%s", mname);
1357 path = g_module_build_path (NULL, libname);
1358 pmodule = g_module_open (path, G_MODULE_BIND_LAZY);
1360 ProfilerInitializer func;
1361 if (!g_module_symbol (pmodule, INITIALIZER_NAME, (gpointer *)&func)) {
1362 g_warning ("Cannot find initializer function %s in profiler module: %s", INITIALIZER_NAME, libname);
1367 g_warning ("Error loading profiler module '%s': %s", libname, g_module_error ());