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