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