2007-06-13 Mark Probst <mark.probst@gmail.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 <fcntl.h>
22 #include "meta.h"
23 #include "util.h"
24 #include "dump.h"
25 #include "get.h"
26 #include "dis-cil.h"
27 #include "declsec.h"
28 #include <mono/metadata/class-internals.h>
29 #include <mono/metadata/object-internals.h>
30 #include <mono/metadata/loader.h>
31 #include <mono/metadata/assembly.h>
32 #include <mono/metadata/appdomain.h>
33
34 static void     setup_filter          (MonoImage *image);
35 static gboolean should_include_type   (int idx);
36 static gboolean should_include_method (int idx);
37 static gboolean should_include_field  (int idx);
38
39 FILE *output;
40
41 /* True if you want to get a dump of the header data */
42 gboolean dump_header_data_p = FALSE;
43
44 /* True if you want to get forward declarations */
45 gboolean dump_forward_decls = FALSE;
46
47 /* True if you want to dump managed resources as files */
48 gboolean dump_managed_resources = FALSE;
49
50 gboolean substitute_with_mscorlib_p = FALSE;
51
52 int dump_table = -1;
53
54 static void
55 dump_header_data (MonoImage *img)
56 {
57         if (!dump_header_data_p)
58                 return;
59
60         fprintf (output,
61                  "// Ximian's CIL disassembler, version 1.0\n"
62                  "// Copyright (C) 2001 Ximian, Inc.\n\n");
63 }
64
65 static void
66 dump_cattrs_list (GList *list,  const char *indent)
67 {
68         GList *tmp;
69
70         for (tmp = list; tmp; tmp = tmp->next) {
71                 fprintf (output, "%s%s\n", indent, (char*)tmp->data);
72                 g_free (tmp->data);
73         }
74         g_list_free (list);
75 }
76
77 static void
78 dump_cattrs (MonoImage *m, guint32 token, const char *indent)
79 {
80         GList *list;
81
82         list = dis_get_custom_attrs (m, token);
83         dump_cattrs_list (list, indent);
84 }
85
86 static const char*
87 get_il_security_action (int val) 
88 {
89         static char buf [32];
90
91         switch (val) {
92         case SECURITY_ACTION_DEMAND:
93                 return "demand";
94         case SECURITY_ACTION_ASSERT:
95                 return "assert";
96         case SECURITY_ACTION_DENY:
97                 return "deny";
98         case SECURITY_ACTION_PERMITONLY:
99                 return "permitonly";
100         case SECURITY_ACTION_LINKDEMAND:
101                 return "linkcheck";
102         case SECURITY_ACTION_INHERITDEMAND:
103                 return "inheritcheck";
104         case SECURITY_ACTION_REQMIN:
105                 return "reqmin";
106         case SECURITY_ACTION_REQOPT:
107                 return "reqopt";
108         case SECURITY_ACTION_REQREFUSE:
109                 return "reqrefuse";
110         /* Special actions (for non CAS permissions) */
111         case SECURITY_ACTION_NONCASDEMAND:
112                 return "noncasdemand";
113         case SECURITY_ACTION_NONCASLINKDEMAND:
114                 return "noncaslinkdemand";
115         case SECURITY_ACTION_NONCASINHERITANCE:
116                 return "noncasinheritance";
117         /* Fx 2.0 actions (for both CAS and non-CAS permissions) */
118         case SECURITY_ACTION_LINKDEMANDCHOICE:
119                 return "linkdemandor";
120         case SECURITY_ACTION_INHERITDEMANDCHOICE:
121                 return "inheritancedemandor";
122         case SECURITY_ACTION_DEMANDCHOICE:
123                 return "demandor";
124         default:
125                 g_snprintf (buf, sizeof (buf), "0x%04X", val);
126                 return buf;
127         }
128 }
129
130 #define OBJECT_TYPE_TYPEDEF     0
131 #define OBJECT_TYPE_METHODDEF   1
132 #define OBJECT_TYPE_ASSEMBLYDEF 2
133
134 static void
135 dump_declarative_security (MonoImage *m, guint32 objectType, guint32 token, const char *indent)
136 {
137         MonoTableInfo *t = &m->tables [MONO_TABLE_DECLSECURITY];
138         guint32 cols [MONO_DECL_SECURITY_SIZE];
139         int i, len;
140         guint32 idx;
141         const char *blob, *action;
142         
143         for (i = 1; i <= t->rows; i++) {
144                 mono_metadata_decode_row (t, i - 1, cols, MONO_DECL_SECURITY_SIZE);
145                 blob = mono_metadata_blob_heap (m, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
146                 len = mono_metadata_decode_blob_size (blob, &blob);
147                 action = get_il_security_action (cols [MONO_DECL_SECURITY_ACTION]);
148                 idx = cols [MONO_DECL_SECURITY_PARENT];
149                 if (((idx & MONO_HAS_DECL_SECURITY_MASK) == objectType) && ((idx >> MONO_HAS_DECL_SECURITY_BITS) == token)) {
150                         char *dump;
151                         if (blob [0] == MONO_DECLSEC_FORMAT_20) {
152                                 /* 2.0 declarative security format */
153                                 dump = dump_declsec_entry20 (m, blob, indent);
154                                 fprintf (output, "%s.permissionset %s = %s\n", indent, action, dump);
155                         } else {
156                                 /* 1.x declarative security metadata format */
157                                 dump = data_dump (blob, len, indent);
158                                 fprintf (output, "%s.permissionset %s = %s", indent, action, dump);
159                         }
160                         g_free (dump);
161                 }
162         }
163 }
164
165 static char *
166 assembly_flags (guint32 f)
167 {
168         if (f & ASSEMBLYREF_RETARGETABLE_FLAG)
169                 return g_strdup ("retargetable ");
170         return g_strdup ("");
171 }
172
173 static void
174 dis_directive_assembly (MonoImage *m)
175 {
176         MonoTableInfo *t  = &m->tables [MONO_TABLE_ASSEMBLY];
177         guint32 cols [MONO_ASSEMBLY_SIZE];
178         char *flags;
179         
180         if (t->base == NULL)
181                 return;
182
183         mono_metadata_decode_row (t, 0, cols, MONO_ASSEMBLY_SIZE);
184         flags = assembly_flags (cols [MONO_ASSEMBLY_FLAGS]);
185         
186         fprintf (output, ".assembly %s'%s'\n{\n",
187                  flags, mono_metadata_string_heap (m, cols [MONO_ASSEMBLY_NAME]));
188         dump_cattrs (m, MONO_TOKEN_ASSEMBLY | 1, "  ");
189         dump_declarative_security (m, OBJECT_TYPE_ASSEMBLYDEF, 1, "  ");
190         fprintf (output,
191                  "  .hash algorithm 0x%08x\n"
192                  "  .ver  %d:%d:%d:%d\n",
193                  cols [MONO_ASSEMBLY_HASH_ALG],
194                  cols [MONO_ASSEMBLY_MAJOR_VERSION], cols [MONO_ASSEMBLY_MINOR_VERSION], 
195                  cols [MONO_ASSEMBLY_BUILD_NUMBER], cols [MONO_ASSEMBLY_REV_NUMBER]);
196         if (cols [MONO_ASSEMBLY_CULTURE]){
197                 const char *locale = mono_metadata_string_heap (m, cols [MONO_ASSEMBLY_CULTURE]);
198                 glong items_read, items_written;
199                 gunichar2 *render = g_utf8_to_utf16 (locale, strlen (locale), &items_read, &items_written, NULL);
200                 char *dump = data_dump ((const char *) render, items_written * sizeof (gunichar2), "\t\t");
201                 fprintf (output, "  .locale %s\n", dump);
202                 g_free (dump);
203                 g_free (render);
204                 
205         } if (cols [MONO_ASSEMBLY_PUBLIC_KEY]) {
206                 const char* b = mono_metadata_blob_heap (m, cols [MONO_ASSEMBLY_PUBLIC_KEY]);
207                 int len = mono_metadata_decode_blob_size (b, &b);
208                 char *dump = data_dump (b, len, "\t\t");
209                 fprintf (output, "  .publickey =%s", dump);
210                 g_free (dump);
211         }
212         fprintf (output, "}\n");
213         
214         g_free (flags);
215 }
216
217 static void
218 dis_directive_assemblyref (MonoImage *m)
219 {
220         MonoTableInfo *t = &m->tables [MONO_TABLE_ASSEMBLYREF];
221         guint32 cols [MONO_ASSEMBLYREF_SIZE];
222         int i;
223         
224         if (t->base == NULL)
225                 return;
226
227         for (i = 0; i < t->rows; i++){
228                 char *esc, *flags;
229
230                 mono_metadata_decode_row (t, i, cols, MONO_ASSEMBLYREF_SIZE);
231
232                 esc = get_escaped_name (mono_metadata_string_heap (m, cols [MONO_ASSEMBLYREF_NAME]));
233                 flags = assembly_flags (cols [MONO_ASSEMBLYREF_FLAGS]);
234                 
235                 fprintf (output,
236                          ".assembly extern %s%s\n"
237                          "{\n"
238                          "  .ver %d:%d:%d:%d\n",
239                          flags,
240                          esc,
241                          cols [MONO_ASSEMBLYREF_MAJOR_VERSION], cols [MONO_ASSEMBLYREF_MINOR_VERSION], 
242                          cols [MONO_ASSEMBLYREF_BUILD_NUMBER], cols [MONO_ASSEMBLYREF_REV_NUMBER]
243                         );
244                 dump_cattrs (m, MONO_TOKEN_ASSEMBLY_REF | (i + 1), "  ");
245                 if (cols [MONO_ASSEMBLYREF_CULTURE]){
246                         fprintf (output, "  .locale %s\n", mono_metadata_string_heap (m, cols [MONO_ASSEMBLYREF_CULTURE]));
247                 }
248                 if (cols [MONO_ASSEMBLYREF_PUBLIC_KEY]){
249                         const char* b = mono_metadata_blob_heap (m, cols [MONO_ASSEMBLYREF_PUBLIC_KEY]);
250                         int len = mono_metadata_decode_blob_size (b, &b);
251                         char *dump = data_dump (b, len, "\t\t");
252                         fprintf (output, "  .publickeytoken =%s", dump);
253                         g_free (dump);
254                 }
255                 fprintf (output, "}\n");
256                 g_free (flags);
257                 g_free (esc);
258         }
259 }
260
261 static void
262 dis_directive_module (MonoImage *m)
263 {
264         MonoTableInfo *t = &m->tables [MONO_TABLE_MODULE];
265         int i;
266
267         for (i = 0; i < t->rows; i++){
268                 guint32 cols [MONO_MODULE_SIZE];
269                 const char *name;
270                 char *guid, *ename;
271                 
272                 mono_metadata_decode_row (t, i, cols, MONO_MODULE_SIZE);
273
274                 name = mono_metadata_string_heap (m, cols [MONO_MODULE_NAME]);
275                 ename = get_escaped_name (name);
276                 guid = get_guid (m, cols [MONO_MODULE_MVID]);
277                 fprintf (output, ".module %s // GUID = %s\n\n", ename, guid);
278                 g_free (ename);
279
280                 dump_cattrs (m, MONO_TOKEN_MODULE | (i + 1), "");
281         }
282 }
283
284 static void
285 dis_directive_moduleref (MonoImage *m)
286 {
287         MonoTableInfo *t = &m->tables [MONO_TABLE_MODULEREF];
288         int i;
289
290         for (i = 0; i < t->rows; i++){
291                 guint32 cols [MONO_MODULEREF_SIZE];
292                 
293                 mono_metadata_decode_row (t, i, cols, MONO_MODULEREF_SIZE);
294
295                 fprintf (output, ".module extern '%s'\n", mono_metadata_string_heap (m, cols [MONO_MODULEREF_NAME]));
296         }
297         
298 }
299
300 static void
301 dis_nt_header (MonoImage *m)
302 {
303         MonoCLIImageInfo *image_info = m->image_info;
304         if (image_info && image_info->cli_header.nt.pe_stack_reserve != 0x100000)
305                 fprintf (output, ".stackreserve 0x%x\n", image_info->cli_header.nt.pe_stack_reserve);
306 }
307
308 static void
309 dis_directive_file (MonoImage *m)
310 {
311         MonoTableInfo *t = &m->tables [MONO_TABLE_FILE];
312         int i, j, len;
313         guint32 entry_point;
314
315         entry_point = mono_image_get_entry_point (m);
316
317         for (i = 0; i < t->rows; i++){
318                 guint32 cols [MONO_FILE_SIZE];
319                 const char *name, *hash;
320                 guint32 token;
321
322                 mono_metadata_decode_row (t, i, cols, MONO_FILE_SIZE);
323
324                 name = mono_metadata_string_heap (m, cols [MONO_FILE_NAME]);
325
326                 hash = mono_metadata_blob_heap (m, cols [MONO_FILE_HASH_VALUE]);
327                 len = mono_metadata_decode_blob_size (hash, &hash);
328
329                 fprintf (output, ".file %s%s .hash = (",
330                                 cols [MONO_FILE_FLAGS] & FILE_CONTAINS_NO_METADATA ? "nometadata " : "", name);
331
332                 for (j = 0; j < len; ++j)
333                         fprintf (output, " %02X", hash [j] & 0xff);
334
335                 token = mono_metadata_make_token (MONO_TABLE_FILE, i + 1);
336                 fprintf (output, " )%s\n", (token == entry_point) ? " .entrypoint" : "");
337         }
338         
339 }
340
341 static void
342 dis_directive_mresource (MonoImage *m)
343 {
344         MonoTableInfo *t = &m->tables [MONO_TABLE_MANIFESTRESOURCE];
345         int i;
346
347         for (i = 0; i < t->rows; i++){
348                 guint32 cols [MONO_MANIFEST_SIZE];
349                 const char *name;
350                 guint32 impl, idx, name_token;
351
352                 mono_metadata_decode_row (t, i, cols, MONO_MANIFEST_SIZE);
353
354                 name = mono_metadata_string_heap (m, cols [MONO_MANIFEST_NAME]);
355
356                 fprintf (output, ".mresource %s '%s'\n", (cols [MONO_MANIFEST_FLAGS] & MANIFEST_RESOURCE_VISIBILITY_MASK) == (MANIFEST_RESOURCE_PUBLIC) ? "public" : "private", name);
357                 fprintf (output, "{\n");
358                 impl = cols [MONO_MANIFEST_IMPLEMENTATION];
359                 if (impl) {
360                         idx = impl >> MONO_IMPLEMENTATION_BITS;
361                         if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE) {
362                                 name_token = mono_metadata_decode_row_col (&m->tables [MONO_TABLE_FILE], idx - 1, MONO_FILE_NAME);
363
364                                 fprintf (output, "    .file '%s' at 0x0\n", mono_metadata_string_heap (m, name_token));
365                         }
366                         if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_ASSEMBLYREF) {
367                                 name_token = mono_metadata_decode_row_col (&m->tables [MONO_TABLE_ASSEMBLYREF], idx - 1, MONO_ASSEMBLYREF_NAME);
368                                 fprintf (output, "    .assembly extern '%s'\n", mono_metadata_string_heap (m, name_token));
369                         }
370                 }                               
371                 fprintf (output, "}\n");
372         }
373         
374 }
375
376 static dis_map_t visibility_map [] = {
377         { TYPE_ATTRIBUTE_NOT_PUBLIC,           "private " },
378         { TYPE_ATTRIBUTE_PUBLIC,               "public " },
379         { TYPE_ATTRIBUTE_NESTED_PUBLIC,        "nested public " },
380         { TYPE_ATTRIBUTE_NESTED_PRIVATE,       "nested private " },
381         { TYPE_ATTRIBUTE_NESTED_FAMILY,        "nested family " },
382         { TYPE_ATTRIBUTE_NESTED_ASSEMBLY,      "nested assembly " },
383         { TYPE_ATTRIBUTE_NESTED_FAM_AND_ASSEM, "nested famandassem " },
384         { TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM,  "nested famorassem " },
385         { 0, NULL }
386 };
387
388 static dis_map_t layout_map [] = {
389         { TYPE_ATTRIBUTE_AUTO_LAYOUT,          "auto " },
390         { TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT,    "sequential " },
391         { TYPE_ATTRIBUTE_EXPLICIT_LAYOUT,      "explicit " },
392         { 0, NULL }
393 };
394
395 static dis_map_t format_map [] = {
396         { TYPE_ATTRIBUTE_ANSI_CLASS,           "ansi " },
397         { TYPE_ATTRIBUTE_UNICODE_CLASS,        "unicode " },
398         { TYPE_ATTRIBUTE_AUTO_CLASS,           "auto " },
399         { 0, NULL }
400 };
401
402 static char *
403 typedef_flags (guint32 flags)
404 {
405         static char buffer [1024];
406         int visibility = flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
407         int layout = flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
408         int format = flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK;
409         
410         buffer [0] = 0;
411
412         strcat (buffer, map (visibility, visibility_map));
413         strcat (buffer, map (layout, layout_map));
414         strcat (buffer, map (format, format_map));
415         
416         if (flags & TYPE_ATTRIBUTE_ABSTRACT)
417                 strcat (buffer, "abstract ");
418         if (flags & TYPE_ATTRIBUTE_SEALED)
419                 strcat (buffer, "sealed ");
420         if (flags & TYPE_ATTRIBUTE_SPECIAL_NAME)
421                 strcat (buffer, "specialname ");
422         if (flags & TYPE_ATTRIBUTE_IMPORT)
423                 strcat (buffer, "import ");
424         if (flags & TYPE_ATTRIBUTE_SERIALIZABLE)
425                 strcat (buffer, "serializable ");
426         if (flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)
427                 strcat (buffer, "beforefieldinit ");
428         if (flags & TYPE_ATTRIBUTE_FORWARDER)
429                 strcat (buffer, "forwarder ");
430
431         return buffer;
432 }
433
434 /**
435  * dis_field_list:
436  * @m: metadata context
437  * @start: starting index into the Field Table.
438  * @end: ending index into Field table.
439  *
440  * This routine displays all the decoded fields from @start to @end
441  */
442 static void
443 dis_field_list (MonoImage *m, guint32 start, guint32 end, MonoGenericContainer *container)
444 {
445         MonoTableInfo *t = &m->tables [MONO_TABLE_FIELD];
446         guint32 cols [MONO_FIELD_SIZE];
447         char *esname;
448         char rva_desc [32];
449         guint32 rva;
450         int i;
451
452         if (end > t->rows + 1) {
453                 g_warning ("ERROR index out of range in fields");
454                 end = t->rows;
455         }
456                         
457         for (i = start; i < end; i++){
458                 char *sig, *flags, *attrs = NULL;
459                 char *marshal_str = NULL;
460                 guint32 field_offset = -1;
461
462                 if (!should_include_field (i + 1))
463                         continue;
464                 mono_metadata_decode_row (t, i, cols, MONO_FIELD_SIZE);
465                 sig = get_field_signature (m, cols [MONO_FIELD_SIGNATURE], container);
466                 flags = field_flags (cols [MONO_FIELD_FLAGS]);
467                 
468                 if (cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL) {
469                         const char *tp;
470                         MonoMarshalSpec *spec;
471                         
472                         tp = mono_metadata_get_marshal_info (m, i, TRUE);
473                         spec = mono_metadata_parse_marshal_spec (m, tp);
474                         marshal_str = dis_stringify_marshal_spec (spec);
475                 }
476
477                 if (cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_HAS_FIELD_RVA) {
478                         mono_metadata_field_info (m, i, NULL, &rva, NULL);
479                         g_snprintf (rva_desc, sizeof (rva_desc), " at D_%08x", rva);
480                 } else {
481                         rva_desc [0] = 0;
482                 }
483                 
484                 mono_metadata_field_info (m, i, &field_offset, NULL, NULL);
485                 if (field_offset != -1)
486                         attrs = g_strdup_printf ("[%d]", field_offset);
487                 esname = get_escaped_name (mono_metadata_string_heap (m, cols [MONO_FIELD_NAME]));
488                 if (cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_HAS_DEFAULT){
489                         char *lit;
490                         guint32 const_cols [MONO_CONSTANT_SIZE];
491                         guint32 crow;
492                         
493                         if ((crow = mono_metadata_get_constant_index (m, MONO_TOKEN_FIELD_DEF | (i+1), 0))) {
494                                 mono_metadata_decode_row (&m->tables [MONO_TABLE_CONSTANT], crow-1, const_cols, MONO_CONSTANT_SIZE);
495                                 lit = get_constant (m, const_cols [MONO_CONSTANT_TYPE], const_cols [MONO_CONSTANT_VALUE]);
496                         } else {
497                                 lit = g_strdup ("not found");
498                         }
499                         
500                         fprintf (output, "    .field %s%s%s %s = ",
501                                  flags, marshal_str ? marshal_str : " ", sig, esname);
502                         fprintf (output, "%s\n", lit);
503                         g_free (lit);
504                 } else
505                         fprintf (output, "    .field %s %s%s%s %s%s\n",
506                                  attrs? attrs: "", flags, marshal_str ? marshal_str : " ", sig, esname, rva_desc);
507                 g_free (attrs);
508                 g_free (flags);
509                 g_free (marshal_str);
510                 g_free (sig);
511                 g_free (esname);
512                 dump_cattrs (m, MONO_TOKEN_FIELD_DEF | (i + 1), "    ");
513         }
514 }
515
516 static dis_map_t method_access_map [] = {
517         { METHOD_ATTRIBUTE_COMPILER_CONTROLLED, "privatescope " },
518         { METHOD_ATTRIBUTE_PRIVATE,             "private " },
519         { METHOD_ATTRIBUTE_FAM_AND_ASSEM,       "famandassem " },
520         { METHOD_ATTRIBUTE_ASSEM,               "assembly " },
521         { METHOD_ATTRIBUTE_FAMILY,              "family " },
522         { METHOD_ATTRIBUTE_FAM_OR_ASSEM,        "famorassem " },
523         { METHOD_ATTRIBUTE_PUBLIC,              "public " },
524         { 0, NULL }
525 };
526
527 static dis_map_t method_flags_map [] = {
528         { METHOD_ATTRIBUTE_STATIC,              "static " },
529         { METHOD_ATTRIBUTE_FINAL,               "final " },
530         { METHOD_ATTRIBUTE_VIRTUAL,             "virtual " },
531         { METHOD_ATTRIBUTE_HIDE_BY_SIG,         "hidebysig " },
532         { METHOD_ATTRIBUTE_VTABLE_LAYOUT_MASK,  "newslot " },
533         { METHOD_ATTRIBUTE_ABSTRACT,            "abstract " },
534         { METHOD_ATTRIBUTE_SPECIAL_NAME,        "specialname " },
535         { METHOD_ATTRIBUTE_RT_SPECIAL_NAME,     "rtspecialname " },
536         { METHOD_ATTRIBUTE_UNMANAGED_EXPORT,    "export " },
537 /* MS ilasm doesn't compile this statement - is must be added automagically when permissionset are present */
538 /*      { METHOD_ATTRIBUTE_HAS_SECURITY,        "hassecurity" }, */
539         { METHOD_ATTRIBUTE_REQUIRE_SEC_OBJECT,  "requiresecobj" },
540         { METHOD_ATTRIBUTE_PINVOKE_IMPL,        "pinvokeimpl " }, 
541         { 0, NULL }
542 };
543
544 /**
545  * method_flags:
546  *
547  * Returns a stringified version of the Method's flags
548  */
549 static char *
550 method_flags (guint32 f)
551 {
552         GString *str = g_string_new ("");
553         int access = f & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK;
554         char *s;
555         
556         g_string_append (str, map (access, method_access_map));
557         g_string_append (str, flags (f, method_flags_map));
558
559         s = str->str;
560         g_string_free (str, FALSE);
561
562         return s;
563 }
564
565 static dis_map_t pinvoke_flags_map [] = {
566         { PINVOKE_ATTRIBUTE_NO_MANGLE ,            "nomangle " },
567         { PINVOKE_ATTRIBUTE_SUPPORTS_LAST_ERROR,   "lasterr " },
568         { PINVOKE_ATTRIBUTE_BEST_FIT_ENABLED,      "bestfit:on" },
569         { PINVOKE_ATTRIBUTE_BEST_FIT_DISABLED,      "bestfit:off" },
570         { PINVOKE_ATTRIBUTE_THROW_ON_UNMAPPABLE_ENABLED, "charmaperror:on" },
571         { PINVOKE_ATTRIBUTE_THROW_ON_UNMAPPABLE_DISABLED, "charmaperror:off" },
572         { 0, NULL }
573 };
574
575 static dis_map_t pinvoke_call_conv_map [] = {
576         { PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI,      "winapi " },
577         { PINVOKE_ATTRIBUTE_CALL_CONV_CDECL,       "cdecl " },
578         { PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL,     "stdcall " },
579         { PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL,    "thiscall " },
580         { PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL,    "fastcall " },
581         { 0, "" },
582         { -1, NULL }
583 };
584
585 static dis_map_t pinvoke_char_set_map [] = {
586         { PINVOKE_ATTRIBUTE_CHAR_SET_NOT_SPEC,     "" },
587         { PINVOKE_ATTRIBUTE_CHAR_SET_ANSI,         "ansi " },
588         { PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE ,     "unicode " },
589         { PINVOKE_ATTRIBUTE_CHAR_SET_AUTO,         "autochar " },
590         { 0, NULL }
591 };
592
593 /**
594  * pinvoke_flags:
595  *
596  * Returns a stringified version of the Method's pinvoke flags
597  */
598 static char *
599 pinvoke_flags (guint32 f)
600 {
601         GString *str = g_string_new ("");
602         int cset = f & PINVOKE_ATTRIBUTE_CHAR_SET_MASK;
603         int cconv = f & PINVOKE_ATTRIBUTE_CALL_CONV_MASK;
604         char *s;
605
606         g_string_append (str, map (cset, pinvoke_char_set_map));
607         g_string_append (str, map (cconv, pinvoke_call_conv_map));
608         g_string_append (str, flags (f, pinvoke_flags_map));
609
610         s = g_strdup(str->str);
611         g_string_free (str, FALSE);
612
613         return s;
614 }
615
616 static dis_map_t method_impl_map [] = {
617         { METHOD_IMPL_ATTRIBUTE_IL,              "cil " },
618         { METHOD_IMPL_ATTRIBUTE_NATIVE,          "native " },
619         { METHOD_IMPL_ATTRIBUTE_OPTIL,           "optil " },
620         { METHOD_IMPL_ATTRIBUTE_RUNTIME,         "runtime " },
621         { 0, NULL }
622 };
623
624 static dis_map_t managed_type_map [] = {
625         { METHOD_IMPL_ATTRIBUTE_UNMANAGED,       "unmanaged " },
626         { METHOD_IMPL_ATTRIBUTE_MANAGED,         "managed " },
627         { 0, NULL }
628 };
629
630 static dis_map_t managed_impl_flags [] = {
631         { METHOD_IMPL_ATTRIBUTE_FORWARD_REF,     "fwdref " },
632         { METHOD_IMPL_ATTRIBUTE_PRESERVE_SIG,    "preservesig " },
633         { METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL,   "internalcall " },
634         { METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED,    "synchronized " },
635         { METHOD_IMPL_ATTRIBUTE_NOINLINING,      "noinlining " },
636         { 0, NULL }
637 };
638
639 static char *
640 method_impl_flags (guint32 f)
641 {
642         GString *str = g_string_new ("");
643         char *s;
644         int code_type = f & METHOD_IMPL_ATTRIBUTE_CODE_TYPE_MASK;
645         int managed_type = f & METHOD_IMPL_ATTRIBUTE_MANAGED_MASK;
646
647         g_string_append (str, map (code_type, method_impl_map));
648         g_string_append (str, map (managed_type, managed_type_map));
649         g_string_append (str, flags (f, managed_impl_flags));
650         
651         s = str->str;
652         g_string_free (str, FALSE);
653         return s;
654 }
655
656 static void
657 dis_locals (MonoImage *m, MonoMethodHeader *mh, const char *ptr) 
658 {
659         int i;
660
661         if (show_tokens) {
662                 unsigned char flags = *(const unsigned char *) ptr;
663                 unsigned char format = flags & METHOD_HEADER_FORMAT_MASK;
664                 guint16 fat_flags;
665                 guint32 local_var_sig_tok, max_stack, code_size, init_locals;
666                 int hsize;
667
668                 g_assert (format == METHOD_HEADER_FAT_FORMAT);
669                 fat_flags = read16 (ptr);
670                 ptr += 2;
671                 hsize = (fat_flags >> 12) & 0xf;
672                 max_stack = read16 (ptr);
673                 ptr += 2;
674                 code_size = read32 (ptr);
675                 ptr += 4;
676                 local_var_sig_tok = read32 (ptr);
677                 ptr += 4;
678
679                 if (fat_flags & METHOD_HEADER_INIT_LOCALS)
680                         init_locals = 1;
681                 else
682                         init_locals = 0;
683
684                 fprintf(output, "\t.locals /*%08x*/ %s(\n",
685                         local_var_sig_tok, init_locals ? "init " : "");
686         } else
687                 fprintf(output, "\t.locals %s(\n", mh->init_locals ? "init " : "");
688
689         for (i=0; i < mh->num_locals; ++i) {
690                 char * desc;
691                 if (i)
692                         fprintf(output, ",\n");
693                 /* print also byref and pinned attributes */
694                 desc = dis_stringify_type (m, mh->locals[i], TRUE);
695                 fprintf(output, "\t\t%s\tV_%d", desc, i);
696                 g_free(desc);
697         }
698         fprintf(output, ")\n");
699 }
700
701 static void
702 dis_code (MonoImage *m, guint32 token, guint32 rva, MonoGenericContainer *container)
703 {
704         MonoMethodHeader *mh;
705         const char *ptr = mono_image_rva_map (m, rva);
706         const char *loc;
707         gchar *override;
708         guint32 entry_point;
709
710         if (rva == 0)
711                 return;
712
713         override = get_method_override (m, token, container);
714         if (override) {
715                 fprintf (output, "\t.override %s\n", override);
716                 g_free (override);
717         }
718
719         mh = mono_metadata_parse_mh_full (m, container, ptr);
720         if ((entry_point = mono_image_get_entry_point (m))){
721                 loc = mono_metadata_locate_token (m, entry_point);
722                 if (rva == read32 (loc))
723                         fprintf (output, "\t.entrypoint\n");
724         }
725         
726         fprintf (output, "\t// Code size %d (0x%x)\n", mh->code_size, mh->code_size);
727         fprintf (output, "\t.maxstack %d\n", mh->max_stack);
728         if (mh->num_locals)
729                 dis_locals (m, mh, ptr);
730         disassemble_cil (m, mh, container);
731         
732 /*
733   hex_dump (mh->code, 0, mh->code_size);
734   printf ("\nAfter the code\n");
735   hex_dump (mh->code + mh->code_size, 0, 64);
736 */
737         mono_metadata_free_mh (mh);
738 }
739
740 static char *
741 pinvoke_info (MonoImage *m, guint32 mindex)
742 {
743         MonoTableInfo *im = &m->tables [MONO_TABLE_IMPLMAP];
744         MonoTableInfo *mr = &m->tables [MONO_TABLE_MODULEREF];
745         guint32 im_cols [MONO_IMPLMAP_SIZE];
746         guint32 mr_cols [MONO_MODULEREF_SIZE];
747         const char *import, *scope;
748         char *flags;
749         int i;
750
751         for (i = 0; i < im->rows; i++) {
752
753                 mono_metadata_decode_row (im, i, im_cols, MONO_IMPLMAP_SIZE);
754
755                 if ((im_cols [MONO_IMPLMAP_MEMBER] >> 1) == mindex + 1) {
756
757                         flags = pinvoke_flags (im_cols [MONO_IMPLMAP_FLAGS]);
758
759                         import = mono_metadata_string_heap (m, im_cols [MONO_IMPLMAP_NAME]);
760
761                         mono_metadata_decode_row (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, 
762                                                   mr_cols, MONO_MODULEREF_SIZE);
763
764                         scope = mono_metadata_string_heap (m, mr_cols [MONO_MODULEREF_NAME]);
765                                 
766                         return g_strdup_printf ("(\"%s\" as \"%s\" %s)", scope, import,
767                                                 flags);
768                         g_free (flags);
769                 }
770         }
771
772         return NULL;
773 }
774
775 /*
776  * dump_cattrs_for_type_params
777  *
778  * @m: 
779  * @token: TypeOrMethodDef token, owner for GenericParam
780  *
781  * Dumps the custom attributes for @token's type parameters
782  */
783 static void
784 dump_cattrs_for_type_params (MonoImage *m, guint32 token, const char *indent)
785 {
786         MonoTableInfo *tdef  = &m->tables [MONO_TABLE_GENERICPARAM];
787         guint32 cols [MONO_GENERICPARAM_SIZE];
788         guint32 owner = 0, i;
789         GList *list = NULL;
790
791         if (! (i = mono_metadata_get_generic_param_row (m, token, &owner)))
792                 return;
793
794         mono_metadata_decode_row (tdef, i - 1, cols, MONO_GENERICPARAM_SIZE);
795         do {
796                 list = dis_get_custom_attrs (m, mono_metadata_make_token (MONO_TABLE_GENERICPARAM, i));
797                 if (list) {
798                         fprintf (output, "%s.param type %s\n", indent, mono_metadata_string_heap (m, cols [MONO_GENERICPARAM_NAME]));
799                         dump_cattrs_list (list, indent);
800                 }
801
802                 if (++i > tdef->rows)
803                         break;
804                 mono_metadata_decode_row (tdef, i - 1, cols, MONO_GENERICPARAM_SIZE);
805         } while (cols [MONO_GENERICPARAM_OWNER] == owner);
806 }
807
808 static void
809 dump_cattrs_for_method_params (MonoImage *m, guint32 midx, MonoMethodSignature *sig) {
810         MonoTableInfo *methodt;
811         MonoTableInfo *paramt;
812         guint param_index, lastp, i;
813
814         methodt = &m->tables [MONO_TABLE_METHOD];
815         paramt = &m->tables [MONO_TABLE_PARAM];
816         param_index = mono_metadata_decode_row_col (methodt, midx, MONO_METHOD_PARAMLIST);
817         if (midx + 1 < methodt->rows)
818                 lastp = mono_metadata_decode_row_col (methodt, midx + 1, MONO_METHOD_PARAMLIST);
819         else
820                 lastp = paramt->rows + 1;
821         for (i = param_index; i < lastp; ++i) {
822                 char *lit;
823                 int crow;
824                 guint32 param_cols [MONO_PARAM_SIZE];
825                 GList *list;
826                 
827                 list = dis_get_custom_attrs (m, MONO_TOKEN_PARAM_DEF | i);
828
829                 mono_metadata_decode_row (paramt, i-1, param_cols, MONO_PARAM_SIZE);
830                 if (!(param_cols[MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_DEFAULT)) {
831                         if(list != NULL)
832                                 fprintf (output, "\t.param [%d]\n", param_cols[MONO_PARAM_SEQUENCE]);
833                 } else {
834                         fprintf (output, "\t.param [%d] = ", param_cols[MONO_PARAM_SEQUENCE]);
835                   
836                         if ((crow = mono_metadata_get_constant_index(m, MONO_TOKEN_PARAM_DEF | i, 0))) {
837                                 guint32 const_cols [MONO_CONSTANT_SIZE];
838                                 mono_metadata_decode_row( &m->tables[MONO_TABLE_CONSTANT], crow-1, const_cols, MONO_CONSTANT_SIZE);
839                                 lit = get_constant(m, const_cols [MONO_CONSTANT_TYPE], const_cols [MONO_CONSTANT_VALUE]);
840                         }
841                         else {
842                                 lit = g_strdup ("not found");
843                         }
844                   fprintf(output, "%s\n", lit);
845                   g_free(lit);
846                 }
847                 dump_cattrs_list (list, "\t");
848         }
849 }
850
851 /**
852  * dis_method_list:
853  * @m: metadata context
854  * @start: starting index into the Method Table.
855  * @end: ending index into Method table.
856  *
857  * This routine displays the methods in the Method Table from @start to @end
858  */
859 static void
860 dis_method_list (const char *klass_name, MonoImage *m, guint32 start, guint32 end, MonoGenericContainer *type_container)
861 {
862         MonoTableInfo *t = &m->tables [MONO_TABLE_METHOD];
863         guint32 cols [MONO_METHOD_SIZE];
864         int i;
865
866         if (end > t->rows){
867                 fprintf (output, "ERROR index out of range in methods");
868                 /*exit (1);*/
869                 end = t->rows;
870         }
871
872         for (i = start; i < end; i++){
873                 MonoMethodSignature *ms;
874                 MonoGenericContainer *container;
875                 char *flags, *impl_flags;
876                 const char *sig, *method_name;
877                 char *sig_str;
878                 guint32 token;
879
880                 if (!should_include_method (i + 1))
881                         continue;
882                 mono_metadata_decode_row (t, i, cols, MONO_METHOD_SIZE);
883
884                 flags = method_flags (cols [MONO_METHOD_FLAGS]);
885                 impl_flags = method_impl_flags (cols [MONO_METHOD_IMPLFLAGS]);
886
887                 sig = mono_metadata_blob_heap (m, cols [MONO_METHOD_SIGNATURE]);
888                 mono_metadata_decode_blob_size (sig, &sig);
889
890                 container = mono_metadata_load_generic_params (m, MONO_TOKEN_METHOD_DEF | (i + 1), type_container);
891                 if (container)
892                         mono_metadata_load_generic_param_constraints (m, MONO_TOKEN_METHOD_DEF | (i + 1), container);
893                 else 
894                         container = type_container;
895
896                 ms = mono_metadata_parse_method_signature_full (m, container, i + 1, sig, &sig);
897                 sig_str = dis_stringify_method_signature (m, ms, i + 1, container, FALSE);
898                 method_name = mono_metadata_string_heap (m, cols [MONO_METHOD_NAME]);
899
900                 fprintf (output, "    // method line %d\n", i + 1);
901                 fprintf (output, "    .method %s", flags);
902
903                 if ((cols [MONO_METHOD_FLAGS] & METHOD_ATTRIBUTE_PINVOKE_IMPL) && (cols [MONO_METHOD_RVA] == 0)) {
904                         gchar *pi = pinvoke_info (m, i);
905                         if (pi) {
906                                 fprintf (output, "%s", pi);
907                                 g_free (pi);
908                         }
909                 }
910
911                 fprintf (output, "\n           %s", sig_str);
912                 fprintf (output, " %s\n", impl_flags);
913                 g_free (flags);
914                 g_free (impl_flags);
915
916                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
917                 
918                 fprintf (output, "    {\n");
919                 dump_cattrs (m, token, "        ");
920                 dump_cattrs_for_type_params (m, MONO_TOKEN_METHOD_DEF | (i + 1), "        ");
921                 dump_cattrs_for_method_params (m, i, ms);
922
923                 fprintf (output, "        // Method begins at RVA 0x%x\n", cols [MONO_METHOD_RVA]);
924                 dump_declarative_security (m, OBJECT_TYPE_METHODDEF, i + 1, "        ");
925                 if (cols [MONO_METHOD_IMPLFLAGS] & METHOD_IMPL_ATTRIBUTE_NATIVE)
926                         fprintf (output, "          // Disassembly of native methods is not supported\n");
927                 else
928                         dis_code (m, token, cols [MONO_METHOD_RVA], container);
929                 if (klass_name)
930                         fprintf (output, "    } // end of method %s::%s\n\n", klass_name, method_name);
931                 else
932                         fprintf (output, "    } // end of global method %s\n\n", method_name);
933                 mono_metadata_free_method_signature (ms);
934                 g_free (sig_str);
935         }
936 }
937
938 typedef struct {
939         MonoTableInfo *t;
940         guint32 col_idx;
941         guint32 idx;
942         guint32 result;
943 } plocator_t;
944
945 static int
946 table_locator (const void *a, const void *b)
947 {
948         plocator_t *loc = (plocator_t *) a;
949         const char *bb = (const char *) b;
950         guint32 table_index = (bb - loc->t->base) / loc->t->row_size;
951         guint32 col;
952         
953         col = mono_metadata_decode_row_col (loc->t, table_index, loc->col_idx);
954
955         if (loc->idx == col) {
956                 loc->result = table_index;
957                 return 0;
958         }
959         if (loc->idx < col)
960                 return -1;
961         else 
962                 return 1;
963 }
964
965 static void
966 dis_property_methods (MonoImage *m, guint32 prop, MonoGenericContainer *container)
967 {
968         guint start, end;
969         MonoTableInfo *msemt = &m->tables [MONO_TABLE_METHODSEMANTICS];
970         guint32 cols [MONO_METHOD_SEMA_SIZE];
971         char *sig;
972         const char *type[] = {NULL, ".set", ".get", NULL, ".other"};
973
974         start = mono_metadata_methods_from_property (m, prop, &end);
975         for (; start < end; ++start) {
976                 mono_metadata_decode_row (msemt, start, cols, MONO_METHOD_SEMA_SIZE);
977                 if (!should_include_method (cols [MONO_METHOD_SEMA_METHOD]))
978                         continue;
979                 sig = dis_stringify_method_signature_full (m, NULL, cols [MONO_METHOD_SEMA_METHOD], container, TRUE, FALSE);
980                 fprintf (output, "\t\t%s %s\n", type [cols [MONO_METHOD_SEMA_SEMANTICS]], sig);
981                 g_free (sig);
982         }
983 }
984 static char*
985 dis_property_signature (MonoImage *m, guint32 prop_idx, MonoGenericContainer *container)
986 {
987         MonoTableInfo *propt = &m->tables [MONO_TABLE_PROPERTY];
988         const char *ptr;
989         guint32 pcount, i;
990         guint32 cols [MONO_PROPERTY_SIZE];
991         MonoType *type;
992         MonoType *param;
993         char *blurb, *qk;
994         const char *name;
995         int prop_flags;
996         GString *res = g_string_new ("");
997
998         mono_metadata_decode_row (propt, prop_idx, cols, MONO_PROPERTY_SIZE);
999         name = mono_metadata_string_heap (m, cols [MONO_PROPERTY_NAME]);
1000         prop_flags = cols [MONO_PROPERTY_FLAGS];
1001         ptr = mono_metadata_blob_heap (m, cols [MONO_PROPERTY_TYPE]);
1002         mono_metadata_decode_blob_size (ptr, &ptr);
1003         if (!(*ptr & 0x08))
1004                 g_warning("incorrect signature in property blob: 0x%x", *ptr);
1005         if (*ptr & 0x20)
1006                 g_string_append (res, "instance ");
1007         ptr++;
1008         pcount = mono_metadata_decode_value (ptr, &ptr);
1009         type = mono_metadata_parse_type_full (m, container, MONO_PARSE_TYPE, 0, ptr, &ptr);
1010         blurb = dis_stringify_type (m, type, TRUE);
1011         if (prop_flags & 0x0200)
1012                 g_string_append (res, "specialname ");
1013         if (prop_flags & 0x0400)
1014                 g_string_append (res, "rtspecialname ");
1015         qk = get_escaped_name (name);
1016         g_string_sprintfa (res, "%s %s (", blurb, qk);
1017         g_free (qk);
1018         g_free (blurb);
1019         mono_metadata_free_type (type);
1020         for (i = 0; i < pcount; i++) {
1021                 if (i)
1022                         g_string_append (res, ", ");
1023                 param = mono_metadata_parse_type_full (m, container, MONO_PARSE_PARAM, 0, ptr, &ptr);
1024                 blurb = dis_stringify_param (m, param);
1025                 g_string_append (res, blurb);
1026                 mono_metadata_free_type (param);
1027                 g_free (blurb);
1028         }
1029         g_string_append_c (res, ')');
1030         blurb = res->str;
1031         g_string_free (res, FALSE);
1032         return blurb;
1033
1034 }
1035
1036 static void
1037 dis_property_list (MonoImage *m, guint32 typedef_row, MonoGenericContainer *container)
1038 {
1039         guint start, end, i;
1040         start = mono_metadata_properties_from_typedef (m, typedef_row, &end);
1041
1042         for (i = start; i < end; ++i) {
1043                 char *sig = dis_property_signature (m, i, container);
1044                 fprintf (output, "\t.property %s\n\t{\n", sig);
1045                 dump_cattrs (m, MONO_TOKEN_PROPERTY | (i + 1), "\t\t");
1046                 dis_property_methods (m, i, container);
1047                 fprintf (output, "\t}\n");
1048                 g_free (sig);
1049         }
1050 }
1051
1052 static char*
1053 dis_event_signature (MonoImage *m, guint32 event_idx, MonoGenericContainer *container)
1054 {
1055         MonoTableInfo *et = &m->tables [MONO_TABLE_EVENT];
1056         char *type, *result, *esname;
1057         guint32 cols [MONO_EVENT_SIZE];
1058         int event_flags;
1059         GString *res = g_string_new ("");
1060         
1061         mono_metadata_decode_row (et, event_idx, cols, MONO_EVENT_SIZE);
1062         esname = get_escaped_name (mono_metadata_string_heap (m, cols [MONO_EVENT_NAME]));
1063         type = get_typedef_or_ref (m, cols [MONO_EVENT_TYPE], container);
1064         event_flags = cols [MONO_EVENT_FLAGS];
1065
1066         if (event_flags & 0x0200)
1067                 g_string_append (res, "specialname ");
1068         if (event_flags & 0x0400)
1069                 g_string_append (res, "rtspecialname ");
1070         g_string_sprintfa (res, "%s %s", type, esname);
1071
1072         g_free (type);
1073         g_free (esname);
1074         result = res->str;
1075         g_string_free (res, FALSE);
1076         return result;
1077 }
1078
1079 static void
1080 dis_event_methods (MonoImage *m, guint32 event, MonoGenericContainer *container)
1081 {
1082         guint start, end;
1083         MonoTableInfo *msemt = &m->tables [MONO_TABLE_METHODSEMANTICS];
1084         guint32 cols [MONO_METHOD_SEMA_SIZE];
1085         char *sig;
1086         const char *type = "";
1087
1088         start = mono_metadata_methods_from_event (m, event, &end);
1089         for (; start < end; ++start) {
1090                 mono_metadata_decode_row (msemt, start, cols, MONO_METHOD_SEMA_SIZE);
1091                 if (!should_include_method (cols [MONO_METHOD_SEMA_METHOD]))
1092                         continue;
1093                 sig = dis_stringify_method_signature_full (m, NULL, cols [MONO_METHOD_SEMA_METHOD], container, TRUE, FALSE);
1094                 switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
1095                 case METHOD_SEMANTIC_OTHER:
1096                         type = ".other"; break;
1097                 case METHOD_SEMANTIC_ADD_ON:
1098                         type = ".addon"; break;
1099                 case METHOD_SEMANTIC_REMOVE_ON:
1100                         type = ".removeon"; break;
1101                 case METHOD_SEMANTIC_FIRE:
1102                         type = ".fire"; break;
1103                 default:
1104                         break;
1105                 }
1106                 fprintf (output, "\t\t%s %s\n", type, sig);
1107                 g_free (sig);
1108         }
1109 }
1110
1111 static void
1112 dis_event_list (MonoImage *m, guint32 typedef_row, MonoGenericContainer *container)
1113 {
1114         guint start, end, i;
1115         start = mono_metadata_events_from_typedef (m, typedef_row, &end);
1116
1117         for (i = start; i < end; ++i) {
1118                 char *sig = dis_event_signature (m, i, container);
1119                 fprintf (output, "\t.event %s\n\t{\n", sig);
1120                 dump_cattrs (m, MONO_TOKEN_EVENT | (i + 1), "\t\t");
1121                 dis_event_methods (m, i, container);
1122                 fprintf (output, "\t}\n");
1123                 g_free (sig);
1124         }
1125 }
1126
1127 static void
1128 dis_interfaces (MonoImage *m, guint32 typedef_row, MonoGenericContainer *container)
1129 {
1130         plocator_t loc;
1131         guint start;
1132         gboolean first_interface = 1;
1133         guint32 cols [MONO_INTERFACEIMPL_SIZE];
1134         char *intf;
1135         MonoTableInfo *table = &m->tables [MONO_TABLE_INTERFACEIMPL];
1136
1137         if (!table->base)
1138                 return;
1139
1140         loc.t = table;
1141         loc.col_idx = MONO_INTERFACEIMPL_CLASS;
1142         loc.idx = typedef_row;
1143
1144         if (!bsearch (&loc, table->base, table->rows, table->row_size, table_locator))
1145                 return;
1146
1147         start = loc.result;
1148         /*
1149          * We may end up in the middle of the rows... 
1150          */
1151         while (start > 0) {
1152                 if (loc.idx == mono_metadata_decode_row_col (table, start - 1, MONO_INTERFACEIMPL_CLASS))
1153                         start--;
1154                 else
1155                         break;
1156         }
1157         while (start < table->rows) {
1158                 mono_metadata_decode_row (table, start, cols, MONO_INTERFACEIMPL_SIZE);
1159                 if (cols [MONO_INTERFACEIMPL_CLASS] != loc.idx)
1160                         break;
1161                 intf = get_typedef_or_ref (m, cols [MONO_INTERFACEIMPL_INTERFACE], container);
1162                 if (first_interface) {
1163                         fprintf (output, "  \timplements %s", intf);
1164                         first_interface = 0;
1165                 } else {
1166                         fprintf (output, ", %s", intf);
1167                 }
1168                 g_free (intf);
1169                 ++start;
1170         }
1171 }
1172
1173 /**
1174  * dis_type:
1175  * @m: metadata context
1176  * @n: index of type to disassemble
1177  * @is_nested: nested type ?
1178  * @forward: forward declarations?
1179  *
1180  * Disassembles the type whose index in the TypeDef table is @n.
1181  */
1182 static void
1183 dis_type (MonoImage *m, int n, int is_nested, int forward)
1184 {
1185         MonoTableInfo *t = &m->tables [MONO_TABLE_TYPEDEF];
1186         guint32 cols [MONO_TYPEDEF_SIZE];
1187         guint32 cols_next [MONO_TYPEDEF_SIZE];
1188         const char *name, *nspace;
1189         char *esname, *param;
1190         MonoGenericContainer *container;
1191         guint32 packing_size, class_size;
1192         gboolean next_is_valid, last;
1193         guint32 nested;
1194
1195         if (!should_include_type (n + 1))
1196                 return;
1197         mono_metadata_decode_row (t, n, cols, MONO_TYPEDEF_SIZE);
1198
1199         if (t->rows > n + 1) {
1200                 mono_metadata_decode_row (t, n + 1, cols_next, MONO_TYPEDEF_SIZE);
1201                 next_is_valid = 1;
1202         } else
1203                 next_is_valid = 0;
1204
1205         name = mono_metadata_string_heap (m, cols [MONO_TYPEDEF_NAME]);
1206         nspace = mono_metadata_string_heap (m, cols [MONO_TYPEDEF_NAMESPACE]);
1207         if (*nspace && !is_nested) 
1208                 fprintf (output, ".namespace %s\n{\n", nspace);
1209
1210         container = mono_metadata_load_generic_params (m, MONO_TOKEN_TYPE_DEF | (n + 1), NULL);
1211         if (container)
1212                 mono_metadata_load_generic_param_constraints (m, MONO_TOKEN_TYPE_DEF | (n + 1), container);
1213
1214         esname = get_escaped_name (name);
1215         if ((cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_CLASS_SEMANTIC_MASK) == TYPE_ATTRIBUTE_CLASS){
1216                 fprintf (output, "  .class %s%s", typedef_flags (cols [MONO_TYPEDEF_FLAGS]), esname);
1217                 
1218                 param = get_generic_param (m, container);
1219                 if (param) {
1220                         fprintf (output, param);
1221                         g_free (param);
1222                 }
1223                 fprintf (output, "\n");
1224                 if (cols [MONO_TYPEDEF_EXTENDS]) {
1225                         char *base = get_typedef_or_ref (m, cols [MONO_TYPEDEF_EXTENDS], container);
1226                         fprintf (output, "  \textends %s\n", base);
1227                         g_free (base);
1228                 }
1229         } else {
1230                 fprintf (output, "  .class interface %s%s", typedef_flags (cols [MONO_TYPEDEF_FLAGS]), esname);
1231
1232                 param = get_generic_param (m, container);
1233                 if (param) {
1234                         fprintf (output, param);
1235                         g_free (param);
1236                 }
1237                 fprintf (output, "\n");
1238         }
1239
1240         g_free (esname);
1241         dis_interfaces (m, n + 1, container);
1242         fprintf (output, "  {\n");
1243         if (!forward) {
1244                 dump_cattrs (m, MONO_TOKEN_TYPE_DEF | (n + 1), "    ");
1245                 dump_cattrs_for_type_params (m, MONO_TOKEN_TYPE_DEF | (n + 1), "    ");
1246                 dump_declarative_security (m, OBJECT_TYPE_TYPEDEF, (n + 1), "    ");
1247
1248                 if (mono_metadata_packing_from_typedef (m, n + 1, &packing_size, &class_size)) {
1249                         fprintf (output, "    .pack %d\n", packing_size);
1250                         fprintf (output, "    .size %d\n", class_size);
1251                 }
1252                 /*
1253                  * The value in the table is always valid, we know we have fields
1254                  * if the value stored is different than the next record.
1255                  */
1256         
1257                 if (next_is_valid)
1258                         last = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
1259                 else
1260                         last = m->tables [MONO_TABLE_FIELD].rows;
1261                         
1262                 if (cols [MONO_TYPEDEF_FIELD_LIST] && cols [MONO_TYPEDEF_FIELD_LIST] <= m->tables [MONO_TABLE_FIELD].rows)
1263                         dis_field_list (m, cols [MONO_TYPEDEF_FIELD_LIST] - 1, last, container);
1264                 fprintf (output, "\n");
1265
1266                 if (next_is_valid)
1267                         last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
1268                 else
1269                         last = m->tables [MONO_TABLE_METHOD].rows;
1270         
1271                 if (cols [MONO_TYPEDEF_METHOD_LIST] && cols [MONO_TYPEDEF_METHOD_LIST] <= m->tables [MONO_TABLE_METHOD].rows)
1272                         dis_method_list (name, m, cols [MONO_TYPEDEF_METHOD_LIST] - 1, last, container);
1273
1274                 dis_property_list (m, n, container);
1275                 dis_event_list (m, n, container);
1276         }
1277
1278         t = &m->tables [MONO_TABLE_NESTEDCLASS];
1279         nested = mono_metadata_nesting_typedef (m, n + 1, 1);
1280         while (nested) {
1281                 dis_type (m, mono_metadata_decode_row_col (t, nested - 1, MONO_NESTED_CLASS_NESTED) - 1, 1, forward);
1282                 nested = mono_metadata_nesting_typedef (m, n + 1, nested + 1);
1283         }
1284         
1285         fprintf (output, "  } // end of class %s%s%s\n", nspace, *nspace? ".": "", name);
1286         if (*nspace && !is_nested)
1287                 fprintf (output, "}\n");
1288         fprintf (output, "\n");
1289 }
1290
1291
1292 /**
1293  * dis_globals
1294  * @m: metadata context
1295  *
1296  * disassembles all the global fields and methods
1297  */
1298 static void
1299 dis_globals (MonoImage *m)
1300 {
1301         MonoTableInfo *t = &m->tables [MONO_TABLE_TYPEDEF];
1302         guint32 cols [MONO_TYPEDEF_SIZE];
1303         guint32 cols_next [MONO_TYPEDEF_SIZE];
1304         gboolean next_is_valid, last;
1305
1306         mono_metadata_decode_row (t, 0, cols, MONO_TYPEDEF_SIZE);
1307
1308         if (t->rows > 1) {
1309                 mono_metadata_decode_row (t, 1, cols_next, MONO_TYPEDEF_SIZE);
1310                 next_is_valid = 1;
1311         } else
1312                 next_is_valid = 0;
1313         
1314         /*
1315          * The value in the table is always valid, we know we have fields
1316          * if the value stored is different than the next record.
1317          */
1318
1319         if (next_is_valid)
1320                 last = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
1321         else
1322                 last = m->tables [MONO_TABLE_FIELD].rows;
1323                         
1324         if (cols [MONO_TYPEDEF_FIELD_LIST] && cols [MONO_TYPEDEF_FIELD_LIST] <= m->tables [MONO_TABLE_FIELD].rows)
1325                 dis_field_list (m, cols [MONO_TYPEDEF_FIELD_LIST] - 1, last, NULL);
1326         fprintf (output, "\n");
1327
1328         if (next_is_valid)
1329                 last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
1330         else
1331                 last = m->tables [MONO_TABLE_METHOD].rows;
1332         
1333         if (cols [MONO_TYPEDEF_METHOD_LIST] && cols [MONO_TYPEDEF_METHOD_LIST] <= m->tables [MONO_TABLE_METHOD].rows)
1334                 dis_method_list (NULL, m, cols [MONO_TYPEDEF_METHOD_LIST] - 1, last, NULL);
1335
1336 }
1337
1338 static void
1339 dis_mresource (MonoImage *m)
1340 {
1341         MonoTableInfo *t = &m->tables [MONO_TABLE_MANIFESTRESOURCE];
1342         int i;
1343         
1344         for (i = 0; i < t->rows; i++){
1345                 guint32 cols [MONO_MANIFEST_SIZE];
1346                 const char *name, *res;
1347                 guint32 size;
1348                 FILE* fp;
1349
1350                 mono_metadata_decode_row (t, i, cols, MONO_MANIFEST_SIZE);
1351                 name = mono_metadata_string_heap (m, cols [MONO_MANIFEST_NAME]);
1352                 
1353                 if (! (res = mono_image_get_resource (m, cols [MONO_MANIFEST_OFFSET], &size)))
1354                         continue;       
1355
1356                 if ( (fp = fopen (name, "ab")) ) {
1357                         if (ftell (fp) == 0)
1358                                 fwrite (res, size, 1, fp);
1359                         else 
1360                                 g_warning ("Error creating managed resource - %s : File already exists.", name);
1361
1362                         fclose (fp);
1363                 } else
1364                         g_warning ("Error creating managed resource - %s : %s", name, g_strerror (errno));
1365         }               
1366 }
1367
1368 /**
1369  * dis_types:
1370  * @m: metadata context
1371  *
1372  * disassembles all types in the @m context
1373  */
1374 static void
1375 dis_types (MonoImage *m, int forward)
1376 {
1377         MonoTableInfo *t = &m->tables [MONO_TABLE_TYPEDEF];
1378         int i;
1379         guint32 flags;
1380
1381         dis_globals (m);
1382         
1383         for (i = 1; i < t->rows; i++) {
1384                 flags = mono_metadata_decode_row_col (t, i, MONO_TYPEDEF_FLAGS);
1385                 flags &= TYPE_ATTRIBUTE_VISIBILITY_MASK;
1386                 if (flags == TYPE_ATTRIBUTE_PUBLIC || flags == TYPE_ATTRIBUTE_NOT_PUBLIC)
1387                         dis_type (m, i, 0, forward);
1388         }
1389 }
1390
1391 /**
1392  * dis_data:
1393  * @m: metadata context
1394  *
1395  * disassembles all data blobs references in the FieldRVA table in the @m context
1396  */
1397 static void
1398 dis_data (MonoImage *m)
1399 {
1400         MonoTableInfo *t = &m->tables [MONO_TABLE_FIELDRVA];
1401         MonoTableInfo *ft = &m->tables [MONO_TABLE_FIELD];
1402         int i, b;
1403         const char *rva, *sig;
1404         guint32 size;
1405         gint align;
1406         guint32 cols [MONO_FIELD_RVA_SIZE];
1407         MonoType *type;
1408
1409         for (i = 0; i < t->rows; i++) {
1410                 mono_metadata_decode_row (t, i, cols, MONO_FIELD_RVA_SIZE);
1411                 rva = mono_image_rva_map (m, cols [MONO_FIELD_RVA_RVA]);
1412                 sig = mono_metadata_blob_heap (m, mono_metadata_decode_row_col (ft, cols [MONO_FIELD_RVA_FIELD] -1, MONO_FIELD_SIGNATURE));
1413                 mono_metadata_decode_value (sig, &sig);
1414                 /* FIELD signature == 0x06 */
1415                 g_assert (*sig == 0x06);
1416                 type = mono_metadata_parse_field_type (m, 0, sig + 1, &sig);
1417                 mono_class_init (mono_class_from_mono_type (type));
1418                 size = mono_type_size (type, &align);
1419                 fprintf (output, ".data D_%08x = bytearray (", cols [MONO_FIELD_RVA_RVA]);
1420                 for (b = 0; b < size; ++b) {
1421                         if (!(b % 16))
1422                                 fprintf (output, "\n\t");
1423                         fprintf (output, " %02X", rva [b] & 0xff);
1424                 }
1425                 fprintf (output, ") // size: %d\n", size);
1426         }
1427 }
1428
1429 struct {
1430         const char *name;
1431         int table;
1432         void (*dumper) (MonoImage *m);
1433 } table_list [] = {
1434         { "--assembly",    MONO_TABLE_ASSEMBLY,         dump_table_assembly },
1435         { "--assemblyref", MONO_TABLE_ASSEMBLYREF,      dump_table_assemblyref },
1436         { "--classlayout", MONO_TABLE_CLASSLAYOUT,      dump_table_class_layout },
1437         { "--constant",    MONO_TABLE_CONSTANT,         dump_table_constant },
1438         { "--customattr",  MONO_TABLE_CUSTOMATTRIBUTE,  dump_table_customattr },
1439         { "--declsec",     MONO_TABLE_DECLSECURITY,     dump_table_declsec },
1440         { "--event",       MONO_TABLE_EVENT,            dump_table_event },
1441         { "--exported",    MONO_TABLE_EXPORTEDTYPE,     dump_table_exported },
1442         { "--fields",      MONO_TABLE_FIELD,            dump_table_field },
1443         { "--file",        MONO_TABLE_FILE,             dump_table_file },
1444         { "--genericpar",  MONO_TABLE_GENERICPARAM,     dump_table_genericpar },
1445         { "--interface",   MONO_TABLE_INTERFACEIMPL,    dump_table_interfaceimpl },
1446         { "--manifest",    MONO_TABLE_MANIFESTRESOURCE, dump_table_manifest },
1447         { "--marshal",     MONO_TABLE_FIELDMARSHAL,     dump_table_field_marshal },
1448         { "--memberref",   MONO_TABLE_MEMBERREF,        dump_table_memberref },
1449         { "--method",      MONO_TABLE_METHOD,           dump_table_method },
1450         { "--methodimpl",  MONO_TABLE_METHODIMPL,       dump_table_methodimpl },
1451         { "--methodsem",   MONO_TABLE_METHODSEMANTICS,  dump_table_methodsem },
1452         { "--methodspec",  MONO_TABLE_METHODSPEC,       dump_table_methodspec },
1453         { "--moduleref",   MONO_TABLE_MODULEREF,        dump_table_moduleref },
1454         { "--module",      MONO_TABLE_MODULE,           dump_table_module },
1455         { "--mresources",  0,   dis_mresource },
1456         { "--nested",      MONO_TABLE_NESTEDCLASS,      dump_table_nestedclass },
1457         { "--param",       MONO_TABLE_PARAM,            dump_table_param },
1458         { "--parconst",    MONO_TABLE_GENERICPARAMCONSTRAINT, dump_table_parconstraint },
1459         { "--property",    MONO_TABLE_PROPERTY,         dump_table_property },
1460         { "--propertymap", MONO_TABLE_PROPERTYMAP,      dump_table_property_map },
1461         { "--typedef",     MONO_TABLE_TYPEDEF,          dump_table_typedef },
1462         { "--typeref",     MONO_TABLE_TYPEREF,          dump_table_typeref },
1463         { "--typespec",    MONO_TABLE_TYPESPEC,         dump_table_typespec },
1464         { "--implmap",     MONO_TABLE_IMPLMAP,          dump_table_implmap },
1465         { "--standalonesig", MONO_TABLE_STANDALONESIG,  dump_table_standalonesig },
1466         { "--methodptr", MONO_TABLE_METHOD_POINTER,  dump_table_methodptr },
1467         { "--fieldptr", MONO_TABLE_FIELD_POINTER,  dump_table_fieldptr },
1468         { "--paramptr", MONO_TABLE_PARAM_POINTER,  dump_table_paramptr },
1469         { "--eventptr", MONO_TABLE_EVENT_POINTER,  dump_table_eventptr },
1470         { "--propertyptr", MONO_TABLE_PROPERTY_POINTER,  dump_table_propertyptr },
1471         { "--blob", 0, dump_stream_blob },
1472         { "--strings", 0, dump_stream_strings },
1473         { "--userstrings", 0, dump_stream_us },
1474         { NULL, -1, }
1475 };
1476
1477 /**
1478  * disassemble_file:
1479  * @file: file containing CIL code.
1480  *
1481  * Disassembles the @file file.
1482  */
1483 static void
1484 disassemble_file (const char *file)
1485 {
1486         MonoAssembly *ass;
1487         MonoImageOpenStatus status;
1488         MonoImage *img;
1489
1490         ass = mono_assembly_open (file, &status);
1491         if (ass == NULL){
1492                 img = mono_image_open (file, &status);
1493                 if (!img) {
1494                         fprintf (stderr, "Error while trying to process %s\n", file);
1495                         return;
1496                 } else {
1497                         mono_assembly_load_references (img, &status);
1498                 }
1499         } else {
1500                 img = ass->image;
1501         }
1502
1503         setup_filter (img);
1504
1505         if (dump_table != -1){
1506                 (*table_list [dump_table].dumper) (img);
1507         } else {
1508                 dump_header_data (img);
1509                 
1510                 dis_directive_assemblyref (img);
1511                 dis_directive_assembly (img);
1512                 dis_directive_file (img);
1513                 dis_directive_mresource (img);
1514                 dis_directive_module (img);
1515                 dis_directive_moduleref (img);
1516                 dis_nt_header (img);
1517                 if (dump_managed_resources)
1518                         dis_mresource (img);
1519                 if (dump_forward_decls) {
1520                         fprintf (output, "// *************** Forward Declarations for Classes ***************\n\n"); 
1521                         dis_types (img, 1);
1522                         fprintf (output, "// *************** End-Of Forward Declarations for Classes ***************\n\n"); 
1523                 }       
1524                 dis_types (img, 0);
1525                 dis_data (img);
1526         }
1527         
1528         mono_image_close (img);
1529 }
1530
1531 typedef struct {
1532         int size;
1533         int count;
1534         int *elems;
1535 } TableFilter;
1536
1537 typedef struct {
1538         char *name;
1539         char *guid;
1540         TableFilter types;
1541         TableFilter fields;
1542         TableFilter methods;
1543 } ImageFilter;
1544
1545 static GList *filter_list = NULL;
1546 static ImageFilter *cur_filter = NULL;
1547
1548 static void     
1549 setup_filter (MonoImage *image)
1550 {
1551         ImageFilter *ifilter;
1552         GList *item;
1553         const char *name = mono_image_get_name (image);
1554
1555         for (item = filter_list; item; item = item->next) {
1556                 ifilter = item->data;
1557                 if (strcmp (ifilter->name, name) == 0) {
1558                         cur_filter = ifilter;
1559                         return;
1560                 }
1561         }
1562         cur_filter = NULL;
1563 }
1564
1565 static int
1566 int_cmp (const void *e1, const void *e2)
1567 {
1568         const int *i1 = e1;
1569         const int *i2 = e2;
1570         return *i1 - *i2;
1571 }
1572
1573 static gboolean 
1574 table_includes (TableFilter *tf, int idx)
1575 {
1576         if (!tf->count)
1577                 return FALSE;
1578         return bsearch (&idx, tf->elems, tf->count, sizeof (int), int_cmp) != NULL;
1579 }
1580
1581 static gboolean 
1582 should_include_type (int idx)
1583 {
1584         if (!cur_filter)
1585                 return TRUE;
1586         return table_includes (&cur_filter->types, idx);
1587 }
1588
1589 static gboolean
1590 should_include_method (int idx)
1591 {
1592         if (!cur_filter)
1593                 return TRUE;
1594         return table_includes (&cur_filter->methods, idx);
1595 }
1596
1597 static gboolean
1598 should_include_field (int idx)
1599 {
1600         if (!cur_filter)
1601                 return TRUE;
1602         return table_includes (&cur_filter->fields, idx);
1603 }
1604
1605 static ImageFilter*
1606 add_filter (const char *name)
1607 {
1608         ImageFilter *ifilter;
1609         GList *item;
1610
1611         for (item = filter_list; item; item = item->next) {
1612                 ifilter = item->data;
1613                 if (strcmp (ifilter->name, name) == 0)
1614                         return ifilter;
1615         }
1616         ifilter = g_new0 (ImageFilter, 1);
1617         ifilter->name = g_strdup (name);
1618         filter_list = g_list_prepend (filter_list, ifilter);
1619         return ifilter;
1620 }
1621
1622 static void
1623 add_item (TableFilter *tf, int val)
1624 {
1625         if (tf->count >= tf->size) {
1626                 if (!tf->size) {
1627                         tf->size = 8;
1628                         tf->elems = g_malloc (sizeof (int) * tf->size);
1629                 } else {
1630                         tf->size *= 2;
1631                         tf->elems = g_realloc (tf->elems, sizeof (int) * tf->size);
1632                 }
1633         }
1634         tf->elems [tf->count++] = val;
1635 }
1636
1637 static void
1638 sort_filter_elems (void)
1639 {
1640         ImageFilter *ifilter;
1641         GList *item;
1642
1643         for (item = filter_list; item; item = item->next) {
1644                 ifilter = item->data;
1645                 qsort (ifilter->types.elems, ifilter->types.count, sizeof (int), int_cmp);
1646                 qsort (ifilter->fields.elems, ifilter->fields.count, sizeof (int), int_cmp);
1647                 qsort (ifilter->methods.elems, ifilter->methods.count, sizeof (int), int_cmp);
1648         }
1649 }
1650
1651 static void
1652 load_filter (const char* filename)
1653 {
1654         FILE *file;
1655         char buf [1024];
1656         char *p, *s, *endptr;
1657         int line = 0;
1658         ImageFilter *ifilter = NULL;
1659         int value = 0;
1660         
1661         if (!(file = fopen (filename, "r"))) {
1662                 g_print ("Cannot open filter file '%s'\n", filename);
1663                 exit (1);
1664         }
1665         while (fgets (buf, sizeof (buf), file) != NULL) {
1666                 ++line;
1667                 s = buf;
1668                 while (*s && g_ascii_isspace (*s)) ++s;
1669                 switch (*s) {
1670                 case 0:
1671                 case '#':
1672                         break;
1673                 case '[':
1674                         p = strchr (s, ']');
1675                         if (!p)
1676                                 g_error ("No matching ']' in filter at line %d\n", line);
1677                         *p = 0;
1678                         ifilter = add_filter (s + 1);
1679                         break;
1680                 case 'T':
1681                         if (!ifilter)
1682                                 g_error ("Invalid format in filter at line %d\n", line);
1683                         if ((s [1] != ':') || !(value = strtol (s + 2, &endptr, 0)) || (endptr == s + 2))
1684                                 g_error ("Invalid type number in filter at line %d\n", line);
1685                         add_item (&ifilter->types, value);
1686                         break;
1687                 case 'M':
1688                         if (!ifilter)
1689                                 g_error ("Invalid format in filter at line %d\n", line);
1690                         if ((s [1] != ':') || !(value = strtol (s + 2, &endptr, 0)) || (endptr == s + 2))
1691                                 g_error ("Invalid method number in filter at line %d\n", line);
1692                         add_item (&ifilter->methods, value);
1693                         break;
1694                 case 'F':
1695                         if (!ifilter)
1696                                 g_error ("Invalid format in filter at line %d\n", line);
1697                         if ((s [1] != ':') || !(value = strtol (s + 2, &endptr, 0)) || (endptr == s + 2))
1698                                 g_error ("Invalid field number in filter at line %d\n", line);
1699                         add_item (&ifilter->fields, value);
1700                         break;
1701                 default:
1702                         g_error ("Invalid format in filter at line %d\n", line);
1703                 }
1704         }
1705         fclose (file);
1706         sort_filter_elems ();
1707 }
1708
1709
1710 static gboolean
1711 try_load_from (MonoAssembly **assembly, const gchar *path1, const gchar *path2,
1712                                         const gchar *path3, const gchar *path4, gboolean refonly)
1713 {
1714         gchar *fullpath;
1715
1716         *assembly = NULL;
1717         fullpath = g_build_filename (path1, path2, path3, path4, NULL);
1718         if (g_file_test (fullpath, G_FILE_TEST_IS_REGULAR))
1719                 *assembly = mono_assembly_open_full (fullpath, NULL, refonly);
1720
1721         g_free (fullpath);
1722         return (*assembly != NULL);
1723 }
1724
1725 static MonoAssembly *
1726 real_load (gchar **search_path, const gchar *culture, const gchar *name, gboolean refonly)
1727 {
1728         MonoAssembly *result = NULL;
1729         gchar **path;
1730         gchar *filename;
1731         const gchar *local_culture;
1732         gint len;
1733
1734         if (!culture || *culture == '\0') {
1735                 local_culture = "";
1736         } else {
1737                 local_culture = culture;
1738         }
1739
1740         filename =  g_strconcat (name, ".dll", NULL);
1741         len = strlen (filename);
1742
1743         for (path = search_path; *path; path++) {
1744                 if (**path == '\0')
1745                         continue; /* Ignore empty ApplicationBase */
1746
1747                 /* See test cases in bug #58992 and bug #57710 */
1748                 /* 1st try: [culture]/[name].dll (culture may be empty) */
1749                 strcpy (filename + len - 4, ".dll");
1750                 if (try_load_from (&result, *path, local_culture, "", filename, refonly))
1751                         break;
1752
1753                 /* 2nd try: [culture]/[name].exe (culture may be empty) */
1754                 strcpy (filename + len - 4, ".exe");
1755                 if (try_load_from (&result, *path, local_culture, "", filename, refonly))
1756                         break;
1757
1758                 /* 3rd try: [culture]/[name]/[name].dll (culture may be empty) */
1759                 strcpy (filename + len - 4, ".dll");
1760                 if (try_load_from (&result, *path, local_culture, name, filename, refonly))
1761                         break;
1762
1763                 /* 4th try: [culture]/[name]/[name].exe (culture may be empty) */
1764                 strcpy (filename + len - 4, ".exe");
1765                 if (try_load_from (&result, *path, local_culture, name, filename, refonly))
1766                         break;
1767         }
1768
1769         g_free (filename);
1770         return result;
1771 }
1772
1773 /*
1774  * Try to load referenced assemblies from assemblies_path.
1775  */
1776 static MonoAssembly *
1777 monodis_preload (MonoAssemblyName *aname,
1778                                  gchar **assemblies_path,
1779                                  gpointer user_data)
1780 {
1781         MonoAssembly *result = NULL;
1782         gboolean refonly = GPOINTER_TO_UINT (user_data);
1783
1784         if (assemblies_path && assemblies_path [0] != NULL) {
1785                 result = real_load (assemblies_path, aname->culture, aname->name, refonly);
1786         }
1787
1788         return result;
1789 }
1790
1791 static GList *loaded_assemblies = NULL;
1792
1793 static void
1794 monodis_assembly_load_hook (MonoAssembly *assembly, gpointer user_data)
1795 {
1796         loaded_assemblies = g_list_prepend (loaded_assemblies, assembly);
1797 }
1798
1799 static MonoAssembly *
1800 monodis_assembly_search_hook (MonoAssemblyName *aname, gpointer user_data)
1801 {
1802         GList *tmp;
1803
1804        for (tmp = loaded_assemblies; tmp; tmp = tmp->next) {
1805                MonoAssembly *ass = tmp->data;
1806                if (mono_assembly_names_equal (aname, &ass->aname))
1807                        return ass;
1808        }
1809        return NULL;
1810 }
1811
1812 static void
1813 usage (void)
1814 {
1815         GString *args = g_string_new ("[--output=filename] [--filter=filename] [--help] [--mscorlib]\n");
1816         int i;
1817         
1818         for (i = 0; table_list [i].name != NULL; i++){
1819                 g_string_append (args, "[");
1820                 g_string_append (args, table_list [i].name);
1821                 g_string_append (args, "] ");
1822                 if (((i-2) % 5) == 0)
1823                         g_string_append_c (args, '\n');
1824         }
1825         g_string_append (args, "[--forward-decls]");
1826         fprintf (stderr,
1827                  "monodis -- Mono Common Intermediate Language Disassembler\n" 
1828                  "Usage is: monodis %s file ..\n", args->str);
1829         exit (1);
1830 }
1831
1832 int
1833 main (int argc, char *argv [])
1834 {
1835         GList *input_files = NULL, *l;
1836         int i, j;
1837
1838         output = stdout;
1839         init_key_table ();
1840         for (i = 1; i < argc; i++){
1841                 if (argv [i][0] == '-'){
1842                         if (argv [i][1] == 'h')
1843                                 usage ();
1844                         else if (argv [i][1] == 'd')
1845                                 dump_header_data_p = TRUE;
1846                         else if (strcmp (argv [i], "--mscorlib") == 0) {
1847                                 substitute_with_mscorlib_p = TRUE;
1848                                 continue;
1849                         } else if (strcmp (argv [i], "--show-method-tokens") == 0) {
1850                                 show_method_tokens = TRUE;
1851                                 continue;
1852                         } else if (strcmp (argv [i], "--show-tokens") == 0) {
1853                                 show_tokens = TRUE;
1854                                 continue;
1855                         } else if (strncmp (argv [i], "--output=", 9) == 0) {
1856                                 output = fopen (argv [i]+9, "w");
1857                                 if (output == NULL) {
1858                                         fprintf (stderr, "Can't open output file `%s': %s\n",
1859                                                  argv [i]+9, strerror (errno));
1860                                         exit (1);
1861                                 }
1862                                 dump_managed_resources = TRUE;
1863                                 continue;
1864                         } else if (strncmp (argv [i], "--filter=", 9) == 0) {
1865                                 load_filter (argv [i]+9);
1866                                 continue;
1867                         } else if (strcmp (argv [i], "--forward-decls") == 0) {
1868                                 dump_forward_decls = TRUE;
1869                                 continue;
1870                         } else if (strcmp (argv [i], "--help") == 0)
1871                                 usage ();
1872                         for (j = 0; table_list [j].name != NULL; j++) {
1873                                 if (strcmp (argv [i], table_list [j].name) == 0)
1874                                         dump_table = j;
1875                         }
1876                         if (dump_table < 0)
1877                                 usage ();
1878                 } else
1879                         input_files = g_list_append (input_files, argv [i]);
1880         }
1881
1882         if (input_files == NULL)
1883                 usage ();
1884
1885         mono_install_assembly_load_hook (monodis_assembly_load_hook, NULL);
1886         mono_install_assembly_search_hook (monodis_assembly_search_hook, NULL);
1887
1888         /*
1889          * If we just have one file, use the corlib version it requires.
1890          */
1891         if (!input_files->next) {
1892                 char *filename = input_files->data;
1893
1894                 mono_init_from_assembly (argv [0], filename);
1895
1896                 mono_install_assembly_preload_hook (monodis_preload, GUINT_TO_POINTER (FALSE));
1897
1898                 disassemble_file (filename);
1899         } else {
1900                 mono_init (argv [0]);
1901
1902                 for (l = input_files; l; l = l->next)
1903                         disassemble_file (l->data);
1904         }
1905
1906         return 0;
1907 }