added some docu
[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 "meta.h"
21 #include "util.h"
22 #include "dump.h"
23 #include "get.h"
24 #include "dis-cil.h"
25 #include <mono/metadata/loader.h>
26 #include <mono/metadata/assembly.h>
27
28 FILE *output;
29
30 /* True if you want to get a dump of the header data */
31 gboolean dump_header_data_p = FALSE;
32
33 int dump_table = -1;
34
35 static void
36 dump_header_data (MonoImage *img)
37 {
38         if (!dump_header_data_p)
39                 return;
40
41         fprintf (output,
42                  "// Ximian's CIL disassembler, version 1.0\n"
43                  "// Copyright (C) 2001 Ximian, Inc.\n\n");
44 }
45
46 static void
47 dis_directive_assembly (MonoImage *m)
48 {
49         MonoTableInfo *t  = &m->tables [MONO_TABLE_ASSEMBLY];
50         guint32 cols [MONO_ASSEMBLY_SIZE];
51         
52         if (t->base == NULL)
53                 return;
54
55         mono_metadata_decode_row (t, 0, cols, MONO_ASSEMBLY_SIZE);
56         
57         fprintf (output,
58                  ".assembly '%s'\n"
59                  "{\n"
60                  "  .hash algorithm 0x%08x\n"
61                  "  .ver  %d:%d:%d:%d"
62                  "%s %s"
63                  "%s"
64                  "\n"
65                  "}\n",
66                  mono_metadata_string_heap (m, cols [MONO_ASSEMBLY_NAME]),
67                  cols [MONO_ASSEMBLY_HASH_ALG],
68                  cols [MONO_ASSEMBLY_MAJOR_VERSION], cols [MONO_ASSEMBLY_MINOR_VERSION], 
69                  cols [MONO_ASSEMBLY_BUILD_NUMBER], cols [MONO_ASSEMBLY_REV_NUMBER],
70                  cols [MONO_ASSEMBLY_CULTURE] ? "\n  .locale" : "",
71                  cols [MONO_ASSEMBLY_CULTURE] ? mono_metadata_string_heap (m, cols [MONO_ASSEMBLY_CULTURE]) : "",
72                  cols [MONO_ASSEMBLY_PUBLIC_KEY] ? "\n  .publickey" : ""
73                 );
74 }
75
76 static void
77 dis_directive_assemblyref (MonoImage *m)
78 {
79         MonoTableInfo *t = &m->tables [MONO_TABLE_ASSEMBLYREF];
80         guint32 cols [MONO_ASSEMBLYREF_SIZE];
81         int i;
82         
83         if (t->base == NULL)
84                 return;
85
86         for (i = 0; i < t->rows; i++){
87                 mono_metadata_decode_row (t, i, cols, MONO_ASSEMBLYREF_SIZE);
88
89                 fprintf (output,
90                          ".assembly extern %s\n"
91                          "{\n"
92                          "  .ver %d:%d:%d:%d\n"
93                          "}\n",
94                          mono_metadata_string_heap (m, cols [MONO_ASSEMBLYREF_NAME]),
95                          cols [MONO_ASSEMBLYREF_MAJOR_VERSION], cols [MONO_ASSEMBLYREF_MINOR_VERSION], 
96                          cols [MONO_ASSEMBLYREF_BUILD_NUMBER], cols [MONO_ASSEMBLYREF_REV_NUMBER]
97                         );
98         }
99 }
100
101 static map_t visibility_map [] = {
102         { TYPE_ATTRIBUTE_NOT_PUBLIC,           "private " },
103         { TYPE_ATTRIBUTE_PUBLIC,               "public " },
104         { TYPE_ATTRIBUTE_NESTED_PUBLIC,        "nested-public " },
105         { TYPE_ATTRIBUTE_NESTED_PRIVATE,       "nested-private " },
106         { TYPE_ATTRIBUTE_NESTED_FAMILY,        "family " },
107         { TYPE_ATTRIBUTE_NESTED_ASSEMBLY,      "nested-assembly" },
108         { TYPE_ATTRIBUTE_NESTED_FAM_AND_ASSEM, "nested-fam-and-assembly" },
109         { TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM,  "nested-fam-or-assembly" },
110         { 0, NULL }
111 };
112
113 static map_t layout_map [] = {
114         { TYPE_ATTRIBUTE_AUTO_LAYOUT,          "auto " },
115         { TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT,    "sequential " },
116         { TYPE_ATTRIBUTE_EXPLICIT_LAYOUT,      "explicit " },
117         { 0, NULL }
118 };
119
120 static map_t format_map [] = {
121         { TYPE_ATTRIBUTE_ANSI_CLASS,           "ansi " },
122         { TYPE_ATTRIBUTE_UNICODE_CLASS,        "unicode " },
123         { TYPE_ATTRIBUTE_AUTO_CLASS,           "auto " },
124         { 0, NULL }
125 };
126
127 static char *
128 typedef_flags (guint32 flags)
129 {
130         static char buffer [1024];
131         int visibility = flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
132         int layout = flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
133         int format = flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK;
134         
135         buffer [0] = 0;
136
137         strcat (buffer, map (visibility, visibility_map));
138         strcat (buffer, map (layout, layout_map));
139         strcat (buffer, map (format, format_map));
140         
141         if (flags & TYPE_ATTRIBUTE_ABSTRACT)
142                 strcat (buffer, "abstract ");
143         if (flags & TYPE_ATTRIBUTE_SEALED)
144                 strcat (buffer, "sealed ");
145         if (flags & TYPE_ATTRIBUTE_SPECIAL_NAME)
146                 strcat (buffer, "special-name ");
147         if (flags & TYPE_ATTRIBUTE_IMPORT)
148                 strcat (buffer, "import ");
149         if (flags & TYPE_ATTRIBUTE_SERIALIZABLE)
150                 strcat (buffer, "serializable ");
151         if (flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)
152                 strcat (buffer, "beforefieldinit ");
153
154         return buffer;
155 }
156
157 /**
158  * dis_field_list:
159  * @m: metadata context
160  * @start: starting index into the Field Table.
161  * @end: ending index into Field table.
162  *
163  * This routine displays all the decoded fields from @start to @end
164  */
165 static void
166 dis_field_list (MonoImage *m, guint32 start, guint32 end)
167 {
168         MonoTableInfo *t = &m->tables [MONO_TABLE_FIELD];
169         guint32 cols [MONO_FIELD_SIZE];
170         int i;
171
172         if (end > t->rows + 1) {
173                 g_warning ("ERROR index out of range in fields");
174                 end = t->rows;
175         }
176                         
177         for (i = start; i < end; i++){
178                 char *sig, *flags;
179                 
180                 mono_metadata_decode_row (t, i, cols, MONO_FIELD_SIZE);
181                 sig = get_field_signature (m, cols [MONO_FIELD_SIGNATURE]);
182                 flags = field_flags (cols [MONO_FIELD_FLAGS]);
183                 
184                 if (cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_LITERAL){
185                         char *lit;
186                         guint32 const_cols [MONO_CONSTANT_SIZE];
187                         guint32 crow;
188                         
189                         if ((crow = mono_metadata_get_constant_index (m, MONO_TOKEN_FIELD_DEF | (i+1)))) {
190                                 mono_metadata_decode_row (&m->tables [MONO_TABLE_CONSTANT], crow-1, const_cols, MONO_CONSTANT_SIZE);
191                                 lit = get_constant (m, const_cols [MONO_CONSTANT_TYPE], const_cols [MONO_CONSTANT_VALUE]);
192                         } else {
193                                 lit = g_strdup ("not found");
194                         }
195                         
196                         fprintf (output, "    .field %s %s %s = ",
197                                  flags, sig,
198                                  mono_metadata_string_heap (m, cols [MONO_FIELD_NAME]));
199                         fprintf (output, "%s\n", lit);
200                         g_free (lit);
201                 } else 
202                         fprintf (output, "    .field %s %s %s\n",
203                                  flags, sig,
204                                  mono_metadata_string_heap (m, cols [MONO_FIELD_NAME]));
205                 g_free (flags);
206                 g_free (sig);
207         }
208 }
209
210 static map_t method_access_map [] = {
211         { METHOD_ATTRIBUTE_COMPILER_CONTROLLED, "compilercontrolled " },
212         { METHOD_ATTRIBUTE_PRIVATE,             "private" },
213         { METHOD_ATTRIBUTE_FAM_AND_ASSEM,       "famandassem" },
214         { METHOD_ATTRIBUTE_ASSEM,               "assembly " },
215         { METHOD_ATTRIBUTE_FAMILY,              "family " },
216         { METHOD_ATTRIBUTE_FAM_OR_ASSEM,        "famorassem " },
217         { METHOD_ATTRIBUTE_PUBLIC,              "public " },
218         { 0, NULL }
219 };
220
221 static map_t method_flags_map [] = {
222         { METHOD_ATTRIBUTE_STATIC,              "static " },
223         { METHOD_ATTRIBUTE_FINAL,               "final " },
224         { METHOD_ATTRIBUTE_VIRTUAL,             "virtual " },
225         { METHOD_ATTRIBUTE_HIDE_BY_SIG,         "hidebysig " },
226         { METHOD_ATTRIBUTE_VTABLE_LAYOUT_MASK,  "newslot " },
227         { METHOD_ATTRIBUTE_ABSTRACT,            "abstract " },
228         { METHOD_ATTRIBUTE_SPECIAL_NAME,        "specialname " },
229         { METHOD_ATTRIBUTE_RT_SPECIAL_NAME,     "rtspecialname " },
230         { METHOD_ATTRIBUTE_UNMANAGED_EXPORT,    "export " },
231         { METHOD_ATTRIBUTE_HAS_SECURITY,        "hassecurity" },
232         { METHOD_ATTRIBUTE_REQUIRE_SEC_OBJECT,  "requiresecobj" },
233         { METHOD_ATTRIBUTE_PINVOKE_IMPL,        "pinvokeimpl " }, 
234         { 0, NULL }
235 };
236
237 /**
238  * method_flags:
239  *
240  * Returns a stringified version of the Method's flags
241  */
242 static char *
243 method_flags (guint32 f)
244 {
245         GString *str = g_string_new ("");
246         int access = f & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK;
247         char *s;
248         
249         g_string_append (str, map (access, method_access_map));
250         g_string_append (str, flags (f, method_flags_map));
251
252         s = str->str;
253         g_string_free (str, FALSE);
254
255         return s;
256 }
257
258 static map_t pinvoke_flags_map [] = {
259         { PINVOKE_ATTRIBUTE_NO_MANGLE ,            "nomangle " },
260         { PINVOKE_ATTRIBUTE_SUPPORTS_LAST_ERROR,   "lasterr " },
261         { 0, NULL }
262 };
263
264 static map_t pinvoke_call_conv_map [] = {
265         { PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI,      "winapi " },
266         { PINVOKE_ATTRIBUTE_CALL_CONV_CDECL,       "cdecl " },
267         { PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL,     "stdcall " },
268         { PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL,    "thiscall " },
269         { PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL,    "fastcall " },
270         { 0, NULL }
271 };
272
273 static map_t pinvoke_char_set_map [] = {
274         { PINVOKE_ATTRIBUTE_CHAR_SET_NOT_SPEC,     "" },
275         { PINVOKE_ATTRIBUTE_CHAR_SET_ANSI,         "ansi " },
276         { PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE ,     "unicode " },
277         { PINVOKE_ATTRIBUTE_CHAR_SET_AUTO,         "autochar " },
278         { 0, NULL }
279 };
280
281 /**
282  * pinvoke_flags:
283  *
284  * Returns a stringified version of the Method's pinvoke flags
285  */
286 static char *
287 pinvoke_flags (guint32 f)
288 {
289         GString *str = g_string_new ("");
290         int cset = f & PINVOKE_ATTRIBUTE_CHAR_SET_MASK;
291         int cconv = f & PINVOKE_ATTRIBUTE_CALL_CONV_MASK;
292         char *s;
293         
294         g_string_append (str, map (cset, pinvoke_char_set_map));
295         g_string_append (str, map (cconv, pinvoke_call_conv_map));
296         g_string_append (str, flags (f, pinvoke_flags_map));
297
298         s = g_strdup(str->str);
299         g_string_free (str, FALSE);
300
301         return s;
302 }
303
304 static map_t method_impl_map [] = {
305         { METHOD_IMPL_ATTRIBUTE_IL,              "cil " },
306         { METHOD_IMPL_ATTRIBUTE_NATIVE,          "native " },
307         { METHOD_IMPL_ATTRIBUTE_OPTIL,           "optil " },
308         { METHOD_IMPL_ATTRIBUTE_RUNTIME,         "runtime " },
309         { 0, NULL }
310 };
311
312 static map_t managed_type_map [] = {
313         { METHOD_IMPL_ATTRIBUTE_UNMANAGED,       "unmanaged " },
314         { METHOD_IMPL_ATTRIBUTE_MANAGED,         "managed " },
315         { 0, NULL }
316 };
317
318 static map_t managed_impl_flags [] = {
319         { METHOD_IMPL_ATTRIBUTE_FORWARD_REF,     "fwdref " },
320         { METHOD_IMPL_ATTRIBUTE_PRESERVE_SIG,    "preservesig " },
321         { METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL,   "internalcall " },
322         { METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED,    "synchronized " },
323         { METHOD_IMPL_ATTRIBUTE_NOINLINING,      "noinline " },
324         { 0, NULL }
325 };
326
327 static char *
328 method_impl_flags (guint32 f)
329 {
330         GString *str = g_string_new ("");
331         char *s;
332         int code_type = f & METHOD_IMPL_ATTRIBUTE_CODE_TYPE_MASK;
333         int managed_type = f & METHOD_IMPL_ATTRIBUTE_MANAGED_MASK;
334
335         g_string_append (str, map (code_type, method_impl_map));
336         g_string_append (str, map (managed_type, managed_type_map));
337         g_string_append (str, flags (f, managed_impl_flags));
338         
339         s = str->str;
340         g_string_free (str, FALSE);
341         return s;
342 }
343
344 static void
345 dis_locals (MonoImage *m, MonoMethodHeader *mh) 
346 {
347         int i;
348
349         fprintf(output, "\t.locals %s(\n", mh->init_locals ? "init " : "");
350         for (i=0; i < mh->num_locals; ++i) {
351                 char * desc;
352                 if (i)
353                         fprintf(output, ",\n");
354                 /* print also byref and pinned attributes */
355                 desc = dis_stringify_type (m, mh->locals[i]);
356                 fprintf(output, "\t\t%s\tV_%d", desc, i);
357                 g_free(desc);
358         }
359         fprintf(output, ")\n");
360 }
361
362 static void
363 dis_code (MonoImage *m, guint32 rva)
364 {
365         MonoMethodHeader *mh;
366         MonoCLIImageInfo *ii = m->image_info;
367         const char *ptr = mono_cli_rva_map (ii, rva);
368         char *loc;
369
370         if (rva == 0)
371                 return;
372
373         mh = mono_metadata_parse_mh (m, ptr);
374         if (ii->cli_cli_header.ch_entry_point){
375                 loc = mono_metadata_locate_token (m, ii->cli_cli_header.ch_entry_point);
376                 if (rva == read32 (loc))
377                         fprintf (output, "\t.entrypoint\n");
378         }
379         
380         fprintf (output, "\t// Code size %d (0x%x)\n", mh->code_size, mh->code_size);
381         fprintf (output, "\t.maxstack %d\n", mh->max_stack);
382         if (mh->num_locals)
383                 dis_locals (m, mh);
384         dissasemble_cil (m, mh);
385         
386 /*
387   hex_dump (mh->code, 0, mh->code_size);
388   printf ("\nAfter the code\n");
389   hex_dump (mh->code + mh->code_size, 0, 64);
390 */
391         mono_metadata_free_mh (mh);
392 }
393
394 static char *
395 pinvoke_info (MonoImage *m, guint32 mindex)
396 {
397         MonoTableInfo *im = &m->tables [MONO_TABLE_IMPLMAP];
398         MonoTableInfo *mr = &m->tables [MONO_TABLE_MODULEREF];
399         guint32 im_cols [MONO_IMPLMAP_SIZE];
400         guint32 mr_cols [MONO_MODULEREF_SIZE];
401         const char *import, *scope;
402         char *flags;
403         int i;
404
405         for (i = 0; i < im->rows; i++) {
406
407                 mono_metadata_decode_row (im, i, im_cols, MONO_IMPLMAP_SIZE);
408
409                 if ((im_cols [MONO_IMPLMAP_MEMBER] >> 1) == mindex + 1) {
410
411                         flags = pinvoke_flags (im_cols [MONO_IMPLMAP_FLAGS]);
412
413                         import = mono_metadata_string_heap (m, im_cols [MONO_IMPLMAP_NAME]);
414
415                         mono_metadata_decode_row (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, 
416                                                   mr_cols, MONO_MODULEREF_SIZE);
417
418                         scope = mono_metadata_string_heap (m, mr_cols [MONO_MODULEREF_NAME]);
419                                 
420                         return g_strdup_printf ("(%s as %s %s)", scope, import,
421                                                 flags);
422                         g_free (flags);
423                 }
424         }
425
426         return NULL;
427 }
428
429 /**
430  * dis_method_list:
431  * @m: metadata context
432  * @start: starting index into the Method Table.
433  * @end: ending index into Method table.
434  *
435  * This routine displays the methods in the Method Table from @start to @end
436  */
437 static void
438 dis_method_list (MonoImage *m, guint32 start, guint32 end)
439 {
440         MonoTableInfo *t = &m->tables [MONO_TABLE_METHOD];
441         guint32 cols [MONO_METHOD_SIZE];
442         int i;
443
444         if (end > t->rows){
445                 fprintf (output, "ERROR index out of range in methods");
446                 /*exit (1);*/
447                 end = t->rows;
448         }
449
450         for (i = start; i < end; i++){
451                 MonoMethodSignature *ms;
452                 char *flags, *impl_flags;
453                 const char *sig;
454                 char *sig_str;
455                 
456                 mono_metadata_decode_row (t, i, cols, MONO_METHOD_SIZE);
457
458                 flags = method_flags (cols [MONO_METHOD_FLAGS]);
459                 impl_flags = method_impl_flags (cols [MONO_METHOD_IMPLFLAGS]);
460
461                 sig = mono_metadata_blob_heap (m, cols [MONO_METHOD_SIGNATURE]);
462                 mono_metadata_decode_blob_size (sig, &sig);
463                 ms = mono_metadata_parse_method_signature (m, 1, sig, &sig);
464                 sig_str = dis_stringify_method_signature (m, ms, i + 1);
465                         
466                 fprintf (output, "    // method line %d\n", i + 1);
467                 fprintf (output, "    .method %s", flags);
468
469                 if (cols [MONO_METHOD_FLAGS] & METHOD_ATTRIBUTE_PINVOKE_IMPL)
470                         fprintf (output, "%s", pinvoke_info (m, i));
471
472                 fprintf (output, "\n           %s", sig_str);
473                 fprintf (output, " %s\n", impl_flags);
474                 g_free (flags);
475                 g_free (impl_flags);
476                 
477                 fprintf (output, "    {\n");
478                 fprintf (output, "        // Method begins at RVA 0x%x\n", cols [MONO_METHOD_RVA]);
479                 dis_code (m, cols [MONO_METHOD_RVA]);
480                 fprintf (output, "    }\n\n");
481                 mono_metadata_free_method_signature (ms);
482                 g_free (sig_str);
483         }
484 }
485
486 typedef struct {
487         MonoTableInfo *t;
488         guint32 col_idx;
489         guint32 idx;
490         guint32 result;
491 } plocator_t;
492
493 static int
494 table_locator (const void *a, const void *b)
495 {
496         plocator_t *loc = (plocator_t *) a;
497         char *bb = (char *) b;
498         guint32 table_index = (bb - loc->t->base) / loc->t->row_size;
499         guint32 col;
500         
501         col = mono_metadata_decode_row_col (loc->t, table_index, loc->col_idx);
502
503         if (loc->idx == col) {
504                 loc->result = table_index;
505                 return 0;
506         }
507         if (loc->idx < col)
508                 return -1;
509         else 
510                 return 1;
511 }
512
513 static void
514 dis_property_methods (MonoImage *m, guint32 prop)
515 {
516         guint start, end;
517         MonoTableInfo *msemt = &m->tables [MONO_TABLE_METHODSEMANTICS];
518         guint32 cols [MONO_METHOD_SEMA_SIZE];
519         char *sig;
520         char *type[] = {NULL, ".set", ".get", NULL, ".other"};
521
522         start = mono_metadata_methods_from_property (m, prop, &end);
523         while (start < end) {
524                 mono_metadata_decode_row (msemt, start, cols, MONO_METHOD_SEMA_SIZE);
525                 sig = dis_stringify_method_signature (m, NULL, cols [MONO_METHOD_SEMA_METHOD]);
526                 fprintf (output, "\t\t%s %s\n", type [cols [MONO_METHOD_SEMA_SEMANTICS]], sig);
527                 g_free (sig);
528                 ++start;
529         }
530 }
531
532 static char*
533 dis_property_signature (MonoImage *m, guint32 prop_idx)
534 {
535         MonoTableInfo *propt = &m->tables [MONO_TABLE_PROPERTY];
536         const char *ptr;
537         guint32 pcount, i;
538         guint32 cols [MONO_PROPERTY_SIZE];
539         MonoType *type;
540         MonoType *param;
541         char *blurb;
542         const char *name;
543         int prop_flags;
544         GString *res = g_string_new ("");
545
546         mono_metadata_decode_row (propt, prop_idx, cols, MONO_PROPERTY_SIZE);
547         name = mono_metadata_string_heap (m, cols [MONO_PROPERTY_NAME]);
548         prop_flags = cols [MONO_PROPERTY_FLAGS];
549         ptr = mono_metadata_blob_heap (m, cols [MONO_PROPERTY_TYPE]);
550         mono_metadata_decode_blob_size (ptr, &ptr);
551         /* ECMA claims 0x08 ... */
552         if (*ptr != 0x28 && *ptr != 0x08)
553                 g_warning("incorrect signature in propert blob: 0x%x", *ptr);
554         ptr++;
555         pcount = mono_metadata_decode_value (ptr, &ptr);
556         type = mono_metadata_parse_type (m, MONO_PARSE_TYPE, 0, ptr, &ptr);
557         blurb = dis_stringify_type (m, type);
558         if (prop_flags & 0x0200)
559                 g_string_append (res, "special ");
560         if (prop_flags & 0x0400)
561                 g_string_append (res, "runtime ");
562         if (prop_flags & 0x1000)
563                 g_string_append (res, "hasdefault ");
564         g_string_sprintfa (res, "%s %s (", blurb, name);
565         g_free (blurb);
566         mono_metadata_free_type (type);
567         for (i = 0; i < pcount; i++) {
568                 if (i)
569                         g_string_append (res, ", ");
570                 param = mono_metadata_parse_param (m, ptr, &ptr);
571                 blurb = dis_stringify_param (m, param);
572                 g_string_append (res, blurb);
573                 mono_metadata_free_type (param);
574                 g_free (blurb);
575         }
576         g_string_append_c (res, ')');
577         blurb = res->str;
578         g_string_free (res, FALSE);
579         return blurb;
580
581 }
582
583 static void
584 dis_property_list (MonoImage *m, guint32 typedef_row)
585 {
586         guint start, end, i;
587         start = mono_metadata_properties_from_typedef (m, typedef_row, &end);
588
589         for (i = start; i < end; ++i) {
590                 char *sig = dis_property_signature (m, i);
591                 fprintf (output, "\t.property %s\n\t{\n", sig);
592                 dis_property_methods (m, i);
593                 fprintf (output, "\t}\n");
594                 g_free (sig);
595         }
596 }
597
598 static void
599 dis_interfaces (MonoImage *m, guint32 typedef_row)
600 {
601         plocator_t loc;
602         guint start;
603         guint32 cols [MONO_INTERFACEIMPL_SIZE];
604         char *intf;
605         MonoTableInfo *table = &m->tables [MONO_TABLE_INTERFACEIMPL];
606
607         if (!table->base)
608                 return;
609
610         loc.t = table;
611         loc.col_idx = MONO_INTERFACEIMPL_CLASS;
612         loc.idx = typedef_row;
613
614         if (!bsearch (&loc, table->base, table->rows, table->row_size, table_locator))
615                 return;
616
617         start = loc.result;
618         /*
619          * We may end up in the middle of the rows... 
620          */
621         while (start > 0) {
622                 if (loc.idx == mono_metadata_decode_row_col (table, start - 1, MONO_INTERFACEIMPL_CLASS))
623                         start--;
624                 else
625                         break;
626         }
627         while (start < table->rows) {
628                 mono_metadata_decode_row (table, start, cols, MONO_INTERFACEIMPL_SIZE);
629                 if (cols [MONO_INTERFACEIMPL_CLASS] != loc.idx)
630                         break;
631                 intf = get_typedef_or_ref (m, cols [MONO_INTERFACEIMPL_INTERFACE]);
632                 fprintf (output, "  \timplements %s\n", intf);
633                 g_free (intf);
634                 ++start;
635         }
636 }
637
638 /**
639  * dis_type:
640  * @m: metadata context
641  * @n: index of type to disassemble
642  *
643  * Disassembles the type whose index in the TypeDef table is @n.
644  */
645 static void
646 dis_type (MonoImage *m, int n)
647 {
648         MonoTableInfo *t = &m->tables [MONO_TABLE_TYPEDEF];
649         guint32 cols [MONO_TYPEDEF_SIZE];
650         guint32 cols_next [MONO_TYPEDEF_SIZE];
651         const char *name, *nspace;
652         gboolean next_is_valid, last;
653         
654         mono_metadata_decode_row (t, n, cols, MONO_TYPEDEF_SIZE);
655
656         if (t->rows > n + 1) {
657                 mono_metadata_decode_row (t, n + 1, cols_next, MONO_TYPEDEF_SIZE);
658                 next_is_valid = 1;
659         } else
660                 next_is_valid = 0;
661
662         nspace = mono_metadata_string_heap (m, cols [MONO_TYPEDEF_NAMESPACE]);
663         if (*nspace)
664                 fprintf (output, ".namespace %s\n{\n", nspace);
665         name = mono_metadata_string_heap (m, cols [MONO_TYPEDEF_NAME]);
666
667         if ((cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_CLASS_SEMANTIC_MASK) == TYPE_ATTRIBUTE_CLASS){
668                 char *base = get_typedef_or_ref (m, cols [MONO_TYPEDEF_EXTENDS]);
669                 fprintf (output, "  .class %s%s\n", typedef_flags (cols [MONO_TYPEDEF_FLAGS]), name);
670                 fprintf (output, "  \textends %s\n", base);
671                 g_free (base);
672         } else
673                 fprintf (output, "  .class interface %s%s\n", typedef_flags (cols [MONO_TYPEDEF_FLAGS]), name);
674         
675         dis_interfaces (m, n + 1);
676         fprintf (output, "  {\n");
677
678         /*
679          * The value in the table is always valid, we know we have fields
680          * if the value stored is different than the next record.
681          */
682
683         if (next_is_valid)
684                 last = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
685         else
686                 last = m->tables [MONO_TABLE_FIELD].rows;
687                         
688         if (cols [MONO_TYPEDEF_FIELD_LIST] && cols [MONO_TYPEDEF_FIELD_LIST] <= m->tables [MONO_TABLE_FIELD].rows)
689                 dis_field_list (m, cols [MONO_TYPEDEF_FIELD_LIST] - 1, last);
690         fprintf (output, "\n");
691
692         if (next_is_valid)
693                 last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
694         else
695                 last = m->tables [MONO_TABLE_METHOD].rows;
696         
697         if (cols [MONO_TYPEDEF_METHOD_LIST] && cols [MONO_TYPEDEF_METHOD_LIST] <= m->tables [MONO_TABLE_METHOD].rows)
698                 dis_method_list (m, cols [MONO_TYPEDEF_METHOD_LIST] - 1, last);
699
700         dis_property_list (m, n);
701
702         fprintf (output, "  }\n");
703         if (*nspace)
704                 fprintf (output, "}\n");
705         fprintf (output, "\n");
706 }
707
708 /**
709  * dis_types:
710  * @m: metadata context
711  *
712  * disassembles all types in the @m context
713  */
714 static void
715 dis_types (MonoImage *m)
716 {
717         MonoTableInfo *t = &m->tables [MONO_TABLE_TYPEDEF];
718         int i;
719
720         for (i = 1; i < t->rows; i++)
721                 dis_type (m, i);
722 }
723
724 struct {
725         char *name;
726         int table;
727         void (*dumper) (MonoImage *m);
728 } table_list [] = {
729         { "--assembly",    MONO_TABLE_ASSEMBLY,    dump_table_assembly },
730         { "--assemblyref", MONO_TABLE_ASSEMBLYREF, dump_table_assemblyref },
731         { "--fields",      MONO_TABLE_FIELD,       dump_table_field },
732         { "--memberref",   MONO_TABLE_MEMBERREF,   dump_table_memberref },
733         { "--param",       MONO_TABLE_PARAM,       dump_table_param },
734         { "--typedef",     MONO_TABLE_TYPEDEF,     dump_table_typedef },
735         { "--typeref",     MONO_TABLE_TYPEREF,     dump_table_typeref },
736         { "--nested",      MONO_TABLE_NESTEDCLASS, dump_table_nestedclass },
737         { "--interface",   MONO_TABLE_INTERFACEIMPL,     dump_table_interfaceimpl },
738         { "--classlayout", MONO_TABLE_CLASSLAYOUT, dump_table_class_layout },
739         { "--constant",    MONO_TABLE_CONSTANT,    dump_table_constant },
740         { "--customattr",  MONO_TABLE_CUSTOMATTRIBUTE,    dump_table_customattr },
741         { "--property",    MONO_TABLE_PROPERTY,    dump_table_property },
742         { "--propertymap", MONO_TABLE_PROPERTYMAP, dump_table_property_map },
743         { "--event",       MONO_TABLE_EVENT,       dump_table_event },
744         { "--file",        MONO_TABLE_FILE,        dump_table_file },
745         { "--moduleref",   MONO_TABLE_MODULEREF,   dump_table_moduleref },
746         { "--method",      MONO_TABLE_METHOD,      dump_table_method },
747         { "--methodsem",   MONO_TABLE_METHODSEMANTICS,      dump_table_methodsem },
748         { NULL, -1 }
749 };
750
751 /**
752  * disassemble_file:
753  * @file: file containing CIL code.
754  *
755  * Disassembles the @file file.
756  */
757 static void
758 disassemble_file (const char *file)
759 {
760         MonoAssembly *ass;
761         enum MonoImageOpenStatus status;
762         MonoImage *img;
763
764         ass = mono_assembly_open (file, NULL, &status);
765         if (ass == NULL){
766                 fprintf (stderr, "Error while trying to process %s\n", file);
767                 return;
768         }
769
770         img = ass->image;
771
772         if (dump_table != -1){
773                 (*table_list [dump_table].dumper) (img);
774         } else {
775                 dump_header_data (img);
776                 
777                 dis_directive_assemblyref (img);
778                 dis_directive_assembly (img);
779                 dis_types (img);
780         }
781         
782         mono_image_close (img);
783 }
784
785 static void
786 usage (void)
787 {
788         GString *args = g_string_new ("[--help] ");
789         int i;
790         
791         for (i = 0; table_list [i].name != NULL; i++){
792                 g_string_append (args, "[");
793                 g_string_append (args, table_list [i].name);
794                 g_string_append (args, "] ");
795                 if (((i-2) % 5) == 0)
796                         g_string_append_c (args, '\n');
797         }
798         fprintf (stderr,
799                  "Usage is: monodis %s file ..\n", args->str);
800         exit (1);
801 }
802
803 int
804 main (int argc, char *argv [])
805 {
806         GList *input_files = NULL, *l;
807         int i, j;
808
809         output = stdout;
810         for (i = 1; i < argc; i++){
811                 if (argv [i][0] == '-'){
812                         if (argv [i][1] == 'h')
813                                 usage ();
814                         else if (argv [i][1] == 'd')
815                                 dump_header_data_p = TRUE;
816                         else if (strcmp (argv [i], "--help") == 0)
817                                 usage ();
818                         for (j = 0; table_list [j].name != NULL; j++) {
819                                 if (strcmp (argv [i], table_list [j].name) == 0)
820                                         dump_table = j;
821                         }
822                         if (dump_table < 0)
823                                 usage ();
824                 } else
825                         input_files = g_list_append (input_files, argv [i]);
826         }
827
828         if (input_files == NULL)
829                 usage ();
830         
831         mono_init ();
832
833         for (l = input_files; l; l = l->next)
834                 disassemble_file (l->data);
835
836         return 0;
837 }