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