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