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