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