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