2004-05-16 Patrik Torstensson <totte@hiddenpeaks.com>
[mono.git] / mono / mini / helpers.c
1 /*
2  * helpers.c: Assorted routines
3  *
4  * (C) 2003 Ximian, Inc.
5  */
6 #include "mini.h"
7 #include <ctype.h>
8 #include <mono/metadata/opcodes.h>
9
10 #ifdef MINI_OP
11 #undef MINI_OP
12 #endif
13 #define MINI_OP(a,b) b,
14 /* keep in sync with the enum in mini.h */
15 static const char* 
16 opnames[] = {
17 #include "mini-ops.h"
18 };
19 #undef MINI_OP
20
21 const char*
22 mono_inst_name (int op) {
23         if (op >= OP_LOAD && op <= OP_LAST)
24                 return opnames [op - OP_LOAD];
25         if (op < OP_LOAD)
26                 return mono_opcode_names [op];
27         g_error ("unknown opcode name for %d", op);
28         return NULL;
29 }
30
31 void
32 mono_blockset_print (MonoCompile *cfg, MonoBitSet *set, const char *name, guint idom) 
33 {
34         int i;
35
36         if (name)
37                 g_print ("%s:", name);
38         
39         mono_bitset_foreach_bit (set, i, cfg->num_bblocks) {
40                 if (idom == i)
41                         g_print (" [BB%d]", cfg->bblocks [i]->block_num);
42                 else
43                         g_print (" BB%d", cfg->bblocks [i]->block_num);
44                 
45         }
46         g_print ("\n");
47 }
48
49 /**
50  * mono_disassemble_code:
51  * @code: a pointer to the code
52  * @size: the code size in bytes
53  *
54  * Disassemble to code to stdout.
55  */
56 void
57 mono_disassemble_code (guint8 *code, int size, char *id)
58 {
59         int i;
60         FILE *ofd;
61         const char *tmp = getenv("TMP");
62         char *as_file;
63         char *o_file;
64         char *cmd;
65
66         if (tmp == NULL)
67                 tmp = "/tmp";
68         as_file = g_strdup_printf ("%s/test.s", tmp);    
69
70         if (!(ofd = fopen (as_file, "w")))
71                 g_assert_not_reached ();
72
73         for (i = 0; id [i]; ++i) {
74                 if (!isalnum (id [i]))
75                         fprintf (ofd, "_");
76                 else
77                         fprintf (ofd, "%c", id [i]);
78         }
79         fprintf (ofd, ":\n");
80
81         for (i = 0; i < size; ++i) 
82                 fprintf (ofd, ".byte %d\n", (unsigned int) code [i]);
83
84         fclose (ofd);
85 #ifdef __APPLE__
86 #define DIS_CMD "otool -V -v -t"
87 #else
88 #if defined(sparc) && !defined(__GNUC__)
89 #define DIS_CMD "dis"
90 #else
91 #define DIS_CMD "objdump -d"
92 #endif
93 #endif
94         o_file = g_strdup_printf ("%s/test.o", tmp);    
95         cmd = g_strdup_printf ("as %s -o %s", as_file, o_file);
96         system (cmd); 
97         g_free (cmd);
98         cmd = g_strdup_printf (DIS_CMD " %s", o_file);
99         system (cmd);
100         g_free (cmd);
101
102         cmd = g_strdup_printf ("objdump -d %s", o_file);
103         system (cmd);
104         g_free (cmd);
105         g_free (o_file);
106         g_free (as_file);
107 }
108