2004-08-02 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 dis_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 dis_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 dis_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 dis_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 dis_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 dis_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 dis_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 dis_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 dis_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 dis_map_t managed_type_map [] = {
423         { METHOD_IMPL_ATTRIBUTE_UNMANAGED,       "unmanaged " },
424         { METHOD_IMPL_ATTRIBUTE_MANAGED,         "managed " },
425         { 0, NULL }
426 };
427
428 static dis_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, const char *ptr) 
456 {
457         int i;
458
459         if (show_tokens) {
460                 unsigned char flags = *(const unsigned char *) ptr;
461                 unsigned char format = flags & METHOD_HEADER_FORMAT_MASK;
462                 guint16 fat_flags;
463                 guint32 local_var_sig_tok, max_stack, code_size, init_locals;
464                 int hsize;
465
466                 g_assert (format == METHOD_HEADER_FAT_FORMAT);
467                 fat_flags = read16 (ptr);
468                 ptr += 2;
469                 hsize = (fat_flags >> 12) & 0xf;
470                 max_stack = read16 (ptr);
471                 ptr += 2;
472                 code_size = read32 (ptr);
473                 ptr += 4;
474                 local_var_sig_tok = read32 (ptr);
475                 ptr += 4;
476
477                 if (fat_flags & METHOD_HEADER_INIT_LOCALS)
478                         init_locals = 1;
479                 else
480                         init_locals = 0;
481
482                 fprintf(output, "\t.locals /*%08x*/ %s(\n",
483                         local_var_sig_tok, init_locals ? "init " : "");
484         } else
485                 fprintf(output, "\t.locals %s(\n", mh->init_locals ? "init " : "");
486
487         for (i=0; i < mh->num_locals; ++i) {
488                 char * desc;
489                 if (i)
490                         fprintf(output, ",\n");
491                 /* print also byref and pinned attributes */
492                 desc = dis_stringify_type (m, mh->locals[i]);
493                 fprintf(output, "\t\t%s\tV_%d", desc, i);
494                 g_free(desc);
495         }
496         fprintf(output, ")\n");
497 }
498
499 static void
500 dis_code (MonoImage *m, guint32 rva)
501 {
502         MonoMethodHeader *mh;
503         const char *ptr = mono_image_rva_map (m, rva);
504         const char *loc;
505         guint32 entry_point;
506
507         if (rva == 0)
508                 return;
509
510         mh = mono_metadata_parse_mh (m, ptr);
511         if ((entry_point = mono_image_get_entry_point (m))){
512                 loc = mono_metadata_locate_token (m, entry_point);
513                 if (rva == read32 (loc))
514                         fprintf (output, "\t.entrypoint\n");
515         }
516         
517         fprintf (output, "\t// Code size %d (0x%x)\n", mh->code_size, mh->code_size);
518         fprintf (output, "\t.maxstack %d\n", mh->max_stack);
519         if (mh->num_locals)
520                 dis_locals (m, mh, ptr);
521         dissasemble_cil (m, mh);
522         
523 /*
524   hex_dump (mh->code, 0, mh->code_size);
525   printf ("\nAfter the code\n");
526   hex_dump (mh->code + mh->code_size, 0, 64);
527 */
528         mono_metadata_free_mh (mh);
529 }
530
531 static char *
532 pinvoke_info (MonoImage *m, guint32 mindex)
533 {
534         MonoTableInfo *im = &m->tables [MONO_TABLE_IMPLMAP];
535         MonoTableInfo *mr = &m->tables [MONO_TABLE_MODULEREF];
536         guint32 im_cols [MONO_IMPLMAP_SIZE];
537         guint32 mr_cols [MONO_MODULEREF_SIZE];
538         const char *import, *scope;
539         char *flags;
540         int i;
541
542         for (i = 0; i < im->rows; i++) {
543
544                 mono_metadata_decode_row (im, i, im_cols, MONO_IMPLMAP_SIZE);
545
546                 if ((im_cols [MONO_IMPLMAP_MEMBER] >> 1) == mindex + 1) {
547
548                         flags = pinvoke_flags (im_cols [MONO_IMPLMAP_FLAGS]);
549
550                         import = mono_metadata_string_heap (m, im_cols [MONO_IMPLMAP_NAME]);
551
552                         mono_metadata_decode_row (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, 
553                                                   mr_cols, MONO_MODULEREF_SIZE);
554
555                         scope = mono_metadata_string_heap (m, mr_cols [MONO_MODULEREF_NAME]);
556                                 
557                         return g_strdup_printf ("(\"%s\" as \"%s\" %s)", scope, import,
558                                                 flags);
559                         g_free (flags);
560                 }
561         }
562
563         return NULL;
564 }
565
566 static void
567 cattrs_for_method (MonoImage *m, guint32 midx, MonoMethodSignature *sig) {
568         MonoTableInfo *methodt;
569         MonoTableInfo *paramt;
570         guint param_index, lastp, i, pid;
571
572         methodt = &m->tables [MONO_TABLE_METHOD];
573         paramt = &m->tables [MONO_TABLE_PARAM];
574         param_index = mono_metadata_decode_row_col (methodt, midx, MONO_METHOD_PARAMLIST);
575         if (midx + 1 < methodt->rows)
576                 lastp = mono_metadata_decode_row_col (methodt, midx + 1, MONO_METHOD_PARAMLIST);
577         else
578                 lastp = paramt->rows + 1;
579         for (i = param_index; i < lastp; ++i) {
580                 pid = mono_metadata_decode_row_col (paramt, i - 1, MONO_PARAM_SEQUENCE);
581                 fprintf (output, "\t.param [%d]\n", pid);
582                 dump_cattrs (m, MONO_TOKEN_PARAM_DEF | i, "\t");
583         }
584 }
585
586 /**
587  * dis_method_list:
588  * @m: metadata context
589  * @start: starting index into the Method Table.
590  * @end: ending index into Method table.
591  *
592  * This routine displays the methods in the Method Table from @start to @end
593  */
594 static void
595 dis_method_list (const char *klass_name, MonoImage *m, guint32 start, guint32 end)
596 {
597         MonoTableInfo *t = &m->tables [MONO_TABLE_METHOD];
598         guint32 cols [MONO_METHOD_SIZE];
599         int i;
600
601         if (end > t->rows){
602                 fprintf (output, "ERROR index out of range in methods");
603                 /*exit (1);*/
604                 end = t->rows;
605         }
606
607         for (i = start; i < end; i++){
608                 MonoMethodSignature *ms;
609                 char *flags, *impl_flags;
610                 const char *sig;
611                 char *sig_str;
612                 
613                 mono_metadata_decode_row (t, i, cols, MONO_METHOD_SIZE);
614
615                 flags = method_flags (cols [MONO_METHOD_FLAGS]);
616                 impl_flags = method_impl_flags (cols [MONO_METHOD_IMPLFLAGS]);
617
618                 sig = mono_metadata_blob_heap (m, cols [MONO_METHOD_SIGNATURE]);
619                 mono_metadata_decode_blob_size (sig, &sig);
620                 ms = mono_metadata_parse_method_signature (m, i + 1, sig, &sig);
621                 sig_str = dis_stringify_method_signature (m, ms, i + 1, FALSE);
622
623                 fprintf (output, "    // method line %d\n", i + 1);
624                 fprintf (output, "    .method %s", flags);
625
626                 if ((cols [MONO_METHOD_FLAGS] & METHOD_ATTRIBUTE_PINVOKE_IMPL) && (cols [MONO_METHOD_RVA] == 0)) {
627                         gchar *pi = pinvoke_info (m, i);
628                         if (pi) {
629                                 fprintf (output, "%s", pi);
630                                 g_free (pi);
631                         }
632                 }
633
634                 fprintf (output, "\n           %s", sig_str);
635                 fprintf (output, " %s\n", impl_flags);
636                 g_free (flags);
637                 g_free (impl_flags);
638                 
639                 fprintf (output, "    {\n");
640                 dump_cattrs (m, MONO_TOKEN_METHOD_DEF | (i + 1), "        ");
641                 cattrs_for_method (m, i, ms);
642                 /* FIXME: need to sump also param custom attributes */
643                 fprintf (output, "        // Method begins at RVA 0x%x\n", cols [MONO_METHOD_RVA]);
644                 if (cols [MONO_METHOD_IMPLFLAGS] & METHOD_IMPL_ATTRIBUTE_NATIVE)
645                         fprintf (output, "          // Disassembly of native methods is not supported\n");
646                 else
647                         dis_code (m, cols [MONO_METHOD_RVA]);
648                 fprintf (output, "    } // end of method %s::%s\n\n", klass_name, sig_str);
649                 mono_metadata_free_method_signature (ms);
650                 g_free (sig_str);
651         }
652 }
653
654 typedef struct {
655         MonoTableInfo *t;
656         guint32 col_idx;
657         guint32 idx;
658         guint32 result;
659 } plocator_t;
660
661 static int
662 table_locator (const void *a, const void *b)
663 {
664         plocator_t *loc = (plocator_t *) a;
665         const char *bb = (const char *) b;
666         guint32 table_index = (bb - loc->t->base) / loc->t->row_size;
667         guint32 col;
668         
669         col = mono_metadata_decode_row_col (loc->t, table_index, loc->col_idx);
670
671         if (loc->idx == col) {
672                 loc->result = table_index;
673                 return 0;
674         }
675         if (loc->idx < col)
676                 return -1;
677         else 
678                 return 1;
679 }
680
681 static void
682 dis_property_methods (MonoImage *m, guint32 prop)
683 {
684         guint start, end;
685         MonoTableInfo *msemt = &m->tables [MONO_TABLE_METHODSEMANTICS];
686         guint32 cols [MONO_METHOD_SEMA_SIZE];
687         char *sig;
688         const char *type[] = {NULL, ".set", ".get", NULL, ".other"};
689
690         start = mono_metadata_methods_from_property (m, prop, &end);
691         while (start < end) {
692                 mono_metadata_decode_row (msemt, start, cols, MONO_METHOD_SEMA_SIZE);
693                 sig = dis_stringify_method_signature (m, NULL, cols [MONO_METHOD_SEMA_METHOD], TRUE);
694                 fprintf (output, "\t\t%s %s\n", type [cols [MONO_METHOD_SEMA_SEMANTICS]], sig);
695                 g_free (sig);
696                 ++start;
697         }
698 }
699
700 static char*
701 dis_property_signature (MonoImage *m, guint32 prop_idx)
702 {
703         MonoTableInfo *propt = &m->tables [MONO_TABLE_PROPERTY];
704         const char *ptr;
705         guint32 pcount, i;
706         guint32 cols [MONO_PROPERTY_SIZE];
707         MonoType *type;
708         MonoType *param;
709         char *blurb;
710         const char *name;
711         int prop_flags;
712         GString *res = g_string_new ("");
713
714         mono_metadata_decode_row (propt, prop_idx, cols, MONO_PROPERTY_SIZE);
715         name = mono_metadata_string_heap (m, cols [MONO_PROPERTY_NAME]);
716         prop_flags = cols [MONO_PROPERTY_FLAGS];
717         ptr = mono_metadata_blob_heap (m, cols [MONO_PROPERTY_TYPE]);
718         mono_metadata_decode_blob_size (ptr, &ptr);
719         /* ECMA claims 0x08 ... */
720         if (*ptr != 0x28 && *ptr != 0x08)
721                 g_warning("incorrect signature in propert blob: 0x%x", *ptr);
722         ptr++;
723         pcount = mono_metadata_decode_value (ptr, &ptr);
724         type = mono_metadata_parse_type (m, MONO_PARSE_TYPE, 0, ptr, &ptr);
725         blurb = dis_stringify_type (m, type);
726         if (prop_flags & 0x0200)
727                 g_string_append (res, "specialname ");
728         if (prop_flags & 0x0400)
729                 g_string_append (res, "rtspecialname ");
730         g_string_sprintfa (res, "%s %s (", blurb, name);
731         g_free (blurb);
732         mono_metadata_free_type (type);
733         for (i = 0; i < pcount; i++) {
734                 if (i)
735                         g_string_append (res, ", ");
736                 param = mono_metadata_parse_param (m, ptr, &ptr);
737                 blurb = dis_stringify_param (m, param);
738                 g_string_append (res, blurb);
739                 mono_metadata_free_type (param);
740                 g_free (blurb);
741         }
742         g_string_append_c (res, ')');
743         blurb = res->str;
744         g_string_free (res, FALSE);
745         return blurb;
746
747 }
748
749 static void
750 dis_property_list (MonoImage *m, guint32 typedef_row)
751 {
752         guint start, end, i;
753         start = mono_metadata_properties_from_typedef (m, typedef_row, &end);
754
755         for (i = start; i < end; ++i) {
756                 char *sig = dis_property_signature (m, i);
757                 fprintf (output, "\t.property %s\n\t{\n", sig);
758                 dump_cattrs (m, MONO_TOKEN_PROPERTY | (i + 1), "\t\t");
759                 dis_property_methods (m, i);
760                 fprintf (output, "\t}\n");
761                 g_free (sig);
762         }
763 }
764
765 static char*
766 dis_event_signature (MonoImage *m, guint32 event_idx)
767 {
768         MonoTableInfo *et = &m->tables [MONO_TABLE_EVENT];
769         char *type, *result, *esname;
770         guint32 cols [MONO_EVENT_SIZE];
771         int event_flags;
772         GString *res = g_string_new ("");
773         
774         mono_metadata_decode_row (et, event_idx, cols, MONO_EVENT_SIZE);
775         esname = get_escaped_name (mono_metadata_string_heap (m, cols [MONO_EVENT_NAME]));
776         type = get_typedef_or_ref (m, cols [MONO_EVENT_TYPE]);
777         event_flags = cols [MONO_EVENT_FLAGS];
778
779         if (event_flags & 0x0200)
780                 g_string_append (res, "specialname ");
781         if (event_flags & 0x0400)
782                 g_string_append (res, "rtspecialname ");
783         g_string_sprintfa (res, "%s %s", type, esname);
784
785         g_free (type);
786         g_free (esname);
787         result = res->str;
788         g_string_free (res, FALSE);
789         return result;
790 }
791
792 static void
793 dis_event_methods (MonoImage *m, guint32 event)
794 {
795         guint start, end;
796         MonoTableInfo *msemt = &m->tables [MONO_TABLE_METHODSEMANTICS];
797         guint32 cols [MONO_METHOD_SEMA_SIZE];
798         char *sig;
799         const char *type = "";
800
801         start = mono_metadata_methods_from_event (m, event, &end);
802         while (start < end) {
803                 mono_metadata_decode_row (msemt, start, cols, MONO_METHOD_SEMA_SIZE);
804                 sig = dis_stringify_method_signature (m, NULL, cols [MONO_METHOD_SEMA_METHOD], TRUE);
805                 switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
806                 case METHOD_SEMANTIC_OTHER:
807                         type = ".other"; break;
808                 case METHOD_SEMANTIC_ADD_ON:
809                         type = ".addon"; break;
810                 case METHOD_SEMANTIC_REMOVE_ON:
811                         type = ".removeon"; break;
812                 case METHOD_SEMANTIC_FIRE:
813                         type = ".fire"; break;
814                 default:
815                         break;
816                 }
817                 fprintf (output, "\t\t%s %s\n", type, sig);
818                 g_free (sig);
819                 ++start;
820         }
821 }
822
823 static void
824 dis_event_list (MonoImage *m, guint32 typedef_row)
825 {
826         guint start, end, i;
827         start = mono_metadata_events_from_typedef (m, typedef_row, &end);
828
829         for (i = start; i < end; ++i) {
830                 char *sig = dis_event_signature (m, i);
831                 fprintf (output, "\t.event %s\n\t{\n", sig);
832                 dump_cattrs (m, MONO_TOKEN_EVENT | (i + 1), "\t\t");
833                 dis_event_methods (m, i);
834                 fprintf (output, "\t}\n");
835                 g_free (sig);
836         }
837 }
838
839 static void
840 dis_interfaces (MonoImage *m, guint32 typedef_row)
841 {
842         plocator_t loc;
843         guint start;
844         gboolean first_interface = 1;
845         guint32 cols [MONO_INTERFACEIMPL_SIZE];
846         char *intf;
847         MonoTableInfo *table = &m->tables [MONO_TABLE_INTERFACEIMPL];
848
849         if (!table->base)
850                 return;
851
852         loc.t = table;
853         loc.col_idx = MONO_INTERFACEIMPL_CLASS;
854         loc.idx = typedef_row;
855
856         if (!bsearch (&loc, table->base, table->rows, table->row_size, table_locator))
857                 return;
858
859         start = loc.result;
860         /*
861          * We may end up in the middle of the rows... 
862          */
863         while (start > 0) {
864                 if (loc.idx == mono_metadata_decode_row_col (table, start - 1, MONO_INTERFACEIMPL_CLASS))
865                         start--;
866                 else
867                         break;
868         }
869         while (start < table->rows) {
870                 mono_metadata_decode_row (table, start, cols, MONO_INTERFACEIMPL_SIZE);
871                 if (cols [MONO_INTERFACEIMPL_CLASS] != loc.idx)
872                         break;
873                 intf = get_typedef_or_ref (m, cols [MONO_INTERFACEIMPL_INTERFACE]);
874                 if (first_interface) {
875                         fprintf (output, "  \timplements %s", intf);
876                         first_interface = 0;
877                 } else {
878                         fprintf (output, ", %s", intf);
879                 }
880                 g_free (intf);
881                 ++start;
882         }
883 }
884
885 /**
886  * dis_generic_param_and_constraints:
887  * @m: metadata context
888  * @table_type: Type of table (0 for typedef, 1 for methoddef)
889  * @row: Row in table
890  *
891  * Dissasembles the generic parameters for this type or method, also
892  * returns an allocated GString containing the generic constraints NULL
893  * if their are no generic constraints.
894  */
895 static GString*
896 dis_generic_param_and_constraints (MonoImage *m, int table_type, guint32 typedef_row)
897 {
898         MonoTableInfo *t = &m->tables [MONO_TABLE_GENERICPARAM];
899         MonoTableInfo *ct = &m->tables [MONO_TABLE_GENERICPARAMCONSTRAINT];
900         GString* cnst_block = NULL;
901         guint32 cols [MONO_GENERICPARAM_SIZE];
902         guint32 ccols [MONO_GENPARCONSTRAINT_SIZE];
903         int i, own_tok, table, idx, found_count, cnst_start, cnst_ind;
904
905         g_assert (table_type != MONO_TYPEORMETHOD_TYPE || table_type != MONO_TYPEORMETHOD_METHOD);
906         
907         found_count = cnst_start = 0;
908         for (i = 1; i <= t->rows; i++) {
909                 mono_metadata_decode_row (t, i-1, cols, MONO_GENERICPARAM_SIZE);
910                 own_tok = cols [MONO_GENERICPARAM_OWNER];
911                 table = own_tok & MONO_TYPEORMETHOD_MASK;
912                 idx = own_tok >> MONO_TYPEORMETHOD_BITS;
913                 
914                 if (table != table_type || idx != typedef_row)
915                         continue;
916
917                 if (found_count == 0)
918                         fprintf (output, "<");
919                 else
920                         fprintf (output, ", ");
921
922                 for (cnst_ind = cnst_start; cnst_ind < ct->rows; cnst_ind++) {
923                         char *sig;
924                         mono_metadata_decode_row (ct, cnst_ind, ccols, MONO_GENPARCONSTRAINT_SIZE);
925                         if (ccols [MONO_GENPARCONSTRAINT_GENERICPAR] != i)
926                                 continue;
927                         if (cnst_block == NULL)
928                                 cnst_block = g_string_new ("");
929                         sig = get_typedef_or_ref (m, ccols [MONO_GENPARCONSTRAINT_CONSTRAINT]);
930                         fprintf (output, "(%s) ", sig);
931                         g_free (sig);
932                         cnst_start = cnst_ind;
933                 }
934
935                 fprintf (output, "%s", mono_metadata_string_heap (m, cols [MONO_GENERICPARAM_NAME]));
936                
937                 found_count++;
938         }
939
940         if (found_count)
941                 fprintf (output, ">");
942
943         return cnst_block;
944 }
945
946 /**
947  * dis_type:
948  * @m: metadata context
949  * @n: index of type to disassemble
950  *
951  * Disassembles the type whose index in the TypeDef table is @n.
952  */
953 static void
954 dis_type (MonoImage *m, int n)
955 {
956         MonoTableInfo *t = &m->tables [MONO_TABLE_TYPEDEF];
957         GString *cnst_block = NULL;
958         guint32 cols [MONO_TYPEDEF_SIZE];
959         guint32 cols_next [MONO_TYPEDEF_SIZE];
960         const char *name, *nspace;
961         char *esname;
962         guint32 packing_size, class_size;
963         gboolean next_is_valid, last;
964         guint32 nested;
965
966         mono_metadata_decode_row (t, n, cols, MONO_TYPEDEF_SIZE);
967
968         if (t->rows > n + 1) {
969                 mono_metadata_decode_row (t, n + 1, cols_next, MONO_TYPEDEF_SIZE);
970                 next_is_valid = 1;
971         } else
972                 next_is_valid = 0;
973
974         name = mono_metadata_string_heap (m, cols [MONO_TYPEDEF_NAME]);
975         nspace = mono_metadata_string_heap (m, cols [MONO_TYPEDEF_NAMESPACE]);
976         if (*nspace)
977                 fprintf (output, ".namespace %s\n{\n", nspace);
978
979         esname = get_escaped_name (name);
980         if ((cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_CLASS_SEMANTIC_MASK) == TYPE_ATTRIBUTE_CLASS){
981                 fprintf (output, "  .class %s%s", typedef_flags (cols [MONO_TYPEDEF_FLAGS]), esname);
982                 
983                 cnst_block = dis_generic_param_and_constraints (m, MONO_TYPEORMETHOD_TYPE, n+1);
984                 fprintf (output, "\n");
985                 if (cols [MONO_TYPEDEF_EXTENDS]) {
986                         char *base = get_typedef_or_ref (m, cols [MONO_TYPEDEF_EXTENDS]);
987                         fprintf (output, "  \textends %s\n", base);
988                         g_free (base);
989                 }
990         } else
991                 fprintf (output, "  .class interface %s%s\n", typedef_flags (cols [MONO_TYPEDEF_FLAGS]), esname);
992         g_free (esname);
993         dis_interfaces (m, n + 1);
994         fprintf (output, "  {\n");
995         if (cnst_block) {
996                 fprintf (output, "%s", cnst_block->str);
997                 g_string_free (cnst_block, TRUE);
998         }
999         dump_cattrs (m, MONO_TOKEN_TYPE_DEF | (n + 1), "    ");
1000
1001         if (mono_metadata_packing_from_typedef (m, n + 1, &packing_size, &class_size)) {
1002                 fprintf (output, "    .pack %d\n", packing_size);
1003                 fprintf (output, "    .size %d\n", class_size);
1004         }
1005         /*
1006          * The value in the table is always valid, we know we have fields
1007          * if the value stored is different than the next record.
1008          */
1009
1010         if (next_is_valid)
1011                 last = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
1012         else
1013                 last = m->tables [MONO_TABLE_FIELD].rows;
1014                         
1015         if (cols [MONO_TYPEDEF_FIELD_LIST] && cols [MONO_TYPEDEF_FIELD_LIST] <= m->tables [MONO_TABLE_FIELD].rows)
1016                 dis_field_list (m, cols [MONO_TYPEDEF_FIELD_LIST] - 1, last);
1017         fprintf (output, "\n");
1018
1019         if (next_is_valid)
1020                 last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
1021         else
1022                 last = m->tables [MONO_TABLE_METHOD].rows;
1023         
1024         if (cols [MONO_TYPEDEF_METHOD_LIST] && cols [MONO_TYPEDEF_METHOD_LIST] <= m->tables [MONO_TABLE_METHOD].rows)
1025                 dis_method_list (name, m, cols [MONO_TYPEDEF_METHOD_LIST] - 1, last);
1026
1027         dis_property_list (m, n);
1028         dis_event_list (m, n);
1029
1030         t = &m->tables [MONO_TABLE_NESTEDCLASS];
1031         nested = mono_metadata_nesting_typedef (m, n + 1, 1);
1032         while (nested) {
1033                 dis_type (m, mono_metadata_decode_row_col (t, nested - 1, MONO_NESTED_CLASS_NESTED) - 1);
1034                 nested = mono_metadata_nesting_typedef (m, n + 1, nested + 1);
1035         }
1036         
1037         fprintf (output, "  } // end of class %s%s%s\n", nspace, *nspace? ".": "", name);
1038         if (*nspace)
1039                 fprintf (output, "}\n");
1040         fprintf (output, "\n");
1041 }
1042
1043
1044 /**
1045  * dis_globals
1046  * @m: metadata context
1047  *
1048  * disassembles all the global fields and methods
1049  */
1050 static void
1051 dis_globals (MonoImage *m)
1052 {
1053         MonoTableInfo *t = &m->tables [MONO_TABLE_TYPEDEF];
1054         guint32 cols [MONO_TYPEDEF_SIZE];
1055         guint32 cols_next [MONO_TYPEDEF_SIZE];
1056         gboolean next_is_valid, last;
1057         gchar *name;
1058
1059         name = g_strdup ("<Module>");
1060
1061         mono_metadata_decode_row (t, 0, cols, MONO_TYPEDEF_SIZE);
1062
1063         if (t->rows > 1) {
1064                 mono_metadata_decode_row (t, 1, cols_next, MONO_TYPEDEF_SIZE);
1065                 next_is_valid = 1;
1066         } else
1067                 next_is_valid = 0;
1068         
1069         /*
1070          * The value in the table is always valid, we know we have fields
1071          * if the value stored is different than the next record.
1072          */
1073
1074         if (next_is_valid)
1075                 last = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
1076         else
1077                 last = m->tables [MONO_TABLE_FIELD].rows;
1078                         
1079         if (cols [MONO_TYPEDEF_FIELD_LIST] && cols [MONO_TYPEDEF_FIELD_LIST] <= m->tables [MONO_TABLE_FIELD].rows)
1080                 dis_field_list (m, cols [MONO_TYPEDEF_FIELD_LIST] - 1, last);
1081         fprintf (output, "\n");
1082
1083         if (next_is_valid)
1084                 last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
1085         else
1086                 last = m->tables [MONO_TABLE_METHOD].rows;
1087         
1088         if (cols [MONO_TYPEDEF_METHOD_LIST] && cols [MONO_TYPEDEF_METHOD_LIST] <= m->tables [MONO_TABLE_METHOD].rows)
1089                 dis_method_list (name, m, cols [MONO_TYPEDEF_METHOD_LIST] - 1, last);
1090
1091 }
1092
1093 /**
1094  * dis_types:
1095  * @m: metadata context
1096  *
1097  * disassembles all types in the @m context
1098  */
1099 static void
1100 dis_types (MonoImage *m)
1101 {
1102         MonoTableInfo *t = &m->tables [MONO_TABLE_TYPEDEF];
1103         int i;
1104         guint32 flags;
1105
1106         dis_globals (m);
1107         
1108         for (i = 1; i < t->rows; i++) {
1109                 flags = mono_metadata_decode_row_col (t, i, MONO_TYPEDEF_FLAGS);
1110                 flags &= TYPE_ATTRIBUTE_VISIBILITY_MASK;
1111                 if (flags == TYPE_ATTRIBUTE_PUBLIC || flags == TYPE_ATTRIBUTE_NOT_PUBLIC)
1112                         dis_type (m, i);
1113         }
1114 }
1115
1116 /**
1117  * dis_data:
1118  * @m: metadata context
1119  *
1120  * disassembles all data blobs references in the FieldRVA table in the @m context
1121  */
1122 static void
1123 dis_data (MonoImage *m)
1124 {
1125         MonoTableInfo *t = &m->tables [MONO_TABLE_FIELDRVA];
1126         MonoTableInfo *ft = &m->tables [MONO_TABLE_FIELD];
1127         int i, b;
1128         const char *rva, *sig;
1129         guint32 align, size;
1130         guint32 cols [MONO_FIELD_RVA_SIZE];
1131         MonoType *type;
1132
1133         for (i = 0; i < t->rows; i++) {
1134                 mono_metadata_decode_row (t, i, cols, MONO_FIELD_RVA_SIZE);
1135                 rva = mono_image_rva_map (m, cols [MONO_FIELD_RVA_RVA]);
1136                 sig = mono_metadata_blob_heap (m, mono_metadata_decode_row_col (ft, cols [MONO_FIELD_RVA_FIELD] -1, MONO_FIELD_SIGNATURE));
1137                 mono_metadata_decode_value (sig, &sig);
1138                 /* FIELD signature == 0x06 */
1139                 g_assert (*sig == 0x06);
1140                 type = mono_metadata_parse_field_type (m, 0, sig + 1, &sig);
1141                 mono_class_init (mono_class_from_mono_type (type));
1142                 size = mono_type_size (type, &align);
1143                 fprintf (output, ".data D_%08x = bytearray (", cols [MONO_FIELD_RVA_RVA]);
1144                 for (b = 0; b < size; ++b) {
1145                         if (!(b % 16))
1146                                 fprintf (output, "\n\t");
1147                         fprintf (output, " %02X", rva [b] & 0xff);
1148                 }
1149                 fprintf (output, ") // size: %d\n", size);
1150         }
1151 }
1152
1153 struct {
1154         const char *name;
1155         int table;
1156         void (*dumper) (MonoImage *m);
1157 } table_list [] = {
1158         { "--assembly",    MONO_TABLE_ASSEMBLY,         dump_table_assembly },
1159         { "--assemblyref", MONO_TABLE_ASSEMBLYREF,      dump_table_assemblyref },
1160         { "--classlayout", MONO_TABLE_CLASSLAYOUT,      dump_table_class_layout },
1161         { "--constant",    MONO_TABLE_CONSTANT,         dump_table_constant },
1162         { "--customattr",  MONO_TABLE_CUSTOMATTRIBUTE,  dump_table_customattr },
1163         { "--declsec",     MONO_TABLE_DECLSECURITY,     dump_table_declsec },
1164         { "--event",       MONO_TABLE_EVENT,            dump_table_event },
1165         { "--exported",    MONO_TABLE_EXPORTEDTYPE,     dump_table_exported },
1166         { "--fields",      MONO_TABLE_FIELD,            dump_table_field },
1167         { "--file",        MONO_TABLE_FILE,             dump_table_file },
1168         { "--genericpar",  MONO_TABLE_GENERICPARAM,     dump_table_genericpar },
1169         { "--interface",   MONO_TABLE_INTERFACEIMPL,    dump_table_interfaceimpl },
1170         { "--manifest",    MONO_TABLE_MANIFESTRESOURCE, dump_table_manifest },
1171         { "--marshal",     MONO_TABLE_FIELDMARSHAL,     dump_table_field_marshal },
1172         { "--memberref",   MONO_TABLE_MEMBERREF,        dump_table_memberref },
1173         { "--method",      MONO_TABLE_METHOD,           dump_table_method },
1174         { "--methodimpl",  MONO_TABLE_METHODIMPL,       dump_table_methodimpl },
1175         { "--methodsem",   MONO_TABLE_METHODSEMANTICS,  dump_table_methodsem },
1176         { "--methodspec",  MONO_TABLE_METHODSPEC,       dump_table_methodspec },
1177         { "--moduleref",   MONO_TABLE_MODULEREF,        dump_table_moduleref },
1178         { "--module",      MONO_TABLE_MODULE,           dump_table_module },
1179         { "--nested",      MONO_TABLE_NESTEDCLASS,      dump_table_nestedclass },
1180         { "--param",       MONO_TABLE_PARAM,            dump_table_param },
1181         { "--parconst",    MONO_TABLE_GENERICPARAMCONSTRAINT, dump_table_parconstraint },
1182         { "--property",    MONO_TABLE_PROPERTY,         dump_table_property },
1183         { "--propertymap", MONO_TABLE_PROPERTYMAP,      dump_table_property_map },
1184         { "--typedef",     MONO_TABLE_TYPEDEF,          dump_table_typedef },
1185         { "--typeref",     MONO_TABLE_TYPEREF,          dump_table_typeref },
1186         { "--typespec",    MONO_TABLE_TYPESPEC,         dump_table_typespec },
1187         { "--implmap",     MONO_TABLE_IMPLMAP,          dump_table_implmap },
1188         { "--standalonesig", MONO_TABLE_STANDALONESIG,  dump_table_standalonesig },
1189         { "--blob",        NULL,                        dump_stream_blob },
1190         { NULL, -1 }
1191 };
1192
1193 /**
1194  * disassemble_file:
1195  * @file: file containing CIL code.
1196  *
1197  * Disassembles the @file file.
1198  */
1199 static void
1200 disassemble_file (const char *file)
1201 {
1202         MonoAssembly *ass;
1203         MonoImageOpenStatus status;
1204         MonoImage *img;
1205
1206         ass = mono_assembly_open (file, &status);
1207         if (ass == NULL){
1208                 fprintf (stderr, "Error while trying to process %s\n", file);
1209                 return;
1210         }
1211
1212         img = ass->image;
1213
1214         if (dump_table != -1){
1215                 (*table_list [dump_table].dumper) (img);
1216         } else {
1217                 dump_header_data (img);
1218                 
1219                 dis_directive_assemblyref (img);
1220                 dis_directive_assembly (img);
1221                 dis_directive_file (img);
1222                 dis_directive_module (img);
1223                 dis_directive_moduleref (img);
1224                 dis_types (img);
1225                 dis_data (img);
1226         }
1227         
1228         mono_image_close (img);
1229 }
1230
1231 static void
1232 usage (void)
1233 {
1234         GString *args = g_string_new ("[--output=filename] [--help] [--mscorlib]\n");
1235         int i;
1236         
1237         for (i = 0; table_list [i].name != NULL; i++){
1238                 g_string_append (args, "[");
1239                 g_string_append (args, table_list [i].name);
1240                 g_string_append (args, "] ");
1241                 if (((i-2) % 5) == 0)
1242                         g_string_append_c (args, '\n');
1243         }
1244         fprintf (stderr,
1245                  "Usage is: monodis %s file ..\n", args->str);
1246         exit (1);
1247 }
1248
1249 int
1250 main (int argc, char *argv [])
1251 {
1252         GList *input_files = NULL, *l;
1253         int i, j;
1254
1255         output = stdout;
1256         init_key_table ();
1257         for (i = 1; i < argc; i++){
1258                 if (argv [i][0] == '-'){
1259                         if (argv [i][1] == 'h')
1260                                 usage ();
1261                         else if (argv [i][1] == 'd')
1262                                 dump_header_data_p = TRUE;
1263                         else if (strcmp (argv [i], "--mscorlib") == 0) {
1264                                 substitute_with_mscorlib_p = TRUE;
1265                                 continue;
1266                         } else if (strcmp (argv [i], "--show-method-tokens") == 0) {
1267                                 show_method_tokens = TRUE;
1268                                 continue;
1269                         } else if (strcmp (argv [i], "--show-tokens") == 0) {
1270                                 show_tokens = TRUE;
1271                                 continue;
1272                         } else if (strncmp (argv [i], "--output=", 9) == 0) {
1273                                 output = fopen (argv [i]+9, "w");
1274                                 if (output == NULL) {
1275                                         fprintf (stderr, "Can't open output file `%s': %s\n",
1276                                                  argv [i]+9, strerror (errno));
1277                                         exit (1);
1278                                 }
1279                                 continue;
1280                         } else if (strcmp (argv [i], "--help") == 0)
1281                                 usage ();
1282                         for (j = 0; table_list [j].name != NULL; j++) {
1283                                 if (strcmp (argv [i], table_list [j].name) == 0)
1284                                         dump_table = j;
1285                         }
1286                         if (dump_table < 0)
1287                                 usage ();
1288                 } else
1289                         input_files = g_list_append (input_files, argv [i]);
1290         }
1291
1292         if (input_files == NULL)
1293                 usage ();
1294         
1295         mono_init (argv [0]);
1296
1297         for (l = input_files; l; l = l->next)
1298                 disassemble_file (l->data);
1299
1300         return 0;
1301 }