2004-01-26 Martin Baulig <martin@ximian.com>
[mono.git] / mono / dis / main.c
1 /*
2  * main.c: Sample disassembler
3  *
4  * Author:
5  *   Miguel de Icaza (miguel@ximian.com)
6  *
7  * (C) 2001 Ximian, Inc.
8  *
9  * TODO:
10  *   Investigate how interface inheritance works and how it should be dumped.
11  *   Structs are not being labeled as `valuetype' classes
12  *   
13  *   How are fields with literals mapped to constants?
14  */
15 #include <config.h>
16 #include <stdio.h>
17 #include <string.h>
18 #include <glib.h>
19 #include <stdlib.h>
20 #include <errno.h>
21 #include "meta.h"
22 #include "util.h"
23 #include "dump.h"
24 #include "get.h"
25 #include "dis-cil.h"
26 #include <mono/metadata/loader.h>
27 #include <mono/metadata/assembly.h>
28 #include <mono/metadata/appdomain.h>
29
30 FILE *output;
31
32 /* True if you want to get a dump of the header data */
33 gboolean dump_header_data_p = FALSE;
34
35 gboolean substitute_with_mscorlib_p = FALSE;
36
37 int dump_table = -1;
38
39 static void
40 dump_header_data (MonoImage *img)
41 {
42         if (!dump_header_data_p)
43                 return;
44
45         fprintf (output,
46                  "// Ximian's CIL disassembler, version 1.0\n"
47                  "// Copyright (C) 2001 Ximian, Inc.\n\n");
48 }
49
50 static void
51 dump_cattrs (MonoImage *m, guint32 token, const char *indent)
52 {
53         GList *tmp, *list;
54
55         list = dis_get_custom_attrs (m, token);
56         for (tmp = list; tmp; tmp = tmp->next) {
57                 fprintf (output, "%s%s\n", indent, (char*)tmp->data);
58                 g_free (tmp->data);
59         }
60         g_list_free (list);
61 }
62
63 static void
64 dis_directive_assembly (MonoImage *m)
65 {
66         MonoTableInfo *t  = &m->tables [MONO_TABLE_ASSEMBLY];
67         guint32 cols [MONO_ASSEMBLY_SIZE];
68         
69         if (t->base == NULL)
70                 return;
71
72         mono_metadata_decode_row (t, 0, cols, MONO_ASSEMBLY_SIZE);
73         
74         fprintf (output, ".assembly '%s'\n{\n",
75                  mono_metadata_string_heap (m, cols [MONO_ASSEMBLY_NAME]));
76         dump_cattrs (m, MONO_TOKEN_ASSEMBLY | 1, "  ");
77         fprintf (output,
78                  "  .hash algorithm 0x%08x\n"
79                  "  .ver  %d:%d:%d:%d\n",
80                  cols [MONO_ASSEMBLY_HASH_ALG],
81                  cols [MONO_ASSEMBLY_MAJOR_VERSION], cols [MONO_ASSEMBLY_MINOR_VERSION], 
82                  cols [MONO_ASSEMBLY_BUILD_NUMBER], cols [MONO_ASSEMBLY_REV_NUMBER]);
83         if (cols [MONO_ASSEMBLY_CULTURE])
84                 fprintf (output, "  .locale %s\n", mono_metadata_string_heap (m, cols [MONO_ASSEMBLY_CULTURE]));
85         if (cols [MONO_ASSEMBLY_PUBLIC_KEY]) {
86                 const char* b = mono_metadata_blob_heap (m, cols [MONO_ASSEMBLY_PUBLIC_KEY]);
87                 int len = mono_metadata_decode_blob_size (b, &b);
88                 char *dump = data_dump (b, len, "\t\t");
89                 fprintf (output, "  .publickey =%s", dump);
90                 g_free (dump);
91         }
92         fprintf (output, "}\n");
93 }
94
95 static void
96 dis_directive_assemblyref (MonoImage *m)
97 {
98         MonoTableInfo *t = &m->tables [MONO_TABLE_ASSEMBLYREF];
99         guint32 cols [MONO_ASSEMBLYREF_SIZE];
100         int i;
101         
102         if (t->base == NULL)
103                 return;
104
105         for (i = 0; i < t->rows; i++){
106                 mono_metadata_decode_row (t, i, cols, MONO_ASSEMBLYREF_SIZE);
107
108                 fprintf (output,
109                          ".assembly extern %s\n"
110                          "{\n"
111                          "  .ver %d:%d:%d:%d\n"
112                          "}\n",
113                          mono_metadata_string_heap (m, cols [MONO_ASSEMBLYREF_NAME]),
114                          cols [MONO_ASSEMBLYREF_MAJOR_VERSION], cols [MONO_ASSEMBLYREF_MINOR_VERSION], 
115                          cols [MONO_ASSEMBLYREF_BUILD_NUMBER], cols [MONO_ASSEMBLYREF_REV_NUMBER]
116                         );
117         }
118 }
119
120 static void
121 dis_directive_module (MonoImage *m)
122 {
123         MonoTableInfo *t = &m->tables [MONO_TABLE_MODULE];
124         int i;
125
126         for (i = 0; i < t->rows; i++){
127                 guint32 cols [MONO_MODULE_SIZE];
128                 const char *name;
129                 char *guid, *ename;
130                 
131                 mono_metadata_decode_row (t, i, cols, MONO_MODULE_SIZE);
132
133                 name = mono_metadata_string_heap (m, cols [MONO_MODULE_NAME]);
134                 ename = get_escaped_name (name);
135                 guid = get_guid (m, cols [MONO_MODULE_MVID]);
136                 fprintf (output, ".module %s // GUID = %s\n\n", ename, guid);
137                 g_free (ename);
138
139                 dump_cattrs (m, MONO_TOKEN_MODULE | (i + 1), "");
140         }
141 }
142
143 static void
144 dis_directive_moduleref (MonoImage *m)
145 {
146         MonoTableInfo *t = &m->tables [MONO_TABLE_MODULEREF];
147         int i;
148
149         for (i = 0; i < t->rows; i++){
150                 guint32 cols [MONO_MODULEREF_SIZE];
151                 const char *name;
152                 
153                 mono_metadata_decode_row (t, i, cols, MONO_MODULEREF_SIZE);
154
155                 name = mono_metadata_string_heap (m, cols [MONO_MODULEREF_NAME]);
156                 fprintf (output, ".module extern %s\n", name);
157         }
158         
159 }
160
161 static void
162 dis_directive_file (MonoImage *m)
163 {
164         MonoTableInfo *t = &m->tables [MONO_TABLE_FILE];
165         int i, j, len;
166         guint32 entry_point;
167
168         entry_point = mono_image_get_entry_point (m);
169
170         for (i = 0; i < t->rows; i++){
171                 guint32 cols [MONO_FILE_SIZE];
172                 const char *name, *hash;
173                 guint32 token;
174
175                 mono_metadata_decode_row (t, i, cols, MONO_FILE_SIZE);
176
177                 name = mono_metadata_string_heap (m, cols [MONO_FILE_NAME]);
178
179                 hash = mono_metadata_blob_heap (m, cols [MONO_FILE_HASH_VALUE]);
180                 len = mono_metadata_decode_blob_size (hash, &hash);
181
182                 fprintf (output, ".file %s%s .hash = (", name,
183                                 cols [MONO_FILE_FLAGS] & FILE_CONTAINS_NO_METADATA ? " nometadata" : "");
184
185                 for (j = 0; j < len; ++j)
186                         fprintf (output, " %02X", hash [j] & 0xff);
187
188                 token = mono_metadata_make_token (MONO_TABLE_FILE, i + 1);
189                 fprintf (output, " )%s\n", (token == entry_point) ? " .entrypoint" : "");
190         }
191         
192 }
193
194 static map_t visibility_map [] = {
195         { TYPE_ATTRIBUTE_NOT_PUBLIC,           "private " },
196         { TYPE_ATTRIBUTE_PUBLIC,               "public " },
197         { TYPE_ATTRIBUTE_NESTED_PUBLIC,        "nested public " },
198         { TYPE_ATTRIBUTE_NESTED_PRIVATE,       "nested private " },
199         { TYPE_ATTRIBUTE_NESTED_FAMILY,        "nested family " },
200         { TYPE_ATTRIBUTE_NESTED_ASSEMBLY,      "nested assembly" },
201         { TYPE_ATTRIBUTE_NESTED_FAM_AND_ASSEM, "nested famandassem" },
202         { TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM,  "nested famorassem" },
203         { 0, NULL }
204 };
205
206 static map_t layout_map [] = {
207         { TYPE_ATTRIBUTE_AUTO_LAYOUT,          "auto " },
208         { TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT,    "sequential " },
209         { TYPE_ATTRIBUTE_EXPLICIT_LAYOUT,      "explicit " },
210         { 0, NULL }
211 };
212
213 static map_t format_map [] = {
214         { TYPE_ATTRIBUTE_ANSI_CLASS,           "ansi " },
215         { TYPE_ATTRIBUTE_UNICODE_CLASS,        "unicode " },
216         { TYPE_ATTRIBUTE_AUTO_CLASS,           "auto " },
217         { 0, NULL }
218 };
219
220 static char *
221 typedef_flags (guint32 flags)
222 {
223         static char buffer [1024];
224         int visibility = flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
225         int layout = flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
226         int format = flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK;
227         
228         buffer [0] = 0;
229
230         strcat (buffer, map (visibility, visibility_map));
231         strcat (buffer, map (layout, layout_map));
232         strcat (buffer, map (format, format_map));
233         
234         if (flags & TYPE_ATTRIBUTE_ABSTRACT)
235                 strcat (buffer, "abstract ");
236         if (flags & TYPE_ATTRIBUTE_SEALED)
237                 strcat (buffer, "sealed ");
238         if (flags & TYPE_ATTRIBUTE_SPECIAL_NAME)
239                 strcat (buffer, "special-name ");
240         if (flags & TYPE_ATTRIBUTE_IMPORT)
241                 strcat (buffer, "import ");
242         if (flags & TYPE_ATTRIBUTE_SERIALIZABLE)
243                 strcat (buffer, "serializable ");
244         if (flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)
245                 strcat (buffer, "beforefieldinit ");
246
247         return buffer;
248 }
249
250 /**
251  * dis_field_list:
252  * @m: metadata context
253  * @start: starting index into the Field Table.
254  * @end: ending index into Field table.
255  *
256  * This routine displays all the decoded fields from @start to @end
257  */
258 static void
259 dis_field_list (MonoImage *m, guint32 start, guint32 end)
260 {
261         MonoTableInfo *t = &m->tables [MONO_TABLE_FIELD];
262         guint32 cols [MONO_FIELD_SIZE];
263         char *esname;
264         char rva_desc [32];
265         guint32 rva;
266         int i;
267
268         if (end > t->rows + 1) {
269                 g_warning ("ERROR index out of range in fields");
270                 end = t->rows;
271         }
272                         
273         for (i = start; i < end; i++){
274                 char *sig, *flags, *attrs = NULL;
275                 guint32 field_offset = -1;
276                 
277                 mono_metadata_decode_row (t, i, cols, MONO_FIELD_SIZE);
278                 sig = get_field_signature (m, cols [MONO_FIELD_SIGNATURE]);
279                 flags = field_flags (cols [MONO_FIELD_FLAGS]);
280
281                 if (cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_HAS_FIELD_RVA) {
282                         mono_metadata_field_info (m, i, NULL, &rva, NULL);
283                         g_snprintf (rva_desc, sizeof (rva_desc), " at D_%08x", rva);
284                 } else {
285                         rva_desc [0] = 0;
286                 }
287                 
288                 mono_metadata_field_info (m, i, &field_offset, NULL, NULL);
289                 if (field_offset != -1)
290                         attrs = g_strdup_printf ("[%d]", field_offset);
291                 esname = get_escaped_name (mono_metadata_string_heap (m, cols [MONO_FIELD_NAME]));
292                 if (cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_LITERAL){
293                         char *lit;
294                         guint32 const_cols [MONO_CONSTANT_SIZE];
295                         guint32 crow;
296                         
297                         if ((crow = mono_metadata_get_constant_index (m, MONO_TOKEN_FIELD_DEF | (i+1), 0))) {
298                                 mono_metadata_decode_row (&m->tables [MONO_TABLE_CONSTANT], crow-1, const_cols, MONO_CONSTANT_SIZE);
299                                 lit = get_constant (m, const_cols [MONO_CONSTANT_TYPE], const_cols [MONO_CONSTANT_VALUE]);
300                         } else {
301                                 lit = g_strdup ("not found");
302                         }
303                         
304                         
305                         fprintf (output, "    .field %s %s %s = ",
306                                  flags, sig, esname);
307                         fprintf (output, "%s\n", lit);
308                         g_free (lit);
309                 } else
310                         fprintf (output, "    .field %s %s %s %s%s\n",
311                                  attrs? attrs: "", flags, sig, esname, rva_desc);
312                 g_free (attrs);
313                 g_free (flags);
314                 g_free (sig);
315                 g_free (esname);
316                 dump_cattrs (m, MONO_TOKEN_FIELD_DEF | (i + 1), "    ");
317         }
318 }
319
320 static map_t method_access_map [] = {
321         { METHOD_ATTRIBUTE_COMPILER_CONTROLLED, "compilercontrolled " },
322         { METHOD_ATTRIBUTE_PRIVATE,             "private " },
323         { METHOD_ATTRIBUTE_FAM_AND_ASSEM,       "famandassem " },
324         { METHOD_ATTRIBUTE_ASSEM,               "assembly " },
325         { METHOD_ATTRIBUTE_FAMILY,              "family " },
326         { METHOD_ATTRIBUTE_FAM_OR_ASSEM,        "famorassem " },
327         { METHOD_ATTRIBUTE_PUBLIC,              "public " },
328         { 0, NULL }
329 };
330
331 static map_t method_flags_map [] = {
332         { METHOD_ATTRIBUTE_STATIC,              "static " },
333         { METHOD_ATTRIBUTE_FINAL,               "final " },
334         { METHOD_ATTRIBUTE_VIRTUAL,             "virtual " },
335         { METHOD_ATTRIBUTE_HIDE_BY_SIG,         "hidebysig " },
336         { METHOD_ATTRIBUTE_VTABLE_LAYOUT_MASK,  "newslot " },
337         { METHOD_ATTRIBUTE_ABSTRACT,            "abstract " },
338         { METHOD_ATTRIBUTE_SPECIAL_NAME,        "specialname " },
339         { METHOD_ATTRIBUTE_RT_SPECIAL_NAME,     "rtspecialname " },
340         { METHOD_ATTRIBUTE_UNMANAGED_EXPORT,    "export " },
341         { METHOD_ATTRIBUTE_HAS_SECURITY,        "hassecurity" },
342         { METHOD_ATTRIBUTE_REQUIRE_SEC_OBJECT,  "requiresecobj" },
343         { METHOD_ATTRIBUTE_PINVOKE_IMPL,        "pinvokeimpl " }, 
344         { 0, NULL }
345 };
346
347 /**
348  * method_flags:
349  *
350  * Returns a stringified version of the Method's flags
351  */
352 static char *
353 method_flags (guint32 f)
354 {
355         GString *str = g_string_new ("");
356         int access = f & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK;
357         char *s;
358         
359         g_string_append (str, map (access, method_access_map));
360         g_string_append (str, flags (f, method_flags_map));
361
362         s = str->str;
363         g_string_free (str, FALSE);
364
365         return s;
366 }
367
368 static map_t pinvoke_flags_map [] = {
369         { PINVOKE_ATTRIBUTE_NO_MANGLE ,            "nomangle " },
370         { PINVOKE_ATTRIBUTE_SUPPORTS_LAST_ERROR,   "lasterr " },
371         { 0, NULL }
372 };
373
374 static map_t pinvoke_call_conv_map [] = {
375         { PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI,      "winapi " },
376         { PINVOKE_ATTRIBUTE_CALL_CONV_CDECL,       "cdecl " },
377         { PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL,     "stdcall " },
378         { PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL,    "thiscall " },
379         { PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL,    "fastcall " },
380         { 0, NULL }
381 };
382
383 static map_t pinvoke_char_set_map [] = {
384         { PINVOKE_ATTRIBUTE_CHAR_SET_NOT_SPEC,     "" },
385         { PINVOKE_ATTRIBUTE_CHAR_SET_ANSI,         "ansi " },
386         { PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE ,     "unicode " },
387         { PINVOKE_ATTRIBUTE_CHAR_SET_AUTO,         "autochar " },
388         { 0, NULL }
389 };
390
391 /**
392  * pinvoke_flags:
393  *
394  * Returns a stringified version of the Method's pinvoke flags
395  */
396 static char *
397 pinvoke_flags (guint32 f)
398 {
399         GString *str = g_string_new ("");
400         int cset = f & PINVOKE_ATTRIBUTE_CHAR_SET_MASK;
401         int cconv = f & PINVOKE_ATTRIBUTE_CALL_CONV_MASK;
402         char *s;
403         
404         g_string_append (str, map (cset, pinvoke_char_set_map));
405         g_string_append (str, map (cconv, pinvoke_call_conv_map));
406         g_string_append (str, flags (f, pinvoke_flags_map));
407
408         s = g_strdup(str->str);
409         g_string_free (str, FALSE);
410
411         return s;
412 }
413
414 static map_t method_impl_map [] = {
415         { METHOD_IMPL_ATTRIBUTE_IL,              "cil " },
416         { METHOD_IMPL_ATTRIBUTE_NATIVE,          "native " },
417         { METHOD_IMPL_ATTRIBUTE_OPTIL,           "optil " },
418         { METHOD_IMPL_ATTRIBUTE_RUNTIME,         "runtime " },
419         { 0, NULL }
420 };
421
422 static map_t managed_type_map [] = {
423         { METHOD_IMPL_ATTRIBUTE_UNMANAGED,       "unmanaged " },
424         { METHOD_IMPL_ATTRIBUTE_MANAGED,         "managed " },
425         { 0, NULL }
426 };
427
428 static map_t managed_impl_flags [] = {
429         { METHOD_IMPL_ATTRIBUTE_FORWARD_REF,     "fwdref " },
430         { METHOD_IMPL_ATTRIBUTE_PRESERVE_SIG,    "preservesig " },
431         { METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL,   "internalcall " },
432         { METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED,    "synchronized " },
433         { METHOD_IMPL_ATTRIBUTE_NOINLINING,      "noinline " },
434         { 0, NULL }
435 };
436
437 static char *
438 method_impl_flags (guint32 f)
439 {
440         GString *str = g_string_new ("");
441         char *s;
442         int code_type = f & METHOD_IMPL_ATTRIBUTE_CODE_TYPE_MASK;
443         int managed_type = f & METHOD_IMPL_ATTRIBUTE_MANAGED_MASK;
444
445         g_string_append (str, map (code_type, method_impl_map));
446         g_string_append (str, map (managed_type, managed_type_map));
447         g_string_append (str, flags (f, managed_impl_flags));
448         
449         s = str->str;
450         g_string_free (str, FALSE);
451         return s;
452 }
453
454 static void
455 dis_locals (MonoImage *m, MonoMethodHeader *mh) 
456 {
457         int i;
458
459         fprintf(output, "\t.locals %s(\n", mh->init_locals ? "init " : "");
460         for (i=0; i < mh->num_locals; ++i) {
461                 char * desc;
462                 if (i)
463                         fprintf(output, ",\n");
464                 /* print also byref and pinned attributes */
465                 desc = dis_stringify_type (m, mh->locals[i]);
466                 fprintf(output, "\t\t%s\tV_%d", desc, i);
467                 g_free(desc);
468         }
469         fprintf(output, ")\n");
470 }
471
472 static void
473 dis_code (MonoImage *m, guint32 rva)
474 {
475         MonoMethodHeader *mh;
476         MonoCLIImageInfo *ii = m->image_info;
477         const char *ptr = mono_cli_rva_map (ii, rva);
478         const char *loc;
479         guint32 entry_point;
480
481         if (rva == 0)
482                 return;
483
484         mh = mono_metadata_parse_mh (m, ptr);
485         if ((entry_point = mono_image_get_entry_point (m))){
486                 loc = mono_metadata_locate_token (m, entry_point);
487                 if (rva == read32 (loc))
488                         fprintf (output, "\t.entrypoint\n");
489         }
490         
491         fprintf (output, "\t// Code size %d (0x%x)\n", mh->code_size, mh->code_size);
492         fprintf (output, "\t.maxstack %d\n", mh->max_stack);
493         if (mh->num_locals)
494                 dis_locals (m, mh);
495         dissasemble_cil (m, mh);
496         
497 /*
498   hex_dump (mh->code, 0, mh->code_size);
499   printf ("\nAfter the code\n");
500   hex_dump (mh->code + mh->code_size, 0, 64);
501 */
502         mono_metadata_free_mh (mh);
503 }
504
505 static char *
506 pinvoke_info (MonoImage *m, guint32 mindex)
507 {
508         MonoTableInfo *im = &m->tables [MONO_TABLE_IMPLMAP];
509         MonoTableInfo *mr = &m->tables [MONO_TABLE_MODULEREF];
510         guint32 im_cols [MONO_IMPLMAP_SIZE];
511         guint32 mr_cols [MONO_MODULEREF_SIZE];
512         const char *import, *scope;
513         char *flags;
514         int i;
515
516         for (i = 0; i < im->rows; i++) {
517
518                 mono_metadata_decode_row (im, i, im_cols, MONO_IMPLMAP_SIZE);
519
520                 if ((im_cols [MONO_IMPLMAP_MEMBER] >> 1) == mindex + 1) {
521
522                         flags = pinvoke_flags (im_cols [MONO_IMPLMAP_FLAGS]);
523
524                         import = mono_metadata_string_heap (m, im_cols [MONO_IMPLMAP_NAME]);
525
526                         mono_metadata_decode_row (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, 
527                                                   mr_cols, MONO_MODULEREF_SIZE);
528
529                         scope = mono_metadata_string_heap (m, mr_cols [MONO_MODULEREF_NAME]);
530                                 
531                         return g_strdup_printf ("(\"%s\" as \"%s\" %s)", scope, import,
532                                                 flags);
533                         g_free (flags);
534                 }
535         }
536
537         return NULL;
538 }
539
540 static void
541 cattrs_for_method (MonoImage *m, guint32 midx, MonoMethodSignature *sig) {
542         MonoTableInfo *methodt;
543         MonoTableInfo *paramt;
544         guint param_index, lastp, i, pid;
545
546         methodt = &m->tables [MONO_TABLE_METHOD];
547         paramt = &m->tables [MONO_TABLE_PARAM];
548         param_index = mono_metadata_decode_row_col (methodt, midx, MONO_METHOD_PARAMLIST);
549         if (midx + 1 < methodt->rows)
550                 lastp = mono_metadata_decode_row_col (methodt, midx + 1, MONO_METHOD_PARAMLIST);
551         else
552                 lastp = paramt->rows + 1;
553         for (i = param_index; i < lastp; ++i) {
554                 pid = mono_metadata_decode_row_col (paramt, i - 1, MONO_PARAM_SEQUENCE);
555                 fprintf (output, "\t.param [%d]\n", pid);
556                 dump_cattrs (m, MONO_TOKEN_PARAM_DEF | i, "\t");
557         }
558 }
559
560 /**
561  * dis_method_list:
562  * @m: metadata context
563  * @start: starting index into the Method Table.
564  * @end: ending index into Method table.
565  *
566  * This routine displays the methods in the Method Table from @start to @end
567  */
568 static void
569 dis_method_list (const char *klass_name, MonoImage *m, guint32 start, guint32 end)
570 {
571         MonoTableInfo *t = &m->tables [MONO_TABLE_METHOD];
572         guint32 cols [MONO_METHOD_SIZE];
573         int i;
574
575         if (end > t->rows){
576                 fprintf (output, "ERROR index out of range in methods");
577                 /*exit (1);*/
578                 end = t->rows;
579         }
580
581         for (i = start; i < end; i++){
582                 MonoMethodSignature *ms;
583                 char *flags, *impl_flags;
584                 const char *sig;
585                 char *sig_str;
586                 
587                 mono_metadata_decode_row (t, i, cols, MONO_METHOD_SIZE);
588
589                 flags = method_flags (cols [MONO_METHOD_FLAGS]);
590                 impl_flags = method_impl_flags (cols [MONO_METHOD_IMPLFLAGS]);
591
592                 sig = mono_metadata_blob_heap (m, cols [MONO_METHOD_SIGNATURE]);
593                 mono_metadata_decode_blob_size (sig, &sig);
594                 ms = mono_metadata_parse_method_signature (m, i + 1, sig, &sig);
595                 sig_str = dis_stringify_method_signature (m, ms, i + 1, FALSE);
596
597                 fprintf (output, "    // method line %d\n", i + 1);
598                 fprintf (output, "    .method %s", flags);
599
600                 if ((cols [MONO_METHOD_FLAGS] & METHOD_ATTRIBUTE_PINVOKE_IMPL) && (cols [MONO_METHOD_RVA] == 0))
601                         fprintf (output, "%s", pinvoke_info (m, i));
602
603                 fprintf (output, "\n           %s", sig_str);
604                 fprintf (output, " %s\n", impl_flags);
605                 g_free (flags);
606                 g_free (impl_flags);
607                 
608                 fprintf (output, "    {\n");
609                 dump_cattrs (m, MONO_TOKEN_METHOD_DEF | (i + 1), "        ");
610                 cattrs_for_method (m, i, ms);
611                 /* FIXME: need to sump also param custom attributes */
612                 fprintf (output, "        // Method begins at RVA 0x%x\n", cols [MONO_METHOD_RVA]);
613                 if (cols [MONO_METHOD_IMPLFLAGS] & METHOD_IMPL_ATTRIBUTE_NATIVE)
614                         fprintf (output, "          // Disassembly of native methods is not supported\n");
615                 else
616                         dis_code (m, cols [MONO_METHOD_RVA]);
617                 fprintf (output, "    } // end of method %s::%s\n\n", klass_name, sig_str);
618                 mono_metadata_free_method_signature (ms);
619                 g_free (sig_str);
620         }
621 }
622
623 typedef struct {
624         MonoTableInfo *t;
625         guint32 col_idx;
626         guint32 idx;
627         guint32 result;
628 } plocator_t;
629
630 static int
631 table_locator (const void *a, const void *b)
632 {
633         plocator_t *loc = (plocator_t *) a;
634         const char *bb = (const char *) b;
635         guint32 table_index = (bb - loc->t->base) / loc->t->row_size;
636         guint32 col;
637         
638         col = mono_metadata_decode_row_col (loc->t, table_index, loc->col_idx);
639
640         if (loc->idx == col) {
641                 loc->result = table_index;
642                 return 0;
643         }
644         if (loc->idx < col)
645                 return -1;
646         else 
647                 return 1;
648 }
649
650 static void
651 dis_property_methods (MonoImage *m, guint32 prop)
652 {
653         guint start, end;
654         MonoTableInfo *msemt = &m->tables [MONO_TABLE_METHODSEMANTICS];
655         guint32 cols [MONO_METHOD_SEMA_SIZE];
656         char *sig;
657         const char *type[] = {NULL, ".set", ".get", NULL, ".other"};
658
659         start = mono_metadata_methods_from_property (m, prop, &end);
660         while (start < end) {
661                 mono_metadata_decode_row (msemt, start, cols, MONO_METHOD_SEMA_SIZE);
662                 sig = dis_stringify_method_signature (m, NULL, cols [MONO_METHOD_SEMA_METHOD], TRUE);
663                 fprintf (output, "\t\t%s %s\n", type [cols [MONO_METHOD_SEMA_SEMANTICS]], sig);
664                 g_free (sig);
665                 ++start;
666         }
667 }
668
669 static char*
670 dis_property_signature (MonoImage *m, guint32 prop_idx)
671 {
672         MonoTableInfo *propt = &m->tables [MONO_TABLE_PROPERTY];
673         const char *ptr;
674         guint32 pcount, i;
675         guint32 cols [MONO_PROPERTY_SIZE];
676         MonoType *type;
677         MonoType *param;
678         char *blurb;
679         const char *name;
680         int prop_flags;
681         GString *res = g_string_new ("");
682
683         mono_metadata_decode_row (propt, prop_idx, cols, MONO_PROPERTY_SIZE);
684         name = mono_metadata_string_heap (m, cols [MONO_PROPERTY_NAME]);
685         prop_flags = cols [MONO_PROPERTY_FLAGS];
686         ptr = mono_metadata_blob_heap (m, cols [MONO_PROPERTY_TYPE]);
687         mono_metadata_decode_blob_size (ptr, &ptr);
688         /* ECMA claims 0x08 ... */
689         if (*ptr != 0x28 && *ptr != 0x08)
690                 g_warning("incorrect signature in propert blob: 0x%x", *ptr);
691         ptr++;
692         pcount = mono_metadata_decode_value (ptr, &ptr);
693         type = mono_metadata_parse_type (m, MONO_PARSE_TYPE, 0, ptr, &ptr);
694         blurb = dis_stringify_type (m, type);
695         if (prop_flags & 0x0200)
696                 g_string_append (res, "specialname ");
697         if (prop_flags & 0x0400)
698                 g_string_append (res, "rtspecialname ");
699         g_string_sprintfa (res, "%s %s (", blurb, name);
700         g_free (blurb);
701         mono_metadata_free_type (type);
702         for (i = 0; i < pcount; i++) {
703                 if (i)
704                         g_string_append (res, ", ");
705                 param = mono_metadata_parse_param (m, ptr, &ptr);
706                 blurb = dis_stringify_param (m, param);
707                 g_string_append (res, blurb);
708                 mono_metadata_free_type (param);
709                 g_free (blurb);
710         }
711         g_string_append_c (res, ')');
712         blurb = res->str;
713         g_string_free (res, FALSE);
714         return blurb;
715
716 }
717
718 static void
719 dis_property_list (MonoImage *m, guint32 typedef_row)
720 {
721         guint start, end, i;
722         start = mono_metadata_properties_from_typedef (m, typedef_row, &end);
723
724         for (i = start; i < end; ++i) {
725                 char *sig = dis_property_signature (m, i);
726                 fprintf (output, "\t.property %s\n\t{\n", sig);
727                 dump_cattrs (m, MONO_TOKEN_PROPERTY | (i + 1), "\t\t");
728                 dis_property_methods (m, i);
729                 fprintf (output, "\t}\n");
730                 g_free (sig);
731         }
732 }
733
734 static char*
735 dis_event_signature (MonoImage *m, guint32 event_idx)
736 {
737         MonoTableInfo *et = &m->tables [MONO_TABLE_EVENT];
738         char *type, *res, *esname;
739         guint32 cols [MONO_EVENT_SIZE];
740         
741         mono_metadata_decode_row (et, event_idx, cols, MONO_EVENT_SIZE);
742         esname = get_escaped_name (mono_metadata_string_heap (m, cols [MONO_EVENT_NAME]));
743         type = get_typedef_or_ref (m, cols [MONO_EVENT_TYPE]);
744
745         res = g_strdup_printf ("%s %s", type, esname);
746         g_free (type);
747         g_free (esname);
748         return res;
749 }
750
751 static void
752 dis_event_methods (MonoImage *m, guint32 event)
753 {
754         guint start, end;
755         MonoTableInfo *msemt = &m->tables [MONO_TABLE_METHODSEMANTICS];
756         guint32 cols [MONO_METHOD_SEMA_SIZE];
757         char *sig;
758         const char *type = "";
759
760         start = mono_metadata_methods_from_event (m, event, &end);
761         while (start < end) {
762                 mono_metadata_decode_row (msemt, start, cols, MONO_METHOD_SEMA_SIZE);
763                 sig = dis_stringify_method_signature (m, NULL, cols [MONO_METHOD_SEMA_METHOD], TRUE);
764                 switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
765                 case METHOD_SEMANTIC_OTHER:
766                         type = ".other"; break;
767                 case METHOD_SEMANTIC_ADD_ON:
768                         type = ".addon"; break;
769                 case METHOD_SEMANTIC_REMOVE_ON:
770                         type = ".removeon"; break;
771                 case METHOD_SEMANTIC_FIRE:
772                         type = ".fire"; break;
773                 default:
774                         break;
775                 }
776                 fprintf (output, "\t\t%s %s\n", type, sig);
777                 g_free (sig);
778                 ++start;
779         }
780 }
781
782 static void
783 dis_event_list (MonoImage *m, guint32 typedef_row)
784 {
785         guint start, end, i;
786         start = mono_metadata_events_from_typedef (m, typedef_row, &end);
787
788         for (i = start; i < end; ++i) {
789                 char *sig = dis_event_signature (m, i);
790                 fprintf (output, "\t.event %s\n\t{\n", sig);
791                 dump_cattrs (m, MONO_TOKEN_EVENT | (i + 1), "\t\t");
792                 dis_event_methods (m, i);
793                 fprintf (output, "\t}\n");
794                 g_free (sig);
795         }
796 }
797
798 static void
799 dis_interfaces (MonoImage *m, guint32 typedef_row)
800 {
801         plocator_t loc;
802         guint start;
803         gboolean first_interface = 1;
804         guint32 cols [MONO_INTERFACEIMPL_SIZE];
805         char *intf;
806         MonoTableInfo *table = &m->tables [MONO_TABLE_INTERFACEIMPL];
807
808         if (!table->base)
809                 return;
810
811         loc.t = table;
812         loc.col_idx = MONO_INTERFACEIMPL_CLASS;
813         loc.idx = typedef_row;
814
815         if (!bsearch (&loc, table->base, table->rows, table->row_size, table_locator))
816                 return;
817
818         start = loc.result;
819         /*
820          * We may end up in the middle of the rows... 
821          */
822         while (start > 0) {
823                 if (loc.idx == mono_metadata_decode_row_col (table, start - 1, MONO_INTERFACEIMPL_CLASS))
824                         start--;
825                 else
826                         break;
827         }
828         while (start < table->rows) {
829                 mono_metadata_decode_row (table, start, cols, MONO_INTERFACEIMPL_SIZE);
830                 if (cols [MONO_INTERFACEIMPL_CLASS] != loc.idx)
831                         break;
832                 intf = get_typedef_or_ref (m, cols [MONO_INTERFACEIMPL_INTERFACE]);
833                 if (first_interface) {
834                         fprintf (output, "  \timplements %s", intf);
835                         first_interface = 0;
836                 } else {
837                         fprintf (output, ", %s", intf);
838                 }
839                 g_free (intf);
840                 ++start;
841         }
842 }
843
844 /**
845  * dis_generic_param_and_constraints:
846  * @m: metadata context
847  * @table_type: Type of table (0 for typedef, 1 for methoddef)
848  * @row: Row in table
849  *
850  * Dissasembles the generic parameters for this type or method, also
851  * returns an allocated GString containing the generic constraints NULL
852  * if their are no generic constraints.
853  */
854 static GString*
855 dis_generic_param_and_constraints (MonoImage *m, int table_type, guint32 typedef_row)
856 {
857         MonoTableInfo *t = &m->tables [MONO_TABLE_GENERICPARAM];
858         MonoTableInfo *ct = &m->tables [MONO_TABLE_GENERICPARAMCONSTRAINT];
859         GString* cnst_block = NULL;
860         guint32 cols [MONO_GENERICPARAM_SIZE];
861         guint32 ccols [MONO_GENPARCONSTRAINT_SIZE];
862         int i, own_tok, table, idx, found_count, cnst_start, cnst_ind;
863
864         g_assert (table_type != MONO_TYPEORMETHOD_TYPE || table_type != MONO_TYPEORMETHOD_METHOD);
865         
866         found_count = cnst_start = 0;
867         for (i = 1; i <= t->rows; i++) {
868                 mono_metadata_decode_row (t, i-1, cols, MONO_GENERICPARAM_SIZE);
869                 own_tok = cols [MONO_GENERICPARAM_OWNER];
870                 table = own_tok & MONO_TYPEORMETHOD_MASK;
871                 idx = own_tok >> MONO_TYPEORMETHOD_BITS;
872                 
873                 if (table != table_type || idx != typedef_row)
874                         continue;
875
876                 if (found_count == 0)
877                         fprintf (output, "<%s", mono_metadata_string_heap (m, cols [MONO_GENERICPARAM_NAME]));
878                 else
879                         fprintf (output, ", %s", mono_metadata_string_heap (m, cols [MONO_GENERICPARAM_NAME]));
880
881                 for (cnst_ind = cnst_start; cnst_ind < ct->rows; cnst_ind++) {
882                         char *sig;
883                         mono_metadata_decode_row (ct, cnst_ind, ccols, MONO_GENPARCONSTRAINT_SIZE);
884                         if (ccols [MONO_GENPARCONSTRAINT_GENERICPAR] != i)
885                                 continue;
886                         if (cnst_block == NULL)
887                                 cnst_block = g_string_new ("");
888                         sig = get_typedef_or_ref (m, ccols [MONO_GENPARCONSTRAINT_CONSTRAINT]);
889                         g_string_append_printf (cnst_block, "    .constraint !%d is %s\n",
890                                         cols [MONO_GENERICPARAM_NUMBER], sig);
891                         g_free (sig);
892                         cnst_start = cnst_ind;
893                 }
894                 
895                 found_count++;
896         }
897
898         if (found_count)
899                 fprintf (output, ">");
900
901         return cnst_block;
902 }
903
904 /**
905  * dis_type:
906  * @m: metadata context
907  * @n: index of type to disassemble
908  *
909  * Disassembles the type whose index in the TypeDef table is @n.
910  */
911 static void
912 dis_type (MonoImage *m, int n)
913 {
914         MonoTableInfo *t = &m->tables [MONO_TABLE_TYPEDEF];
915         GString *cnst_block = NULL;
916         guint32 cols [MONO_TYPEDEF_SIZE];
917         guint32 cols_next [MONO_TYPEDEF_SIZE];
918         const char *name, *nspace;
919         char *esname;
920         guint32 packing_size, class_size;
921         gboolean next_is_valid, last;
922         guint32 nested;
923
924         mono_metadata_decode_row (t, n, cols, MONO_TYPEDEF_SIZE);
925
926         if (t->rows > n + 1) {
927                 mono_metadata_decode_row (t, n + 1, cols_next, MONO_TYPEDEF_SIZE);
928                 next_is_valid = 1;
929         } else
930                 next_is_valid = 0;
931
932         name = mono_metadata_string_heap (m, cols [MONO_TYPEDEF_NAME]);
933         nspace = mono_metadata_string_heap (m, cols [MONO_TYPEDEF_NAMESPACE]);
934         if (*nspace)
935                 fprintf (output, ".namespace %s\n{\n", nspace);
936
937         esname = get_escaped_name (name);
938         if ((cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_CLASS_SEMANTIC_MASK) == TYPE_ATTRIBUTE_CLASS){
939                 fprintf (output, "  .class %s%s", typedef_flags (cols [MONO_TYPEDEF_FLAGS]), esname);
940                 
941                 cnst_block = dis_generic_param_and_constraints (m, MONO_TYPEORMETHOD_TYPE, n+1);
942                 fprintf (output, "\n");
943                 if (cols [MONO_TYPEDEF_EXTENDS]) {
944                         char *base = get_typedef_or_ref (m, cols [MONO_TYPEDEF_EXTENDS]);
945                         fprintf (output, "  \textends %s\n", base);
946                         g_free (base);
947                 }
948         } else
949                 fprintf (output, "  .class interface %s%s\n", typedef_flags (cols [MONO_TYPEDEF_FLAGS]), esname);
950         g_free (esname);
951         dis_interfaces (m, n + 1);
952         fprintf (output, "  {\n");
953         if (cnst_block) {
954                 fprintf (output, "%s", cnst_block->str);
955                 g_string_free (cnst_block, TRUE);
956         }
957         dump_cattrs (m, MONO_TOKEN_TYPE_DEF | (n + 1), "    ");
958
959         if (mono_metadata_packing_from_typedef (m, n + 1, &packing_size, &class_size)) {
960                 fprintf (output, "    .pack %d\n", packing_size);
961                 fprintf (output, "    .size %d\n", class_size);
962         }
963         /*
964          * The value in the table is always valid, we know we have fields
965          * if the value stored is different than the next record.
966          */
967
968         if (next_is_valid)
969                 last = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
970         else
971                 last = m->tables [MONO_TABLE_FIELD].rows;
972                         
973         if (cols [MONO_TYPEDEF_FIELD_LIST] && cols [MONO_TYPEDEF_FIELD_LIST] <= m->tables [MONO_TABLE_FIELD].rows)
974                 dis_field_list (m, cols [MONO_TYPEDEF_FIELD_LIST] - 1, last);
975         fprintf (output, "\n");
976
977         if (next_is_valid)
978                 last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
979         else
980                 last = m->tables [MONO_TABLE_METHOD].rows;
981         
982         if (cols [MONO_TYPEDEF_METHOD_LIST] && cols [MONO_TYPEDEF_METHOD_LIST] <= m->tables [MONO_TABLE_METHOD].rows)
983                 dis_method_list (name, m, cols [MONO_TYPEDEF_METHOD_LIST] - 1, last);
984
985         dis_property_list (m, n);
986         dis_event_list (m, n);
987
988         t = &m->tables [MONO_TABLE_NESTEDCLASS];
989         nested = mono_metadata_nesting_typedef (m, n + 1, 1);
990         while (nested) {
991                 dis_type (m, mono_metadata_decode_row_col (t, nested - 1, MONO_NESTED_CLASS_NESTED) - 1);
992                 nested = mono_metadata_nesting_typedef (m, n + 1, nested + 1);
993         }
994         
995         fprintf (output, "  } // end of type %s%s%s\n", nspace, *nspace? ".": "", name);
996         if (*nspace)
997                 fprintf (output, "}\n");
998         fprintf (output, "\n");
999 }
1000
1001
1002 /**
1003  * dis_globals
1004  * @m: metadata context
1005  *
1006  * disassembles all the global fields and methods
1007  */
1008 static void
1009 dis_globals (MonoImage *m)
1010 {
1011         MonoTableInfo *t = &m->tables [MONO_TABLE_TYPEDEF];
1012         guint32 cols [MONO_TYPEDEF_SIZE];
1013         guint32 cols_next [MONO_TYPEDEF_SIZE];
1014         gboolean next_is_valid, last;
1015         gchar *name;
1016
1017         name = g_strdup ("<Module>");
1018
1019         mono_metadata_decode_row (t, 0, cols, MONO_TYPEDEF_SIZE);
1020
1021         if (t->rows > 1) {
1022                 mono_metadata_decode_row (t, 1, cols_next, MONO_TYPEDEF_SIZE);
1023                 next_is_valid = 1;
1024         } else
1025                 next_is_valid = 0;
1026         
1027         /*
1028          * The value in the table is always valid, we know we have fields
1029          * if the value stored is different than the next record.
1030          */
1031
1032         if (next_is_valid)
1033                 last = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
1034         else
1035                 last = m->tables [MONO_TABLE_FIELD].rows;
1036                         
1037         if (cols [MONO_TYPEDEF_FIELD_LIST] && cols [MONO_TYPEDEF_FIELD_LIST] <= m->tables [MONO_TABLE_FIELD].rows)
1038                 dis_field_list (m, cols [MONO_TYPEDEF_FIELD_LIST] - 1, last);
1039         fprintf (output, "\n");
1040
1041         if (next_is_valid)
1042                 last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
1043         else
1044                 last = m->tables [MONO_TABLE_METHOD].rows;
1045         
1046         if (cols [MONO_TYPEDEF_METHOD_LIST] && cols [MONO_TYPEDEF_METHOD_LIST] <= m->tables [MONO_TABLE_METHOD].rows)
1047                 dis_method_list (name, m, cols [MONO_TYPEDEF_METHOD_LIST] - 1, last);
1048
1049 }
1050
1051 /**
1052  * dis_types:
1053  * @m: metadata context
1054  *
1055  * disassembles all types in the @m context
1056  */
1057 static void
1058 dis_types (MonoImage *m)
1059 {
1060         MonoTableInfo *t = &m->tables [MONO_TABLE_TYPEDEF];
1061         int i;
1062         guint32 flags;
1063
1064         dis_globals (m);
1065         
1066         for (i = 1; i < t->rows; i++) {
1067                 flags = mono_metadata_decode_row_col (t, i, MONO_TYPEDEF_FLAGS);
1068                 flags &= TYPE_ATTRIBUTE_VISIBILITY_MASK;
1069                 if (flags == TYPE_ATTRIBUTE_PUBLIC || flags == TYPE_ATTRIBUTE_NOT_PUBLIC)
1070                         dis_type (m, i);
1071         }
1072 }
1073
1074 /**
1075  * dis_data:
1076  * @m: metadata context
1077  *
1078  * disassembles all data blobs references in the FieldRVA table in the @m context
1079  */
1080 static void
1081 dis_data (MonoImage *m)
1082 {
1083         MonoTableInfo *t = &m->tables [MONO_TABLE_FIELDRVA];
1084         MonoTableInfo *ft = &m->tables [MONO_TABLE_FIELD];
1085         int i, b;
1086         const char *rva, *sig;
1087         guint32 align, size;
1088         guint32 cols [MONO_FIELD_RVA_SIZE];
1089         MonoType *type;
1090
1091         for (i = 0; i < t->rows; i++) {
1092                 mono_metadata_decode_row (t, i, cols, MONO_FIELD_RVA_SIZE);
1093                 rva = mono_cli_rva_map (m->image_info, cols [MONO_FIELD_RVA_RVA]);
1094                 sig = mono_metadata_blob_heap (m, mono_metadata_decode_row_col (ft, cols [MONO_FIELD_RVA_FIELD] -1, MONO_FIELD_SIGNATURE));
1095                 mono_metadata_decode_value (sig, &sig);
1096                 /* FIELD signature == 0x06 */
1097                 g_assert (*sig == 0x06);
1098                 type = mono_metadata_parse_field_type (m, 0, sig + 1, &sig);
1099                 mono_class_init (mono_class_from_mono_type (type));
1100                 size = mono_type_size (type, &align);
1101                 fprintf (output, ".data D_%08x = bytearray (", cols [MONO_FIELD_RVA_RVA]);
1102                 for (b = 0; b < size; ++b) {
1103                         if (!(b % 16))
1104                                 fprintf (output, "\n\t");
1105                         fprintf (output, " %02X", rva [b] & 0xff);
1106                 }
1107                 fprintf (output, ") // size: %d\n", size);
1108         }
1109 }
1110
1111 struct {
1112         const char *name;
1113         int table;
1114         void (*dumper) (MonoImage *m);
1115 } table_list [] = {
1116         { "--assembly",    MONO_TABLE_ASSEMBLY,         dump_table_assembly },
1117         { "--assemblyref", MONO_TABLE_ASSEMBLYREF,      dump_table_assemblyref },
1118         { "--classlayout", MONO_TABLE_CLASSLAYOUT,      dump_table_class_layout },
1119         { "--constant",    MONO_TABLE_CONSTANT,         dump_table_constant },
1120         { "--customattr",  MONO_TABLE_CUSTOMATTRIBUTE,  dump_table_customattr },
1121         { "--declsec",     MONO_TABLE_DECLSECURITY,     dump_table_declsec },
1122         { "--event",       MONO_TABLE_EVENT,            dump_table_event },
1123         { "--exported",    MONO_TABLE_EXPORTEDTYPE,     dump_table_exported },
1124         { "--fields",      MONO_TABLE_FIELD,            dump_table_field },
1125         { "--file",        MONO_TABLE_FILE,             dump_table_file },
1126         { "--genericpar",  MONO_TABLE_GENERICPARAM,     dump_table_genericpar },
1127         { "--interface",   MONO_TABLE_INTERFACEIMPL,    dump_table_interfaceimpl },
1128         { "--manifest",    MONO_TABLE_MANIFESTRESOURCE, dump_table_manifest },
1129         { "--marshal",     MONO_TABLE_FIELDMARSHAL,     dump_table_field_marshal },
1130         { "--memberref",   MONO_TABLE_MEMBERREF,        dump_table_memberref },
1131         { "--method",      MONO_TABLE_METHOD,           dump_table_method },
1132         { "--methodimpl",  MONO_TABLE_METHODIMPL,       dump_table_methodimpl },
1133         { "--methodsem",   MONO_TABLE_METHODSEMANTICS,  dump_table_methodsem },
1134         { "--methodspec",  MONO_TABLE_METHODSPEC,       dump_table_methodspec },
1135         { "--moduleref",   MONO_TABLE_MODULEREF,        dump_table_moduleref },
1136         { "--module",      MONO_TABLE_MODULE,           dump_table_module },
1137         { "--nested",      MONO_TABLE_NESTEDCLASS,      dump_table_nestedclass },
1138         { "--param",       MONO_TABLE_PARAM,            dump_table_param },
1139         { "--parconst",    MONO_TABLE_GENERICPARAMCONSTRAINT, dump_table_parconstraint },
1140         { "--property",    MONO_TABLE_PROPERTY,         dump_table_property },
1141         { "--propertymap", MONO_TABLE_PROPERTYMAP,      dump_table_property_map },
1142         { "--typedef",     MONO_TABLE_TYPEDEF,          dump_table_typedef },
1143         { "--typeref",     MONO_TABLE_TYPEREF,          dump_table_typeref },
1144         { "--typespec",    MONO_TABLE_TYPESPEC,         dump_table_typespec },
1145         { "--implmap",     MONO_TABLE_IMPLMAP,          dump_table_implmap },
1146         { NULL, -1 }
1147 };
1148
1149 /**
1150  * disassemble_file:
1151  * @file: file containing CIL code.
1152  *
1153  * Disassembles the @file file.
1154  */
1155 static void
1156 disassemble_file (const char *file)
1157 {
1158         MonoAssembly *ass;
1159         MonoImageOpenStatus status;
1160         MonoImage *img;
1161
1162         ass = mono_assembly_open (file, &status);
1163         if (ass == NULL){
1164                 fprintf (stderr, "Error while trying to process %s\n", file);
1165                 return;
1166         }
1167
1168         img = ass->image;
1169
1170         if (dump_table != -1){
1171                 (*table_list [dump_table].dumper) (img);
1172         } else {
1173                 dump_header_data (img);
1174                 
1175                 dis_directive_assemblyref (img);
1176                 dis_directive_assembly (img);
1177                 dis_directive_file (img);
1178                 dis_directive_module (img);
1179                 dis_directive_moduleref (img);
1180                 dis_types (img);
1181                 dis_data (img);
1182         }
1183         
1184         mono_image_close (img);
1185 }
1186
1187 static void
1188 usage (void)
1189 {
1190         GString *args = g_string_new ("[--output=filename] [--help] [--mscorlib]\n");
1191         int i;
1192         
1193         for (i = 0; table_list [i].name != NULL; i++){
1194                 g_string_append (args, "[");
1195                 g_string_append (args, table_list [i].name);
1196                 g_string_append (args, "] ");
1197                 if (((i-2) % 5) == 0)
1198                         g_string_append_c (args, '\n');
1199         }
1200         fprintf (stderr,
1201                  "Usage is: monodis %s file ..\n", args->str);
1202         exit (1);
1203 }
1204
1205 int
1206 main (int argc, char *argv [])
1207 {
1208         GList *input_files = NULL, *l;
1209         int i, j;
1210
1211         output = stdout;
1212         init_key_table ();
1213         for (i = 1; i < argc; i++){
1214                 if (argv [i][0] == '-'){
1215                         if (argv [i][1] == 'h')
1216                                 usage ();
1217                         else if (argv [i][1] == 'd')
1218                                 dump_header_data_p = TRUE;
1219                         else if (strcmp (argv [i], "--mscorlib") == 0) {
1220                                 substitute_with_mscorlib_p = TRUE;
1221                                 continue;
1222                         } else if (strcmp (argv [i], "--show-method-tokens") == 0) {
1223                                 show_method_tokens = TRUE;
1224                                 continue;
1225                         } else if (strcmp (argv [i], "--show-tokens") == 0) {
1226                                 show_tokens = TRUE;
1227                                 continue;
1228                         } else if (strncmp (argv [i], "--output=", 9) == 0) {
1229                                 output = fopen (argv [i]+9, "w");
1230                                 if (output == NULL) {
1231                                         fprintf (stderr, "Can't open output file `%s': %s\n",
1232                                                  argv [i]+9, strerror (errno));
1233                                         exit (1);
1234                                 }
1235                                 continue;
1236                         } else if (strcmp (argv [i], "--help") == 0)
1237                                 usage ();
1238                         for (j = 0; table_list [j].name != NULL; j++) {
1239                                 if (strcmp (argv [i], table_list [j].name) == 0)
1240                                         dump_table = j;
1241                         }
1242                         if (dump_table < 0)
1243                                 usage ();
1244                 } else
1245                         input_files = g_list_append (input_files, argv [i]);
1246         }
1247
1248         if (input_files == NULL)
1249                 usage ();
1250         
1251         mono_init (argv [0]);
1252
1253         for (l = input_files; l; l = l->next)
1254                 disassemble_file (l->data);
1255
1256         return 0;
1257 }