2 * profiler.c: Profiler interface for Mono
5 * Paolo Molaro (lupus@ximian.com)
7 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
8 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
12 #include "mono/metadata/profiler-private.h"
13 #include "mono/metadata/debug-helpers.h"
14 #include "mono/metadata/mono-debug.h"
15 #include "mono/metadata/debug-mono-symfile.h"
16 #include "mono/metadata/metadata-internals.h"
17 #include "mono/metadata/class-internals.h"
18 #include "mono/metadata/domain-internals.h"
19 #include "mono/metadata/gc-internal.h"
20 #include "mono/io-layer/io-layer.h"
21 #include "mono/utils/mono-dl.h"
26 #ifdef HAVE_SYS_TIME_H
29 #ifdef HAVE_BACKTRACE_SYMBOLS
33 typedef struct _ProfilerDesc ProfilerDesc;
34 struct _ProfilerDesc {
36 MonoProfiler *profiler;
37 MonoProfileFlags events;
39 MonoProfileAppDomainFunc domain_start_load;
40 MonoProfileAppDomainResult domain_end_load;
41 MonoProfileAppDomainFunc domain_start_unload;
42 MonoProfileAppDomainFunc domain_end_unload;
44 MonoProfileAssemblyFunc assembly_start_load;
45 MonoProfileAssemblyResult assembly_end_load;
46 MonoProfileAssemblyFunc assembly_start_unload;
47 MonoProfileAssemblyFunc assembly_end_unload;
49 MonoProfileModuleFunc module_start_load;
50 MonoProfileModuleResult module_end_load;
51 MonoProfileModuleFunc module_start_unload;
52 MonoProfileModuleFunc module_end_unload;
54 MonoProfileClassFunc class_start_load;
55 MonoProfileClassResult class_end_load;
56 MonoProfileClassFunc class_start_unload;
57 MonoProfileClassFunc class_end_unload;
59 MonoProfileMethodFunc jit_start;
60 MonoProfileMethodResult jit_end;
61 MonoProfileJitResult jit_end2;
62 MonoProfileMethodFunc method_free;
63 MonoProfileMethodFunc method_start_invoke;
64 MonoProfileMethodFunc method_end_invoke;
65 MonoProfileMethodResult man_unman_transition;
66 MonoProfileAllocFunc allocation_cb;
67 MonoProfileMonitorFunc monitor_event_cb;
68 MonoProfileStatFunc statistical_cb;
69 MonoProfileStatCallChainFunc statistical_call_chain_cb;
70 int statistical_call_chain_depth;
71 MonoProfilerCallChainStrategy statistical_call_chain_strategy;
72 MonoProfileMethodFunc method_enter;
73 MonoProfileMethodFunc method_leave;
75 MonoProfileExceptionFunc exception_throw_cb;
76 MonoProfileMethodFunc exception_method_leave_cb;
77 MonoProfileExceptionClauseFunc exception_clause_cb;
79 MonoProfileIomapFunc iomap_cb;
81 MonoProfileThreadFunc thread_start;
82 MonoProfileThreadFunc thread_end;
84 MonoProfileCoverageFilterFunc coverage_filter_cb;
86 MonoProfileFunc shutdown_callback;
88 MonoProfileGCFunc gc_event;
89 MonoProfileGCResizeFunc gc_heap_resize;
90 MonoProfileGCMoveFunc gc_moves;
92 MonoProfileFunc runtime_initialized_event;
94 MonoProfilerCodeChunkNew code_chunk_new;
95 MonoProfilerCodeChunkDestroy code_chunk_destroy;
96 MonoProfilerCodeBufferNew code_buffer_new;
99 static ProfilerDesc *prof_list = NULL;
101 #define mono_profiler_coverage_lock() EnterCriticalSection (&profiler_coverage_mutex)
102 #define mono_profiler_coverage_unlock() LeaveCriticalSection (&profiler_coverage_mutex)
103 static CRITICAL_SECTION profiler_coverage_mutex;
105 /* this is directly accessible to other mono libs.
106 * It is the ORed value of all the profiler's events.
108 MonoProfileFlags mono_profiler_events;
111 * mono_profiler_install:
112 * @prof: a MonoProfiler structure pointer, or a pointer to a derived structure.
113 * @callback: the function to invoke at shutdown
115 * Use mono_profiler_install to activate profiling in the Mono runtime.
116 * Typically developers of new profilers will create a new structure whose
117 * first field is a MonoProfiler and put any extra information that they need
118 * to access from the various profiling callbacks there.
122 mono_profiler_install (MonoProfiler *prof, MonoProfileFunc callback)
124 ProfilerDesc *desc = g_new0 (ProfilerDesc, 1);
126 InitializeCriticalSection (&profiler_coverage_mutex);
127 desc->profiler = prof;
128 desc->shutdown_callback = callback;
129 desc->next = prof_list;
134 * mono_profiler_set_events:
135 * @events: an ORed set of values made up of MONO_PROFILER_ flags
137 * The events descriped in the @events argument is a set of flags
138 * that represent which profiling events must be triggered. For
139 * example if you have registered a set of methods for tracking
140 * JIT compilation start and end with mono_profiler_install_jit_compile,
141 * you will want to pass the MONO_PROFILE_JIT_COMPILATION flag to
144 * You can call mono_profile_set_events more than once and you can
145 * do this at runtime to modify which methods are invoked.
148 mono_profiler_set_events (MonoProfileFlags events)
151 MonoProfileFlags value = 0;
153 prof_list->events = events;
154 for (prof = prof_list; prof; prof = prof->next)
155 value |= prof->events;
156 mono_profiler_events = value;
160 * mono_profiler_get_events:
162 * Returns a list of active events that will be intercepted.
165 mono_profiler_get_events (void)
167 return mono_profiler_events;
171 * mono_profiler_install_enter_leave:
172 * @enter: the routine to be called on each method entry
173 * @fleave: the routine to be called each time a method returns
175 * Use this routine to install routines that will be called everytime
176 * a method enters and leaves. The routines will receive as an argument
177 * the MonoMethod representing the method that is entering or leaving.
180 mono_profiler_install_enter_leave (MonoProfileMethodFunc enter, MonoProfileMethodFunc fleave)
184 prof_list->method_enter = enter;
185 prof_list->method_leave = fleave;
189 * mono_profiler_install_jit_compile:
190 * @start: the routine to be called when the JIT process starts.
191 * @end: the routine to be called when the JIT process ends.
193 * Use this routine to install routines that will be called when JIT
194 * compilation of a method starts and completes.
197 mono_profiler_install_jit_compile (MonoProfileMethodFunc start, MonoProfileMethodResult end)
201 prof_list->jit_start = start;
202 prof_list->jit_end = end;
206 mono_profiler_install_jit_end (MonoProfileJitResult end)
210 prof_list->jit_end2 = end;
214 mono_profiler_install_method_free (MonoProfileMethodFunc callback)
218 prof_list->method_free = callback;
222 mono_profiler_install_method_invoke (MonoProfileMethodFunc start, MonoProfileMethodFunc end)
226 prof_list->method_start_invoke = start;
227 prof_list->method_end_invoke = end;
231 mono_profiler_install_thread (MonoProfileThreadFunc start, MonoProfileThreadFunc end)
235 prof_list->thread_start = start;
236 prof_list->thread_end = end;
240 mono_profiler_install_transition (MonoProfileMethodResult callback)
244 prof_list->man_unman_transition = callback;
248 mono_profiler_install_allocation (MonoProfileAllocFunc callback)
252 prof_list->allocation_cb = callback;
256 mono_profiler_install_monitor (MonoProfileMonitorFunc callback)
260 prof_list->monitor_event_cb = callback;
264 mono_profiler_install_statistical (MonoProfileStatFunc callback)
268 prof_list->statistical_cb = callback;
272 mono_profiler_install_statistical_call_chain (MonoProfileStatCallChainFunc callback, int call_chain_depth, MonoProfilerCallChainStrategy call_chain_strategy) {
275 if (call_chain_depth > MONO_PROFILER_MAX_STAT_CALL_CHAIN_DEPTH) {
276 call_chain_depth = MONO_PROFILER_MAX_STAT_CALL_CHAIN_DEPTH;
278 if ((call_chain_strategy >= MONO_PROFILER_CALL_CHAIN_INVALID) || (call_chain_strategy < MONO_PROFILER_CALL_CHAIN_NONE)) {
279 call_chain_strategy = MONO_PROFILER_CALL_CHAIN_NONE;
281 prof_list->statistical_call_chain_cb = callback;
282 prof_list->statistical_call_chain_depth = call_chain_depth;
283 prof_list->statistical_call_chain_strategy = call_chain_strategy;
287 mono_profiler_stat_get_call_chain_depth (void) {
288 if (prof_list && prof_list->statistical_call_chain_cb != NULL) {
289 return prof_list->statistical_call_chain_depth;
295 MonoProfilerCallChainStrategy
296 mono_profiler_stat_get_call_chain_strategy (void) {
297 if (prof_list && prof_list->statistical_call_chain_cb != NULL) {
298 return prof_list->statistical_call_chain_strategy;
300 return MONO_PROFILER_CALL_CHAIN_NONE;
304 void mono_profiler_install_exception (MonoProfileExceptionFunc throw_callback, MonoProfileMethodFunc exc_method_leave, MonoProfileExceptionClauseFunc clause_callback)
308 prof_list->exception_throw_cb = throw_callback;
309 prof_list->exception_method_leave_cb = exc_method_leave;
310 prof_list->exception_clause_cb = clause_callback;
314 mono_profiler_install_coverage_filter (MonoProfileCoverageFilterFunc callback)
318 prof_list->coverage_filter_cb = callback;
322 mono_profiler_install_appdomain (MonoProfileAppDomainFunc start_load, MonoProfileAppDomainResult end_load,
323 MonoProfileAppDomainFunc start_unload, MonoProfileAppDomainFunc end_unload)
328 prof_list->domain_start_load = start_load;
329 prof_list->domain_end_load = end_load;
330 prof_list->domain_start_unload = start_unload;
331 prof_list->domain_end_unload = end_unload;
335 mono_profiler_install_assembly (MonoProfileAssemblyFunc start_load, MonoProfileAssemblyResult end_load,
336 MonoProfileAssemblyFunc start_unload, MonoProfileAssemblyFunc end_unload)
340 prof_list->assembly_start_load = start_load;
341 prof_list->assembly_end_load = end_load;
342 prof_list->assembly_start_unload = start_unload;
343 prof_list->assembly_end_unload = end_unload;
347 mono_profiler_install_module (MonoProfileModuleFunc start_load, MonoProfileModuleResult end_load,
348 MonoProfileModuleFunc start_unload, MonoProfileModuleFunc end_unload)
352 prof_list->module_start_load = start_load;
353 prof_list->module_end_load = end_load;
354 prof_list->module_start_unload = start_unload;
355 prof_list->module_end_unload = end_unload;
359 mono_profiler_install_class (MonoProfileClassFunc start_load, MonoProfileClassResult end_load,
360 MonoProfileClassFunc start_unload, MonoProfileClassFunc end_unload)
364 prof_list->class_start_load = start_load;
365 prof_list->class_end_load = end_load;
366 prof_list->class_start_unload = start_unload;
367 prof_list->class_end_unload = end_unload;
371 mono_profiler_method_enter (MonoMethod *method)
374 for (prof = prof_list; prof; prof = prof->next) {
375 if ((prof->events & MONO_PROFILE_ENTER_LEAVE) && prof->method_enter)
376 prof->method_enter (prof->profiler, method);
381 mono_profiler_method_leave (MonoMethod *method)
384 for (prof = prof_list; prof; prof = prof->next) {
385 if ((prof->events & MONO_PROFILE_ENTER_LEAVE) && prof->method_leave)
386 prof->method_leave (prof->profiler, method);
391 mono_profiler_method_jit (MonoMethod *method)
394 for (prof = prof_list; prof; prof = prof->next) {
395 if ((prof->events & MONO_PROFILE_JIT_COMPILATION) && prof->jit_start)
396 prof->jit_start (prof->profiler, method);
401 mono_profiler_method_end_jit (MonoMethod *method, MonoJitInfo* jinfo, int result)
404 for (prof = prof_list; prof; prof = prof->next) {
405 if ((prof->events & MONO_PROFILE_JIT_COMPILATION)) {
407 prof->jit_end (prof->profiler, method, result);
409 prof->jit_end2 (prof->profiler, method, jinfo, result);
415 mono_profiler_method_free (MonoMethod *method)
418 for (prof = prof_list; prof; prof = prof->next) {
419 if ((prof->events & MONO_PROFILE_METHOD_EVENTS) && prof->method_free)
420 prof->method_free (prof->profiler, method);
425 mono_profiler_method_start_invoke (MonoMethod *method)
428 for (prof = prof_list; prof; prof = prof->next) {
429 if ((prof->events & MONO_PROFILE_METHOD_EVENTS) && prof->method_start_invoke)
430 prof->method_start_invoke (prof->profiler, method);
435 mono_profiler_method_end_invoke (MonoMethod *method)
438 for (prof = prof_list; prof; prof = prof->next) {
439 if ((prof->events & MONO_PROFILE_METHOD_EVENTS) && prof->method_end_invoke)
440 prof->method_end_invoke (prof->profiler, method);
445 mono_profiler_code_transition (MonoMethod *method, int result)
448 for (prof = prof_list; prof; prof = prof->next) {
449 if ((prof->events & MONO_PROFILE_TRANSITIONS) && prof->man_unman_transition)
450 prof->man_unman_transition (prof->profiler, method, result);
455 mono_profiler_allocation (MonoObject *obj, MonoClass *klass)
458 for (prof = prof_list; prof; prof = prof->next) {
459 if ((prof->events & MONO_PROFILE_ALLOCATIONS) && prof->allocation_cb)
460 prof->allocation_cb (prof->profiler, obj, klass);
465 mono_profiler_monitor_event (MonoObject *obj, MonoProfilerMonitorEvent event) {
467 for (prof = prof_list; prof; prof = prof->next) {
468 if ((prof->events & MONO_PROFILE_MONITOR_EVENTS) && prof->monitor_event_cb)
469 prof->monitor_event_cb (prof->profiler, obj, event);
474 mono_profiler_stat_hit (guchar *ip, void *context)
477 for (prof = prof_list; prof; prof = prof->next) {
478 if ((prof->events & MONO_PROFILE_STATISTICAL) && prof->statistical_cb)
479 prof->statistical_cb (prof->profiler, ip, context);
484 mono_profiler_stat_call_chain (int call_chain_depth, guchar **ips, void *context)
487 for (prof = prof_list; prof; prof = prof->next) {
488 if ((prof->events & MONO_PROFILE_STATISTICAL) && prof->statistical_call_chain_cb)
489 prof->statistical_call_chain_cb (prof->profiler, call_chain_depth, ips, context);
494 mono_profiler_exception_thrown (MonoObject *exception)
497 for (prof = prof_list; prof; prof = prof->next) {
498 if ((prof->events & MONO_PROFILE_EXCEPTIONS) && prof->exception_throw_cb)
499 prof->exception_throw_cb (prof->profiler, exception);
504 mono_profiler_exception_method_leave (MonoMethod *method)
507 for (prof = prof_list; prof; prof = prof->next) {
508 if ((prof->events & MONO_PROFILE_EXCEPTIONS) && prof->exception_method_leave_cb)
509 prof->exception_method_leave_cb (prof->profiler, method);
514 mono_profiler_exception_clause_handler (MonoMethod *method, int clause_type, int clause_num)
517 for (prof = prof_list; prof; prof = prof->next) {
518 if ((prof->events & MONO_PROFILE_EXCEPTIONS) && prof->exception_clause_cb)
519 prof->exception_clause_cb (prof->profiler, method, clause_type, clause_num);
524 mono_profiler_thread_start (gsize tid)
527 for (prof = prof_list; prof; prof = prof->next) {
528 if ((prof->events & MONO_PROFILE_THREADS) && prof->thread_start)
529 prof->thread_start (prof->profiler, tid);
534 mono_profiler_thread_end (gsize tid)
537 for (prof = prof_list; prof; prof = prof->next) {
538 if ((prof->events & MONO_PROFILE_THREADS) && prof->thread_end)
539 prof->thread_end (prof->profiler, tid);
544 mono_profiler_assembly_event (MonoAssembly *assembly, int code)
547 for (prof = prof_list; prof; prof = prof->next) {
548 if (!(prof->events & MONO_PROFILE_ASSEMBLY_EVENTS))
552 case MONO_PROFILE_START_LOAD:
553 if (prof->assembly_start_load)
554 prof->assembly_start_load (prof->profiler, assembly);
556 case MONO_PROFILE_START_UNLOAD:
557 if (prof->assembly_start_unload)
558 prof->assembly_start_unload (prof->profiler, assembly);
560 case MONO_PROFILE_END_UNLOAD:
561 if (prof->assembly_end_unload)
562 prof->assembly_end_unload (prof->profiler, assembly);
565 g_assert_not_reached ();
571 mono_profiler_assembly_loaded (MonoAssembly *assembly, int result)
574 for (prof = prof_list; prof; prof = prof->next) {
575 if ((prof->events & MONO_PROFILE_ASSEMBLY_EVENTS) && prof->assembly_end_load)
576 prof->assembly_end_load (prof->profiler, assembly, result);
580 void mono_profiler_iomap (char *report, const char *pathname, const char *new_pathname)
583 for (prof = prof_list; prof; prof = prof->next) {
584 if ((prof->events & MONO_PROFILE_IOMAP_EVENTS) && prof->iomap_cb)
585 prof->iomap_cb (prof->profiler, report, pathname, new_pathname);
590 mono_profiler_module_event (MonoImage *module, int code)
593 for (prof = prof_list; prof; prof = prof->next) {
594 if (!(prof->events & MONO_PROFILE_MODULE_EVENTS))
598 case MONO_PROFILE_START_LOAD:
599 if (prof->module_start_load)
600 prof->module_start_load (prof->profiler, module);
602 case MONO_PROFILE_START_UNLOAD:
603 if (prof->module_start_unload)
604 prof->module_start_unload (prof->profiler, module);
606 case MONO_PROFILE_END_UNLOAD:
607 if (prof->module_end_unload)
608 prof->module_end_unload (prof->profiler, module);
611 g_assert_not_reached ();
617 mono_profiler_module_loaded (MonoImage *module, int result)
620 for (prof = prof_list; prof; prof = prof->next) {
621 if ((prof->events & MONO_PROFILE_MODULE_EVENTS) && prof->module_end_load)
622 prof->module_end_load (prof->profiler, module, result);
627 mono_profiler_class_event (MonoClass *klass, int code)
630 for (prof = prof_list; prof; prof = prof->next) {
631 if (!(prof->events & MONO_PROFILE_CLASS_EVENTS))
635 case MONO_PROFILE_START_LOAD:
636 if (prof->class_start_load)
637 prof->class_start_load (prof->profiler, klass);
639 case MONO_PROFILE_START_UNLOAD:
640 if (prof->class_start_unload)
641 prof->class_start_unload (prof->profiler, klass);
643 case MONO_PROFILE_END_UNLOAD:
644 if (prof->class_end_unload)
645 prof->class_end_unload (prof->profiler, klass);
648 g_assert_not_reached ();
654 mono_profiler_class_loaded (MonoClass *klass, int result)
657 for (prof = prof_list; prof; prof = prof->next) {
658 if ((prof->events & MONO_PROFILE_CLASS_EVENTS) && prof->class_end_load)
659 prof->class_end_load (prof->profiler, klass, result);
664 mono_profiler_appdomain_event (MonoDomain *domain, int code)
667 for (prof = prof_list; prof; prof = prof->next) {
668 if (!(prof->events & MONO_PROFILE_APPDOMAIN_EVENTS))
672 case MONO_PROFILE_START_LOAD:
673 if (prof->domain_start_load)
674 prof->domain_start_load (prof->profiler, domain);
676 case MONO_PROFILE_START_UNLOAD:
677 if (prof->domain_start_unload)
678 prof->domain_start_unload (prof->profiler, domain);
680 case MONO_PROFILE_END_UNLOAD:
681 if (prof->domain_end_unload)
682 prof->domain_end_unload (prof->profiler, domain);
685 g_assert_not_reached ();
691 mono_profiler_appdomain_loaded (MonoDomain *domain, int result)
694 for (prof = prof_list; prof; prof = prof->next) {
695 if ((prof->events & MONO_PROFILE_APPDOMAIN_EVENTS) && prof->domain_end_load)
696 prof->domain_end_load (prof->profiler, domain, result);
701 mono_profiler_shutdown (void)
704 for (prof = prof_list; prof; prof = prof->next) {
705 if (prof->shutdown_callback)
706 prof->shutdown_callback (prof->profiler);
709 mono_profiler_set_events (0);
713 mono_profiler_gc_heap_resize (gint64 new_size)
716 for (prof = prof_list; prof; prof = prof->next) {
717 if ((prof->events & MONO_PROFILE_GC) && prof->gc_heap_resize)
718 prof->gc_heap_resize (prof->profiler, new_size);
723 mono_profiler_gc_event (MonoGCEvent event, int generation)
726 for (prof = prof_list; prof; prof = prof->next) {
727 if ((prof->events & MONO_PROFILE_GC) && prof->gc_event)
728 prof->gc_event (prof->profiler, event, generation);
733 mono_profiler_gc_moves (void **objects, int num)
736 for (prof = prof_list; prof; prof = prof->next) {
737 if ((prof->events & MONO_PROFILE_GC_MOVES) && prof->gc_moves)
738 prof->gc_moves (prof->profiler, objects, num);
743 mono_profiler_install_gc (MonoProfileGCFunc callback, MonoProfileGCResizeFunc heap_resize_callback)
745 mono_gc_enable_events ();
748 prof_list->gc_event = callback;
749 prof_list->gc_heap_resize = heap_resize_callback;
753 * mono_profiler_install_gc_moves:
754 * @callback: callback function
756 * Install the @callback function that the GC will call when moving objects.
757 * The callback receives an array of pointers and the number of elements
758 * in the array. Every even element in the array is the original object location
759 * and the following odd element is the new location of the object in memory.
760 * So the number of elements argument will always be a multiple of 2.
761 * Since this callback happens during the GC, it is a restricted environment:
762 * no locks can be taken and the object pointers can be inspected only once
763 * the GC is finished (of course the original location pointers will not
764 * point to valid objects anymore).
767 mono_profiler_install_gc_moves (MonoProfileGCMoveFunc callback)
771 prof_list->gc_moves = callback;
775 mono_profiler_install_runtime_initialized (MonoProfileFunc runtime_initialized_callback)
779 prof_list->runtime_initialized_event = runtime_initialized_callback;
783 mono_profiler_runtime_initialized (void) {
785 for (prof = prof_list; prof; prof = prof->next) {
786 if (prof->runtime_initialized_event)
787 prof->runtime_initialized_event (prof->profiler);
792 mono_profiler_install_code_chunk_new (MonoProfilerCodeChunkNew callback) {
795 prof_list->code_chunk_new = callback;
798 mono_profiler_code_chunk_new (gpointer chunk, int size) {
800 for (prof = prof_list; prof; prof = prof->next) {
801 if (prof->code_chunk_new)
802 prof->code_chunk_new (prof->profiler, chunk, size);
807 mono_profiler_install_code_chunk_destroy (MonoProfilerCodeChunkDestroy callback) {
810 prof_list->code_chunk_destroy = callback;
813 mono_profiler_code_chunk_destroy (gpointer chunk) {
815 for (prof = prof_list; prof; prof = prof->next) {
816 if (prof->code_chunk_destroy)
817 prof->code_chunk_destroy (prof->profiler, chunk);
822 mono_profiler_install_code_buffer_new (MonoProfilerCodeBufferNew callback) {
825 prof_list->code_buffer_new = callback;
829 mono_profiler_install_iomap (MonoProfileIomapFunc callback)
833 prof_list->iomap_cb = callback;
837 mono_profiler_code_buffer_new (gpointer buffer, int size, MonoProfilerCodeBufferType type, void *data) {
839 for (prof = prof_list; prof; prof = prof->next) {
840 if (prof->code_buffer_new)
841 prof->code_buffer_new (prof->profiler, buffer, size, type, data);
845 static GHashTable *coverage_hash = NULL;
847 MonoProfileCoverageInfo*
848 mono_profiler_coverage_alloc (MonoMethod *method, int entries)
850 MonoProfileCoverageInfo *res;
851 int instrument = FALSE;
854 for (prof = prof_list; prof; prof = prof->next) {
855 /* note that we call the filter on all the profilers even if just
856 * a single one would be enough to instrument a method
858 if (prof->coverage_filter_cb)
859 if (prof->coverage_filter_cb (prof->profiler, method))
865 mono_profiler_coverage_lock ();
867 coverage_hash = g_hash_table_new (NULL, NULL);
869 res = g_malloc0 (sizeof (MonoProfileCoverageInfo) + sizeof (void*) * 2 * entries);
871 res->entries = entries;
873 g_hash_table_insert (coverage_hash, method, res);
874 mono_profiler_coverage_unlock ();
879 /* safe only when the method antive code has been unloaded */
881 mono_profiler_coverage_free (MonoMethod *method)
883 MonoProfileCoverageInfo* info;
885 mono_profiler_coverage_lock ();
886 if (!coverage_hash) {
887 mono_profiler_coverage_unlock ();
891 info = g_hash_table_lookup (coverage_hash, method);
894 g_hash_table_remove (coverage_hash, method);
896 mono_profiler_coverage_unlock ();
900 * mono_profiler_coverage_get:
901 * @prof: The profiler handle, installed with mono_profiler_install
902 * @method: the method to gather information from.
903 * @func: A routine that will be called back with the results
905 * If the MONO_PROFILER_INS_COVERAGE flag was active during JIT compilation
906 * it is posisble to obtain coverage information about a give method.
908 * The function @func will be invoked repeatedly with instances of the
909 * MonoProfileCoverageEntry structure.
912 mono_profiler_coverage_get (MonoProfiler *prof, MonoMethod *method, MonoProfileCoverageFunc func)
914 MonoProfileCoverageInfo* info;
917 const unsigned char *start, *end, *cil_code;
918 MonoMethodHeader *header;
919 MonoProfileCoverageEntry entry;
920 MonoDebugMethodInfo *debug_minfo;
922 mono_profiler_coverage_lock ();
923 info = g_hash_table_lookup (coverage_hash, method);
924 mono_profiler_coverage_unlock ();
929 header = mono_method_get_header (method);
930 start = mono_method_header_get_code (header, &code_size, NULL);
931 debug_minfo = mono_debug_lookup_method (method);
933 end = start + code_size;
934 for (i = 0; i < info->entries; ++i) {
935 cil_code = info->data [i].cil_code;
936 if (cil_code && cil_code >= start && cil_code < end) {
938 offset = cil_code - start;
939 entry.iloffset = offset;
940 entry.method = method;
941 entry.counter = info->data [i].count;
942 entry.line = entry.col = 1;
943 entry.filename = NULL;
945 MonoDebugSourceLocation *location;
947 location = mono_debug_symfile_lookup_location (debug_minfo, offset);
949 entry.line = location->row;
950 entry.col = location->column;
951 entry.filename = fname = g_strdup (location->source_file);
952 mono_debug_free_source_location (location);
960 mono_metadata_free_mh (header);
963 #ifndef DISABLE_PROFILER
965 * Small profiler extracted from mint: we should move it in a loadable module
966 * and improve it to do graphs and more accurate timestamping with rdtsc.
969 static FILE* poutput = NULL;
972 #define USE_WIN32COUNTER 0
976 unsigned int lows, highs, lowe, highe;
979 #define rdtsc(low,high) \
980 __asm__ __volatile__("rdtsc" : "=a" (low), "=d" (high))
985 rdtsc_elapsed (MonoRdtscTimer *t)
987 unsigned long long diff;
988 unsigned int highe = t->highe;
989 if (t->lowe < t->lows)
991 diff = (((unsigned long long) highe - t->highs) << 32) + (t->lowe - t->lows);
992 return ((double)diff / freq) / 1000000; /* have to return the result in seconds */
1003 if (!(cpuinfo = fopen ("/proc/cpuinfo", "r")))
1005 while (fgets (buf, sizeof(buf), cpuinfo)) {
1006 if (sscanf (buf, "cpu MHz : %f", &val) == 1) {
1007 /*printf ("got mh: %f\n", val);*/
1010 if (strncmp (buf, "flags", 5) == 0) {
1011 if (strstr (buf, "tsc")) {
1013 /*printf ("have tsc\n");*/
1018 return have_flag? have_freq: 0;
1021 #define MONO_TIMER_STARTUP \
1022 if (!(freq = have_rdtsc ())) g_error ("Compiled with TSC support, but none found");
1023 #define MONO_TIMER_TYPE MonoRdtscTimer
1024 #define MONO_TIMER_INIT(t)
1025 #define MONO_TIMER_DESTROY(t)
1026 #define MONO_TIMER_START(t) rdtsc ((t).lows, (t).highs);
1027 #define MONO_TIMER_STOP(t) rdtsc ((t).lowe, (t).highe);
1028 #define MONO_TIMER_ELAPSED(t) rdtsc_elapsed (&(t))
1030 #elif USE_WIN32COUNTER
1031 #include <windows.h>
1034 LARGE_INTEGER start, stop;
1040 win32_elapsed (MonoWin32Timer *t)
1042 LONGLONG diff = t->stop.QuadPart - t->start.QuadPart;
1043 return ((double)diff / freq) / 1000000; /* have to return the result in seconds */
1047 have_win32counter (void) {
1050 if (!QueryPerformanceFrequency (&f))
1055 #define MONO_TIMER_STARTUP \
1056 if (!(freq = have_win32counter ())) g_error ("Compiled with Win32 counter support, but none found");
1057 #define MONO_TIMER_TYPE MonoWin32Timer
1058 #define MONO_TIMER_INIT(t)
1059 #define MONO_TIMER_DESTROY(t)
1060 #define MONO_TIMER_START(t) QueryPerformanceCounter (&(t).start)
1061 #define MONO_TIMER_STOP(t) QueryPerformanceCounter (&(t).stop)
1062 #define MONO_TIMER_ELAPSED(t) win32_elapsed (&(t))
1067 GTimeVal start, stop;
1071 timeval_elapsed (MonoGLibTimer *t)
1073 if (t->start.tv_usec > t->stop.tv_usec) {
1074 t->stop.tv_usec += G_USEC_PER_SEC;
1077 return (t->stop.tv_sec - t->start.tv_sec)
1078 + ((double)(t->stop.tv_usec - t->start.tv_usec))/ G_USEC_PER_SEC;
1081 #define MONO_TIMER_STARTUP
1082 #define MONO_TIMER_TYPE MonoGLibTimer
1083 #define MONO_TIMER_INIT(t)
1084 #define MONO_TIMER_DESTROY(t)
1085 #define MONO_TIMER_START(t) g_get_current_time (&(t).start)
1086 #define MONO_TIMER_STOP(t) g_get_current_time (&(t).stop)
1087 #define MONO_TIMER_ELAPSED(t) timeval_elapsed (&(t))
1090 typedef struct _AllocInfo AllocInfo;
1091 typedef struct _CallerInfo CallerInfo;
1092 typedef struct _LastCallerInfo LastCallerInfo;
1094 struct _MonoProfiler {
1095 GHashTable *methods;
1096 MonoMemPool *mempool;
1098 /* info about JIT time */
1099 MONO_TIMER_TYPE jit_timer;
1101 double max_jit_time;
1102 MonoMethod *max_jit_method;
1107 /* chain of callers for the current thread */
1108 LastCallerInfo *callers;
1109 /* LastCallerInfo nodes for faster allocation */
1110 LastCallerInfo *cstorage;
1117 AllocInfo *alloc_info;
1118 CallerInfo *caller_info;
1121 typedef struct _MethodCallProfile MethodCallProfile;
1123 struct _MethodCallProfile {
1124 MethodCallProfile *next;
1125 MONO_TIMER_TYPE timer;
1136 struct _CallerInfo {
1142 struct _LastCallerInfo {
1143 LastCallerInfo *next;
1145 MONO_TIMER_TYPE timer;
1148 static MonoProfiler*
1149 create_profiler (void)
1151 MonoProfiler *prof = g_new0 (MonoProfiler, 1);
1153 prof->methods = g_hash_table_new (mono_aligned_addr_hash, NULL);
1154 MONO_TIMER_INIT (prof->jit_timer);
1155 prof->mempool = mono_mempool_new ();
1160 #ifdef HAVE_KW_THREAD
1161 static __thread MonoProfiler * tls_profiler;
1162 # define GET_PROFILER() tls_profiler
1163 # define SET_PROFILER(x) tls_profiler = (x)
1164 # define ALLOC_PROFILER() /* nop */
1166 static guint32 profiler_thread_id = -1;
1167 # define GET_PROFILER() ((MonoProfiler *)TlsGetValue (profiler_thread_id))
1168 # define SET_PROFILER(x) TlsSetValue (profiler_thread_id, x);
1169 # define ALLOC_PROFILER() profiler_thread_id = TlsAlloc ()
1172 #define GET_THREAD_PROF(prof) do { \
1173 MonoProfiler *_tprofiler = GET_PROFILER (); \
1174 if (!_tprofiler) { \
1175 _tprofiler = create_profiler (); \
1176 prof->per_thread = g_slist_prepend (prof->per_thread, _tprofiler); \
1177 SET_PROFILER (_tprofiler); \
1179 prof = _tprofiler; \
1182 /* thread unsafe but faster variant */
1183 #define GET_THREAD_PROF(prof)
1187 compare_profile (MethodProfile *profa, MethodProfile *profb)
1189 return (gint)((profb->total - profa->total)*1000);
1193 build_profile (MonoMethod *m, MethodProfile *prof, GList **funcs)
1196 *funcs = g_list_insert_sorted (*funcs, prof, (GCompareFunc)compare_profile);
1200 method_get_name (MonoMethod* method)
1204 sig = mono_signature_get_desc (mono_method_signature (method), FALSE);
1205 res = g_strdup_printf ("%s%s%s::%s(%s)", method->klass->name_space,
1206 method->klass->name_space ? "." : "", method->klass->name,
1212 static void output_callers (MethodProfile *p);
1214 /* This isn't defined on older glib versions and on some platforms */
1215 #ifndef G_GUINT64_FORMAT
1216 #define G_GUINT64_FORMAT "ul"
1218 #ifndef G_GINT64_FORMAT
1219 #define G_GINT64_FORMAT "lld"
1223 output_profile (GList *funcs)
1228 guint64 total_calls = 0;
1231 fprintf (poutput, "Time(ms) Count P/call(ms) Method name\n");
1232 for (tmp = funcs; tmp; tmp = tmp->next) {
1234 total_calls += p->count;
1235 if (!(gint)(p->total*1000))
1237 m = method_get_name (p->method);
1238 fprintf (poutput, "########################\n");
1239 fprintf (poutput, "% 8.3f ", (double) (p->total * 1000));
1240 fprintf (poutput, "%7" G_GUINT64_FORMAT " ", (guint64)p->count);
1241 fprintf (poutput, "% 8.3f ", (double) (p->total * 1000)/(double)p->count);
1242 fprintf (poutput, " %s\n", m);
1248 fprintf (poutput, "Total number of calls: %" G_GINT64_FORMAT "\n", (gint64)total_calls);
1257 compare_newobj_profile (NewobjProfile *profa, NewobjProfile *profb)
1259 if (profb->count == profa->count)
1262 return profb->count > profa->count ? 1 : -1;
1266 build_newobj_profile (MonoClass *class, MethodProfile *mprof, GList **funcs)
1268 NewobjProfile *prof = g_new (NewobjProfile, 1);
1273 /* we use the total amount of memory to sort */
1274 for (tmp = mprof->alloc_info; tmp; tmp = tmp->next)
1276 prof->count = count;
1277 *funcs = g_list_insert_sorted (*funcs, prof, (GCompareFunc)compare_newobj_profile);
1281 compare_caller (CallerInfo *a, CallerInfo *b)
1283 return b->count - a->count;
1287 compare_alloc (AllocInfo *a, AllocInfo *b)
1289 return b->mem - a->mem;
1293 sort_alloc_list (AllocInfo *ai)
1297 for (tmp = ai; tmp; tmp = tmp->next) {
1298 l = g_slist_insert_sorted (l, tmp, (GCompareFunc)compare_alloc);
1304 sort_caller_list (CallerInfo *ai)
1308 for (tmp = ai; tmp; tmp = tmp->next) {
1309 l = g_slist_insert_sorted (l, tmp, (GCompareFunc)compare_caller);
1315 output_callers (MethodProfile *p) {
1316 guint total_callers, percent;
1317 GSList *sorted, *tmps;
1321 fprintf (poutput, " Callers (with count) that contribute at least for 1%%:\n");
1323 for (cinfo = p->caller_info; cinfo; cinfo = cinfo->next) {
1324 total_callers += cinfo->count;
1326 sorted = sort_caller_list (p->caller_info);
1327 for (tmps = sorted; tmps; tmps = tmps->next) {
1329 percent = (cinfo->count * 100)/total_callers;
1332 m = method_get_name (cinfo->caller);
1333 fprintf (poutput, " %8d % 3d %% %s\n", cinfo->count, percent, m);
1338 static int moved_objects = 0;
1340 simple_gc_move (MonoProfiler *prof, void **objects, int num)
1342 moved_objects += num / 2;
1346 output_newobj_profile (GList *proflist)
1353 const char* isarray;
1357 GSList *sorted, *tmps;
1359 fprintf (poutput, "\nAllocation profiler\n");
1362 fprintf (poutput, "%-9s %s\n", "Total mem", "Method");
1363 for (tmp = proflist; tmp; tmp = tmp->next) {
1366 if (p->count < 50000)
1369 m = method_get_name (mp->method);
1370 fprintf (poutput, "########################\n%8" G_GUINT64_FORMAT " KB %s\n", (p->count / 1024), m);
1372 sorted = sort_alloc_list (mp->alloc_info);
1373 for (tmps = sorted; tmps; tmps = tmps->next) {
1375 if (ainfo->mem < 50000)
1377 klass = ainfo->klass;
1380 klass = klass->element_class;
1384 g_snprintf (buf, sizeof (buf), "%s%s%s%s",
1385 klass->name_space, klass->name_space ? "." : "", klass->name, isarray);
1386 fprintf (poutput, " %8" G_GUINT64_FORMAT " KB %8" G_GUINT64_FORMAT " %-48s\n", (ainfo->mem / 1024), ainfo->count, buf);
1389 output_callers (mp);
1391 fprintf (poutput, "Total memory allocated: %" G_GUINT64_FORMAT " KB\n", total / 1024);
1392 fprintf (poutput, "Objects copied: %d\n", moved_objects);
1396 merge_methods (MonoMethod *method, MethodProfile *profile, MonoProfiler *prof)
1398 MethodProfile *mprof;
1399 AllocInfo *talloc_info, *alloc_info;
1400 CallerInfo *tcaller_info, *caller_info;
1402 mprof = g_hash_table_lookup (prof->methods, method);
1404 /* the master thread didn't see this method, just transfer the info as is */
1405 g_hash_table_insert (prof->methods, method, profile);
1408 /* merge the info from profile into mprof */
1409 mprof->count += profile->count;
1410 mprof->total += profile->total;
1411 /* merge alloc info */
1412 for (talloc_info = profile->alloc_info; talloc_info; talloc_info = talloc_info->next) {
1413 for (alloc_info = mprof->alloc_info; alloc_info; alloc_info = alloc_info->next) {
1414 if (alloc_info->klass == talloc_info->klass) {
1415 /* mprof already has a record for the klass, merge */
1416 alloc_info->count += talloc_info->count;
1417 alloc_info->mem += talloc_info->mem;
1422 /* mprof didn't have the info, just copy it over */
1423 alloc_info = mono_mempool_alloc0 (prof->mempool, sizeof (AllocInfo));
1424 *alloc_info = *talloc_info;
1425 alloc_info->next = mprof->alloc_info;
1426 mprof->alloc_info = alloc_info->next;
1429 /* merge callers info */
1430 for (tcaller_info = profile->caller_info; tcaller_info; tcaller_info = tcaller_info->next) {
1431 for (caller_info = mprof->caller_info; caller_info; caller_info = caller_info->next) {
1432 if (caller_info->caller == tcaller_info->caller) {
1433 /* mprof already has a record for the caller method, merge */
1434 caller_info->count += tcaller_info->count;
1439 /* mprof didn't have the info, just copy it over */
1440 caller_info = mono_mempool_alloc0 (prof->mempool, sizeof (CallerInfo));
1441 *caller_info = *tcaller_info;
1442 caller_info->next = mprof->caller_info;
1443 mprof->caller_info = caller_info;
1449 merge_thread_data (MonoProfiler *master, MonoProfiler *tprof)
1451 master->jit_time += tprof->jit_time;
1452 master->methods_jitted += tprof->methods_jitted;
1453 if (master->max_jit_time < tprof->max_jit_time) {
1454 master->max_jit_time = tprof->max_jit_time;
1455 master->max_jit_method = tprof->max_jit_method;
1458 g_hash_table_foreach (tprof->methods, (GHFunc)merge_methods, master);
1462 simple_method_enter (MonoProfiler *prof, MonoMethod *method)
1464 MethodProfile *profile_info;
1465 LastCallerInfo *callinfo;
1466 GET_THREAD_PROF (prof);
1467 /*g_print ("enter %p %s::%s in %d (%p)\n", method, method->klass->name, method->name, GetCurrentThreadId (), prof);*/
1468 if (!(profile_info = g_hash_table_lookup (prof->methods, method))) {
1469 profile_info = mono_mempool_alloc0 (prof->mempool, sizeof (MethodProfile));
1470 MONO_TIMER_INIT (profile_info->u.timer);
1471 g_hash_table_insert (prof->methods, method, profile_info);
1473 profile_info->count++;
1474 if (prof->callers) {
1476 MonoMethod *caller = prof->callers->method;
1477 for (cinfo = profile_info->caller_info; cinfo; cinfo = cinfo->next) {
1478 if (cinfo->caller == caller)
1482 cinfo = mono_mempool_alloc0 (prof->mempool, sizeof (CallerInfo));
1483 cinfo->caller = caller;
1484 cinfo->next = profile_info->caller_info;
1485 profile_info->caller_info = cinfo;
1489 if (!(callinfo = prof->cstorage)) {
1490 callinfo = mono_mempool_alloc (prof->mempool, sizeof (LastCallerInfo));
1491 MONO_TIMER_INIT (callinfo->timer);
1493 prof->cstorage = prof->cstorage->next;
1495 callinfo->method = method;
1496 callinfo->next = prof->callers;
1497 prof->callers = callinfo;
1498 MONO_TIMER_START (callinfo->timer);
1502 simple_method_leave (MonoProfiler *prof, MonoMethod *method)
1504 MethodProfile *profile_info;
1505 LastCallerInfo *callinfo, *newcallinfo = NULL;
1507 GET_THREAD_PROF (prof);
1508 /*g_print ("leave %p %s::%s in %d (%p)\n", method, method->klass->name, method->name, GetCurrentThreadId (), prof);*/
1509 callinfo = prof->callers;
1510 /* should really not happen, but we don't catch exceptions events, yet ... */
1512 MONO_TIMER_STOP (callinfo->timer);
1513 profile_info = g_hash_table_lookup (prof->methods, callinfo->method);
1515 profile_info->total += MONO_TIMER_ELAPSED (callinfo->timer);
1516 newcallinfo = callinfo->next;
1517 callinfo->next = prof->cstorage;
1518 prof->cstorage = callinfo;
1519 if (callinfo->method == method)
1521 callinfo = newcallinfo;
1523 prof->callers = newcallinfo;
1527 simple_allocation (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1529 MethodProfile *profile_info;
1532 GET_THREAD_PROF (prof);
1533 if (prof->callers) {
1534 MonoMethod *caller = prof->callers->method;
1536 /* Otherwise all allocations are attributed to icall_wrapper_mono_object_new */
1537 if (caller->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && prof->callers->next)
1538 caller = prof->callers->next->method;
1540 if (!(profile_info = g_hash_table_lookup (prof->methods, caller)))
1541 g_assert_not_reached ();
1543 return; /* fine for now */
1546 for (tmp = profile_info->alloc_info; tmp; tmp = tmp->next) {
1547 if (tmp->klass == klass)
1551 tmp = mono_mempool_alloc0 (prof->mempool, sizeof (AllocInfo));
1553 tmp->next = profile_info->alloc_info;
1554 profile_info->alloc_info = tmp;
1557 tmp->mem += mono_object_get_size (obj);
1561 simple_method_jit (MonoProfiler *prof, MonoMethod *method)
1563 GET_THREAD_PROF (prof);
1564 prof->methods_jitted++;
1565 MONO_TIMER_START (prof->jit_timer);
1569 simple_method_end_jit (MonoProfiler *prof, MonoMethod *method, int result)
1572 GET_THREAD_PROF (prof);
1573 MONO_TIMER_STOP (prof->jit_timer);
1574 jtime = MONO_TIMER_ELAPSED (prof->jit_timer);
1575 prof->jit_time += jtime;
1576 if (jtime > prof->max_jit_time) {
1577 prof->max_jit_time = jtime;
1578 prof->max_jit_method = method;
1582 /* about 10 minutes of samples */
1583 #define MAX_PROF_SAMPLES (1000*60*10)
1584 static int prof_counts = 0;
1585 static int prof_ucounts = 0;
1586 static gpointer* prof_addresses = NULL;
1587 static GHashTable *prof_table = NULL;
1590 simple_stat_hit (MonoProfiler *prof, guchar *ip, void *context)
1594 if (prof_counts >= MAX_PROF_SAMPLES)
1596 pos = InterlockedIncrement (&prof_counts);
1597 prof_addresses [pos - 1] = ip;
1601 compare_methods_prof (gconstpointer a, gconstpointer b)
1603 int ca = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, a));
1604 int cb = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, b));
1609 prof_foreach (char *method, gpointer c, gpointer data)
1611 GList **list = data;
1612 *list = g_list_insert_sorted (*list, method, compare_methods_prof);
1615 typedef struct Addr2LineData Addr2LineData;
1617 struct Addr2LineData {
1618 Addr2LineData *next;
1625 static Addr2LineData *addr2line_pipes = NULL;
1628 try_addr2line (const char* binary, gpointer ip)
1632 Addr2LineData *addr2line;
1634 for (addr2line = addr2line_pipes; addr2line; addr2line = addr2line->next) {
1635 if (strcmp (binary, addr2line->binary) == 0)
1639 const char *addr_argv[] = {"addr2line", "-f", "-e", binary, NULL};
1643 char monobin [1024];
1644 /* non-linux platforms will need different code here */
1645 if (strcmp (binary, "mono") == 0) {
1646 int count = readlink ("/proc/self/exe", monobin, sizeof (monobin));
1647 if (count >= 0 && count < sizeof (monobin)) {
1648 monobin [count] = 0;
1649 addr_argv [3] = monobin;
1653 if (!g_spawn_async_with_pipes (NULL, (char**)addr_argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
1654 &child_pid, &ch_in, &ch_out, NULL, NULL)) {
1655 return g_strdup (binary);
1657 addr2line = g_new0 (Addr2LineData, 1);
1658 addr2line->child_pid = child_pid;
1659 addr2line->binary = g_strdup (binary);
1660 addr2line->pipein = fdopen (ch_in, "w");
1661 addr2line->pipeout = fdopen (ch_out, "r");
1662 addr2line->next = addr2line_pipes;
1663 addr2line_pipes = addr2line;
1665 fprintf (addr2line->pipein, "%p\n", ip);
1666 fflush (addr2line->pipein);
1667 /* we first get the func name and then file:lineno in a second line */
1668 if (fgets (buf, sizeof (buf), addr2line->pipeout) && buf [0] != '?') {
1669 char *end = strchr (buf, '\n');
1672 res = g_strdup_printf ("%s(%s", binary, buf);
1673 /* discard the filename/line info */
1674 fgets (buf, sizeof (buf), addr2line->pipeout);
1676 res = g_strdup (binary);
1682 stat_prof_report (MonoProfiler *prof)
1685 int count = prof_counts;
1689 GList *tmp, *sorted = NULL;
1691 int pcount = ++ prof_counts;
1693 prof_counts = MAX_PROF_SAMPLES;
1694 for (i = 0; i < count; ++i) {
1695 ip = prof_addresses [i];
1696 ji = mono_jit_info_table_find (mono_domain_get (), ip);
1699 for (l = prof->domains; l && !ji; l = l->next)
1700 ji = mono_jit_info_table_find (l->data, ip);
1704 mn = mono_method_full_name (ji->method, TRUE);
1706 #ifdef HAVE_BACKTRACE_SYMBOLS
1711 names = backtrace_symbols (&ip, 1);
1712 send = strchr (names [0], '+');
1719 send = strchr (names [0], '[');
1722 if (no_func && names [0][0]) {
1723 char *endp = strchr (names [0], 0);
1724 while (--endp >= names [0] && g_ascii_isspace (*endp))
1726 mn = try_addr2line (names [0], ip);
1728 mn = g_strdup (names [0]);
1733 mn = g_strdup_printf ("unmanaged [%p]", ip);
1736 c = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, mn));
1738 g_hash_table_insert (prof_table, mn, GUINT_TO_POINTER (c));
1742 fprintf (poutput, "prof counts: total/unmanaged: %d/%d\n", pcount, prof_ucounts);
1743 g_hash_table_foreach (prof_table, (GHFunc)prof_foreach, &sorted);
1744 for (tmp = sorted; tmp; tmp = tmp->next) {
1746 c = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, tmp->data));
1747 perc = c*100.0/count;
1748 fprintf (poutput, "%7d\t%5.2f %% %s\n", c, perc, (char*)tmp->data);
1750 g_list_free (sorted);
1754 simple_appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
1756 prof->domains = g_slist_prepend (prof->domains, domain);
1760 simple_appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
1762 /* FIXME: we should actually record partial data for each domain,
1763 * but at this point it's must easier using the new logging profiler.
1765 mono_profiler_shutdown ();
1768 static gint32 simple_shutdown_done = FALSE;
1771 simple_shutdown (MonoProfiler *prof)
1773 GList *profile = NULL;
1774 MonoProfiler *tprof;
1777 gint32 see_shutdown_done;
1780 mono_thread_attach(mono_get_root_domain());
1783 // Make sure we execute simple_shutdown only once
1784 see_shutdown_done = InterlockedExchange(& simple_shutdown_done, TRUE);
1785 if (see_shutdown_done)
1788 if (mono_profiler_events & MONO_PROFILE_STATISTICAL) {
1789 stat_prof_report (prof);
1792 // Stop all incoming events
1793 mono_profiler_set_events (0);
1795 for (tmp = prof->per_thread; tmp; tmp = tmp->next) {
1797 merge_thread_data (prof, tprof);
1800 fprintf (poutput, "Total time spent compiling %d methods (sec): %.4g\n", prof->methods_jitted, prof->jit_time);
1801 if (prof->max_jit_method) {
1802 str = method_get_name (prof->max_jit_method);
1803 fprintf (poutput, "Slowest method to compile (sec): %.4g: %s\n", prof->max_jit_time, str);
1806 g_hash_table_foreach (prof->methods, (GHFunc)build_profile, &profile);
1807 output_profile (profile);
1808 g_list_free (profile);
1811 g_hash_table_foreach (prof->methods, (GHFunc)build_newobj_profile, &profile);
1812 output_newobj_profile (profile);
1813 g_list_free (profile);
1815 g_free (prof_addresses);
1816 prof_addresses = NULL;
1817 g_hash_table_destroy (prof_table);
1821 mono_profiler_install_simple (const char *desc)
1824 gchar **args, **ptr;
1825 MonoProfileFlags flags = 0;
1831 desc = "alloc,time,jit";
1835 if (strstr (desc, ":"))
1836 desc = strstr (desc, ":") + 1;
1838 desc = "alloc,time,jit";
1839 args = g_strsplit (desc, ",", -1);
1841 for (ptr = args; ptr && *ptr; ptr++) {
1842 const char *arg = *ptr;
1844 // Alwais listen to appdomaon events to shutdown at the first unload
1845 flags |= MONO_PROFILE_APPDOMAIN_EVENTS;
1846 if (!strcmp (arg, "time"))
1847 flags |= MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_EXCEPTIONS;
1848 else if (!strcmp (arg, "alloc"))
1849 flags |= MONO_PROFILE_ALLOCATIONS;
1850 else if (!strcmp (arg, "stat"))
1851 flags |= MONO_PROFILE_STATISTICAL;
1852 else if (!strcmp (arg, "jit"))
1853 flags |= MONO_PROFILE_JIT_COMPILATION;
1854 else if (strncmp (arg, "file=", 5) == 0) {
1855 poutput = fopen (arg + 5, "wb");
1858 fprintf (stderr, "profiler : cannot open profile output file '%s'.\n", arg + 5);
1861 fprintf (stderr, "profiler : Unknown argument '%s'.\n", arg);
1866 if (flags & MONO_PROFILE_ALLOCATIONS)
1867 flags |= MONO_PROFILE_GC_MOVES;
1868 if (flags & MONO_PROFILE_ALLOCATIONS)
1869 flags |= MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_EXCEPTIONS;
1871 flags = MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_ALLOCATIONS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_EXCEPTIONS;
1873 prof = create_profiler ();
1875 SET_PROFILER (prof);
1877 /* statistical profiler data */
1878 prof_addresses = g_new0 (gpointer, MAX_PROF_SAMPLES);
1879 prof_table = g_hash_table_new (g_str_hash, g_str_equal);
1881 mono_profiler_install (prof, simple_shutdown);
1882 mono_profiler_install_enter_leave (simple_method_enter, simple_method_leave);
1883 mono_profiler_install_exception (NULL, simple_method_leave, NULL);
1884 mono_profiler_install_jit_compile (simple_method_jit, simple_method_end_jit);
1885 mono_profiler_install_allocation (simple_allocation);
1886 mono_profiler_install_appdomain (NULL, simple_appdomain_load, simple_appdomain_unload, NULL);
1887 mono_profiler_install_statistical (simple_stat_hit);
1888 mono_profiler_install_gc_moves (simple_gc_move);
1889 mono_profiler_set_events (flags);
1892 #endif /* DISABLE_PROFILER */
1894 typedef void (*ProfilerInitializer) (const char*);
1895 #define INITIALIZER_NAME "mono_profiler_startup"
1898 * mono_profiler_load:
1899 * @desc: arguments to configure the profiler
1901 * Invoke this method to initialize the profiler. This will drive the
1902 * loading of the internal ("default") or any external profilers.
1904 * This routine is invoked by Mono's driver, but must be called manually
1905 * if you embed Mono into your application.
1908 mono_profiler_load (const char *desc)
1910 mono_gc_base_init ();
1912 #ifndef DISABLE_PROFILER
1913 if (!desc || (strcmp ("default", desc) == 0) || (strncmp (desc, "default:", 8) == 0)) {
1914 mono_profiler_install_simple (desc);
1923 MonoDl *pmodule = NULL;
1924 const char* col = strchr (desc, ':');
1931 mname = g_memdup (desc, col - desc + 1);
1932 mname [col - desc] = 0;
1934 mname = g_strdup (desc);
1936 libname = g_strdup_printf ("mono-profiler-%s", mname);
1939 while ((path = mono_dl_build_path (NULL, libname, &iter))) {
1941 pmodule = mono_dl_open (path, MONO_DL_LAZY, &err);
1943 ProfilerInitializer func;
1944 if ((err = mono_dl_symbol (pmodule, INITIALIZER_NAME, (gpointer *)&func))) {
1945 g_warning ("Cannot find initializer function %s in profiler module: %s (%s)", INITIALIZER_NAME, libname, err);
1956 g_warning ("Error loading profiler module '%s': %s", libname, err);