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/io-layer/io-layer.h"
12 #ifdef HAVE_BACKTRACE_SYMBOLS
16 static MonoProfiler * current_profiler = NULL;
18 static MonoProfileAppDomainFunc domain_start_load;
19 static MonoProfileAppDomainResult domain_end_load;
20 static MonoProfileAppDomainFunc domain_start_unload;
21 static MonoProfileAppDomainFunc domain_end_unload;
23 static MonoProfileAssemblyFunc assembly_start_load;
24 static MonoProfileAssemblyResult assembly_end_load;
25 static MonoProfileAssemblyFunc assembly_start_unload;
26 static MonoProfileAssemblyFunc assembly_end_unload;
28 static MonoProfileModuleFunc module_start_load;
29 static MonoProfileModuleResult module_end_load;
30 static MonoProfileModuleFunc module_start_unload;
31 static MonoProfileModuleFunc module_end_unload;
33 static MonoProfileClassFunc class_start_load;
34 static MonoProfileClassResult class_end_load;
35 static MonoProfileClassFunc class_start_unload;
36 static MonoProfileClassFunc class_end_unload;
38 static MonoProfileMethodFunc jit_start;
39 static MonoProfileMethodResult jit_end;
40 static MonoProfileMethodResult man_unman_transition;
41 static MonoProfileAllocFunc allocation_cb;
42 static MonoProfileStatFunc statistical_cb;
43 static MonoProfileMethodFunc method_enter;
44 static MonoProfileMethodFunc method_leave;
46 static MonoProfileThreadFunc thread_start;
47 static MonoProfileThreadFunc thread_end;
49 static MonoProfileCoverageFilterFunc coverage_filter_cb;
51 static MonoProfileFunc shutdown_callback;
53 static CRITICAL_SECTION profiler_coverage_mutex;
55 /* this is directly accessible to other mono libs. */
56 MonoProfileFlags mono_profiler_events;
59 mono_profiler_install (MonoProfiler *prof, MonoProfileFunc callback)
62 g_error ("profiler already setup");
63 current_profiler = prof;
64 shutdown_callback = callback;
65 InitializeCriticalSection (&profiler_coverage_mutex);
69 mono_profiler_set_events (MonoProfileFlags events)
71 mono_profiler_events = events;
75 mono_profiler_get_events (void)
77 return mono_profiler_events;
81 mono_profiler_install_enter_leave (MonoProfileMethodFunc enter, MonoProfileMethodFunc fleave)
84 method_leave = fleave;
88 mono_profiler_install_jit_compile (MonoProfileMethodFunc start, MonoProfileMethodResult end)
95 mono_profiler_install_thread (MonoProfileThreadFunc start, MonoProfileThreadFunc end)
102 mono_profiler_install_transition (MonoProfileMethodResult callback)
104 man_unman_transition = callback;
108 mono_profiler_install_allocation (MonoProfileAllocFunc callback)
110 allocation_cb = callback;
114 mono_profiler_install_statistical (MonoProfileStatFunc callback)
116 statistical_cb = callback;
120 mono_profiler_install_coverage_filter (MonoProfileCoverageFilterFunc callback)
122 coverage_filter_cb = callback;
126 mono_profiler_install_appdomain (MonoProfileAppDomainFunc start_load, MonoProfileAppDomainResult end_load,
127 MonoProfileAppDomainFunc start_unload, MonoProfileAppDomainFunc end_unload)
130 domain_start_load = start_load;
131 domain_end_load = end_load;
132 domain_start_unload = start_unload;
133 domain_end_unload = end_unload;
137 mono_profiler_install_assembly (MonoProfileAssemblyFunc start_load, MonoProfileAssemblyResult end_load,
138 MonoProfileAssemblyFunc start_unload, MonoProfileAssemblyFunc end_unload)
140 assembly_start_load = start_load;
141 assembly_end_load = end_load;
142 assembly_start_unload = start_unload;
143 assembly_end_unload = end_unload;
147 mono_profiler_install_module (MonoProfileModuleFunc start_load, MonoProfileModuleResult end_load,
148 MonoProfileModuleFunc start_unload, MonoProfileModuleFunc end_unload)
150 module_start_load = start_load;
151 module_end_load = end_load;
152 module_start_unload = start_unload;
153 module_end_unload = end_unload;
157 mono_profiler_install_class (MonoProfileClassFunc start_load, MonoProfileClassResult end_load,
158 MonoProfileClassFunc start_unload, MonoProfileClassFunc end_unload)
160 class_start_load = start_load;
161 class_end_load = end_load;
162 class_start_unload = start_unload;
163 class_end_unload = end_unload;
167 mono_profiler_method_enter (MonoMethod *method)
169 if ((mono_profiler_events & MONO_PROFILE_ENTER_LEAVE) && method_enter)
170 method_enter (current_profiler, method);
174 mono_profiler_method_leave (MonoMethod *method)
176 if ((mono_profiler_events & MONO_PROFILE_ENTER_LEAVE) && method_leave)
177 method_leave (current_profiler, method);
181 mono_profiler_method_jit (MonoMethod *method)
183 if ((mono_profiler_events & MONO_PROFILE_JIT_COMPILATION) && jit_start)
184 jit_start (current_profiler, method);
188 mono_profiler_method_end_jit (MonoMethod *method, int result)
190 if ((mono_profiler_events & MONO_PROFILE_JIT_COMPILATION) && jit_end)
191 jit_end (current_profiler, method, result);
195 mono_profiler_code_transition (MonoMethod *method, int result)
197 if ((mono_profiler_events & MONO_PROFILE_TRANSITIONS) && man_unman_transition)
198 man_unman_transition (current_profiler, method, result);
202 mono_profiler_allocation (MonoObject *obj, MonoClass *klass)
204 if ((mono_profiler_events & MONO_PROFILE_ALLOCATIONS) && allocation_cb)
205 allocation_cb (current_profiler, obj, klass);
209 mono_profiler_stat_hit (guchar *ip, void *context)
211 if ((mono_profiler_events & MONO_PROFILE_STATISTICAL) && statistical_cb)
212 statistical_cb (current_profiler, ip, context);
216 mono_profiler_thread_start (guint32 tid)
218 if ((mono_profiler_events & MONO_PROFILE_THREADS) && thread_start)
219 thread_start (current_profiler, tid);
223 mono_profiler_thread_end (guint32 tid)
225 if ((mono_profiler_events & MONO_PROFILE_THREADS) && thread_end)
226 thread_end (current_profiler, tid);
230 mono_profiler_assembly_event (MonoAssembly *assembly, int code)
232 if (!(mono_profiler_events & MONO_PROFILE_ASSEMBLY_EVENTS))
236 case MONO_PROFILE_START_LOAD:
237 if (assembly_start_load)
238 assembly_start_load (current_profiler, assembly);
240 case MONO_PROFILE_START_UNLOAD:
241 if (assembly_start_unload)
242 assembly_start_unload (current_profiler, assembly);
244 case MONO_PROFILE_END_UNLOAD:
245 if (assembly_end_unload)
246 assembly_end_unload (current_profiler, assembly);
249 g_assert_not_reached ();
254 mono_profiler_assembly_loaded (MonoAssembly *assembly, int result)
256 if ((mono_profiler_events & MONO_PROFILE_ASSEMBLY_EVENTS) && assembly_end_load)
257 assembly_end_load (current_profiler, assembly, result);
261 mono_profiler_module_event (MonoImage *module, int code)
263 if (!(mono_profiler_events & MONO_PROFILE_MODULE_EVENTS))
267 case MONO_PROFILE_START_LOAD:
268 if (module_start_load)
269 module_start_load (current_profiler, module);
271 case MONO_PROFILE_START_UNLOAD:
272 if (module_start_unload)
273 module_start_unload (current_profiler, module);
275 case MONO_PROFILE_END_UNLOAD:
276 if (module_end_unload)
277 module_end_unload (current_profiler, module);
280 g_assert_not_reached ();
285 mono_profiler_module_loaded (MonoImage *module, int result)
287 if ((mono_profiler_events & MONO_PROFILE_MODULE_EVENTS) && module_end_load)
288 module_end_load (current_profiler, module, result);
292 mono_profiler_class_event (MonoClass *klass, int code)
294 if (!(mono_profiler_events & MONO_PROFILE_CLASS_EVENTS))
298 case MONO_PROFILE_START_LOAD:
299 if (class_start_load)
300 class_start_load (current_profiler, klass);
302 case MONO_PROFILE_START_UNLOAD:
303 if (class_start_unload)
304 class_start_unload (current_profiler, klass);
306 case MONO_PROFILE_END_UNLOAD:
307 if (class_end_unload)
308 class_end_unload (current_profiler, klass);
311 g_assert_not_reached ();
316 mono_profiler_class_loaded (MonoClass *klass, int result)
318 if ((mono_profiler_events & MONO_PROFILE_CLASS_EVENTS) && class_end_load)
319 class_end_load (current_profiler, klass, result);
323 mono_profiler_appdomain_event (MonoDomain *domain, int code)
325 if (!(mono_profiler_events & MONO_PROFILE_APPDOMAIN_EVENTS))
329 case MONO_PROFILE_START_LOAD:
330 if (domain_start_load)
331 domain_start_load (current_profiler, domain);
333 case MONO_PROFILE_START_UNLOAD:
334 if (domain_start_unload)
335 domain_start_unload (current_profiler, domain);
337 case MONO_PROFILE_END_UNLOAD:
338 if (domain_end_unload)
339 domain_end_unload (current_profiler, domain);
342 g_assert_not_reached ();
347 mono_profiler_appdomain_loaded (MonoDomain *domain, int result)
349 if ((mono_profiler_events & MONO_PROFILE_APPDOMAIN_EVENTS) && domain_end_load)
350 domain_end_load (current_profiler, domain, result);
354 mono_profiler_shutdown (void)
356 if (current_profiler && shutdown_callback)
357 shutdown_callback (current_profiler);
360 static GHashTable *coverage_hash = NULL;
362 MonoProfileCoverageInfo*
363 mono_profiler_coverage_alloc (MonoMethod *method, int entries)
365 MonoProfileCoverageInfo *res;
367 if (coverage_filter_cb)
368 if (! (*coverage_filter_cb) (current_profiler, method))
371 EnterCriticalSection (&profiler_coverage_mutex);
373 coverage_hash = g_hash_table_new (NULL, NULL);
375 res = g_malloc0 (sizeof (MonoProfileCoverageInfo) + sizeof (void*) * 2 * entries);
377 res->entries = entries;
379 g_hash_table_insert (coverage_hash, method, res);
380 LeaveCriticalSection (&profiler_coverage_mutex);
385 /* safe only when the method antive code has been unloaded */
387 mono_profiler_coverage_free (MonoMethod *method)
389 MonoProfileCoverageInfo* info;
391 EnterCriticalSection (&profiler_coverage_mutex);
392 if (!coverage_hash) {
393 LeaveCriticalSection (&profiler_coverage_mutex);
397 info = g_hash_table_lookup (coverage_hash, method);
400 g_hash_table_remove (coverage_hash, method);
402 LeaveCriticalSection (&profiler_coverage_mutex);
406 mono_profiler_coverage_get (MonoProfiler *prof, MonoMethod *method, MonoProfileCoverageFunc func)
408 MonoProfileCoverageInfo* info;
411 unsigned char *start, *end, *cil_code;
412 MonoMethodHeader *header;
413 MonoProfileCoverageEntry entry;
415 EnterCriticalSection (&profiler_coverage_mutex);
416 info = g_hash_table_lookup (coverage_hash, method);
417 LeaveCriticalSection (&profiler_coverage_mutex);
422 header = mono_method_get_header (method);
423 start = (unsigned char*)header->code;
424 end = start + header->code_size;
425 for (i = 0; i < info->entries; ++i) {
426 cil_code = info->data [i].cil_code;
427 if (cil_code && cil_code >= start && cil_code < end) {
428 offset = cil_code - start;
429 entry.iloffset = offset;
430 entry.method = method;
431 entry.counter = info->data [i].count;
432 /* the debug interface doesn't support column info, sigh */
434 entry.filename = mono_debug_source_location_from_il_offset (method, offset, &line);
442 #ifndef DISABLE_PROFILER
444 * Small profiler extracted from mint: we should move it in a loadable module
445 * and improve it to do graphs and more accurate timestamping with rdtsc.
449 #define USE_WIN32COUNTER 0
453 unsigned int lows, highs, lowe, highe;
456 #define rdtsc(low,high) \
457 __asm__ __volatile__("rdtsc" : "=a" (low), "=d" (high))
462 rdtsc_elapsed (MonoRdtscTimer *t)
464 unsigned long long diff;
465 unsigned int highe = t->highe;
466 if (t->lowe < t->lows)
468 diff = (((unsigned long long) highe - t->highs) << 32) + (t->lowe - t->lows);
469 return ((double)diff / freq) / 1000000; /* have to return the result in seconds */
480 if (!(cpuinfo = fopen ("/proc/cpuinfo", "r")))
482 while (fgets (buf, sizeof(buf), cpuinfo)) {
483 if (sscanf (buf, "cpu MHz : %f", &val) == 1) {
484 /*printf ("got mh: %f\n", val);*/
487 if (strncmp (buf, "flags", 5) == 0) {
488 if (strstr (buf, "tsc")) {
490 /*printf ("have tsc\n");*/
495 return have_flag? have_freq: 0;
498 #define MONO_TIMER_STARTUP \
499 if (!(freq = have_rdtsc ())) g_error ("Compiled with TSC support, but none found");
500 #define MONO_TIMER_TYPE MonoRdtscTimer
501 #define MONO_TIMER_INIT(t)
502 #define MONO_TIMER_DESTROY(t)
503 #define MONO_TIMER_START(t) rdtsc ((t).lows, (t).highs);
504 #define MONO_TIMER_STOP(t) rdtsc ((t).lowe, (t).highe);
505 #define MONO_TIMER_ELAPSED(t) rdtsc_elapsed (&(t))
507 #elif USE_WIN32COUNTER
511 LARGE_INTEGER start, stop;
517 win32_elapsed (MonoWin32Timer *t)
519 LONGLONG diff = t->stop.QuadPart - t->start.QuadPart;
520 return ((double)diff / freq) / 1000000; /* have to return the result in seconds */
524 have_win32counter (void) {
527 if (!QueryPerformanceFrequency (&f))
532 #define MONO_TIMER_STARTUP \
533 if (!(freq = have_win32counter ())) g_error ("Compiled with Win32 counter support, but none found");
534 #define MONO_TIMER_TYPE MonoWin32Timer
535 #define MONO_TIMER_INIT(t)
536 #define MONO_TIMER_DESTROY(t)
537 #define MONO_TIMER_START(t) QueryPerformanceCounter (&(t).start)
538 #define MONO_TIMER_STOP(t) QueryPerformanceCounter (&(t).stop)
539 #define MONO_TIMER_ELAPSED(t) win32_elapsed (&(t))
544 GTimeVal start, stop;
548 timeval_elapsed (MonoGLibTimer *t)
550 if (t->start.tv_usec > t->stop.tv_usec) {
551 t->stop.tv_usec += G_USEC_PER_SEC;
554 return (t->stop.tv_sec - t->start.tv_sec)
555 + ((double)(t->stop.tv_usec - t->start.tv_usec))/ G_USEC_PER_SEC;
558 #define MONO_TIMER_STARTUP
559 #define MONO_TIMER_TYPE MonoGLibTimer
560 #define MONO_TIMER_INIT(t)
561 #define MONO_TIMER_DESTROY(t)
562 #define MONO_TIMER_START(t) g_get_current_time (&(t).start)
563 #define MONO_TIMER_STOP(t) g_get_current_time (&(t).stop)
564 #define MONO_TIMER_ELAPSED(t) timeval_elapsed (&(t))
567 typedef struct _AllocInfo AllocInfo;
568 typedef struct _CallerInfo CallerInfo;
569 typedef struct _LastCallerInfo LastCallerInfo;
571 struct _MonoProfiler {
573 MonoMemPool *mempool;
574 /* info about JIT time */
575 MONO_TIMER_TYPE jit_timer;
578 MonoMethod *max_jit_method;
583 /* chain of callers for the current thread */
584 LastCallerInfo *callers;
585 /* LastCallerInfo nodes for faster allocation */
586 LastCallerInfo *cstorage;
593 AllocInfo *alloc_info;
594 CallerInfo *caller_info;
597 typedef struct _MethodCallProfile MethodCallProfile;
599 struct _MethodCallProfile {
600 MethodCallProfile *next;
601 MONO_TIMER_TYPE timer;
618 struct _LastCallerInfo {
619 LastCallerInfo *next;
621 MONO_TIMER_TYPE timer;
625 create_profiler (void)
627 MonoProfiler *prof = g_new0 (MonoProfiler, 1);
629 prof->methods = g_hash_table_new (NULL, NULL);
630 MONO_TIMER_INIT (prof->jit_timer);
631 prof->mempool = mono_mempool_new ();
636 #ifdef HAVE_KW_THREAD
637 static __thread MonoProfiler * tls_profiler;
638 # define GET_PROFILER() tls_profiler
639 # define SET_PROFILER(x) tls_profiler = (x)
640 # define ALLOC_PROFILER() /* nop */
642 static guint32 profiler_thread_id = -1;
643 # define GET_PROFILER() ((MonoProfiler *)TlsGetValue (profiler_thread_id))
644 # define SET_PROFILER(x) TlsSetValue (profiler_thread_id, x);
645 # define ALLOC_PROFILER() profiler_thread_id = TlsAlloc ()
648 #define GET_THREAD_PROF(prof) do { \
649 MonoProfiler *_tprofiler = GET_PROFILER (); \
651 _tprofiler = create_profiler (); \
652 prof->per_thread = g_slist_prepend (prof->per_thread, _tprofiler); \
653 SET_PROFILER (_tprofiler); \
658 /* thread unsafe but faster variant */
659 #define GET_THREAD_PROF(prof)
663 compare_profile (MethodProfile *profa, MethodProfile *profb)
665 return (gint)((profb->total - profa->total)*1000);
669 build_profile (MonoMethod *m, MethodProfile *prof, GList **funcs)
672 *funcs = g_list_insert_sorted (*funcs, prof, (GCompareFunc)compare_profile);
676 method_get_name (MonoMethod* method)
680 sig = mono_signature_get_desc (method->signature, FALSE);
681 res = g_strdup_printf ("%s.%s::%s(%s)", method->klass->name_space, method->klass->name,
687 static void output_callers (MethodProfile *p);
690 output_profile (GList *funcs)
695 guint64 total_calls = 0;
698 g_print ("Time(ms) Count P/call(ms) Method name\n");
699 for (tmp = funcs; tmp; tmp = tmp->next) {
701 total_calls += p->count;
702 if (!(gint)(p->total*1000))
704 m = method_get_name (p->method);
705 printf ("########################\n");
706 printf ("% 8.3f ", (double) (p->total * 1000));
707 printf ("%7llu ", p->count);
708 printf ("% 8.3f ", (double) (p->total * 1000)/(double)p->count);
715 printf ("Total number of calls: %lld\n", total_calls);
724 compare_newobj_profile (NewobjProfile *profa, NewobjProfile *profb)
726 return (gint)profb->count - (gint)profa->count;
730 build_newobj_profile (MonoClass *class, MethodProfile *mprof, GList **funcs)
732 NewobjProfile *prof = g_new (NewobjProfile, 1);
737 /* we use the total amount of memory to sort */
738 for (tmp = mprof->alloc_info; tmp; tmp = tmp->next)
741 *funcs = g_list_insert_sorted (*funcs, prof, (GCompareFunc)compare_newobj_profile);
745 compare_caller (CallerInfo *a, CallerInfo *b)
747 return b->count - a->count;
751 compare_alloc (AllocInfo *a, AllocInfo *b)
753 return b->mem - a->mem;
757 sort_alloc_list (AllocInfo *ai)
761 for (tmp = ai; tmp; tmp = tmp->next) {
762 l = g_slist_insert_sorted (l, tmp, (GCompareFunc)compare_alloc);
768 sort_caller_list (CallerInfo *ai)
772 for (tmp = ai; tmp; tmp = tmp->next) {
773 l = g_slist_insert_sorted (l, tmp, (GCompareFunc)compare_caller);
779 output_callers (MethodProfile *p) {
780 guint total_callers, percent;
781 GSList *sorted, *tmps;
785 g_print (" Callers (with count) that contribute at least for 1%%:\n");
787 for (cinfo = p->caller_info; cinfo; cinfo = cinfo->next) {
788 total_callers += cinfo->count;
790 sorted = sort_caller_list (p->caller_info);
791 for (tmps = sorted; tmps; tmps = tmps->next) {
793 percent = (cinfo->count * 100)/total_callers;
796 m = method_get_name (cinfo->caller);
797 g_print (" %8d % 3d %% %s\n", cinfo->count, percent, m);
803 output_newobj_profile (GList *proflist)
814 GSList *sorted, *tmps;
816 g_print ("\nAllocation profiler\n");
819 g_print ("%-9s %s\n", "Total mem", "Method");
820 for (tmp = proflist; tmp; tmp = tmp->next) {
823 if (p->count < 50000)
826 m = method_get_name (mp->method);
827 g_print ("########################\n%8d KB %s\n", p->count / 1024, m);
829 sorted = sort_alloc_list (mp->alloc_info);
830 for (tmps = sorted; tmps; tmps = tmps->next) {
832 if (ainfo->mem < 50000)
834 klass = ainfo->klass;
837 klass = klass->element_class;
841 g_snprintf (buf, sizeof (buf), "%s.%s%s",
842 klass->name_space, klass->name, isarray);
843 g_print (" %8d KB %8d %-48s\n", ainfo->mem / 1024, ainfo->count, buf);
848 g_print ("Total memory allocated: %d KB\n", total / 1024);
852 merge_methods (MonoMethod *method, MethodProfile *profile, MonoProfiler *prof)
854 MethodProfile *mprof;
855 AllocInfo *talloc_info, *alloc_info;
856 CallerInfo *tcaller_info, *caller_info;
858 mprof = g_hash_table_lookup (prof->methods, method);
860 /* the master thread didn't see this method, just transfer the info as is */
861 g_hash_table_insert (prof->methods, method, profile);
864 /* merge the info from profile into mprof */
865 mprof->count += profile->count;
866 mprof->total += profile->total;
867 /* merge alloc info */
868 for (talloc_info = profile->alloc_info; talloc_info; talloc_info = talloc_info->next) {
869 for (alloc_info = mprof->alloc_info; alloc_info; alloc_info = alloc_info->next) {
870 if (alloc_info->klass == talloc_info->klass) {
871 /* mprof already has a record for the klass, merge */
872 alloc_info->count += talloc_info->count;
873 alloc_info->mem += talloc_info->mem;
878 /* mprof didn't have the info, just copy it over */
879 alloc_info = mono_mempool_alloc0 (prof->mempool, sizeof (AllocInfo));
880 *alloc_info = *talloc_info;
881 alloc_info->next = mprof->alloc_info;
882 mprof->alloc_info = alloc_info->next;
885 /* merge callers info */
886 for (tcaller_info = profile->caller_info; tcaller_info; tcaller_info = tcaller_info->next) {
887 for (caller_info = mprof->caller_info; caller_info; caller_info = caller_info->next) {
888 if (caller_info->caller == tcaller_info->caller) {
889 /* mprof already has a record for the caller method, merge */
890 caller_info->count += tcaller_info->count;
895 /* mprof didn't have the info, just copy it over */
896 caller_info = mono_mempool_alloc0 (prof->mempool, sizeof (CallerInfo));
897 *caller_info = *tcaller_info;
898 caller_info->next = mprof->caller_info;
899 mprof->caller_info = caller_info;
905 merge_thread_data (MonoProfiler *master, MonoProfiler *tprof)
907 master->jit_time += tprof->jit_time;
908 master->methods_jitted += tprof->methods_jitted;
909 if (master->max_jit_time < tprof->max_jit_time) {
910 master->max_jit_time = tprof->max_jit_time;
911 master->max_jit_method = tprof->max_jit_method;
914 g_hash_table_foreach (tprof->methods, (GHFunc)merge_methods, master);
918 simple_method_enter (MonoProfiler *prof, MonoMethod *method)
920 MethodProfile *profile_info;
921 LastCallerInfo *callinfo;
922 GET_THREAD_PROF (prof);
923 /*g_print ("enter %p %s::%s in %d (%p)\n", method, method->klass->name, method->name, GetCurrentThreadId (), prof);*/
924 if (!(profile_info = g_hash_table_lookup (prof->methods, method))) {
925 profile_info = mono_mempool_alloc0 (prof->mempool, sizeof (MethodProfile));
926 MONO_TIMER_INIT (profile_info->u.timer);
927 g_hash_table_insert (prof->methods, method, profile_info);
929 profile_info->count++;
932 MonoMethod *caller = prof->callers->method;
933 for (cinfo = profile_info->caller_info; cinfo; cinfo = cinfo->next) {
934 if (cinfo->caller == caller)
938 cinfo = mono_mempool_alloc0 (prof->mempool, sizeof (CallerInfo));
939 cinfo->caller = caller;
940 cinfo->next = profile_info->caller_info;
941 profile_info->caller_info = cinfo;
945 if (!(callinfo = prof->cstorage)) {
946 callinfo = mono_mempool_alloc (prof->mempool, sizeof (LastCallerInfo));
947 MONO_TIMER_INIT (callinfo->timer);
949 prof->cstorage = prof->cstorage->next;
951 callinfo->method = method;
952 callinfo->next = prof->callers;
953 prof->callers = callinfo;
954 MONO_TIMER_START (callinfo->timer);
958 simple_method_leave (MonoProfiler *prof, MonoMethod *method)
960 MethodProfile *profile_info;
961 LastCallerInfo *callinfo, *newcallinfo = NULL;
963 GET_THREAD_PROF (prof);
964 /*g_print ("leave %p %s::%s in %d (%p)\n", method, method->klass->name, method->name, GetCurrentThreadId (), prof);*/
965 callinfo = prof->callers;
966 /* should really not happen, but we don't catch exceptions events, yet ... */
968 MONO_TIMER_STOP (callinfo->timer);
969 profile_info = g_hash_table_lookup (prof->methods, callinfo->method);
971 profile_info->total += MONO_TIMER_ELAPSED (callinfo->timer);
972 newcallinfo = callinfo->next;
973 callinfo->next = prof->cstorage;
974 prof->cstorage = callinfo;
975 if (callinfo->method == method)
977 callinfo = newcallinfo;
979 prof->callers = newcallinfo;
983 simple_allocation (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
985 MethodProfile *profile_info;
988 GET_THREAD_PROF (prof);
990 MonoMethod *caller = prof->callers->method;
992 /* Otherwise all allocations are attributed to icall_wrapper_mono_object_new */
993 if (caller->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
994 caller = prof->callers->next->method;
996 if (!(profile_info = g_hash_table_lookup (prof->methods, caller)))
997 g_assert_not_reached ();
999 return; /* fine for now */
1002 for (tmp = profile_info->alloc_info; tmp; tmp = tmp->next) {
1003 if (tmp->klass == klass)
1007 tmp = mono_mempool_alloc0 (prof->mempool, sizeof (AllocInfo));
1009 tmp->next = profile_info->alloc_info;
1010 profile_info->alloc_info = tmp;
1013 tmp->mem += mono_object_get_size (obj);
1017 simple_method_jit (MonoProfiler *prof, MonoMethod *method)
1019 GET_THREAD_PROF (prof);
1020 prof->methods_jitted++;
1021 MONO_TIMER_START (prof->jit_timer);
1025 simple_method_end_jit (MonoProfiler *prof, MonoMethod *method, int result)
1028 GET_THREAD_PROF (prof);
1029 MONO_TIMER_STOP (prof->jit_timer);
1030 jtime = MONO_TIMER_ELAPSED (prof->jit_timer);
1031 prof->jit_time += jtime;
1032 if (jtime > prof->max_jit_time) {
1033 prof->max_jit_time = jtime;
1034 prof->max_jit_method = method;
1038 /* about 10 minutes of samples */
1039 #define MAX_PROF_SAMPLES (1000*60*10)
1040 static int prof_counts = 0;
1041 static int prof_ucounts = 0;
1042 static gpointer* prof_addresses = NULL;
1043 static GHashTable *prof_table = NULL;
1046 simple_stat_hit (MonoProfiler *prof, guchar *ip, void *context)
1050 if (prof_counts >= MAX_PROF_SAMPLES)
1052 pos = InterlockedIncrement (&prof_counts);
1053 prof_addresses [pos - 1] = ip;
1057 compare_methods_prof (gconstpointer a, gconstpointer b)
1059 int ca = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, a));
1060 int cb = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, b));
1065 prof_foreach (char *method, gpointer c, gpointer data)
1067 GList **list = data;
1068 *list = g_list_insert_sorted (*list, method, compare_methods_prof);
1071 typedef struct Addr2LineData Addr2LineData;
1073 struct Addr2LineData {
1074 Addr2LineData *next;
1081 static Addr2LineData *addr2line_pipes = NULL;
1084 try_addr2line (const char* binary, gpointer ip)
1088 Addr2LineData *addr2line;
1090 for (addr2line = addr2line_pipes; addr2line; addr2line = addr2line->next) {
1091 if (strcmp (binary, addr2line->binary) == 0)
1095 const char *addr_argv[] = {"addr2line", "-f", "-e", binary, NULL};
1098 if (!g_spawn_async_with_pipes (NULL, (char**)addr_argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
1099 &child_pid, &ch_in, &ch_out, NULL, NULL)) {
1100 return g_strdup (binary);
1102 addr2line = g_new0 (Addr2LineData, 1);
1103 addr2line->child_pid = child_pid;
1104 addr2line->binary = g_strdup (binary);
1105 addr2line->pipein = fdopen (ch_in, "w");
1106 addr2line->pipeout = fdopen (ch_out, "r");
1107 addr2line->next = addr2line_pipes;
1108 addr2line_pipes = addr2line;
1110 fprintf (addr2line->pipein, "%p\n", ip);
1111 fflush (addr2line->pipein);
1112 /* we first get the func name and then file:lineno in a second line */
1113 if (fgets (buf, sizeof (buf), addr2line->pipeout) && buf [0] != '?') {
1114 char *end = strchr (buf, '\n');
1117 res = g_strdup_printf ("%s(%s", binary, buf);
1118 /* discard the filename/line info */
1119 fgets (buf, sizeof (buf), addr2line->pipeout);
1121 res = g_strdup (binary);
1127 stat_prof_report (void)
1130 int count = prof_counts;
1134 GList *tmp, *sorted = NULL;
1137 for (i = 0; i < count; ++i) {
1138 ip = prof_addresses [i];
1139 ji = mono_jit_info_table_find (mono_domain_get (), ip);
1141 mn = mono_method_full_name (ji->method, TRUE);
1143 #ifdef HAVE_BACKTRACE_SYMBOLS
1148 names = backtrace_symbols (&ip, 1);
1149 send = strchr (names [0], '+');
1156 send = strchr (names [0], '[');
1159 if (no_func && names [0][0]) {
1160 char *endp = strchr (names [0], 0);
1161 while (--endp >= names [0] && g_ascii_isspace (*endp))
1163 mn = try_addr2line (names [0], ip);
1165 mn = g_strdup (names [0]);
1170 mn = g_strdup_printf ("unmanaged [%p]", ip);
1173 c = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, mn));
1175 g_hash_table_insert (prof_table, mn, GUINT_TO_POINTER (c));
1179 g_print ("prof counts: total/unmanaged: %d/%d\n", prof_counts, prof_ucounts);
1180 g_hash_table_foreach (prof_table, (GHFunc)prof_foreach, &sorted);
1181 for (tmp = sorted; tmp; tmp = tmp->next) {
1183 c = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, tmp->data));
1184 perc = c*100.0/count;
1185 g_print ("%7d\t%5.2f %% %s\n", c, perc, (char*)tmp->data);
1187 g_list_free (sorted);
1191 simple_appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
1193 /* FIXME: we should actually record partial data for each domain,
1194 * since the ip->ji->method mappings are going away at domain unload time.
1196 if (domain == mono_get_root_domain ())
1197 stat_prof_report ();
1201 simple_shutdown (MonoProfiler *prof)
1203 GList *profile = NULL;
1204 MonoProfiler *tprof;
1208 for (tmp = prof->per_thread; tmp; tmp = tmp->next) {
1210 merge_thread_data (prof, tprof);
1213 printf("Total time spent compiling %d methods (sec): %.4g\n", prof->methods_jitted, prof->jit_time);
1214 if (prof->max_jit_method) {
1215 str = method_get_name (prof->max_jit_method);
1216 printf("Slowest method to compile (sec): %.4g: %s\n", prof->max_jit_time, str);
1219 g_hash_table_foreach (prof->methods, (GHFunc)build_profile, &profile);
1220 output_profile (profile);
1221 g_list_free (profile);
1224 g_hash_table_foreach (prof->methods, (GHFunc)build_newobj_profile, &profile);
1225 output_newobj_profile (profile);
1226 g_list_free (profile);
1228 g_free (prof_addresses);
1229 g_hash_table_destroy (prof_table);
1233 mono_profiler_install_simple (const char *desc)
1236 gchar **args, **ptr;
1237 MonoProfileFlags flags = MONO_PROFILE_JIT_COMPILATION;
1243 if (strstr (desc, ":"))
1244 desc = strstr (desc, ":") + 1;
1246 desc = "alloc,time";
1247 args = g_strsplit (desc, ",", -1);
1249 for (ptr = args; ptr && *ptr; ptr++) {
1250 const char *arg = *ptr;
1252 if (!strcmp (arg, "time"))
1253 flags |= MONO_PROFILE_ENTER_LEAVE;
1254 else if (!strcmp (arg, "alloc"))
1255 flags |= MONO_PROFILE_ALLOCATIONS;
1256 else if (!strcmp (arg, "stat"))
1257 flags |= MONO_PROFILE_STATISTICAL | MONO_PROFILE_APPDOMAIN_EVENTS;
1259 fprintf (stderr, "profiler : Unknown argument '%s'.\n", arg);
1265 prof = create_profiler ();
1267 SET_PROFILER (prof);
1269 /* statistical profiler data */
1270 prof_addresses = g_new0 (gpointer, MAX_PROF_SAMPLES);
1271 prof_table = g_hash_table_new (g_str_hash, g_str_equal);
1273 mono_profiler_install (prof, simple_shutdown);
1274 mono_profiler_install_enter_leave (simple_method_enter, simple_method_leave);
1275 mono_profiler_install_jit_compile (simple_method_jit, simple_method_end_jit);
1276 mono_profiler_install_allocation (simple_allocation);
1277 mono_profiler_install_appdomain (NULL, NULL, simple_appdomain_unload, NULL);
1278 mono_profiler_install_statistical (simple_stat_hit);
1279 mono_profiler_set_events (flags);
1282 #endif /* DISABLE_PROFILER */
1284 typedef void (*ProfilerInitializer) (const char*);
1285 #define INITIALIZER_NAME "mono_profiler_startup"
1288 mono_profiler_load (const char *desc)
1290 #ifndef DISABLE_PROFILER
1291 if (!desc || (strcmp ("default", desc) == 0) || (strncmp (desc, "default:", 8) == 0)) {
1292 mono_profiler_install_simple (desc);
1302 const char* col = strchr (desc, ':');
1307 mname = g_memdup (desc, col - desc);
1308 mname [col - desc] = 0;
1310 mname = g_strdup (desc);
1312 libname = g_strdup_printf ("mono-profiler-%s", mname);
1313 path = g_module_build_path (NULL, libname);
1314 pmodule = g_module_open (path, G_MODULE_BIND_LAZY);
1316 ProfilerInitializer func;
1317 if (!g_module_symbol (pmodule, INITIALIZER_NAME, (gpointer *)&func)) {
1318 g_warning ("Cannot find initializer function %s in profiler module: %s", INITIALIZER_NAME, libname);
1323 g_warning ("Error loading profiler module '%s': %s", libname, g_module_error ());