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