0a33040a73dad76eee8e08ed67ef3ae928c7d3cf
[mono.git] / mono / profiler / decode.c
1 /*
2  * decode.c: mprof-report program source: decode and analyze the log profiler data
3  *
4  * Author:
5  *   Paolo Molaro (lupus@ximian.com)
6  *
7  * Copyright 2010 Novell, Inc (http://www.novell.com)
8  */
9 #include <config.h>
10 #include "utils.c"
11 #include "proflog.h"
12 #include <string.h>
13 #include <assert.h>
14 #include <stdio.h>
15 #if !defined(__APPLE__)
16 #include <malloc.h>
17 #endif
18 #include <unistd.h>
19 #include <stdlib.h>
20 #if defined (HAVE_SYS_ZLIB)
21 #include <zlib.h>
22 #endif
23 #include <mono/metadata/profiler.h>
24 #include <mono/metadata/object.h>
25 #include <mono/metadata/debug-helpers.h>
26
27 #define HASH_SIZE 9371
28 #define SMALL_HASH_SIZE 31
29
30 static int debug = 0;
31 static int collect_traces = 0;
32 static int show_traces = 0;
33 static int trace_max = 6;
34 static int verbose = 0;
35 static uintptr_t *tracked_objects = 0;
36 static int num_tracked_objects = 0;
37 static uintptr_t thread_filter = 0;
38 static uint64_t find_size = 0;
39 static const char* find_name = NULL;
40 static uint64_t time_from = 0;
41 static uint64_t time_to = 0xffffffffffffffffULL;
42 static uint64_t startup_time = 0;
43 static FILE* outfile = NULL;
44
45 static int32_t
46 read_int32 (unsigned char *p)
47 {
48         int32_t value = *p++;
49         value |= (*p++) << 8;
50         value |= (*p++) << 16;
51         value |= (uint32_t)(*p++) << 24;
52         return value;
53 }
54
55 static int64_t
56 read_int64 (unsigned char *p)
57 {
58         uint64_t value = *p++;
59         value |= (*p++) << 8;
60         value |= (*p++) << 16;
61         value |= (uint64_t)(*p++) << 24;
62         value |= (uint64_t)(*p++) << 32;
63         value |= (uint64_t)(*p++) << 40;
64         value |= (uint64_t)(*p++) << 48;
65         value |= (uint64_t)(*p++) << 54;
66         return value;
67 }
68
69 static char*
70 pstrdup (const char *s)
71 {
72         int len = strlen (s) + 1;
73         char *p = malloc (len);
74         memcpy (p, s, len);
75         return p;
76 }
77
78 static int num_images;
79 typedef struct _ImageDesc ImageDesc;
80 struct _ImageDesc {
81         ImageDesc *next;
82         intptr_t image;
83         char *filename;
84 };
85
86 static ImageDesc* image_hash [SMALL_HASH_SIZE] = {0};
87
88 static void
89 add_image (intptr_t image, char *name)
90 {
91         int slot = ((image >> 2) & 0xffff) % SMALL_HASH_SIZE;
92         ImageDesc *cd = malloc (sizeof (ImageDesc));
93         cd->image = image;
94         cd->filename = pstrdup (name);
95         cd->next = image_hash [slot];
96         image_hash [slot] = cd;
97         num_images++;
98 }
99
100 typedef struct _BackTrace BackTrace;
101 typedef struct {
102         uint64_t count;
103         BackTrace *bt;
104 } CallContext;
105
106 typedef struct {
107         int count;
108         int size;
109         CallContext *traces;
110 } TraceDesc;
111
112 typedef struct _ClassDesc ClassDesc;
113 struct _ClassDesc {
114         ClassDesc *next;
115         intptr_t klass;
116         char *name;
117         intptr_t allocs;
118         uint64_t alloc_size;
119         TraceDesc traces;
120 };
121
122 static ClassDesc* class_hash [HASH_SIZE] = {0};
123 static int num_classes = 0;
124
125 static ClassDesc*
126 add_class (intptr_t klass, const char *name)
127 {
128         int slot = ((klass >> 2) & 0xffff) % HASH_SIZE;
129         ClassDesc *cd;
130         cd = class_hash [slot];
131         while (cd && cd->klass != klass)
132                 cd = cd->next;
133         /* we resolved an unknown class (unless we had the code unloaded) */
134         if (cd) {
135                 /*printf ("resolved unknown: %s\n", name);*/
136                 free (cd->name);
137                 cd->name = pstrdup (name);
138                 return cd;
139         }
140         cd = calloc (sizeof (ClassDesc), 1);
141         cd->klass = klass;
142         cd->name = pstrdup (name);
143         cd->next = class_hash [slot];
144         cd->allocs = 0;
145         cd->alloc_size = 0;
146         cd->traces.count = 0;
147         cd->traces.size = 0;
148         cd->traces.traces = NULL;
149         class_hash [slot] = cd;
150         num_classes++;
151         return cd;
152 }
153
154 static ClassDesc *
155 lookup_class (intptr_t klass)
156 {
157         int slot = ((klass >> 2) & 0xffff) % HASH_SIZE;
158         ClassDesc *cd = class_hash [slot];
159         while (cd && cd->klass != klass)
160                 cd = cd->next;
161         if (!cd)
162                 return add_class (klass, "unresolved class");
163         return cd;
164 }
165
166 typedef struct _MethodDesc MethodDesc;
167 struct _MethodDesc {
168         MethodDesc *next;
169         intptr_t method;
170         char *name;
171         intptr_t code;
172         int len;
173         int recurse_count;
174         uint64_t calls;
175         uint64_t total_time;
176         uint64_t callee_time;
177         uint64_t self_time;
178         TraceDesc traces;
179 };
180
181 static MethodDesc* method_hash [HASH_SIZE] = {0};
182 static int num_methods = 0;
183
184 static MethodDesc*
185 add_method (intptr_t method, const char *name, intptr_t code, int len)
186 {
187         int slot = ((method >> 2) & 0xffff) % HASH_SIZE;
188         MethodDesc *cd;
189         cd = method_hash [slot];
190         while (cd && cd->method != method)
191                 cd = cd->next;
192         /* we resolved an unknown method (unless we had the code unloaded) */
193         if (cd) {
194                 cd->code = code;
195                 cd->len = len;
196                 /*printf ("resolved unknown: %s\n", name);*/
197                 free (cd->name);
198                 cd->name = pstrdup (name);
199                 return cd;
200         }
201         cd = calloc (sizeof (MethodDesc), 1);
202         cd->method = method;
203         cd->name = pstrdup (name);
204         cd->code = code;
205         cd->len = len;
206         cd->calls = 0;
207         cd->total_time = 0;
208         cd->traces.count = 0;
209         cd->traces.size = 0;
210         cd->traces.traces = NULL;
211         cd->next = method_hash [slot];
212         method_hash [slot] = cd;
213         num_methods++;
214         return cd;
215 }
216
217 static MethodDesc *
218 lookup_method (intptr_t method)
219 {
220         int slot = ((method >> 2) & 0xffff) % HASH_SIZE;
221         MethodDesc *cd = method_hash [slot];
222         while (cd && cd->method != method)
223                 cd = cd->next;
224         if (!cd)
225                 return add_method (method, "unknown method", 0, 0);
226         return cd;
227 }
228
229 typedef struct _HeapClassDesc HeapClassDesc;
230 typedef struct {
231         HeapClassDesc *klass;
232         uint64_t count;
233 } HeapClassRevRef;
234
235 struct _HeapClassDesc {
236         ClassDesc *klass;
237         int64_t count;
238         int64_t total_size;
239         HeapClassRevRef *rev_hash;
240         int rev_hash_size;
241         int rev_count;
242 };
243
244 static int
245 add_rev_class_hashed (HeapClassRevRef *rev_hash, uintptr_t size, HeapClassDesc *hklass, uint64_t value)
246 {
247         uintptr_t i;
248         uintptr_t start_pos;
249         start_pos = (hklass->klass->klass >> 2) % size;
250         assert (start_pos < size);
251         i = start_pos;
252         do {
253                 if (rev_hash [i].klass == hklass) {
254                         rev_hash [i].count += value;
255                         return 0;
256                 } else if (!rev_hash [i].klass) {
257                         rev_hash [i].klass = hklass;
258                         rev_hash [i].count += value;
259                         start_pos = 0;
260                         for (i = 0; i < size; ++i)
261                                 if (rev_hash [i].klass && rev_hash [i].klass->klass == hklass->klass)
262                                         start_pos ++;
263                         assert (start_pos == 1);
264                         return 1;
265                 }
266                 /* wrap around */
267                 if (++i == size)
268                         i = 0;
269         } while (i != start_pos);
270         /* should not happen */
271         printf ("failed revref store\n");
272         return 0;
273 }
274
275 static void
276 add_heap_class_rev (HeapClassDesc *from, HeapClassDesc *to)
277 {
278         uintptr_t i;
279         if (to->rev_count * 2 >= to->rev_hash_size) {
280                 HeapClassRevRef *n;
281                 uintptr_t old_size = to->rev_hash_size;
282                 to->rev_hash_size *= 2;
283                 if (to->rev_hash_size == 0)
284                         to->rev_hash_size = 4;
285                 n = calloc (sizeof (HeapClassRevRef) * to->rev_hash_size, 1);
286                 for (i = 0; i < old_size; ++i) {
287                         if (to->rev_hash [i].klass)
288                                 add_rev_class_hashed (n, to->rev_hash_size, to->rev_hash [i].klass, to->rev_hash [i].count);
289                 }
290                 if (to->rev_hash)
291                         free (to->rev_hash);
292                 to->rev_hash = n;
293         }
294         to->rev_count += add_rev_class_hashed (to->rev_hash, to->rev_hash_size, from, 1);
295 }
296
297 typedef struct {
298         uintptr_t objaddr;
299         HeapClassDesc *hklass;
300         uintptr_t num_refs;
301         uintptr_t refs [0];
302 } HeapObjectDesc;
303
304 typedef struct _HeapShot HeapShot;
305 struct _HeapShot {
306         HeapShot *next;
307         uint64_t timestamp;
308         int class_count;
309         int hash_size;
310         HeapClassDesc **class_hash;
311         HeapClassDesc **sorted;
312         HeapObjectDesc **objects_hash;
313         uintptr_t objects_count;
314         uintptr_t objects_hash_size;
315 };
316
317 static HeapShot *heap_shots = NULL;
318 static int num_heap_shots = 0;
319
320 static HeapShot*
321 new_heap_shot (uint64_t timestamp)
322 {
323         HeapShot *hs = calloc (sizeof (HeapShot), 1);
324         hs->hash_size = 4;
325         hs->class_hash = calloc (sizeof (void*), hs->hash_size);
326         hs->timestamp = timestamp;
327         num_heap_shots++;
328         hs->next = heap_shots;
329         heap_shots = hs;
330         return hs;
331 }
332
333 static HeapClassDesc*
334 heap_class_lookup (HeapShot *hs, ClassDesc *klass)
335 {
336         int i;
337         unsigned int start_pos;
338         start_pos = ((uintptr_t)klass->klass >> 2) % hs->hash_size;
339         i = start_pos;
340         do {
341                 HeapClassDesc* cd = hs->class_hash [i];
342                 if (!cd)
343                         return NULL;
344                 if (cd->klass == klass)
345                         return cd;
346                 /* wrap around */
347                 if (++i == hs->hash_size)
348                         i = 0;
349         } while (i != start_pos);
350         return NULL;
351 }
352
353 static int
354 add_heap_hashed (HeapClassDesc **hash, HeapClassDesc **retv, uintptr_t hsize, ClassDesc *klass, uint64_t size, uint64_t count)
355 {
356         uintptr_t i;
357         uintptr_t start_pos;
358         start_pos = ((uintptr_t)klass->klass >> 2) % hsize;
359         i = start_pos;
360         do {
361                 if (hash [i] && hash [i]->klass == klass) {
362                         hash [i]->total_size += size;
363                         hash [i]->count += count;
364                         *retv = hash [i];
365                         return 0;
366                 } else if (!hash [i]) {
367                         if (*retv) {
368                                 hash [i] = *retv;
369                                 return 1;
370                         }
371                         hash [i] = calloc (sizeof (HeapClassDesc), 1);
372                         hash [i]->klass = klass;
373                         hash [i]->total_size += size;
374                         hash [i]->count += count;
375                         *retv = hash [i];
376                         return 1;
377                 }
378                 /* wrap around */
379                 if (++i == hsize)
380                         i = 0;
381         } while (i != start_pos);
382         /* should not happen */
383         printf ("failed heap class store\n");
384         return 0;
385 }
386
387 static HeapClassDesc*
388 add_heap_shot_class (HeapShot *hs, ClassDesc *klass, uint64_t size)
389 {
390         HeapClassDesc *res;
391         int i;
392         if (hs->class_count * 2 >= hs->hash_size) {
393                 HeapClassDesc **n;
394                 int old_size = hs->hash_size;
395                 hs->hash_size *= 2;
396                 if (hs->hash_size == 0)
397                         hs->hash_size = 4;
398                 n = calloc (sizeof (void*) * hs->hash_size, 1);
399                 for (i = 0; i < old_size; ++i) {
400                         res = hs->class_hash [i];
401                         if (hs->class_hash [i])
402                                 add_heap_hashed (n, &res, hs->hash_size, hs->class_hash [i]->klass, hs->class_hash [i]->total_size, hs->class_hash [i]->count);
403                 }
404                 if (hs->class_hash)
405                         free (hs->class_hash);
406                 hs->class_hash = n;
407         }
408         res = NULL;
409         hs->class_count += add_heap_hashed (hs->class_hash, &res, hs->hash_size, klass, size, 1);
410         //if (res->count == 1)
411         //      printf ("added heap class: %s\n", res->klass->name);
412         return res;
413 }
414
415 static HeapObjectDesc*
416 alloc_heap_obj (uintptr_t objaddr, HeapClassDesc *hklass, uintptr_t num_refs)
417 {
418         HeapObjectDesc* ho = calloc (sizeof (HeapObjectDesc) + num_refs * sizeof (uintptr_t), 1);
419         ho->objaddr = objaddr;
420         ho->hklass = hklass;
421         ho->num_refs = num_refs;
422         return ho;
423 }
424
425 static uintptr_t
426 heap_shot_find_obj_slot (HeapShot *hs, uintptr_t objaddr)
427 {
428         uintptr_t i;
429         uintptr_t start_pos;
430         HeapObjectDesc **hash = hs->objects_hash;
431         start_pos = ((uintptr_t)objaddr >> 3) % hs->objects_hash_size;
432         i = start_pos;
433         do {
434                 if (hash [i] && hash [i]->objaddr == objaddr) {
435                         return i;
436                 } else if (!hash [i]) {
437                         break; /* fail */
438                 }
439                 /* wrap around */
440                 if (++i == hs->objects_hash_size)
441                         i = 0;
442         } while (i != start_pos);
443         /* should not happen */
444         printf ("failed heap obj update\n");
445         return -1;
446 }
447
448 static HeapObjectDesc*
449 heap_shot_obj_add_refs (HeapShot *hs, uintptr_t objaddr, uintptr_t num, uintptr_t *ref_offset)
450 {
451         HeapObjectDesc **hash = hs->objects_hash;
452         uintptr_t i = heap_shot_find_obj_slot (hs, objaddr);
453         if (i >= 0) {
454                 HeapObjectDesc* ho = alloc_heap_obj (objaddr, hash [i]->hklass, hash [i]->num_refs + num);
455                 *ref_offset = hash [i]->num_refs;
456                 memcpy (ho->refs, hash [i]->refs, hash [i]->num_refs * sizeof (uintptr_t));
457                 free (hash [i]);
458                 hash [i] = ho;
459                 return ho;
460         }
461         /* should not happen */
462         printf ("failed heap obj update\n");
463         return NULL;
464         
465 }
466
467 static uintptr_t
468 add_heap_hashed_obj (HeapObjectDesc **hash, uintptr_t hsize, HeapObjectDesc *obj)
469 {
470         uintptr_t i;
471         uintptr_t start_pos;
472         start_pos = ((uintptr_t)obj->objaddr >> 3) % hsize;
473         i = start_pos;
474         do {
475                 if (hash [i] && hash [i]->objaddr == obj->objaddr) {
476                         printf ("duplicate object!\n");
477                         return 0;
478                 } else if (!hash [i]) {
479                         hash [i] = obj;
480                         return 1;
481                 }
482                 /* wrap around */
483                 if (++i == hsize)
484                         i = 0;
485         } while (i != start_pos);
486         /* should not happen */
487         printf ("failed heap obj store\n");
488         return 0;
489 }
490
491 static void
492 add_heap_shot_obj (HeapShot *hs, HeapObjectDesc *obj)
493 {
494         uintptr_t i;
495         if (hs->objects_count * 2 >= hs->objects_hash_size) {
496                 HeapObjectDesc **n;
497                 uintptr_t old_size = hs->objects_hash_size;
498                 hs->objects_hash_size *= 2;
499                 if (hs->objects_hash_size == 0)
500                         hs->objects_hash_size = 4;
501                 n = calloc (sizeof (void*) * hs->objects_hash_size, 1);
502                 for (i = 0; i < old_size; ++i) {
503                         if (hs->objects_hash [i])
504                                 add_heap_hashed_obj (n, hs->objects_hash_size, hs->objects_hash [i]);
505                 }
506                 if (hs->objects_hash)
507                         free (hs->objects_hash);
508                 hs->objects_hash = n;
509         }
510         hs->objects_count += add_heap_hashed_obj (hs->objects_hash, hs->objects_hash_size, obj);
511 }
512
513 static void
514 heap_shot_resolve_reverse_refs (HeapShot *hs)
515 {
516         uintptr_t i;
517         for (i = 0; i < hs->objects_hash_size; ++i) {
518                 uintptr_t r;
519                 HeapObjectDesc *ho = hs->objects_hash [i];
520                 if (!ho)
521                         continue;
522                 for (r = 0; r < ho->num_refs; ++r) {
523                         uintptr_t oi = heap_shot_find_obj_slot (hs, ho->refs [r]);
524                         add_heap_class_rev (ho->hklass, hs->objects_hash [oi]->hklass);
525                 }
526         }
527 }
528
529 static void
530 heap_shot_free_objects (HeapShot *hs)
531 {
532         uintptr_t i;
533         for (i = 0; i < hs->objects_hash_size; ++i) {
534                 HeapObjectDesc *ho = hs->objects_hash [i];
535                 if (ho)
536                         free (ho);
537         }
538         if (hs->objects_hash)
539                 free (hs->objects_hash);
540         hs->objects_hash = NULL;
541         hs->objects_hash_size = 0;
542         hs->objects_count = 0;
543 }
544
545 struct _BackTrace {
546         BackTrace *next;
547         unsigned int hash;
548         int count;
549         int id;
550         MethodDesc *methods [1];
551 };
552
553 static BackTrace *backtrace_hash [HASH_SIZE];
554 static BackTrace **backtraces = NULL;
555 static int num_backtraces = 0;
556 static int next_backtrace = 0;
557
558 static int
559 hash_backtrace (int count, MethodDesc **methods)
560 {
561         int hash = count;
562         int i;
563         for (i = 0; i < count; ++i) {
564                 hash = (hash << 5) - hash + methods [i]->method;
565         }
566         return hash;
567 }
568
569 static int
570 compare_backtrace (BackTrace *bt, int count, MethodDesc **methods)
571 {
572         int i;
573         if (bt->count != count)
574                 return 0;
575         for (i = 0; i < count; ++i)
576                 if (methods [i] != bt->methods [i])
577                         return 0;
578         return 1;
579 }
580
581 static BackTrace*
582 add_backtrace (int count, MethodDesc **methods)
583 {
584         int hash = hash_backtrace (count, methods);
585         int slot = (hash & 0xffff) % HASH_SIZE;
586         BackTrace *bt = backtrace_hash [slot];
587         while (bt) {
588                 if (bt->hash == hash && compare_backtrace (bt, count, methods))
589                         return bt;
590                 bt = bt->next;
591         }
592         bt = malloc (sizeof (BackTrace) + ((count - 1) * sizeof (void*)));
593         bt->next = backtrace_hash [slot];
594         backtrace_hash [slot] = bt;
595         if (next_backtrace == num_backtraces) {
596                 num_backtraces *= 2;
597                 if (!num_backtraces)
598                         num_backtraces = 16;
599                 backtraces = realloc (backtraces, sizeof (void*) * num_backtraces);
600         }
601         bt->id = next_backtrace++;
602         backtraces [bt->id] = bt;
603         bt->count = count;
604         bt->hash = hash;
605         for (slot = 0; slot < count; ++slot)
606                 bt->methods [slot] = methods [slot];
607
608         return bt;
609 }
610
611 typedef struct _MonitorDesc MonitorDesc;
612 typedef struct _ThreadContext ThreadContext;
613
614 typedef struct {
615         FILE *file;
616 #if defined (HAVE_SYS_ZLIB)
617         gzFile *gzfile;
618 #endif
619         unsigned char *buf;
620         int size;
621         int data_version;
622         int version_major;
623         int version_minor;
624         int timer_overhead;
625         uint64_t startup_time;
626         ThreadContext *threads;
627         ThreadContext *current;
628 } ProfContext;
629
630 struct _ThreadContext {
631         ThreadContext *next;
632         intptr_t thread_id;
633         char *name;
634         /* emulated stack */
635         MethodDesc **stack;
636         uint64_t *time_stack;
637         uint64_t *callee_time_stack;
638         uint64_t last_time;
639         uint64_t contention_start;
640         MonitorDesc *monitor;
641         int stack_size;
642         int stack_id;
643         HeapShot *current_heap_shot;
644 };
645
646 static void
647 ensure_buffer (ProfContext *ctx, int size)
648 {
649         if (ctx->size < size) {
650                 ctx->buf = realloc (ctx->buf, size);
651                 ctx->size = size;
652         }
653 }
654
655 static int
656 load_data (ProfContext *ctx, int size)
657 {
658         ensure_buffer (ctx, size);
659 #if defined (HAVE_SYS_ZLIB)
660         if (ctx->gzfile)
661                 return gzread (ctx->gzfile, ctx->buf, size) == size;
662         else
663 #endif
664                 return fread (ctx->buf, size, 1, ctx->file);
665 }
666
667 static ThreadContext*
668 get_thread (ProfContext *ctx, intptr_t thread_id)
669 {
670         ThreadContext *thread;
671         if (ctx->current && ctx->current->thread_id == thread_id)
672                 return ctx->current;
673         thread = ctx->threads;
674         while (thread) {
675                 if (thread->thread_id == thread_id) {
676                         return thread;
677                 }
678                 thread = thread->next;
679         }
680         thread = calloc (sizeof (ThreadContext), 1);
681         thread->next = ctx->threads;
682         ctx->threads = thread;
683         thread->thread_id = thread_id;
684         thread->last_time = 0;
685         thread->stack_id = 0;
686         thread->stack_size = 32;
687         thread->stack = malloc (thread->stack_size * sizeof (void*));
688         thread->time_stack = malloc (thread->stack_size * sizeof (uint64_t));
689         thread->callee_time_stack = malloc (thread->stack_size * sizeof (uint64_t));
690         return thread;
691 }
692
693 static ThreadContext*
694 load_thread (ProfContext *ctx, intptr_t thread_id)
695 {
696         ThreadContext *thread = get_thread (ctx, thread_id);
697         ctx->current = thread;
698         return thread;
699 }
700
701 static void
702 ensure_thread_stack (ThreadContext *thread)
703 {
704         if (thread->stack_id == thread->stack_size) {
705                 thread->stack_size *= 2;
706                 thread->stack = realloc (thread->stack, thread->stack_size * sizeof (void*));
707                 thread->time_stack = realloc (thread->time_stack, thread->stack_size * sizeof (uint64_t));
708                 thread->callee_time_stack = realloc (thread->callee_time_stack, thread->stack_size * sizeof (uint64_t));
709         }
710 }
711
712 static int
713 add_trace_hashed (CallContext *traces, int size, BackTrace *bt, uint64_t value)
714 {
715         int i;
716         unsigned int start_pos;
717         start_pos = bt->hash % size;
718         i = start_pos;
719         do {
720                 if (traces [i].bt == bt) {
721                         traces [i].count += value;
722                         return 0;
723                 } else if (!traces [i].bt) {
724                         traces [i].bt = bt;
725                         traces [i].count += value;
726                         return 1;
727                 }
728                 /* wrap around */
729                 if (++i == size)
730                         i = 0;
731         } while (i != start_pos);
732         /* should not happen */
733         printf ("failed trace store\n");
734         return 0;
735 }
736
737 static void
738 add_trace_bt (BackTrace *bt, TraceDesc *trace, uint64_t value)
739 {
740         int i;
741         if (!collect_traces)
742                 return;
743         if (trace->count * 2 >= trace->size) {
744                 CallContext *n;
745                 int old_size = trace->size;
746                 trace->size *= 2;
747                 if (trace->size == 0)
748                         trace->size = 4;
749                 n = calloc (sizeof (CallContext) * trace->size, 1);
750                 for (i = 0; i < old_size; ++i) {
751                         if (trace->traces [i].bt)
752                                 add_trace_hashed (n, trace->size, trace->traces [i].bt, trace->traces [i].count);
753                 }
754                 if (trace->traces)
755                         free (trace->traces);
756                 trace->traces = n;
757         }
758         trace->count += add_trace_hashed (trace->traces, trace->size, bt, value);
759 }
760
761 static BackTrace*
762 add_trace_thread (ThreadContext *thread, TraceDesc *trace, uint64_t value)
763 {
764         BackTrace *bt;
765         int count = thread->stack_id;
766         if (!collect_traces)
767                 return NULL;
768         if (count > trace_max)
769                 count = trace_max;
770         bt = add_backtrace (count, thread->stack + thread->stack_id - count);
771         add_trace_bt (bt, trace, value);
772         return bt;
773 }
774
775 static BackTrace*
776 add_trace_methods (MethodDesc **methods, int count, TraceDesc *trace, uint64_t value)
777 {
778         BackTrace *bt;
779         if (!collect_traces)
780                 return NULL;
781         if (count > trace_max)
782                 count = trace_max;
783         bt = add_backtrace (count, methods);
784         add_trace_bt (bt, trace, value);
785         return bt;
786 }
787
788 static int
789 compare_callc (const void *a, const void *b)
790 {
791         const CallContext *A = a;
792         const CallContext *B = b;
793         if (B->count == A->count)
794                 return 0;
795         if (B->count < A->count)
796                 return -1;
797         return 1;
798 }
799
800 static void
801 sort_context_array (TraceDesc* traces)
802 {
803         int i, j;
804         for (i = 0, j = 0; i < traces->size; ++i) {
805                 if (traces->traces [i].bt) {
806                         traces->traces [j].bt = traces->traces [i].bt;
807                         traces->traces [j].count = traces->traces [i].count;
808                         j++;
809                 }
810         }
811         qsort (traces->traces, traces->count, sizeof (CallContext), compare_callc);
812 }
813
814 static void
815 push_method (ThreadContext *thread, MethodDesc *method, uint64_t timestamp)
816 {
817         ensure_thread_stack (thread);
818         thread->time_stack [thread->stack_id] = timestamp;
819         thread->callee_time_stack [thread->stack_id] = 0;
820         thread->stack [thread->stack_id++] = method;
821         method->recurse_count++;
822 }
823
824 static void
825 pop_method (ThreadContext *thread, MethodDesc *method, uint64_t timestamp)
826 {
827         method->recurse_count--;
828         if (thread->stack_id > 0 && thread->stack [thread->stack_id - 1] == method) {
829                 uint64_t tdiff;
830                 thread->stack_id--;
831                 method->calls++;
832                 if (timestamp < thread->time_stack [thread->stack_id])
833                         fprintf (outfile, "time went backwards for %s\n", method->name);
834                 tdiff = timestamp - thread->time_stack [thread->stack_id];
835                 if (thread->callee_time_stack [thread->stack_id] > tdiff)
836                         fprintf (outfile, "callee time bigger for %s\n", method->name);
837                 method->self_time += tdiff - thread->callee_time_stack [thread->stack_id];
838                 method->callee_time += thread->callee_time_stack [thread->stack_id];
839                 if (thread->stack_id)
840                         thread->callee_time_stack [thread->stack_id - 1] += tdiff;
841                 //fprintf (outfile, "method %s took %d\n", method->name, (int)(tdiff/1000));
842         } else {
843                 fprintf (outfile, "unmatched leave at stack pos: %d for method %s\n", thread->stack_id, method->name);
844         }
845 }
846
847 typedef struct {
848         uint64_t start_time; /* move this per-thread? */
849         uint64_t total_time;
850         uint64_t max_time;
851         int count;
852 } GCDesc;
853 static GCDesc gc_info [3];
854 static uint64_t max_heap_size;
855 static uint64_t gc_object_moves;
856 static int gc_resizes;
857 typedef struct {
858         uint64_t created;
859         uint64_t destroyed;
860         uint64_t max_live;
861         TraceDesc traces;
862 } HandleInfo;
863 static HandleInfo handle_info [4];
864
865 static const char*
866 gc_event_name (int ev)
867 {
868         switch (ev) {
869         case MONO_GC_EVENT_START: return "start";
870         case MONO_GC_EVENT_MARK_START: return "mark start";
871         case MONO_GC_EVENT_MARK_END: return "mark end";
872         case MONO_GC_EVENT_RECLAIM_START: return "reclaim start";
873         case MONO_GC_EVENT_RECLAIM_END: return "reclaim end";
874         case MONO_GC_EVENT_END: return "end";
875         case MONO_GC_EVENT_PRE_STOP_WORLD: return "pre stop";
876         case MONO_GC_EVENT_POST_STOP_WORLD: return "post stop";
877         case MONO_GC_EVENT_PRE_START_WORLD: return "pre start";
878         case MONO_GC_EVENT_POST_START_WORLD: return "post start";
879         default:
880                 return "unknown";
881         }
882 }
883
884 static uint64_t clause_summary [MONO_EXCEPTION_CLAUSE_FAULT + 1];
885 static uint64_t throw_count = 0;
886 static TraceDesc exc_traces;
887
888 static const char*
889 clause_name (int type)
890 {
891         switch (type) {
892         case MONO_EXCEPTION_CLAUSE_NONE: return "catch";
893         case MONO_EXCEPTION_CLAUSE_FILTER: return "filter";
894         case MONO_EXCEPTION_CLAUSE_FINALLY: return "finally";
895         case MONO_EXCEPTION_CLAUSE_FAULT: return "fault";
896         default: return "invalid";
897         }
898 }
899
900 static uint64_t monitor_contention;
901 static uint64_t monitor_failed;
902 static uint64_t monitor_acquired;
903
904 struct _MonitorDesc {
905         MonitorDesc *next;
906         uintptr_t objid;
907         uintptr_t contentions;
908         uint64_t wait_time;
909         uint64_t max_wait_time;
910         TraceDesc traces;
911 };
912
913 static MonitorDesc* monitor_hash [SMALL_HASH_SIZE] = {0};
914 static int num_monitors = 0;
915
916 static MonitorDesc*
917 lookup_monitor (uintptr_t objid)
918 {
919         int slot = ((objid >> 3) & 0xffff) % SMALL_HASH_SIZE;
920         MonitorDesc *cd = monitor_hash [slot];
921         while (cd && cd->objid != objid)
922                 cd = cd->next;
923         if (!cd) {
924                 cd = calloc (sizeof (MonitorDesc), 1);
925                 cd->objid = objid;
926                 cd->next = monitor_hash [slot];
927                 monitor_hash [slot] = cd;
928                 num_monitors++;
929         }
930         return cd;
931 }
932
933 static const char*
934 monitor_ev_name (int ev)
935 {
936         switch (ev) {
937         case MONO_PROFILER_MONITOR_CONTENTION: return "contended";
938         case MONO_PROFILER_MONITOR_DONE: return "acquired";
939         case MONO_PROFILER_MONITOR_FAIL: return "not taken";
940         default: return "invalid";
941         }
942 }
943
944 static const char*
945 get_handle_name (int htype)
946 {
947         switch (htype) {
948         case 0: return "weak";
949         case 1: return "weaktrack";
950         case 2: return "normal";
951         case 3: return "pinned";
952         default: return "unknown";
953         }
954 }
955
956 static MethodDesc**
957 decode_bt (MethodDesc** sframes, int *size, unsigned char *p, unsigned char **endp, intptr_t ptr_base)
958 {
959         MethodDesc **frames;
960         int i;
961         int flags = decode_uleb128 (p, &p);
962         int count = decode_uleb128 (p, &p);
963         if (flags != 0)
964                 return NULL;
965         if (count > *size)
966                 frames = malloc (count * sizeof (void*));
967         else
968                 frames = sframes;
969         for (i = 0; i < count; ++i) {
970                 intptr_t ptrdiff = decode_sleb128 (p, &p);
971                 frames [i] = lookup_method (ptr_base + ptrdiff);
972         }
973         *size = count;
974         *endp = p;
975         return frames;
976 }
977
978 static void
979 tracked_creation (uintptr_t obj, ClassDesc *cd, uint64_t size, BackTrace *bt, uint64_t timestamp)
980 {
981         int i;
982         for (i = 0; i < num_tracked_objects; ++i) {
983                 if (tracked_objects [i] != obj)
984                         continue;
985                 fprintf (outfile, "Object %p created (%s, %llu bytes) at %.3f secs.\n", (void*)obj, cd->name, size, (timestamp - startup_time)/1000000000.0);
986                 if (bt && bt->count) {
987                         int k;
988                         for (k = 0; k < bt->count; ++k)
989                                 fprintf (outfile, "\t%s\n", bt->methods [k]->name);
990                 }
991         }
992 }
993
994 static void
995 track_handle (uintptr_t obj, int htype, uint32_t handle)
996 {
997         int i;
998         for (i = 0; i < num_tracked_objects; ++i) {
999                 if (tracked_objects [i] == obj)
1000                         fprintf (outfile, "Object %p referenced from handle %u\n", (void*)obj, handle);
1001         }
1002 }
1003
1004 static void
1005 track_move (uintptr_t src, uintptr_t dst)
1006 {
1007         int i;
1008         for (i = 0; i < num_tracked_objects; ++i) {
1009                 if (tracked_objects [i] == src)
1010                         fprintf (outfile, "Object %p moved to %p\n", (void*)src, (void*)dst);
1011                 else if (tracked_objects [i] == dst)
1012                         fprintf (outfile, "Object %p moved from %p\n", (void*)dst, (void*)src);
1013         }
1014 }
1015
1016 static void
1017 track_obj_reference (uintptr_t obj, uintptr_t parent, ClassDesc *cd)
1018 {
1019         int i;
1020         for (i = 0; i < num_tracked_objects; ++i) {
1021                 if (tracked_objects [i] == obj) 
1022                         fprintf (outfile, "Object %p referenced from %p (%s).\n", (void*)obj, (void*)parent, cd->name);
1023         }
1024 }
1025
1026 static void
1027 found_object (uintptr_t obj)
1028 {
1029         num_tracked_objects ++;
1030         tracked_objects = realloc (tracked_objects, num_tracked_objects * sizeof (tracked_objects [0]));
1031         tracked_objects [num_tracked_objects - 1] = obj;
1032 }
1033
1034 #define OBJ_ADDR(diff) ((obj_base + diff) << 3)
1035 #define LOG_TIME(base,diff) /*fprintf("outfile, time %llu + %llu near offset %d\n", base, diff, p - ctx->buf)*/
1036
1037 static int
1038 decode_buffer (ProfContext *ctx)
1039 {
1040         unsigned char *p;
1041         unsigned char *end;
1042         intptr_t thread_id;
1043         intptr_t ptr_base;
1044         intptr_t obj_base;
1045         intptr_t method_base;
1046         uint64_t time_base;
1047         uint64_t file_offset;
1048         int len, i;
1049         ThreadContext *thread;
1050
1051 #ifdef HAVE_SYS_ZLIB
1052         if (ctx->gzfile)
1053                 file_offset = gztell (ctx->gzfile);
1054         else
1055 #endif
1056                 file_offset = ftell (ctx->file);
1057         if (!load_data (ctx, 48))
1058                 return 0;
1059         p = ctx->buf;
1060         if (read_int32 (p) != BUF_ID)
1061                 return 0;
1062         len = read_int32 (p + 4);
1063         time_base = read_int64 (p + 8);
1064         ptr_base = read_int64 (p + 16);
1065         obj_base = read_int64 (p + 24);
1066         thread_id = read_int64 (p + 32);
1067         method_base = read_int64 (p + 40);
1068         if (debug)
1069                 fprintf (outfile, "buf: thread:%x, len: %d, time: %llu, file offset: %llu\n", thread_id, len, time_base, file_offset);
1070         thread = load_thread (ctx, thread_id);
1071         if (!load_data (ctx, len))
1072                 return 0;
1073         if (!startup_time) {
1074                 startup_time = time_base;
1075                 if (time_from) {
1076                         time_from += startup_time;
1077                         time_to += startup_time;
1078                 }
1079                 if (!thread->name)
1080                         thread->name = pstrdup ("Main");
1081         }
1082         for (i = 0; i < thread->stack_id; ++i)
1083                 thread->stack [i]->recurse_count++;
1084         p = ctx->buf;
1085         end = p + len;
1086         while (p < end) {
1087                 switch (*p & 0xf) {
1088                 case TYPE_GC: {
1089                         int subtype = *p & 0xf0;
1090                         uint64_t tdiff = decode_uleb128 (p + 1, &p);
1091                         LOG_TIME (time_base, tdiff);
1092                         time_base += tdiff;
1093                         if (subtype == TYPE_GC_RESIZE) {
1094                                 uint64_t new_size = decode_uleb128 (p, &p);
1095                                 if (debug)
1096                                         fprintf (outfile, "gc heap resized to %llu\n", new_size);
1097                                 gc_resizes++;
1098                                 if (new_size > max_heap_size)
1099                                         max_heap_size = new_size;
1100                         } else if (subtype == TYPE_GC_EVENT) {
1101                                 uint64_t ev = decode_uleb128 (p, &p);
1102                                 int gen = decode_uleb128 (p, &p);
1103                                 if (debug)
1104                                         fprintf (outfile, "gc event for gen%d: %s at %llu\n", gen - 1, gc_event_name (ev), time_base);
1105                                 if (gen > 2) {
1106                                         fprintf (outfile, "incorrect gc gen: %d\n", gen);
1107                                         break;
1108                                 }
1109                                 if (ev == MONO_GC_EVENT_START) {
1110                                         gc_info [gen].start_time = time_base;
1111                                         gc_info [gen].count++;
1112                                 } else if (ev == MONO_GC_EVENT_END) {
1113                                         tdiff = time_base - gc_info [gen].start_time;
1114                                         gc_info [gen].total_time += tdiff;
1115                                         if (tdiff > gc_info [gen].max_time)
1116                                                 gc_info [gen].max_time = tdiff;
1117                                 }
1118                         } else if (subtype == TYPE_GC_MOVE) {
1119                                 int j, num = decode_uleb128 (p, &p);
1120                                 gc_object_moves += num / 2;
1121                                 for (j = 0; j < num; j += 2) {
1122                                         intptr_t obj1diff = decode_sleb128 (p, &p);
1123                                         intptr_t obj2diff = decode_sleb128 (p, &p);
1124                                         if (num_tracked_objects)
1125                                                 track_move (OBJ_ADDR (obj1diff), OBJ_ADDR (obj2diff));
1126                                         if (debug) {
1127                                                 fprintf (outfile, "moved obj %p to %p\n", (void*)OBJ_ADDR (obj1diff), (void*)OBJ_ADDR (obj2diff));
1128                                         }
1129                                 }
1130                         } else if (subtype == TYPE_GC_HANDLE_CREATED) {
1131                                 int htype = decode_uleb128 (p, &p);
1132                                 uint32_t handle = decode_uleb128 (p, &p);
1133                                 intptr_t objdiff = decode_sleb128 (p, &p);
1134                                 if (htype > 3)
1135                                         return 0;
1136                                 handle_info [htype].created++;
1137                                 add_trace_thread (thread, &handle_info [htype].traces, 1);
1138                                 /* FIXME: we don't take into account timing here */
1139                                 if (handle_info [htype].created > handle_info [htype].max_live)
1140                                         handle_info [htype].max_live = handle_info [htype].created;
1141                                 if (num_tracked_objects)
1142                                         track_handle (OBJ_ADDR (objdiff), htype, handle);
1143                                 if (debug)
1144                                         fprintf (outfile, "handle (%s) %u created for object %p\n", get_handle_name (htype), handle, (void*)OBJ_ADDR (objdiff));
1145                         } else if (subtype == TYPE_GC_HANDLE_DESTROYED) {
1146                                 int htype = decode_uleb128 (p, &p);
1147                                 uint32_t handle = decode_uleb128 (p, &p);
1148                                 if (htype > 3)
1149                                         return 0;
1150                                 handle_info [htype].created--;
1151                                 if (debug)
1152                                         fprintf (outfile, "handle (%s) %u destroyed\n", get_handle_name (htype), handle);
1153                         }
1154                         break;
1155                 }
1156                 case TYPE_METADATA: {
1157                         int error = *p & TYPE_LOAD_ERR;
1158                         uint64_t tdiff = decode_uleb128 (p + 1, &p);
1159                         int mtype = *p++;
1160                         intptr_t ptrdiff = decode_sleb128 (p, &p);
1161                         LOG_TIME (time_base, tdiff);
1162                         time_base += tdiff;
1163                         if (mtype == TYPE_CLASS) {
1164                                 intptr_t imptrdiff = decode_sleb128 (p, &p);
1165                                 uint64_t flags = decode_uleb128 (p, &p);
1166                                 if (flags) {
1167                                         fprintf (outfile, "non-zero flags in class\n");
1168                                         return 0;
1169                                 }
1170                                 if (debug)
1171                                         fprintf (outfile, "loaded class %p (%s in %p) at %llu\n", (void*)(ptr_base + ptrdiff), p, (void*)(ptr_base + imptrdiff), time_base);
1172                                 if (!error)
1173                                         add_class (ptr_base + ptrdiff, (char*)p);
1174                                 while (*p) p++;
1175                                 p++;
1176                         } else if (mtype == TYPE_IMAGE) {
1177                                 uint64_t flags = decode_uleb128 (p, &p);
1178                                 if (flags) {
1179                                         fprintf (outfile, "non-zero flags in image\n");
1180                                         return 0;
1181                                 }
1182                                 if (debug)
1183                                         fprintf (outfile, "loaded image %p (%s) at %llu\n", (void*)(ptr_base + ptrdiff), p, time_base);
1184                                 if (!error)
1185                                         add_image (ptr_base + ptrdiff, (char*)p);
1186                                 while (*p) p++;
1187                                 p++;
1188                         } else if (mtype == TYPE_THREAD) {
1189                                 ThreadContext *nt;
1190                                 uint64_t flags = decode_uleb128 (p, &p);
1191                                 if (flags) {
1192                                         fprintf (outfile, "non-zero flags in thread\n");
1193                                         return 0;
1194                                 }
1195                                 nt = get_thread (ctx, ptr_base * ptrdiff);
1196                                 nt->name = pstrdup ((char*)p);
1197                                 if (debug)
1198                                         fprintf (outfile, "thread %p named: %s\n", (void*)(ptr_base + ptrdiff), p);
1199                                 while (*p) p++;
1200                                 p++;
1201                         }
1202                         break;
1203                 }
1204                 case TYPE_ALLOC: {
1205                         int has_bt = *p & TYPE_ALLOC_BT;
1206                         uint64_t tdiff = decode_uleb128 (p + 1, &p);
1207                         intptr_t ptrdiff = decode_sleb128 (p, &p);
1208                         intptr_t objdiff = decode_sleb128 (p, &p);
1209                         uint64_t len;
1210                         int num_bt = 0;
1211                         MethodDesc* sframes [8];
1212                         MethodDesc** frames = sframes;
1213                         ClassDesc *cd = lookup_class (ptr_base + ptrdiff);
1214                         len = decode_uleb128 (p, &p);
1215                         LOG_TIME (time_base, tdiff);
1216                         time_base += tdiff;
1217                         if (debug)
1218                                 fprintf (outfile, "alloced object %p, size %llu (%s) at %llu\n", (void*)OBJ_ADDR (objdiff), len, lookup_class (ptr_base + ptrdiff)->name, time_base);
1219                         if (has_bt) {
1220                                 num_bt = 8;
1221                                 frames = decode_bt (sframes, &num_bt, p, &p, ptr_base);
1222                                 if (!frames) {
1223                                         fprintf (outfile, "Cannot load backtrace\n");
1224                                         return 0;
1225                                 }
1226                         }
1227                         if ((thread_filter && thread_filter == thread->thread_id) || (time_base >= time_from && time_base < time_to)) {
1228                                 BackTrace *bt;
1229                                 cd->allocs++;
1230                                 cd->alloc_size += len;
1231                                 if (has_bt)
1232                                         bt = add_trace_methods (frames, num_bt, &cd->traces, len);
1233                                 else
1234                                         bt = add_trace_thread (thread, &cd->traces, len);
1235                                 if (find_size && len >= find_size) {
1236                                         if (!find_name || strstr (cd->name, find_name))
1237                                                 found_object (OBJ_ADDR (objdiff));
1238                                 } else if (!find_size && find_name && strstr (cd->name, find_name)) {
1239                                         found_object (OBJ_ADDR (objdiff));
1240                                 }
1241                                 if (num_tracked_objects)
1242                                         tracked_creation (OBJ_ADDR (objdiff), cd, len, bt, time_base);
1243                         }
1244                         if (frames != sframes)
1245                                 free (frames);
1246                         break;
1247                 }
1248                 case TYPE_METHOD: {
1249                         int subtype = *p & 0xf0;
1250                         uint64_t tdiff = decode_uleb128 (p + 1, &p);
1251                         int64_t ptrdiff = decode_sleb128 (p, &p);
1252                         LOG_TIME (time_base, tdiff);
1253                         time_base += tdiff;
1254                         method_base += ptrdiff;
1255                         if (subtype == TYPE_JIT) {
1256                                 intptr_t codediff = decode_sleb128 (p, &p);
1257                                 int codelen = decode_uleb128 (p, &p);
1258                                 if (debug)
1259                                         fprintf (outfile, "jitted method %p (%s), size: %d\n", (void*)(method_base), p, codelen);
1260                                 add_method (method_base, (char*)p, ptr_base + codediff, codelen);
1261                                 while (*p) p++;
1262                                 p++;
1263                         } else {
1264                                 MethodDesc *method;
1265                                 if ((thread_filter && thread_filter != thread->thread_id))
1266                                         break;
1267                                 method = lookup_method (method_base);
1268                                 if (subtype == TYPE_ENTER) {
1269                                         add_trace_thread (thread, &method->traces, 1);
1270                                         push_method (thread, method, time_base);
1271                                 } else {
1272                                         pop_method (thread, method, time_base);
1273                                 }
1274                                 if (debug)
1275                                         fprintf (outfile, "%s method %s\n", subtype == TYPE_ENTER? "enter": subtype == TYPE_EXC_LEAVE? "exleave": "leave", method->name);
1276                         }
1277                         break;
1278                 }
1279                 case TYPE_HEAP: {
1280                         int subtype = *p & 0xf0;
1281                         if (subtype == TYPE_HEAP_OBJECT) {
1282                                 HeapObjectDesc *ho;
1283                                 int i;
1284                                 intptr_t objdiff = decode_sleb128 (p + 1, &p);
1285                                 intptr_t ptrdiff = decode_sleb128 (p, &p);
1286                                 uint64_t size = decode_uleb128 (p, &p);
1287                                 uintptr_t num = decode_uleb128 (p, &p);
1288                                 uintptr_t ref_offset;
1289                                 ClassDesc *cd = lookup_class (ptr_base + ptrdiff);
1290                                 if (size) {
1291                                         HeapClassDesc *hcd = add_heap_shot_class (thread->current_heap_shot, cd, size);
1292                                         if (collect_traces) {
1293                                                 ho = alloc_heap_obj (OBJ_ADDR (objdiff), hcd, num);
1294                                                 add_heap_shot_obj (thread->current_heap_shot, ho);
1295                                                 ref_offset = 0;
1296                                         }
1297                                 } else {
1298                                         if (collect_traces)
1299                                                 ho = heap_shot_obj_add_refs (thread->current_heap_shot, OBJ_ADDR (objdiff), num, &ref_offset);
1300                                 }
1301                                 for (i = 0; i < num; ++i) {
1302                                         /* FIXME: use object distance to measure how good
1303                                          * the GC is at keeping related objects close
1304                                          */
1305                                         intptr_t obj1diff = decode_sleb128 (p, &p);
1306                                         if (collect_traces)
1307                                                 ho->refs [ref_offset + i] = OBJ_ADDR (obj1diff);
1308                                         if (num_tracked_objects)
1309                                                 track_obj_reference (OBJ_ADDR (obj1diff), OBJ_ADDR (objdiff), cd);
1310                                 }
1311                                 if (debug && size)
1312                                         fprintf (outfile, "traced object %p, size %llu (%s), refs: %d\n", (void*)OBJ_ADDR (objdiff), size, cd->name, num);
1313                         } else if (subtype == TYPE_HEAP_END) {
1314                                 uint64_t tdiff = decode_uleb128 (p + 1, &p);
1315                                 LOG_TIME (time_base, tdiff);
1316                                 time_base += tdiff;
1317                                 if (debug)
1318                                         fprintf (outfile, "heap shot end\n");
1319                                 if (collect_traces) {
1320                                         heap_shot_resolve_reverse_refs (thread->current_heap_shot);
1321                                         heap_shot_free_objects (thread->current_heap_shot);
1322                                 }
1323                                 thread->current_heap_shot = NULL;
1324                         } else if (subtype == TYPE_HEAP_START) {
1325                                 uint64_t tdiff = decode_uleb128 (p + 1, &p);
1326                                 LOG_TIME (time_base, tdiff);
1327                                 time_base += tdiff;
1328                                 if (debug)
1329                                         fprintf (outfile, "heap shot start\n");
1330                                 thread->current_heap_shot = new_heap_shot (time_base);
1331                         }
1332                         break;
1333                 }
1334                 case TYPE_MONITOR: {
1335                         int event = (*p >> 4) & 0x3;
1336                         int has_bt = *p & TYPE_MONITOR_BT;
1337                         uint64_t tdiff = decode_uleb128 (p + 1, &p);
1338                         intptr_t objdiff = decode_sleb128 (p, &p);
1339                         MethodDesc* sframes [8];
1340                         MethodDesc** frames = sframes;
1341                         int record;
1342                         int num_bt = 0;
1343                         LOG_TIME (time_base, tdiff);
1344                         time_base += tdiff;
1345                         record = (!thread_filter || thread_filter == thread->thread_id);
1346                         if (event == MONO_PROFILER_MONITOR_CONTENTION) {
1347                                 MonitorDesc *mdesc = lookup_monitor (OBJ_ADDR (objdiff));
1348                                 if (record) {
1349                                         monitor_contention++;
1350                                         mdesc->contentions++;
1351                                         thread->monitor = mdesc;
1352                                         thread->contention_start = time_base;
1353                                 }
1354                                 if (has_bt) {
1355                                         num_bt = 8;
1356                                         frames = decode_bt (sframes, &num_bt, p, &p, ptr_base);
1357                                         if (!frames) {
1358                                                 fprintf (outfile, "Cannot load backtrace\n");
1359                                                 return 0;
1360                                         }
1361                                         if (record)
1362                                                 add_trace_methods (frames, num_bt, &mdesc->traces, 1);
1363                                 } else {
1364                                         if (record)
1365                                                 add_trace_thread (thread, &mdesc->traces, 1);
1366                                 }
1367                         } else if (event == MONO_PROFILER_MONITOR_FAIL) {
1368                                 if (record) {
1369                                         monitor_failed++;
1370                                         if (thread->monitor && thread->contention_start) {
1371                                                 uint64_t wait_time = time_base - thread->contention_start;
1372                                                 if (wait_time > thread->monitor->max_wait_time)
1373                                                         thread->monitor->max_wait_time = wait_time;
1374                                                 thread->monitor->wait_time += wait_time;
1375                                                 thread->monitor = NULL;
1376                                                 thread->contention_start = 0;
1377                                         }
1378                                 }
1379                         } else if (event == MONO_PROFILER_MONITOR_DONE) {
1380                                 if (record) {
1381                                         monitor_acquired++;
1382                                         if (thread->monitor && thread->contention_start) {
1383                                                 uint64_t wait_time = time_base - thread->contention_start;
1384                                                 if (wait_time > thread->monitor->max_wait_time)
1385                                                         thread->monitor->max_wait_time = wait_time;
1386                                                 thread->monitor->wait_time += wait_time;
1387                                                 thread->monitor = NULL;
1388                                                 thread->contention_start = 0;
1389                                         }
1390                                 }
1391                         }
1392                         if (debug)
1393                                 fprintf (outfile, "monitor %s for object %p\n", monitor_ev_name (event), (void*)OBJ_ADDR (objdiff));
1394                         if (frames != sframes)
1395                                 free (frames);
1396                         break;
1397                 }
1398                 case TYPE_EXCEPTION: {
1399                         int subtype = *p & 0x70;
1400                         int has_bt = *p & TYPE_EXCEPTION_BT;
1401                         uint64_t tdiff = decode_uleb128 (p + 1, &p);
1402                         MethodDesc* sframes [8];
1403                         MethodDesc** frames = sframes;
1404                         int record;
1405                         LOG_TIME (time_base, tdiff);
1406                         time_base += tdiff;
1407                         record = (!thread_filter || thread_filter == thread->thread_id);
1408                         if (subtype == TYPE_CLAUSE) {
1409                                 int clause_type = decode_uleb128 (p, &p);
1410                                 int clause_num = decode_uleb128 (p, &p);
1411                                 int64_t ptrdiff = decode_sleb128 (p, &p);
1412                                 method_base += ptrdiff;
1413                                 if (record)
1414                                         clause_summary [clause_type]++;
1415                                 if (debug)
1416                                         fprintf (outfile, "clause %s (%d) in method %s\n", clause_name (clause_type), clause_num, lookup_method (method_base)->name);
1417                         } else {
1418                                 intptr_t objdiff = decode_sleb128 (p, &p);
1419                                 if (record)
1420                                         throw_count++;
1421                                 if (has_bt) {
1422                                         has_bt = 8;
1423                                         frames = decode_bt (sframes, &has_bt, p, &p, ptr_base);
1424                                         if (!frames) {
1425                                                 fprintf (outfile, "Cannot load backtrace\n");
1426                                                 return 0;
1427                                         }
1428                                         if (record)
1429                                                 add_trace_methods (frames, has_bt, &exc_traces, 1);
1430                                 } else {
1431                                         if (record)
1432                                                 add_trace_thread (thread, &exc_traces, 1);
1433                                 }
1434                                 if (frames != sframes)
1435                                         free (frames);
1436                                 if (debug)
1437                                         fprintf (outfile, "throw %p\n", (void*)OBJ_ADDR (objdiff));
1438                         }
1439                         break;
1440                 }
1441                 default:
1442                         fprintf (outfile, "unhandled profiler event: 0x%x at file offset: %llu + %d (len: %d\n)\n", *p, file_offset, p - ctx->buf, len);
1443                         exit (1);
1444                 }
1445         }
1446         thread->last_time = time_base;
1447         for (i = 0; i < thread->stack_id; ++i)
1448                 thread->stack [i]->recurse_count = 0;
1449         return 1;
1450 }
1451
1452 static ProfContext*
1453 load_file (char *name)
1454 {
1455         unsigned char *p;
1456         ProfContext *ctx = calloc (sizeof (ProfContext), 1);
1457         if (strcmp (name, "-") == 0)
1458                 ctx->file = stdin;
1459         else
1460                 ctx->file = fopen (name, "rb");
1461         if (!ctx->file) {
1462                 printf ("Cannot open file: %s\n", name);
1463                 exit (1);
1464         }
1465 #if defined (HAVE_SYS_ZLIB)
1466         ctx->gzfile = gzdopen (fileno (ctx->file), "rb");
1467 #endif
1468         if (!load_data (ctx, 32))
1469                 return NULL;
1470         p = ctx->buf;
1471         if (read_int32 (p) != LOG_HEADER_ID || p [6] != LOG_DATA_VERSION)
1472                 return NULL;
1473         ctx->version_major = p [4];
1474         ctx->version_minor = p [5];
1475         ctx->data_version = p [6];
1476         /* reading 64 bit files on 32 bit systems not supported yet */
1477         if (p [7] > sizeof (void*))
1478                 return NULL;
1479         if (read_int32 (p + 20)) /* flags must be 0 */
1480                 return NULL;
1481         ctx->startup_time = read_int64 (p + 8);
1482         ctx->timer_overhead = read_int32 (p + 16);
1483         return ctx;
1484 }
1485
1486 enum {
1487         ALLOC_SORT_BYTES,
1488         ALLOC_SORT_COUNT
1489 };
1490 static int alloc_sort_mode = ALLOC_SORT_BYTES;
1491
1492 static int
1493 compare_class (const void *a, const void *b)
1494 {
1495         ClassDesc *const*A = a;
1496         ClassDesc *const*B = b;
1497         uint64_t vala, valb;
1498         if (alloc_sort_mode == ALLOC_SORT_BYTES) {
1499                 vala = (*A)->alloc_size;
1500                 valb = (*B)->alloc_size;
1501         } else {
1502                 vala = (*A)->allocs;
1503                 valb = (*B)->allocs;
1504         }
1505         if (valb == vala)
1506                 return 0;
1507         if (valb < vala)
1508                 return -1;
1509         return 1;
1510 }
1511
1512 static void
1513 dump_header (ProfContext *ctx)
1514 {
1515         time_t st = ctx->startup_time / 1000;
1516         char *t = ctime (&st);
1517         fprintf (outfile, "\nMono log profiler data\n");
1518         fprintf (outfile, "\tProfiler version: %d.%d\n", ctx->version_major, ctx->version_minor);
1519         fprintf (outfile, "\tData version: %d\n", ctx->data_version);
1520         fprintf (outfile, "\tMean timer overhead: %d nanoseconds\n", ctx->timer_overhead);
1521         fprintf (outfile, "\tProgram startup: %s\n", t);
1522 }
1523
1524 static void
1525 dump_traces (TraceDesc *traces, const char *desc)
1526 {
1527         int j;
1528         if (!show_traces)
1529                 return;
1530         if (!traces->count)
1531                 return;
1532         sort_context_array (traces);
1533         for (j = 0; j < traces->count; ++j) {
1534                 int k;
1535                 BackTrace *bt;
1536                 bt = traces->traces [j].bt;
1537                 if (!bt->count)
1538                         continue;
1539                 fprintf (outfile, "\t%llu %s from:\n", traces->traces [j].count, desc);
1540                 for (k = 0; k < bt->count; ++k)
1541                         fprintf (outfile, "\t\t%s\n", bt->methods [k]->name);
1542         }
1543 }
1544
1545 static void
1546 dump_threads (ProfContext *ctx)
1547 {
1548         ThreadContext *thread;
1549         fprintf (outfile, "\nThread summary\n");
1550         for (thread = ctx->threads; thread; thread = thread->next) {
1551                 fprintf (outfile, "\tThread: %p, name: \"%s\"\n", (void*)thread->thread_id, thread->name? thread->name: "");
1552         }
1553 }
1554
1555 static void
1556 dump_exceptions (void)
1557 {
1558         int i;
1559         fprintf (outfile, "\nException summary\n");
1560         fprintf (outfile, "\tThrows: %llu\n", throw_count);
1561         dump_traces (&exc_traces, "throws");
1562         for (i = 0; i <= MONO_EXCEPTION_CLAUSE_FAULT; ++i) {
1563                 if (!clause_summary [i])
1564                         continue;
1565                 fprintf (outfile, "\tExecuted %s clauses: %llu\n", clause_name (i), clause_summary [i]);
1566         }
1567 }
1568
1569 static int
1570 compare_monitor (const void *a, const void *b)
1571 {
1572         MonitorDesc *const*A = a;
1573         MonitorDesc *const*B = b;
1574         if ((*B)->wait_time == (*A)->wait_time)
1575                 return 0;
1576         if ((*B)->wait_time < (*A)->wait_time)
1577                 return -1;
1578         return 1;
1579 }
1580
1581 static void
1582 dump_monitors (void)
1583 {
1584         MonitorDesc **monitors;
1585         int i, j;
1586         if (!num_monitors)
1587                 return;
1588         monitors = malloc (sizeof (void*) * num_monitors);
1589         for (i = 0, j = 0; i < SMALL_HASH_SIZE; ++i) {
1590                 MonitorDesc *mdesc = monitor_hash [i];
1591                 while (mdesc) {
1592                         monitors [j++] = mdesc;
1593                         mdesc = mdesc->next;
1594                 }
1595         }
1596         qsort (monitors, num_monitors, sizeof (void*), compare_monitor);
1597         fprintf (outfile, "\nMonitor lock summary\n");
1598         for (i = 0; i < num_monitors; ++i) {
1599                 MonitorDesc *mdesc = monitors [i];
1600                 fprintf (outfile, "\tLock object %p: %d contentions\n", (void*)mdesc->objid, (int)mdesc->contentions);
1601                 fprintf (outfile, "\t\t%.6f secs total wait time, %.6f max, %.6f average\n",
1602                         mdesc->wait_time/1000000000.0, mdesc->max_wait_time/1000000000.0, mdesc->wait_time/1000000000.0/mdesc->contentions);
1603                 dump_traces (&mdesc->traces, "contentions");
1604         }
1605         fprintf (outfile, "\tLock contentions: %llu\n", monitor_contention);
1606         fprintf (outfile, "\tLock acquired: %llu\n", monitor_acquired);
1607         fprintf (outfile, "\tLock failures: %llu\n", monitor_failed);
1608 }
1609
1610 static void
1611 dump_gcs (void)
1612 {
1613         int i;
1614         fprintf (outfile, "\nGC summary\n");
1615         fprintf (outfile, "\tGC resizes: %d\n", gc_resizes);
1616         fprintf (outfile, "\tMax heap size: %llu\n", max_heap_size);
1617         fprintf (outfile, "\tObject moves: %llu\n", gc_object_moves);
1618         for (i = 0; i < 3; ++i) {
1619                 if (!gc_info [i].count)
1620                         continue;
1621                 fprintf (outfile, "\tGen%d collections: %d, max time: %lluus, total time: %lluus, average: %lluus\n",
1622                         i, gc_info [i].count, gc_info [i].max_time / 1000, gc_info [i].total_time / 1000,
1623                         gc_info [i].total_time / gc_info [i].count / 1000);
1624         }
1625         for (i = 0; i < 3; ++i) {
1626                 if (!handle_info [i].max_live)
1627                         continue;
1628                 fprintf (outfile, "\tGC handles %s: created: %llu, destroyed: %llu, max: %llu\n",
1629                         get_handle_name (i), handle_info [i].created, handle_info [i].destroyed, handle_info [i].max_live);
1630                 dump_traces (&handle_info [i].traces, "created");
1631         }
1632 }
1633
1634 static void
1635 dump_allocations (void)
1636 {
1637         int i, c;
1638         intptr_t allocs = 0;
1639         uint64_t size = 0;
1640         int header_done = 0;
1641         ClassDesc **classes = malloc (num_classes * sizeof (void*));
1642         ClassDesc *cd;
1643         c = 0;
1644         for (i = 0; i < HASH_SIZE; ++i) {
1645                 cd = class_hash [i];
1646                 while (cd) {
1647                         classes [c++] = cd;
1648                         cd = cd->next;
1649                 }
1650         }
1651         qsort (classes, num_classes, sizeof (void*), compare_class);
1652         for (i = 0; i < num_classes; ++i) {
1653                 cd = classes [i];
1654                 if (!cd->allocs)
1655                         continue;
1656                 allocs += cd->allocs;
1657                 size += cd->alloc_size;
1658                 if (!header_done++) {
1659                         fprintf (outfile, "\nAllocation summary\n");
1660                         fprintf (outfile, "%10s %10s %8s Type name\n", "Bytes", "Count", "Average");
1661                 }
1662                 fprintf (outfile, "%10llu %10d %8llu %s\n", cd->alloc_size, cd->allocs, cd->alloc_size / cd->allocs, cd->name);
1663                 dump_traces (&cd->traces, "bytes");
1664         }
1665         if (allocs)
1666                 fprintf (outfile, "Total memory allocated: %llu bytes in %d objects\n", size, allocs);
1667 }
1668
1669 enum {
1670         METHOD_SORT_TOTAL,
1671         METHOD_SORT_SELF,
1672         METHOD_SORT_CALLS
1673 };
1674
1675 static int method_sort_mode = METHOD_SORT_TOTAL;
1676
1677 static int
1678 compare_method (const void *a, const void *b)
1679 {
1680         MethodDesc *const*A = a;
1681         MethodDesc *const*B = b;
1682         uint64_t vala, valb;
1683         if (method_sort_mode == METHOD_SORT_SELF) {
1684                 vala = (*A)->self_time;
1685                 valb = (*B)->self_time;
1686         } else if (method_sort_mode == METHOD_SORT_CALLS) {
1687                 vala = (*A)->calls;
1688                 valb = (*B)->calls;
1689         } else {
1690                 vala = (*A)->total_time;
1691                 valb = (*B)->total_time;
1692         }
1693         if (vala == valb)
1694                 return 0;
1695         if (valb < vala)
1696                 return -1;
1697         return 1;
1698 }
1699
1700 static void
1701 dump_metadata (void)
1702 {
1703         fprintf (outfile, "\nMetadata summary\n");
1704         fprintf (outfile, "\tLoaded images: %d\n", num_images);
1705         if (verbose) {
1706                 ImageDesc *image;
1707                 int i;
1708                 for (i = 0; i < SMALL_HASH_SIZE; ++i) {
1709                         image = image_hash [i];
1710                         while (image) {
1711                                 fprintf (outfile, "\t\t%s\n", image->filename);
1712                                 image = image->next;
1713                         }
1714                 }
1715         }
1716
1717 }
1718
1719 static void
1720 dump_methods (void)
1721 {
1722         int i, c;
1723         uint64_t calls = 0;
1724         int header_done = 0;
1725         MethodDesc **methods = malloc (num_methods * sizeof (void*));
1726         MethodDesc *cd;
1727         c = 0;
1728         for (i = 0; i < HASH_SIZE; ++i) {
1729                 cd = method_hash [i];
1730                 while (cd) {
1731                         cd->total_time = cd->self_time + cd->callee_time;
1732                         methods [c++] = cd;
1733                         cd = cd->next;
1734                 }
1735         }
1736         qsort (methods, num_methods, sizeof (void*), compare_method);
1737         for (i = 0; i < num_methods; ++i) {
1738                 uint64_t msecs;
1739                 uint64_t smsecs;
1740                 cd = methods [i];
1741                 if (!cd->calls)
1742                         continue;
1743                 calls += cd->calls;
1744                 msecs = cd->total_time / 1000000;
1745                 smsecs = (cd->total_time - cd->callee_time) / 1000000;
1746                 if (!msecs && !verbose)
1747                         continue;
1748                 if (!header_done++) {
1749                         fprintf (outfile, "\nMethod call summary\n");
1750                         fprintf (outfile, "%8s %8s %10s Method name\n", "Total(ms)", "Self(ms)", "Calls");
1751                 }
1752                 fprintf (outfile, "%8llu %8llu %10llu %s\n", msecs, smsecs, cd->calls, cd->name);
1753                 dump_traces (&cd->traces, "calls");
1754         }
1755         if (calls)
1756                 fprintf (outfile, "Total calls: %llu\n", calls);
1757 }
1758
1759 static int
1760 compare_heap_class (const void *a, const void *b)
1761 {
1762         HeapClassDesc *const*A = a;
1763         HeapClassDesc *const*B = b;
1764         uint64_t vala, valb;
1765         if (alloc_sort_mode == ALLOC_SORT_BYTES) {
1766                 vala = (*A)->total_size;
1767                 valb = (*B)->total_size;
1768         } else {
1769                 vala = (*A)->count;
1770                 valb = (*B)->count;
1771         }
1772         if (valb == vala)
1773                 return 0;
1774         if (valb < vala)
1775                 return -1;
1776         return 1;
1777 }
1778
1779 static int
1780 compare_rev_class (const void *a, const void *b)
1781 {
1782         const HeapClassRevRef *A = a;
1783         const HeapClassRevRef *B = b;
1784         if (B->count == A->count)
1785                 return 0;
1786         if (B->count < A->count)
1787                 return -1;
1788         return 1;
1789 }
1790
1791 static void
1792 dump_rev_claases (HeapClassRevRef *revs, int count)
1793 {
1794         int j;
1795         if (!show_traces)
1796                 return;
1797         if (!count)
1798                 return;
1799         for (j = 0; j < count; ++j) {
1800                 HeapClassDesc *cd = revs [j].klass;
1801                 fprintf (outfile, "\t\t%llu references from: %s\n", revs [j].count, cd->klass->name);
1802         }
1803 }
1804
1805 static void
1806 heap_shot_summary (HeapShot *hs, int hs_num, HeapShot *last_hs)
1807 {
1808         uint64_t size = 0;
1809         uint64_t count = 0;
1810         int ccount = 0;
1811         int i;
1812         HeapClassDesc *cd;
1813         HeapClassDesc **sorted;
1814         sorted = malloc (sizeof (void*) * hs->class_count);
1815         for (i = 0; i < hs->hash_size; ++i) {
1816                 cd = hs->class_hash [i];
1817                 if (!cd)
1818                         continue;
1819                 count += cd->count;
1820                 size += cd->total_size;
1821                 sorted [ccount++] = cd;
1822         }
1823         hs->sorted = sorted;
1824         qsort (sorted, ccount, sizeof (void*), compare_heap_class);
1825         fprintf (outfile, "\n\tHeap shot %d at %.3f secs: size: %llu, object count: %llu, class count: %d\n",
1826                 hs_num, (hs->timestamp - startup_time)/1000000000.0, size, count, ccount);
1827         if (!verbose && ccount > 30)
1828                 ccount = 30;
1829         fprintf (outfile, "\t%10s %10s %8s Class name\n", "Bytes", "Count", "Average");
1830         for (i = 0; i < ccount; ++i) {
1831                 HeapClassRevRef *rev_sorted;
1832                 int j, k;
1833                 HeapClassDesc *ocd = NULL;
1834                 cd = sorted [i];
1835                 if (last_hs)
1836                         ocd = heap_class_lookup (last_hs, cd->klass);
1837                 fprintf (outfile, "\t%10llu %10llu %8llu %s", cd->total_size, cd->count, cd->total_size / cd->count, cd->klass->name);
1838                 if (ocd) {
1839                         int64_t bdiff = cd->total_size - ocd->total_size;
1840                         int64_t cdiff = cd->count - ocd->count;
1841                         fprintf (outfile, " (bytes: %+lld, count: %+lld)\n", bdiff, cdiff);
1842                 } else {
1843                         fprintf (outfile, "\n");
1844                 }
1845                 if (!collect_traces)
1846                         continue;
1847                 rev_sorted = malloc (cd->rev_count * sizeof (HeapClassRevRef));
1848                 k = 0;
1849                 for (j = 0; j < cd->rev_hash_size; ++j) {
1850                         if (cd->rev_hash [j].klass)
1851                                 rev_sorted [k++] = cd->rev_hash [j];
1852                 }
1853                 assert (cd->rev_count == k);
1854                 qsort (rev_sorted, cd->rev_count, sizeof (HeapClassRevRef), compare_rev_class);
1855                 dump_rev_claases (rev_sorted, cd->rev_count);
1856                 free (rev_sorted);
1857         }
1858         free (sorted);
1859 }
1860
1861 static int
1862 compare_heap_shots (const void *a, const void *b)
1863 {
1864         HeapShot *const*A = a;
1865         HeapShot *const*B = b;
1866         if ((*B)->timestamp == (*A)->timestamp)
1867                 return 0;
1868         if ((*B)->timestamp > (*A)->timestamp)
1869                 return -1;
1870         return 1;
1871 }
1872
1873 static void
1874 dump_heap_shots (void)
1875 {
1876         HeapShot **hs_sorted;
1877         HeapShot *hs;
1878         HeapShot *last_hs = NULL;
1879         int i;
1880         if (!heap_shots)
1881                 return;
1882         hs_sorted = malloc (num_heap_shots * sizeof (void*));
1883         fprintf (outfile, "\nHeap shot summary\n");
1884         i = 0;
1885         for (hs = heap_shots; hs; hs = hs->next)
1886                 hs_sorted [i++] = hs;
1887         qsort (hs_sorted, num_heap_shots, sizeof (void*), compare_heap_shots);
1888         for (i = 0; i < num_heap_shots; ++i) {
1889                 hs = hs_sorted [i];
1890                 heap_shot_summary (hs, i, last_hs);
1891                 last_hs = hs;
1892         }
1893 }
1894
1895 static void
1896 flush_context (ProfContext *ctx)
1897 {
1898         ThreadContext *thread;
1899         /* FIXME: sometimes there are leftovers: indagate */
1900         for (thread = ctx->threads; thread; thread = thread->next) {
1901                 while (thread->stack_id) {
1902                         if (debug)
1903                                 fprintf (outfile, "thread %p has %d items on stack\n", (void*)thread->thread_id, thread->stack_id);
1904                         pop_method (thread, thread->stack [thread->stack_id - 1], thread->last_time);
1905                 }
1906         }
1907 }
1908
1909 static const char *reports = "header,gc,alloc,call,metadata,exception,monitor,thread,heapshot";
1910
1911 static const char*
1912 match_option (const char *p, const char *opt)
1913 {
1914         int len = strlen (opt);
1915         if (strncmp (p, opt, len) == 0) {
1916                 if (p [len] == ',')
1917                         len++;
1918                 return p + len;
1919         }
1920         return p;
1921 }
1922
1923 static int
1924 print_reports (ProfContext *ctx, const char *reps, int parse_only)
1925 {
1926         const char *opt;
1927         const char *p;
1928         for (p = reps; *p; p = opt) {
1929                 if ((opt = match_option (p, "header")) != p) {
1930                         if (!parse_only)
1931                                 dump_header (ctx);
1932                         continue;
1933                 }
1934                 if ((opt = match_option (p, "thread")) != p) {
1935                         if (!parse_only)
1936                                 dump_threads (ctx);
1937                         continue;
1938                 }
1939                 if ((opt = match_option (p, "gc")) != p) {
1940                         if (!parse_only)
1941                                 dump_gcs ();
1942                         continue;
1943                 }
1944                 if ((opt = match_option (p, "alloc")) != p) {
1945                         if (!parse_only)
1946                                 dump_allocations ();
1947                         continue;
1948                 }
1949                 if ((opt = match_option (p, "call")) != p) {
1950                         if (!parse_only)
1951                                 dump_methods ();
1952                         continue;
1953                 }
1954                 if ((opt = match_option (p, "metadata")) != p) {
1955                         if (!parse_only)
1956                                 dump_metadata ();
1957                         continue;
1958                 }
1959                 if ((opt = match_option (p, "exception")) != p) {
1960                         if (!parse_only)
1961                                 dump_exceptions ();
1962                         continue;
1963                 }
1964                 if ((opt = match_option (p, "monitor")) != p) {
1965                         if (!parse_only)
1966                                 dump_monitors ();
1967                         continue;
1968                 }
1969                 if ((opt = match_option (p, "heapshot")) != p) {
1970                         if (!parse_only)
1971                                 dump_heap_shots ();
1972                         continue;
1973                 }
1974                 return 0;
1975         }
1976         return 1;
1977 }
1978
1979 static int
1980 add_find_spec (const char *p)
1981 {
1982         if (p [0] == 'S' && p [1] == ':') {
1983                 char *vale;
1984                 find_size = strtoul (p + 2, &vale, 10);
1985                 return 1;
1986         } else if (p [0] == 'T' && p [1] == ':') {
1987                 find_name = p + 2;
1988                 return 1;
1989         }
1990         return 0;
1991 }
1992
1993 static void
1994 usage (void)
1995 {
1996         printf ("Mono log profiler report version %d.%d\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR);
1997         printf ("Usage: mprof-report [OPTIONS] FILENAME\n");
1998         printf ("FILENAME can be '-' to read from standard input.\n");
1999         printf ("Options:\n");
2000         printf ("\t--help               display this help\n");
2001         printf ("\t--out=FILE           write to FILE instead of stdout\n");
2002         printf ("\t--traces             collect and show backtraces\n"); 
2003         printf ("\t--maxframes=NUM      limit backtraces to NUM entries\n");
2004         printf ("\t--reports=R1[,R2...] print the specified reports. Defaults are:\n");
2005         printf ("\t                     %s\n", reports);
2006         printf ("\t--method-sort=MODE   sort methods according to MODE: total, self, calls\n");
2007         printf ("\t--alloc-sort=MODE    sort allocations according to MODE: bytes, count\n");
2008         printf ("\t--track=OB1[,OB2...] track what happens to objects OBJ1, O2 etc.\n");
2009         printf ("\t--find=FINDSPEC      find and track objects matching FINFSPEC, where FINDSPEC is:\n");
2010         printf ("\t                     S:minimum_size or T:partial_name\n");
2011         printf ("\t--thread=THREADID    consider just the data for thread THREADID\n");
2012         printf ("\t--time=FROM-TO       consider data FROM seconds from startup up to TO seconds\n");
2013         printf ("\t--verbose            increase verbosity level\n");
2014         printf ("\t--debug              display decoding debug info for mprof-report devs\n");
2015 }
2016
2017 int
2018 main (int argc, char *argv[])
2019 {
2020         ProfContext *ctx;
2021         int i;
2022         outfile = stdout;
2023         for (i = 1; i < argc; ++i) {
2024                 if (strcmp ("--debug", argv [i]) == 0) {
2025                         debug++;
2026                 } else if (strcmp ("--help", argv [i]) == 0) {
2027                         usage ();
2028                         return 0;
2029                 } else if (strncmp ("--alloc-sort=", argv [i], 13) == 0) {
2030                         const char *val = argv [i] + 13;
2031                         if (strcmp (val, "bytes") == 0) {
2032                                 alloc_sort_mode = ALLOC_SORT_BYTES;
2033                         } else if (strcmp (val, "count") == 0) {
2034                                 alloc_sort_mode = ALLOC_SORT_COUNT;
2035                         } else {
2036                                 usage ();
2037                                 return 1;
2038                         }
2039                 } else if (strncmp ("--method-sort=", argv [i], 14) == 0) {
2040                         const char *val = argv [i] + 14;
2041                         if (strcmp (val, "total") == 0) {
2042                                 method_sort_mode = METHOD_SORT_TOTAL;
2043                         } else if (strcmp (val, "self") == 0) {
2044                                 method_sort_mode = METHOD_SORT_SELF;
2045                         } else if (strcmp (val, "calls") == 0) {
2046                                 method_sort_mode = METHOD_SORT_CALLS;
2047                         } else {
2048                                 usage ();
2049                                 return 1;
2050                         }
2051                 } else if (strncmp ("--reports=", argv [i], 10) == 0) {
2052                         const char *val = argv [i] + 10;
2053                         if (!print_reports (NULL, val, 1)) {
2054                                 usage ();
2055                                 return 1;
2056                         }
2057                         reports = val;
2058                 } else if (strncmp ("--out=", argv [i], 6) == 0) {
2059                         const char *val = argv [i] + 6;
2060                         outfile = fopen (val, "w");
2061                         if (!outfile) {
2062                                 printf ("Cannot open output file: %s\n", val);
2063                                 return 1;
2064                         }
2065                 } else if (strncmp ("--maxframes=", argv [i], 12) == 0) {
2066                         const char *val = argv [i] + 12;
2067                         char *vale;
2068                         trace_max = strtoul (val, &vale, 10);
2069                 } else if (strncmp ("--find=", argv [i], 7) == 0) {
2070                         const char *val = argv [i] + 7;
2071                         if (!add_find_spec (val)) {
2072                                 usage ();
2073                                 return 1;
2074                         }
2075                 } else if (strncmp ("--track=", argv [i], 8) == 0) {
2076                         const char *val = argv [i] + 8;
2077                         char *vale;
2078                         while (*val) {
2079                                 uintptr_t tracked_obj;
2080                                 if (*val == ',') {
2081                                         val++;
2082                                         continue;
2083                                 }
2084                                 tracked_obj = strtoul (val, &vale, 0);
2085                                 found_object (tracked_obj);
2086                                 val = vale;
2087                         }
2088                 } else if (strncmp ("--thread=", argv [i], 9) == 0) {
2089                         const char *val = argv [i] + 9;
2090                         char *vale;
2091                         thread_filter = strtoul (val, &vale, 0);
2092                 } else if (strncmp ("--time=", argv [i], 7) == 0) {
2093                         char *val = pstrdup (argv [i] + 7);
2094                         double from_secs, to_secs;
2095                         char *top = strchr (val, '-');
2096                         if (!top) {
2097                                 usage ();
2098                                 return 1;
2099                         }
2100                         *top++ = 0;
2101                         from_secs = atof (val);
2102                         to_secs = atof (top);
2103                         free (val);
2104                         if (from_secs > to_secs) {
2105                                 usage ();
2106                                 return 1;
2107                         }
2108                         time_from = from_secs * 1000000000;
2109                         time_to = to_secs * 1000000000;
2110                 } else if (strcmp ("--verbose", argv [i]) == 0) {
2111                         verbose++;
2112                 } else if (strcmp ("--traces", argv [i]) == 0) {
2113                         show_traces = 1;
2114                         collect_traces = 1;
2115                 } else {
2116                         break;
2117                 }
2118         }
2119         if (i >= argc) {
2120                 usage ();
2121                 return 2;
2122         }
2123         ctx = load_file (argv [i]);
2124         if (!ctx) {
2125                 printf ("Not a log profiler data file (or unsupported version).\n");
2126                 return 1;
2127         }
2128         while (decode_buffer (ctx));
2129         flush_context (ctx);
2130         if (num_tracked_objects)
2131                 return 0;
2132         print_reports (ctx, reports, 0);
2133         return 0;
2134 }
2135