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 MonoProfileJitResult jit_end2;
42 static MonoProfileMethodResult man_unman_transition;
43 static MonoProfileAllocFunc allocation_cb;
44 static MonoProfileStatFunc statistical_cb;
45 static MonoProfileMethodFunc method_enter;
46 static MonoProfileMethodFunc method_leave;
48 static MonoProfileThreadFunc thread_start;
49 static MonoProfileThreadFunc thread_end;
51 static MonoProfileCoverageFilterFunc coverage_filter_cb;
53 static MonoProfileFunc shutdown_callback;
55 static MonoProfileGCFunc gc_event;
56 static MonoProfileGCResizeFunc gc_heap_resize;
58 #define mono_profiler_coverage_lock() EnterCriticalSection (&profiler_coverage_mutex)
59 #define mono_profiler_coverage_unlock() LeaveCriticalSection (&profiler_coverage_mutex)
60 static CRITICAL_SECTION profiler_coverage_mutex;
62 /* this is directly accessible to other mono libs. */
63 MonoProfileFlags mono_profiler_events;
66 mono_profiler_install (MonoProfiler *prof, MonoProfileFunc callback)
69 g_error ("profiler already setup");
70 current_profiler = prof;
71 shutdown_callback = callback;
72 InitializeCriticalSection (&profiler_coverage_mutex);
76 mono_profiler_set_events (MonoProfileFlags events)
78 mono_profiler_events = events;
82 mono_profiler_get_events (void)
84 return mono_profiler_events;
88 mono_profiler_install_enter_leave (MonoProfileMethodFunc enter, MonoProfileMethodFunc fleave)
91 method_leave = fleave;
95 mono_profiler_install_jit_compile (MonoProfileMethodFunc start, MonoProfileMethodResult end)
102 mono_profiler_install_jit_end (MonoProfileJitResult end)
108 mono_profiler_install_thread (MonoProfileThreadFunc start, MonoProfileThreadFunc end)
110 thread_start = start;
115 mono_profiler_install_transition (MonoProfileMethodResult callback)
117 man_unman_transition = callback;
121 mono_profiler_install_allocation (MonoProfileAllocFunc callback)
123 allocation_cb = callback;
127 mono_profiler_install_statistical (MonoProfileStatFunc callback)
129 statistical_cb = callback;
133 mono_profiler_install_coverage_filter (MonoProfileCoverageFilterFunc callback)
135 coverage_filter_cb = callback;
139 mono_profiler_install_appdomain (MonoProfileAppDomainFunc start_load, MonoProfileAppDomainResult end_load,
140 MonoProfileAppDomainFunc start_unload, MonoProfileAppDomainFunc end_unload)
143 domain_start_load = start_load;
144 domain_end_load = end_load;
145 domain_start_unload = start_unload;
146 domain_end_unload = end_unload;
150 mono_profiler_install_assembly (MonoProfileAssemblyFunc start_load, MonoProfileAssemblyResult end_load,
151 MonoProfileAssemblyFunc start_unload, MonoProfileAssemblyFunc end_unload)
153 assembly_start_load = start_load;
154 assembly_end_load = end_load;
155 assembly_start_unload = start_unload;
156 assembly_end_unload = end_unload;
160 mono_profiler_install_module (MonoProfileModuleFunc start_load, MonoProfileModuleResult end_load,
161 MonoProfileModuleFunc start_unload, MonoProfileModuleFunc end_unload)
163 module_start_load = start_load;
164 module_end_load = end_load;
165 module_start_unload = start_unload;
166 module_end_unload = end_unload;
170 mono_profiler_install_class (MonoProfileClassFunc start_load, MonoProfileClassResult end_load,
171 MonoProfileClassFunc start_unload, MonoProfileClassFunc end_unload)
173 class_start_load = start_load;
174 class_end_load = end_load;
175 class_start_unload = start_unload;
176 class_end_unload = end_unload;
180 mono_profiler_method_enter (MonoMethod *method)
182 if ((mono_profiler_events & MONO_PROFILE_ENTER_LEAVE) && method_enter)
183 method_enter (current_profiler, method);
187 mono_profiler_method_leave (MonoMethod *method)
189 if ((mono_profiler_events & MONO_PROFILE_ENTER_LEAVE) && method_leave)
190 method_leave (current_profiler, method);
194 mono_profiler_method_jit (MonoMethod *method)
196 if ((mono_profiler_events & MONO_PROFILE_JIT_COMPILATION) && jit_start)
197 jit_start (current_profiler, method);
201 mono_profiler_method_end_jit (MonoMethod *method, MonoJitInfo* jinfo, int result)
203 if ((mono_profiler_events & MONO_PROFILE_JIT_COMPILATION)) {
205 jit_end (current_profiler, method, result);
207 jit_end2 (current_profiler, method, jinfo, result);
212 mono_profiler_code_transition (MonoMethod *method, int result)
214 if ((mono_profiler_events & MONO_PROFILE_TRANSITIONS) && man_unman_transition)
215 man_unman_transition (current_profiler, method, result);
219 mono_profiler_allocation (MonoObject *obj, MonoClass *klass)
221 if ((mono_profiler_events & MONO_PROFILE_ALLOCATIONS) && allocation_cb)
222 allocation_cb (current_profiler, obj, klass);
226 mono_profiler_stat_hit (guchar *ip, void *context)
228 if ((mono_profiler_events & MONO_PROFILE_STATISTICAL) && statistical_cb)
229 statistical_cb (current_profiler, ip, context);
233 mono_profiler_thread_start (gsize tid)
235 if ((mono_profiler_events & MONO_PROFILE_THREADS) && thread_start)
236 thread_start (current_profiler, tid);
240 mono_profiler_thread_end (gsize tid)
242 if ((mono_profiler_events & MONO_PROFILE_THREADS) && thread_end)
243 thread_end (current_profiler, tid);
247 mono_profiler_assembly_event (MonoAssembly *assembly, int code)
249 if (!(mono_profiler_events & MONO_PROFILE_ASSEMBLY_EVENTS))
253 case MONO_PROFILE_START_LOAD:
254 if (assembly_start_load)
255 assembly_start_load (current_profiler, assembly);
257 case MONO_PROFILE_START_UNLOAD:
258 if (assembly_start_unload)
259 assembly_start_unload (current_profiler, assembly);
261 case MONO_PROFILE_END_UNLOAD:
262 if (assembly_end_unload)
263 assembly_end_unload (current_profiler, assembly);
266 g_assert_not_reached ();
271 mono_profiler_assembly_loaded (MonoAssembly *assembly, int result)
273 if ((mono_profiler_events & MONO_PROFILE_ASSEMBLY_EVENTS) && assembly_end_load)
274 assembly_end_load (current_profiler, assembly, result);
278 mono_profiler_module_event (MonoImage *module, int code)
280 if (!(mono_profiler_events & MONO_PROFILE_MODULE_EVENTS))
284 case MONO_PROFILE_START_LOAD:
285 if (module_start_load)
286 module_start_load (current_profiler, module);
288 case MONO_PROFILE_START_UNLOAD:
289 if (module_start_unload)
290 module_start_unload (current_profiler, module);
292 case MONO_PROFILE_END_UNLOAD:
293 if (module_end_unload)
294 module_end_unload (current_profiler, module);
297 g_assert_not_reached ();
302 mono_profiler_module_loaded (MonoImage *module, int result)
304 if ((mono_profiler_events & MONO_PROFILE_MODULE_EVENTS) && module_end_load)
305 module_end_load (current_profiler, module, result);
309 mono_profiler_class_event (MonoClass *klass, int code)
311 if (!(mono_profiler_events & MONO_PROFILE_CLASS_EVENTS))
315 case MONO_PROFILE_START_LOAD:
316 if (class_start_load)
317 class_start_load (current_profiler, klass);
319 case MONO_PROFILE_START_UNLOAD:
320 if (class_start_unload)
321 class_start_unload (current_profiler, klass);
323 case MONO_PROFILE_END_UNLOAD:
324 if (class_end_unload)
325 class_end_unload (current_profiler, klass);
328 g_assert_not_reached ();
333 mono_profiler_class_loaded (MonoClass *klass, int result)
335 if ((mono_profiler_events & MONO_PROFILE_CLASS_EVENTS) && class_end_load)
336 class_end_load (current_profiler, klass, result);
340 mono_profiler_appdomain_event (MonoDomain *domain, int code)
342 if (!(mono_profiler_events & MONO_PROFILE_APPDOMAIN_EVENTS))
346 case MONO_PROFILE_START_LOAD:
347 if (domain_start_load)
348 domain_start_load (current_profiler, domain);
350 case MONO_PROFILE_START_UNLOAD:
351 if (domain_start_unload)
352 domain_start_unload (current_profiler, domain);
354 case MONO_PROFILE_END_UNLOAD:
355 if (domain_end_unload)
356 domain_end_unload (current_profiler, domain);
359 g_assert_not_reached ();
364 mono_profiler_appdomain_loaded (MonoDomain *domain, int result)
366 if ((mono_profiler_events & MONO_PROFILE_APPDOMAIN_EVENTS) && domain_end_load)
367 domain_end_load (current_profiler, domain, result);
371 mono_profiler_shutdown (void)
373 if (current_profiler && shutdown_callback)
374 shutdown_callback (current_profiler);
378 mono_profiler_gc_heap_resize (gint64 new_size)
380 if ((mono_profiler_events & MONO_PROFILE_GC) && gc_heap_resize)
381 gc_heap_resize (current_profiler, new_size);
385 mono_profiler_gc_event (MonoGCEvent event, int generation)
387 if ((mono_profiler_events & MONO_PROFILE_GC) && gc_event)
388 gc_event (current_profiler, event, generation);
392 mono_profiler_install_gc (MonoProfileGCFunc callback, MonoProfileGCResizeFunc heap_resize_callback)
394 mono_gc_enable_events ();
396 gc_heap_resize = heap_resize_callback;
399 static GHashTable *coverage_hash = NULL;
401 MonoProfileCoverageInfo*
402 mono_profiler_coverage_alloc (MonoMethod *method, int entries)
404 MonoProfileCoverageInfo *res;
406 if (coverage_filter_cb)
407 if (! (*coverage_filter_cb) (current_profiler, method))
410 mono_profiler_coverage_lock ();
412 coverage_hash = g_hash_table_new (NULL, NULL);
414 res = g_malloc0 (sizeof (MonoProfileCoverageInfo) + sizeof (void*) * 2 * entries);
416 res->entries = entries;
418 g_hash_table_insert (coverage_hash, method, res);
419 mono_profiler_coverage_unlock ();
424 /* safe only when the method antive code has been unloaded */
426 mono_profiler_coverage_free (MonoMethod *method)
428 MonoProfileCoverageInfo* info;
430 mono_profiler_coverage_lock ();
431 if (!coverage_hash) {
432 mono_profiler_coverage_unlock ();
436 info = g_hash_table_lookup (coverage_hash, method);
439 g_hash_table_remove (coverage_hash, method);
441 mono_profiler_coverage_unlock ();
445 mono_profiler_coverage_get (MonoProfiler *prof, MonoMethod *method, MonoProfileCoverageFunc func)
447 MonoProfileCoverageInfo* info;
450 const unsigned char *start, *end, *cil_code;
451 MonoMethodHeader *header;
452 MonoProfileCoverageEntry entry;
454 mono_profiler_coverage_lock ();
455 info = g_hash_table_lookup (coverage_hash, method);
456 mono_profiler_coverage_unlock ();
461 header = mono_method_get_header (method);
462 start = mono_method_header_get_code (header, &col, NULL);
464 for (i = 0; i < info->entries; ++i) {
465 cil_code = info->data [i].cil_code;
466 if (cil_code && cil_code >= start && cil_code < end) {
467 offset = cil_code - start;
468 entry.iloffset = offset;
469 entry.method = method;
470 entry.counter = info->data [i].count;
471 /* the debug interface doesn't support column info, sigh */
473 entry.filename = mono_debug_source_location_from_il_offset (method, offset, &line);
481 #ifndef DISABLE_PROFILER
483 * Small profiler extracted from mint: we should move it in a loadable module
484 * and improve it to do graphs and more accurate timestamping with rdtsc.
488 #define USE_WIN32COUNTER 0
492 unsigned int lows, highs, lowe, highe;
495 #define rdtsc(low,high) \
496 __asm__ __volatile__("rdtsc" : "=a" (low), "=d" (high))
501 rdtsc_elapsed (MonoRdtscTimer *t)
503 unsigned long long diff;
504 unsigned int highe = t->highe;
505 if (t->lowe < t->lows)
507 diff = (((unsigned long long) highe - t->highs) << 32) + (t->lowe - t->lows);
508 return ((double)diff / freq) / 1000000; /* have to return the result in seconds */
519 if (!(cpuinfo = fopen ("/proc/cpuinfo", "r")))
521 while (fgets (buf, sizeof(buf), cpuinfo)) {
522 if (sscanf (buf, "cpu MHz : %f", &val) == 1) {
523 /*printf ("got mh: %f\n", val);*/
526 if (strncmp (buf, "flags", 5) == 0) {
527 if (strstr (buf, "tsc")) {
529 /*printf ("have tsc\n");*/
534 return have_flag? have_freq: 0;
537 #define MONO_TIMER_STARTUP \
538 if (!(freq = have_rdtsc ())) g_error ("Compiled with TSC support, but none found");
539 #define MONO_TIMER_TYPE MonoRdtscTimer
540 #define MONO_TIMER_INIT(t)
541 #define MONO_TIMER_DESTROY(t)
542 #define MONO_TIMER_START(t) rdtsc ((t).lows, (t).highs);
543 #define MONO_TIMER_STOP(t) rdtsc ((t).lowe, (t).highe);
544 #define MONO_TIMER_ELAPSED(t) rdtsc_elapsed (&(t))
546 #elif USE_WIN32COUNTER
550 LARGE_INTEGER start, stop;
556 win32_elapsed (MonoWin32Timer *t)
558 LONGLONG diff = t->stop.QuadPart - t->start.QuadPart;
559 return ((double)diff / freq) / 1000000; /* have to return the result in seconds */
563 have_win32counter (void) {
566 if (!QueryPerformanceFrequency (&f))
571 #define MONO_TIMER_STARTUP \
572 if (!(freq = have_win32counter ())) g_error ("Compiled with Win32 counter support, but none found");
573 #define MONO_TIMER_TYPE MonoWin32Timer
574 #define MONO_TIMER_INIT(t)
575 #define MONO_TIMER_DESTROY(t)
576 #define MONO_TIMER_START(t) QueryPerformanceCounter (&(t).start)
577 #define MONO_TIMER_STOP(t) QueryPerformanceCounter (&(t).stop)
578 #define MONO_TIMER_ELAPSED(t) win32_elapsed (&(t))
583 GTimeVal start, stop;
587 timeval_elapsed (MonoGLibTimer *t)
589 if (t->start.tv_usec > t->stop.tv_usec) {
590 t->stop.tv_usec += G_USEC_PER_SEC;
593 return (t->stop.tv_sec - t->start.tv_sec)
594 + ((double)(t->stop.tv_usec - t->start.tv_usec))/ G_USEC_PER_SEC;
597 #define MONO_TIMER_STARTUP
598 #define MONO_TIMER_TYPE MonoGLibTimer
599 #define MONO_TIMER_INIT(t)
600 #define MONO_TIMER_DESTROY(t)
601 #define MONO_TIMER_START(t) g_get_current_time (&(t).start)
602 #define MONO_TIMER_STOP(t) g_get_current_time (&(t).stop)
603 #define MONO_TIMER_ELAPSED(t) timeval_elapsed (&(t))
606 typedef struct _AllocInfo AllocInfo;
607 typedef struct _CallerInfo CallerInfo;
608 typedef struct _LastCallerInfo LastCallerInfo;
610 struct _MonoProfiler {
612 MonoMemPool *mempool;
613 /* info about JIT time */
614 MONO_TIMER_TYPE jit_timer;
617 MonoMethod *max_jit_method;
622 /* chain of callers for the current thread */
623 LastCallerInfo *callers;
624 /* LastCallerInfo nodes for faster allocation */
625 LastCallerInfo *cstorage;
632 AllocInfo *alloc_info;
633 CallerInfo *caller_info;
636 typedef struct _MethodCallProfile MethodCallProfile;
638 struct _MethodCallProfile {
639 MethodCallProfile *next;
640 MONO_TIMER_TYPE timer;
657 struct _LastCallerInfo {
658 LastCallerInfo *next;
660 MONO_TIMER_TYPE timer;
664 create_profiler (void)
666 MonoProfiler *prof = g_new0 (MonoProfiler, 1);
668 prof->methods = g_hash_table_new (NULL, NULL);
669 MONO_TIMER_INIT (prof->jit_timer);
670 prof->mempool = mono_mempool_new ();
675 #ifdef HAVE_KW_THREAD
676 static __thread MonoProfiler * tls_profiler;
677 # define GET_PROFILER() tls_profiler
678 # define SET_PROFILER(x) tls_profiler = (x)
679 # define ALLOC_PROFILER() /* nop */
681 static guint32 profiler_thread_id = -1;
682 # define GET_PROFILER() ((MonoProfiler *)TlsGetValue (profiler_thread_id))
683 # define SET_PROFILER(x) TlsSetValue (profiler_thread_id, x);
684 # define ALLOC_PROFILER() profiler_thread_id = TlsAlloc ()
687 #define GET_THREAD_PROF(prof) do { \
688 MonoProfiler *_tprofiler = GET_PROFILER (); \
690 _tprofiler = create_profiler (); \
691 prof->per_thread = g_slist_prepend (prof->per_thread, _tprofiler); \
692 SET_PROFILER (_tprofiler); \
697 /* thread unsafe but faster variant */
698 #define GET_THREAD_PROF(prof)
702 compare_profile (MethodProfile *profa, MethodProfile *profb)
704 return (gint)((profb->total - profa->total)*1000);
708 build_profile (MonoMethod *m, MethodProfile *prof, GList **funcs)
711 *funcs = g_list_insert_sorted (*funcs, prof, (GCompareFunc)compare_profile);
715 method_get_name (MonoMethod* method)
719 sig = mono_signature_get_desc (mono_method_signature (method), FALSE);
720 res = g_strdup_printf ("%s%s%s::%s(%s)", method->klass->name_space,
721 method->klass->name_space ? "." : "", method->klass->name,
727 static void output_callers (MethodProfile *p);
730 output_profile (GList *funcs)
735 guint64 total_calls = 0;
738 g_print ("Time(ms) Count P/call(ms) Method name\n");
739 for (tmp = funcs; tmp; tmp = tmp->next) {
741 total_calls += p->count;
742 if (!(gint)(p->total*1000))
744 m = method_get_name (p->method);
745 printf ("########################\n");
746 printf ("% 8.3f ", (double) (p->total * 1000));
747 printf ("%7llu ", (unsigned long long)p->count);
748 printf ("% 8.3f ", (double) (p->total * 1000)/(double)p->count);
755 printf ("Total number of calls: %lld\n", (long long)total_calls);
764 compare_newobj_profile (NewobjProfile *profa, NewobjProfile *profb)
766 if (profb->count == profa->count)
769 return profb->count > profa->count ? 1 : -1;
773 build_newobj_profile (MonoClass *class, MethodProfile *mprof, GList **funcs)
775 NewobjProfile *prof = g_new (NewobjProfile, 1);
780 /* we use the total amount of memory to sort */
781 for (tmp = mprof->alloc_info; tmp; tmp = tmp->next)
784 *funcs = g_list_insert_sorted (*funcs, prof, (GCompareFunc)compare_newobj_profile);
788 compare_caller (CallerInfo *a, CallerInfo *b)
790 return b->count - a->count;
794 compare_alloc (AllocInfo *a, AllocInfo *b)
796 return b->mem - a->mem;
800 sort_alloc_list (AllocInfo *ai)
804 for (tmp = ai; tmp; tmp = tmp->next) {
805 l = g_slist_insert_sorted (l, tmp, (GCompareFunc)compare_alloc);
811 sort_caller_list (CallerInfo *ai)
815 for (tmp = ai; tmp; tmp = tmp->next) {
816 l = g_slist_insert_sorted (l, tmp, (GCompareFunc)compare_caller);
822 output_callers (MethodProfile *p) {
823 guint total_callers, percent;
824 GSList *sorted, *tmps;
828 g_print (" Callers (with count) that contribute at least for 1%%:\n");
830 for (cinfo = p->caller_info; cinfo; cinfo = cinfo->next) {
831 total_callers += cinfo->count;
833 sorted = sort_caller_list (p->caller_info);
834 for (tmps = sorted; tmps; tmps = tmps->next) {
836 percent = (cinfo->count * 100)/total_callers;
839 m = method_get_name (cinfo->caller);
840 g_print (" %8d % 3d %% %s\n", cinfo->count, percent, m);
845 /* This isn't defined on older glib versions and on some platforms */
846 #ifndef G_GUINT64_FORMAT
847 #define G_GUINT64_FORMAT "ul"
851 output_newobj_profile (GList *proflist)
862 GSList *sorted, *tmps;
864 g_print ("\nAllocation profiler\n");
867 g_print ("%-9s %s\n", "Total mem", "Method");
868 for (tmp = proflist; tmp; tmp = tmp->next) {
871 if (p->count < 50000)
874 m = method_get_name (mp->method);
875 g_print ("########################\n%8" G_GUINT64_FORMAT " KB %s\n", (p->count / 1024), m);
877 sorted = sort_alloc_list (mp->alloc_info);
878 for (tmps = sorted; tmps; tmps = tmps->next) {
880 if (ainfo->mem < 50000)
882 klass = ainfo->klass;
885 klass = klass->element_class;
889 g_snprintf (buf, sizeof (buf), "%s%s%s%s",
890 klass->name_space, klass->name_space ? "." : "", klass->name, isarray);
891 g_print (" %8" G_GUINT64_FORMAT " KB %8" G_GUINT64_FORMAT " %-48s\n", (ainfo->mem / 1024), ainfo->count, buf);
896 g_print ("Total memory allocated: %" G_GUINT64_FORMAT " KB\n", total / 1024);
900 merge_methods (MonoMethod *method, MethodProfile *profile, MonoProfiler *prof)
902 MethodProfile *mprof;
903 AllocInfo *talloc_info, *alloc_info;
904 CallerInfo *tcaller_info, *caller_info;
906 mprof = g_hash_table_lookup (prof->methods, method);
908 /* the master thread didn't see this method, just transfer the info as is */
909 g_hash_table_insert (prof->methods, method, profile);
912 /* merge the info from profile into mprof */
913 mprof->count += profile->count;
914 mprof->total += profile->total;
915 /* merge alloc info */
916 for (talloc_info = profile->alloc_info; talloc_info; talloc_info = talloc_info->next) {
917 for (alloc_info = mprof->alloc_info; alloc_info; alloc_info = alloc_info->next) {
918 if (alloc_info->klass == talloc_info->klass) {
919 /* mprof already has a record for the klass, merge */
920 alloc_info->count += talloc_info->count;
921 alloc_info->mem += talloc_info->mem;
926 /* mprof didn't have the info, just copy it over */
927 alloc_info = mono_mempool_alloc0 (prof->mempool, sizeof (AllocInfo));
928 *alloc_info = *talloc_info;
929 alloc_info->next = mprof->alloc_info;
930 mprof->alloc_info = alloc_info->next;
933 /* merge callers info */
934 for (tcaller_info = profile->caller_info; tcaller_info; tcaller_info = tcaller_info->next) {
935 for (caller_info = mprof->caller_info; caller_info; caller_info = caller_info->next) {
936 if (caller_info->caller == tcaller_info->caller) {
937 /* mprof already has a record for the caller method, merge */
938 caller_info->count += tcaller_info->count;
943 /* mprof didn't have the info, just copy it over */
944 caller_info = mono_mempool_alloc0 (prof->mempool, sizeof (CallerInfo));
945 *caller_info = *tcaller_info;
946 caller_info->next = mprof->caller_info;
947 mprof->caller_info = caller_info;
953 merge_thread_data (MonoProfiler *master, MonoProfiler *tprof)
955 master->jit_time += tprof->jit_time;
956 master->methods_jitted += tprof->methods_jitted;
957 if (master->max_jit_time < tprof->max_jit_time) {
958 master->max_jit_time = tprof->max_jit_time;
959 master->max_jit_method = tprof->max_jit_method;
962 g_hash_table_foreach (tprof->methods, (GHFunc)merge_methods, master);
966 simple_method_enter (MonoProfiler *prof, MonoMethod *method)
968 MethodProfile *profile_info;
969 LastCallerInfo *callinfo;
970 GET_THREAD_PROF (prof);
971 /*g_print ("enter %p %s::%s in %d (%p)\n", method, method->klass->name, method->name, GetCurrentThreadId (), prof);*/
972 if (!(profile_info = g_hash_table_lookup (prof->methods, method))) {
973 profile_info = mono_mempool_alloc0 (prof->mempool, sizeof (MethodProfile));
974 MONO_TIMER_INIT (profile_info->u.timer);
975 g_hash_table_insert (prof->methods, method, profile_info);
977 profile_info->count++;
980 MonoMethod *caller = prof->callers->method;
981 for (cinfo = profile_info->caller_info; cinfo; cinfo = cinfo->next) {
982 if (cinfo->caller == caller)
986 cinfo = mono_mempool_alloc0 (prof->mempool, sizeof (CallerInfo));
987 cinfo->caller = caller;
988 cinfo->next = profile_info->caller_info;
989 profile_info->caller_info = cinfo;
993 if (!(callinfo = prof->cstorage)) {
994 callinfo = mono_mempool_alloc (prof->mempool, sizeof (LastCallerInfo));
995 MONO_TIMER_INIT (callinfo->timer);
997 prof->cstorage = prof->cstorage->next;
999 callinfo->method = method;
1000 callinfo->next = prof->callers;
1001 prof->callers = callinfo;
1002 MONO_TIMER_START (callinfo->timer);
1006 simple_method_leave (MonoProfiler *prof, MonoMethod *method)
1008 MethodProfile *profile_info;
1009 LastCallerInfo *callinfo, *newcallinfo = NULL;
1011 GET_THREAD_PROF (prof);
1012 /*g_print ("leave %p %s::%s in %d (%p)\n", method, method->klass->name, method->name, GetCurrentThreadId (), prof);*/
1013 callinfo = prof->callers;
1014 /* should really not happen, but we don't catch exceptions events, yet ... */
1016 MONO_TIMER_STOP (callinfo->timer);
1017 profile_info = g_hash_table_lookup (prof->methods, callinfo->method);
1019 profile_info->total += MONO_TIMER_ELAPSED (callinfo->timer);
1020 newcallinfo = callinfo->next;
1021 callinfo->next = prof->cstorage;
1022 prof->cstorage = callinfo;
1023 if (callinfo->method == method)
1025 callinfo = newcallinfo;
1027 prof->callers = newcallinfo;
1031 simple_allocation (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1033 MethodProfile *profile_info;
1036 GET_THREAD_PROF (prof);
1037 if (prof->callers) {
1038 MonoMethod *caller = prof->callers->method;
1040 /* Otherwise all allocations are attributed to icall_wrapper_mono_object_new */
1041 if (caller->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
1042 caller = prof->callers->next->method;
1044 if (!(profile_info = g_hash_table_lookup (prof->methods, caller)))
1045 g_assert_not_reached ();
1047 return; /* fine for now */
1050 for (tmp = profile_info->alloc_info; tmp; tmp = tmp->next) {
1051 if (tmp->klass == klass)
1055 tmp = mono_mempool_alloc0 (prof->mempool, sizeof (AllocInfo));
1057 tmp->next = profile_info->alloc_info;
1058 profile_info->alloc_info = tmp;
1061 tmp->mem += mono_object_get_size (obj);
1065 simple_method_jit (MonoProfiler *prof, MonoMethod *method)
1067 GET_THREAD_PROF (prof);
1068 prof->methods_jitted++;
1069 MONO_TIMER_START (prof->jit_timer);
1073 simple_method_end_jit (MonoProfiler *prof, MonoMethod *method, int result)
1076 GET_THREAD_PROF (prof);
1077 MONO_TIMER_STOP (prof->jit_timer);
1078 jtime = MONO_TIMER_ELAPSED (prof->jit_timer);
1079 prof->jit_time += jtime;
1080 if (jtime > prof->max_jit_time) {
1081 prof->max_jit_time = jtime;
1082 prof->max_jit_method = method;
1086 /* about 10 minutes of samples */
1087 #define MAX_PROF_SAMPLES (1000*60*10)
1088 static int prof_counts = 0;
1089 static int prof_ucounts = 0;
1090 static gpointer* prof_addresses = NULL;
1091 static GHashTable *prof_table = NULL;
1094 simple_stat_hit (MonoProfiler *prof, guchar *ip, void *context)
1098 if (prof_counts >= MAX_PROF_SAMPLES)
1100 pos = InterlockedIncrement (&prof_counts);
1101 prof_addresses [pos - 1] = ip;
1105 compare_methods_prof (gconstpointer a, gconstpointer b)
1107 int ca = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, a));
1108 int cb = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, b));
1113 prof_foreach (char *method, gpointer c, gpointer data)
1115 GList **list = data;
1116 *list = g_list_insert_sorted (*list, method, compare_methods_prof);
1119 typedef struct Addr2LineData Addr2LineData;
1121 struct Addr2LineData {
1122 Addr2LineData *next;
1129 static Addr2LineData *addr2line_pipes = NULL;
1132 try_addr2line (const char* binary, gpointer ip)
1136 Addr2LineData *addr2line;
1138 for (addr2line = addr2line_pipes; addr2line; addr2line = addr2line->next) {
1139 if (strcmp (binary, addr2line->binary) == 0)
1143 const char *addr_argv[] = {"addr2line", "-f", "-e", binary, NULL};
1146 if (!g_spawn_async_with_pipes (NULL, (char**)addr_argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
1147 &child_pid, &ch_in, &ch_out, NULL, NULL)) {
1148 return g_strdup (binary);
1150 addr2line = g_new0 (Addr2LineData, 1);
1151 addr2line->child_pid = child_pid;
1152 addr2line->binary = g_strdup (binary);
1153 addr2line->pipein = fdopen (ch_in, "w");
1154 addr2line->pipeout = fdopen (ch_out, "r");
1155 addr2line->next = addr2line_pipes;
1156 addr2line_pipes = addr2line;
1158 fprintf (addr2line->pipein, "%p\n", ip);
1159 fflush (addr2line->pipein);
1160 /* we first get the func name and then file:lineno in a second line */
1161 if (fgets (buf, sizeof (buf), addr2line->pipeout) && buf [0] != '?') {
1162 char *end = strchr (buf, '\n');
1165 res = g_strdup_printf ("%s(%s", binary, buf);
1166 /* discard the filename/line info */
1167 fgets (buf, sizeof (buf), addr2line->pipeout);
1169 res = g_strdup (binary);
1175 stat_prof_report (void)
1178 int count = prof_counts;
1182 GList *tmp, *sorted = NULL;
1183 int pcount = ++ prof_counts;
1185 prof_counts = MAX_PROF_SAMPLES;
1186 for (i = 0; i < count; ++i) {
1187 ip = prof_addresses [i];
1188 ji = mono_jit_info_table_find (mono_domain_get (), ip);
1190 mn = mono_method_full_name (ji->method, TRUE);
1192 #ifdef HAVE_BACKTRACE_SYMBOLS
1197 names = backtrace_symbols (&ip, 1);
1198 send = strchr (names [0], '+');
1205 send = strchr (names [0], '[');
1208 if (no_func && names [0][0]) {
1209 char *endp = strchr (names [0], 0);
1210 while (--endp >= names [0] && g_ascii_isspace (*endp))
1212 mn = try_addr2line (names [0], ip);
1214 mn = g_strdup (names [0]);
1219 mn = g_strdup_printf ("unmanaged [%p]", ip);
1222 c = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, mn));
1224 g_hash_table_insert (prof_table, mn, GUINT_TO_POINTER (c));
1228 g_print ("prof counts: total/unmanaged: %d/%d\n", pcount, prof_ucounts);
1229 g_hash_table_foreach (prof_table, (GHFunc)prof_foreach, &sorted);
1230 for (tmp = sorted; tmp; tmp = tmp->next) {
1232 c = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, tmp->data));
1233 perc = c*100.0/count;
1234 g_print ("%7d\t%5.2f %% %s\n", c, perc, (char*)tmp->data);
1236 g_list_free (sorted);
1240 simple_appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
1242 /* FIXME: we should actually record partial data for each domain,
1243 * since the ip->ji->method mappings are going away at domain unload time.
1245 if (domain == mono_get_root_domain ())
1246 stat_prof_report ();
1250 simple_shutdown (MonoProfiler *prof)
1252 GList *profile = NULL;
1253 MonoProfiler *tprof;
1257 for (tmp = prof->per_thread; tmp; tmp = tmp->next) {
1259 merge_thread_data (prof, tprof);
1262 printf("Total time spent compiling %d methods (sec): %.4g\n", prof->methods_jitted, prof->jit_time);
1263 if (prof->max_jit_method) {
1264 str = method_get_name (prof->max_jit_method);
1265 printf("Slowest method to compile (sec): %.4g: %s\n", prof->max_jit_time, str);
1268 g_hash_table_foreach (prof->methods, (GHFunc)build_profile, &profile);
1269 output_profile (profile);
1270 g_list_free (profile);
1273 g_hash_table_foreach (prof->methods, (GHFunc)build_newobj_profile, &profile);
1274 output_newobj_profile (profile);
1275 g_list_free (profile);
1277 g_free (prof_addresses);
1278 prof_addresses = NULL;
1279 g_hash_table_destroy (prof_table);
1283 mono_profiler_install_simple (const char *desc)
1286 gchar **args, **ptr;
1287 MonoProfileFlags flags = 0;
1292 desc = "alloc,time,jit";
1296 if (strstr (desc, ":"))
1297 desc = strstr (desc, ":") + 1;
1299 desc = "alloc,time,jit";
1300 args = g_strsplit (desc, ",", -1);
1302 for (ptr = args; ptr && *ptr; ptr++) {
1303 const char *arg = *ptr;
1305 if (!strcmp (arg, "time"))
1306 flags |= MONO_PROFILE_ENTER_LEAVE;
1307 else if (!strcmp (arg, "alloc"))
1308 flags |= MONO_PROFILE_ALLOCATIONS;
1309 else if (!strcmp (arg, "stat"))
1310 flags |= MONO_PROFILE_STATISTICAL | MONO_PROFILE_APPDOMAIN_EVENTS;
1311 else if (!strcmp (arg, "jit"))
1312 flags |= MONO_PROFILE_JIT_COMPILATION;
1314 fprintf (stderr, "profiler : Unknown argument '%s'.\n", arg);
1320 prof = create_profiler ();
1322 SET_PROFILER (prof);
1324 /* statistical profiler data */
1325 prof_addresses = g_new0 (gpointer, MAX_PROF_SAMPLES);
1326 prof_table = g_hash_table_new (g_str_hash, g_str_equal);
1328 mono_profiler_install (prof, simple_shutdown);
1329 mono_profiler_install_enter_leave (simple_method_enter, simple_method_leave);
1330 mono_profiler_install_jit_compile (simple_method_jit, simple_method_end_jit);
1331 mono_profiler_install_allocation (simple_allocation);
1332 mono_profiler_install_appdomain (NULL, NULL, simple_appdomain_unload, NULL);
1333 mono_profiler_install_statistical (simple_stat_hit);
1334 mono_profiler_set_events (flags);
1337 #endif /* DISABLE_PROFILER */
1339 typedef void (*ProfilerInitializer) (const char*);
1340 #define INITIALIZER_NAME "mono_profiler_startup"
1343 mono_profiler_load (const char *desc)
1345 #ifndef DISABLE_PROFILER
1346 if (!desc || (strcmp ("default", desc) == 0) || (strncmp (desc, "default:", 8) == 0)) {
1347 mono_profiler_install_simple (desc);
1357 const char* col = strchr (desc, ':');
1362 mname = g_memdup (desc, col - desc);
1363 mname [col - desc] = 0;
1365 mname = g_strdup (desc);
1367 libname = g_strdup_printf ("mono-profiler-%s", mname);
1368 path = g_module_build_path (NULL, libname);
1369 pmodule = g_module_open (path, G_MODULE_BIND_LAZY);
1371 ProfilerInitializer func;
1372 if (!g_module_symbol (pmodule, INITIALIZER_NAME, (gpointer *)&func)) {
1373 g_warning ("Cannot find initializer function %s in profiler module: %s", INITIALIZER_NAME, libname);
1378 g_warning ("Error loading profiler module '%s': %s", libname, g_module_error ());