Merge pull request #1168 from esdrubal/iriparsing
[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 void 
277 mono_profiler_install_statistical (MonoProfileStatFunc callback)
278 {
279         if (!prof_list)
280                 return;
281         prof_list->statistical_cb = callback;
282 }
283
284 void 
285 mono_profiler_install_statistical_call_chain (MonoProfileStatCallChainFunc callback, int call_chain_depth, MonoProfilerCallChainStrategy call_chain_strategy) {
286         if (!prof_list)
287                 return;
288         if (call_chain_depth > MONO_PROFILER_MAX_STAT_CALL_CHAIN_DEPTH) {
289                 call_chain_depth = MONO_PROFILER_MAX_STAT_CALL_CHAIN_DEPTH;
290         }
291         if ((call_chain_strategy >= MONO_PROFILER_CALL_CHAIN_INVALID) || (call_chain_strategy < MONO_PROFILER_CALL_CHAIN_NONE)) {
292                 call_chain_strategy = MONO_PROFILER_CALL_CHAIN_NONE;
293         }
294         prof_list->statistical_call_chain_cb = callback;
295         prof_list->statistical_call_chain_depth = call_chain_depth;
296         prof_list->statistical_call_chain_strategy = call_chain_strategy;
297 }
298
299 int
300 mono_profiler_stat_get_call_chain_depth (void) {
301         if (prof_list && prof_list->statistical_call_chain_cb != NULL) {
302                 return prof_list->statistical_call_chain_depth;
303         } else {
304                 return 0;
305         }
306 }
307
308 MonoProfilerCallChainStrategy
309 mono_profiler_stat_get_call_chain_strategy (void) {
310         if (prof_list && prof_list->statistical_call_chain_cb != NULL) {
311                 return prof_list->statistical_call_chain_strategy;
312         } else {
313                 return MONO_PROFILER_CALL_CHAIN_NONE;
314         }
315 }
316
317 void mono_profiler_install_exception (MonoProfileExceptionFunc throw_callback, MonoProfileMethodFunc exc_method_leave, MonoProfileExceptionClauseFunc clause_callback)
318 {
319         if (!prof_list)
320                 return;
321         prof_list->exception_throw_cb = throw_callback;
322         prof_list->exception_method_leave_cb = exc_method_leave;
323         prof_list->exception_clause_cb = clause_callback;
324 }
325
326 void 
327 mono_profiler_install_coverage_filter (MonoProfileCoverageFilterFunc callback)
328 {
329         if (!prof_list)
330                 return;
331         prof_list->coverage_filter_cb = callback;
332 }
333
334 void 
335 mono_profiler_install_appdomain   (MonoProfileAppDomainFunc start_load, MonoProfileAppDomainResult end_load,
336                                    MonoProfileAppDomainFunc start_unload, MonoProfileAppDomainFunc end_unload)
337
338 {
339         if (!prof_list)
340                 return;
341         prof_list->domain_start_load = start_load;
342         prof_list->domain_end_load = end_load;
343         prof_list->domain_start_unload = start_unload;
344         prof_list->domain_end_unload = end_unload;
345 }
346
347 void 
348 mono_profiler_install_assembly    (MonoProfileAssemblyFunc start_load, MonoProfileAssemblyResult end_load,
349                                    MonoProfileAssemblyFunc start_unload, MonoProfileAssemblyFunc end_unload)
350 {
351         if (!prof_list)
352                 return;
353         prof_list->assembly_start_load = start_load;
354         prof_list->assembly_end_load = end_load;
355         prof_list->assembly_start_unload = start_unload;
356         prof_list->assembly_end_unload = end_unload;
357 }
358
359 void 
360 mono_profiler_install_module      (MonoProfileModuleFunc start_load, MonoProfileModuleResult end_load,
361                                    MonoProfileModuleFunc start_unload, MonoProfileModuleFunc end_unload)
362 {
363         if (!prof_list)
364                 return;
365         prof_list->module_start_load = start_load;
366         prof_list->module_end_load = end_load;
367         prof_list->module_start_unload = start_unload;
368         prof_list->module_end_unload = end_unload;
369 }
370
371 void
372 mono_profiler_install_class       (MonoProfileClassFunc start_load, MonoProfileClassResult end_load,
373                                    MonoProfileClassFunc start_unload, MonoProfileClassFunc end_unload)
374 {
375         if (!prof_list)
376                 return;
377         prof_list->class_start_load = start_load;
378         prof_list->class_end_load = end_load;
379         prof_list->class_start_unload = start_unload;
380         prof_list->class_end_unload = end_unload;
381 }
382
383 void
384 mono_profiler_method_enter (MonoMethod *method)
385 {
386         ProfilerDesc *prof;
387         for (prof = prof_list; prof; prof = prof->next) {
388                 if ((prof->events & MONO_PROFILE_ENTER_LEAVE) && prof->method_enter)
389                         prof->method_enter (prof->profiler, method);
390         }
391 }
392
393 void
394 mono_profiler_method_leave (MonoMethod *method)
395 {
396         ProfilerDesc *prof;
397         for (prof = prof_list; prof; prof = prof->next) {
398                 if ((prof->events & MONO_PROFILE_ENTER_LEAVE) && prof->method_leave)
399                         prof->method_leave (prof->profiler, method);
400         }
401 }
402
403 void 
404 mono_profiler_method_jit (MonoMethod *method)
405 {
406         ProfilerDesc *prof;
407         for (prof = prof_list; prof; prof = prof->next) {
408                 if ((prof->events & MONO_PROFILE_JIT_COMPILATION) && prof->jit_start)
409                         prof->jit_start (prof->profiler, method);
410         }
411 }
412
413 void 
414 mono_profiler_method_end_jit (MonoMethod *method, MonoJitInfo* jinfo, int result)
415 {
416         ProfilerDesc *prof;
417         for (prof = prof_list; prof; prof = prof->next) {
418                 if ((prof->events & MONO_PROFILE_JIT_COMPILATION)) {
419                         if (prof->jit_end)
420                                 prof->jit_end (prof->profiler, method, result);
421                         if (prof->jit_end2)
422                                 prof->jit_end2 (prof->profiler, method, jinfo, result);
423                 }
424         }
425 }
426
427 void 
428 mono_profiler_method_free (MonoMethod *method)
429 {
430         ProfilerDesc *prof;
431         for (prof = prof_list; prof; prof = prof->next) {
432                 if ((prof->events & MONO_PROFILE_METHOD_EVENTS) && prof->method_free)
433                         prof->method_free (prof->profiler, method);
434         }
435 }
436
437 void
438 mono_profiler_method_start_invoke (MonoMethod *method)
439 {
440         ProfilerDesc *prof;
441         for (prof = prof_list; prof; prof = prof->next) {
442                 if ((prof->events & MONO_PROFILE_METHOD_EVENTS) && prof->method_start_invoke)
443                         prof->method_start_invoke (prof->profiler, method);
444         }
445 }
446
447 void
448 mono_profiler_method_end_invoke (MonoMethod *method)
449 {
450         ProfilerDesc *prof;
451         for (prof = prof_list; prof; prof = prof->next) {
452                 if ((prof->events & MONO_PROFILE_METHOD_EVENTS) && prof->method_end_invoke)
453                         prof->method_end_invoke (prof->profiler, method);
454         }
455 }
456
457 void 
458 mono_profiler_code_transition (MonoMethod *method, int result)
459 {
460         ProfilerDesc *prof;
461         for (prof = prof_list; prof; prof = prof->next) {
462                 if ((prof->events & MONO_PROFILE_TRANSITIONS) && prof->man_unman_transition)
463                         prof->man_unman_transition (prof->profiler, method, result);
464         }
465 }
466
467 void 
468 mono_profiler_allocation (MonoObject *obj, MonoClass *klass)
469 {
470         ProfilerDesc *prof;
471         for (prof = prof_list; prof; prof = prof->next) {
472                 if ((prof->events & MONO_PROFILE_ALLOCATIONS) && prof->allocation_cb)
473                         prof->allocation_cb (prof->profiler, obj, klass);
474         }
475 }
476
477 void
478 mono_profiler_monitor_event      (MonoObject *obj, MonoProfilerMonitorEvent event) {
479         ProfilerDesc *prof;
480         for (prof = prof_list; prof; prof = prof->next) {
481                 if ((prof->events & MONO_PROFILE_MONITOR_EVENTS) && prof->monitor_event_cb)
482                         prof->monitor_event_cb (prof->profiler, obj, event);
483         }
484 }
485
486 void
487 mono_profiler_stat_hit (guchar *ip, void *context)
488 {
489         ProfilerDesc *prof;
490         for (prof = prof_list; prof; prof = prof->next) {
491                 if ((prof->events & MONO_PROFILE_STATISTICAL) && prof->statistical_cb)
492                         prof->statistical_cb (prof->profiler, ip, context);
493         }
494 }
495
496 void
497 mono_profiler_stat_call_chain (int call_chain_depth, guchar **ips, void *context)
498 {
499         ProfilerDesc *prof;
500         for (prof = prof_list; prof; prof = prof->next) {
501                 if ((prof->events & MONO_PROFILE_STATISTICAL) && prof->statistical_call_chain_cb)
502                         prof->statistical_call_chain_cb (prof->profiler, call_chain_depth, ips, context);
503         }
504 }
505
506 void
507 mono_profiler_exception_thrown (MonoObject *exception)
508 {
509         ProfilerDesc *prof;
510         for (prof = prof_list; prof; prof = prof->next) {
511                 if ((prof->events & MONO_PROFILE_EXCEPTIONS) && prof->exception_throw_cb)
512                         prof->exception_throw_cb (prof->profiler, exception);
513         }
514 }
515
516 void
517 mono_profiler_exception_method_leave (MonoMethod *method)
518 {
519         ProfilerDesc *prof;
520         for (prof = prof_list; prof; prof = prof->next) {
521                 if ((prof->events & MONO_PROFILE_EXCEPTIONS) && prof->exception_method_leave_cb)
522                         prof->exception_method_leave_cb (prof->profiler, method);
523         }
524 }
525
526 void
527 mono_profiler_exception_clause_handler (MonoMethod *method, int clause_type, int clause_num)
528 {
529         ProfilerDesc *prof;
530         for (prof = prof_list; prof; prof = prof->next) {
531                 if ((prof->events & MONO_PROFILE_EXCEPTIONS) && prof->exception_clause_cb)
532                         prof->exception_clause_cb (prof->profiler, method, clause_type, clause_num);
533         }
534 }
535
536 void
537 mono_profiler_thread_start (gsize tid)
538 {
539         ProfilerDesc *prof;
540         for (prof = prof_list; prof; prof = prof->next) {
541                 if ((prof->events & MONO_PROFILE_THREADS) && prof->thread_start)
542                         prof->thread_start (prof->profiler, tid);
543         }
544 }
545
546 void 
547 mono_profiler_thread_end (gsize tid)
548 {
549         ProfilerDesc *prof;
550         for (prof = prof_list; prof; prof = prof->next) {
551                 if ((prof->events & MONO_PROFILE_THREADS) && prof->thread_end)
552                         prof->thread_end (prof->profiler, tid);
553         }
554 }
555
556 void
557 mono_profiler_thread_name (gsize tid, const char *name)
558 {
559         ProfilerDesc *prof;
560         for (prof = prof_list; prof; prof = prof->next) {
561                 if ((prof->events & MONO_PROFILE_THREADS) && prof->thread_name)
562                         prof->thread_name (prof->profiler, tid, name);
563         }
564 }
565
566 void 
567 mono_profiler_assembly_event  (MonoAssembly *assembly, int code)
568 {
569         ProfilerDesc *prof;
570         for (prof = prof_list; prof; prof = prof->next) {
571                 if (!(prof->events & MONO_PROFILE_ASSEMBLY_EVENTS))
572                         continue;
573
574                 switch (code) {
575                 case MONO_PROFILE_START_LOAD:
576                         if (prof->assembly_start_load)
577                                 prof->assembly_start_load (prof->profiler, assembly);
578                         break;
579                 case MONO_PROFILE_START_UNLOAD:
580                         if (prof->assembly_start_unload)
581                                 prof->assembly_start_unload (prof->profiler, assembly);
582                         break;
583                 case MONO_PROFILE_END_UNLOAD:
584                         if (prof->assembly_end_unload)
585                                 prof->assembly_end_unload (prof->profiler, assembly);
586                         break;
587                 default:
588                         g_assert_not_reached ();
589                 }
590         }
591 }
592
593 void 
594 mono_profiler_assembly_loaded (MonoAssembly *assembly, int result)
595 {
596         ProfilerDesc *prof;
597         for (prof = prof_list; prof; prof = prof->next) {
598                 if ((prof->events & MONO_PROFILE_ASSEMBLY_EVENTS) && prof->assembly_end_load)
599                         prof->assembly_end_load (prof->profiler, assembly, result);
600         }
601 }
602
603 void mono_profiler_iomap (char *report, const char *pathname, const char *new_pathname)
604 {
605         ProfilerDesc *prof;
606         for (prof = prof_list; prof; prof = prof->next) {
607                 if ((prof->events & MONO_PROFILE_IOMAP_EVENTS) && prof->iomap_cb)
608                         prof->iomap_cb (prof->profiler, report, pathname, new_pathname);
609         }
610 }
611
612 void 
613 mono_profiler_module_event  (MonoImage *module, int code)
614 {
615         ProfilerDesc *prof;
616         for (prof = prof_list; prof; prof = prof->next) {
617                 if (!(prof->events & MONO_PROFILE_MODULE_EVENTS))
618                         continue;
619
620                 switch (code) {
621                 case MONO_PROFILE_START_LOAD:
622                         if (prof->module_start_load)
623                                 prof->module_start_load (prof->profiler, module);
624                         break;
625                 case MONO_PROFILE_START_UNLOAD:
626                         if (prof->module_start_unload)
627                                 prof->module_start_unload (prof->profiler, module);
628                         break;
629                 case MONO_PROFILE_END_UNLOAD:
630                         if (prof->module_end_unload)
631                                 prof->module_end_unload (prof->profiler, module);
632                         break;
633                 default:
634                         g_assert_not_reached ();
635                 }
636         }
637 }
638
639 void 
640 mono_profiler_module_loaded (MonoImage *module, int result)
641 {
642         ProfilerDesc *prof;
643         for (prof = prof_list; prof; prof = prof->next) {
644                 if ((prof->events & MONO_PROFILE_MODULE_EVENTS) && prof->module_end_load)
645                         prof->module_end_load (prof->profiler, module, result);
646         }
647 }
648
649 void 
650 mono_profiler_class_event  (MonoClass *klass, int code)
651 {
652         ProfilerDesc *prof;
653         for (prof = prof_list; prof; prof = prof->next) {
654                 if (!(prof->events & MONO_PROFILE_CLASS_EVENTS))
655                         continue;
656
657                 switch (code) {
658                 case MONO_PROFILE_START_LOAD:
659                         if (prof->class_start_load)
660                                 prof->class_start_load (prof->profiler, klass);
661                         break;
662                 case MONO_PROFILE_START_UNLOAD:
663                         if (prof->class_start_unload)
664                                 prof->class_start_unload (prof->profiler, klass);
665                         break;
666                 case MONO_PROFILE_END_UNLOAD:
667                         if (prof->class_end_unload)
668                                 prof->class_end_unload (prof->profiler, klass);
669                         break;
670                 default:
671                         g_assert_not_reached ();
672                 }
673         }
674 }
675
676 void 
677 mono_profiler_class_loaded (MonoClass *klass, int result)
678 {
679         ProfilerDesc *prof;
680         for (prof = prof_list; prof; prof = prof->next) {
681                 if ((prof->events & MONO_PROFILE_CLASS_EVENTS) && prof->class_end_load)
682                         prof->class_end_load (prof->profiler, klass, result);
683         }
684 }
685
686 void 
687 mono_profiler_appdomain_event  (MonoDomain *domain, int code)
688 {
689         ProfilerDesc *prof;
690         for (prof = prof_list; prof; prof = prof->next) {
691                 if (!(prof->events & MONO_PROFILE_APPDOMAIN_EVENTS))
692                         continue;
693
694                 switch (code) {
695                 case MONO_PROFILE_START_LOAD:
696                         if (prof->domain_start_load)
697                                 prof->domain_start_load (prof->profiler, domain);
698                         break;
699                 case MONO_PROFILE_START_UNLOAD:
700                         if (prof->domain_start_unload)
701                                 prof->domain_start_unload (prof->profiler, domain);
702                         break;
703                 case MONO_PROFILE_END_UNLOAD:
704                         if (prof->domain_end_unload)
705                                 prof->domain_end_unload (prof->profiler, domain);
706                         break;
707                 default:
708                         g_assert_not_reached ();
709                 }
710         }
711 }
712
713 void 
714 mono_profiler_appdomain_loaded (MonoDomain *domain, int result)
715 {
716         ProfilerDesc *prof;
717         for (prof = prof_list; prof; prof = prof->next) {
718                 if ((prof->events & MONO_PROFILE_APPDOMAIN_EVENTS) && prof->domain_end_load)
719                         prof->domain_end_load (prof->profiler, domain, result);
720         }
721 }
722
723 void 
724 mono_profiler_shutdown (void)
725 {
726         ProfilerDesc *prof;
727         for (prof = prof_list; prof; prof = prof->next) {
728                 if (prof->shutdown_callback)
729                         prof->shutdown_callback (prof->profiler);
730         }
731
732         mono_profiler_set_events (0);
733 }
734
735 void
736 mono_profiler_gc_heap_resize (gint64 new_size)
737 {
738         ProfilerDesc *prof;
739         for (prof = prof_list; prof; prof = prof->next) {
740                 if ((prof->events & MONO_PROFILE_GC) && prof->gc_heap_resize)
741                         prof->gc_heap_resize (prof->profiler, new_size);
742         }
743 }
744
745 void
746 mono_profiler_gc_event (MonoGCEvent event, int generation)
747 {
748         ProfilerDesc *prof;
749         for (prof = prof_list; prof; prof = prof->next) {
750                 if ((prof->events & MONO_PROFILE_GC) && prof->gc_event)
751                         prof->gc_event (prof->profiler, event, generation);
752         }
753 }
754
755 void
756 mono_profiler_gc_moves (void **objects, int num)
757 {
758         ProfilerDesc *prof;
759         for (prof = prof_list; prof; prof = prof->next) {
760                 if ((prof->events & MONO_PROFILE_GC_MOVES) && prof->gc_moves)
761                         prof->gc_moves (prof->profiler, objects, num);
762         }
763 }
764
765 void
766 mono_profiler_gc_handle (int op, int type, uintptr_t handle, MonoObject *obj)
767 {
768         ProfilerDesc *prof;
769         for (prof = prof_list; prof; prof = prof->next) {
770                 if ((prof->events & MONO_PROFILE_GC_ROOTS) && prof->gc_handle)
771                         prof->gc_handle (prof->profiler, op, type, handle, obj);
772         }
773 }
774
775 void
776 mono_profiler_gc_roots (int num, void **objects, int *root_types, uintptr_t *extra_info)
777 {
778         ProfilerDesc *prof;
779         for (prof = prof_list; prof; prof = prof->next) {
780                 if ((prof->events & MONO_PROFILE_GC_ROOTS) && prof->gc_roots)
781                         prof->gc_roots (prof->profiler, num, objects, root_types, extra_info);
782         }
783 }
784
785 void
786 mono_profiler_install_gc (MonoProfileGCFunc callback, MonoProfileGCResizeFunc heap_resize_callback)
787 {
788         mono_gc_enable_events ();
789         if (!prof_list)
790                 return;
791         prof_list->gc_event = callback;
792         prof_list->gc_heap_resize = heap_resize_callback;
793 }
794
795 /**
796  * mono_profiler_install_gc_moves:
797  * @callback: callback function
798  *
799  * Install the @callback function that the GC will call when moving objects.
800  * The callback receives an array of pointers and the number of elements
801  * in the array. Every even element in the array is the original object location
802  * and the following odd element is the new location of the object in memory.
803  * So the number of elements argument will always be a multiple of 2.
804  * Since this callback happens during the GC, it is a restricted environment:
805  * no locks can be taken and the object pointers can be inspected only once
806  * the GC is finished (of course the original location pointers will not
807  * point to valid objects anymore).
808  */
809 void
810 mono_profiler_install_gc_moves (MonoProfileGCMoveFunc callback)
811 {
812         if (!prof_list)
813                 return;
814         prof_list->gc_moves = callback;
815 }
816
817 /**
818  * mono_profiler_install_gc_roots:
819  * @handle_callback: callback function
820  * @roots_callback: callback function
821  *
822  * Install the @handle_callback function that the GC will call when GC
823  * handles are created or destroyed.
824  * The callback receives an operation, which is either #MONO_PROFILER_GC_HANDLE_CREATED
825  * or #MONO_PROFILER_GC_HANDLE_DESTROYED, the handle type, the handle value and the
826  * object pointer, if present.
827  * Install the @roots_callback function that the GC will call when tracing
828  * the roots for a collection.
829  * The callback receives the number of elements and three arrays: an array
830  * of objects, an array of root types and flags and an array of extra info.
831  * The size of each array is given by the first argument.
832  */
833 void
834 mono_profiler_install_gc_roots (MonoProfileGCHandleFunc handle_callback, MonoProfileGCRootFunc roots_callback)
835 {
836         if (!prof_list)
837                 return;
838         prof_list->gc_handle = handle_callback;
839         prof_list->gc_roots = roots_callback;
840 }
841
842 void
843 mono_profiler_install_runtime_initialized (MonoProfileFunc runtime_initialized_callback)
844 {
845         if (!prof_list)
846                 return;
847         prof_list->runtime_initialized_event = runtime_initialized_callback;
848 }
849
850 void
851 mono_profiler_runtime_initialized (void) {
852         ProfilerDesc *prof;
853         for (prof = prof_list; prof; prof = prof->next) {
854                 if (prof->runtime_initialized_event)
855                         prof->runtime_initialized_event (prof->profiler);
856         }
857 }
858
859 void
860 mono_profiler_install_code_chunk_new (MonoProfilerCodeChunkNew callback) {
861         if (!prof_list)
862                 return;
863         prof_list->code_chunk_new = callback;
864 }
865 void
866 mono_profiler_code_chunk_new (gpointer chunk, int size) {
867         ProfilerDesc *prof;
868         for (prof = prof_list; prof; prof = prof->next) {
869                 if (prof->code_chunk_new)
870                         prof->code_chunk_new (prof->profiler, chunk, size);
871         }
872 }
873
874 void
875 mono_profiler_install_code_chunk_destroy (MonoProfilerCodeChunkDestroy callback) {
876         if (!prof_list)
877                 return;
878         prof_list->code_chunk_destroy = callback;
879 }
880 void
881 mono_profiler_code_chunk_destroy (gpointer chunk) {
882         ProfilerDesc *prof;
883         for (prof = prof_list; prof; prof = prof->next) {
884                 if (prof->code_chunk_destroy)
885                         prof->code_chunk_destroy (prof->profiler, chunk);
886         }
887 }
888
889 void
890 mono_profiler_install_code_buffer_new (MonoProfilerCodeBufferNew callback) {
891         if (!prof_list)
892                 return;
893         prof_list->code_buffer_new = callback;
894 }
895
896 void
897 mono_profiler_install_iomap (MonoProfileIomapFunc callback)
898 {
899         if (!prof_list)
900                 return;
901         prof_list->iomap_cb = callback;
902 }
903
904 void
905 mono_profiler_code_buffer_new (gpointer buffer, int size, MonoProfilerCodeBufferType type, void *data) {
906         ProfilerDesc *prof;
907         for (prof = prof_list; prof; prof = prof->next) {
908                 if (prof->code_buffer_new)
909                         prof->code_buffer_new (prof->profiler, buffer, size, type, data);
910         }
911 }
912
913 static GHashTable *coverage_hash = NULL;
914
915 MonoProfileCoverageInfo* 
916 mono_profiler_coverage_alloc (MonoMethod *method, int entries)
917 {
918         MonoProfileCoverageInfo *res;
919         int instrument = FALSE;
920         ProfilerDesc *prof;
921
922         for (prof = prof_list; prof; prof = prof->next) {
923                 /* note that we call the filter on all the profilers even if just
924                  * a single one would be enough to instrument a method
925                  */
926                 if (prof->coverage_filter_cb)
927                         if (prof->coverage_filter_cb (prof->profiler, method))
928                                 instrument = TRUE;
929         }
930         if (!instrument)
931                 return NULL;
932
933         mono_profiler_coverage_lock ();
934         if (!coverage_hash)
935                 coverage_hash = g_hash_table_new (NULL, NULL);
936
937         res = g_malloc0 (sizeof (MonoProfileCoverageInfo) + sizeof (void*) * 2 * entries);
938
939         res->entries = entries;
940
941         g_hash_table_insert (coverage_hash, method, res);
942         mono_profiler_coverage_unlock ();
943
944         return res;
945 }
946
947 /* safe only when the method antive code has been unloaded */
948 void
949 mono_profiler_coverage_free (MonoMethod *method)
950 {
951         MonoProfileCoverageInfo* info;
952
953         mono_profiler_coverage_lock ();
954         if (!coverage_hash) {
955                 mono_profiler_coverage_unlock ();
956                 return;
957         }
958
959         info = g_hash_table_lookup (coverage_hash, method);
960         if (info) {
961                 g_free (info);
962                 g_hash_table_remove (coverage_hash, method);
963         }
964         mono_profiler_coverage_unlock ();
965 }
966
967 /**
968  * mono_profiler_coverage_get:
969  * @prof: The profiler handle, installed with mono_profiler_install
970  * @method: the method to gather information from.
971  * @func: A routine that will be called back with the results
972  *
973  * If the MONO_PROFILER_INS_COVERAGE flag was active during JIT compilation
974  * it is posisble to obtain coverage information about a give method.
975  *
976  * The function @func will be invoked repeatedly with instances of the
977  * MonoProfileCoverageEntry structure.
978  */
979 void 
980 mono_profiler_coverage_get (MonoProfiler *prof, MonoMethod *method, MonoProfileCoverageFunc func)
981 {
982         MonoProfileCoverageInfo* info;
983         int i, offset;
984         guint32 code_size;
985         const unsigned char *start, *end, *cil_code;
986         MonoMethodHeader *header;
987         MonoProfileCoverageEntry entry;
988         MonoDebugMethodInfo *debug_minfo;
989
990         mono_profiler_coverage_lock ();
991         info = g_hash_table_lookup (coverage_hash, method);
992         mono_profiler_coverage_unlock ();
993
994         if (!info)
995                 return;
996
997         header = mono_method_get_header (method);
998         start = mono_method_header_get_code (header, &code_size, NULL);
999         debug_minfo = mono_debug_lookup_method (method);
1000
1001         end = start + code_size;
1002         for (i = 0; i < info->entries; ++i) {
1003                 cil_code = info->data [i].cil_code;
1004                 if (cil_code && cil_code >= start && cil_code < end) {
1005                         char *fname = NULL;
1006                         offset = cil_code - start;
1007                         entry.iloffset = offset;
1008                         entry.method = method;
1009                         entry.counter = info->data [i].count;
1010                         entry.line = entry.col = 1;
1011                         entry.filename = NULL;
1012                         if (debug_minfo) {
1013                                 MonoDebugSourceLocation *location;
1014
1015                                 location = mono_debug_symfile_lookup_location (debug_minfo, offset);
1016                                 if (location) {
1017                                         entry.line = location->row;
1018                                         entry.col = location->column;
1019                                         entry.filename = fname = g_strdup (location->source_file);
1020                                         mono_debug_free_source_location (location);
1021                                 }
1022                         }
1023
1024                         func (prof, &entry);
1025                         g_free (fname);
1026                 }
1027         }
1028         mono_metadata_free_mh (header);
1029 }
1030
1031 typedef void (*ProfilerInitializer) (const char*);
1032 #define INITIALIZER_NAME "mono_profiler_startup"
1033
1034
1035 static gboolean
1036 load_profiler (MonoDl *pmodule, const char *desc, const char *symbol)
1037 {
1038         char *err;
1039         ProfilerInitializer func;
1040
1041         if (!pmodule)
1042                 return FALSE;
1043
1044         if ((err = mono_dl_symbol (pmodule, symbol, (gpointer *) &func))) {
1045                 g_free (err);
1046                 return FALSE;
1047         } else {
1048                 func (desc);
1049         }
1050         return TRUE;
1051 }
1052
1053 static gboolean
1054 load_embedded_profiler (const char *desc, const char *name)
1055 {
1056         char *err = NULL;
1057         char *symbol;
1058         MonoDl *pmodule = NULL;
1059         gboolean result;
1060
1061         pmodule = mono_dl_open (NULL, MONO_DL_LAZY, &err);
1062         if (!pmodule) {
1063                 g_warning ("Could not open main executable (%s)", err);
1064                 g_free (err);
1065                 return FALSE;
1066         }
1067
1068         symbol = g_strdup_printf (INITIALIZER_NAME "_%s", name);
1069         result = load_profiler (pmodule, desc, symbol);
1070         g_free (symbol);
1071
1072         return result;
1073 }
1074
1075 static gboolean
1076 load_profiler_from_directory (const char *directory, const char *libname, const char *desc)
1077 {
1078         MonoDl *pmodule = NULL;
1079         char* path;
1080         char *err;
1081         void *iter;
1082
1083         iter = NULL;
1084         err = NULL;
1085         while ((path = mono_dl_build_path (directory, libname, &iter))) {
1086                 pmodule = mono_dl_open (path, MONO_DL_LAZY, &err);
1087                 g_free (path);
1088                 g_free (err);
1089                 if (pmodule)
1090                         return load_profiler (pmodule, desc, INITIALIZER_NAME);
1091         }
1092                 
1093         return FALSE;
1094 }
1095
1096 static gboolean
1097 load_profiler_from_mono_instalation (const char *libname, const char *desc)
1098 {
1099         char *err = NULL;
1100         MonoDl *pmodule = mono_dl_open_runtime_lib (libname, MONO_DL_LAZY, &err);
1101         g_free (err);
1102         if (pmodule)
1103                 return load_profiler (pmodule, desc, INITIALIZER_NAME);
1104         return FALSE;
1105 }
1106
1107 /**
1108  * mono_profiler_load:
1109  * @desc: arguments to configure the profiler
1110  *
1111  * Invoke this method to initialize the profiler.   This will drive the
1112  * loading of the internal ("default") or any external profilers.
1113  *
1114  * This routine is invoked by Mono's driver, but must be called manually
1115  * if you embed Mono into your application.
1116  */
1117 void 
1118 mono_profiler_load (const char *desc)
1119 {
1120         char *cdesc = NULL;
1121         mono_gc_base_init ();
1122
1123         if (!desc || (strcmp ("default", desc) == 0)) {
1124                 desc = "log:report";
1125         }
1126         /* we keep command-line compat with the old version here */
1127         if (strncmp (desc, "default:", 8) == 0) {
1128                 gchar **args, **ptr;
1129                 GString *str = g_string_new ("log:report");
1130                 args = g_strsplit (desc + 8, ",", -1);
1131                 for (ptr = args; ptr && *ptr; ptr++) {
1132                         const char *arg = *ptr;
1133
1134                         if (!strcmp (arg, "time"))
1135                                 g_string_append (str, ",calls");
1136                         else if (!strcmp (arg, "alloc"))
1137                                 g_string_append (str, ",alloc");
1138                         else if (!strcmp (arg, "stat"))
1139                                 g_string_append (str, ",sample");
1140                         else if (!strcmp (arg, "jit"))
1141                                 continue; /* accept and do nothing */
1142                         else if (strncmp (arg, "file=", 5) == 0) {
1143                                 g_string_append_printf (str, ",output=%s", arg + 5);
1144                         } else {
1145                                 fprintf (stderr, "profiler : Unknown argument '%s'.\n", arg);
1146                                 return;
1147                         }
1148                 }
1149                 desc = cdesc = g_string_free (str, FALSE);
1150         }
1151         {
1152                 const char* col = strchr (desc, ':');
1153                 char* libname;
1154                 char *mname;
1155                 gboolean res = FALSE;
1156
1157                 if (col != NULL) {
1158                         mname = g_memdup (desc, col - desc + 1);
1159                         mname [col - desc] = 0;
1160                 } else {
1161                         mname = g_strdup (desc);
1162                 }
1163                 if (!load_embedded_profiler (desc, mname)) {
1164                         libname = g_strdup_printf ("mono-profiler-%s", mname);
1165                         if (!load_profiler_from_directory (NULL, libname, desc)) {
1166                                 res = FALSE;
1167 #if defined (MONO_ASSEMBLIES)
1168                                 res = load_profiler_from_directory (mono_assembly_getrootdir (), libname, desc);
1169 #endif
1170                                 if (!res)
1171                                         res = load_profiler_from_mono_instalation (libname, desc);
1172
1173                                 if (!res)
1174                                         g_warning ("The '%s' profiler wasn't found in the main executable nor could it be loaded from '%s'.", mname, libname);
1175                         }
1176                         g_free (libname);
1177                 }
1178                 g_free (mname);
1179         }
1180         g_free (cdesc);
1181 }
1182