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