Log profiler: allow overwriting data files and name them from date and pid.
[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         int pid;
626         uint64_t startup_time;
627         ThreadContext *threads;
628         ThreadContext *current;
629 } ProfContext;
630
631 struct _ThreadContext {
632         ThreadContext *next;
633         intptr_t thread_id;
634         char *name;
635         /* emulated stack */
636         MethodDesc **stack;
637         uint64_t *time_stack;
638         uint64_t *callee_time_stack;
639         uint64_t last_time;
640         uint64_t contention_start;
641         MonitorDesc *monitor;
642         int stack_size;
643         int stack_id;
644         HeapShot *current_heap_shot;
645 };
646
647 static void
648 ensure_buffer (ProfContext *ctx, int size)
649 {
650         if (ctx->size < size) {
651                 ctx->buf = realloc (ctx->buf, size);
652                 ctx->size = size;
653         }
654 }
655
656 static int
657 load_data (ProfContext *ctx, int size)
658 {
659         ensure_buffer (ctx, size);
660 #if defined (HAVE_SYS_ZLIB)
661         if (ctx->gzfile)
662                 return gzread (ctx->gzfile, ctx->buf, size) == size;
663         else
664 #endif
665                 return fread (ctx->buf, size, 1, ctx->file);
666 }
667
668 static ThreadContext*
669 get_thread (ProfContext *ctx, intptr_t thread_id)
670 {
671         ThreadContext *thread;
672         if (ctx->current && ctx->current->thread_id == thread_id)
673                 return ctx->current;
674         thread = ctx->threads;
675         while (thread) {
676                 if (thread->thread_id == thread_id) {
677                         return thread;
678                 }
679                 thread = thread->next;
680         }
681         thread = calloc (sizeof (ThreadContext), 1);
682         thread->next = ctx->threads;
683         ctx->threads = thread;
684         thread->thread_id = thread_id;
685         thread->last_time = 0;
686         thread->stack_id = 0;
687         thread->stack_size = 32;
688         thread->stack = malloc (thread->stack_size * sizeof (void*));
689         thread->time_stack = malloc (thread->stack_size * sizeof (uint64_t));
690         thread->callee_time_stack = malloc (thread->stack_size * sizeof (uint64_t));
691         return thread;
692 }
693
694 static ThreadContext*
695 load_thread (ProfContext *ctx, intptr_t thread_id)
696 {
697         ThreadContext *thread = get_thread (ctx, thread_id);
698         ctx->current = thread;
699         return thread;
700 }
701
702 static void
703 ensure_thread_stack (ThreadContext *thread)
704 {
705         if (thread->stack_id == thread->stack_size) {
706                 thread->stack_size *= 2;
707                 thread->stack = realloc (thread->stack, thread->stack_size * sizeof (void*));
708                 thread->time_stack = realloc (thread->time_stack, thread->stack_size * sizeof (uint64_t));
709                 thread->callee_time_stack = realloc (thread->callee_time_stack, thread->stack_size * sizeof (uint64_t));
710         }
711 }
712
713 static int
714 add_trace_hashed (CallContext *traces, int size, BackTrace *bt, uint64_t value)
715 {
716         int i;
717         unsigned int start_pos;
718         start_pos = bt->hash % size;
719         i = start_pos;
720         do {
721                 if (traces [i].bt == bt) {
722                         traces [i].count += value;
723                         return 0;
724                 } else if (!traces [i].bt) {
725                         traces [i].bt = bt;
726                         traces [i].count += value;
727                         return 1;
728                 }
729                 /* wrap around */
730                 if (++i == size)
731                         i = 0;
732         } while (i != start_pos);
733         /* should not happen */
734         printf ("failed trace store\n");
735         return 0;
736 }
737
738 static void
739 add_trace_bt (BackTrace *bt, TraceDesc *trace, uint64_t value)
740 {
741         int i;
742         if (!collect_traces)
743                 return;
744         if (trace->count * 2 >= trace->size) {
745                 CallContext *n;
746                 int old_size = trace->size;
747                 trace->size *= 2;
748                 if (trace->size == 0)
749                         trace->size = 4;
750                 n = calloc (sizeof (CallContext) * trace->size, 1);
751                 for (i = 0; i < old_size; ++i) {
752                         if (trace->traces [i].bt)
753                                 add_trace_hashed (n, trace->size, trace->traces [i].bt, trace->traces [i].count);
754                 }
755                 if (trace->traces)
756                         free (trace->traces);
757                 trace->traces = n;
758         }
759         trace->count += add_trace_hashed (trace->traces, trace->size, bt, value);
760 }
761
762 static BackTrace*
763 add_trace_thread (ThreadContext *thread, TraceDesc *trace, uint64_t value)
764 {
765         BackTrace *bt;
766         int count = thread->stack_id;
767         if (!collect_traces)
768                 return NULL;
769         if (count > trace_max)
770                 count = trace_max;
771         bt = add_backtrace (count, thread->stack + thread->stack_id - count);
772         add_trace_bt (bt, trace, value);
773         return bt;
774 }
775
776 static BackTrace*
777 add_trace_methods (MethodDesc **methods, int count, TraceDesc *trace, uint64_t value)
778 {
779         BackTrace *bt;
780         if (!collect_traces)
781                 return NULL;
782         if (count > trace_max)
783                 count = trace_max;
784         bt = add_backtrace (count, methods);
785         add_trace_bt (bt, trace, value);
786         return bt;
787 }
788
789 static int
790 compare_callc (const void *a, const void *b)
791 {
792         const CallContext *A = a;
793         const CallContext *B = b;
794         if (B->count == A->count)
795                 return 0;
796         if (B->count < A->count)
797                 return -1;
798         return 1;
799 }
800
801 static void
802 sort_context_array (TraceDesc* traces)
803 {
804         int i, j;
805         for (i = 0, j = 0; i < traces->size; ++i) {
806                 if (traces->traces [i].bt) {
807                         traces->traces [j].bt = traces->traces [i].bt;
808                         traces->traces [j].count = traces->traces [i].count;
809                         j++;
810                 }
811         }
812         qsort (traces->traces, traces->count, sizeof (CallContext), compare_callc);
813 }
814
815 static void
816 push_method (ThreadContext *thread, MethodDesc *method, uint64_t timestamp)
817 {
818         ensure_thread_stack (thread);
819         thread->time_stack [thread->stack_id] = timestamp;
820         thread->callee_time_stack [thread->stack_id] = 0;
821         thread->stack [thread->stack_id++] = method;
822         method->recurse_count++;
823 }
824
825 static void
826 pop_method (ThreadContext *thread, MethodDesc *method, uint64_t timestamp)
827 {
828         method->recurse_count--;
829         if (thread->stack_id > 0 && thread->stack [thread->stack_id - 1] == method) {
830                 uint64_t tdiff;
831                 thread->stack_id--;
832                 method->calls++;
833                 if (timestamp < thread->time_stack [thread->stack_id])
834                         fprintf (outfile, "time went backwards for %s\n", method->name);
835                 tdiff = timestamp - thread->time_stack [thread->stack_id];
836                 if (thread->callee_time_stack [thread->stack_id] > tdiff)
837                         fprintf (outfile, "callee time bigger for %s\n", method->name);
838                 method->self_time += tdiff - thread->callee_time_stack [thread->stack_id];
839                 method->callee_time += thread->callee_time_stack [thread->stack_id];
840                 if (thread->stack_id)
841                         thread->callee_time_stack [thread->stack_id - 1] += tdiff;
842                 //fprintf (outfile, "method %s took %d\n", method->name, (int)(tdiff/1000));
843         } else {
844                 fprintf (outfile, "unmatched leave at stack pos: %d for method %s\n", thread->stack_id, method->name);
845         }
846 }
847
848 typedef struct {
849         uint64_t start_time; /* move this per-thread? */
850         uint64_t total_time;
851         uint64_t max_time;
852         int count;
853 } GCDesc;
854 static GCDesc gc_info [3];
855 static uint64_t max_heap_size;
856 static uint64_t gc_object_moves;
857 static int gc_resizes;
858 typedef struct {
859         uint64_t created;
860         uint64_t destroyed;
861         uint64_t max_live;
862         TraceDesc traces;
863 } HandleInfo;
864 static HandleInfo handle_info [4];
865
866 static const char*
867 gc_event_name (int ev)
868 {
869         switch (ev) {
870         case MONO_GC_EVENT_START: return "start";
871         case MONO_GC_EVENT_MARK_START: return "mark start";
872         case MONO_GC_EVENT_MARK_END: return "mark end";
873         case MONO_GC_EVENT_RECLAIM_START: return "reclaim start";
874         case MONO_GC_EVENT_RECLAIM_END: return "reclaim end";
875         case MONO_GC_EVENT_END: return "end";
876         case MONO_GC_EVENT_PRE_STOP_WORLD: return "pre stop";
877         case MONO_GC_EVENT_POST_STOP_WORLD: return "post stop";
878         case MONO_GC_EVENT_PRE_START_WORLD: return "pre start";
879         case MONO_GC_EVENT_POST_START_WORLD: return "post start";
880         default:
881                 return "unknown";
882         }
883 }
884
885 static uint64_t clause_summary [MONO_EXCEPTION_CLAUSE_FAULT + 1];
886 static uint64_t throw_count = 0;
887 static TraceDesc exc_traces;
888
889 static const char*
890 clause_name (int type)
891 {
892         switch (type) {
893         case MONO_EXCEPTION_CLAUSE_NONE: return "catch";
894         case MONO_EXCEPTION_CLAUSE_FILTER: return "filter";
895         case MONO_EXCEPTION_CLAUSE_FINALLY: return "finally";
896         case MONO_EXCEPTION_CLAUSE_FAULT: return "fault";
897         default: return "invalid";
898         }
899 }
900
901 static uint64_t monitor_contention;
902 static uint64_t monitor_failed;
903 static uint64_t monitor_acquired;
904
905 struct _MonitorDesc {
906         MonitorDesc *next;
907         uintptr_t objid;
908         uintptr_t contentions;
909         uint64_t wait_time;
910         uint64_t max_wait_time;
911         TraceDesc traces;
912 };
913
914 static MonitorDesc* monitor_hash [SMALL_HASH_SIZE] = {0};
915 static int num_monitors = 0;
916
917 static MonitorDesc*
918 lookup_monitor (uintptr_t objid)
919 {
920         int slot = ((objid >> 3) & 0xffff) % SMALL_HASH_SIZE;
921         MonitorDesc *cd = monitor_hash [slot];
922         while (cd && cd->objid != objid)
923                 cd = cd->next;
924         if (!cd) {
925                 cd = calloc (sizeof (MonitorDesc), 1);
926                 cd->objid = objid;
927                 cd->next = monitor_hash [slot];
928                 monitor_hash [slot] = cd;
929                 num_monitors++;
930         }
931         return cd;
932 }
933
934 static const char*
935 monitor_ev_name (int ev)
936 {
937         switch (ev) {
938         case MONO_PROFILER_MONITOR_CONTENTION: return "contended";
939         case MONO_PROFILER_MONITOR_DONE: return "acquired";
940         case MONO_PROFILER_MONITOR_FAIL: return "not taken";
941         default: return "invalid";
942         }
943 }
944
945 static const char*
946 get_handle_name (int htype)
947 {
948         switch (htype) {
949         case 0: return "weak";
950         case 1: return "weaktrack";
951         case 2: return "normal";
952         case 3: return "pinned";
953         default: return "unknown";
954         }
955 }
956
957 static MethodDesc**
958 decode_bt (MethodDesc** sframes, int *size, unsigned char *p, unsigned char **endp, intptr_t ptr_base)
959 {
960         MethodDesc **frames;
961         int i;
962         int flags = decode_uleb128 (p, &p);
963         int count = decode_uleb128 (p, &p);
964         if (flags != 0)
965                 return NULL;
966         if (count > *size)
967                 frames = malloc (count * sizeof (void*));
968         else
969                 frames = sframes;
970         for (i = 0; i < count; ++i) {
971                 intptr_t ptrdiff = decode_sleb128 (p, &p);
972                 frames [i] = lookup_method (ptr_base + ptrdiff);
973         }
974         *size = count;
975         *endp = p;
976         return frames;
977 }
978
979 static void
980 tracked_creation (uintptr_t obj, ClassDesc *cd, uint64_t size, BackTrace *bt, uint64_t timestamp)
981 {
982         int i;
983         for (i = 0; i < num_tracked_objects; ++i) {
984                 if (tracked_objects [i] != obj)
985                         continue;
986                 fprintf (outfile, "Object %p created (%s, %llu bytes) at %.3f secs.\n", (void*)obj, cd->name, size, (timestamp - startup_time)/1000000000.0);
987                 if (bt && bt->count) {
988                         int k;
989                         for (k = 0; k < bt->count; ++k)
990                                 fprintf (outfile, "\t%s\n", bt->methods [k]->name);
991                 }
992         }
993 }
994
995 static void
996 track_handle (uintptr_t obj, int htype, uint32_t handle)
997 {
998         int i;
999         for (i = 0; i < num_tracked_objects; ++i) {
1000                 if (tracked_objects [i] == obj)
1001                         fprintf (outfile, "Object %p referenced from handle %u\n", (void*)obj, handle);
1002         }
1003 }
1004
1005 static void
1006 track_move (uintptr_t src, uintptr_t dst)
1007 {
1008         int i;
1009         for (i = 0; i < num_tracked_objects; ++i) {
1010                 if (tracked_objects [i] == src)
1011                         fprintf (outfile, "Object %p moved to %p\n", (void*)src, (void*)dst);
1012                 else if (tracked_objects [i] == dst)
1013                         fprintf (outfile, "Object %p moved from %p\n", (void*)dst, (void*)src);
1014         }
1015 }
1016
1017 static void
1018 track_obj_reference (uintptr_t obj, uintptr_t parent, ClassDesc *cd)
1019 {
1020         int i;
1021         for (i = 0; i < num_tracked_objects; ++i) {
1022                 if (tracked_objects [i] == obj) 
1023                         fprintf (outfile, "Object %p referenced from %p (%s).\n", (void*)obj, (void*)parent, cd->name);
1024         }
1025 }
1026
1027 static void
1028 found_object (uintptr_t obj)
1029 {
1030         num_tracked_objects ++;
1031         tracked_objects = realloc (tracked_objects, num_tracked_objects * sizeof (tracked_objects [0]));
1032         tracked_objects [num_tracked_objects - 1] = obj;
1033 }
1034
1035 #define OBJ_ADDR(diff) ((obj_base + diff) << 3)
1036 #define LOG_TIME(base,diff) /*fprintf("outfile, time %llu + %llu near offset %d\n", base, diff, p - ctx->buf)*/
1037
1038 static int
1039 decode_buffer (ProfContext *ctx)
1040 {
1041         unsigned char *p;
1042         unsigned char *end;
1043         intptr_t thread_id;
1044         intptr_t ptr_base;
1045         intptr_t obj_base;
1046         intptr_t method_base;
1047         uint64_t time_base;
1048         uint64_t file_offset;
1049         int len, i;
1050         ThreadContext *thread;
1051
1052 #ifdef HAVE_SYS_ZLIB
1053         if (ctx->gzfile)
1054                 file_offset = gztell (ctx->gzfile);
1055         else
1056 #endif
1057                 file_offset = ftell (ctx->file);
1058         if (!load_data (ctx, 48))
1059                 return 0;
1060         p = ctx->buf;
1061         if (read_int32 (p) != BUF_ID)
1062                 return 0;
1063         len = read_int32 (p + 4);
1064         time_base = read_int64 (p + 8);
1065         ptr_base = read_int64 (p + 16);
1066         obj_base = read_int64 (p + 24);
1067         thread_id = read_int64 (p + 32);
1068         method_base = read_int64 (p + 40);
1069         if (debug)
1070                 fprintf (outfile, "buf: thread:%x, len: %d, time: %llu, file offset: %llu\n", thread_id, len, time_base, file_offset);
1071         thread = load_thread (ctx, thread_id);
1072         if (!load_data (ctx, len))
1073                 return 0;
1074         if (!startup_time) {
1075                 startup_time = time_base;
1076                 if (time_from) {
1077                         time_from += startup_time;
1078                         time_to += startup_time;
1079                 }
1080                 if (!thread->name)
1081                         thread->name = pstrdup ("Main");
1082         }
1083         for (i = 0; i < thread->stack_id; ++i)
1084                 thread->stack [i]->recurse_count++;
1085         p = ctx->buf;
1086         end = p + len;
1087         while (p < end) {
1088                 switch (*p & 0xf) {
1089                 case TYPE_GC: {
1090                         int subtype = *p & 0xf0;
1091                         uint64_t tdiff = decode_uleb128 (p + 1, &p);
1092                         LOG_TIME (time_base, tdiff);
1093                         time_base += tdiff;
1094                         if (subtype == TYPE_GC_RESIZE) {
1095                                 uint64_t new_size = decode_uleb128 (p, &p);
1096                                 if (debug)
1097                                         fprintf (outfile, "gc heap resized to %llu\n", new_size);
1098                                 gc_resizes++;
1099                                 if (new_size > max_heap_size)
1100                                         max_heap_size = new_size;
1101                         } else if (subtype == TYPE_GC_EVENT) {
1102                                 uint64_t ev = decode_uleb128 (p, &p);
1103                                 int gen = decode_uleb128 (p, &p);
1104                                 if (debug)
1105                                         fprintf (outfile, "gc event for gen%d: %s at %llu\n", gen - 1, gc_event_name (ev), time_base);
1106                                 if (gen > 2) {
1107                                         fprintf (outfile, "incorrect gc gen: %d\n", gen);
1108                                         break;
1109                                 }
1110                                 if (ev == MONO_GC_EVENT_START) {
1111                                         gc_info [gen].start_time = time_base;
1112                                         gc_info [gen].count++;
1113                                 } else if (ev == MONO_GC_EVENT_END) {
1114                                         tdiff = time_base - gc_info [gen].start_time;
1115                                         gc_info [gen].total_time += tdiff;
1116                                         if (tdiff > gc_info [gen].max_time)
1117                                                 gc_info [gen].max_time = tdiff;
1118                                 }
1119                         } else if (subtype == TYPE_GC_MOVE) {
1120                                 int j, num = decode_uleb128 (p, &p);
1121                                 gc_object_moves += num / 2;
1122                                 for (j = 0; j < num; j += 2) {
1123                                         intptr_t obj1diff = decode_sleb128 (p, &p);
1124                                         intptr_t obj2diff = decode_sleb128 (p, &p);
1125                                         if (num_tracked_objects)
1126                                                 track_move (OBJ_ADDR (obj1diff), OBJ_ADDR (obj2diff));
1127                                         if (debug) {
1128                                                 fprintf (outfile, "moved obj %p to %p\n", (void*)OBJ_ADDR (obj1diff), (void*)OBJ_ADDR (obj2diff));
1129                                         }
1130                                 }
1131                         } else if (subtype == TYPE_GC_HANDLE_CREATED) {
1132                                 int htype = decode_uleb128 (p, &p);
1133                                 uint32_t handle = decode_uleb128 (p, &p);
1134                                 intptr_t objdiff = decode_sleb128 (p, &p);
1135                                 if (htype > 3)
1136                                         return 0;
1137                                 handle_info [htype].created++;
1138                                 add_trace_thread (thread, &handle_info [htype].traces, 1);
1139                                 /* FIXME: we don't take into account timing here */
1140                                 if (handle_info [htype].created > handle_info [htype].max_live)
1141                                         handle_info [htype].max_live = handle_info [htype].created;
1142                                 if (num_tracked_objects)
1143                                         track_handle (OBJ_ADDR (objdiff), htype, handle);
1144                                 if (debug)
1145                                         fprintf (outfile, "handle (%s) %u created for object %p\n", get_handle_name (htype), handle, (void*)OBJ_ADDR (objdiff));
1146                         } else if (subtype == TYPE_GC_HANDLE_DESTROYED) {
1147                                 int htype = decode_uleb128 (p, &p);
1148                                 uint32_t handle = decode_uleb128 (p, &p);
1149                                 if (htype > 3)
1150                                         return 0;
1151                                 handle_info [htype].created--;
1152                                 if (debug)
1153                                         fprintf (outfile, "handle (%s) %u destroyed\n", get_handle_name (htype), handle);
1154                         }
1155                         break;
1156                 }
1157                 case TYPE_METADATA: {
1158                         int error = *p & TYPE_LOAD_ERR;
1159                         uint64_t tdiff = decode_uleb128 (p + 1, &p);
1160                         int mtype = *p++;
1161                         intptr_t ptrdiff = decode_sleb128 (p, &p);
1162                         LOG_TIME (time_base, tdiff);
1163                         time_base += tdiff;
1164                         if (mtype == TYPE_CLASS) {
1165                                 intptr_t imptrdiff = decode_sleb128 (p, &p);
1166                                 uint64_t flags = decode_uleb128 (p, &p);
1167                                 if (flags) {
1168                                         fprintf (outfile, "non-zero flags in class\n");
1169                                         return 0;
1170                                 }
1171                                 if (debug)
1172                                         fprintf (outfile, "loaded class %p (%s in %p) at %llu\n", (void*)(ptr_base + ptrdiff), p, (void*)(ptr_base + imptrdiff), time_base);
1173                                 if (!error)
1174                                         add_class (ptr_base + ptrdiff, (char*)p);
1175                                 while (*p) p++;
1176                                 p++;
1177                         } else if (mtype == TYPE_IMAGE) {
1178                                 uint64_t flags = decode_uleb128 (p, &p);
1179                                 if (flags) {
1180                                         fprintf (outfile, "non-zero flags in image\n");
1181                                         return 0;
1182                                 }
1183                                 if (debug)
1184                                         fprintf (outfile, "loaded image %p (%s) at %llu\n", (void*)(ptr_base + ptrdiff), p, time_base);
1185                                 if (!error)
1186                                         add_image (ptr_base + ptrdiff, (char*)p);
1187                                 while (*p) p++;
1188                                 p++;
1189                         } else if (mtype == TYPE_THREAD) {
1190                                 ThreadContext *nt;
1191                                 uint64_t flags = decode_uleb128 (p, &p);
1192                                 if (flags) {
1193                                         fprintf (outfile, "non-zero flags in thread\n");
1194                                         return 0;
1195                                 }
1196                                 nt = get_thread (ctx, ptr_base * ptrdiff);
1197                                 nt->name = pstrdup ((char*)p);
1198                                 if (debug)
1199                                         fprintf (outfile, "thread %p named: %s\n", (void*)(ptr_base + ptrdiff), p);
1200                                 while (*p) p++;
1201                                 p++;
1202                         }
1203                         break;
1204                 }
1205                 case TYPE_ALLOC: {
1206                         int has_bt = *p & TYPE_ALLOC_BT;
1207                         uint64_t tdiff = decode_uleb128 (p + 1, &p);
1208                         intptr_t ptrdiff = decode_sleb128 (p, &p);
1209                         intptr_t objdiff = decode_sleb128 (p, &p);
1210                         uint64_t len;
1211                         int num_bt = 0;
1212                         MethodDesc* sframes [8];
1213                         MethodDesc** frames = sframes;
1214                         ClassDesc *cd = lookup_class (ptr_base + ptrdiff);
1215                         len = decode_uleb128 (p, &p);
1216                         LOG_TIME (time_base, tdiff);
1217                         time_base += tdiff;
1218                         if (debug)
1219                                 fprintf (outfile, "alloced object %p, size %llu (%s) at %llu\n", (void*)OBJ_ADDR (objdiff), len, lookup_class (ptr_base + ptrdiff)->name, time_base);
1220                         if (has_bt) {
1221                                 num_bt = 8;
1222                                 frames = decode_bt (sframes, &num_bt, p, &p, ptr_base);
1223                                 if (!frames) {
1224                                         fprintf (outfile, "Cannot load backtrace\n");
1225                                         return 0;
1226                                 }
1227                         }
1228                         if ((thread_filter && thread_filter == thread->thread_id) || (time_base >= time_from && time_base < time_to)) {
1229                                 BackTrace *bt;
1230                                 cd->allocs++;
1231                                 cd->alloc_size += len;
1232                                 if (has_bt)
1233                                         bt = add_trace_methods (frames, num_bt, &cd->traces, len);
1234                                 else
1235                                         bt = add_trace_thread (thread, &cd->traces, len);
1236                                 if (find_size && len >= find_size) {
1237                                         if (!find_name || strstr (cd->name, find_name))
1238                                                 found_object (OBJ_ADDR (objdiff));
1239                                 } else if (!find_size && find_name && strstr (cd->name, find_name)) {
1240                                         found_object (OBJ_ADDR (objdiff));
1241                                 }
1242                                 if (num_tracked_objects)
1243                                         tracked_creation (OBJ_ADDR (objdiff), cd, len, bt, time_base);
1244                         }
1245                         if (frames != sframes)
1246                                 free (frames);
1247                         break;
1248                 }
1249                 case TYPE_METHOD: {
1250                         int subtype = *p & 0xf0;
1251                         uint64_t tdiff = decode_uleb128 (p + 1, &p);
1252                         int64_t ptrdiff = decode_sleb128 (p, &p);
1253                         LOG_TIME (time_base, tdiff);
1254                         time_base += tdiff;
1255                         method_base += ptrdiff;
1256                         if (subtype == TYPE_JIT) {
1257                                 intptr_t codediff = decode_sleb128 (p, &p);
1258                                 int codelen = decode_uleb128 (p, &p);
1259                                 if (debug)
1260                                         fprintf (outfile, "jitted method %p (%s), size: %d\n", (void*)(method_base), p, codelen);
1261                                 add_method (method_base, (char*)p, ptr_base + codediff, codelen);
1262                                 while (*p) p++;
1263                                 p++;
1264                         } else {
1265                                 MethodDesc *method;
1266                                 if ((thread_filter && thread_filter != thread->thread_id))
1267                                         break;
1268                                 method = lookup_method (method_base);
1269                                 if (subtype == TYPE_ENTER) {
1270                                         add_trace_thread (thread, &method->traces, 1);
1271                                         push_method (thread, method, time_base);
1272                                 } else {
1273                                         pop_method (thread, method, time_base);
1274                                 }
1275                                 if (debug)
1276                                         fprintf (outfile, "%s method %s\n", subtype == TYPE_ENTER? "enter": subtype == TYPE_EXC_LEAVE? "exleave": "leave", method->name);
1277                         }
1278                         break;
1279                 }
1280                 case TYPE_HEAP: {
1281                         int subtype = *p & 0xf0;
1282                         if (subtype == TYPE_HEAP_OBJECT) {
1283                                 HeapObjectDesc *ho;
1284                                 int i;
1285                                 intptr_t objdiff = decode_sleb128 (p + 1, &p);
1286                                 intptr_t ptrdiff = decode_sleb128 (p, &p);
1287                                 uint64_t size = decode_uleb128 (p, &p);
1288                                 uintptr_t num = decode_uleb128 (p, &p);
1289                                 uintptr_t ref_offset;
1290                                 ClassDesc *cd = lookup_class (ptr_base + ptrdiff);
1291                                 if (size) {
1292                                         HeapClassDesc *hcd = add_heap_shot_class (thread->current_heap_shot, cd, size);
1293                                         if (collect_traces) {
1294                                                 ho = alloc_heap_obj (OBJ_ADDR (objdiff), hcd, num);
1295                                                 add_heap_shot_obj (thread->current_heap_shot, ho);
1296                                                 ref_offset = 0;
1297                                         }
1298                                 } else {
1299                                         if (collect_traces)
1300                                                 ho = heap_shot_obj_add_refs (thread->current_heap_shot, OBJ_ADDR (objdiff), num, &ref_offset);
1301                                 }
1302                                 for (i = 0; i < num; ++i) {
1303                                         /* FIXME: use object distance to measure how good
1304                                          * the GC is at keeping related objects close
1305                                          */
1306                                         intptr_t obj1diff = decode_sleb128 (p, &p);
1307                                         if (collect_traces)
1308                                                 ho->refs [ref_offset + i] = OBJ_ADDR (obj1diff);
1309                                         if (num_tracked_objects)
1310                                                 track_obj_reference (OBJ_ADDR (obj1diff), OBJ_ADDR (objdiff), cd);
1311                                 }
1312                                 if (debug && size)
1313                                         fprintf (outfile, "traced object %p, size %llu (%s), refs: %d\n", (void*)OBJ_ADDR (objdiff), size, cd->name, num);
1314                         } else if (subtype == TYPE_HEAP_END) {
1315                                 uint64_t tdiff = decode_uleb128 (p + 1, &p);
1316                                 LOG_TIME (time_base, tdiff);
1317                                 time_base += tdiff;
1318                                 if (debug)
1319                                         fprintf (outfile, "heap shot end\n");
1320                                 if (collect_traces) {
1321                                         heap_shot_resolve_reverse_refs (thread->current_heap_shot);
1322                                         heap_shot_free_objects (thread->current_heap_shot);
1323                                 }
1324                                 thread->current_heap_shot = NULL;
1325                         } else if (subtype == TYPE_HEAP_START) {
1326                                 uint64_t tdiff = decode_uleb128 (p + 1, &p);
1327                                 LOG_TIME (time_base, tdiff);
1328                                 time_base += tdiff;
1329                                 if (debug)
1330                                         fprintf (outfile, "heap shot start\n");
1331                                 thread->current_heap_shot = new_heap_shot (time_base);
1332                         }
1333                         break;
1334                 }
1335                 case TYPE_MONITOR: {
1336                         int event = (*p >> 4) & 0x3;
1337                         int has_bt = *p & TYPE_MONITOR_BT;
1338                         uint64_t tdiff = decode_uleb128 (p + 1, &p);
1339                         intptr_t objdiff = decode_sleb128 (p, &p);
1340                         MethodDesc* sframes [8];
1341                         MethodDesc** frames = sframes;
1342                         int record;
1343                         int num_bt = 0;
1344                         LOG_TIME (time_base, tdiff);
1345                         time_base += tdiff;
1346                         record = (!thread_filter || thread_filter == thread->thread_id);
1347                         if (event == MONO_PROFILER_MONITOR_CONTENTION) {
1348                                 MonitorDesc *mdesc = lookup_monitor (OBJ_ADDR (objdiff));
1349                                 if (record) {
1350                                         monitor_contention++;
1351                                         mdesc->contentions++;
1352                                         thread->monitor = mdesc;
1353                                         thread->contention_start = time_base;
1354                                 }
1355                                 if (has_bt) {
1356                                         num_bt = 8;
1357                                         frames = decode_bt (sframes, &num_bt, p, &p, ptr_base);
1358                                         if (!frames) {
1359                                                 fprintf (outfile, "Cannot load backtrace\n");
1360                                                 return 0;
1361                                         }
1362                                         if (record)
1363                                                 add_trace_methods (frames, num_bt, &mdesc->traces, 1);
1364                                 } else {
1365                                         if (record)
1366                                                 add_trace_thread (thread, &mdesc->traces, 1);
1367                                 }
1368                         } else if (event == MONO_PROFILER_MONITOR_FAIL) {
1369                                 if (record) {
1370                                         monitor_failed++;
1371                                         if (thread->monitor && thread->contention_start) {
1372                                                 uint64_t wait_time = time_base - thread->contention_start;
1373                                                 if (wait_time > thread->monitor->max_wait_time)
1374                                                         thread->monitor->max_wait_time = wait_time;
1375                                                 thread->monitor->wait_time += wait_time;
1376                                                 thread->monitor = NULL;
1377                                                 thread->contention_start = 0;
1378                                         }
1379                                 }
1380                         } else if (event == MONO_PROFILER_MONITOR_DONE) {
1381                                 if (record) {
1382                                         monitor_acquired++;
1383                                         if (thread->monitor && thread->contention_start) {
1384                                                 uint64_t wait_time = time_base - thread->contention_start;
1385                                                 if (wait_time > thread->monitor->max_wait_time)
1386                                                         thread->monitor->max_wait_time = wait_time;
1387                                                 thread->monitor->wait_time += wait_time;
1388                                                 thread->monitor = NULL;
1389                                                 thread->contention_start = 0;
1390                                         }
1391                                 }
1392                         }
1393                         if (debug)
1394                                 fprintf (outfile, "monitor %s for object %p\n", monitor_ev_name (event), (void*)OBJ_ADDR (objdiff));
1395                         if (frames != sframes)
1396                                 free (frames);
1397                         break;
1398                 }
1399                 case TYPE_EXCEPTION: {
1400                         int subtype = *p & 0x70;
1401                         int has_bt = *p & TYPE_EXCEPTION_BT;
1402                         uint64_t tdiff = decode_uleb128 (p + 1, &p);
1403                         MethodDesc* sframes [8];
1404                         MethodDesc** frames = sframes;
1405                         int record;
1406                         LOG_TIME (time_base, tdiff);
1407                         time_base += tdiff;
1408                         record = (!thread_filter || thread_filter == thread->thread_id);
1409                         if (subtype == TYPE_CLAUSE) {
1410                                 int clause_type = decode_uleb128 (p, &p);
1411                                 int clause_num = decode_uleb128 (p, &p);
1412                                 int64_t ptrdiff = decode_sleb128 (p, &p);
1413                                 method_base += ptrdiff;
1414                                 if (record)
1415                                         clause_summary [clause_type]++;
1416                                 if (debug)
1417                                         fprintf (outfile, "clause %s (%d) in method %s\n", clause_name (clause_type), clause_num, lookup_method (method_base)->name);
1418                         } else {
1419                                 intptr_t objdiff = decode_sleb128 (p, &p);
1420                                 if (record)
1421                                         throw_count++;
1422                                 if (has_bt) {
1423                                         has_bt = 8;
1424                                         frames = decode_bt (sframes, &has_bt, p, &p, ptr_base);
1425                                         if (!frames) {
1426                                                 fprintf (outfile, "Cannot load backtrace\n");
1427                                                 return 0;
1428                                         }
1429                                         if (record)
1430                                                 add_trace_methods (frames, has_bt, &exc_traces, 1);
1431                                 } else {
1432                                         if (record)
1433                                                 add_trace_thread (thread, &exc_traces, 1);
1434                                 }
1435                                 if (frames != sframes)
1436                                         free (frames);
1437                                 if (debug)
1438                                         fprintf (outfile, "throw %p\n", (void*)OBJ_ADDR (objdiff));
1439                         }
1440                         break;
1441                 }
1442                 default:
1443                         fprintf (outfile, "unhandled profiler event: 0x%x at file offset: %llu + %d (len: %d\n)\n", *p, file_offset, p - ctx->buf, len);
1444                         exit (1);
1445                 }
1446         }
1447         thread->last_time = time_base;
1448         for (i = 0; i < thread->stack_id; ++i)
1449                 thread->stack [i]->recurse_count = 0;
1450         return 1;
1451 }
1452
1453 static ProfContext*
1454 load_file (char *name)
1455 {
1456         unsigned char *p;
1457         ProfContext *ctx = calloc (sizeof (ProfContext), 1);
1458         if (strcmp (name, "-") == 0)
1459                 ctx->file = stdin;
1460         else
1461                 ctx->file = fopen (name, "rb");
1462         if (!ctx->file) {
1463                 printf ("Cannot open file: %s\n", name);
1464                 exit (1);
1465         }
1466 #if defined (HAVE_SYS_ZLIB)
1467         ctx->gzfile = gzdopen (fileno (ctx->file), "rb");
1468 #endif
1469         if (!load_data (ctx, 32))
1470                 return NULL;
1471         p = ctx->buf;
1472         if (read_int32 (p) != LOG_HEADER_ID || p [6] != LOG_DATA_VERSION)
1473                 return NULL;
1474         ctx->version_major = p [4];
1475         ctx->version_minor = p [5];
1476         ctx->data_version = p [6];
1477         /* reading 64 bit files on 32 bit systems not supported yet */
1478         if (p [7] > sizeof (void*))
1479                 return NULL;
1480         if (read_int32 (p + 20)) /* flags must be 0 */
1481                 return NULL;
1482         ctx->startup_time = read_int64 (p + 8);
1483         ctx->timer_overhead = read_int32 (p + 16);
1484         ctx->pid = read_int32 (p + 24);
1485         return ctx;
1486 }
1487
1488 enum {
1489         ALLOC_SORT_BYTES,
1490         ALLOC_SORT_COUNT
1491 };
1492 static int alloc_sort_mode = ALLOC_SORT_BYTES;
1493
1494 static int
1495 compare_class (const void *a, const void *b)
1496 {
1497         ClassDesc *const*A = a;
1498         ClassDesc *const*B = b;
1499         uint64_t vala, valb;
1500         if (alloc_sort_mode == ALLOC_SORT_BYTES) {
1501                 vala = (*A)->alloc_size;
1502                 valb = (*B)->alloc_size;
1503         } else {
1504                 vala = (*A)->allocs;
1505                 valb = (*B)->allocs;
1506         }
1507         if (valb == vala)
1508                 return 0;
1509         if (valb < vala)
1510                 return -1;
1511         return 1;
1512 }
1513
1514 static void
1515 dump_header (ProfContext *ctx)
1516 {
1517         time_t st = ctx->startup_time / 1000;
1518         char *t = ctime (&st);
1519         fprintf (outfile, "\nMono log profiler data\n");
1520         fprintf (outfile, "\tProfiler version: %d.%d\n", ctx->version_major, ctx->version_minor);
1521         fprintf (outfile, "\tData version: %d\n", ctx->data_version);
1522         fprintf (outfile, "\tMean timer overhead: %d nanoseconds\n", ctx->timer_overhead);
1523         fprintf (outfile, "\tProgram startup: %s", t);
1524         if (ctx->pid)
1525                 fprintf (outfile, "\tProgram ID: %d\n", ctx->pid);
1526 }
1527
1528 static void
1529 dump_traces (TraceDesc *traces, const char *desc)
1530 {
1531         int j;
1532         if (!show_traces)
1533                 return;
1534         if (!traces->count)
1535                 return;
1536         sort_context_array (traces);
1537         for (j = 0; j < traces->count; ++j) {
1538                 int k;
1539                 BackTrace *bt;
1540                 bt = traces->traces [j].bt;
1541                 if (!bt->count)
1542                         continue;
1543                 fprintf (outfile, "\t%llu %s from:\n", traces->traces [j].count, desc);
1544                 for (k = 0; k < bt->count; ++k)
1545                         fprintf (outfile, "\t\t%s\n", bt->methods [k]->name);
1546         }
1547 }
1548
1549 static void
1550 dump_threads (ProfContext *ctx)
1551 {
1552         ThreadContext *thread;
1553         fprintf (outfile, "\nThread summary\n");
1554         for (thread = ctx->threads; thread; thread = thread->next) {
1555                 fprintf (outfile, "\tThread: %p, name: \"%s\"\n", (void*)thread->thread_id, thread->name? thread->name: "");
1556         }
1557 }
1558
1559 static void
1560 dump_exceptions (void)
1561 {
1562         int i;
1563         fprintf (outfile, "\nException summary\n");
1564         fprintf (outfile, "\tThrows: %llu\n", throw_count);
1565         dump_traces (&exc_traces, "throws");
1566         for (i = 0; i <= MONO_EXCEPTION_CLAUSE_FAULT; ++i) {
1567                 if (!clause_summary [i])
1568                         continue;
1569                 fprintf (outfile, "\tExecuted %s clauses: %llu\n", clause_name (i), clause_summary [i]);
1570         }
1571 }
1572
1573 static int
1574 compare_monitor (const void *a, const void *b)
1575 {
1576         MonitorDesc *const*A = a;
1577         MonitorDesc *const*B = b;
1578         if ((*B)->wait_time == (*A)->wait_time)
1579                 return 0;
1580         if ((*B)->wait_time < (*A)->wait_time)
1581                 return -1;
1582         return 1;
1583 }
1584
1585 static void
1586 dump_monitors (void)
1587 {
1588         MonitorDesc **monitors;
1589         int i, j;
1590         if (!num_monitors)
1591                 return;
1592         monitors = malloc (sizeof (void*) * num_monitors);
1593         for (i = 0, j = 0; i < SMALL_HASH_SIZE; ++i) {
1594                 MonitorDesc *mdesc = monitor_hash [i];
1595                 while (mdesc) {
1596                         monitors [j++] = mdesc;
1597                         mdesc = mdesc->next;
1598                 }
1599         }
1600         qsort (monitors, num_monitors, sizeof (void*), compare_monitor);
1601         fprintf (outfile, "\nMonitor lock summary\n");
1602         for (i = 0; i < num_monitors; ++i) {
1603                 MonitorDesc *mdesc = monitors [i];
1604                 fprintf (outfile, "\tLock object %p: %d contentions\n", (void*)mdesc->objid, (int)mdesc->contentions);
1605                 fprintf (outfile, "\t\t%.6f secs total wait time, %.6f max, %.6f average\n",
1606                         mdesc->wait_time/1000000000.0, mdesc->max_wait_time/1000000000.0, mdesc->wait_time/1000000000.0/mdesc->contentions);
1607                 dump_traces (&mdesc->traces, "contentions");
1608         }
1609         fprintf (outfile, "\tLock contentions: %llu\n", monitor_contention);
1610         fprintf (outfile, "\tLock acquired: %llu\n", monitor_acquired);
1611         fprintf (outfile, "\tLock failures: %llu\n", monitor_failed);
1612 }
1613
1614 static void
1615 dump_gcs (void)
1616 {
1617         int i;
1618         fprintf (outfile, "\nGC summary\n");
1619         fprintf (outfile, "\tGC resizes: %d\n", gc_resizes);
1620         fprintf (outfile, "\tMax heap size: %llu\n", max_heap_size);
1621         fprintf (outfile, "\tObject moves: %llu\n", gc_object_moves);
1622         for (i = 0; i < 3; ++i) {
1623                 if (!gc_info [i].count)
1624                         continue;
1625                 fprintf (outfile, "\tGen%d collections: %d, max time: %lluus, total time: %lluus, average: %lluus\n",
1626                         i, gc_info [i].count, gc_info [i].max_time / 1000, gc_info [i].total_time / 1000,
1627                         gc_info [i].total_time / gc_info [i].count / 1000);
1628         }
1629         for (i = 0; i < 3; ++i) {
1630                 if (!handle_info [i].max_live)
1631                         continue;
1632                 fprintf (outfile, "\tGC handles %s: created: %llu, destroyed: %llu, max: %llu\n",
1633                         get_handle_name (i), handle_info [i].created, handle_info [i].destroyed, handle_info [i].max_live);
1634                 dump_traces (&handle_info [i].traces, "created");
1635         }
1636 }
1637
1638 static void
1639 dump_allocations (void)
1640 {
1641         int i, c;
1642         intptr_t allocs = 0;
1643         uint64_t size = 0;
1644         int header_done = 0;
1645         ClassDesc **classes = malloc (num_classes * sizeof (void*));
1646         ClassDesc *cd;
1647         c = 0;
1648         for (i = 0; i < HASH_SIZE; ++i) {
1649                 cd = class_hash [i];
1650                 while (cd) {
1651                         classes [c++] = cd;
1652                         cd = cd->next;
1653                 }
1654         }
1655         qsort (classes, num_classes, sizeof (void*), compare_class);
1656         for (i = 0; i < num_classes; ++i) {
1657                 cd = classes [i];
1658                 if (!cd->allocs)
1659                         continue;
1660                 allocs += cd->allocs;
1661                 size += cd->alloc_size;
1662                 if (!header_done++) {
1663                         fprintf (outfile, "\nAllocation summary\n");
1664                         fprintf (outfile, "%10s %10s %8s Type name\n", "Bytes", "Count", "Average");
1665                 }
1666                 fprintf (outfile, "%10llu %10d %8llu %s\n", cd->alloc_size, cd->allocs, cd->alloc_size / cd->allocs, cd->name);
1667                 dump_traces (&cd->traces, "bytes");
1668         }
1669         if (allocs)
1670                 fprintf (outfile, "Total memory allocated: %llu bytes in %d objects\n", size, allocs);
1671 }
1672
1673 enum {
1674         METHOD_SORT_TOTAL,
1675         METHOD_SORT_SELF,
1676         METHOD_SORT_CALLS
1677 };
1678
1679 static int method_sort_mode = METHOD_SORT_TOTAL;
1680
1681 static int
1682 compare_method (const void *a, const void *b)
1683 {
1684         MethodDesc *const*A = a;
1685         MethodDesc *const*B = b;
1686         uint64_t vala, valb;
1687         if (method_sort_mode == METHOD_SORT_SELF) {
1688                 vala = (*A)->self_time;
1689                 valb = (*B)->self_time;
1690         } else if (method_sort_mode == METHOD_SORT_CALLS) {
1691                 vala = (*A)->calls;
1692                 valb = (*B)->calls;
1693         } else {
1694                 vala = (*A)->total_time;
1695                 valb = (*B)->total_time;
1696         }
1697         if (vala == valb)
1698                 return 0;
1699         if (valb < vala)
1700                 return -1;
1701         return 1;
1702 }
1703
1704 static void
1705 dump_metadata (void)
1706 {
1707         fprintf (outfile, "\nMetadata summary\n");
1708         fprintf (outfile, "\tLoaded images: %d\n", num_images);
1709         if (verbose) {
1710                 ImageDesc *image;
1711                 int i;
1712                 for (i = 0; i < SMALL_HASH_SIZE; ++i) {
1713                         image = image_hash [i];
1714                         while (image) {
1715                                 fprintf (outfile, "\t\t%s\n", image->filename);
1716                                 image = image->next;
1717                         }
1718                 }
1719         }
1720
1721 }
1722
1723 static void
1724 dump_methods (void)
1725 {
1726         int i, c;
1727         uint64_t calls = 0;
1728         int header_done = 0;
1729         MethodDesc **methods = malloc (num_methods * sizeof (void*));
1730         MethodDesc *cd;
1731         c = 0;
1732         for (i = 0; i < HASH_SIZE; ++i) {
1733                 cd = method_hash [i];
1734                 while (cd) {
1735                         cd->total_time = cd->self_time + cd->callee_time;
1736                         methods [c++] = cd;
1737                         cd = cd->next;
1738                 }
1739         }
1740         qsort (methods, num_methods, sizeof (void*), compare_method);
1741         for (i = 0; i < num_methods; ++i) {
1742                 uint64_t msecs;
1743                 uint64_t smsecs;
1744                 cd = methods [i];
1745                 if (!cd->calls)
1746                         continue;
1747                 calls += cd->calls;
1748                 msecs = cd->total_time / 1000000;
1749                 smsecs = (cd->total_time - cd->callee_time) / 1000000;
1750                 if (!msecs && !verbose)
1751                         continue;
1752                 if (!header_done++) {
1753                         fprintf (outfile, "\nMethod call summary\n");
1754                         fprintf (outfile, "%8s %8s %10s Method name\n", "Total(ms)", "Self(ms)", "Calls");
1755                 }
1756                 fprintf (outfile, "%8llu %8llu %10llu %s\n", msecs, smsecs, cd->calls, cd->name);
1757                 dump_traces (&cd->traces, "calls");
1758         }
1759         if (calls)
1760                 fprintf (outfile, "Total calls: %llu\n", calls);
1761 }
1762
1763 static int
1764 compare_heap_class (const void *a, const void *b)
1765 {
1766         HeapClassDesc *const*A = a;
1767         HeapClassDesc *const*B = b;
1768         uint64_t vala, valb;
1769         if (alloc_sort_mode == ALLOC_SORT_BYTES) {
1770                 vala = (*A)->total_size;
1771                 valb = (*B)->total_size;
1772         } else {
1773                 vala = (*A)->count;
1774                 valb = (*B)->count;
1775         }
1776         if (valb == vala)
1777                 return 0;
1778         if (valb < vala)
1779                 return -1;
1780         return 1;
1781 }
1782
1783 static int
1784 compare_rev_class (const void *a, const void *b)
1785 {
1786         const HeapClassRevRef *A = a;
1787         const HeapClassRevRef *B = b;
1788         if (B->count == A->count)
1789                 return 0;
1790         if (B->count < A->count)
1791                 return -1;
1792         return 1;
1793 }
1794
1795 static void
1796 dump_rev_claases (HeapClassRevRef *revs, int count)
1797 {
1798         int j;
1799         if (!show_traces)
1800                 return;
1801         if (!count)
1802                 return;
1803         for (j = 0; j < count; ++j) {
1804                 HeapClassDesc *cd = revs [j].klass;
1805                 fprintf (outfile, "\t\t%llu references from: %s\n", revs [j].count, cd->klass->name);
1806         }
1807 }
1808
1809 static void
1810 heap_shot_summary (HeapShot *hs, int hs_num, HeapShot *last_hs)
1811 {
1812         uint64_t size = 0;
1813         uint64_t count = 0;
1814         int ccount = 0;
1815         int i;
1816         HeapClassDesc *cd;
1817         HeapClassDesc **sorted;
1818         sorted = malloc (sizeof (void*) * hs->class_count);
1819         for (i = 0; i < hs->hash_size; ++i) {
1820                 cd = hs->class_hash [i];
1821                 if (!cd)
1822                         continue;
1823                 count += cd->count;
1824                 size += cd->total_size;
1825                 sorted [ccount++] = cd;
1826         }
1827         hs->sorted = sorted;
1828         qsort (sorted, ccount, sizeof (void*), compare_heap_class);
1829         fprintf (outfile, "\n\tHeap shot %d at %.3f secs: size: %llu, object count: %llu, class count: %d\n",
1830                 hs_num, (hs->timestamp - startup_time)/1000000000.0, size, count, ccount);
1831         if (!verbose && ccount > 30)
1832                 ccount = 30;
1833         fprintf (outfile, "\t%10s %10s %8s Class name\n", "Bytes", "Count", "Average");
1834         for (i = 0; i < ccount; ++i) {
1835                 HeapClassRevRef *rev_sorted;
1836                 int j, k;
1837                 HeapClassDesc *ocd = NULL;
1838                 cd = sorted [i];
1839                 if (last_hs)
1840                         ocd = heap_class_lookup (last_hs, cd->klass);
1841                 fprintf (outfile, "\t%10llu %10llu %8llu %s", cd->total_size, cd->count, cd->total_size / cd->count, cd->klass->name);
1842                 if (ocd) {
1843                         int64_t bdiff = cd->total_size - ocd->total_size;
1844                         int64_t cdiff = cd->count - ocd->count;
1845                         fprintf (outfile, " (bytes: %+lld, count: %+lld)\n", bdiff, cdiff);
1846                 } else {
1847                         fprintf (outfile, "\n");
1848                 }
1849                 if (!collect_traces)
1850                         continue;
1851                 rev_sorted = malloc (cd->rev_count * sizeof (HeapClassRevRef));
1852                 k = 0;
1853                 for (j = 0; j < cd->rev_hash_size; ++j) {
1854                         if (cd->rev_hash [j].klass)
1855                                 rev_sorted [k++] = cd->rev_hash [j];
1856                 }
1857                 assert (cd->rev_count == k);
1858                 qsort (rev_sorted, cd->rev_count, sizeof (HeapClassRevRef), compare_rev_class);
1859                 dump_rev_claases (rev_sorted, cd->rev_count);
1860                 free (rev_sorted);
1861         }
1862         free (sorted);
1863 }
1864
1865 static int
1866 compare_heap_shots (const void *a, const void *b)
1867 {
1868         HeapShot *const*A = a;
1869         HeapShot *const*B = b;
1870         if ((*B)->timestamp == (*A)->timestamp)
1871                 return 0;
1872         if ((*B)->timestamp > (*A)->timestamp)
1873                 return -1;
1874         return 1;
1875 }
1876
1877 static void
1878 dump_heap_shots (void)
1879 {
1880         HeapShot **hs_sorted;
1881         HeapShot *hs;
1882         HeapShot *last_hs = NULL;
1883         int i;
1884         if (!heap_shots)
1885                 return;
1886         hs_sorted = malloc (num_heap_shots * sizeof (void*));
1887         fprintf (outfile, "\nHeap shot summary\n");
1888         i = 0;
1889         for (hs = heap_shots; hs; hs = hs->next)
1890                 hs_sorted [i++] = hs;
1891         qsort (hs_sorted, num_heap_shots, sizeof (void*), compare_heap_shots);
1892         for (i = 0; i < num_heap_shots; ++i) {
1893                 hs = hs_sorted [i];
1894                 heap_shot_summary (hs, i, last_hs);
1895                 last_hs = hs;
1896         }
1897 }
1898
1899 static void
1900 flush_context (ProfContext *ctx)
1901 {
1902         ThreadContext *thread;
1903         /* FIXME: sometimes there are leftovers: indagate */
1904         for (thread = ctx->threads; thread; thread = thread->next) {
1905                 while (thread->stack_id) {
1906                         if (debug)
1907                                 fprintf (outfile, "thread %p has %d items on stack\n", (void*)thread->thread_id, thread->stack_id);
1908                         pop_method (thread, thread->stack [thread->stack_id - 1], thread->last_time);
1909                 }
1910         }
1911 }
1912
1913 static const char *reports = "header,gc,alloc,call,metadata,exception,monitor,thread,heapshot";
1914
1915 static const char*
1916 match_option (const char *p, const char *opt)
1917 {
1918         int len = strlen (opt);
1919         if (strncmp (p, opt, len) == 0) {
1920                 if (p [len] == ',')
1921                         len++;
1922                 return p + len;
1923         }
1924         return p;
1925 }
1926
1927 static int
1928 print_reports (ProfContext *ctx, const char *reps, int parse_only)
1929 {
1930         const char *opt;
1931         const char *p;
1932         for (p = reps; *p; p = opt) {
1933                 if ((opt = match_option (p, "header")) != p) {
1934                         if (!parse_only)
1935                                 dump_header (ctx);
1936                         continue;
1937                 }
1938                 if ((opt = match_option (p, "thread")) != p) {
1939                         if (!parse_only)
1940                                 dump_threads (ctx);
1941                         continue;
1942                 }
1943                 if ((opt = match_option (p, "gc")) != p) {
1944                         if (!parse_only)
1945                                 dump_gcs ();
1946                         continue;
1947                 }
1948                 if ((opt = match_option (p, "alloc")) != p) {
1949                         if (!parse_only)
1950                                 dump_allocations ();
1951                         continue;
1952                 }
1953                 if ((opt = match_option (p, "call")) != p) {
1954                         if (!parse_only)
1955                                 dump_methods ();
1956                         continue;
1957                 }
1958                 if ((opt = match_option (p, "metadata")) != p) {
1959                         if (!parse_only)
1960                                 dump_metadata ();
1961                         continue;
1962                 }
1963                 if ((opt = match_option (p, "exception")) != p) {
1964                         if (!parse_only)
1965                                 dump_exceptions ();
1966                         continue;
1967                 }
1968                 if ((opt = match_option (p, "monitor")) != p) {
1969                         if (!parse_only)
1970                                 dump_monitors ();
1971                         continue;
1972                 }
1973                 if ((opt = match_option (p, "heapshot")) != p) {
1974                         if (!parse_only)
1975                                 dump_heap_shots ();
1976                         continue;
1977                 }
1978                 return 0;
1979         }
1980         return 1;
1981 }
1982
1983 static int
1984 add_find_spec (const char *p)
1985 {
1986         if (p [0] == 'S' && p [1] == ':') {
1987                 char *vale;
1988                 find_size = strtoul (p + 2, &vale, 10);
1989                 return 1;
1990         } else if (p [0] == 'T' && p [1] == ':') {
1991                 find_name = p + 2;
1992                 return 1;
1993         }
1994         return 0;
1995 }
1996
1997 static void
1998 usage (void)
1999 {
2000         printf ("Mono log profiler report version %d.%d\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR);
2001         printf ("Usage: mprof-report [OPTIONS] FILENAME\n");
2002         printf ("FILENAME can be '-' to read from standard input.\n");
2003         printf ("Options:\n");
2004         printf ("\t--help               display this help\n");
2005         printf ("\t--out=FILE           write to FILE instead of stdout\n");
2006         printf ("\t--traces             collect and show backtraces\n"); 
2007         printf ("\t--maxframes=NUM      limit backtraces to NUM entries\n");
2008         printf ("\t--reports=R1[,R2...] print the specified reports. Defaults are:\n");
2009         printf ("\t                     %s\n", reports);
2010         printf ("\t--method-sort=MODE   sort methods according to MODE: total, self, calls\n");
2011         printf ("\t--alloc-sort=MODE    sort allocations according to MODE: bytes, count\n");
2012         printf ("\t--track=OB1[,OB2...] track what happens to objects OBJ1, O2 etc.\n");
2013         printf ("\t--find=FINDSPEC      find and track objects matching FINFSPEC, where FINDSPEC is:\n");
2014         printf ("\t                     S:minimum_size or T:partial_name\n");
2015         printf ("\t--thread=THREADID    consider just the data for thread THREADID\n");
2016         printf ("\t--time=FROM-TO       consider data FROM seconds from startup up to TO seconds\n");
2017         printf ("\t--verbose            increase verbosity level\n");
2018         printf ("\t--debug              display decoding debug info for mprof-report devs\n");
2019 }
2020
2021 int
2022 main (int argc, char *argv[])
2023 {
2024         ProfContext *ctx;
2025         int i;
2026         outfile = stdout;
2027         for (i = 1; i < argc; ++i) {
2028                 if (strcmp ("--debug", argv [i]) == 0) {
2029                         debug++;
2030                 } else if (strcmp ("--help", argv [i]) == 0) {
2031                         usage ();
2032                         return 0;
2033                 } else if (strncmp ("--alloc-sort=", argv [i], 13) == 0) {
2034                         const char *val = argv [i] + 13;
2035                         if (strcmp (val, "bytes") == 0) {
2036                                 alloc_sort_mode = ALLOC_SORT_BYTES;
2037                         } else if (strcmp (val, "count") == 0) {
2038                                 alloc_sort_mode = ALLOC_SORT_COUNT;
2039                         } else {
2040                                 usage ();
2041                                 return 1;
2042                         }
2043                 } else if (strncmp ("--method-sort=", argv [i], 14) == 0) {
2044                         const char *val = argv [i] + 14;
2045                         if (strcmp (val, "total") == 0) {
2046                                 method_sort_mode = METHOD_SORT_TOTAL;
2047                         } else if (strcmp (val, "self") == 0) {
2048                                 method_sort_mode = METHOD_SORT_SELF;
2049                         } else if (strcmp (val, "calls") == 0) {
2050                                 method_sort_mode = METHOD_SORT_CALLS;
2051                         } else {
2052                                 usage ();
2053                                 return 1;
2054                         }
2055                 } else if (strncmp ("--reports=", argv [i], 10) == 0) {
2056                         const char *val = argv [i] + 10;
2057                         if (!print_reports (NULL, val, 1)) {
2058                                 usage ();
2059                                 return 1;
2060                         }
2061                         reports = val;
2062                 } else if (strncmp ("--out=", argv [i], 6) == 0) {
2063                         const char *val = argv [i] + 6;
2064                         outfile = fopen (val, "w");
2065                         if (!outfile) {
2066                                 printf ("Cannot open output file: %s\n", val);
2067                                 return 1;
2068                         }
2069                 } else if (strncmp ("--maxframes=", argv [i], 12) == 0) {
2070                         const char *val = argv [i] + 12;
2071                         char *vale;
2072                         trace_max = strtoul (val, &vale, 10);
2073                 } else if (strncmp ("--find=", argv [i], 7) == 0) {
2074                         const char *val = argv [i] + 7;
2075                         if (!add_find_spec (val)) {
2076                                 usage ();
2077                                 return 1;
2078                         }
2079                 } else if (strncmp ("--track=", argv [i], 8) == 0) {
2080                         const char *val = argv [i] + 8;
2081                         char *vale;
2082                         while (*val) {
2083                                 uintptr_t tracked_obj;
2084                                 if (*val == ',') {
2085                                         val++;
2086                                         continue;
2087                                 }
2088                                 tracked_obj = strtoul (val, &vale, 0);
2089                                 found_object (tracked_obj);
2090                                 val = vale;
2091                         }
2092                 } else if (strncmp ("--thread=", argv [i], 9) == 0) {
2093                         const char *val = argv [i] + 9;
2094                         char *vale;
2095                         thread_filter = strtoul (val, &vale, 0);
2096                 } else if (strncmp ("--time=", argv [i], 7) == 0) {
2097                         char *val = pstrdup (argv [i] + 7);
2098                         double from_secs, to_secs;
2099                         char *top = strchr (val, '-');
2100                         if (!top) {
2101                                 usage ();
2102                                 return 1;
2103                         }
2104                         *top++ = 0;
2105                         from_secs = atof (val);
2106                         to_secs = atof (top);
2107                         free (val);
2108                         if (from_secs > to_secs) {
2109                                 usage ();
2110                                 return 1;
2111                         }
2112                         time_from = from_secs * 1000000000;
2113                         time_to = to_secs * 1000000000;
2114                 } else if (strcmp ("--verbose", argv [i]) == 0) {
2115                         verbose++;
2116                 } else if (strcmp ("--traces", argv [i]) == 0) {
2117                         show_traces = 1;
2118                         collect_traces = 1;
2119                 } else {
2120                         break;
2121                 }
2122         }
2123         if (i >= argc) {
2124                 usage ();
2125                 return 2;
2126         }
2127         ctx = load_file (argv [i]);
2128         if (!ctx) {
2129                 printf ("Not a log profiler data file (or unsupported version).\n");
2130                 return 1;
2131         }
2132         while (decode_buffer (ctx));
2133         flush_context (ctx);
2134         if (num_tracked_objects)
2135                 return 0;
2136         print_reports (ctx, reports, 0);
2137         return 0;
2138 }
2139