Fri Jan 26 12:00:45 CET 2007 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                         char *fname = NULL;
542                         offset = cil_code - start;
543                         entry.iloffset = offset;
544                         entry.method = method;
545                         entry.counter = info->data [i].count;
546                         entry.line = entry.col = 1;
547                         entry.filename = NULL;
548                         if (debug_minfo) {
549                                 MonoDebugSourceLocation *location;
550
551                                 location = mono_debug_symfile_lookup_location (debug_minfo, offset);
552                                 if (location) {
553                                         entry.line = location->row;
554                                         entry.col = location->column;
555                                         entry.filename = fname = g_strdup (location->source_file);
556                                         mono_debug_free_source_location (location);
557                                 }
558                         }
559
560                         func (prof, &entry);
561                         g_free (fname);
562                 }
563         }
564 }
565
566 #ifndef DISABLE_PROFILER
567 /*
568  * Small profiler extracted from mint: we should move it in a loadable module
569  * and improve it to do graphs and more accurate timestamping with rdtsc.
570  */
571
572 static FILE* poutput = NULL;
573
574 #define USE_X86TSC 0
575 #define USE_WIN32COUNTER 0
576 #if USE_X86TSC
577
578 typedef struct {
579         unsigned int lows, highs, lowe, highe;
580 } MonoRdtscTimer;
581
582 #define rdtsc(low,high) \
583         __asm__ __volatile__("rdtsc" : "=a" (low), "=d" (high))
584
585 static int freq;
586
587 static double
588 rdtsc_elapsed (MonoRdtscTimer *t)
589 {
590         unsigned long long diff;
591         unsigned int highe = t->highe;
592         if (t->lowe < t->lows)
593                 highe--;
594         diff = (((unsigned long long) highe - t->highs) << 32) + (t->lowe - t->lows);
595         return ((double)diff / freq) / 1000000; /* have to return the result in seconds */
596 }
597
598 static int 
599 have_rdtsc (void) {
600         char buf[256];
601         int have_freq = 0;
602         int have_flag = 0;
603         float val;
604         FILE *cpuinfo;
605
606         if (!(cpuinfo = fopen ("/proc/cpuinfo", "r")))
607                 return 0;
608         while (fgets (buf, sizeof(buf), cpuinfo)) {
609                 if (sscanf (buf, "cpu MHz : %f", &val) == 1) {
610                         /*printf ("got mh: %f\n", val);*/
611                         have_freq = val;
612                 }
613                 if (strncmp (buf, "flags", 5) == 0) {
614                         if (strstr (buf, "tsc")) {
615                                 have_flag = 1;
616                                 /*printf ("have tsc\n");*/
617                         }
618                 }
619         }
620         fclose (cpuinfo);
621         return have_flag? have_freq: 0;
622 }
623
624 #define MONO_TIMER_STARTUP      \
625         if (!(freq = have_rdtsc ())) g_error ("Compiled with TSC support, but none found");
626 #define MONO_TIMER_TYPE  MonoRdtscTimer
627 #define MONO_TIMER_INIT(t)
628 #define MONO_TIMER_DESTROY(t)
629 #define MONO_TIMER_START(t) rdtsc ((t).lows, (t).highs);
630 #define MONO_TIMER_STOP(t) rdtsc ((t).lowe, (t).highe);
631 #define MONO_TIMER_ELAPSED(t) rdtsc_elapsed (&(t))
632
633 #elif USE_WIN32COUNTER
634 #include <windows.h>
635
636 typedef struct {
637         LARGE_INTEGER start, stop;
638 } MonoWin32Timer;
639
640 static int freq;
641
642 static double
643 win32_elapsed (MonoWin32Timer *t)
644 {
645         LONGLONG diff = t->stop.QuadPart - t->start.QuadPart;
646         return ((double)diff / freq) / 1000000; /* have to return the result in seconds */
647 }
648
649 static int 
650 have_win32counter (void) {
651         LARGE_INTEGER f;
652
653         if (!QueryPerformanceFrequency (&f))
654                 return 0;
655         return f.LowPart;
656 }
657
658 #define MONO_TIMER_STARTUP      \
659         if (!(freq = have_win32counter ())) g_error ("Compiled with Win32 counter support, but none found");
660 #define MONO_TIMER_TYPE  MonoWin32Timer
661 #define MONO_TIMER_INIT(t)
662 #define MONO_TIMER_DESTROY(t)
663 #define MONO_TIMER_START(t) QueryPerformanceCounter (&(t).start)
664 #define MONO_TIMER_STOP(t) QueryPerformanceCounter (&(t).stop)
665 #define MONO_TIMER_ELAPSED(t) win32_elapsed (&(t))
666
667 #else
668
669 typedef struct {
670         GTimeVal start, stop;
671 } MonoGLibTimer;
672
673 static double
674 timeval_elapsed (MonoGLibTimer *t)
675 {
676         if (t->start.tv_usec > t->stop.tv_usec) {
677                 t->stop.tv_usec += G_USEC_PER_SEC;
678                 t->stop.tv_sec--;
679         }
680         return (t->stop.tv_sec - t->start.tv_sec) 
681                 + ((double)(t->stop.tv_usec - t->start.tv_usec))/ G_USEC_PER_SEC;
682 }
683
684 #define MONO_TIMER_STARTUP
685 #define MONO_TIMER_TYPE MonoGLibTimer
686 #define MONO_TIMER_INIT(t)
687 #define MONO_TIMER_DESTROY(t)
688 #define MONO_TIMER_START(t) g_get_current_time (&(t).start)
689 #define MONO_TIMER_STOP(t) g_get_current_time (&(t).stop)
690 #define MONO_TIMER_ELAPSED(t) timeval_elapsed (&(t))
691 #endif
692
693 typedef struct _AllocInfo AllocInfo;
694 typedef struct _CallerInfo CallerInfo;
695 typedef struct _LastCallerInfo LastCallerInfo;
696
697 struct _MonoProfiler {
698         GHashTable *methods;
699         MonoMemPool *mempool;
700         /* info about JIT time */
701         MONO_TIMER_TYPE jit_timer;
702         double      jit_time;
703         double      max_jit_time;
704         MonoMethod *max_jit_method;
705         int         methods_jitted;
706         
707         GSList     *per_thread;
708         
709         /* chain of callers for the current thread */
710         LastCallerInfo *callers;
711         /* LastCallerInfo nodes for faster allocation */
712         LastCallerInfo *cstorage;
713 };
714
715 typedef struct {
716         MonoMethod *method;
717         guint64 count;
718         double total;
719         AllocInfo *alloc_info;
720         CallerInfo *caller_info;
721 } MethodProfile;
722
723 typedef struct _MethodCallProfile MethodCallProfile;
724
725 struct _MethodCallProfile {
726         MethodCallProfile *next;
727         MONO_TIMER_TYPE timer;
728         MonoMethod *method;
729 };
730
731 struct _AllocInfo {
732         AllocInfo *next;
733         MonoClass *klass;
734         guint64 count;
735         guint64 mem;
736 };
737
738 struct _CallerInfo {
739         CallerInfo *next;
740         MonoMethod *caller;
741         guint count;
742 };
743
744 struct _LastCallerInfo {
745         LastCallerInfo *next;
746         MonoMethod *method;
747         MONO_TIMER_TYPE timer;
748 };
749
750 static MonoProfiler*
751 create_profiler (void)
752 {
753         MonoProfiler *prof = g_new0 (MonoProfiler, 1);
754
755         prof->methods = g_hash_table_new (mono_aligned_addr_hash, NULL);
756         MONO_TIMER_INIT (prof->jit_timer);
757         prof->mempool = mono_mempool_new ();
758         return prof;
759 }
760 #if 1
761
762 #ifdef HAVE_KW_THREAD
763         static __thread MonoProfiler * tls_profiler;
764 #       define GET_PROFILER() tls_profiler
765 #       define SET_PROFILER(x) tls_profiler = (x)
766 #       define ALLOC_PROFILER() /* nop */
767 #else
768         static guint32 profiler_thread_id = -1;
769 #       define GET_PROFILER() ((MonoProfiler *)TlsGetValue (profiler_thread_id))
770 #       define SET_PROFILER(x) TlsSetValue (profiler_thread_id, x);
771 #       define ALLOC_PROFILER() profiler_thread_id = TlsAlloc ()
772 #endif
773
774 #define GET_THREAD_PROF(prof) do {                                                           \
775                 MonoProfiler *_tprofiler = GET_PROFILER ();                                  \
776                 if (!_tprofiler) {                                                           \
777                         _tprofiler = create_profiler ();                                     \
778                         prof->per_thread = g_slist_prepend (prof->per_thread, _tprofiler);   \
779                         SET_PROFILER (_tprofiler);                                           \
780                 }                                                                            \
781                 prof = _tprofiler;                                                           \
782         } while (0)
783 #else
784 /* thread unsafe but faster variant */
785 #define GET_THREAD_PROF(prof)
786 #endif
787
788 static gint
789 compare_profile (MethodProfile *profa, MethodProfile *profb)
790 {
791         return (gint)((profb->total - profa->total)*1000);
792 }
793
794 static void
795 build_profile (MonoMethod *m, MethodProfile *prof, GList **funcs)
796 {
797         prof->method = m;
798         *funcs = g_list_insert_sorted (*funcs, prof, (GCompareFunc)compare_profile);
799 }
800
801 static char*
802 method_get_name (MonoMethod* method)
803 {
804         char *sig, *res;
805         
806         sig = mono_signature_get_desc (mono_method_signature (method), FALSE);
807         res = g_strdup_printf ("%s%s%s::%s(%s)", method->klass->name_space,
808                         method->klass->name_space ? "." : "", method->klass->name,
809                 method->name, sig);
810         g_free (sig);
811         return res;
812 }
813
814 static void output_callers (MethodProfile *p);
815
816 static void
817 output_profile (GList *funcs)
818 {
819         GList *tmp;
820         MethodProfile *p;
821         char *m;
822         guint64 total_calls = 0;
823
824         if (funcs)
825                 fprintf (poutput, "Time(ms) Count   P/call(ms) Method name\n");
826         for (tmp = funcs; tmp; tmp = tmp->next) {
827                 p = tmp->data;
828                 total_calls += p->count;
829                 if (!(gint)(p->total*1000))
830                         continue;
831                 m = method_get_name (p->method);
832                 fprintf (poutput, "########################\n");
833                 fprintf (poutput, "% 8.3f ", (double) (p->total * 1000));
834                 fprintf (poutput, "%7llu ", (unsigned long long)p->count);
835                 fprintf (poutput, "% 8.3f ", (double) (p->total * 1000)/(double)p->count);
836                 fprintf (poutput, "  %s\n", m);
837
838                 g_free (m);
839                 /* callers */
840                 output_callers (p);
841         }
842         fprintf (poutput, "Total number of calls: %lld\n", (long long)total_calls);
843 }
844
845 typedef struct {
846         MethodProfile *mp;
847         guint64 count;
848 } NewobjProfile;
849
850 static gint
851 compare_newobj_profile (NewobjProfile *profa, NewobjProfile *profb)
852 {
853         if (profb->count == profa->count)
854                 return 0;
855         else
856                 return profb->count > profa->count ? 1 : -1;
857 }
858
859 static void
860 build_newobj_profile (MonoClass *class, MethodProfile *mprof, GList **funcs)
861 {
862         NewobjProfile *prof = g_new (NewobjProfile, 1);
863         AllocInfo *tmp;
864         guint64 count = 0;
865         
866         prof->mp = mprof;
867         /* we use the total amount of memory to sort */
868         for (tmp = mprof->alloc_info; tmp; tmp = tmp->next)
869                 count += tmp->mem;
870         prof->count = count;
871         *funcs = g_list_insert_sorted (*funcs, prof, (GCompareFunc)compare_newobj_profile);
872 }
873
874 static int
875 compare_caller (CallerInfo *a, CallerInfo *b)
876 {
877         return b->count - a->count;
878 }
879
880 static int
881 compare_alloc (AllocInfo *a, AllocInfo *b)
882 {
883         return b->mem - a->mem;
884 }
885
886 static GSList*
887 sort_alloc_list (AllocInfo *ai)
888 {
889         GSList *l = NULL;
890         AllocInfo *tmp;
891         for (tmp = ai; tmp; tmp = tmp->next) {
892                 l = g_slist_insert_sorted (l, tmp, (GCompareFunc)compare_alloc);
893         }
894         return l;
895 }
896
897 static GSList*
898 sort_caller_list (CallerInfo *ai)
899 {
900         GSList *l = NULL;
901         CallerInfo *tmp;
902         for (tmp = ai; tmp; tmp = tmp->next) {
903                 l = g_slist_insert_sorted (l, tmp, (GCompareFunc)compare_caller);
904         }
905         return l;
906 }
907
908 static void
909 output_callers (MethodProfile *p) {
910         guint total_callers, percent;
911         GSList *sorted, *tmps;
912         CallerInfo *cinfo;
913         char *m;
914         
915         fprintf (poutput, "  Callers (with count) that contribute at least for 1%%:\n");
916         total_callers = 0;
917         for (cinfo = p->caller_info; cinfo; cinfo = cinfo->next) {
918                 total_callers += cinfo->count;
919         }
920         sorted = sort_caller_list (p->caller_info);
921         for (tmps = sorted; tmps; tmps = tmps->next) {
922                 cinfo = tmps->data;
923                 percent = (cinfo->count * 100)/total_callers;
924                 if (percent < 1)
925                         continue;
926                 m = method_get_name (cinfo->caller);
927                 fprintf (poutput, "    %8d % 3d %% %s\n", cinfo->count, percent, m);
928                 g_free (m);
929         }
930 }
931
932 /* This isn't defined on older glib versions and on some platforms */
933 #ifndef G_GUINT64_FORMAT
934 #define G_GUINT64_FORMAT "ul"
935 #endif
936
937 static void
938 output_newobj_profile (GList *proflist)
939 {
940         GList *tmp;
941         NewobjProfile *p;
942         MethodProfile *mp;
943         AllocInfo *ainfo;
944         MonoClass *klass;
945         const char* isarray;
946         char buf [256];
947         char *m;
948         guint64 total = 0;
949         GSList *sorted, *tmps;
950
951         fprintf (poutput, "\nAllocation profiler\n");
952
953         if (proflist)
954                 fprintf (poutput, "%-9s %s\n", "Total mem", "Method");
955         for (tmp = proflist; tmp; tmp = tmp->next) {
956                 p = tmp->data;
957                 total += p->count;
958                 if (p->count < 50000)
959                         continue;
960                 mp = p->mp;
961                 m = method_get_name (mp->method);
962                 fprintf (poutput, "########################\n%8" G_GUINT64_FORMAT " KB %s\n", (p->count / 1024), m);
963                 g_free (m);
964                 sorted = sort_alloc_list (mp->alloc_info);
965                 for (tmps = sorted; tmps; tmps = tmps->next) {
966                         ainfo = tmps->data;
967                         if (ainfo->mem < 50000)
968                                 continue;
969                         klass = ainfo->klass;
970                         if (klass->rank) {
971                                 isarray = "[]";
972                                 klass = klass->element_class;
973                         } else {
974                                 isarray = "";
975                         }
976                         g_snprintf (buf, sizeof (buf), "%s%s%s%s",
977                                 klass->name_space, klass->name_space ? "." : "", klass->name, isarray);
978                         fprintf (poutput, "    %8" G_GUINT64_FORMAT " KB %8" G_GUINT64_FORMAT " %-48s\n", (ainfo->mem / 1024), ainfo->count, buf);
979                 }
980                 /* callers */
981                 output_callers (mp);
982         }
983         fprintf (poutput, "Total memory allocated: %" G_GUINT64_FORMAT " KB\n", total / 1024);
984 }
985
986 static void
987 merge_methods (MonoMethod *method, MethodProfile *profile, MonoProfiler *prof)
988 {
989         MethodProfile *mprof;
990         AllocInfo *talloc_info, *alloc_info;
991         CallerInfo *tcaller_info, *caller_info;
992
993         mprof = g_hash_table_lookup (prof->methods, method);
994         if (!mprof) {
995                 /* the master thread didn't see this method, just transfer the info as is */
996                 g_hash_table_insert (prof->methods, method, profile);
997                 return;
998         }
999         /* merge the info from profile into mprof */
1000         mprof->count += profile->count;
1001         mprof->total += profile->total;
1002         /* merge alloc info */
1003         for (talloc_info = profile->alloc_info; talloc_info; talloc_info = talloc_info->next) {
1004                 for (alloc_info = mprof->alloc_info; alloc_info; alloc_info = alloc_info->next) {
1005                         if (alloc_info->klass == talloc_info->klass) {
1006                                 /* mprof already has a record for the klass, merge */
1007                                 alloc_info->count += talloc_info->count;
1008                                 alloc_info->mem += talloc_info->mem;
1009                                 break;
1010                         }
1011                 }
1012                 if (!alloc_info) {
1013                         /* mprof didn't have the info, just copy it over */
1014                         alloc_info = mono_mempool_alloc0 (prof->mempool, sizeof (AllocInfo));
1015                         *alloc_info = *talloc_info;
1016                         alloc_info->next = mprof->alloc_info;
1017                         mprof->alloc_info = alloc_info->next;
1018                 }
1019         }
1020         /* merge callers info */
1021         for (tcaller_info = profile->caller_info; tcaller_info; tcaller_info = tcaller_info->next) {
1022                 for (caller_info = mprof->caller_info; caller_info; caller_info = caller_info->next) {
1023                         if (caller_info->caller == tcaller_info->caller) {
1024                                 /* mprof already has a record for the caller method, merge */
1025                                 caller_info->count += tcaller_info->count;
1026                                 break;
1027                         }
1028                 }
1029                 if (!caller_info) {
1030                         /* mprof didn't have the info, just copy it over */
1031                         caller_info = mono_mempool_alloc0 (prof->mempool, sizeof (CallerInfo));
1032                         *caller_info = *tcaller_info;
1033                         caller_info->next = mprof->caller_info;
1034                         mprof->caller_info = caller_info;
1035                 }
1036         }
1037 }
1038
1039 static void
1040 merge_thread_data (MonoProfiler *master, MonoProfiler *tprof)
1041 {
1042         master->jit_time += tprof->jit_time;
1043         master->methods_jitted += tprof->methods_jitted;
1044         if (master->max_jit_time < tprof->max_jit_time) {
1045                 master->max_jit_time = tprof->max_jit_time;
1046                 master->max_jit_method = tprof->max_jit_method;
1047         }
1048
1049         g_hash_table_foreach (tprof->methods, (GHFunc)merge_methods, master);
1050 }
1051
1052 static void
1053 simple_method_enter (MonoProfiler *prof, MonoMethod *method)
1054 {
1055         MethodProfile *profile_info;
1056         LastCallerInfo *callinfo;
1057         GET_THREAD_PROF (prof);
1058         /*g_print ("enter %p %s::%s in %d (%p)\n", method, method->klass->name, method->name, GetCurrentThreadId (), prof);*/
1059         if (!(profile_info = g_hash_table_lookup (prof->methods, method))) {
1060                 profile_info = mono_mempool_alloc0 (prof->mempool, sizeof (MethodProfile));
1061                 MONO_TIMER_INIT (profile_info->u.timer);
1062                 g_hash_table_insert (prof->methods, method, profile_info);
1063         }
1064         profile_info->count++;
1065         if (prof->callers) {
1066                 CallerInfo *cinfo;
1067                 MonoMethod *caller = prof->callers->method;
1068                 for (cinfo = profile_info->caller_info; cinfo; cinfo = cinfo->next) {
1069                         if (cinfo->caller == caller)
1070                                 break;
1071                 }
1072                 if (!cinfo) {
1073                         cinfo = mono_mempool_alloc0 (prof->mempool, sizeof (CallerInfo));
1074                         cinfo->caller = caller;
1075                         cinfo->next = profile_info->caller_info;
1076                         profile_info->caller_info = cinfo;
1077                 }
1078                 cinfo->count++;
1079         }
1080         if (!(callinfo = prof->cstorage)) {
1081                 callinfo = mono_mempool_alloc (prof->mempool, sizeof (LastCallerInfo));
1082                 MONO_TIMER_INIT (callinfo->timer);
1083         } else {
1084                 prof->cstorage = prof->cstorage->next;
1085         }
1086         callinfo->method = method;
1087         callinfo->next = prof->callers;
1088         prof->callers = callinfo;
1089         MONO_TIMER_START (callinfo->timer);
1090 }
1091
1092 static void
1093 simple_method_leave (MonoProfiler *prof, MonoMethod *method)
1094 {
1095         MethodProfile *profile_info;
1096         LastCallerInfo *callinfo, *newcallinfo = NULL;
1097         
1098         GET_THREAD_PROF (prof);
1099         /*g_print ("leave %p %s::%s in %d (%p)\n", method, method->klass->name, method->name, GetCurrentThreadId (), prof);*/
1100         callinfo = prof->callers;
1101         /* should really not happen, but we don't catch exceptions events, yet ... */
1102         while (callinfo) {
1103                 MONO_TIMER_STOP (callinfo->timer);
1104                 profile_info = g_hash_table_lookup (prof->methods, callinfo->method);
1105                 if (profile_info)
1106                         profile_info->total += MONO_TIMER_ELAPSED (callinfo->timer);
1107                 newcallinfo = callinfo->next;
1108                 callinfo->next = prof->cstorage;
1109                 prof->cstorage = callinfo;
1110                 if (callinfo->method == method)
1111                         break;
1112                 callinfo = newcallinfo;
1113         }
1114         prof->callers = newcallinfo;
1115 }
1116
1117 static void
1118 simple_allocation (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1119 {
1120         MethodProfile *profile_info;
1121         AllocInfo *tmp;
1122
1123         GET_THREAD_PROF (prof);
1124         if (prof->callers) {
1125                 MonoMethod *caller = prof->callers->method;
1126
1127                 /* Otherwise all allocations are attributed to icall_wrapper_mono_object_new */
1128                 if (caller->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
1129                         caller = prof->callers->next->method;
1130
1131                 if (!(profile_info = g_hash_table_lookup (prof->methods, caller)))
1132                         g_assert_not_reached ();
1133         } else {
1134                 return; /* fine for now */
1135         }
1136
1137         for (tmp = profile_info->alloc_info; tmp; tmp = tmp->next) {
1138                 if (tmp->klass == klass)
1139                         break;
1140         }
1141         if (!tmp) {
1142                 tmp = mono_mempool_alloc0 (prof->mempool, sizeof (AllocInfo));
1143                 tmp->klass = klass;
1144                 tmp->next = profile_info->alloc_info;
1145                 profile_info->alloc_info = tmp;
1146         }
1147         tmp->count++;
1148         tmp->mem += mono_object_get_size (obj);
1149 }
1150
1151 static void
1152 simple_method_jit (MonoProfiler *prof, MonoMethod *method)
1153 {
1154         GET_THREAD_PROF (prof);
1155         prof->methods_jitted++;
1156         MONO_TIMER_START (prof->jit_timer);
1157 }
1158
1159 static void
1160 simple_method_end_jit (MonoProfiler *prof, MonoMethod *method, int result)
1161 {
1162         double jtime;
1163         GET_THREAD_PROF (prof);
1164         MONO_TIMER_STOP (prof->jit_timer);
1165         jtime = MONO_TIMER_ELAPSED (prof->jit_timer);
1166         prof->jit_time += jtime;
1167         if (jtime > prof->max_jit_time) {
1168                 prof->max_jit_time = jtime;
1169                 prof->max_jit_method = method;
1170         }
1171 }
1172
1173 /* about 10 minutes of samples */
1174 #define MAX_PROF_SAMPLES (1000*60*10)
1175 static int prof_counts = 0;
1176 static int prof_ucounts = 0;
1177 static gpointer* prof_addresses = NULL;
1178 static GHashTable *prof_table = NULL;
1179
1180 static void
1181 simple_stat_hit (MonoProfiler *prof, guchar *ip, void *context)
1182 {
1183         int pos;
1184
1185         if (prof_counts >= MAX_PROF_SAMPLES)
1186                 return;
1187         pos = InterlockedIncrement (&prof_counts);
1188         prof_addresses [pos - 1] = ip;
1189 }
1190
1191 static int
1192 compare_methods_prof (gconstpointer a, gconstpointer b)
1193 {
1194         int ca = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, a));
1195         int cb = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, b));
1196         return cb-ca;
1197 }
1198
1199 static void
1200 prof_foreach (char *method, gpointer c, gpointer data)
1201 {
1202         GList **list = data;
1203         *list = g_list_insert_sorted (*list, method, compare_methods_prof);
1204 }
1205
1206 typedef struct Addr2LineData Addr2LineData;
1207
1208 struct Addr2LineData {
1209         Addr2LineData *next;
1210         FILE *pipein;
1211         FILE *pipeout;
1212         char *binary;
1213         int child_pid;
1214 };
1215
1216 static Addr2LineData *addr2line_pipes = NULL;
1217
1218 static char*
1219 try_addr2line (const char* binary, gpointer ip)
1220 {
1221         char buf [1024];
1222         char *res;
1223         Addr2LineData *addr2line;
1224
1225         for (addr2line = addr2line_pipes; addr2line; addr2line = addr2line->next) {
1226                 if (strcmp (binary, addr2line->binary) == 0)
1227                         break;
1228         }
1229         if (!addr2line) {
1230                 const char *addr_argv[] = {"addr2line", "-f", "-e", binary, NULL};
1231                 int child_pid;
1232                 int ch_in, ch_out;
1233 #ifdef __linux__
1234                 char monobin [1024];
1235                 /* non-linux platforms will need different code here */
1236                 if (strcmp (binary, "mono") == 0) {
1237                         int count = readlink ("/proc/self/exe", monobin, sizeof (monobin));
1238                         if (count >= 0 && count < sizeof (monobin)) {
1239                                 monobin [count] = 0;
1240                                 addr_argv [3] = monobin;
1241                         }
1242                 }
1243 #endif
1244                 if (!g_spawn_async_with_pipes (NULL, (char**)addr_argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
1245                                 &child_pid, &ch_in, &ch_out, NULL, NULL)) {
1246                         return g_strdup (binary);
1247                 }
1248                 addr2line = g_new0 (Addr2LineData, 1);
1249                 addr2line->child_pid = child_pid;
1250                 addr2line->binary = g_strdup (binary);
1251                 addr2line->pipein = fdopen (ch_in, "w");
1252                 addr2line->pipeout = fdopen (ch_out, "r");
1253                 addr2line->next = addr2line_pipes;
1254                 addr2line_pipes = addr2line;
1255         }
1256         fprintf (addr2line->pipein, "%p\n", ip);
1257         fflush (addr2line->pipein);
1258         /* we first get the func name and then file:lineno in a second line */
1259         if (fgets (buf, sizeof (buf), addr2line->pipeout) && buf [0] != '?') {
1260                 char *end = strchr (buf, '\n');
1261                 if (end)
1262                         *end = 0;
1263                 res = g_strdup_printf ("%s(%s", binary, buf);
1264                 /* discard the filename/line info */
1265                 fgets (buf, sizeof (buf), addr2line->pipeout);
1266         } else {
1267                 res = g_strdup (binary);
1268         }
1269         return res;
1270 }
1271
1272 static void
1273 stat_prof_report (void)
1274 {
1275         MonoJitInfo *ji;
1276         int count = prof_counts;
1277         int i, c;
1278         char *mn;
1279         gpointer ip;
1280         GList *tmp, *sorted = NULL;
1281         int pcount = ++ prof_counts;
1282
1283         prof_counts = MAX_PROF_SAMPLES;
1284         for (i = 0; i < count; ++i) {
1285                 ip = prof_addresses [i];
1286                 ji = mono_jit_info_table_find (mono_domain_get (), ip);
1287                 if (ji) {
1288                         mn = mono_method_full_name (ji->method, TRUE);
1289                 } else {
1290 #ifdef HAVE_BACKTRACE_SYMBOLS
1291                         char **names;
1292                         char *send;
1293                         int no_func;
1294                         prof_ucounts++;
1295                         names = backtrace_symbols (&ip, 1);
1296                         send = strchr (names [0], '+');
1297                         if (send) {
1298                                 *send = 0;
1299                                 no_func = 0;
1300                         } else {
1301                                 no_func = 1;
1302                         }
1303                         send = strchr (names [0], '[');
1304                         if (send)
1305                                 *send = 0;
1306                         if (no_func && names [0][0]) {
1307                                 char *endp = strchr (names [0], 0);
1308                                 while (--endp >= names [0] && g_ascii_isspace (*endp))
1309                                         *endp = 0;
1310                                 mn = try_addr2line (names [0], ip);
1311                         } else {
1312                                 mn = g_strdup (names [0]);
1313                         }
1314                         free (names);
1315 #else
1316                         prof_ucounts++;
1317                         mn = g_strdup_printf ("unmanaged [%p]", ip);
1318 #endif
1319                 }
1320                 c = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, mn));
1321                 c++;
1322                 g_hash_table_insert (prof_table, mn, GUINT_TO_POINTER (c));
1323                 if (c > 1)
1324                         g_free (mn);
1325         }
1326         fprintf (poutput, "prof counts: total/unmanaged: %d/%d\n", pcount, prof_ucounts);
1327         g_hash_table_foreach (prof_table, (GHFunc)prof_foreach, &sorted);
1328         for (tmp = sorted; tmp; tmp = tmp->next) {
1329                 double perc;
1330                 c = GPOINTER_TO_UINT (g_hash_table_lookup (prof_table, tmp->data));
1331                 perc = c*100.0/count;
1332                 fprintf (poutput, "%7d\t%5.2f %% %s\n", c, perc, (char*)tmp->data);
1333         }
1334         g_list_free (sorted);
1335 }
1336
1337 static void
1338 simple_appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
1339 {
1340         /* FIXME: we should actually record partial data for each domain, 
1341          * since the ip->ji->method mappings are going away at domain unload time.
1342          */
1343         if (domain == mono_get_root_domain ())
1344                 stat_prof_report ();
1345 }
1346
1347 static void
1348 simple_shutdown (MonoProfiler *prof)
1349 {
1350         GList *profile = NULL;
1351         MonoProfiler *tprof;
1352         GSList *tmp;
1353         char *str;
1354
1355         for (tmp = prof->per_thread; tmp; tmp = tmp->next) {
1356                 tprof = tmp->data;
1357                 merge_thread_data (prof, tprof);
1358         }
1359
1360         fprintf (poutput, "Total time spent compiling %d methods (sec): %.4g\n", prof->methods_jitted, prof->jit_time);
1361         if (prof->max_jit_method) {
1362                 str = method_get_name (prof->max_jit_method);
1363                 fprintf (poutput, "Slowest method to compile (sec): %.4g: %s\n", prof->max_jit_time, str);
1364                 g_free (str);
1365         }
1366         g_hash_table_foreach (prof->methods, (GHFunc)build_profile, &profile);
1367         output_profile (profile);
1368         g_list_free (profile);
1369         profile = NULL;
1370                 
1371         g_hash_table_foreach (prof->methods, (GHFunc)build_newobj_profile, &profile);
1372         output_newobj_profile (profile);
1373         g_list_free (profile);
1374
1375         g_free (prof_addresses);
1376         prof_addresses = NULL;
1377         g_hash_table_destroy (prof_table);
1378 }
1379
1380 static void
1381 mono_profiler_install_simple (const char *desc)
1382 {
1383         MonoProfiler *prof;
1384         gchar **args, **ptr;
1385         MonoProfileFlags flags = 0;
1386
1387         MONO_TIMER_STARTUP;
1388         poutput = stdout;
1389
1390         if (!desc)
1391                 desc = "alloc,time,jit";
1392
1393         if (desc) {
1394                 /* Parse options */
1395                 if (strstr (desc, ":"))
1396                         desc = strstr (desc, ":") + 1;
1397                 else
1398                         desc = "alloc,time,jit";
1399                 args = g_strsplit (desc, ",", -1);
1400
1401                 for (ptr = args; ptr && *ptr; ptr++) {
1402                         const char *arg = *ptr;
1403
1404                         if (!strcmp (arg, "time"))
1405                                 flags |= MONO_PROFILE_ENTER_LEAVE;
1406                         else if (!strcmp (arg, "alloc"))
1407                                 flags |= MONO_PROFILE_ALLOCATIONS;
1408                         else if (!strcmp (arg, "stat"))
1409                                 flags |= MONO_PROFILE_STATISTICAL | MONO_PROFILE_APPDOMAIN_EVENTS;
1410                         else if (!strcmp (arg, "jit"))
1411                                 flags |= MONO_PROFILE_JIT_COMPILATION;
1412                         else if (strncmp (arg, "file=", 5) == 0) {
1413                                 poutput = fopen (arg + 5, "wb");
1414                                 if (!poutput) {
1415                                         poutput = stdout;
1416                                         fprintf (stderr, "profiler : cannot open profile output file '%s'.\n", arg + 5);
1417                                 }
1418                         } else {
1419                                 fprintf (stderr, "profiler : Unknown argument '%s'.\n", arg);
1420                                 return;
1421                         }
1422                 }
1423         }
1424         if (flags & MONO_PROFILE_ALLOCATIONS)
1425                 flags |= MONO_PROFILE_ENTER_LEAVE;
1426         if (!flags)
1427                 flags = MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_ALLOCATIONS | MONO_PROFILE_JIT_COMPILATION;
1428
1429         prof = create_profiler ();
1430         ALLOC_PROFILER ();
1431         SET_PROFILER (prof);
1432
1433         /* statistical profiler data */
1434         prof_addresses = g_new0 (gpointer, MAX_PROF_SAMPLES);
1435         prof_table = g_hash_table_new (g_str_hash, g_str_equal);
1436
1437         mono_profiler_install (prof, simple_shutdown);
1438         mono_profiler_install_enter_leave (simple_method_enter, simple_method_leave);
1439         mono_profiler_install_jit_compile (simple_method_jit, simple_method_end_jit);
1440         mono_profiler_install_allocation (simple_allocation);
1441         mono_profiler_install_appdomain (NULL, NULL, simple_appdomain_unload, NULL);
1442         mono_profiler_install_statistical (simple_stat_hit);
1443         mono_profiler_set_events (flags);
1444 }
1445
1446 #endif /* DISABLE_PROFILER */
1447
1448 typedef void (*ProfilerInitializer) (const char*);
1449 #define INITIALIZER_NAME "mono_profiler_startup"
1450
1451 /**
1452  * mono_profiler_load:
1453  * @desc: arguments to configure the profiler
1454  *
1455  * Invoke this method to initialize the profiler.   This will drive the
1456  * loading of the internal ("default") or any external profilers.
1457  *
1458  * This routine is invoked by Mono's driver, but must be called manually
1459  * if you embed Mono into your application.
1460  */
1461 void 
1462 mono_profiler_load (const char *desc)
1463 {
1464 #ifndef DISABLE_PROFILER
1465         if (!desc || (strcmp ("default", desc) == 0) || (strncmp (desc, "default:", 8) == 0)) {
1466                 mono_profiler_install_simple (desc);
1467                 return;
1468         }
1469 #else
1470         if (!desc) {
1471                 desc = "default";
1472         }
1473 #endif
1474         {
1475                 MonoDl *pmodule;
1476                 const char* col = strchr (desc, ':');
1477                 char* libname;
1478                 char* path;
1479                 char *mname;
1480                 char *err;
1481                 void *iter;
1482                 if (col != NULL) {
1483                         mname = g_memdup (desc, col - desc);
1484                         mname [col - desc] = 0;
1485                 } else {
1486                         mname = g_strdup (desc);
1487                 }
1488                 libname = g_strdup_printf ("mono-profiler-%s", mname);
1489                 iter = NULL;
1490                 err = NULL;
1491                 while ((path = mono_dl_build_path (NULL, libname, &iter))) {
1492                         g_free (err);
1493                         pmodule = mono_dl_open (path, MONO_DL_LAZY, &err);
1494                         if (pmodule) {
1495                                 ProfilerInitializer func;
1496                                 if ((err = mono_dl_symbol (pmodule, INITIALIZER_NAME, (gpointer *)&func))) {
1497                                         g_warning ("Cannot find initializer function %s in profiler module: %s (%s)", INITIALIZER_NAME, libname, err);
1498                                         g_free (err);
1499                                         err = NULL;
1500                                 } else {
1501                                         func (desc);
1502                                 }
1503                                 break;
1504                         }
1505                         g_free (path);
1506                 }
1507                 if (!pmodule) {
1508                         g_warning ("Error loading profiler module '%s': %s", libname, err);
1509                         g_free (err);
1510                 }
1511                 g_free (libname);
1512                 g_free (mname);
1513                 g_free (path);
1514         }
1515 }
1516