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