Merge pull request #2816 from xmcclure/profile-clean-0
[mono.git] / mono / metadata / profiler.c
1 /*
2  * profiler.c: Profiler interface for Mono
3  *
4  * Author:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Alex Rønne Petersen (alexrp@xamarin.com)
7  *
8  * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
9  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
10  * Copyright 2011 Xamarin Inc (http://www.xamarin.com).
11  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
12  */
13
14 #include "config.h"
15 #include "mono/metadata/profiler-private.h"
16 #include "mono/metadata/assembly.h"
17 #include "mono/metadata/debug-helpers.h"
18 #include "mono/metadata/mono-debug.h"
19 #include "mono/metadata/debug-mono-symfile.h"
20 #include "mono/metadata/metadata-internals.h"
21 #include "mono/metadata/class-internals.h"
22 #include "mono/metadata/domain-internals.h"
23 #include "mono/metadata/gc-internals.h"
24 #include "mono/metadata/mono-config-dirs.h"
25 #include "mono/io-layer/io-layer.h"
26 #include "mono/utils/mono-dl.h"
27 #include <mono/utils/mono-logger-internals.h>
28 #include <string.h>
29 #ifdef HAVE_UNISTD_H
30 #include <unistd.h>
31 #endif
32 #ifdef HAVE_SYS_TIME_H
33 #include <sys/time.h>
34 #endif
35 #ifdef HAVE_BACKTRACE_SYMBOLS
36 #include <execinfo.h>
37 #endif
38
39 typedef struct _ProfilerDesc ProfilerDesc;
40 struct _ProfilerDesc {
41         ProfilerDesc *next;
42         MonoProfiler *profiler;
43         MonoProfileFlags events;
44
45         MonoProfileAppDomainFunc   domain_start_load;
46         MonoProfileAppDomainResult domain_end_load;
47         MonoProfileAppDomainFunc   domain_start_unload;
48         MonoProfileAppDomainFunc   domain_end_unload;
49         MonoProfileAppDomainFriendlyNameFunc   domain_name;
50
51         MonoProfileContextFunc context_load;
52         MonoProfileContextFunc context_unload;
53
54         MonoProfileAssemblyFunc   assembly_start_load;
55         MonoProfileAssemblyResult assembly_end_load;
56         MonoProfileAssemblyFunc   assembly_start_unload;
57         MonoProfileAssemblyFunc   assembly_end_unload;
58
59         MonoProfileModuleFunc   module_start_load;
60         MonoProfileModuleResult module_end_load;
61         MonoProfileModuleFunc   module_start_unload;
62         MonoProfileModuleFunc   module_end_unload;
63
64         MonoProfileClassFunc   class_start_load;
65         MonoProfileClassResult class_end_load;
66         MonoProfileClassFunc   class_start_unload;
67         MonoProfileClassFunc   class_end_unload;
68
69         MonoProfileMethodFunc   jit_start;
70         MonoProfileMethodResult jit_end;
71         MonoProfileJitResult    jit_end2;
72         MonoProfileMethodFunc   method_free;
73         MonoProfileMethodFunc   method_start_invoke;
74         MonoProfileMethodFunc   method_end_invoke;
75         MonoProfileMethodResult man_unman_transition;
76         MonoProfileAllocFunc    allocation_cb;
77         MonoProfileMonitorFunc  monitor_event_cb;
78         MonoProfileStatFunc     statistical_cb;
79         MonoProfileStatCallChainFunc statistical_call_chain_cb;
80         int                     statistical_call_chain_depth;
81         MonoProfilerCallChainStrategy  statistical_call_chain_strategy;
82         MonoProfileMethodFunc   method_enter;
83         MonoProfileMethodFunc   method_leave;
84
85         MonoProfileExceptionFunc        exception_throw_cb;
86         MonoProfileMethodFunc exception_method_leave_cb;
87         MonoProfileExceptionClauseFunc exception_clause_cb;
88
89         MonoProfileIomapFunc iomap_cb;
90
91         MonoProfileThreadFunc   thread_start;
92         MonoProfileThreadFunc   thread_end;
93         MonoProfileThreadNameFunc   thread_name;
94
95         MonoProfileCoverageFilterFunc coverage_filter_cb;
96
97         MonoProfileFunc shutdown_callback;
98
99         MonoProfileGCFunc        gc_event;
100         MonoProfileGCResizeFunc  gc_heap_resize;
101         MonoProfileGCMoveFunc    gc_moves;
102         MonoProfileGCHandleFunc  gc_handle;
103         MonoProfileGCRootFunc    gc_roots;
104
105         MonoProfileFunc          runtime_initialized_event;
106
107         MonoProfilerCodeChunkNew code_chunk_new;
108         MonoProfilerCodeChunkDestroy code_chunk_destroy;
109         MonoProfilerCodeBufferNew code_buffer_new;
110 };
111
112 static ProfilerDesc *prof_list = NULL;
113
114 #define mono_profiler_coverage_lock() mono_os_mutex_lock (&profiler_coverage_mutex)
115 #define mono_profiler_coverage_unlock() mono_os_mutex_unlock (&profiler_coverage_mutex)
116 static mono_mutex_t profiler_coverage_mutex;
117
118 /* this is directly accessible to other mono libs.
119  * It is the ORed value of all the profiler's events.
120  */
121 MonoProfileFlags mono_profiler_events;
122
123 /**
124  * mono_profiler_install:
125  * @prof: a MonoProfiler structure pointer, or a pointer to a derived structure.
126  * @callback: the function to invoke at shutdown
127  *
128  * Use mono_profiler_install to activate profiling in the Mono runtime.
129  * Typically developers of new profilers will create a new structure whose
130  * first field is a MonoProfiler and put any extra information that they need
131  * to access from the various profiling callbacks there.
132  *
133  */
134 void
135 mono_profiler_install (MonoProfiler *prof, MonoProfileFunc callback)
136 {
137         ProfilerDesc *desc = g_new0 (ProfilerDesc, 1);
138         if (!prof_list)
139                 mono_os_mutex_init_recursive (&profiler_coverage_mutex);
140         desc->profiler = prof;
141         desc->shutdown_callback = callback;
142         desc->next = prof_list;
143         prof_list = desc;
144 }
145
146 /**
147  * mono_profiler_set_events:
148  * @events: an ORed set of values made up of MONO_PROFILER_ flags
149  *
150  * The events descriped in the @events argument is a set of flags
151  * that represent which profiling events must be triggered.  For
152  * example if you have registered a set of methods for tracking
153  * JIT compilation start and end with mono_profiler_install_jit_compile,
154  * you will want to pass the MONO_PROFILE_JIT_COMPILATION flag to
155  * this routine.
156  *
157  * You can call mono_profile_set_events more than once and you can
158  * do this at runtime to modify which methods are invoked.
159  */
160 void
161 mono_profiler_set_events (MonoProfileFlags events)
162 {
163         ProfilerDesc *prof;
164         MonoProfileFlags value = (MonoProfileFlags)0;
165         if (prof_list)
166                 prof_list->events = events;
167         for (prof = prof_list; prof; prof = prof->next)
168                 value = (MonoProfileFlags)(value | prof->events);
169         mono_profiler_events = value;
170 }
171
172 /**
173  * mono_profiler_get_events:
174  *
175  * Returns a list of active events that will be intercepted. 
176  */
177 MonoProfileFlags
178 mono_profiler_get_events (void)
179 {
180         return mono_profiler_events;
181 }
182
183 /**
184  * mono_profiler_install_enter_leave:
185  * @enter: the routine to be called on each method entry
186  * @fleave: the routine to be called each time a method returns
187  *
188  * Use this routine to install routines that will be called everytime
189  * a method enters and leaves.   The routines will receive as an argument
190  * the MonoMethod representing the method that is entering or leaving.
191  */
192 void
193 mono_profiler_install_enter_leave (MonoProfileMethodFunc enter, MonoProfileMethodFunc fleave)
194 {
195         if (!prof_list)
196                 return;
197         prof_list->method_enter = enter;
198         prof_list->method_leave = fleave;
199 }
200
201 /**
202  * mono_profiler_install_jit_compile:
203  * @start: the routine to be called when the JIT process starts.
204  * @end: the routine to be called when the JIT process ends.
205  *
206  * Use this routine to install routines that will be called when JIT 
207  * compilation of a method starts and completes.
208  */
209 void 
210 mono_profiler_install_jit_compile (MonoProfileMethodFunc start, MonoProfileMethodResult end)
211 {
212         if (!prof_list)
213                 return;
214         prof_list->jit_start = start;
215         prof_list->jit_end = end;
216 }
217
218 void 
219 mono_profiler_install_jit_end (MonoProfileJitResult end)
220 {
221         if (!prof_list)
222                 return;
223         prof_list->jit_end2 = end;
224 }
225
226 void 
227 mono_profiler_install_method_free (MonoProfileMethodFunc callback)
228 {
229         if (!prof_list)
230                 return;
231         prof_list->method_free = callback;
232 }
233
234 void
235 mono_profiler_install_method_invoke (MonoProfileMethodFunc start, MonoProfileMethodFunc end)
236 {
237         if (!prof_list)
238                 return;
239         prof_list->method_start_invoke = start;
240         prof_list->method_end_invoke = end;
241 }
242
243 void 
244 mono_profiler_install_thread (MonoProfileThreadFunc start, MonoProfileThreadFunc end)
245 {
246         if (!prof_list)
247                 return;
248         prof_list->thread_start = start;
249         prof_list->thread_end = end;
250 }
251
252 void 
253 mono_profiler_install_thread_name (MonoProfileThreadNameFunc thread_name_cb)
254 {
255         if (!prof_list)
256                 return;
257         prof_list->thread_name = thread_name_cb;
258 }
259
260 void 
261 mono_profiler_install_transition (MonoProfileMethodResult callback)
262 {
263         if (!prof_list)
264                 return;
265         prof_list->man_unman_transition = callback;
266 }
267
268 void 
269 mono_profiler_install_allocation (MonoProfileAllocFunc callback)
270 {
271         mono_gc_enable_alloc_events ();
272         if (!prof_list)
273                 return;
274         prof_list->allocation_cb = callback;
275 }
276
277 void
278 mono_profiler_install_monitor  (MonoProfileMonitorFunc callback)
279 {
280         if (!prof_list)
281                 return;
282         prof_list->monitor_event_cb = callback;
283 }
284
285 static MonoProfileSamplingMode sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
286 static int64_t sampling_frequency = 1000; //1ms
287
288 /**
289  * mono_profiler_set_statistical_mode:
290  * @mode the sampling mode used.
291  * @sample_frequency_is_us the sampling frequency in microseconds.
292  *
293  * Set the sampling parameters for the profiler. Sampling mode affects the effective sampling rate as in samples/s you'll witness.
294  * The default sampling mode is process mode, which only reports samples when there's activity in the process.
295  *
296  * Sampling frequency should be interpreted as a suggestion that can't always be honored due to how most kernels expose alarms.
297  *
298  * Said that, when using statistical sampling, always assume variable rate sampling as all sort of external factors can interfere.
299  */
300 void
301 mono_profiler_set_statistical_mode (MonoProfileSamplingMode mode, int64_t sampling_frequency_is_us)
302 {
303         sampling_mode = mode;
304         sampling_frequency = sampling_frequency_is_us;
305 }
306
307 void 
308 mono_profiler_install_statistical (MonoProfileStatFunc callback)
309 {
310         if (!prof_list)
311                 return;
312         prof_list->statistical_cb = callback;
313 }
314
315 int64_t
316 mono_profiler_get_sampling_rate (void)
317 {
318         return sampling_frequency;
319 }
320
321 MonoProfileSamplingMode
322 mono_profiler_get_sampling_mode (void)
323 {
324         return sampling_mode;
325 }
326
327 void 
328 mono_profiler_install_statistical_call_chain (MonoProfileStatCallChainFunc callback, int call_chain_depth, MonoProfilerCallChainStrategy call_chain_strategy) {
329         if (!prof_list)
330                 return;
331         if (call_chain_depth > MONO_PROFILER_MAX_STAT_CALL_CHAIN_DEPTH) {
332                 call_chain_depth = MONO_PROFILER_MAX_STAT_CALL_CHAIN_DEPTH;
333         }
334         if ((call_chain_strategy >= MONO_PROFILER_CALL_CHAIN_INVALID) || (call_chain_strategy < MONO_PROFILER_CALL_CHAIN_NONE)) {
335                 call_chain_strategy = MONO_PROFILER_CALL_CHAIN_NONE;
336         }
337         prof_list->statistical_call_chain_cb = callback;
338         prof_list->statistical_call_chain_depth = call_chain_depth;
339         prof_list->statistical_call_chain_strategy = call_chain_strategy;
340 }
341
342 int
343 mono_profiler_stat_get_call_chain_depth (void) {
344         if (prof_list && prof_list->statistical_call_chain_cb != NULL) {
345                 return prof_list->statistical_call_chain_depth;
346         } else {
347                 return 0;
348         }
349 }
350
351 MonoProfilerCallChainStrategy
352 mono_profiler_stat_get_call_chain_strategy (void) {
353         if (prof_list && prof_list->statistical_call_chain_cb != NULL) {
354                 return prof_list->statistical_call_chain_strategy;
355         } else {
356                 return MONO_PROFILER_CALL_CHAIN_NONE;
357         }
358 }
359
360 void mono_profiler_install_exception (MonoProfileExceptionFunc throw_callback, MonoProfileMethodFunc exc_method_leave, MonoProfileExceptionClauseFunc clause_callback)
361 {
362         if (!prof_list)
363                 return;
364         prof_list->exception_throw_cb = throw_callback;
365         prof_list->exception_method_leave_cb = exc_method_leave;
366         prof_list->exception_clause_cb = clause_callback;
367 }
368
369 void 
370 mono_profiler_install_coverage_filter (MonoProfileCoverageFilterFunc callback)
371 {
372         if (!prof_list)
373                 return;
374         prof_list->coverage_filter_cb = callback;
375 }
376
377 void 
378 mono_profiler_install_appdomain   (MonoProfileAppDomainFunc start_load, MonoProfileAppDomainResult end_load,
379                                    MonoProfileAppDomainFunc start_unload, MonoProfileAppDomainFunc end_unload)
380
381 {
382         if (!prof_list)
383                 return;
384         prof_list->domain_start_load = start_load;
385         prof_list->domain_end_load = end_load;
386         prof_list->domain_start_unload = start_unload;
387         prof_list->domain_end_unload = end_unload;
388 }
389
390 void
391 mono_profiler_install_appdomain_name (MonoProfileAppDomainFriendlyNameFunc domain_name_cb)
392 {
393         if (!prof_list)
394                 return;
395
396         prof_list->domain_name = domain_name_cb;
397 }
398
399 void
400 mono_profiler_install_context (MonoProfileContextFunc load, MonoProfileContextFunc unload)
401 {
402         if (!prof_list)
403                 return;
404
405         prof_list->context_load = load;
406         prof_list->context_unload = unload;
407 }
408
409 void 
410 mono_profiler_install_assembly    (MonoProfileAssemblyFunc start_load, MonoProfileAssemblyResult end_load,
411                                    MonoProfileAssemblyFunc start_unload, MonoProfileAssemblyFunc end_unload)
412 {
413         if (!prof_list)
414                 return;
415         prof_list->assembly_start_load = start_load;
416         prof_list->assembly_end_load = end_load;
417         prof_list->assembly_start_unload = start_unload;
418         prof_list->assembly_end_unload = end_unload;
419 }
420
421 void 
422 mono_profiler_install_module      (MonoProfileModuleFunc start_load, MonoProfileModuleResult end_load,
423                                    MonoProfileModuleFunc start_unload, MonoProfileModuleFunc end_unload)
424 {
425         if (!prof_list)
426                 return;
427         prof_list->module_start_load = start_load;
428         prof_list->module_end_load = end_load;
429         prof_list->module_start_unload = start_unload;
430         prof_list->module_end_unload = end_unload;
431 }
432
433 void
434 mono_profiler_install_class       (MonoProfileClassFunc start_load, MonoProfileClassResult end_load,
435                                    MonoProfileClassFunc start_unload, MonoProfileClassFunc end_unload)
436 {
437         if (!prof_list)
438                 return;
439         prof_list->class_start_load = start_load;
440         prof_list->class_end_load = end_load;
441         prof_list->class_start_unload = start_unload;
442         prof_list->class_end_unload = end_unload;
443 }
444
445 void
446 mono_profiler_method_enter (MonoMethod *method)
447 {
448         ProfilerDesc *prof;
449         for (prof = prof_list; prof; prof = prof->next) {
450                 if ((prof->events & MONO_PROFILE_ENTER_LEAVE) && prof->method_enter)
451                         prof->method_enter (prof->profiler, method);
452         }
453 }
454
455 void
456 mono_profiler_method_leave (MonoMethod *method)
457 {
458         ProfilerDesc *prof;
459         for (prof = prof_list; prof; prof = prof->next) {
460                 if ((prof->events & MONO_PROFILE_ENTER_LEAVE) && prof->method_leave)
461                         prof->method_leave (prof->profiler, method);
462         }
463 }
464
465 void 
466 mono_profiler_method_jit (MonoMethod *method)
467 {
468         ProfilerDesc *prof;
469         for (prof = prof_list; prof; prof = prof->next) {
470                 if ((prof->events & MONO_PROFILE_JIT_COMPILATION) && prof->jit_start)
471                         prof->jit_start (prof->profiler, method);
472         }
473 }
474
475 void 
476 mono_profiler_method_end_jit (MonoMethod *method, MonoJitInfo* jinfo, int result)
477 {
478         ProfilerDesc *prof;
479         for (prof = prof_list; prof; prof = prof->next) {
480                 if ((prof->events & MONO_PROFILE_JIT_COMPILATION)) {
481                         if (prof->jit_end)
482                                 prof->jit_end (prof->profiler, method, result);
483                         if (prof->jit_end2)
484                                 prof->jit_end2 (prof->profiler, method, jinfo, result);
485                 }
486         }
487 }
488
489 void 
490 mono_profiler_method_free (MonoMethod *method)
491 {
492         ProfilerDesc *prof;
493         for (prof = prof_list; prof; prof = prof->next) {
494                 if ((prof->events & MONO_PROFILE_METHOD_EVENTS) && prof->method_free)
495                         prof->method_free (prof->profiler, method);
496         }
497 }
498
499 void
500 mono_profiler_method_start_invoke (MonoMethod *method)
501 {
502         ProfilerDesc *prof;
503         for (prof = prof_list; prof; prof = prof->next) {
504                 if ((prof->events & MONO_PROFILE_METHOD_EVENTS) && prof->method_start_invoke)
505                         prof->method_start_invoke (prof->profiler, method);
506         }
507 }
508
509 void
510 mono_profiler_method_end_invoke (MonoMethod *method)
511 {
512         ProfilerDesc *prof;
513         for (prof = prof_list; prof; prof = prof->next) {
514                 if ((prof->events & MONO_PROFILE_METHOD_EVENTS) && prof->method_end_invoke)
515                         prof->method_end_invoke (prof->profiler, method);
516         }
517 }
518
519 void 
520 mono_profiler_code_transition (MonoMethod *method, int result)
521 {
522         ProfilerDesc *prof;
523         for (prof = prof_list; prof; prof = prof->next) {
524                 if ((prof->events & MONO_PROFILE_TRANSITIONS) && prof->man_unman_transition)
525                         prof->man_unman_transition (prof->profiler, method, result);
526         }
527 }
528
529 void 
530 mono_profiler_allocation (MonoObject *obj)
531 {
532         ProfilerDesc *prof;
533         for (prof = prof_list; prof; prof = prof->next) {
534                 if ((prof->events & MONO_PROFILE_ALLOCATIONS) && prof->allocation_cb)
535                         prof->allocation_cb (prof->profiler, obj, obj->vtable->klass);
536         }
537 }
538
539 void
540 mono_profiler_monitor_event      (MonoObject *obj, MonoProfilerMonitorEvent event) {
541         ProfilerDesc *prof;
542         for (prof = prof_list; prof; prof = prof->next) {
543                 if ((prof->events & MONO_PROFILE_MONITOR_EVENTS) && prof->monitor_event_cb)
544                         prof->monitor_event_cb (prof->profiler, obj, event);
545         }
546 }
547
548 void
549 mono_profiler_stat_hit (guchar *ip, void *context)
550 {
551         ProfilerDesc *prof;
552         for (prof = prof_list; prof; prof = prof->next) {
553                 if ((prof->events & MONO_PROFILE_STATISTICAL) && prof->statistical_cb)
554                         prof->statistical_cb (prof->profiler, ip, context);
555         }
556 }
557
558 void
559 mono_profiler_stat_call_chain (int call_chain_depth, guchar **ips, void *context)
560 {
561         ProfilerDesc *prof;
562         for (prof = prof_list; prof; prof = prof->next) {
563                 if ((prof->events & MONO_PROFILE_STATISTICAL) && prof->statistical_call_chain_cb)
564                         prof->statistical_call_chain_cb (prof->profiler, call_chain_depth, ips, context);
565         }
566 }
567
568 void
569 mono_profiler_exception_thrown (MonoObject *exception)
570 {
571         ProfilerDesc *prof;
572         for (prof = prof_list; prof; prof = prof->next) {
573                 if ((prof->events & MONO_PROFILE_EXCEPTIONS) && prof->exception_throw_cb)
574                         prof->exception_throw_cb (prof->profiler, exception);
575         }
576 }
577
578 void
579 mono_profiler_exception_method_leave (MonoMethod *method)
580 {
581         ProfilerDesc *prof;
582         for (prof = prof_list; prof; prof = prof->next) {
583                 if ((prof->events & MONO_PROFILE_EXCEPTIONS) && prof->exception_method_leave_cb)
584                         prof->exception_method_leave_cb (prof->profiler, method);
585         }
586 }
587
588 void
589 mono_profiler_exception_clause_handler (MonoMethod *method, int clause_type, int clause_num)
590 {
591         ProfilerDesc *prof;
592         for (prof = prof_list; prof; prof = prof->next) {
593                 if ((prof->events & MONO_PROFILE_EXCEPTIONS) && prof->exception_clause_cb)
594                         prof->exception_clause_cb (prof->profiler, method, clause_type, clause_num);
595         }
596 }
597
598 void
599 mono_profiler_thread_start (gsize tid)
600 {
601         ProfilerDesc *prof;
602         for (prof = prof_list; prof; prof = prof->next) {
603                 if ((prof->events & MONO_PROFILE_THREADS) && prof->thread_start)
604                         prof->thread_start (prof->profiler, tid);
605         }
606 }
607
608 void 
609 mono_profiler_thread_end (gsize tid)
610 {
611         ProfilerDesc *prof;
612         for (prof = prof_list; prof; prof = prof->next) {
613                 if ((prof->events & MONO_PROFILE_THREADS) && prof->thread_end)
614                         prof->thread_end (prof->profiler, tid);
615         }
616 }
617
618 void
619 mono_profiler_thread_name (gsize tid, const char *name)
620 {
621         ProfilerDesc *prof;
622         for (prof = prof_list; prof; prof = prof->next) {
623                 if ((prof->events & MONO_PROFILE_THREADS) && prof->thread_name)
624                         prof->thread_name (prof->profiler, tid, name);
625         }
626 }
627
628 void 
629 mono_profiler_assembly_event  (MonoAssembly *assembly, int code)
630 {
631         ProfilerDesc *prof;
632         for (prof = prof_list; prof; prof = prof->next) {
633                 if (!(prof->events & MONO_PROFILE_ASSEMBLY_EVENTS))
634                         continue;
635
636                 switch (code) {
637                 case MONO_PROFILE_START_LOAD:
638                         if (prof->assembly_start_load)
639                                 prof->assembly_start_load (prof->profiler, assembly);
640                         break;
641                 case MONO_PROFILE_START_UNLOAD:
642                         if (prof->assembly_start_unload)
643                                 prof->assembly_start_unload (prof->profiler, assembly);
644                         break;
645                 case MONO_PROFILE_END_UNLOAD:
646                         if (prof->assembly_end_unload)
647                                 prof->assembly_end_unload (prof->profiler, assembly);
648                         break;
649                 default:
650                         g_assert_not_reached ();
651                 }
652         }
653 }
654
655 void 
656 mono_profiler_assembly_loaded (MonoAssembly *assembly, int result)
657 {
658         ProfilerDesc *prof;
659         for (prof = prof_list; prof; prof = prof->next) {
660                 if ((prof->events & MONO_PROFILE_ASSEMBLY_EVENTS) && prof->assembly_end_load)
661                         prof->assembly_end_load (prof->profiler, assembly, result);
662         }
663 }
664
665 void mono_profiler_iomap (char *report, const char *pathname, const char *new_pathname)
666 {
667         ProfilerDesc *prof;
668         for (prof = prof_list; prof; prof = prof->next) {
669                 if ((prof->events & MONO_PROFILE_IOMAP_EVENTS) && prof->iomap_cb)
670                         prof->iomap_cb (prof->profiler, report, pathname, new_pathname);
671         }
672 }
673
674 void 
675 mono_profiler_module_event  (MonoImage *module, int code)
676 {
677         ProfilerDesc *prof;
678         for (prof = prof_list; prof; prof = prof->next) {
679                 if (!(prof->events & MONO_PROFILE_MODULE_EVENTS))
680                         continue;
681
682                 switch (code) {
683                 case MONO_PROFILE_START_LOAD:
684                         if (prof->module_start_load)
685                                 prof->module_start_load (prof->profiler, module);
686                         break;
687                 case MONO_PROFILE_START_UNLOAD:
688                         if (prof->module_start_unload)
689                                 prof->module_start_unload (prof->profiler, module);
690                         break;
691                 case MONO_PROFILE_END_UNLOAD:
692                         if (prof->module_end_unload)
693                                 prof->module_end_unload (prof->profiler, module);
694                         break;
695                 default:
696                         g_assert_not_reached ();
697                 }
698         }
699 }
700
701 void 
702 mono_profiler_module_loaded (MonoImage *module, int result)
703 {
704         ProfilerDesc *prof;
705         for (prof = prof_list; prof; prof = prof->next) {
706                 if ((prof->events & MONO_PROFILE_MODULE_EVENTS) && prof->module_end_load)
707                         prof->module_end_load (prof->profiler, module, result);
708         }
709 }
710
711 void 
712 mono_profiler_class_event  (MonoClass *klass, int code)
713 {
714         ProfilerDesc *prof;
715         for (prof = prof_list; prof; prof = prof->next) {
716                 if (!(prof->events & MONO_PROFILE_CLASS_EVENTS))
717                         continue;
718
719                 switch (code) {
720                 case MONO_PROFILE_START_LOAD:
721                         if (prof->class_start_load)
722                                 prof->class_start_load (prof->profiler, klass);
723                         break;
724                 case MONO_PROFILE_START_UNLOAD:
725                         if (prof->class_start_unload)
726                                 prof->class_start_unload (prof->profiler, klass);
727                         break;
728                 case MONO_PROFILE_END_UNLOAD:
729                         if (prof->class_end_unload)
730                                 prof->class_end_unload (prof->profiler, klass);
731                         break;
732                 default:
733                         g_assert_not_reached ();
734                 }
735         }
736 }
737
738 void 
739 mono_profiler_class_loaded (MonoClass *klass, int result)
740 {
741         ProfilerDesc *prof;
742         for (prof = prof_list; prof; prof = prof->next) {
743                 if ((prof->events & MONO_PROFILE_CLASS_EVENTS) && prof->class_end_load)
744                         prof->class_end_load (prof->profiler, klass, result);
745         }
746 }
747
748 void 
749 mono_profiler_appdomain_event  (MonoDomain *domain, int code)
750 {
751         ProfilerDesc *prof;
752         for (prof = prof_list; prof; prof = prof->next) {
753                 if (!(prof->events & MONO_PROFILE_APPDOMAIN_EVENTS))
754                         continue;
755
756                 switch (code) {
757                 case MONO_PROFILE_START_LOAD:
758                         if (prof->domain_start_load)
759                                 prof->domain_start_load (prof->profiler, domain);
760                         break;
761                 case MONO_PROFILE_START_UNLOAD:
762                         if (prof->domain_start_unload)
763                                 prof->domain_start_unload (prof->profiler, domain);
764                         break;
765                 case MONO_PROFILE_END_UNLOAD:
766                         if (prof->domain_end_unload)
767                                 prof->domain_end_unload (prof->profiler, domain);
768                         break;
769                 default:
770                         g_assert_not_reached ();
771                 }
772         }
773 }
774
775 void 
776 mono_profiler_appdomain_loaded (MonoDomain *domain, int result)
777 {
778         ProfilerDesc *prof;
779         for (prof = prof_list; prof; prof = prof->next) {
780                 if ((prof->events & MONO_PROFILE_APPDOMAIN_EVENTS) && prof->domain_end_load)
781                         prof->domain_end_load (prof->profiler, domain, result);
782         }
783 }
784
785 void
786 mono_profiler_appdomain_name (MonoDomain *domain, const char *name)
787 {
788         for (ProfilerDesc *prof = prof_list; prof; prof = prof->next)
789                 if ((prof->events & MONO_PROFILE_APPDOMAIN_EVENTS) && prof->domain_name)
790                         prof->domain_name (prof->profiler, domain, name);
791 }
792
793 void
794 mono_profiler_context_loaded (MonoAppContext *context)
795 {
796         for (ProfilerDesc *prof = prof_list; prof; prof = prof->next)
797                 if ((prof->events & MONO_PROFILE_CONTEXT_EVENTS) && prof->context_load)
798                         prof->context_load (prof->profiler, context);
799 }
800
801 void
802 mono_profiler_context_unloaded (MonoAppContext *context)
803 {
804         for (ProfilerDesc *prof = prof_list; prof; prof = prof->next)
805                 if ((prof->events & MONO_PROFILE_CONTEXT_EVENTS) && prof->context_unload)
806                         prof->context_unload (prof->profiler, context);
807 }
808
809 void 
810 mono_profiler_shutdown (void)
811 {
812         ProfilerDesc *prof;
813         for (prof = prof_list; prof; prof = prof->next) {
814                 if (prof->shutdown_callback)
815                         prof->shutdown_callback (prof->profiler);
816         }
817
818         mono_profiler_set_events ((MonoProfileFlags)0);
819 }
820
821 void
822 mono_profiler_gc_heap_resize (gint64 new_size)
823 {
824         ProfilerDesc *prof;
825         for (prof = prof_list; prof; prof = prof->next) {
826                 if ((prof->events & MONO_PROFILE_GC) && prof->gc_heap_resize)
827                         prof->gc_heap_resize (prof->profiler, new_size);
828         }
829 }
830
831 void
832 mono_profiler_gc_event (MonoGCEvent event, int generation)
833 {
834         ProfilerDesc *prof;
835         for (prof = prof_list; prof; prof = prof->next) {
836                 if ((prof->events & MONO_PROFILE_GC) && prof->gc_event)
837                         prof->gc_event (prof->profiler, event, generation);
838         }
839 }
840
841 void
842 mono_profiler_gc_moves (void **objects, int num)
843 {
844         ProfilerDesc *prof;
845         for (prof = prof_list; prof; prof = prof->next) {
846                 if ((prof->events & MONO_PROFILE_GC_MOVES) && prof->gc_moves)
847                         prof->gc_moves (prof->profiler, objects, num);
848         }
849 }
850
851 void
852 mono_profiler_gc_handle (int op, int type, uintptr_t handle, MonoObject *obj)
853 {
854         ProfilerDesc *prof;
855         for (prof = prof_list; prof; prof = prof->next) {
856                 if ((prof->events & MONO_PROFILE_GC_ROOTS) && prof->gc_handle)
857                         prof->gc_handle (prof->profiler, op, type, handle, obj);
858         }
859 }
860
861 void
862 mono_profiler_gc_roots (int num, void **objects, int *root_types, uintptr_t *extra_info)
863 {
864         ProfilerDesc *prof;
865         for (prof = prof_list; prof; prof = prof->next) {
866                 if ((prof->events & MONO_PROFILE_GC_ROOTS) && prof->gc_roots)
867                         prof->gc_roots (prof->profiler, num, objects, root_types, extra_info);
868         }
869 }
870
871 void
872 mono_profiler_install_gc (MonoProfileGCFunc callback, MonoProfileGCResizeFunc heap_resize_callback)
873 {
874         mono_gc_enable_events ();
875         if (!prof_list)
876                 return;
877         prof_list->gc_event = callback;
878         prof_list->gc_heap_resize = heap_resize_callback;
879 }
880
881 /**
882  * mono_profiler_install_gc_moves:
883  * @callback: callback function
884  *
885  * Install the @callback function that the GC will call when moving objects.
886  * The callback receives an array of pointers and the number of elements
887  * in the array. Every even element in the array is the original object location
888  * and the following odd element is the new location of the object in memory.
889  * So the number of elements argument will always be a multiple of 2.
890  * Since this callback happens during the GC, it is a restricted environment:
891  * no locks can be taken and the object pointers can be inspected only once
892  * the GC is finished (of course the original location pointers will not
893  * point to valid objects anymore).
894  */
895 void
896 mono_profiler_install_gc_moves (MonoProfileGCMoveFunc callback)
897 {
898         if (!prof_list)
899                 return;
900         prof_list->gc_moves = callback;
901 }
902
903 /**
904  * mono_profiler_install_gc_roots:
905  * @handle_callback: callback function
906  * @roots_callback: callback function
907  *
908  * Install the @handle_callback function that the GC will call when GC
909  * handles are created or destroyed.
910  * The callback receives an operation, which is either #MONO_PROFILER_GC_HANDLE_CREATED
911  * or #MONO_PROFILER_GC_HANDLE_DESTROYED, the handle type, the handle value and the
912  * object pointer, if present.
913  * Install the @roots_callback function that the GC will call when tracing
914  * the roots for a collection.
915  * The callback receives the number of elements and three arrays: an array
916  * of objects, an array of root types and flags and an array of extra info.
917  * The size of each array is given by the first argument.
918  */
919 void
920 mono_profiler_install_gc_roots (MonoProfileGCHandleFunc handle_callback, MonoProfileGCRootFunc roots_callback)
921 {
922         if (!prof_list)
923                 return;
924         prof_list->gc_handle = handle_callback;
925         prof_list->gc_roots = roots_callback;
926 }
927
928 void
929 mono_profiler_install_runtime_initialized (MonoProfileFunc runtime_initialized_callback)
930 {
931         if (!prof_list)
932                 return;
933         prof_list->runtime_initialized_event = runtime_initialized_callback;
934 }
935
936 void
937 mono_profiler_runtime_initialized (void) {
938         ProfilerDesc *prof;
939         for (prof = prof_list; prof; prof = prof->next) {
940                 if (prof->runtime_initialized_event)
941                         prof->runtime_initialized_event (prof->profiler);
942         }
943 }
944
945 void
946 mono_profiler_install_code_chunk_new (MonoProfilerCodeChunkNew callback) {
947         if (!prof_list)
948                 return;
949         prof_list->code_chunk_new = callback;
950 }
951 void
952 mono_profiler_code_chunk_new (gpointer chunk, int size) {
953         ProfilerDesc *prof;
954         for (prof = prof_list; prof; prof = prof->next) {
955                 if (prof->code_chunk_new)
956                         prof->code_chunk_new (prof->profiler, chunk, size);
957         }
958 }
959
960 void
961 mono_profiler_install_code_chunk_destroy (MonoProfilerCodeChunkDestroy callback) {
962         if (!prof_list)
963                 return;
964         prof_list->code_chunk_destroy = callback;
965 }
966 void
967 mono_profiler_code_chunk_destroy (gpointer chunk) {
968         ProfilerDesc *prof;
969         for (prof = prof_list; prof; prof = prof->next) {
970                 if (prof->code_chunk_destroy)
971                         prof->code_chunk_destroy (prof->profiler, chunk);
972         }
973 }
974
975 void
976 mono_profiler_install_code_buffer_new (MonoProfilerCodeBufferNew callback) {
977         if (!prof_list)
978                 return;
979         prof_list->code_buffer_new = callback;
980 }
981
982 void
983 mono_profiler_install_iomap (MonoProfileIomapFunc callback)
984 {
985         if (!prof_list)
986                 return;
987         prof_list->iomap_cb = callback;
988 }
989
990 void
991 mono_profiler_code_buffer_new (gpointer buffer, int size, MonoProfilerCodeBufferType type, gconstpointer data) {
992         ProfilerDesc *prof;
993         for (prof = prof_list; prof; prof = prof->next) {
994                 if (prof->code_buffer_new)
995                         prof->code_buffer_new (prof->profiler, buffer, size, type, (void*)data);
996         }
997 }
998
999 static GHashTable *coverage_hash = NULL;
1000
1001 MonoProfileCoverageInfo* 
1002 mono_profiler_coverage_alloc (MonoMethod *method, int entries)
1003 {
1004         MonoProfileCoverageInfo *res;
1005         int instrument = FALSE;
1006         ProfilerDesc *prof;
1007
1008         for (prof = prof_list; prof; prof = prof->next) {
1009                 /* note that we call the filter on all the profilers even if just
1010                  * a single one would be enough to instrument a method
1011                  */
1012                 if (prof->coverage_filter_cb)
1013                         if (prof->coverage_filter_cb (prof->profiler, method))
1014                                 instrument = TRUE;
1015         }
1016         if (!instrument)
1017                 return NULL;
1018
1019         mono_profiler_coverage_lock ();
1020         if (!coverage_hash)
1021                 coverage_hash = g_hash_table_new (NULL, NULL);
1022
1023         res = (MonoProfileCoverageInfo *)g_malloc0 (sizeof (MonoProfileCoverageInfo) + sizeof (void*) * 2 * entries);
1024
1025         res->entries = entries;
1026
1027         g_hash_table_insert (coverage_hash, method, res);
1028         mono_profiler_coverage_unlock ();
1029
1030         return res;
1031 }
1032
1033 /* safe only when the method antive code has been unloaded */
1034 void
1035 mono_profiler_coverage_free (MonoMethod *method)
1036 {
1037         MonoProfileCoverageInfo* info;
1038
1039         mono_profiler_coverage_lock ();
1040         if (!coverage_hash) {
1041                 mono_profiler_coverage_unlock ();
1042                 return;
1043         }
1044
1045         info = (MonoProfileCoverageInfo *)g_hash_table_lookup (coverage_hash, method);
1046         if (info) {
1047                 g_free (info);
1048                 g_hash_table_remove (coverage_hash, method);
1049         }
1050         mono_profiler_coverage_unlock ();
1051 }
1052
1053 /**
1054  * mono_profiler_coverage_get:
1055  * @prof: The profiler handle, installed with mono_profiler_install
1056  * @method: the method to gather information from.
1057  * @func: A routine that will be called back with the results
1058  *
1059  * If the MONO_PROFILER_INS_COVERAGE flag was active during JIT compilation
1060  * it is posisble to obtain coverage information about a give method.
1061  *
1062  * The function @func will be invoked repeatedly with instances of the
1063  * MonoProfileCoverageEntry structure.
1064  */
1065 void 
1066 mono_profiler_coverage_get (MonoProfiler *prof, MonoMethod *method, MonoProfileCoverageFunc func)
1067 {
1068         MonoError error;
1069         MonoProfileCoverageInfo* info = NULL;
1070         int i, offset;
1071         guint32 code_size;
1072         const unsigned char *start, *end, *cil_code;
1073         MonoMethodHeader *header;
1074         MonoProfileCoverageEntry entry;
1075         MonoDebugMethodInfo *debug_minfo;
1076
1077         mono_profiler_coverage_lock ();
1078         if (coverage_hash)
1079                 info = (MonoProfileCoverageInfo *)g_hash_table_lookup (coverage_hash, method);
1080         mono_profiler_coverage_unlock ();
1081
1082         if (!info)
1083                 return;
1084
1085         header = mono_method_get_header_checked (method, &error);
1086         mono_error_assert_ok (&error);
1087         start = mono_method_header_get_code (header, &code_size, NULL);
1088         debug_minfo = mono_debug_lookup_method (method);
1089
1090         end = start + code_size;
1091         for (i = 0; i < info->entries; ++i) {
1092                 cil_code = info->data [i].cil_code;
1093                 if (cil_code && cil_code >= start && cil_code < end) {
1094                         char *fname = NULL;
1095                         offset = cil_code - start;
1096                         entry.iloffset = offset;
1097                         entry.method = method;
1098                         entry.counter = info->data [i].count;
1099                         entry.line = entry.col = 1;
1100                         entry.filename = NULL;
1101                         if (debug_minfo) {
1102                                 MonoDebugSourceLocation *location;
1103
1104                                 location = mono_debug_symfile_lookup_location (debug_minfo, offset);
1105                                 if (location) {
1106                                         entry.line = location->row;
1107                                         entry.col = location->column;
1108                                         entry.filename = fname = g_strdup (location->source_file);
1109                                         mono_debug_free_source_location (location);
1110                                 }
1111                         }
1112
1113                         func (prof, &entry);
1114                         g_free (fname);
1115                 }
1116         }
1117         mono_metadata_free_mh (header);
1118 }
1119
1120 typedef void (*ProfilerInitializer) (const char*);
1121 #define INITIALIZER_NAME "mono_profiler_startup"
1122
1123
1124 static gboolean
1125 load_profiler (MonoDl *pmodule, const char *desc, const char *symbol)
1126 {
1127         char *err;
1128         ProfilerInitializer func;
1129
1130         if (!pmodule)
1131                 return FALSE;
1132
1133         if ((err = mono_dl_symbol (pmodule, symbol, (gpointer *) &func))) {
1134                 g_free (err);
1135                 return FALSE;
1136         } else {
1137                 func (desc);
1138         }
1139         return TRUE;
1140 }
1141
1142 static gboolean
1143 load_embedded_profiler (const char *desc, const char *name)
1144 {
1145         char *err = NULL;
1146         char *symbol;
1147         MonoDl *pmodule = NULL;
1148         gboolean result;
1149
1150         pmodule = mono_dl_open (NULL, MONO_DL_LAZY, &err);
1151         if (!pmodule) {
1152                 g_warning ("Could not open main executable (%s)", err);
1153                 g_free (err);
1154                 return FALSE;
1155         }
1156
1157         symbol = g_strdup_printf (INITIALIZER_NAME "_%s", name);
1158         result = load_profiler (pmodule, desc, symbol);
1159         g_free (symbol);
1160
1161         return result;
1162 }
1163
1164 static gboolean
1165 load_profiler_from_directory (const char *directory, const char *libname, const char *desc)
1166 {
1167         MonoDl *pmodule = NULL;
1168         char* path;
1169         char *err;
1170         void *iter;
1171
1172         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Attempting to load profiler %s from %s (desc %s)", libname, directory, desc);
1173
1174         iter = NULL;
1175         err = NULL;
1176         while ((path = mono_dl_build_path (directory, libname, &iter))) {
1177                 pmodule = mono_dl_open (path, MONO_DL_LAZY, &err);
1178                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Attempting to load profiler: %s %ssuccessful, err: %s", path, pmodule?"":"not ", err);
1179                 g_free (path);
1180                 g_free (err);
1181                 if (pmodule)
1182                         return load_profiler (pmodule, desc, INITIALIZER_NAME);
1183         }
1184                 
1185         return FALSE;
1186 }
1187
1188 static gboolean
1189 load_profiler_from_mono_instalation (const char *libname, const char *desc)
1190 {
1191         char *err = NULL;
1192         MonoDl *pmodule = mono_dl_open_runtime_lib (libname, MONO_DL_LAZY, &err);
1193         g_free (err);
1194         if (pmodule)
1195                 return load_profiler (pmodule, desc, INITIALIZER_NAME);
1196         return FALSE;
1197 }
1198
1199 /**
1200  * mono_profiler_load:
1201  * @desc: arguments to configure the profiler
1202  *
1203  * Invoke this method to initialize the profiler.   This will drive the
1204  * loading of the internal ("default") or any external profilers.
1205  *
1206  * This routine is invoked by Mono's driver, but must be called manually
1207  * if you embed Mono into your application.
1208  */
1209 void 
1210 mono_profiler_load (const char *desc)
1211 {
1212         char *cdesc = NULL;
1213         mono_gc_base_init ();
1214
1215         if (!desc || (strcmp ("default", desc) == 0)) {
1216                 desc = "log:report";
1217         }
1218         /* we keep command-line compat with the old version here */
1219         if (strncmp (desc, "default:", 8) == 0) {
1220                 gchar **args, **ptr;
1221                 GString *str = g_string_new ("log:report");
1222                 args = g_strsplit (desc + 8, ",", -1);
1223                 for (ptr = args; ptr && *ptr; ptr++) {
1224                         const char *arg = *ptr;
1225
1226                         if (!strcmp (arg, "time"))
1227                                 g_string_append (str, ",calls");
1228                         else if (!strcmp (arg, "alloc"))
1229                                 g_string_append (str, ",alloc");
1230                         else if (!strcmp (arg, "stat"))
1231                                 g_string_append (str, ",sample");
1232                         else if (!strcmp (arg, "jit"))
1233                                 continue; /* accept and do nothing */
1234                         else if (strncmp (arg, "file=", 5) == 0) {
1235                                 g_string_append_printf (str, ",output=%s", arg + 5);
1236                         } else {
1237                                 fprintf (stderr, "profiler : Unknown argument '%s'.\n", arg);
1238                                 return;
1239                         }
1240                 }
1241                 desc = cdesc = g_string_free (str, FALSE);
1242         }
1243         {
1244                 const char* col = strchr (desc, ':');
1245                 char* libname;
1246                 char *mname;
1247                 gboolean res = FALSE;
1248
1249                 if (col != NULL) {
1250                         mname = (char *)g_memdup (desc, col - desc + 1);
1251                         mname [col - desc] = 0;
1252                 } else {
1253                         mname = g_strdup (desc);
1254                 }
1255                 if (!load_embedded_profiler (desc, mname)) {
1256                         libname = g_strdup_printf ("mono-profiler-%s", mname);
1257                         char *profiler_lib_dir = getenv ("MONO_PROFILER_LIB_DIR");
1258                         if (profiler_lib_dir)
1259                                 res = load_profiler_from_directory (profiler_lib_dir, libname, desc);
1260                         if (!res && mono_config_get_assemblies_dir ())
1261                                 res = load_profiler_from_directory (mono_assembly_getrootdir (), libname, desc);
1262                         if (!res)
1263                                 res = load_profiler_from_directory (NULL, libname, desc);
1264                         if (!res)
1265                                 res = load_profiler_from_mono_instalation (libname, desc);
1266                         if (!res)
1267                                 g_warning ("The '%s' profiler wasn't found in the main executable nor could it be loaded from '%s'.", mname, libname);
1268                         g_free (libname);
1269                 }
1270                 g_free (mname);
1271         }
1272         g_free (cdesc);
1273 }
1274