remove .cvsignore, as this is not used anymore
[mono.git] / mono / monograph / monograph.c
1 #include <glib.h>
2 #include <string.h>
3 #include "mono/metadata/class-internals.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         const MonoTableInfo *t;
30         MonoClass *child;
31
32         if (depth++ > max_depth)
33                 return;
34
35         t = mono_image_get_table_info (image, MONO_TABLE_TYPEDEF);
36         
37         token = mono_metadata_token_index (class->type_token);
38         token <<= MONO_TYPEDEFORREF_BITS;
39         token |= MONO_TYPEDEFORREF_TYPEDEF;
40
41         /* use a subgraph? */
42         for (i = 0; i < mono_table_info_get_rows (t); ++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         const MonoTableInfo *intf = mono_image_get_table_info (image, 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 <<= MONO_TYPEDEFORREF_BITS;
116         token |= MONO_TYPEDEFORREF_TYPEDEF;
117         for (i = 0; i < mono_table_info_get_rows (intf); ++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 = mono_method_get_header (method);
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_name (i), n);
240                         } else if (n < 128 && n >= -128) {
241                                 int_waste += 3;
242                                 g_print ("%s %d\n", mono_opcode_name (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_name (i), n);
284                                                 break;
285                                         default:
286                                                 var_waste += 2;
287                                                 g_print ("%s %d\n", mono_opcode_name (i), n);
288                                                 break;
289                                         }
290                                 } else {
291                                         var_waste += 2;
292                                         g_print ("%s %d\n", mono_opcode_name (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_name (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_name (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         num_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
435         for (i = 0; i < num_methods; ++i) {
436                 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
437                 method_stats (method);
438         }
439         num_types = mono_image_get_table_rows (image, MONO_TABLE_TYPEDEF);
440         for (i = 0; i < num_types; ++i) {
441                 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | (i + 1));
442                 type_stats (klass);
443         }
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         static GHashTable *visited = NULL;
518         const unsigned char *ip;
519         int i;
520
521         if (depth++ > max_depth)
522                 return;
523         
524         if (! visited)
525                 visited = g_hash_table_new (NULL, NULL);
526         
527         if (g_hash_table_lookup (visited, method))
528                 return;
529         
530         g_hash_table_insert (visited, method, method);
531
532         if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME))
533                 return;
534         if (method->flags & (METHOD_ATTRIBUTE_PINVOKE_IMPL | METHOD_ATTRIBUTE_ABSTRACT))
535                 return;
536
537         header = mono_method_get_header (method);
538         ip = header->code;
539
540         hash = g_hash_table_new (g_direct_hash, g_direct_equal);
541         
542         while (ip < (header->code + header->code_size)) {
543                 if (*ip == 0xfe) {
544                         ++ip;
545                         i = *ip + 256;
546                 } else {
547                         i = *ip;
548                 }
549
550                 opcode = &mono_opcodes [i];
551
552                 switch (opcode->argument) {
553                 case MonoInlineNone:
554                         ++ip;
555                         break;
556                 case MonoInlineType:
557                 case MonoInlineField:
558                 case MonoInlineTok:
559                 case MonoInlineString:
560                 case MonoInlineSig:
561                 case MonoShortInlineR:
562                 case MonoInlineI:
563                 case MonoInlineBrTarget:
564                         ip += 5;
565                         break;
566                 case MonoInlineVar:
567                         ip += 3;
568                         break;
569                 case MonoShortInlineVar:
570                 case MonoShortInlineI:
571                 case MonoShortInlineBrTarget:
572                         ip += 2;
573                         break;
574                 case MonoInlineSwitch: {
575                         gint32 n;
576                         ++ip;
577                         n = read32 (ip);
578                         ip += 4;
579                         ip += 4 * n;
580                         break;
581                 }
582                 case MonoInlineR:
583                 case MonoInlineI8:
584                         ip += 9;
585                         break;
586                 case MonoInlineMethod: {
587                         guint32 token;
588                         MonoMethod *called;
589                         ip++;
590                         token = read32 (ip);
591                         ip += 4;
592                         called = mono_get_method (method->klass->image, token, NULL);
593                         if (!called)
594                                 break; /* warn? */
595                         if (g_hash_table_lookup (hash, called))
596                                 break;
597                         g_hash_table_insert (hash, called, called);
598                         output_method_edge (method, called);
599                         print_method (called, depth);
600                         break;
601                 }
602                 default:
603                         g_assert_not_reached ();
604                 }
605         }
606         g_hash_table_destroy (hash);
607 }
608
609 static void
610 method_graph (MonoImage *image, const char *name) {
611         int depth = 0;
612         MonoMethod *method = NULL;
613         
614         if (!name) {
615                 guint32 token = mono_image_get_entry_point (image);
616                 if (!token || !(method = mono_get_method (image, token, NULL))) {
617                         g_print ("Cannot find entry point in %s: specify an explict method name.\n", mono_image_get_filename (image));
618                         exit (1);
619                 }
620         } else {
621                 /* search the method */
622                 MonoMethodDesc *desc;
623
624                 desc = mono_method_desc_new (name, include_namespace);
625                 if (!desc) {
626                         g_print ("Invalid method name %s\n", name);
627                         exit (1);
628                 }
629                 method = mono_method_desc_search_in_image (desc, image);
630                 if (!method) {
631                         g_print ("Cannot find method %s\n", name);
632                         exit (1);
633                 }
634         }
635         fprintf (output, "digraph blah {\n");
636         fprintf (output, "%s", graph_properties);
637
638         print_method (method, depth);
639         
640         fprintf (output, "}\n");
641 }
642
643 typedef struct MonoBasicBlock MonoBasicBlock;
644
645 struct MonoBasicBlock {
646         const unsigned char* cil_code;
647         gint32 cil_length;
648         gint dfn;
649         GList *in_bb;
650         GList *out_bb;
651 };
652
653 static const unsigned char *debug_start;
654
655 static void
656 link_bblock (MonoBasicBlock *from, MonoBasicBlock* to)
657 {
658         from->out_bb = g_list_prepend (from->out_bb, to);
659         to->in_bb = g_list_prepend (to->in_bb, from);
660         /*fprintf (stderr, "linking IL_%04x to IL_%04x\n", from->cil_code-debug_start, to->cil_code-debug_start);*/
661 }
662
663 static int
664 compare_bblock (const void *a, const void *b)
665 {
666         MonoBasicBlock * const *ab = a;
667         MonoBasicBlock * const *bb = b;
668
669         return (*ab)->cil_code - (*bb)->cil_code;
670 }
671
672 static GPtrArray*
673 mono_method_find_bblocks (MonoMethodHeader *header)
674 {
675         const unsigned char *ip, *end, *start;
676         const MonoOpcode *opcode;
677         int i, block_end = 0;
678         GPtrArray *result = g_ptr_array_new ();
679         GHashTable *table = g_hash_table_new (g_direct_hash, g_direct_equal);
680         MonoBasicBlock *entry_bb, *end_bb, *bb, *target;
681
682         ip = header->code;
683         end = ip + header->code_size;
684         debug_start = ip;
685
686         entry_bb = g_new0 (MonoBasicBlock, 1);
687         end_bb = g_new0 (MonoBasicBlock, 1);
688         g_ptr_array_add (result, entry_bb);
689         g_ptr_array_add (result, end_bb);
690
691         bb = g_new0 (MonoBasicBlock, 1);
692         bb->cil_code = ip;
693         g_ptr_array_add (result, bb);
694         link_bblock (entry_bb, bb);
695         g_hash_table_insert (table, (char*)ip, bb);
696         block_end = TRUE;
697
698         /* handle exception code blocks... */
699         while (ip < end) {
700                 start = ip;
701                 if ((target = g_hash_table_lookup (table, ip)) && target != bb) {
702                         if (!block_end)
703                                 link_bblock (bb, target);
704                         bb = target;
705                         block_end = FALSE;
706                 }
707                 if (block_end) {
708                         /*fprintf (stderr, "processing bbclok at IL_%04x\n", ip - header->code);*/
709                         if (!(bb = g_hash_table_lookup (table, ip))) {
710                                 bb = g_new0 (MonoBasicBlock, 1);
711                                 bb->cil_code = ip;
712                                 g_ptr_array_add (result, bb);
713                                 g_hash_table_insert (table, (char*)ip, bb);
714                         }
715                         block_end = FALSE;
716                 }
717                 if (*ip == 0xfe) {
718                         ++ip;
719                         i = *ip + 256;
720                 } else {
721                         i = *ip;
722                 }
723
724                 opcode = &mono_opcodes [i];
725                 switch (opcode->flow_type) {
726                 case MONO_FLOW_RETURN:
727                         link_bblock (bb, end_bb);
728                 case MONO_FLOW_ERROR:
729                         block_end = 1;
730                         break;
731                 case MONO_FLOW_BRANCH: /* we handle branch when checking the argument type */
732                 case MONO_FLOW_COND_BRANCH:
733                 case MONO_FLOW_CALL:
734                 case MONO_FLOW_NEXT:
735                 case MONO_FLOW_META:
736                         break;
737                 default:
738                         g_assert_not_reached ();
739                 }
740                 switch (opcode->argument) {
741                 case MonoInlineNone:
742                         ++ip;
743                         break;
744                 case MonoInlineType:
745                 case MonoInlineField:
746                 case MonoInlineMethod:
747                 case MonoInlineTok:
748                 case MonoInlineString:
749                 case MonoInlineSig:
750                 case MonoShortInlineR:
751                 case MonoInlineI:
752                         ip += 5;
753                         break;
754                 case MonoInlineVar:
755                         ip += 3;
756                         break;
757                 case MonoShortInlineVar:
758                 case MonoShortInlineI:
759                         ip += 2;
760                         break;
761                 case MonoShortInlineBrTarget:
762                 case MonoInlineBrTarget:
763                         ip++;
764                         if (opcode->argument == MonoShortInlineBrTarget) {
765                                 i = (signed char)*ip;
766                                 ip++;
767                         } else {
768                                 i = (gint32) read32 (ip);
769                                 ip += 4;
770                         }
771                         if (opcode->flow_type == MONO_FLOW_COND_BRANCH) {
772                                 if (!(target = g_hash_table_lookup (table, ip))) {
773                                         target = g_new0 (MonoBasicBlock, 1);
774                                         target->cil_code = ip;
775                                         g_ptr_array_add (result, target);
776                                         g_hash_table_insert (table, (char*)ip, target);
777                                 }
778                                 link_bblock (bb, target);
779                         }
780                         if (!(target = g_hash_table_lookup (table, ip + i))) {
781                                 target = g_new0 (MonoBasicBlock, 1);
782                                 target->cil_code = ip + i;
783                                 g_ptr_array_add (result, target);
784                                 g_hash_table_insert (table, (char*)ip + i, target);
785                         }
786                         link_bblock (bb, target);
787                         block_end = 1;
788                         break;
789                 case MonoInlineSwitch: {
790                         gint32 n;
791                         const char *itarget, *st;
792                         ++ip;
793                         n = read32 (ip);
794                         ip += 4;
795                         st = (const char*)ip + 4 * n;
796
797                         for (i = 0; i < n; i++) {
798                                 itarget = st + read32 (ip);
799                                 ip += 4;
800                                 if (!(target = g_hash_table_lookup (table, itarget))) {
801                                         target = g_new0 (MonoBasicBlock, 1);
802                                         target->cil_code = itarget;
803                                         g_ptr_array_add (result, target);
804                                         g_hash_table_insert (table, (gpointer) itarget, target);
805                                 }
806                                 link_bblock (bb, target);
807                         }
808                         /*
809                          * Note: the code didn't set block_end in switch.
810                          */
811                         break;
812                 }
813                 case MonoInlineR:
814                 case MonoInlineI8:
815                         ip += 9;
816                         break;
817                 default:
818                         g_assert_not_reached ();
819                 }
820
821         }
822         g_hash_table_destroy (table);
823         qsort (result->pdata, result->len, sizeof (gpointer), compare_bblock);
824         /* skip entry and end */
825         bb = target = NULL;
826         for (i = 2; i < result->len; ++i) {
827                 bb = (MonoBasicBlock*)g_ptr_array_index (result, i);
828                 if (target)
829                         target->cil_length = bb->cil_code - target->cil_code;
830                 target = bb;
831                 /*fprintf (stderr, "bblock %d at IL_%04x:\n", i, bb->cil_code - header->code);*/
832         }
833         bb->cil_length = header->code + header->code_size - bb->cil_code;
834         return result;
835 }
836
837 static char*
838 indenter (MonoDisHelper *dh, MonoMethod *method, guint32 ip_offset)
839 {
840         return g_strdup (" ");
841 }
842
843 static MonoDisHelper graph_dh = {
844         "\\l",
845         NULL,
846         "IL_%04x",
847         indenter, 
848         NULL,
849         NULL
850 };
851
852 static void
853 df_visit (MonoBasicBlock *bb, int *dfn, const unsigned char* code)
854 {
855         GList *tmp;
856         MonoBasicBlock *next;
857         
858         if (bb->dfn)
859                 return;
860         ++(*dfn);
861         bb->dfn = *dfn;
862         for (tmp = bb->out_bb; tmp; tmp = tmp->next) {
863                 next = tmp->data;
864                 if (!next->dfn) {
865                         if (!bb->cil_code)
866                                 fprintf (output, "\t\"DF entry\" -> \"IL_%04x (%d)\"\n", next->cil_code - code, *dfn + 1);
867                         else
868                                 fprintf (output, "\t\"IL_%04x (%d)\" -> \"IL_%04x (%d)\"\n", bb->cil_code - code, bb->dfn, next->cil_code - code, *dfn + 1);
869                         df_visit (next, dfn, code);
870                 }
871         }
872 }
873
874 static void
875 print_method_cfg (MonoMethod *method) {
876         GPtrArray *bblocks;
877         GList *tmp;
878         MonoBasicBlock *bb, *target;
879         MonoMethodHeader *header;
880         int i, dfn;
881         char *code;
882
883         header = mono_method_get_header (method);
884         bblocks = mono_method_find_bblocks (header);
885         for (i = 0; i < bblocks->len; ++i) {
886                 bb = (MonoBasicBlock*)g_ptr_array_index (bblocks, i);
887                 if (i == 0)
888                         fprintf (output, "\tB%p [shape=record,label=\"entry\"]\n", bb);
889                 else if (i == 1)
890                         fprintf (output, "\tB%p [shape=record,label=\"end\"]\n", bb);
891                 else {
892                         code = mono_disasm_code (&graph_dh, method, bb->cil_code, bb->cil_code + bb->cil_length);
893                         fprintf (output, "\tB%p [shape=record,label=\"IL_%04x\\n%s\"]\n", bb, bb->cil_code - header->code, code);
894                         g_free (code);
895                 }
896         }
897         for (i = 0; i < bblocks->len; ++i) {
898                 bb = (MonoBasicBlock*)g_ptr_array_index (bblocks, i);
899                 for (tmp = bb->out_bb; tmp; tmp = tmp->next) {
900                         target = tmp->data;
901                         fprintf (output, "\tB%p -> B%p\n", bb, target);
902                 }
903         }
904 #if 1
905         for (i = 0; i < bblocks->len; ++i) {
906                 bb = (MonoBasicBlock*)g_ptr_array_index (bblocks, i);
907                 bb->dfn = 0;
908         }
909         dfn = 0;
910         for (i = 0; i < bblocks->len; ++i) {
911                 bb = (MonoBasicBlock*)g_ptr_array_index (bblocks, i);
912                 df_visit (bb, &dfn, header->code);
913         }
914 #endif
915 }
916
917 /*
918  * TODO: change to create the DF tree, dominance relation etc.
919  */
920 static void
921 method_cfg (MonoImage *image, const char *name) {
922         MonoMethod *method = NULL;
923         const static char *cfg_graph_properties = "\tnode [fontsize=8.0]\n\tedge [len=1.5,color=red]\n";
924         
925         if (!name) {
926                 guint32 token = mono_image_get_entry_point (image);
927                 if (!token || !(method = mono_get_method (image, token, NULL))) {
928                         g_print ("Cannot find entry point in %s: specify an explict method name.\n", mono_image_get_filename (image));
929                         exit (1);
930                 }
931         } else {
932                 /* search the method */
933                 MonoMethodDesc *desc;
934
935                 desc = mono_method_desc_new (name, include_namespace);
936                 if (!desc) {
937                         g_print ("Invalid method name %s\n", name);
938                         exit (1);
939                 }
940                 method = mono_method_desc_search_in_image (desc, image);
941                 if (!method) {
942                         g_print ("Cannot find method %s\n", name);
943                         exit (1);
944                 }
945         }
946         fprintf (output, "digraph blah {\n");
947         fprintf (output, "%s", cfg_graph_properties);
948
949         print_method_cfg (method);
950         
951         fprintf (output, "}\n");
952 }
953
954 static void
955 usage (void) {
956         printf ("monograph 0.2 Copyright (c) 2002 Ximian, Inc\n");
957         printf ("Create call graph or type hierarchy information from CIL assemblies.\n");
958         printf ("Usage: monograph [options] [assembly [typename|methodname]]\n\n");
959         printf ("Valid options are:\n");
960         printf ("\t-c|--call             output call graph instead of type hierarchy\n");
961         printf ("\t-C|--control-flow     output control flow of methodname\n");
962         printf ("\t--stats               output some statistics about the assembly\n");
963         printf ("\t-d|--depth num        max depth recursion (default: 6)\n");
964         printf ("\t-o|--output filename  write graph to file filename (default: stdout)\n");
965         printf ("\t-f|--fullname         include namespace in type and method names\n");
966         printf ("\t-n|--neato            invoke neato directly\n");
967         printf ("\t-v|--verbose          verbose operation\n\n");
968         printf ("The default assembly is mscorlib.dll. The default method for\n");
969         printf ("the --call and --control-flow options is the entrypoint.\n\n");
970         printf ("When the --neato option is used the output type info is taken\n");
971         printf ("from the output filename extension. You need the graphviz package\n");
972         printf ("installed to be able to use this option and build bitmap files.\n");
973         printf ("Without --neato, monograph will create .dot files, a description\n");
974         printf ("file for a graph.\n\n");
975         printf ("Sample runs:\n");
976         printf ("\tmonograph -n -o vt.png mscorlib.dll System.ValueType\n");
977         printf ("\tmonograph -n -o expr.png mcs.exe Mono.CSharp.Expression\n");
978         printf ("\tmonograph -n -o cfg.png -C mcs.exe Driver:Main\n");
979         printf ("\tmonograph -d 3 -n -o callgraph.png -c mis.exe\n");
980         exit (1);
981 }
982
983 enum {
984         GRAPH_TYPES,
985         GRAPH_CALL,
986         GRAPH_INTERFACE,
987         GRAPH_CONTROL_FLOW,
988         GRAPH_STATS
989 };
990
991 /*
992  * TODO:
993  * * virtual method calls as explained above
994  * * maybe track field references
995  * * track what exceptions a method could throw?
996  * * for some inputs neato appears to hang or take a long time: kill it?
997  * * allow passing additional command-line arguments to neato
998  * * allow setting different graph/node/edge options directly
999  * * option to avoid specialname methods
1000  * * make --neato option the default?
1001  * * use multiple classes/method roots?
1002  * * write a manpage
1003  * * reverse call graph: given a method what methods call it?
1004  */
1005 int
1006 main (int argc, char *argv[]) {
1007         MonoAssembly *assembly;
1008         MonoImage *image;
1009         const char *cname = NULL;
1010         const char *aname = NULL;
1011         char *outputfile = NULL;
1012         int graphtype = GRAPH_TYPES;
1013         int callneato = 0;
1014         int i;
1015         
1016         mono_init (argv [0]);
1017         output = stdout;
1018
1019         for (i = 1; i < argc; ++i) {
1020                 if (argv [i] [0] != '-')
1021                         break;
1022                 if (strcmp (argv [i], "--call") == 0 || strcmp (argv [i], "-c") == 0) {
1023                         graphtype = GRAPH_CALL;
1024                 } else if (strcmp (argv [i], "--control-flow") == 0 || strcmp (argv [i], "-C") == 0) {
1025                         graphtype = GRAPH_CONTROL_FLOW;
1026                 } else if (strcmp (argv [i], "--interface") == 0 || strcmp (argv [i], "-i") == 0) {
1027                         graphtype = GRAPH_INTERFACE;
1028                 } else if (strcmp (argv [i], "--stats") == 0) {
1029                         graphtype = GRAPH_STATS;
1030                 } else if (strcmp (argv [i], "--fullname") == 0 || strcmp (argv [i], "-f") == 0) {
1031                         include_namespace = 1;
1032                 } else if (strcmp (argv [i], "--neato") == 0 || strcmp (argv [i], "-n") == 0) {
1033                         callneato = 1;
1034                 } else if (strcmp (argv [i], "--verbose") == 0 || strcmp (argv [i], "-v") == 0) {
1035                         verbose++;
1036                 } else if (strcmp (argv [i], "--output") == 0 || strcmp (argv [i], "-o") == 0) {
1037                         if (i + 1 >= argc)
1038                                 usage ();
1039                         outputfile = argv [++i];
1040                 } else if (strcmp (argv [i], "--depth") == 0 || strcmp (argv [i], "-d") == 0) {
1041                         if (i + 1 >= argc)
1042                                 usage ();
1043                         max_depth = atoi (argv [++i]);
1044                 } else {
1045                         usage ();
1046                 }
1047                 
1048         }
1049         if (argc > i)
1050                 aname = argv [i];
1051         if (argc > i + 1)
1052                 cname = argv [i + 1];
1053         if (!aname)
1054                 aname = "mscorlib";
1055         if (!cname && (graphtype == GRAPH_TYPES))
1056                 cname = "System.Object";
1057
1058         assembly = mono_assembly_open (aname, NULL);
1059         if (!assembly) {
1060                 g_print ("cannot open assembly %s\n", aname);
1061                 exit (1);
1062         }
1063
1064         if (callneato) {
1065                 GString *command = g_string_new ("neato");
1066                 char *type = NULL;
1067
1068                 if (outputfile) {
1069                         type = strrchr (outputfile, '.');
1070                         g_string_sprintfa (command, " -o %s", outputfile);
1071                 }
1072                 if (type)
1073                         g_string_sprintfa (command, " -T%s", type + 1);
1074                 output = popen (command->str, "w");
1075                 if (!output) {
1076                         g_print ("Cannot run neato: you may need to install the graphviz package.\n");
1077                         exit (1);
1078                 }
1079         } else if (outputfile) {
1080                 output = fopen (outputfile, "w");
1081                 if (!output) {
1082                         g_print ("Cannot open file: %s\n", outputfile);
1083                         exit (1);
1084                 }
1085         }
1086         /* if it looks like a method name, we want a callgraph. */
1087         if (cname && strchr (cname, ':') && graphtype == GRAPH_TYPES)
1088                 graphtype = GRAPH_CALL;
1089
1090         image = mono_assembly_get_image (assembly);
1091         switch (graphtype) {
1092         case GRAPH_TYPES:
1093                 type_graph (image, cname);
1094                 break;
1095         case GRAPH_CALL:
1096                 method_graph (image, cname);
1097                 break;
1098         case GRAPH_INTERFACE:
1099                 interface_graph (image, cname);
1100                 break;
1101         case GRAPH_CONTROL_FLOW:
1102                 method_cfg (image, cname);
1103                 break;
1104         case GRAPH_STATS:
1105                 stats (image, cname);
1106                 break;
1107         default:
1108                 g_error ("wrong graph type");
1109         }
1110         
1111         if (callneato) {
1112                 if (verbose)
1113                         g_print ("waiting for neato.\n");
1114                 pclose (output);
1115         } else if (outputfile)
1116                 fclose (output);
1117         return 0;
1118 }
1119
1120