3 #include "mono/metadata/class.h"
4 #include "mono/metadata/assembly.h"
5 #include "mono/metadata/tokentype.h"
6 #include "mono/metadata/opcodes.h"
7 #include "mono/metadata/tabledefs.h"
8 #include "mono/metadata/cil-coff.h" /* MonoCLIImageInfo */
9 #include "mono/metadata/mono-endian.h"
10 #include "mono/metadata/appdomain.h" /* mono_init */
11 #include "mono/metadata/debug-helpers.h"
14 static int include_namespace = 0;
15 static int max_depth = 6;
16 static int verbose = 0;
17 static const char *graph_properties = "\tnode [fontsize=8.0]\n\tedge [len=2,color=red]\n";
20 output_type_edge (MonoClass *first, MonoClass *second) {
21 if (include_namespace)
22 fprintf (output, "\t\"%s.%s\" -> \"%s.%s\"\n", first->name_space, first->name, second->name_space, second->name);
24 fprintf (output, "\t\"%s\" -> \"%s\"\n", first->name, second->name);
28 print_subtypes (MonoImage *image, MonoClass *class, int depth) {
33 if (depth++ > max_depth)
36 t = &image->tables [MONO_TABLE_TYPEDEF];
38 token = mono_metadata_token_index (class->type_token);
39 token <<= TYPEDEFORREF_BITS;
40 token |= TYPEDEFORREF_TYPEDEF;
43 for (i = 0; i < t->rows; ++i) {
44 if (token == mono_metadata_decode_row_col (t, i, MONO_TYPEDEF_EXTENDS)) {
45 child = mono_class_get (image, MONO_TOKEN_TYPE_DEF | (i + 1));
46 output_type_edge (class, child);
47 print_subtypes (image, child, depth);
53 type_graph (MonoImage *image, const char* cname) {
57 const char *name_space;
61 cname = g_strdup (cname);
62 p = strrchr (cname, '.');
70 class = mono_class_from_name (image, name_space, cname);
72 g_print ("class %s.%s not found\n", name_space, cname);
75 fprintf (output, "digraph blah {\n");
76 fprintf (output, "%s", graph_properties);
78 /* go back and print the parents for the node as well: not sure it's a good idea */
79 for (parent = class->parent; parent; parent = parent->parent) {
80 output_type_edge (parent, child);
83 print_subtypes (image, class, depth);
84 fprintf (output, "}\n");
88 interface_graph (MonoImage *image, const char* cname) {
91 const char *name_space;
93 guint32 cols [MONO_INTERFACEIMPL_SIZE];
94 guint32 token, i, count = 0;
95 MonoTableInfo *intf = &image->tables [MONO_TABLE_INTERFACEIMPL];
97 cname = g_strdup (cname);
98 p = strrchr (cname, '.');
106 class = mono_class_from_name (image, name_space, cname);
108 g_print ("interface %s.%s not found\n", name_space, cname);
111 /* chek if it's really an interface... */
112 fprintf (output, "digraph interface {\n");
113 fprintf (output, "%s", graph_properties);
114 /* TODO: handle inetrface defined in one image and class defined in another. */
115 token = mono_metadata_token_index (class->type_token);
116 token <<= TYPEDEFORREF_BITS;
117 token |= TYPEDEFORREF_TYPEDEF;
118 for (i = 0; i < intf->rows; ++i) {
119 mono_metadata_decode_row (intf, i, cols, MONO_INTERFACEIMPL_SIZE);
120 /*g_print ("index: %d [%d implements %d]\n", index, cols [MONO_INTERFACEIMPL_CLASS], cols [MONO_INTERFACEIMPL_INTERFACE]);*/
121 if (token == cols [MONO_INTERFACEIMPL_INTERFACE]) {
122 child = mono_class_get (image, MONO_TOKEN_TYPE_DEF | cols [MONO_INTERFACEIMPL_CLASS]);
123 output_type_edge (class, child);
127 fprintf (output, "}\n");
128 if (verbose && !count)
129 g_print ("No class implements %s.%s\n", class->name_space, class->name);
134 get_signature (MonoMethod *method) {
136 static GHashTable *hash = NULL;
140 hash = g_hash_table_new (g_direct_hash, g_direct_equal);
141 if ((result = g_hash_table_lookup (hash, method)))
144 res = g_string_new ("");
145 if (include_namespace && *(method->klass->name_space))
146 g_string_sprintfa (res, "%s.", method->klass->name_space);
147 result = mono_signature_get_desc (method->signature, include_namespace);
148 g_string_sprintfa (res, "%s:%s(%s)", method->klass->name, method->name, result);
150 g_hash_table_insert (hash, method, res->str);
153 g_string_free (res, FALSE);
159 output_method_edge (MonoMethod *first, MonoMethod *second) {
160 char * f = get_signature (first);
161 char * s = get_signature (second);
163 fprintf (output, "\t\"%s\" -> \"%s\"\n", f, s);
167 * We need to handle virtual calls is derived types.
168 * We could check what types implement the method and
169 * disassemble all of them: this can make the graph to explode.
170 * We could try and keep track of the 'this' pointer type and
171 * consider only the methods in the classes derived from that:
172 * this can reduce the graph complexity somewhat (and it would
173 * be the more correct approach).
176 print_method (MonoMethod *method, int depth) {
177 const MonoOpcode *opcode;
178 MonoMethodHeader *header;
180 const unsigned char *ip;
183 if (depth++ > max_depth)
185 if (method->info) /* avoid recursion */
187 method->info = method;
189 if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME))
191 if (method->flags & (METHOD_ATTRIBUTE_PINVOKE_IMPL | METHOD_ATTRIBUTE_ABSTRACT))
194 header = ((MonoMethodNormal *)method)->header;
197 hash = g_hash_table_new (g_direct_hash, g_direct_equal);
199 while (ip < (header->code + header->code_size)) {
207 opcode = &mono_opcodes [i];
209 switch (opcode->argument) {
214 case MonoInlineField:
216 case MonoInlineString:
218 case MonoShortInlineR:
220 case MonoInlineBrTarget:
226 case MonoShortInlineVar:
227 case MonoShortInlineI:
228 case MonoShortInlineBrTarget:
231 case MonoInlineSwitch: {
243 case MonoInlineMethod: {
249 called = mono_get_method (method->klass->image, token, NULL);
252 if (g_hash_table_lookup (hash, called))
254 g_hash_table_insert (hash, called, called);
255 output_method_edge (method, called);
256 print_method (called, depth);
260 g_assert_not_reached ();
263 g_hash_table_destroy (hash);
267 method_graph (MonoImage *image, const char *name) {
269 MonoMethod *method = NULL;
272 guint32 token = ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
273 if (!token || !(method = mono_get_method (image, token, NULL))) {
274 g_print ("Cannot find entry point in %s: specify an explict method name.\n", image->name);
278 /* search the method */
279 MonoMethodDesc *desc;
281 desc = mono_method_desc_new (name, include_namespace);
283 g_print ("Invalid method name %s\n", name);
286 method = mono_method_desc_search_in_image (desc, image);
288 g_print ("Cannot find method %s\n", name);
292 fprintf (output, "digraph blah {\n");
293 fprintf (output, "%s", graph_properties);
295 print_method (method, depth);
297 fprintf (output, "}\n");
300 typedef struct MonoBasicBlock MonoBasicBlock;
302 struct MonoBasicBlock {
303 const unsigned char* cil_code;
310 static const unsigned char *debug_start;
313 link_bblock (MonoBasicBlock *from, MonoBasicBlock* to)
315 from->out_bb = g_list_prepend (from->out_bb, to);
316 to->in_bb = g_list_prepend (to->in_bb, from);
317 /*fprintf (stderr, "linking IL_%04x to IL_%04x\n", from->cil_code-debug_start, to->cil_code-debug_start);*/
321 compare_bblock (void *a, void *b)
323 MonoBasicBlock **ab = a;
324 MonoBasicBlock **bb = b;
326 return (*ab)->cil_code - (*bb)->cil_code;
330 mono_method_find_bblocks (MonoMethodHeader *header)
332 const unsigned char *ip, *end, *start;
333 const MonoOpcode *opcode;
334 int i, block_end = 0;
335 GPtrArray *result = g_ptr_array_new ();
336 GHashTable *table = g_hash_table_new (g_direct_hash, g_direct_equal);
337 MonoBasicBlock *entry_bb, *end_bb, *bb, *target;
340 end = ip + header->code_size;
343 entry_bb = g_new0 (MonoBasicBlock, 1);
344 end_bb = g_new0 (MonoBasicBlock, 1);
345 g_ptr_array_add (result, entry_bb);
346 g_ptr_array_add (result, end_bb);
348 bb = g_new0 (MonoBasicBlock, 1);
350 g_ptr_array_add (result, bb);
351 link_bblock (entry_bb, bb);
352 g_hash_table_insert (table, (char*)ip, bb);
355 /* handle exception code blocks... */
358 if ((target = g_hash_table_lookup (table, ip)) && target != bb) {
360 link_bblock (bb, target);
365 /*fprintf (stderr, "processing bbclok at IL_%04x\n", ip - header->code);*/
366 if (!(bb = g_hash_table_lookup (table, ip))) {
367 bb = g_new0 (MonoBasicBlock, 1);
369 g_ptr_array_add (result, bb);
370 g_hash_table_insert (table, (char*)ip, bb);
381 opcode = &mono_opcodes [i];
382 switch (opcode->flow_type) {
383 case MONO_FLOW_RETURN:
384 link_bblock (bb, end_bb);
385 case MONO_FLOW_ERROR:
388 case MONO_FLOW_BRANCH: /* we handle branch when checking the argument type */
389 case MONO_FLOW_COND_BRANCH:
395 g_assert_not_reached ();
397 switch (opcode->argument) {
402 case MonoInlineField:
403 case MonoInlineMethod:
405 case MonoInlineString:
407 case MonoShortInlineR:
414 case MonoShortInlineVar:
415 case MonoShortInlineI:
418 case MonoShortInlineBrTarget:
419 case MonoInlineBrTarget:
421 if (opcode->argument == MonoShortInlineBrTarget) {
422 i = (signed char)*ip;
425 i = (gint32) read32 (ip);
428 if (opcode->flow_type == MONO_FLOW_COND_BRANCH) {
429 if (!(target = g_hash_table_lookup (table, ip))) {
430 target = g_new0 (MonoBasicBlock, 1);
431 target->cil_code = ip;
432 g_ptr_array_add (result, target);
433 g_hash_table_insert (table, (char*)ip, target);
435 link_bblock (bb, target);
437 if (!(target = g_hash_table_lookup (table, ip + i))) {
438 target = g_new0 (MonoBasicBlock, 1);
439 target->cil_code = ip + i;
440 g_ptr_array_add (result, target);
441 g_hash_table_insert (table, (char*)ip + i, target);
443 link_bblock (bb, target);
446 case MonoInlineSwitch: {
448 const char *itarget, *st;
452 st = (const char*)ip + 4 * n;
454 for (i = 0; i < n; i++) {
455 itarget = st + read32 (ip);
457 if (!(target = g_hash_table_lookup (table, itarget))) {
458 target = g_new0 (MonoBasicBlock, 1);
459 target->cil_code = itarget;
460 g_ptr_array_add (result, target);
461 g_hash_table_insert (table, itarget, target);
463 link_bblock (bb, target);
466 * Note: the code didn't set block_end in switch.
475 g_assert_not_reached ();
479 g_hash_table_destroy (table);
480 qsort (result->pdata, result->len, sizeof (gpointer), compare_bblock);
481 /* skip entry and end */
483 for (i = 2; i < result->len; ++i) {
484 bb = (MonoBasicBlock*)g_ptr_array_index (result, i);
486 target->cil_length = bb->cil_code - target->cil_code;
488 /*fprintf (stderr, "bblock %d at IL_%04x:\n", i, bb->cil_code - header->code);*/
490 bb->cil_length = header->code + header->code_size - bb->cil_code;
495 indenter (MonoDisHelper *dh, MonoMethod *method, guint32 ip_offset)
497 return g_strdup (" ");
500 static MonoDisHelper graph_dh = {
510 df_visit (MonoBasicBlock *bb, int *dfn, const unsigned char* code)
513 MonoBasicBlock *next;
519 for (tmp = bb->out_bb; tmp; tmp = tmp->next) {
523 fprintf (output, "\t\"DF entry\" -> \"IL_%04x (%d)\"\n", next->cil_code - code, *dfn + 1);
525 fprintf (output, "\t\"IL_%04x (%d)\" -> \"IL_%04x (%d)\"\n", bb->cil_code - code, bb->dfn, next->cil_code - code, *dfn + 1);
526 df_visit (next, dfn, code);
532 print_method_cfg (MonoMethod *method) {
535 MonoBasicBlock *bb, *target;
536 MonoMethodHeader *header;
540 header = ((MonoMethodNormal*)method)->header;
541 bblocks = mono_method_find_bblocks (header);
542 for (i = 0; i < bblocks->len; ++i) {
543 bb = (MonoBasicBlock*)g_ptr_array_index (bblocks, i);
545 fprintf (output, "\tB%p [shape=record,label=\"entry\"]\n", bb);
547 fprintf (output, "\tB%p [shape=record,label=\"end\"]\n", bb);
549 code = mono_disasm_code (&graph_dh, method, bb->cil_code, bb->cil_code + bb->cil_length);
550 fprintf (output, "\tB%p [shape=record,label=\"IL_%04x\\n%s\"]\n", bb, bb->cil_code - header->code, code);
554 for (i = 0; i < bblocks->len; ++i) {
555 bb = (MonoBasicBlock*)g_ptr_array_index (bblocks, i);
556 for (tmp = bb->out_bb; tmp; tmp = tmp->next) {
558 fprintf (output, "\tB%p -> B%p\n", bb, target);
562 for (i = 0; i < bblocks->len; ++i) {
563 bb = (MonoBasicBlock*)g_ptr_array_index (bblocks, i);
567 for (i = 0; i < bblocks->len; ++i) {
568 bb = (MonoBasicBlock*)g_ptr_array_index (bblocks, i);
569 df_visit (bb, &dfn, header->code);
575 * TODO: change to create the DF tree, dominance relation etc.
578 method_cfg (MonoImage *image, const char *name) {
579 MonoMethod *method = NULL;
580 const static char *cfg_graph_properties = "\tnode [fontsize=8.0]\n\tedge [len=1.5,color=red]\n";
583 guint32 token = ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
584 if (!token || !(method = mono_get_method (image, token, NULL))) {
585 g_print ("Cannot find entry point in %s: specify an explict method name.\n", image->name);
589 /* search the method */
590 MonoMethodDesc *desc;
592 desc = mono_method_desc_new (name, include_namespace);
594 g_print ("Invalid method name %s\n", name);
597 method = mono_method_desc_search_in_image (desc, image);
599 g_print ("Cannot find method %s\n", name);
603 fprintf (output, "digraph blah {\n");
604 fprintf (output, "%s", cfg_graph_properties);
606 print_method_cfg (method);
608 fprintf (output, "}\n");
613 printf ("monograph 0.2 Copyright (c) 2002 Ximian, Inc\n");
614 printf ("Create call graph or type hierarchy information from CIL assemblies.\n");
615 printf ("Usage: monograph [options] [assembly [typename|methodname]]\n");
616 printf ("Valid options are:\n");
617 printf ("\t-c|--call output call graph instead of type hierarchy\n");
618 printf ("\t-C|--control-flow output control flow of methodname\n");
619 printf ("\t-d|--depth num max depth recursion (default: 6)\n");
620 printf ("\t-o|--output filename write graph to file filename (default: stdout)\n");
621 printf ("\t-f|--fullname include namespace in type and method names\n");
622 printf ("\t-n|--neato invoke neato directly\n");
623 printf ("\t-v|--verbose verbose operation\n");
624 printf ("The default assembly is corlib.dll. The default method for\n");
625 printf ("the --call and --control-flow options is the entrypoint.\n");
626 printf ("When the --neato option is used the output type info is taken\n");
627 printf ("from the output filename extension. You need the graphviz package installed\n");
628 printf ("to be able to use this option.\n");
629 printf ("Sample runs:\n");
630 printf ("\tmonograph -n -o vt.png corlib.dll System.ValueType\n");
631 printf ("\tmonograph -n -o expr.png mcs.exe Mono.CSharp.Expression\n");
632 printf ("\tmonograph -n -o cfg.png -C mcs.exe Driver:Main\n");
633 printf ("\tmonograph -d 3 -n -o callgraph.png -c mis.exe\n");
646 * * virtual method calls as explained above
647 * * maybe track field references
648 * * track what exceptions a method could throw?
649 * * for some inputs neato appears to hang or take a long time: kill it?
650 * * allow passing additional command-line arguments to neato
651 * * allow setting different graph/node/edge options directly
652 * * option to avoid specialname methods
653 * * make --neato option the default?
654 * * use multiple classes/method roots?
656 * * reverse call graph: given a method what methods call it?
659 main (int argc, char *argv[]) {
660 MonoAssembly *assembly;
661 const char *cname = NULL;
662 const char *aname = NULL;
663 char *outputfile = NULL;
664 int graphtype = GRAPH_TYPES;
668 mono_init (argv [0]);
671 for (i = 1; i < argc; ++i) {
672 if (argv [i] [0] != '-')
674 if (strcmp (argv [i], "--call") == 0 || strcmp (argv [i], "-c") == 0) {
675 graphtype = GRAPH_CALL;
676 } else if (strcmp (argv [i], "--control-flow") == 0 || strcmp (argv [i], "-C") == 0) {
677 graphtype = GRAPH_CONTROL_FLOW;
678 } else if (strcmp (argv [i], "--interface") == 0 || strcmp (argv [i], "-i") == 0) {
679 graphtype = GRAPH_INTERFACE;
680 } else if (strcmp (argv [i], "--fullname") == 0 || strcmp (argv [i], "-f") == 0) {
681 include_namespace = 1;
682 } else if (strcmp (argv [i], "--neato") == 0 || strcmp (argv [i], "-n") == 0) {
684 } else if (strcmp (argv [i], "--verbose") == 0 || strcmp (argv [i], "-v") == 0) {
686 } else if (strcmp (argv [i], "--output") == 0 || strcmp (argv [i], "-o") == 0) {
689 outputfile = argv [++i];
690 } else if (strcmp (argv [i], "--depth") == 0 || strcmp (argv [i], "-d") == 0) {
693 max_depth = atoi (argv [++i]);
702 cname = argv [i + 1];
704 aname = "corlib.dll";
705 if (!cname && (graphtype == GRAPH_TYPES))
706 cname = "System.Object";
708 assembly = mono_assembly_open (aname, NULL, NULL);
710 g_print ("cannot open assembly %s\n", aname);
715 GString *command = g_string_new ("neato");
719 type = strrchr (outputfile, '.');
720 g_string_sprintfa (command, " -o %s", outputfile);
723 g_string_sprintfa (command, " -T%s", type + 1);
724 output = popen (command->str, "w");
726 g_print ("Cannot run neato: you may need to install the graphviz package.\n");
729 } else if (outputfile) {
730 output = fopen (outputfile, "w");
732 g_print ("Cannot open file: %s\n", outputfile);
736 /* if it looks like a method name, we want a callgraph. */
737 if (cname && strchr (cname, ':') && graphtype == GRAPH_TYPES)
738 graphtype = GRAPH_CALL;
742 type_graph (assembly->image, cname);
745 method_graph (assembly->image, cname);
747 case GRAPH_INTERFACE:
748 interface_graph (assembly->image, cname);
750 case GRAPH_CONTROL_FLOW:
751 method_cfg (assembly->image, cname);
754 g_error ("wrong graph type");
759 g_print ("waiting for neato.\n");
761 } else if (outputfile)