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