5d2bbaa617ff25d34567872ae27c64395c1d8dde
[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  */
10
11 #include "config.h"
12 #include "mono/metadata/profiler-private.h"
13 #include "mono/metadata/debug-helpers.h"
14 #include "mono/metadata/mono-debug.h"
15 #include "mono/metadata/debug-mono-symfile.h"
16 #include "mono/metadata/metadata-internals.h"
17 #include "mono/metadata/class-internals.h"
18 #include "mono/metadata/domain-internals.h"
19 #include "mono/metadata/gc-internal.h"
20 #include "mono/io-layer/io-layer.h"
21 #include "mono/utils/mono-dl.h"
22 #include <string.h>
23 #ifdef HAVE_UNISTD_H
24 #include <unistd.h>
25 #endif
26 #ifdef HAVE_SYS_TIME_H
27 #include <sys/time.h>
28 #endif
29 #ifdef HAVE_BACKTRACE_SYMBOLS
30 #include <execinfo.h>
31 #endif
32
33 static MonoProfiler * current_profiler = NULL;
34
35 static MonoProfileAppDomainFunc   domain_start_load;
36 static MonoProfileAppDomainResult domain_end_load;
37 static MonoProfileAppDomainFunc   domain_start_unload;
38 static MonoProfileAppDomainFunc   domain_end_unload;
39
40 static MonoProfileAssemblyFunc   assembly_start_load;
41 static MonoProfileAssemblyResult assembly_end_load;
42 static MonoProfileAssemblyFunc   assembly_start_unload;
43 static MonoProfileAssemblyFunc   assembly_end_unload;
44
45 static MonoProfileModuleFunc   module_start_load;
46 static MonoProfileModuleResult module_end_load;
47 static MonoProfileModuleFunc   module_start_unload;
48 static MonoProfileModuleFunc   module_end_unload;
49
50 static MonoProfileClassFunc   class_start_load;
51 static MonoProfileClassResult class_end_load;
52 static MonoProfileClassFunc   class_start_unload;
53 static MonoProfileClassFunc   class_end_unload;
54
55 static MonoProfileMethodFunc   jit_start;
56 static MonoProfileMethodResult jit_end;
57 static MonoProfileJitResult    jit_end2;
58 static MonoProfileMethodFunc   method_free;
59 static MonoProfileMethodFunc   method_start_invoke;
60 static MonoProfileMethodFunc   method_end_invoke;
61 static MonoProfileMethodResult man_unman_transition;
62 static MonoProfileAllocFunc    allocation_cb;
63 static MonoProfileMonitorFunc  monitor_event_cb;
64 static MonoProfileStatFunc     statistical_cb;
65 static MonoProfileStatCallChainFunc statistical_call_chain_cb;
66 static int                     statistical_call_chain_depth;
67 static MonoProfilerCallChainStrategy  statistical_call_chain_strategy;
68 static MonoProfileMethodFunc   method_enter;
69 static MonoProfileMethodFunc   method_leave;
70
71 static MonoProfileExceptionFunc exception_throw_cb;
72 static MonoProfileMethodFunc exception_method_leave_cb;
73 static MonoProfileExceptionClauseFunc exception_clause_cb;
74
75 static MonoProfileIomapFunc iomap_cb;
76
77 static MonoProfileThreadFunc   thread_start;
78 static MonoProfileThreadFunc   thread_end;
79
80 static MonoProfileCoverageFilterFunc coverage_filter_cb;
81
82 static MonoProfileFunc shutdown_callback;
83
84 static MonoProfileGCFunc        gc_event;
85 static MonoProfileGCResizeFunc  gc_heap_resize;
86
87 static MonoProfileFunc          runtime_initialized_event;
88
89 #define mono_profiler_coverage_lock() EnterCriticalSection (&profiler_coverage_mutex)
90 #define mono_profiler_coverage_unlock() LeaveCriticalSection (&profiler_coverage_mutex)
91 static CRITICAL_SECTION profiler_coverage_mutex;
92
93 /* this is directly accessible to other mono libs. */
94 MonoProfileFlags mono_profiler_events;
95
96 /**
97  * mono_profiler_install:
98  * @prof: a MonoProfiler structure pointer, or a pointer to a derived structure.
99  * @callback: the function to invoke at shutdown
100  *
101  * Use mono_profiler_install to activate profiling in the Mono runtime.
102  * Typically developers of new profilers will create a new structure whose
103  * first field is a MonoProfiler and put any extra information that they need
104  * to access from the various profiling callbacks there.
105  *
106  */
107 void
108 mono_profiler_install (MonoProfiler *prof, MonoProfileFunc callback)
109 {
110         if (current_profiler)
111                 g_error ("profiler already setup");
112         current_profiler = prof;
113         shutdown_callback = callback;
114         InitializeCriticalSection (&profiler_coverage_mutex);
115 }
116
117 /**
118  * mono_profiler_set_events:
119  * @events: an ORed set of values made up of MONO_PROFILER_ flags
120  *
121  * The events descriped in the @events argument is a set of flags
122  * that represent which profiling events must be triggered.  For
123  * example if you have registered a set of methods for tracking
124  * JIT compilation start and end with mono_profiler_install_jit_compile,
125  * you will want to pass the MONO_PROFILE_JIT_COMPILATION flag to
126  * this routine.
127  *
128  * You can call mono_profile_set_events more than once and you can
129  * do this at runtime to modify which methods are invoked.
130  */
131 void
132 mono_profiler_set_events (MonoProfileFlags events)
133 {
134         mono_profiler_events = events;
135 }
136
137 /**
138  * mono_profiler_get_events:
139  *
140  * Returns a list of active events that will be intercepted. 
141  */
142 MonoProfileFlags
143 mono_profiler_get_events (void)
144 {
145         return mono_profiler_events;
146 }
147
148 /**
149  * mono_profiler_install_enter_leave:
150  * @enter: the routine to be called on each method entry
151  * @fleave: the routine to be called each time a method returns
152  *
153  * Use this routine to install routines that will be called everytime
154  * a method enters and leaves.   The routines will receive as an argument
155  * the MonoMethod representing the method that is entering or leaving.
156  */
157 void
158 mono_profiler_install_enter_leave (MonoProfileMethodFunc enter, MonoProfileMethodFunc fleave)
159 {
160         method_enter = enter;
161         method_leave = fleave;
162 }
163
164 /**
165  * mono_profiler_install_jit_compile:
166  * @start: the routine to be called when the JIT process starts.
167  * @end: the routine to be called when the JIT process ends.
168  *
169  * Use this routine to install routines that will be called when JIT 
170  * compilation of a method starts and completes.
171  */
172 void 
173 mono_profiler_install_jit_compile (MonoProfileMethodFunc start, MonoProfileMethodResult end)
174 {
175         jit_start = start;
176         jit_end = end;
177 }
178
179 void 
180 mono_profiler_install_jit_end (MonoProfileJitResult end)
181 {
182         jit_end2 = end;
183 }
184
185 void 
186 mono_profiler_install_method_free (MonoProfileMethodFunc callback)
187 {
188         method_free = callback;
189 }
190
191 void
192 mono_profiler_install_method_invoke (MonoProfileMethodFunc start, MonoProfileMethodFunc end)
193 {
194         method_start_invoke = start;
195         method_end_invoke = end;
196 }
197
198 void 
199 mono_profiler_install_thread (MonoProfileThreadFunc start, MonoProfileThreadFunc end)
200 {
201         thread_start = start;
202         thread_end = end;
203 }
204
205 void 
206 mono_profiler_install_transition (MonoProfileMethodResult callback)
207 {
208         man_unman_transition = callback;
209 }
210
211 void 
212 mono_profiler_install_allocation (MonoProfileAllocFunc callback)
213 {
214         allocation_cb = callback;
215 }
216
217 void
218 mono_profiler_install_monitor  (MonoProfileMonitorFunc callback)
219 {
220         monitor_event_cb = callback;
221 }
222
223 void 
224 mono_profiler_install_statistical (MonoProfileStatFunc callback)
225 {
226         statistical_cb = callback;
227 }
228
229 void 
230 mono_profiler_install_statistical_call_chain (MonoProfileStatCallChainFunc callback, int call_chain_depth, MonoProfilerCallChainStrategy call_chain_strategy) {
231         statistical_call_chain_cb = callback;
232         statistical_call_chain_depth = call_chain_depth;
233         if (statistical_call_chain_depth > MONO_PROFILER_MAX_STAT_CALL_CHAIN_DEPTH) {
234                 statistical_call_chain_depth = MONO_PROFILER_MAX_STAT_CALL_CHAIN_DEPTH;
235         }
236         statistical_call_chain_strategy = call_chain_strategy;
237         if ((statistical_call_chain_strategy >= MONO_PROFILER_CALL_CHAIN_INVALID) || (statistical_call_chain_strategy < MONO_PROFILER_CALL_CHAIN_NONE)) {
238                 statistical_call_chain_strategy = MONO_PROFILER_CALL_CHAIN_NONE;
239         }
240 }
241
242 int
243 mono_profiler_stat_get_call_chain_depth (void) {
244         if (statistical_call_chain_cb != NULL) {
245                 return statistical_call_chain_depth;
246         } else {
247                 return 0;
248         }
249 }
250
251 MonoProfilerCallChainStrategy
252 mono_profiler_stat_get_call_chain_strategy (void) {
253         if (statistical_call_chain_cb != NULL) {
254                 return statistical_call_chain_strategy;
255         } else {
256                 return MONO_PROFILER_CALL_CHAIN_NONE;
257         }
258 }
259
260 void mono_profiler_install_exception (MonoProfileExceptionFunc throw_callback, MonoProfileMethodFunc exc_method_leave, MonoProfileExceptionClauseFunc clause_callback)
261 {
262         exception_throw_cb = throw_callback;
263         exception_method_leave_cb = exc_method_leave;
264         exception_clause_cb = clause_callback;
265 }
266
267 void 
268 mono_profiler_install_coverage_filter (MonoProfileCoverageFilterFunc callback)
269 {
270         coverage_filter_cb = callback;
271 }
272
273 void 
274 mono_profiler_install_appdomain   (MonoProfileAppDomainFunc start_load, MonoProfileAppDomainResult end_load,
275                                    MonoProfileAppDomainFunc start_unload, MonoProfileAppDomainFunc end_unload)
276
277 {
278         domain_start_load = start_load;
279         domain_end_load = end_load;
280         domain_start_unload = start_unload;
281         domain_end_unload = end_unload;
282 }
283
284 void 
285 mono_profiler_install_assembly    (MonoProfileAssemblyFunc start_load, MonoProfileAssemblyResult end_load,
286                                    MonoProfileAssemblyFunc start_unload, MonoProfileAssemblyFunc end_unload)
287 {
288         assembly_start_load = start_load;
289         assembly_end_load = end_load;
290         assembly_start_unload = start_unload;
291         assembly_end_unload = end_unload;
292 }
293
294 void 
295 mono_profiler_install_module      (MonoProfileModuleFunc start_load, MonoProfileModuleResult end_load,
296                                    MonoProfileModuleFunc start_unload, MonoProfileModuleFunc end_unload)
297 {
298         module_start_load = start_load;
299         module_end_load = end_load;
300         module_start_unload = start_unload;
301         module_end_unload = end_unload;
302 }
303
304 void
305 mono_profiler_install_class       (MonoProfileClassFunc start_load, MonoProfileClassResult end_load,
306                                    MonoProfileClassFunc start_unload, MonoProfileClassFunc end_unload)
307 {
308         class_start_load = start_load;
309         class_end_load = end_load;
310         class_start_unload = start_unload;
311         class_end_unload = end_unload;
312 }
313
314 void
315 mono_profiler_method_enter (MonoMethod *method)
316 {
317         if ((mono_profiler_events & MONO_PROFILE_ENTER_LEAVE) && method_enter)
318                 method_enter (current_profiler, method);
319 }
320
321 void
322 mono_profiler_method_leave (MonoMethod *method)
323 {
324         if ((mono_profiler_events & MONO_PROFILE_ENTER_LEAVE) && method_leave)
325                 method_leave (current_profiler, method);
326 }
327
328 void 
329 mono_profiler_method_jit (MonoMethod *method)
330 {
331         if ((mono_profiler_events & MONO_PROFILE_JIT_COMPILATION) && jit_start)
332                 jit_start (current_profiler, method);
333 }
334
335 void 
336 mono_profiler_method_end_jit (MonoMethod *method, MonoJitInfo* jinfo, int result)
337 {
338         if ((mono_profiler_events & MONO_PROFILE_JIT_COMPILATION)) {
339                 if (jit_end)
340                         jit_end (current_profiler, method, result);
341                 if (jit_end2)
342                         jit_end2 (current_profiler, method, jinfo, result);
343         }
344 }
345
346 void 
347 mono_profiler_method_free (MonoMethod *method)
348 {
349         if ((mono_profiler_events & MONO_PROFILE_METHOD_EVENTS) && method_free)
350                 method_free (current_profiler, method);
351 }
352
353 void
354 mono_profiler_method_start_invoke (MonoMethod *method)
355 {
356         if ((mono_profiler_events & MONO_PROFILE_METHOD_EVENTS) && method_start_invoke)
357                 method_start_invoke (current_profiler, method);
358 }
359
360 void
361 mono_profiler_method_end_invoke (MonoMethod *method)
362 {
363         if ((mono_profiler_events & MONO_PROFILE_METHOD_EVENTS) && method_end_invoke)
364                 method_end_invoke (current_profiler, method);
365 }
366
367 void 
368 mono_profiler_code_transition (MonoMethod *method, int result)
369 {
370         if ((mono_profiler_events & MONO_PROFILE_TRANSITIONS) && man_unman_transition)
371                 man_unman_transition (current_profiler, method, result);
372 }
373
374 void 
375 mono_profiler_allocation (MonoObject *obj, MonoClass *klass)
376 {
377         if ((mono_profiler_events & MONO_PROFILE_ALLOCATIONS) && allocation_cb)
378                 allocation_cb (current_profiler, obj, klass);
379 }
380
381 void
382 mono_profiler_monitor_event      (MonoObject *obj, MonoProfilerMonitorEvent event) {
383         if ((mono_profiler_events & MONO_PROFILE_MONITOR_EVENTS) && monitor_event_cb) {
384                 monitor_event_cb (current_profiler, obj, event);
385         }
386 }
387
388 void
389 mono_profiler_stat_hit (guchar *ip, void *context)
390 {
391         if ((mono_profiler_events & MONO_PROFILE_STATISTICAL) && statistical_cb)
392                 statistical_cb (current_profiler, ip, context);
393 }
394
395 void
396 mono_profiler_stat_call_chain (int call_chain_depth, guchar **ips, void *context)
397 {
398         if ((mono_profiler_events & MONO_PROFILE_STATISTICAL) && statistical_call_chain_cb)
399                 statistical_call_chain_cb (current_profiler, call_chain_depth, ips, context);
400 }
401
402 void
403 mono_profiler_exception_thrown (MonoObject *exception)
404 {
405         if ((mono_profiler_events & MONO_PROFILE_EXCEPTIONS) && exception_throw_cb)
406                 exception_throw_cb (current_profiler, exception);
407 }
408
409 void
410 mono_profiler_exception_method_leave (MonoMethod *method)
411 {
412         if ((mono_profiler_events & MONO_PROFILE_EXCEPTIONS) && exception_method_leave_cb)
413                 exception_method_leave_cb (current_profiler, method);
414 }
415
416 void
417 mono_profiler_exception_clause_handler (MonoMethod *method, int clause_type, int clause_num)
418 {
419         if ((mono_profiler_events & MONO_PROFILE_EXCEPTIONS) && exception_clause_cb)
420                 exception_clause_cb (current_profiler, method, clause_type, clause_num);
421 }
422
423 void
424 mono_profiler_thread_start (gsize tid)
425 {
426         if ((mono_profiler_events & MONO_PROFILE_THREADS) && thread_start)
427                 thread_start (current_profiler, tid);
428 }
429
430 void 
431 mono_profiler_thread_end (gsize tid)
432 {
433         if ((mono_profiler_events & MONO_PROFILE_THREADS) && thread_end)
434                 thread_end (current_profiler, tid);
435 }
436
437 void 
438 mono_profiler_assembly_event  (MonoAssembly *assembly, int code)
439 {
440         if (!(mono_profiler_events & MONO_PROFILE_ASSEMBLY_EVENTS))
441                 return;
442         
443         switch (code) {
444         case MONO_PROFILE_START_LOAD:
445                 if (assembly_start_load)
446                         assembly_start_load (current_profiler, assembly);
447                 break;
448         case MONO_PROFILE_START_UNLOAD:
449                 if (assembly_start_unload)
450                         assembly_start_unload (current_profiler, assembly);
451                 break;
452         case MONO_PROFILE_END_UNLOAD:
453                 if (assembly_end_unload)
454                         assembly_end_unload (current_profiler, assembly);
455                 break;
456         default:
457                 g_assert_not_reached ();
458         }
459 }
460
461 void 
462 mono_profiler_assembly_loaded (MonoAssembly *assembly, int result)
463 {
464         if ((mono_profiler_events & MONO_PROFILE_ASSEMBLY_EVENTS) && assembly_end_load)
465                 assembly_end_load (current_profiler, assembly, result);
466 }
467
468 void mono_profiler_iomap (char *report, const char *pathname, const char *new_pathname)
469 {
470         if ((mono_profiler_events && MONO_PROFILE_IOMAP_EVENTS) && iomap_cb)
471                 iomap_cb (current_profiler, report, pathname, new_pathname);
472 }
473
474 void 
475 mono_profiler_module_event  (MonoImage *module, int code)
476 {
477         if (!(mono_profiler_events & MONO_PROFILE_MODULE_EVENTS))
478                 return;
479         
480         switch (code) {
481         case MONO_PROFILE_START_LOAD:
482                 if (module_start_load)
483                         module_start_load (current_profiler, module);
484                 break;
485         case MONO_PROFILE_START_UNLOAD:
486                 if (module_start_unload)
487                         module_start_unload (current_profiler, module);
488                 break;
489         case MONO_PROFILE_END_UNLOAD:
490                 if (module_end_unload)
491                         module_end_unload (current_profiler, module);
492                 break;
493         default:
494                 g_assert_not_reached ();
495         }
496 }
497
498 void 
499 mono_profiler_module_loaded (MonoImage *module, int result)
500 {
501         if ((mono_profiler_events & MONO_PROFILE_MODULE_EVENTS) && module_end_load)
502                 module_end_load (current_profiler, module, result);
503 }
504
505 void 
506 mono_profiler_class_event  (MonoClass *klass, int code)
507 {
508         if (!(mono_profiler_events & MONO_PROFILE_CLASS_EVENTS))
509                 return;
510         
511         switch (code) {
512         case MONO_PROFILE_START_LOAD:
513                 if (class_start_load)
514                         class_start_load (current_profiler, klass);
515                 break;
516         case MONO_PROFILE_START_UNLOAD:
517                 if (class_start_unload)
518                         class_start_unload (current_profiler, klass);
519                 break;
520         case MONO_PROFILE_END_UNLOAD:
521                 if (class_end_unload)
522                         class_end_unload (current_profiler, klass);
523                 break;
524         default:
525                 g_assert_not_reached ();
526         }
527 }
528
529 void 
530 mono_profiler_class_loaded (MonoClass *klass, int result)
531 {
532         if ((mono_profiler_events & MONO_PROFILE_CLASS_EVENTS) && class_end_load)
533                 class_end_load (current_profiler, klass, result);
534 }
535
536 void 
537 mono_profiler_appdomain_event  (MonoDomain *domain, int code)
538 {
539         if (!(mono_profiler_events & MONO_PROFILE_APPDOMAIN_EVENTS))
540                 return;
541         
542         switch (code) {
543         case MONO_PROFILE_START_LOAD:
544                 if (domain_start_load)
545                         domain_start_load (current_profiler, domain);
546                 break;
547         case MONO_PROFILE_START_UNLOAD:
548                 if (domain_start_unload)
549                         domain_start_unload (current_profiler, domain);
550                 break;
551         case MONO_PROFILE_END_UNLOAD:
552                 if (domain_end_unload)
553                         domain_end_unload (current_profiler, domain);
554                 break;
555         default:
556                 g_assert_not_reached ();
557         }
558 }
559
560 void 
561 mono_profiler_appdomain_loaded (MonoDomain *domain, int result)
562 {
563         if ((mono_profiler_events & MONO_PROFILE_APPDOMAIN_EVENTS) && domain_end_load)
564                 domain_end_load (current_profiler, domain, result);
565 }
566
567 void 
568 mono_profiler_shutdown (void)
569 {
570         if (current_profiler && shutdown_callback)
571                 shutdown_callback (current_profiler);
572 }
573
574 void
575 mono_profiler_gc_heap_resize (gint64 new_size)
576 {
577         if ((mono_profiler_events & MONO_PROFILE_GC) && gc_heap_resize)
578                 gc_heap_resize (current_profiler, new_size);
579 }
580
581 void
582 mono_profiler_gc_event (MonoGCEvent event, int generation)
583 {
584         if ((mono_profiler_events & MONO_PROFILE_GC) && gc_event)
585                 gc_event (current_profiler, event, generation);
586 }
587
588 void
589 mono_profiler_install_gc (MonoProfileGCFunc callback, MonoProfileGCResizeFunc heap_resize_callback)
590 {
591         mono_gc_enable_events ();
592         gc_event = callback;
593         gc_heap_resize = heap_resize_callback;
594 }
595
596 void
597 mono_profiler_install_runtime_initialized (MonoProfileFunc runtime_initialized_callback)
598 {
599         runtime_initialized_event = runtime_initialized_callback;
600 }
601
602 void
603 mono_profiler_runtime_initialized (void) {
604         if (runtime_initialized_event)
605                 runtime_initialized_event (current_profiler);
606 }
607
608 static MonoProfilerCodeChunkNew code_chunk_new = NULL;
609 void
610 mono_profiler_install_code_chunk_new (MonoProfilerCodeChunkNew callback) {
611         code_chunk_new = callback;
612 }
613 void
614 mono_profiler_code_chunk_new (gpointer chunk, int size) {
615         if (code_chunk_new)
616                 code_chunk_new (current_profiler, chunk, size);
617 }
618
619 static MonoProfilerCodeChunkDestroy code_chunk_destroy = NULL;
620 void
621 mono_profiler_install_code_chunk_destroy (MonoProfilerCodeChunkDestroy callback) {
622         code_chunk_destroy = callback;
623 }
624 void
625 mono_profiler_code_chunk_destroy (gpointer chunk) {
626         if (code_chunk_destroy)
627                 code_chunk_destroy (current_profiler, chunk);
628 }
629
630 static MonoProfilerCodeBufferNew code_buffer_new = NULL;
631 void
632 mono_profiler_install_code_buffer_new (MonoProfilerCodeBufferNew callback) {
633         code_buffer_new = callback;
634 }
635
636 void
637 mono_profiler_install_iomap (MonoProfileIomapFunc callback)
638 {
639         iomap_cb = callback;
640 }
641
642 void
643 mono_profiler_code_buffer_new (gpointer buffer, int size, MonoProfilerCodeBufferType type, void *data) {
644         if (code_buffer_new)
645                 code_buffer_new (current_profiler, buffer, size, type, data);
646 }
647
648 static GHashTable *coverage_hash = NULL;
649
650 MonoProfileCoverageInfo* 
651 mono_profiler_coverage_alloc (MonoMethod *method, int entries)
652 {
653         MonoProfileCoverageInfo *res;
654
655         if (coverage_filter_cb)
656                 if (! (*coverage_filter_cb) (current_profiler, method))
657                         return NULL;
658
659         mono_profiler_coverage_lock ();
660         if (!coverage_hash)
661                 coverage_hash = g_hash_table_new (NULL, NULL);
662
663         res = g_malloc0 (sizeof (MonoProfileCoverageInfo) + sizeof (void*) * 2 * entries);
664
665         res->entries = entries;
666
667         g_hash_table_insert (coverage_hash, method, res);
668         mono_profiler_coverage_unlock ();
669
670         return res;
671 }
672
673 /* safe only when the method antive code has been unloaded */
674 void
675 mono_profiler_coverage_free (MonoMethod *method)
676 {
677         MonoProfileCoverageInfo* info;
678
679         mono_profiler_coverage_lock ();
680         if (!coverage_hash) {
681                 mono_profiler_coverage_unlock ();
682                 return;
683         }
684
685         info = g_hash_table_lookup (coverage_hash, method);
686         if (info) {
687                 g_free (info);
688                 g_hash_table_remove (coverage_hash, method);
689         }
690         mono_profiler_coverage_unlock ();
691 }
692
693 /**
694  * mono_profiler_coverage_get:
695  * @prof: The profiler handle, installed with mono_profiler_install
696  * @method: the method to gather information from.
697  * @func: A routine that will be called back with the results
698  *
699  * If the MONO_PROFILER_INS_COVERAGE flag was active during JIT compilation
700  * it is posisble to obtain coverage information about a give method.
701  *
702  * The function @func will be invoked repeatedly with instances of the
703  * MonoProfileCoverageEntry structure.
704  */
705 void 
706 mono_profiler_coverage_get (MonoProfiler *prof, MonoMethod *method, MonoProfileCoverageFunc func)
707 {
708         MonoProfileCoverageInfo* info;
709         int i, offset;
710         guint32 code_size;
711         const unsigned char *start, *end, *cil_code;
712         MonoMethodHeader *header;
713         MonoProfileCoverageEntry entry;
714         MonoDebugMethodInfo *debug_minfo;
715
716         mono_profiler_coverage_lock ();
717         info = g_hash_table_lookup (coverage_hash, method);
718         mono_profiler_coverage_unlock ();
719
720         if (!info)
721                 return;
722
723         header = mono_method_get_header (method);
724         start = mono_method_header_get_code (header, &code_size, NULL);
725         debug_minfo = mono_debug_lookup_method (method);
726
727         end = start + code_size;
728         for (i = 0; i < info->entries; ++i) {
729                 cil_code = info->data [i].cil_code;
730                 if (cil_code && cil_code >= start && cil_code < end) {
731                         char *fname = NULL;
732                         offset = cil_code - start;
733                         entry.iloffset = offset;
734                         entry.method = method;
735                         entry.counter = info->data [i].count;
736                         entry.line = entry.col = 1;
737                         entry.filename = NULL;
738                         if (debug_minfo) {
739                                 MonoDebugSourceLocation *location;
740
741                                 location = mono_debug_symfile_lookup_location (debug_minfo, offset);
742                                 if (location) {
743                                         entry.line = location->row;
744                                         entry.col = location->column;
745                                         entry.filename = fname = g_strdup (location->source_file);
746                                         mono_debug_free_source_location (location);
747                                 }
748                         }
749
750                         func (prof, &entry);
751                         g_free (fname);
752                 }
753         }
754 }
755
756 #ifndef DISABLE_PROFILER
757 /*
758  * Small profiler extracted from mint: we should move it in a loadable module
759  * and improve it to do graphs and more accurate timestamping with rdtsc.
760  */
761
762 static FILE* poutput = NULL;
763
764 #define USE_X86TSC 0
765 #define USE_WIN32COUNTER 0
766 #if USE_X86TSC
767
768 typedef struct {
769         unsigned int lows, highs, lowe, highe;
770 } MonoRdtscTimer;
771
772 #define rdtsc(low,high) \
773         __asm__ __volatile__("rdtsc" : "=a" (low), "=d" (high))
774
775 static int freq;
776
777 static double
778 rdtsc_elapsed (MonoRdtscTimer *t)
779 {
780         unsigned long long diff;
781         unsigned int highe = t->highe;
782         if (t->lowe < t->lows)
783                 highe--;
784         diff = (((unsigned long long) highe - t->highs) << 32) + (t->lowe - t->lows);
785         return ((double)diff / freq) / 1000000; /* have to return the result in seconds */
786 }
787
788 static int 
789 have_rdtsc (void) {
790         char buf[256];
791         int have_freq = 0;
792         int have_flag = 0;
793         float val;
794         FILE *cpuinfo;
795
796         if (!(cpuinfo = fopen ("/proc/cpuinfo", "r")))
797                 return 0;
798         while (fgets (buf, sizeof(buf), cpuinfo)) {
799                 if (sscanf (buf, "cpu MHz : %f", &val) == 1) {
800                         /*printf ("got mh: %f\n", val);*/
801                         have_freq = val;
802                 }
803                 if (strncmp (buf, "flags", 5) == 0) {
804                         if (strstr (buf, "tsc")) {
805                                 have_flag = 1;
806                                 /*printf ("have tsc\n");*/
807                         }
808                 }
809         }
810         fclose (cpuinfo);
811         return have_flag? have_freq: 0;
812 }
813
814 #define MONO_TIMER_STARTUP      \
815         if (!(freq = have_rdtsc ())) g_error ("Compiled with TSC support, but none found");
816 #define MONO_TIMER_TYPE  MonoRdtscTimer
817 #define MONO_TIMER_INIT(t)
818 #define MONO_TIMER_DESTROY(t)
819 #define MONO_TIMER_START(t) rdtsc ((t).lows, (t).highs);
820 #define MONO_TIMER_STOP(t) rdtsc ((t).lowe, (t).highe);
821 #define MONO_TIMER_ELAPSED(t) rdtsc_elapsed (&(t))
822
823 #elif USE_WIN32COUNTER
824 #include <windows.h>
825
826 typedef struct {
827         LARGE_INTEGER start, stop;
828 } MonoWin32Timer;
829
830 static int freq;
831
832 static double
833 win32_elapsed (MonoWin32Timer *t)
834 {
835         LONGLONG diff = t->stop.QuadPart - t->start.QuadPart;
836         return ((double)diff / freq) / 1000000; /* have to return the result in seconds */
837 }
838
839 static int 
840 have_win32counter (void) {
841         LARGE_INTEGER f;
842
843         if (!QueryPerformanceFrequency (&f))
844                 return 0;
845         return f.LowPart;
846 }
847
848 #define MONO_TIMER_STARTUP      \
849         if (!(freq = have_win32counter ())) g_error ("Compiled with Win32 counter support, but none found");
850 #define MONO_TIMER_TYPE  MonoWin32Timer
851 #define MONO_TIMER_INIT(t)
852 #define MONO_TIMER_DESTROY(t)
853 #define MONO_TIMER_START(t) QueryPerformanceCounter (&(t).start)
854 #define MONO_TIMER_STOP(t) QueryPerformanceCounter (&(t).stop)
855 #define MONO_TIMER_ELAPSED(t) win32_elapsed (&(t))
856
857 #else
858
859 typedef struct {
860         GTimeVal start, stop;
861 } MonoGLibTimer;
862
863 static double
864 timeval_elapsed (MonoGLibTimer *t)
865 {
866         if (t->start.tv_usec > t->stop.tv_usec) {
867                 t->stop.tv_usec += G_USEC_PER_SEC;
868                 t->stop.tv_sec--;
869         }
870         return (t->stop.tv_sec - t->start.tv_sec) 
871                 + ((double)(t->stop.tv_usec - t->start.tv_usec))/ G_USEC_PER_SEC;
872 }
873
874 #define MONO_TIMER_STARTUP
875 #define MONO_TIMER_TYPE MonoGLibTimer
876 #define MONO_TIMER_INIT(t)
877 #define MONO_TIMER_DESTROY(t)
878 #define MONO_TIMER_START(t) g_get_current_time (&(t).start)
879 #define MONO_TIMER_STOP(t) g_get_current_time (&(t).stop)
880 #define MONO_TIMER_ELAPSED(t) timeval_elapsed (&(t))
881 #endif
882
883 typedef struct _AllocInfo AllocInfo;
884 typedef struct _CallerInfo CallerInfo;
885 typedef struct _LastCallerInfo LastCallerInfo;
886
887 struct _MonoProfiler {
888         GHashTable *methods;
889         MonoMemPool *mempool;
890         GSList *domains;
891         /* info about JIT time */
892         MONO_TIMER_TYPE jit_timer;
893         double      jit_time;
894         double      max_jit_time;
895         MonoMethod *max_jit_method;
896         int         methods_jitted;
897         
898         GSList     *per_thread;
899         
900         /* chain of callers for the current thread */
901         LastCallerInfo *callers;
902         /* LastCallerInfo nodes for faster allocation */
903         LastCallerInfo *cstorage;
904 };
905
906 typedef struct {
907         MonoMethod *method;
908         guint64 count;
909         double total;
910         AllocInfo *alloc_info;
911         CallerInfo *caller_info;
912 } MethodProfile;
913
914 typedef struct _MethodCallProfile MethodCallProfile;
915
916 struct _MethodCallProfile {
917         MethodCallProfile *next;
918         MONO_TIMER_TYPE timer;
919         MonoMethod *method;
920 };
921
922 struct _AllocInfo {
923         AllocInfo *next;
924         MonoClass *klass;
925         guint64 count;
926         guint64 mem;
927 };
928
929 struct _CallerInfo {
930         CallerInfo *next;
931         MonoMethod *caller;
932         guint count;
933 };
934
935 struct _LastCallerInfo {
936         LastCallerInfo *next;
937         MonoMethod *method;
938         MONO_TIMER_TYPE timer;
939 };
940
941 static MonoProfiler*
942 create_profiler (void)
943 {
944         MonoProfiler *prof = g_new0 (MonoProfiler, 1);
945
946         prof->methods = g_hash_table_new (mono_aligned_addr_hash, NULL);
947         MONO_TIMER_INIT (prof->jit_timer);
948         prof->mempool = mono_mempool_new ();
949         return prof;
950 }
951 #if 1
952
953 #ifdef HAVE_KW_THREAD
954         static __thread MonoProfiler * tls_profiler;
955 #       define GET_PROFILER() tls_profiler
956 #       define SET_PROFILER(x) tls_profiler = (x)
957 #       define ALLOC_PROFILER() /* nop */
958 #else
959         static guint32 profiler_thread_id = -1;
960 #       define GET_PROFILER() ((MonoProfiler *)TlsGetValue (profiler_thread_id))
961 #       define SET_PROFILER(x) TlsSetValue (profiler_thread_id, x);
962 #       define ALLOC_PROFILER() profiler_thread_id = TlsAlloc ()
963 #endif
964
965 #define GET_THREAD_PROF(prof) do {                                                           \
966                 MonoProfiler *_tprofiler = GET_PROFILER ();                                  \
967                 if (!_tprofiler) {                                                           \
968                         _tprofiler = create_profiler ();                                     \
969                         prof->per_thread = g_slist_prepend (prof->per_thread, _tprofiler);   \
970                         SET_PROFILER (_tprofiler);                                           \
971                 }                                                                            \
972                 prof = _tprofiler;                                                           \
973         } while (0)
974 #else
975 /* thread unsafe but faster variant */
976 #define GET_THREAD_PROF(prof)
977 #endif
978
979 static gint
980 compare_profile (MethodProfile *profa, MethodProfile *profb)
981 {
982         return (gint)((profb->total - profa->total)*1000);
983 }
984
985 static void
986 build_profile (MonoMethod *m, MethodProfile *prof, GList **funcs)
987 {
988         prof->method = m;
989         *funcs = g_list_insert_sorted (*funcs, prof, (GCompareFunc)compare_profile);
990 }
991
992 static char*
993 method_get_name (MonoMethod* method)
994 {
995         char *sig, *res;
996         
997         sig = mono_signature_get_desc (mono_method_signature (method), FALSE);
998         res = g_strdup_printf ("%s%s%s::%s(%s)", method->klass->name_space,
999                         method->klass->name_space ? "." : "", method->klass->name,
1000                 method->name, sig);
1001         g_free (sig);
1002         return res;
1003 }
1004
1005 static void output_callers (MethodProfile *p);
1006
1007 /* This isn't defined on older glib versions and on some platforms */
1008 #ifndef G_GUINT64_FORMAT
1009 #define G_GUINT64_FORMAT "ul"
1010 #endif
1011 #ifndef G_GINT64_FORMAT
1012 #define G_GINT64_FORMAT "lld"
1013 #endif
1014
1015 static void
1016 output_profile (GList *funcs)
1017 {
1018         GList *tmp;
1019         MethodProfile *p;
1020         char *m;
1021         guint64 total_calls = 0;
1022
1023         if (funcs)
1024                 fprintf (poutput, "Time(ms) Count   P/call(ms) Method name\n");
1025         for (tmp = funcs; tmp; tmp = tmp->next) {
1026                 p = tmp->data;
1027                 total_calls += p->count;
1028                 if (!(gint)(p->total*1000))
1029                         continue;
1030                 m = method_get_name (p->method);
1031                 fprintf (poutput, "########################\n");
1032                 fprintf (poutput, "% 8.3f ", (double) (p->total * 1000));
1033                 fprintf (poutput, "%7" G_GUINT64_FORMAT " ", (guint64)p->count);
1034                 fprintf (poutput, "% 8.3f ", (double) (p->total * 1000)/(double)p->count);
1035                 fprintf (poutput, "  %s\n", m);
1036
1037                 g_free (m);
1038                 /* callers */
1039                 output_callers (p);
1040         }
1041         fprintf (poutput, "Total number of calls: %" G_GINT64_FORMAT "\n", (gint64)total_calls);
1042 }
1043
1044 typedef struct {
1045         MethodProfile *mp;
1046         guint64 count;
1047 } NewobjProfile;
1048
1049 static gint
1050 compare_newobj_profile (NewobjProfile *profa, NewobjProfile *profb)
1051 {
1052         if (profb->count == profa->count)
1053                 return 0;
1054         else
1055                 return profb->count > profa->count ? 1 : -1;
1056 }
1057
1058 static void
1059 build_newobj_profile (MonoClass *class, MethodProfile *mprof, GList **funcs)
1060 {
1061         NewobjProfile *prof = g_new (NewobjProfile, 1);
1062         AllocInfo *tmp;
1063         guint64 count = 0;
1064         
1065         prof->mp = mprof;
1066         /* we use the total amount of memory to sort */
1067         for (tmp = mprof->alloc_info; tmp; tmp = tmp->next)
1068                 count += tmp->mem;
1069         prof->count = count;
1070         *funcs = g_list_insert_sorted (*funcs, prof, (GCompareFunc)compare_newobj_profile);
1071 }
1072
1073 static int
1074 compare_caller (CallerInfo *a, CallerInfo *b)
1075 {
1076         return b->count - a->count;
1077 }
1078
1079 static int
1080 compare_alloc (AllocInfo *a, AllocInfo *b)
1081 {
1082         return b->mem - a->mem;
1083 }
1084
1085 static GSList*
1086 sort_alloc_list (AllocInfo *ai)
1087 {
1088         GSList *l = NULL;
1089         AllocInfo *tmp;
1090         for (tmp = ai; tmp; tmp = tmp->next) {
1091                 l = g_slist_insert_sorted (l, tmp, (GCompareFunc)compare_alloc);
1092         }
1093         return l;
1094 }
1095
1096 static GSList*
1097 sort_caller_list (CallerInfo *ai)
1098 {
1099         GSList *l = NULL;
1100         CallerInfo *tmp;
1101         for (tmp = ai; tmp; tmp = tmp->next) {
1102                 l = g_slist_insert_sorted (l, tmp, (GCompareFunc)compare_caller);
1103         }
1104         return l;
1105 }
1106
1107 static void
1108 output_callers (MethodProfile *p) {
1109         guint total_callers, percent;
1110         GSList *sorted, *tmps;
1111         CallerInfo *cinfo;
1112         char *m;
1113         
1114         fprintf (poutput, "  Callers (with count) that contribute at least for 1%%:\n");
1115         total_callers = 0;
1116         for (cinfo = p->caller_info; cinfo; cinfo = cinfo->next) {
1117                 total_callers += cinfo->count;
1118         }
1119         sorted = sort_caller_list (p->caller_info);
1120         for (tmps = sorted; tmps; tmps = tmps->next) {
1121                 cinfo = tmps->data;
1122                 percent = (cinfo->count * 100)/total_callers;
1123                 if (percent < 1)
1124                         continue;
1125                 m = method_get_name (cinfo->caller);
1126                 fprintf (poutput, "    %8d % 3d %% %s\n", cinfo->count, percent, m);
1127                 g_free (m);
1128         }
1129 }
1130
1131 static void
1132 output_newobj_profile (GList *proflist)
1133 {
1134         GList *tmp;
1135         NewobjProfile *p;
1136         MethodProfile *mp;
1137         AllocInfo *ainfo;
1138         MonoClass *klass;
1139         const char* isarray;
1140         char buf [256];
1141         char *m;
1142         guint64 total = 0;
1143         GSList *sorted, *tmps;
1144
1145         fprintf (poutput, "\nAllocation profiler\n");
1146
1147         if (proflist)
1148                 fprintf (poutput, "%-9s %s\n", "Total mem", "Method");
1149         for (tmp = proflist; tmp; tmp = tmp->next) {
1150                 p = tmp->data;
1151                 total += p->count;
1152                 if (p->count < 50000)
1153                         continue;
1154                 mp = p->mp;
1155                 m = method_get_name (mp->method);
1156                 fprintf (poutput, "########################\n%8" G_GUINT64_FORMAT " KB %s\n", (p->count / 1024), m);
1157                 g_free (m);
1158                 sorted = sort_alloc_list (mp->alloc_info);
1159                 for (tmps = sorted; tmps; tmps = tmps->next) {
1160                         ainfo = tmps->data;
1161                         if (ainfo->mem < 50000)
1162                                 continue;
1163                         klass = ainfo->klass;
1164                         if (klass->rank) {
1165                                 isarray = "[]";
1166                                 klass = klass->element_class;
1167                         } else {
1168                                 isarray = "";
1169                         }
1170                         g_snprintf (buf, sizeof (buf), "%s%s%s%s",
1171                                 klass->name_space, klass->name_space ? "." : "", klass->name, isarray);
1172                         fprintf (poutput, "    %8" G_GUINT64_FORMAT " KB %8" G_GUINT64_FORMAT " %-48s\n", (ainfo->mem / 1024), ainfo->count, buf);
1173                 }
1174                 /* callers */
1175                 output_callers (mp);
1176         }
1177         fprintf (poutput, "Total memory allocated: %" G_GUINT64_FORMAT " KB\n", total / 1024);
1178 }
1179
1180 static void
1181 merge_methods (MonoMethod *method, MethodProfile *profile, MonoProfiler *prof)
1182 {
1183         MethodProfile *mprof;
1184         AllocInfo *talloc_info, *alloc_info;
1185         CallerInfo *tcaller_info, *caller_info;
1186
1187         mprof = g_hash_table_lookup (prof->methods, method);
1188         if (!mprof) {
1189                 /* the master thread didn't see this method, just transfer the info as is */
1190                 g_hash_table_insert (prof->methods, method, profile);
1191                 return;
1192         }
1193         /* merge the info from profile into mprof */
1194         mprof->count += profile->count;
1195         mprof->total += profile->total;
1196         /* merge alloc info */
1197         for (talloc_info = profile->alloc_info; talloc_info; talloc_info = talloc_info->next) {
1198                 for (alloc_info = mprof->alloc_info; alloc_info; alloc_info = alloc_info->next) {
1199                         if (alloc_info->klass == talloc_info->klass) {
1200                                 /* mprof already has a record for the klass, merge */
1201                                 alloc_info->count += talloc_info->count;
1202                                 alloc_info->mem += talloc_info->mem;
1203                                 break;
1204                         }
1205                 }
1206                 if (!alloc_info) {
1207                         /* mprof didn't have the info, just copy it over */
1208                         alloc_info = mono_mempool_alloc0 (prof->mempool, sizeof (AllocInfo));
1209                         *alloc_info = *talloc_info;
1210                         alloc_info->next = mprof->alloc_info;
1211                         mprof->alloc_info = alloc_info->next;
1212                 }
1213         }
1214         /* merge callers info */
1215         for (tcaller_info = profile->caller_info; tcaller_info; tcaller_info = tcaller_info->next) {
1216                 for (caller_info = mprof->caller_info; caller_info; caller_info = caller_info->next) {
1217                         if (caller_info->caller == tcaller_info->caller) {
1218                                 /* mprof already has a record for the caller method, merge */
1219                                 caller_info->count += tcaller_info->count;
1220                                 break;
1221                         }
1222                 }
1223                 if (!caller_info) {
1224                         /* mprof didn't have the info, just copy it over */
1225                         caller_info = mono_mempool_alloc0 (prof->mempool, sizeof (CallerInfo));
1226                         *caller_info = *tcaller_info;
1227                         caller_info->next = mprof->caller_info;
1228                         mprof->caller_info = caller_info;
1229                 }
1230         }
1231 }
1232
1233 static void
1234 merge_thread_data (MonoProfiler *master, MonoProfiler *tprof)
1235 {
1236         master->jit_time += tprof->jit_time;
1237         master->methods_jitted += tprof->methods_jitted;
1238         if (master->max_jit_time < tprof->max_jit_time) {
1239                 master->max_jit_time = tprof->max_jit_time;
1240                 master->max_jit_method = tprof->max_jit_method;
1241         }
1242
1243         g_hash_table_foreach (tprof->methods, (GHFunc)merge_methods, master);
1244 }
1245
1246 static void
1247 simple_method_enter (MonoProfiler *prof, MonoMethod *method)
1248 {
1249         MethodProfile *profile_info;
1250         LastCallerInfo *callinfo;
1251         GET_THREAD_PROF (prof);
1252         /*g_print ("enter %p %s::%s in %d (%p)\n", method, method->klass->name, method->name, GetCurrentThreadId (), prof);*/
1253         if (!(profile_info = g_hash_table_lookup (prof->methods, method))) {
1254                 profile_info = mono_mempool_alloc0 (prof->mempool, sizeof (MethodProfile));
1255                 MONO_TIMER_INIT (profile_info->u.timer);
1256                 g_hash_table_insert (prof->methods, method, profile_info);
1257         }
1258         profile_info->count++;
1259         if (prof->callers) {
1260                 CallerInfo *cinfo;
1261                 MonoMethod *caller = prof->callers->method;
1262                 for (cinfo = profile_info->caller_info; cinfo; cinfo = cinfo->next) {
1263                         if (cinfo->caller == caller)
1264                                 break;
1265                 }
1266                 if (!cinfo) {
1267                         cinfo = mono_mempool_alloc0 (prof->mempool, sizeof (CallerInfo));
1268                         cinfo->caller = caller;
1269                         cinfo->next = profile_info->caller_info;
1270                         profile_info->caller_info = cinfo;
1271                 }
1272                 cinfo->count++;
1273         }
1274         if (!(callinfo = prof->cstorage)) {
1275                 callinfo = mono_mempool_alloc (prof->mempool, sizeof (LastCallerInfo));
1276                 MONO_TIMER_INIT (callinfo->timer);
1277         } else {
1278                 prof->cstorage = prof->cstorage->next;
1279         }
1280         callinfo->method = method;
1281         callinfo->next = prof->callers;
1282         prof->callers = callinfo;
1283         MONO_TIMER_START (callinfo->timer);
1284 }
1285
1286 static void
1287 simple_method_leave (MonoProfiler *prof, MonoMethod *method)
1288 {
1289         MethodProfile *profile_info;
1290         LastCallerInfo *callinfo, *newcallinfo = NULL;
1291         
1292         GET_THREAD_PROF (prof);
1293         /*g_print ("leave %p %s::%s in %d (%p)\n", method, method->klass->name, method->name, GetCurrentThreadId (), prof);*/
1294         callinfo = prof->callers;
1295         /* should really not happen, but we don't catch exceptions events, yet ... */
1296         while (callinfo) {
1297                 MONO_TIMER_STOP (callinfo->timer);
1298                 profile_info = g_hash_table_lookup (prof->methods, callinfo->method);
1299                 if (profile_info)
1300                         profile_info->total += MONO_TIMER_ELAPSED (callinfo->timer);
1301                 newcallinfo = callinfo->next;
1302                 callinfo->next = prof->cstorage;
1303                 prof->cstorage = callinfo;
1304                 if (callinfo->method == method)
1305                         break;
1306                 callinfo = newcallinfo;
1307         }
1308         prof->callers = newcallinfo;
1309 }
1310
1311 static void
1312 simple_allocation (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1313 {
1314         MethodProfile *profile_info;
1315         AllocInfo *tmp;
1316
1317         GET_THREAD_PROF (prof);
1318         if (prof->callers) {
1319                 MonoMethod *caller = prof->callers->method;
1320
1321                 /* Otherwise all allocations are attributed to icall_wrapper_mono_object_new */
1322                 if (caller->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && prof->callers->next)
1323                         caller = prof->callers->next->method;
1324
1325                 if (!(profile_info = g_hash_table_lookup (prof->methods, caller)))
1326                         g_assert_not_reached ();
1327         } else {
1328                 return; /* fine for now */
1329         }
1330
1331         for (tmp = profile_info->alloc_info; tmp; tmp = tmp->next) {
1332                 if (tmp->klass == klass)
1333                         break;
1334         }
1335         if (!tmp) {
1336                 tmp = mono_mempool_alloc0 (prof->mempool, sizeof (AllocInfo));
1337                 tmp->klass = klass;
1338                 tmp->next = profile_info->alloc_info;
1339                 profile_info->alloc_info = tmp;
1340         }
1341         tmp->count++;
1342         tmp->mem += mono_object_get_size (obj);
1343 }
1344
1345 static void
1346 simple_method_jit (MonoProfiler *prof, MonoMethod *method)
1347 {
1348         GET_THREAD_PROF (prof);
1349         prof->methods_jitted++;
1350         MONO_TIMER_START (prof->jit_timer);
1351 }
1352
1353 static void
1354 simple_method_end_jit (MonoProfiler *prof, MonoMethod *method, int result)
1355 {
1356         double jtime;
1357         GET_THREAD_PROF (prof);
1358         MONO_TIMER_STOP (prof->jit_timer);
1359         jtime = MONO_TIMER_ELAPSED (prof->jit_timer);
1360         prof->jit_time += jtime;
1361         if (jtime > prof->max_jit_time) {
1362                 prof->max_jit_time = jtime;
1363                 prof->max_jit_method = method;
1364         }
1365 }
1366
1367 /* about 10 minutes of samples */
1368 #define MAX_PROF_SAMPLES (1000*60*10)
1369 static int prof_counts = 0;
1370 static int prof_ucounts = 0;
1371 static gpointer* prof_addresses = NULL;
1372 static GHashTable *prof_table = NULL;
1373
1374 static void
1375 simple_stat_hit (MonoProfiler *prof, guchar *ip, void *context)
1376 {
1377         int pos;
1378
1379         if (prof_counts >= MAX_PROF_SAMPLES)
1380                 return;
1381         pos = InterlockedIncrement (&prof_counts);
1382         prof_addresses [pos - 1] = ip;
1383 }
1384
1385 static int
1386 compare_methods_prof (gconstpointer a, gconstpointer b)
1387 {
1388         int ca = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, a));
1389         int cb = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, b));
1390         return cb-ca;
1391 }
1392
1393 static void
1394 prof_foreach (char *method, gpointer c, gpointer data)
1395 {
1396         GList **list = data;
1397         *list = g_list_insert_sorted (*list, method, compare_methods_prof);
1398 }
1399
1400 typedef struct Addr2LineData Addr2LineData;
1401
1402 struct Addr2LineData {
1403         Addr2LineData *next;
1404         FILE *pipein;
1405         FILE *pipeout;
1406         char *binary;
1407         int child_pid;
1408 };
1409
1410 static Addr2LineData *addr2line_pipes = NULL;
1411
1412 static char*
1413 try_addr2line (const char* binary, gpointer ip)
1414 {
1415         char buf [1024];
1416         char *res;
1417         Addr2LineData *addr2line;
1418
1419         for (addr2line = addr2line_pipes; addr2line; addr2line = addr2line->next) {
1420                 if (strcmp (binary, addr2line->binary) == 0)
1421                         break;
1422         }
1423         if (!addr2line) {
1424                 const char *addr_argv[] = {"addr2line", "-f", "-e", binary, NULL};
1425                 int child_pid;
1426                 int ch_in, ch_out;
1427 #ifdef __linux__
1428                 char monobin [1024];
1429                 /* non-linux platforms will need different code here */
1430                 if (strcmp (binary, "mono") == 0) {
1431                         int count = readlink ("/proc/self/exe", monobin, sizeof (monobin));
1432                         if (count >= 0 && count < sizeof (monobin)) {
1433                                 monobin [count] = 0;
1434                                 addr_argv [3] = monobin;
1435                         }
1436                 }
1437 #endif
1438                 if (!g_spawn_async_with_pipes (NULL, (char**)addr_argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
1439                                 &child_pid, &ch_in, &ch_out, NULL, NULL)) {
1440                         return g_strdup (binary);
1441                 }
1442                 addr2line = g_new0 (Addr2LineData, 1);
1443                 addr2line->child_pid = child_pid;
1444                 addr2line->binary = g_strdup (binary);
1445                 addr2line->pipein = fdopen (ch_in, "w");
1446                 addr2line->pipeout = fdopen (ch_out, "r");
1447                 addr2line->next = addr2line_pipes;
1448                 addr2line_pipes = addr2line;
1449         }
1450         fprintf (addr2line->pipein, "%p\n", ip);
1451         fflush (addr2line->pipein);
1452         /* we first get the func name and then file:lineno in a second line */
1453         if (fgets (buf, sizeof (buf), addr2line->pipeout) && buf [0] != '?') {
1454                 char *end = strchr (buf, '\n');
1455                 if (end)
1456                         *end = 0;
1457                 res = g_strdup_printf ("%s(%s", binary, buf);
1458                 /* discard the filename/line info */
1459                 fgets (buf, sizeof (buf), addr2line->pipeout);
1460         } else {
1461                 res = g_strdup (binary);
1462         }
1463         return res;
1464 }
1465
1466 static void
1467 stat_prof_report (MonoProfiler *prof)
1468 {
1469         MonoJitInfo *ji;
1470         int count = prof_counts;
1471         int i, c;
1472         char *mn;
1473         gpointer ip;
1474         GList *tmp, *sorted = NULL;
1475         GSList *l;
1476         int pcount = ++ prof_counts;
1477
1478         prof_counts = MAX_PROF_SAMPLES;
1479         for (i = 0; i < count; ++i) {
1480                 ip = prof_addresses [i];
1481                 ji = mono_jit_info_table_find (mono_domain_get (), ip);
1482
1483                 if (!ji) {
1484                         for (l = prof->domains; l && !ji; l = l->next)
1485                                 ji = mono_jit_info_table_find (l->data, ip);
1486                 }
1487
1488                 if (ji) {
1489                         mn = mono_method_full_name (ji->method, TRUE);
1490                 } else {
1491 #ifdef HAVE_BACKTRACE_SYMBOLS
1492                         char **names;
1493                         char *send;
1494                         int no_func;
1495                         prof_ucounts++;
1496                         names = backtrace_symbols (&ip, 1);
1497                         send = strchr (names [0], '+');
1498                         if (send) {
1499                                 *send = 0;
1500                                 no_func = 0;
1501                         } else {
1502                                 no_func = 1;
1503                         }
1504                         send = strchr (names [0], '[');
1505                         if (send)
1506                                 *send = 0;
1507                         if (no_func && names [0][0]) {
1508                                 char *endp = strchr (names [0], 0);
1509                                 while (--endp >= names [0] && g_ascii_isspace (*endp))
1510                                         *endp = 0;
1511                                 mn = try_addr2line (names [0], ip);
1512                         } else {
1513                                 mn = g_strdup (names [0]);
1514                         }
1515                         free (names);
1516 #else
1517                         prof_ucounts++;
1518                         mn = g_strdup_printf ("unmanaged [%p]", ip);
1519 #endif
1520                 }
1521                 c = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, mn));
1522                 c++;
1523                 g_hash_table_insert (prof_table, mn, GUINT_TO_POINTER (c));
1524                 if (c > 1)
1525                         g_free (mn);
1526         }
1527         fprintf (poutput, "prof counts: total/unmanaged: %d/%d\n", pcount, prof_ucounts);
1528         g_hash_table_foreach (prof_table, (GHFunc)prof_foreach, &sorted);
1529         for (tmp = sorted; tmp; tmp = tmp->next) {
1530                 double perc;
1531                 c = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, tmp->data));
1532                 perc = c*100.0/count;
1533                 fprintf (poutput, "%7d\t%5.2f %% %s\n", c, perc, (char*)tmp->data);
1534         }
1535         g_list_free (sorted);
1536 }
1537
1538 static void
1539 simple_appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
1540 {
1541         prof->domains = g_slist_prepend (prof->domains, domain);
1542 }
1543
1544 static void
1545 simple_appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
1546 {
1547         /* FIXME: we should actually record partial data for each domain, 
1548          * but at this point it's must easier using the new logging profiler.
1549          */
1550         mono_profiler_shutdown ();
1551 }
1552
1553 static gint32 simple_shutdown_done = FALSE;
1554
1555 static void
1556 simple_shutdown (MonoProfiler *prof)
1557 {
1558         GList *profile = NULL;
1559         MonoProfiler *tprof;
1560         GSList *tmp;
1561         char *str;
1562         gint32 see_shutdown_done;
1563
1564 #ifndef HOST_WIN32
1565         mono_thread_attach(mono_get_root_domain());
1566 #endif
1567
1568         // Make sure we execute simple_shutdown only once
1569         see_shutdown_done = InterlockedExchange(& simple_shutdown_done, TRUE);
1570         if (see_shutdown_done)
1571                 return;
1572
1573         if (mono_profiler_events & MONO_PROFILE_STATISTICAL) {
1574                 stat_prof_report (prof);
1575         }
1576
1577         // Stop all incoming events
1578         mono_profiler_set_events (0);
1579         
1580         for (tmp = prof->per_thread; tmp; tmp = tmp->next) {
1581                 tprof = tmp->data;
1582                 merge_thread_data (prof, tprof);
1583         }
1584
1585         fprintf (poutput, "Total time spent compiling %d methods (sec): %.4g\n", prof->methods_jitted, prof->jit_time);
1586         if (prof->max_jit_method) {
1587                 str = method_get_name (prof->max_jit_method);
1588                 fprintf (poutput, "Slowest method to compile (sec): %.4g: %s\n", prof->max_jit_time, str);
1589                 g_free (str);
1590         }
1591         g_hash_table_foreach (prof->methods, (GHFunc)build_profile, &profile);
1592         output_profile (profile);
1593         g_list_free (profile);
1594         profile = NULL;
1595                 
1596         g_hash_table_foreach (prof->methods, (GHFunc)build_newobj_profile, &profile);
1597         output_newobj_profile (profile);
1598         g_list_free (profile);
1599
1600         g_free (prof_addresses);
1601         prof_addresses = NULL;
1602         g_hash_table_destroy (prof_table);
1603 }
1604
1605 static void
1606 mono_profiler_install_simple (const char *desc)
1607 {
1608         MonoProfiler *prof;
1609         gchar **args, **ptr;
1610         MonoProfileFlags flags = 0;
1611
1612         MONO_TIMER_STARTUP;
1613         poutput = stdout;
1614
1615         if (!desc)
1616                 desc = "alloc,time,jit";
1617
1618         if (desc) {
1619                 /* Parse options */
1620                 if (strstr (desc, ":"))
1621                         desc = strstr (desc, ":") + 1;
1622                 else
1623                         desc = "alloc,time,jit";
1624                 args = g_strsplit (desc, ",", -1);
1625
1626                 for (ptr = args; ptr && *ptr; ptr++) {
1627                         const char *arg = *ptr;
1628
1629                         // Alwais listen to appdomaon events to shutdown at the first unload
1630                         flags |= MONO_PROFILE_APPDOMAIN_EVENTS;
1631                         if (!strcmp (arg, "time"))
1632                                 flags |= MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_EXCEPTIONS;
1633                         else if (!strcmp (arg, "alloc"))
1634                                 flags |= MONO_PROFILE_ALLOCATIONS;
1635                         else if (!strcmp (arg, "stat"))
1636                                 flags |= MONO_PROFILE_STATISTICAL;
1637                         else if (!strcmp (arg, "jit"))
1638                                 flags |= MONO_PROFILE_JIT_COMPILATION;
1639                         else if (strncmp (arg, "file=", 5) == 0) {
1640                                 poutput = fopen (arg + 5, "wb");
1641                                 if (!poutput) {
1642                                         poutput = stdout;
1643                                         fprintf (stderr, "profiler : cannot open profile output file '%s'.\n", arg + 5);
1644                                 }
1645                         } else {
1646                                 fprintf (stderr, "profiler : Unknown argument '%s'.\n", arg);
1647                                 return;
1648                         }
1649                 }
1650         }
1651         if (flags & MONO_PROFILE_ALLOCATIONS)
1652                 flags |= MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_EXCEPTIONS;
1653         if (!flags)
1654                 flags = MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_ALLOCATIONS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_EXCEPTIONS;
1655
1656         prof = create_profiler ();
1657         ALLOC_PROFILER ();
1658         SET_PROFILER (prof);
1659
1660         /* statistical profiler data */
1661         prof_addresses = g_new0 (gpointer, MAX_PROF_SAMPLES);
1662         prof_table = g_hash_table_new (g_str_hash, g_str_equal);
1663
1664         mono_profiler_install (prof, simple_shutdown);
1665         mono_profiler_install_enter_leave (simple_method_enter, simple_method_leave);
1666         mono_profiler_install_exception (NULL, simple_method_leave, NULL);
1667         mono_profiler_install_jit_compile (simple_method_jit, simple_method_end_jit);
1668         mono_profiler_install_allocation (simple_allocation);
1669         mono_profiler_install_appdomain (NULL, simple_appdomain_load, simple_appdomain_unload, NULL);
1670         mono_profiler_install_statistical (simple_stat_hit);
1671         mono_profiler_set_events (flags);
1672 }
1673
1674 #endif /* DISABLE_PROFILER */
1675
1676 typedef void (*ProfilerInitializer) (const char*);
1677 #define INITIALIZER_NAME "mono_profiler_startup"
1678
1679 /**
1680  * mono_profiler_load:
1681  * @desc: arguments to configure the profiler
1682  *
1683  * Invoke this method to initialize the profiler.   This will drive the
1684  * loading of the internal ("default") or any external profilers.
1685  *
1686  * This routine is invoked by Mono's driver, but must be called manually
1687  * if you embed Mono into your application.
1688  */
1689 void 
1690 mono_profiler_load (const char *desc)
1691 {
1692         mono_gc_base_init ();
1693
1694 #ifndef DISABLE_PROFILER
1695         if (!desc || (strcmp ("default", desc) == 0) || (strncmp (desc, "default:", 8) == 0)) {
1696                 mono_profiler_install_simple (desc);
1697                 return;
1698         }
1699 #else
1700         if (!desc) {
1701                 desc = "default";
1702         }
1703 #endif
1704         {
1705                 MonoDl *pmodule = NULL;
1706                 const char* col = strchr (desc, ':');
1707                 char* libname;
1708                 char* path;
1709                 char *mname;
1710                 char *err;
1711                 void *iter;
1712                 if (col != NULL) {
1713                         mname = g_memdup (desc, col - desc + 1);
1714                         mname [col - desc] = 0;
1715                 } else {
1716                         mname = g_strdup (desc);
1717                 }
1718                 libname = g_strdup_printf ("mono-profiler-%s", mname);
1719                 iter = NULL;
1720                 err = NULL;
1721                 while ((path = mono_dl_build_path (NULL, libname, &iter))) {
1722                         g_free (err);
1723                         pmodule = mono_dl_open (path, MONO_DL_LAZY, &err);
1724                         if (pmodule) {
1725                                 ProfilerInitializer func;
1726                                 if ((err = mono_dl_symbol (pmodule, INITIALIZER_NAME, (gpointer *)&func))) {
1727                                         g_warning ("Cannot find initializer function %s in profiler module: %s (%s)", INITIALIZER_NAME, libname, err);
1728                                         g_free (err);
1729                                         err = NULL;
1730                                 } else {
1731                                         func (desc);
1732                                 }
1733                                 break;
1734                         }
1735                         g_free (path);
1736                 }
1737                 if (!pmodule) {
1738                         g_warning ("Error loading profiler module '%s': %s", libname, err);
1739                         g_free (err);
1740                 }
1741                 g_free (libname);
1742                 g_free (mname);
1743                 g_free (path);
1744         }
1745 }
1746