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