* monograph.c: Change default assembly name to mscorlib.dll
[mono.git] / mono / monograph / monograph.c
1 #include <glib.h>
2 #include <string.h>
3 #include "mono/metadata/class.h"
4 #include "mono/metadata/assembly.h"
5 #include "mono/metadata/tokentype.h"
6 #include "mono/metadata/opcodes.h"
7 #include "mono/metadata/tabledefs.h"
8 #include "mono/metadata/mono-endian.h"
9 #include "mono/metadata/appdomain.h" /* mono_init */
10 #include "mono/metadata/debug-helpers.h"
11
12 static FILE *output;
13 static int include_namespace = 0;
14 static int max_depth = 6;
15 static int verbose = 0;
16 static const char *graph_properties = "\tnode [fontsize=8.0]\n\tedge [len=2,color=red]\n";
17
18 static void
19 output_type_edge (MonoClass *first, MonoClass *second) {
20         if (include_namespace)
21                 fprintf (output, "\t\"%s.%s\" -> \"%s.%s\"\n", first->name_space, first->name, second->name_space, second->name);
22         else
23                 fprintf (output, "\t\"%s\" -> \"%s\"\n", first->name, second->name);
24 }
25
26 static void
27 print_subtypes (MonoImage *image, MonoClass *class, int depth) {
28         int i, token;
29         MonoTableInfo *t;
30         MonoClass *child;
31
32         if (depth++ > max_depth)
33                 return;
34
35         t = &image->tables [MONO_TABLE_TYPEDEF];
36         
37         token = mono_metadata_token_index (class->type_token);
38         token <<= TYPEDEFORREF_BITS;
39         token |= TYPEDEFORREF_TYPEDEF;
40
41         /* use a subgraph? */
42         for (i = 0; i < t->rows; ++i) {
43                 if (token == mono_metadata_decode_row_col (t, i, MONO_TYPEDEF_EXTENDS)) {
44                         child = mono_class_get (image, MONO_TOKEN_TYPE_DEF | (i + 1));
45                         output_type_edge (class, child);
46                         print_subtypes (image, child, depth);
47                 }
48         }
49 }
50
51 static void
52 type_graph (MonoImage *image, const char* cname) {
53         MonoClass *class;
54         MonoClass *parent;
55         MonoClass *child;
56         const char *name_space;
57         char *p;
58         int depth = 0;
59
60         cname = g_strdup (cname);
61         p = strrchr (cname, '.');
62         if (p) {
63                 name_space = cname;
64                 *p++ = 0;
65                 cname = p;
66         } else {
67                 name_space = "";
68         }
69         class = mono_class_from_name (image, name_space, cname);
70         if (!class) {
71                 g_print ("class %s.%s not found\n", name_space, cname);
72                 exit (1);
73         }
74         fprintf (output, "digraph blah {\n");
75         fprintf (output, "%s", graph_properties);
76         child = class;
77         /* go back and print the parents for the node as well: not sure it's a good idea */
78         for (parent = class->parent; parent; parent = parent->parent) {
79                 output_type_edge (parent, child);
80                 child = parent;
81         }
82         print_subtypes (image, class, depth);
83         fprintf (output, "}\n");
84 }
85
86 static void
87 interface_graph (MonoImage *image, const char* cname) {
88         MonoClass *class;
89         MonoClass *child;
90         const char *name_space;
91         char *p;
92         guint32 cols [MONO_INTERFACEIMPL_SIZE];
93         guint32 token, i, count = 0;
94         MonoTableInfo *intf = &image->tables [MONO_TABLE_INTERFACEIMPL];
95
96         cname = g_strdup (cname);
97         p = strrchr (cname, '.');
98         if (p) {
99                 name_space = cname;
100                 *p++ = 0;
101                 cname = p;
102         } else {
103                 name_space = "";
104         }
105         class = mono_class_from_name (image, name_space, cname);
106         if (!class) {
107                 g_print ("interface %s.%s not found\n", name_space, cname);
108                 exit (1);
109         }
110         /* chek if it's really an interface... */
111         fprintf (output, "digraph interface {\n");
112         fprintf (output, "%s", graph_properties);
113         /* TODO: handle inetrface defined in one image and class defined in another. */
114         token = mono_metadata_token_index (class->type_token);
115         token <<= TYPEDEFORREF_BITS;
116         token |= TYPEDEFORREF_TYPEDEF;
117         for (i = 0; i < intf->rows; ++i) {
118                 mono_metadata_decode_row (intf, i, cols, MONO_INTERFACEIMPL_SIZE);
119                 /*g_print ("index: %d [%d implements %d]\n", index, cols [MONO_INTERFACEIMPL_CLASS], cols [MONO_INTERFACEIMPL_INTERFACE]);*/
120                 if (token == cols [MONO_INTERFACEIMPL_INTERFACE]) {
121                         child = mono_class_get (image, MONO_TOKEN_TYPE_DEF | cols [MONO_INTERFACEIMPL_CLASS]);
122                         output_type_edge (class, child);
123                         count++;
124                 }
125         }
126         fprintf (output, "}\n");
127         if (verbose && !count)
128                 g_print ("No class implements %s.%s\n", class->name_space, class->name);
129
130 }
131
132 static int back_branch_waste = 0;
133 static int branch_waste = 0;
134 static int var_waste = 0;
135 static int int_waste = 0;
136 static int nop_waste = 0;
137 static int has_exceptions = 0;
138 static int num_exceptions = 0;
139 static int max_exceptions = 0;
140 static int has_locals = 0;
141 static int num_locals = 0;
142 static int max_locals = 0;
143 static int has_args = 0;
144 static int num_args = 0;
145 static int max_args = 0;
146 static int has_maxstack = 0;
147 static int num_maxstack = 0;
148 static int max_maxstack = 0;
149 static int has_code = 0;
150 static int num_code = 0;
151 static int max_code = 0;
152 static int has_branch = 0;
153 static int num_branch = 0;
154 static int max_branch = 0;
155 static int has_condbranch = 0;
156 static int num_condbranch = 0;
157 static int max_condbranch = 0;
158 static int has_calls = 0;
159 static int num_calls = 0;
160 static int max_calls = 0;
161 static int has_throw = 0;
162 static int num_throw = 0;
163 static int max_throw = 0;
164 static int has_switch = 0;
165 static int num_switch = 0;
166 static int max_switch = 0;
167 static int cast_sealed = 0;
168 static int cast_iface = 0;
169 static int total_cast = 0;
170 static int nonvirt_callvirt = 0;
171 static int total_callvirt = 0;
172
173 static void
174 method_stats (MonoMethod *method) {
175         const MonoOpcode *opcode;
176         MonoMethodHeader *header;
177         const unsigned char *ip;
178         int i, n;
179         int local_branch = 0, local_condbranch = 0, local_throw = 0, local_calls = 0;
180         gint64 l;
181
182         if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME))
183                 return;
184         if (method->flags & (METHOD_ATTRIBUTE_PINVOKE_IMPL | METHOD_ATTRIBUTE_ABSTRACT))
185                 return;
186
187         header = ((MonoMethodNormal *)method)->header;
188         if (header->num_clauses)
189                 has_exceptions++;
190         num_exceptions += header->num_clauses;
191         if (max_exceptions < header->num_clauses)
192                 max_exceptions = header->num_clauses;
193         if (header->num_locals)
194                 has_locals++;
195         num_locals += header->num_locals;
196         if (max_locals < header->num_locals)
197                 max_locals = header->num_locals;
198
199         if (max_maxstack < header->max_stack)
200                 max_maxstack = header->max_stack;
201         num_maxstack += header->max_stack;
202         if (header->max_stack != 8) /* just a guess */
203                 has_maxstack++;
204
205         n = method->signature->hasthis + method->signature->param_count;
206         if (max_args < n)
207                 max_args = n;
208         num_args += n;
209         if (n)
210                 has_args++;
211
212         has_code++;
213         if (max_code < header->code_size)
214                 max_code = header->code_size;
215         num_code += header->code_size;
216
217         ip = header->code;
218
219         while (ip < (header->code + header->code_size)) {
220                 if (*ip == 0xfe) {
221                         ++ip;
222                         i = *ip + 256;
223                 } else {
224                         i = *ip;
225                 }
226
227                 opcode = &mono_opcodes [i];
228
229                 switch (opcode->argument) {
230                 case MonoInlineNone:
231                         if (i == MONO_CEE_NOP)
232                                 nop_waste++;
233                         ++ip;
234                         break;
235                 case MonoInlineI:
236                         n = read32 (ip + 1);
237                         if (n >= -1 && n <= 8) {
238                                 int_waste += 4;
239                                 g_print ("%s %d\n", mono_opcode_names [i], n);
240                         } else if (n < 128 && n >= -128) {
241                                 int_waste += 3;
242                                 g_print ("%s %d\n", mono_opcode_names [i], n);
243                         }
244                         ip += 5;
245                         break;
246                 case MonoInlineType:
247                         if (i == MONO_CEE_CASTCLASS || i == MONO_CEE_ISINST) {
248                                 guint32 token = read32 (ip + 1);
249                                 MonoClass *k = mono_class_get (method->klass->image, token);
250                                 if (k && k->flags & TYPE_ATTRIBUTE_SEALED)
251                                         cast_sealed++;
252                                 if (k && k->flags & TYPE_ATTRIBUTE_INTERFACE)
253                                         cast_iface++;
254                                 total_cast++;
255                         }
256                         ip += 5;
257                         break;
258                 case MonoInlineField:
259                 case MonoInlineTok:
260                 case MonoInlineString:
261                 case MonoInlineSig:
262                 case MonoShortInlineR:
263                         ip += 5;
264                         break;
265                 case MonoInlineBrTarget:
266                         n = read32 (ip + 1);
267                         if (n < 128 && n >= -128) {
268                                 branch_waste += 3;
269                                 if (n < 0)
270                                         back_branch_waste += 3;
271                         }
272                         ip += 5;
273                         break;
274                 case MonoInlineVar:
275                         n = read16 (ip + 1);
276                         if (n < 256) {
277                                 if (n < 4) {
278                                         switch (i) {
279                                         case MONO_CEE_LDARG:
280                                         case MONO_CEE_LDLOC:
281                                         case MONO_CEE_STLOC:
282                                                 var_waste += 3;
283                                                 g_print ("%s %d\n", mono_opcode_names [i], n);
284                                                 break;
285                                         default:
286                                                 var_waste += 2;
287                                                 g_print ("%s %d\n", mono_opcode_names [i], n);
288                                                 break;
289                                         }
290                                 } else {
291                                         var_waste += 2;
292                                         g_print ("%s %d\n", mono_opcode_names [i], n);
293                                 }
294                         }
295                         ip += 3;
296                         break;
297                 case MonoShortInlineVar:
298                         if ((signed char)ip [1] < 4 && (signed char)ip [1] >= 0) {
299                                 switch (i) {
300                                 case MONO_CEE_LDARG_S:
301                                 case MONO_CEE_LDLOC_S:
302                                 case MONO_CEE_STLOC_S:
303                                         var_waste++;
304                                         g_print ("%s %d\n", mono_opcode_names [i], (signed char)ip [1]);
305                                         break;
306                                 default:
307                                         break;
308                                 }
309                         }
310                         ip += 2;
311                         break;
312                 case MonoShortInlineI:
313                         if ((signed char)ip [1] <= 8 && (signed char)ip [1] >= -1) {
314                                 g_print ("%s %d\n", mono_opcode_names [i], (signed char)ip [1]);
315                                 int_waste ++;
316                         }
317                         ip += 2;
318                         break;
319                 case MonoShortInlineBrTarget:
320                         ip += 2;
321                         break;
322                 case MonoInlineSwitch: {
323                         gint32 n;
324                         ++ip;
325                         n = read32 (ip);
326                         ip += 4;
327                         ip += 4 * n;
328                         num_switch += n;
329                         has_switch++;
330                         if (max_switch < n)
331                                 max_switch = n;
332                         break;
333                 }
334                 case MonoInlineR:
335                         ip += 9;
336                         break;
337                 case MonoInlineI8:
338                         l = read64 (ip + 1);
339                         /* should load and convert */
340                         if (l >= -1 && l <= 8) {
341                                 int_waste += 7;
342                         } else if (l < 128 && l >= -128) {
343                                 int_waste += 6;
344                         } else if (l <= 2147483647 && l >= (-2147483647 -1)) {
345                                 int_waste += 3;
346                         }
347                         ip += 9;
348                         break;
349                 case MonoInlineMethod:
350                         if (i == MONO_CEE_CALLVIRT) {
351                                 MonoMethod *cm = mono_get_method (method->klass->image, read32 (ip + 1), NULL);
352                                 if (cm && !(cm->flags & METHOD_ATTRIBUTE_VIRTUAL))
353                                         nonvirt_callvirt++;
354                                 total_callvirt++;
355                         }
356                         ip += 5;
357                         break;
358                 default:
359                         g_assert_not_reached ();
360                 }
361
362                 switch (opcode->flow_type) {
363                 case MONO_FLOW_BRANCH:
364                         local_branch++;
365                         break;
366                 case MONO_FLOW_COND_BRANCH:
367                         local_condbranch++;
368                         break;
369                 case MONO_FLOW_CALL:
370                         local_calls++;
371                         break;
372                 case MONO_FLOW_ERROR:
373                         local_throw++;
374                         break;
375                 }
376         }
377         
378         if (local_branch)
379                 has_branch++;
380         if (max_branch < local_branch)
381                 max_branch = local_branch;
382         num_branch += local_branch;
383
384         if (local_condbranch)
385                 has_condbranch++;
386         if (max_condbranch < local_condbranch)
387                 max_condbranch = local_condbranch;
388         num_condbranch += local_condbranch;
389
390         if (local_calls)
391                 has_calls++;
392         if (max_calls < local_calls)
393                 max_calls = local_calls;
394         num_calls += local_calls;
395
396         if (local_throw)
397                 has_throw++;
398         if (max_throw < local_throw)
399                 max_throw = local_throw;
400         num_throw += local_throw;
401
402         return;
403 }
404
405 static int num_pdepth = 0;
406 static int max_pdepth = 0;
407 static int num_ifaces = 0;
408
409 static void
410 type_stats (MonoClass *klass) {
411         MonoClass *parent;
412         int depth = 0;
413
414         if (klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
415                 num_ifaces++;
416                 return;
417         }
418         parent = klass->parent;
419         while (parent) {
420                 depth++;
421                 parent = parent->parent;
422         }
423         num_pdepth += depth;
424         if (max_pdepth < depth)
425                 max_pdepth = depth;
426 }
427
428 static void
429 stats (MonoImage *image, const char *name) {
430         int i, num_methods, num_types;
431         MonoMethod *method;
432         MonoClass *klass;
433         
434         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
435                 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
436                 method_stats (method);
437         }
438         num_methods = image->tables [MONO_TABLE_METHOD].rows;
439         for (i = 0; i < image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
440                 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | (i + 1));
441                 type_stats (klass);
442         }
443         num_types = image->tables [MONO_TABLE_TYPEDEF].rows;
444
445         g_print ("Methods and code stats:\n");
446         g_print ("back branch waste: %d\n", back_branch_waste);
447         g_print ("branch waste: %d\n", branch_waste);
448         g_print ("var waste: %d\n", var_waste);
449         g_print ("int waste: %d\n", int_waste);
450         g_print ("nop waste: %d\n", nop_waste);
451         g_print ("has exceptions: %d/%d, total: %d, max: %d, mean: %f\n", has_exceptions, num_methods, num_exceptions, max_exceptions, num_exceptions/(double)has_exceptions);
452         g_print ("has locals: %d/%d, total: %d, max: %d, mean: %f\n", has_locals, num_methods, num_locals, max_locals, num_locals/(double)has_locals);
453         g_print ("has args: %d/%d, total: %d, max: %d, mean: %f\n", has_args, num_methods, num_args, max_args, num_args/(double)has_args);
454         g_print ("has maxstack: %d/%d, total: %d, max: %d, mean: %f\n", has_maxstack, num_methods, num_maxstack, max_maxstack, num_maxstack/(double)i);
455         g_print ("has code: %d/%d, total: %d, max: %d, mean: %f\n", has_code, num_methods, num_code, max_code, num_code/(double)has_code);
456         g_print ("has branch: %d/%d, total: %d, max: %d, mean: %f\n", has_branch, num_methods, num_branch, max_branch, num_branch/(double)has_branch);
457         g_print ("has condbranch: %d/%d, total: %d, max: %d, mean: %f\n", has_condbranch, num_methods, num_condbranch, max_condbranch, num_condbranch/(double)has_condbranch);
458         g_print ("has switch: %d/%d, total: %d, max: %d, mean: %f\n", has_switch, num_methods, num_switch, max_switch, num_switch/(double)has_switch);
459         g_print ("has calls: %d/%d, total: %d, max: %d, mean: %f\n", has_calls, num_methods, num_calls, max_calls, num_calls/(double)has_calls);
460         g_print ("has throw: %d/%d, total: %d, max: %d, mean: %f\n", has_throw, num_methods, num_throw, max_throw, num_throw/(double)has_throw);
461         g_print ("sealed type cast: %d/%d\n", cast_sealed, total_cast);
462         g_print ("interface type cast: %d/%d\n", cast_iface, total_cast);
463         g_print ("non virtual callvirt: %d/%d\n", nonvirt_callvirt, total_callvirt);
464         
465         g_print ("\nType stats:\n");
466         g_print ("interface types: %d/%d\n", num_ifaces, num_types);
467         g_print ("parent depth: max: %d, mean: %d\n", max_pdepth, num_pdepth/(num_types - num_ifaces));
468 }
469
470 static char *
471 get_signature (MonoMethod *method) {
472         GString *res;
473         static GHashTable *hash = NULL;
474         char *result;
475
476         if (!hash)
477                 hash = g_hash_table_new (g_direct_hash, g_direct_equal);
478         if ((result = g_hash_table_lookup (hash, method)))
479                 return result;
480
481         res = g_string_new ("");
482         if (include_namespace && *(method->klass->name_space))
483                 g_string_sprintfa (res, "%s.", method->klass->name_space);
484         result = mono_signature_get_desc (method->signature, include_namespace);
485         g_string_sprintfa (res, "%s:%s(%s)", method->klass->name, method->name, result);
486         g_free (result);
487         g_hash_table_insert (hash, method, res->str);
488
489         result = res->str;
490         g_string_free (res, FALSE);
491         return result;
492                 
493 }
494
495 static void
496 output_method_edge (MonoMethod *first, MonoMethod *second) {
497         char * f = get_signature (first);
498         char * s = get_signature (second);
499         
500         fprintf (output, "\t\"%s\" -> \"%s\"\n", f, s);
501 }
502
503 /*
504  * We need to handle virtual calls is derived types.
505  * We could check what types implement the method and
506  * disassemble all of them: this can make the graph to explode.
507  * We could try and keep track of the 'this' pointer type and
508  * consider only the methods in the classes derived from that:
509  * this can reduce the graph complexity somewhat (and it would 
510  * be the more correct approach).
511  */
512 static void
513 print_method (MonoMethod *method, int depth) {
514         const MonoOpcode *opcode;
515         MonoMethodHeader *header;
516         GHashTable *hash;
517         const unsigned char *ip;
518         int i;
519
520         if (depth++ > max_depth)
521                 return;
522         if (method->info) /* avoid recursion */
523                 return;
524         method->info = method;
525
526         if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME))
527                 return;
528         if (method->flags & (METHOD_ATTRIBUTE_PINVOKE_IMPL | METHOD_ATTRIBUTE_ABSTRACT))
529                 return;
530
531         header = ((MonoMethodNormal *)method)->header;
532         ip = header->code;
533
534         hash = g_hash_table_new (g_direct_hash, g_direct_equal);
535         
536         while (ip < (header->code + header->code_size)) {
537                 if (*ip == 0xfe) {
538                         ++ip;
539                         i = *ip + 256;
540                 } else {
541                         i = *ip;
542                 }
543
544                 opcode = &mono_opcodes [i];
545
546                 switch (opcode->argument) {
547                 case MonoInlineNone:
548                         ++ip;
549                         break;
550                 case MonoInlineType:
551                 case MonoInlineField:
552                 case MonoInlineTok:
553                 case MonoInlineString:
554                 case MonoInlineSig:
555                 case MonoShortInlineR:
556                 case MonoInlineI:
557                 case MonoInlineBrTarget:
558                         ip += 5;
559                         break;
560                 case MonoInlineVar:
561                         ip += 3;
562                         break;
563                 case MonoShortInlineVar:
564                 case MonoShortInlineI:
565                 case MonoShortInlineBrTarget:
566                         ip += 2;
567                         break;
568                 case MonoInlineSwitch: {
569                         gint32 n;
570                         ++ip;
571                         n = read32 (ip);
572                         ip += 4;
573                         ip += 4 * n;
574                         break;
575                 }
576                 case MonoInlineR:
577                 case MonoInlineI8:
578                         ip += 9;
579                         break;
580                 case MonoInlineMethod: {
581                         guint32 token;
582                         MonoMethod *called;
583                         ip++;
584                         token = read32 (ip);
585                         ip += 4;
586                         called = mono_get_method (method->klass->image, token, NULL);
587                         if (!called)
588                                 break; /* warn? */
589                         if (g_hash_table_lookup (hash, called))
590                                 break;
591                         g_hash_table_insert (hash, called, called);
592                         output_method_edge (method, called);
593                         print_method (called, depth);
594                         break;
595                 }
596                 default:
597                         g_assert_not_reached ();
598                 }
599         }
600         g_hash_table_destroy (hash);
601 }
602
603 static void
604 method_graph (MonoImage *image, const char *name) {
605         int depth = 0;
606         MonoMethod *method = NULL;
607         
608         if (!name) {
609                 guint32 token = mono_image_get_entry_point (image);
610                 if (!token || !(method = mono_get_method (image, token, NULL))) {
611                         g_print ("Cannot find entry point in %s: specify an explict method name.\n", image->name);
612                         exit (1);
613                 }
614         } else {
615                 /* search the method */
616                 MonoMethodDesc *desc;
617
618                 desc = mono_method_desc_new (name, include_namespace);
619                 if (!desc) {
620                         g_print ("Invalid method name %s\n", name);
621                         exit (1);
622                 }
623                 method = mono_method_desc_search_in_image (desc, image);
624                 if (!method) {
625                         g_print ("Cannot find method %s\n", name);
626                         exit (1);
627                 }
628         }
629         fprintf (output, "digraph blah {\n");
630         fprintf (output, "%s", graph_properties);
631
632         print_method (method, depth);
633         
634         fprintf (output, "}\n");
635 }
636
637 typedef struct MonoBasicBlock MonoBasicBlock;
638
639 struct MonoBasicBlock {
640         const unsigned char* cil_code;
641         gint32 cil_length;
642         gint dfn;
643         GList *in_bb;
644         GList *out_bb;
645 };
646
647 static const unsigned char *debug_start;
648
649 static void
650 link_bblock (MonoBasicBlock *from, MonoBasicBlock* to)
651 {
652         from->out_bb = g_list_prepend (from->out_bb, to);
653         to->in_bb = g_list_prepend (to->in_bb, from);
654         /*fprintf (stderr, "linking IL_%04x to IL_%04x\n", from->cil_code-debug_start, to->cil_code-debug_start);*/
655 }
656
657 static int
658 compare_bblock (const void *a, const void *b)
659 {
660         MonoBasicBlock * const *ab = a;
661         MonoBasicBlock * const *bb = b;
662
663         return (*ab)->cil_code - (*bb)->cil_code;
664 }
665
666 static GPtrArray*
667 mono_method_find_bblocks (MonoMethodHeader *header)
668 {
669         const unsigned char *ip, *end, *start;
670         const MonoOpcode *opcode;
671         int i, block_end = 0;
672         GPtrArray *result = g_ptr_array_new ();
673         GHashTable *table = g_hash_table_new (g_direct_hash, g_direct_equal);
674         MonoBasicBlock *entry_bb, *end_bb, *bb, *target;
675
676         ip = header->code;
677         end = ip + header->code_size;
678         debug_start = ip;
679
680         entry_bb = g_new0 (MonoBasicBlock, 1);
681         end_bb = g_new0 (MonoBasicBlock, 1);
682         g_ptr_array_add (result, entry_bb);
683         g_ptr_array_add (result, end_bb);
684
685         bb = g_new0 (MonoBasicBlock, 1);
686         bb->cil_code = ip;
687         g_ptr_array_add (result, bb);
688         link_bblock (entry_bb, bb);
689         g_hash_table_insert (table, (char*)ip, bb);
690         block_end = TRUE;
691
692         /* handle exception code blocks... */
693         while (ip < end) {
694                 start = ip;
695                 if ((target = g_hash_table_lookup (table, ip)) && target != bb) {
696                         if (!block_end)
697                                 link_bblock (bb, target);
698                         bb = target;
699                         block_end = FALSE;
700                 }
701                 if (block_end) {
702                         /*fprintf (stderr, "processing bbclok at IL_%04x\n", ip - header->code);*/
703                         if (!(bb = g_hash_table_lookup (table, ip))) {
704                                 bb = g_new0 (MonoBasicBlock, 1);
705                                 bb->cil_code = ip;
706                                 g_ptr_array_add (result, bb);
707                                 g_hash_table_insert (table, (char*)ip, bb);
708                         }
709                         block_end = FALSE;
710                 }
711                 if (*ip == 0xfe) {
712                         ++ip;
713                         i = *ip + 256;
714                 } else {
715                         i = *ip;
716                 }
717
718                 opcode = &mono_opcodes [i];
719                 switch (opcode->flow_type) {
720                 case MONO_FLOW_RETURN:
721                         link_bblock (bb, end_bb);
722                 case MONO_FLOW_ERROR:
723                         block_end = 1;
724                         break;
725                 case MONO_FLOW_BRANCH: /* we handle branch when checking the argument type */
726                 case MONO_FLOW_COND_BRANCH:
727                 case MONO_FLOW_CALL:
728                 case MONO_FLOW_NEXT:
729                 case MONO_FLOW_META:
730                         break;
731                 default:
732                         g_assert_not_reached ();
733                 }
734                 switch (opcode->argument) {
735                 case MonoInlineNone:
736                         ++ip;
737                         break;
738                 case MonoInlineType:
739                 case MonoInlineField:
740                 case MonoInlineMethod:
741                 case MonoInlineTok:
742                 case MonoInlineString:
743                 case MonoInlineSig:
744                 case MonoShortInlineR:
745                 case MonoInlineI:
746                         ip += 5;
747                         break;
748                 case MonoInlineVar:
749                         ip += 3;
750                         break;
751                 case MonoShortInlineVar:
752                 case MonoShortInlineI:
753                         ip += 2;
754                         break;
755                 case MonoShortInlineBrTarget:
756                 case MonoInlineBrTarget:
757                         ip++;
758                         if (opcode->argument == MonoShortInlineBrTarget) {
759                                 i = (signed char)*ip;
760                                 ip++;
761                         } else {
762                                 i = (gint32) read32 (ip);
763                                 ip += 4;
764                         }
765                         if (opcode->flow_type == MONO_FLOW_COND_BRANCH) {
766                                 if (!(target = g_hash_table_lookup (table, ip))) {
767                                         target = g_new0 (MonoBasicBlock, 1);
768                                         target->cil_code = ip;
769                                         g_ptr_array_add (result, target);
770                                         g_hash_table_insert (table, (char*)ip, target);
771                                 }
772                                 link_bblock (bb, target);
773                         }
774                         if (!(target = g_hash_table_lookup (table, ip + i))) {
775                                 target = g_new0 (MonoBasicBlock, 1);
776                                 target->cil_code = ip + i;
777                                 g_ptr_array_add (result, target);
778                                 g_hash_table_insert (table, (char*)ip + i, target);
779                         }
780                         link_bblock (bb, target);
781                         block_end = 1;
782                         break;
783                 case MonoInlineSwitch: {
784                         gint32 n;
785                         const char *itarget, *st;
786                         ++ip;
787                         n = read32 (ip);
788                         ip += 4;
789                         st = (const char*)ip + 4 * n;
790
791                         for (i = 0; i < n; i++) {
792                                 itarget = st + read32 (ip);
793                                 ip += 4;
794                                 if (!(target = g_hash_table_lookup (table, itarget))) {
795                                         target = g_new0 (MonoBasicBlock, 1);
796                                         target->cil_code = itarget;
797                                         g_ptr_array_add (result, target);
798                                         g_hash_table_insert (table, (gpointer) itarget, target);
799                                 }
800                                 link_bblock (bb, target);
801                         }
802                         /*
803                          * Note: the code didn't set block_end in switch.
804                          */
805                         break;
806                 }
807                 case MonoInlineR:
808                 case MonoInlineI8:
809                         ip += 9;
810                         break;
811                 default:
812                         g_assert_not_reached ();
813                 }
814
815         }
816         g_hash_table_destroy (table);
817         qsort (result->pdata, result->len, sizeof (gpointer), compare_bblock);
818         /* skip entry and end */
819         bb = target = NULL;
820         for (i = 2; i < result->len; ++i) {
821                 bb = (MonoBasicBlock*)g_ptr_array_index (result, i);
822                 if (target)
823                         target->cil_length = bb->cil_code - target->cil_code;
824                 target = bb;
825                 /*fprintf (stderr, "bblock %d at IL_%04x:\n", i, bb->cil_code - header->code);*/
826         }
827         bb->cil_length = header->code + header->code_size - bb->cil_code;
828         return result;
829 }
830
831 static char*
832 indenter (MonoDisHelper *dh, MonoMethod *method, guint32 ip_offset)
833 {
834         return g_strdup (" ");
835 }
836
837 static MonoDisHelper graph_dh = {
838         "\\l",
839         NULL,
840         "IL_%04x",
841         indenter, 
842         NULL,
843         NULL
844 };
845
846 static void
847 df_visit (MonoBasicBlock *bb, int *dfn, const unsigned char* code)
848 {
849         GList *tmp;
850         MonoBasicBlock *next;
851         
852         if (bb->dfn)
853                 return;
854         ++(*dfn);
855         bb->dfn = *dfn;
856         for (tmp = bb->out_bb; tmp; tmp = tmp->next) {
857                 next = tmp->data;
858                 if (!next->dfn) {
859                         if (!bb->cil_code)
860                                 fprintf (output, "\t\"DF entry\" -> \"IL_%04x (%d)\"\n", next->cil_code - code, *dfn + 1);
861                         else
862                                 fprintf (output, "\t\"IL_%04x (%d)\" -> \"IL_%04x (%d)\"\n", bb->cil_code - code, bb->dfn, next->cil_code - code, *dfn + 1);
863                         df_visit (next, dfn, code);
864                 }
865         }
866 }
867
868 static void
869 print_method_cfg (MonoMethod *method) {
870         GPtrArray *bblocks;
871         GList *tmp;
872         MonoBasicBlock *bb, *target;
873         MonoMethodHeader *header;
874         int i, dfn;
875         char *code;
876
877         header = ((MonoMethodNormal*)method)->header;
878         bblocks = mono_method_find_bblocks (header);
879         for (i = 0; i < bblocks->len; ++i) {
880                 bb = (MonoBasicBlock*)g_ptr_array_index (bblocks, i);
881                 if (i == 0)
882                         fprintf (output, "\tB%p [shape=record,label=\"entry\"]\n", bb);
883                 else if (i == 1)
884                         fprintf (output, "\tB%p [shape=record,label=\"end\"]\n", bb);
885                 else {
886                         code = mono_disasm_code (&graph_dh, method, bb->cil_code, bb->cil_code + bb->cil_length);
887                         fprintf (output, "\tB%p [shape=record,label=\"IL_%04x\\n%s\"]\n", bb, bb->cil_code - header->code, code);
888                         g_free (code);
889                 }
890         }
891         for (i = 0; i < bblocks->len; ++i) {
892                 bb = (MonoBasicBlock*)g_ptr_array_index (bblocks, i);
893                 for (tmp = bb->out_bb; tmp; tmp = tmp->next) {
894                         target = tmp->data;
895                         fprintf (output, "\tB%p -> B%p\n", bb, target);
896                 }
897         }
898 #if 1
899         for (i = 0; i < bblocks->len; ++i) {
900                 bb = (MonoBasicBlock*)g_ptr_array_index (bblocks, i);
901                 bb->dfn = 0;
902         }
903         dfn = 0;
904         for (i = 0; i < bblocks->len; ++i) {
905                 bb = (MonoBasicBlock*)g_ptr_array_index (bblocks, i);
906                 df_visit (bb, &dfn, header->code);
907         }
908 #endif
909 }
910
911 /*
912  * TODO: change to create the DF tree, dominance relation etc.
913  */
914 static void
915 method_cfg (MonoImage *image, const char *name) {
916         MonoMethod *method = NULL;
917         const static char *cfg_graph_properties = "\tnode [fontsize=8.0]\n\tedge [len=1.5,color=red]\n";
918         
919         if (!name) {
920                 guint32 token = mono_image_get_entry_point (image);
921                 if (!token || !(method = mono_get_method (image, token, NULL))) {
922                         g_print ("Cannot find entry point in %s: specify an explict method name.\n", image->name);
923                         exit (1);
924                 }
925         } else {
926                 /* search the method */
927                 MonoMethodDesc *desc;
928
929                 desc = mono_method_desc_new (name, include_namespace);
930                 if (!desc) {
931                         g_print ("Invalid method name %s\n", name);
932                         exit (1);
933                 }
934                 method = mono_method_desc_search_in_image (desc, image);
935                 if (!method) {
936                         g_print ("Cannot find method %s\n", name);
937                         exit (1);
938                 }
939         }
940         fprintf (output, "digraph blah {\n");
941         fprintf (output, "%s", cfg_graph_properties);
942
943         print_method_cfg (method);
944         
945         fprintf (output, "}\n");
946 }
947
948 static void
949 usage (void) {
950         printf ("monograph 0.2 Copyright (c) 2002 Ximian, Inc\n");
951         printf ("Create call graph or type hierarchy information from CIL assemblies.\n");
952         printf ("Usage: monograph [options] [assembly [typename|methodname]]\n");
953         printf ("Valid options are:\n");
954         printf ("\t-c|--call             output call graph instead of type hierarchy\n");
955         printf ("\t-C|--control-flow     output control flow of methodname\n");
956         printf ("\t--stats               output some statistics about the assembly\n");
957         printf ("\t-d|--depth num        max depth recursion (default: 6)\n");
958         printf ("\t-o|--output filename  write graph to file filename (default: stdout)\n");
959         printf ("\t-f|--fullname         include namespace in type and method names\n");
960         printf ("\t-n|--neato            invoke neato directly\n");
961         printf ("\t-v|--verbose          verbose operation\n");
962         printf ("The default assembly is corlib.dll. The default method for\n");
963         printf ("the --call and --control-flow options is the entrypoint.\n");
964         printf ("When the --neato option is used the output type info is taken\n");
965         printf ("from the output filename extension. You need the graphviz package installed\n");
966         printf ("to be able to use this option.\n");
967         printf ("Sample runs:\n");
968         printf ("\tmonograph -n -o vt.png corlib.dll System.ValueType\n");
969         printf ("\tmonograph -n -o expr.png mcs.exe Mono.CSharp.Expression\n");
970         printf ("\tmonograph -n -o cfg.png -C mcs.exe Driver:Main\n");
971         printf ("\tmonograph -d 3 -n -o callgraph.png -c mis.exe\n");
972         exit (1);
973 }
974
975 enum {
976         GRAPH_TYPES,
977         GRAPH_CALL,
978         GRAPH_INTERFACE,
979         GRAPH_CONTROL_FLOW,
980         GRAPH_STATS
981 };
982
983 /*
984  * TODO:
985  * * virtual method calls as explained above
986  * * maybe track field references
987  * * track what exceptions a method could throw?
988  * * for some inputs neato appears to hang or take a long time: kill it?
989  * * allow passing additional command-line arguments to neato
990  * * allow setting different graph/node/edge options directly
991  * * option to avoid specialname methods
992  * * make --neato option the default?
993  * * use multiple classes/method roots?
994  * * write a manpage
995  * * reverse call graph: given a method what methods call it?
996  */
997 int
998 main (int argc, char *argv[]) {
999         MonoAssembly *assembly;
1000         const char *cname = NULL;
1001         const char *aname = NULL;
1002         char *outputfile = NULL;
1003         int graphtype = GRAPH_TYPES;
1004         int callneato = 0;
1005         int i;
1006         
1007         mono_init (argv [0]);
1008         output = stdout;
1009
1010         for (i = 1; i < argc; ++i) {
1011                 if (argv [i] [0] != '-')
1012                         break;
1013                 if (strcmp (argv [i], "--call") == 0 || strcmp (argv [i], "-c") == 0) {
1014                         graphtype = GRAPH_CALL;
1015                 } else if (strcmp (argv [i], "--control-flow") == 0 || strcmp (argv [i], "-C") == 0) {
1016                         graphtype = GRAPH_CONTROL_FLOW;
1017                 } else if (strcmp (argv [i], "--interface") == 0 || strcmp (argv [i], "-i") == 0) {
1018                         graphtype = GRAPH_INTERFACE;
1019                 } else if (strcmp (argv [i], "--stats") == 0) {
1020                         graphtype = GRAPH_STATS;
1021                 } else if (strcmp (argv [i], "--fullname") == 0 || strcmp (argv [i], "-f") == 0) {
1022                         include_namespace = 1;
1023                 } else if (strcmp (argv [i], "--neato") == 0 || strcmp (argv [i], "-n") == 0) {
1024                         callneato = 1;
1025                 } else if (strcmp (argv [i], "--verbose") == 0 || strcmp (argv [i], "-v") == 0) {
1026                         verbose++;
1027                 } else if (strcmp (argv [i], "--output") == 0 || strcmp (argv [i], "-o") == 0) {
1028                         if (i + 1 >= argc)
1029                                 usage ();
1030                         outputfile = argv [++i];
1031                 } else if (strcmp (argv [i], "--depth") == 0 || strcmp (argv [i], "-d") == 0) {
1032                         if (i + 1 >= argc)
1033                                 usage ();
1034                         max_depth = atoi (argv [++i]);
1035                 } else {
1036                         usage ();
1037                 }
1038                 
1039         }
1040         if (argc > i)
1041                 aname = argv [i];
1042         if (argc > i + 1)
1043                 cname = argv [i + 1];
1044         if (!aname)
1045                 aname = "mscorlib.dll";
1046         if (!cname && (graphtype == GRAPH_TYPES))
1047                 cname = "System.Object";
1048
1049         assembly = mono_assembly_open (aname, NULL);
1050         if (!assembly) {
1051                 g_print ("cannot open assembly %s\n", aname);
1052                 exit (1);
1053         }
1054
1055         if (callneato) {
1056                 GString *command = g_string_new ("neato");
1057                 char *type = NULL;
1058
1059                 if (outputfile) {
1060                         type = strrchr (outputfile, '.');
1061                         g_string_sprintfa (command, " -o %s", outputfile);
1062                 }
1063                 if (type)
1064                         g_string_sprintfa (command, " -T%s", type + 1);
1065                 output = popen (command->str, "w");
1066                 if (!output) {
1067                         g_print ("Cannot run neato: you may need to install the graphviz package.\n");
1068                         exit (1);
1069                 }
1070         } else if (outputfile) {
1071                 output = fopen (outputfile, "w");
1072                 if (!output) {
1073                         g_print ("Cannot open file: %s\n", outputfile);
1074                         exit (1);
1075                 }
1076         }
1077         /* if it looks like a method name, we want a callgraph. */
1078         if (cname && strchr (cname, ':') && graphtype == GRAPH_TYPES)
1079                 graphtype = GRAPH_CALL;
1080
1081         switch (graphtype) {
1082         case GRAPH_TYPES:
1083                 type_graph (assembly->image, cname);
1084                 break;
1085         case GRAPH_CALL:
1086                 method_graph (assembly->image, cname);
1087                 break;
1088         case GRAPH_INTERFACE:
1089                 interface_graph (assembly->image, cname);
1090                 break;
1091         case GRAPH_CONTROL_FLOW:
1092                 method_cfg (assembly->image, cname);
1093                 break;
1094         case GRAPH_STATS:
1095                 stats (assembly->image, cname);
1096                 break;
1097         default:
1098                 g_error ("wrong graph type");
1099         }
1100         
1101         if (callneato) {
1102                 if (verbose)
1103                         g_print ("waiting for neato.\n");
1104                 pclose (output);
1105         } else if (outputfile)
1106                 fclose (output);
1107         return 0;
1108 }
1109
1110