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