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