Remove some #if __cplusplus wrt inlining. (#18891)
[mono-project.git] / mono / dis / main.c
blob1f69815ccee9c80e3d27eff8d51d14a40e539a8e
1 /*
2 * main.c: Sample disassembler
4 * Author:
5 * Miguel de Icaza (miguel@ximian.com)
7 * (C) 2001 Ximian, Inc.
9 * TODO:
10 * Investigate how interface inheritance works and how it should be dumped.
11 * Structs are not being labeled as `valuetype' classes
13 * How are fields with literals mapped to constants?
14 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
16 #include <config.h>
17 #include <stdio.h>
18 #include <string.h>
19 #include <glib.h>
20 #include <stdlib.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include "meta.h"
24 #include "util.h"
25 #include "dump.h"
26 #include "get.h"
27 #include "dis-cil.h"
28 #include "declsec.h"
29 #include <mono/metadata/class-internals.h>
30 #include <mono/metadata/object-internals.h>
31 #include <mono/metadata/loader.h>
32 #include <mono/metadata/assembly-internals.h>
33 #include <mono/metadata/appdomain.h>
34 #include <mono/metadata/w32handle.h>
35 #include <mono/utils/bsearch.h>
36 #include <mono/utils/mono-counters.h>
37 #include "mono/metadata/class-init.h"
39 static void setup_filter (MonoImage *image);
40 static gboolean should_include_type (int idx);
41 static gboolean should_include_method (int idx);
42 static gboolean should_include_field (int idx);
44 FILE *output;
46 /* True if you want to get a dump of the header data */
47 gboolean dump_header_data_p = FALSE;
49 /* True if you want to get forward declarations */
50 gboolean dump_forward_decls = FALSE;
52 /* True if you want to dump managed resources as files */
53 gboolean dump_managed_resources = FALSE;
55 gboolean substitute_with_mscorlib_p = FALSE;
57 int dump_table = -1;
59 static void
60 dump_header_data (MonoImage *img)
62 if (!dump_header_data_p)
63 return;
65 fprintf (output,
66 "// Ximian's CIL disassembler, version 1.0\n"
67 "// Copyright (C) 2001 Ximian, Inc.\n\n");
70 static void
71 dump_cattrs_list (GList *list, const char *indent)
73 GList *tmp;
75 for (tmp = list; tmp; tmp = tmp->next) {
76 fprintf (output, "%s%s\n", indent, (char*)tmp->data);
77 g_free (tmp->data);
79 g_list_free (list);
82 static void
83 dump_cattrs (MonoImage *m, guint32 token, const char *indent)
85 GList *list;
87 list = dis_get_custom_attrs (m, token);
88 dump_cattrs_list (list, indent);
91 static const char*
92 get_il_security_action (int val)
94 static char buf [32];
96 switch (val) {
97 case SECURITY_ACTION_DEMAND:
98 return "demand";
99 case SECURITY_ACTION_ASSERT:
100 return "assert";
101 case SECURITY_ACTION_DENY:
102 return "deny";
103 case SECURITY_ACTION_PERMITONLY:
104 return "permitonly";
105 case SECURITY_ACTION_LINKDEMAND:
106 return "linkcheck";
107 case SECURITY_ACTION_INHERITDEMAND:
108 return "inheritcheck";
109 case SECURITY_ACTION_REQMIN:
110 return "reqmin";
111 case SECURITY_ACTION_REQOPT:
112 return "reqopt";
113 case SECURITY_ACTION_REQREFUSE:
114 return "reqrefuse";
115 /* Special actions (for non CAS permissions) */
116 case SECURITY_ACTION_NONCASDEMAND:
117 return "noncasdemand";
118 case SECURITY_ACTION_NONCASLINKDEMAND:
119 return "noncaslinkdemand";
120 case SECURITY_ACTION_NONCASINHERITANCE:
121 return "noncasinheritance";
122 /* Fx 2.0 actions (for both CAS and non-CAS permissions) */
123 case SECURITY_ACTION_LINKDEMANDCHOICE:
124 return "linkdemandor";
125 case SECURITY_ACTION_INHERITDEMANDCHOICE:
126 return "inheritancedemandor";
127 case SECURITY_ACTION_DEMANDCHOICE:
128 return "demandor";
129 default:
130 g_snprintf (buf, sizeof (buf), "0x%04X", val);
131 return buf;
135 #define OBJECT_TYPE_TYPEDEF 0
136 #define OBJECT_TYPE_METHODDEF 1
137 #define OBJECT_TYPE_ASSEMBLYDEF 2
139 static void
140 dump_declarative_security (MonoImage *m, guint32 objectType, guint32 token, const char *indent)
142 MonoTableInfo *t = &m->tables [MONO_TABLE_DECLSECURITY];
143 guint32 cols [MONO_DECL_SECURITY_SIZE];
144 int i, len;
145 guint32 idx;
146 const char *blob, *action;
148 for (i = 1; i <= t->rows; i++) {
149 mono_metadata_decode_row (t, i - 1, cols, MONO_DECL_SECURITY_SIZE);
150 blob = mono_metadata_blob_heap (m, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
151 len = mono_metadata_decode_blob_size (blob, &blob);
152 action = get_il_security_action (cols [MONO_DECL_SECURITY_ACTION]);
153 idx = cols [MONO_DECL_SECURITY_PARENT];
154 if (((idx & MONO_HAS_DECL_SECURITY_MASK) == objectType) && ((idx >> MONO_HAS_DECL_SECURITY_BITS) == token)) {
155 char *dump;
156 if (blob [0] == MONO_DECLSEC_FORMAT_20) {
157 /* 2.0 declarative security format */
158 dump = dump_declsec_entry20 (m, blob, indent);
159 fprintf (output, "%s.permissionset %s = %s\n", indent, action, dump);
160 } else {
161 /* 1.x declarative security metadata format */
162 dump = data_dump (blob, len, indent);
163 fprintf (output, "%s.permissionset %s = %s", indent, action, dump);
165 g_free (dump);
170 static char *
171 assembly_flags (guint32 f)
173 if (f & ASSEMBLYREF_RETARGETABLE_FLAG)
174 return g_strdup ("retargetable ");
175 return g_strdup ("");
178 static void
179 dis_directive_assembly (MonoImage *m)
181 MonoTableInfo *t = &m->tables [MONO_TABLE_ASSEMBLY];
182 guint32 cols [MONO_ASSEMBLY_SIZE];
183 char *flags;
185 if (t->base == NULL)
186 return;
188 mono_metadata_decode_row (t, 0, cols, MONO_ASSEMBLY_SIZE);
189 flags = assembly_flags (cols [MONO_ASSEMBLY_FLAGS]);
191 fprintf (output, ".assembly %s'%s'\n{\n",
192 flags, mono_metadata_string_heap (m, cols [MONO_ASSEMBLY_NAME]));
193 dump_cattrs (m, MONO_TOKEN_ASSEMBLY | 1, " ");
194 dump_declarative_security (m, OBJECT_TYPE_ASSEMBLYDEF, 1, " ");
195 fprintf (output,
196 " .hash algorithm 0x%08x\n"
197 " .ver %d:%d:%d:%d\n",
198 cols [MONO_ASSEMBLY_HASH_ALG],
199 cols [MONO_ASSEMBLY_MAJOR_VERSION], cols [MONO_ASSEMBLY_MINOR_VERSION],
200 cols [MONO_ASSEMBLY_BUILD_NUMBER], cols [MONO_ASSEMBLY_REV_NUMBER]);
201 if (cols [MONO_ASSEMBLY_CULTURE]){
202 const char *locale = mono_metadata_string_heap (m, cols [MONO_ASSEMBLY_CULTURE]);
203 glong items_read, items_written;
204 gunichar2 *render = g_utf8_to_utf16 (locale, strlen (locale), &items_read, &items_written, NULL);
205 char *dump = data_dump ((const char *) render, items_written * sizeof (gunichar2), "\t\t");
206 fprintf (output, " .locale %s\n", dump);
207 g_free (dump);
208 g_free (render);
210 } if (cols [MONO_ASSEMBLY_PUBLIC_KEY]) {
211 const char* b = mono_metadata_blob_heap (m, cols [MONO_ASSEMBLY_PUBLIC_KEY]);
212 int len = mono_metadata_decode_blob_size (b, &b);
213 char *dump = data_dump (b, len, "\t\t");
214 fprintf (output, " .publickey =%s", dump);
215 g_free (dump);
217 fprintf (output, "}\n");
219 g_free (flags);
222 static void
223 dis_directive_assemblyref (MonoImage *m)
225 MonoTableInfo *t = &m->tables [MONO_TABLE_ASSEMBLYREF];
226 guint32 cols [MONO_ASSEMBLYREF_SIZE];
227 int i;
229 if (t->base == NULL)
230 return;
232 for (i = 0; i < t->rows; i++){
233 char *esc, *flags;
235 mono_metadata_decode_row (t, i, cols, MONO_ASSEMBLYREF_SIZE);
237 esc = get_escaped_name (mono_metadata_string_heap (m, cols [MONO_ASSEMBLYREF_NAME]));
238 flags = assembly_flags (cols [MONO_ASSEMBLYREF_FLAGS]);
240 fprintf (output,
241 ".assembly extern %s%s\n"
242 "{\n"
243 " .ver %d:%d:%d:%d\n",
244 flags,
245 esc,
246 cols [MONO_ASSEMBLYREF_MAJOR_VERSION], cols [MONO_ASSEMBLYREF_MINOR_VERSION],
247 cols [MONO_ASSEMBLYREF_BUILD_NUMBER], cols [MONO_ASSEMBLYREF_REV_NUMBER]
249 dump_cattrs (m, MONO_TOKEN_ASSEMBLY_REF | (i + 1), " ");
250 if (cols [MONO_ASSEMBLYREF_CULTURE]){
251 fprintf (output, " .locale %s\n", mono_metadata_string_heap (m, cols [MONO_ASSEMBLYREF_CULTURE]));
253 if (cols [MONO_ASSEMBLYREF_PUBLIC_KEY]){
254 const char* b = mono_metadata_blob_heap (m, cols [MONO_ASSEMBLYREF_PUBLIC_KEY]);
255 int len = mono_metadata_decode_blob_size (b, &b);
256 char *dump = data_dump (b, len, "\t\t");
257 fprintf (output, " .publickeytoken =%s", dump);
258 g_free (dump);
260 fprintf (output, "}\n");
261 g_free (flags);
262 g_free (esc);
266 static void
267 dis_directive_module (MonoImage *m)
269 MonoTableInfo *t = &m->tables [MONO_TABLE_MODULE];
270 int i;
272 for (i = 0; i < t->rows; i++){
273 guint32 cols [MONO_MODULE_SIZE];
274 const char *name;
275 char *guid, *ename;
277 mono_metadata_decode_row (t, i, cols, MONO_MODULE_SIZE);
279 name = mono_metadata_string_heap (m, cols [MONO_MODULE_NAME]);
280 ename = get_escaped_name (name);
281 guid = get_guid (m, cols [MONO_MODULE_MVID]);
282 fprintf (output, ".module %s // GUID = %s\n\n", ename, guid);
283 g_free (ename);
285 dump_cattrs (m, MONO_TOKEN_MODULE | (i + 1), "");
289 static void
290 dis_directive_moduleref (MonoImage *m)
292 MonoTableInfo *t = &m->tables [MONO_TABLE_MODULEREF];
293 int i;
295 for (i = 0; i < t->rows; i++){
296 guint32 cols [MONO_MODULEREF_SIZE];
298 mono_metadata_decode_row (t, i, cols, MONO_MODULEREF_SIZE);
300 fprintf (output, ".module extern '%s'\n", mono_metadata_string_heap (m, cols [MONO_MODULEREF_NAME]));
305 static void
306 dis_nt_header (MonoImage *m)
308 MonoCLIImageInfo *image_info = (MonoCLIImageInfo *)m->image_info;
309 if (image_info && image_info->cli_header.nt.pe_stack_reserve != 0x100000)
310 fprintf (output, ".stackreserve 0x%x\n", image_info->cli_header.nt.pe_stack_reserve);
313 static void
314 dis_directive_file (MonoImage *m)
316 MonoTableInfo *t = &m->tables [MONO_TABLE_FILE];
317 int i, j, len;
318 guint32 entry_point;
320 entry_point = mono_image_get_entry_point (m);
322 for (i = 0; i < t->rows; i++){
323 guint32 cols [MONO_FILE_SIZE];
324 const char *name, *hash;
325 guint32 token;
327 mono_metadata_decode_row (t, i, cols, MONO_FILE_SIZE);
329 name = mono_metadata_string_heap (m, cols [MONO_FILE_NAME]);
331 hash = mono_metadata_blob_heap (m, cols [MONO_FILE_HASH_VALUE]);
332 len = mono_metadata_decode_blob_size (hash, &hash);
334 fprintf (output, ".file %s%s .hash = (",
335 cols [MONO_FILE_FLAGS] & FILE_CONTAINS_NO_METADATA ? "nometadata " : "", name);
337 for (j = 0; j < len; ++j)
338 fprintf (output, " %02X", hash [j] & 0xff);
340 token = mono_metadata_make_token (MONO_TABLE_FILE, i + 1);
341 fprintf (output, " )%s\n", (token == entry_point) ? " .entrypoint" : "");
346 static void
347 dis_directive_mresource (MonoImage *m)
349 MonoTableInfo *t = &m->tables [MONO_TABLE_MANIFESTRESOURCE];
350 int i;
352 for (i = 0; i < t->rows; i++){
353 guint32 cols [MONO_MANIFEST_SIZE];
354 const char *name;
355 guint32 impl, idx, name_token;
357 mono_metadata_decode_row (t, i, cols, MONO_MANIFEST_SIZE);
359 name = mono_metadata_string_heap (m, cols [MONO_MANIFEST_NAME]);
361 fprintf (output, ".mresource %s '%s'\n", (cols [MONO_MANIFEST_FLAGS] & MANIFEST_RESOURCE_VISIBILITY_MASK) == (MANIFEST_RESOURCE_PUBLIC) ? "public" : "private", name);
362 fprintf (output, "{\n");
363 impl = cols [MONO_MANIFEST_IMPLEMENTATION];
364 if (impl) {
365 idx = impl >> MONO_IMPLEMENTATION_BITS;
366 if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE) {
367 name_token = mono_metadata_decode_row_col (&m->tables [MONO_TABLE_FILE], idx - 1, MONO_FILE_NAME);
369 fprintf (output, " .file '%s' at 0x0\n", mono_metadata_string_heap (m, name_token));
371 if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_ASSEMBLYREF) {
372 name_token = mono_metadata_decode_row_col (&m->tables [MONO_TABLE_ASSEMBLYREF], idx - 1, MONO_ASSEMBLYREF_NAME);
373 fprintf (output, " .assembly extern '%s'\n", mono_metadata_string_heap (m, name_token));
376 fprintf (output, "}\n");
381 static dis_map_t visibility_map [] = {
382 { TYPE_ATTRIBUTE_NOT_PUBLIC, "private " },
383 { TYPE_ATTRIBUTE_PUBLIC, "public " },
384 { TYPE_ATTRIBUTE_NESTED_PUBLIC, "nested public " },
385 { TYPE_ATTRIBUTE_NESTED_PRIVATE, "nested private " },
386 { TYPE_ATTRIBUTE_NESTED_FAMILY, "nested family " },
387 { TYPE_ATTRIBUTE_NESTED_ASSEMBLY, "nested assembly " },
388 { TYPE_ATTRIBUTE_NESTED_FAM_AND_ASSEM, "nested famandassem " },
389 { TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM, "nested famorassem " },
390 { 0, NULL }
393 static dis_map_t layout_map [] = {
394 { TYPE_ATTRIBUTE_AUTO_LAYOUT, "auto " },
395 { TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT, "sequential " },
396 { TYPE_ATTRIBUTE_EXPLICIT_LAYOUT, "explicit " },
397 { 0, NULL }
400 static dis_map_t format_map [] = {
401 { TYPE_ATTRIBUTE_ANSI_CLASS, "ansi " },
402 { TYPE_ATTRIBUTE_UNICODE_CLASS, "unicode " },
403 { TYPE_ATTRIBUTE_AUTO_CLASS, "auto " },
404 { 0, NULL }
407 static char *
408 typedef_flags (guint32 flags)
410 static char buffer [1024];
411 int visibility = flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
412 int layout = flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
413 int format = flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK;
415 buffer [0] = 0;
417 strcat (buffer, map (visibility, visibility_map));
418 strcat (buffer, map (layout, layout_map));
419 strcat (buffer, map (format, format_map));
421 if (flags & TYPE_ATTRIBUTE_ABSTRACT)
422 strcat (buffer, "abstract ");
423 if (flags & TYPE_ATTRIBUTE_SEALED)
424 strcat (buffer, "sealed ");
425 if (flags & TYPE_ATTRIBUTE_SPECIAL_NAME)
426 strcat (buffer, "specialname ");
427 if (flags & TYPE_ATTRIBUTE_IMPORT)
428 strcat (buffer, "import ");
429 if (flags & TYPE_ATTRIBUTE_SERIALIZABLE)
430 strcat (buffer, "serializable ");
431 if (flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)
432 strcat (buffer, "beforefieldinit ");
433 if (flags & TYPE_ATTRIBUTE_FORWARDER)
434 strcat (buffer, "forwarder ");
436 return buffer;
440 * dis_field_list:
441 * @m: metadata context
442 * @start: starting index into the Field Table.
443 * @end: ending index into Field table.
445 * This routine displays all the decoded fields from @start to @end
447 static void
448 dis_field_list (MonoImage *m, guint32 start, guint32 end, MonoGenericContainer *container)
450 MonoTableInfo *t = &m->tables [MONO_TABLE_FIELD];
451 guint32 cols [MONO_FIELD_SIZE];
452 char *esname;
453 char rva_desc [32];
454 guint32 rva;
455 int i;
457 if (end > t->rows + 1) {
458 g_warning ("ERROR index out of range in fields");
459 end = t->rows;
462 for (i = start; i < end; i++){
463 char *sig, *flags, *attrs = NULL;
464 char *marshal_str = NULL;
465 guint32 field_offset = -1;
467 if (!should_include_field (i + 1))
468 continue;
469 mono_metadata_decode_row (t, i, cols, MONO_FIELD_SIZE);
470 sig = get_field_signature (m, cols [MONO_FIELD_SIGNATURE], container);
471 flags = field_flags (cols [MONO_FIELD_FLAGS]);
473 if (cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL) {
474 const char *tp;
475 MonoMarshalSpec *spec;
477 tp = mono_metadata_get_marshal_info (m, i, TRUE);
478 spec = mono_metadata_parse_marshal_spec (m, tp);
479 marshal_str = dis_stringify_marshal_spec (spec);
482 if (cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_HAS_FIELD_RVA) {
483 mono_metadata_field_info (m, i, NULL, &rva, NULL);
484 g_snprintf (rva_desc, sizeof (rva_desc), " at D_%08x", rva);
485 } else {
486 rva_desc [0] = 0;
489 mono_metadata_field_info (m, i, &field_offset, NULL, NULL);
490 if (field_offset != -1)
491 attrs = g_strdup_printf ("[%d]", field_offset);
492 esname = get_escaped_name (mono_metadata_string_heap (m, cols [MONO_FIELD_NAME]));
493 if (cols [MONO_FIELD_FLAGS] & FIELD_ATTRIBUTE_HAS_DEFAULT){
494 char *lit;
495 guint32 const_cols [MONO_CONSTANT_SIZE];
496 guint32 crow;
498 if ((crow = mono_metadata_get_constant_index (m, MONO_TOKEN_FIELD_DEF | (i+1), 0))) {
499 mono_metadata_decode_row (&m->tables [MONO_TABLE_CONSTANT], crow-1, const_cols, MONO_CONSTANT_SIZE);
500 lit = get_constant (m, (MonoTypeEnum)const_cols [MONO_CONSTANT_TYPE], const_cols [MONO_CONSTANT_VALUE]);
501 } else {
502 lit = g_strdup ("not found");
505 fprintf (output, " .field %s%s%s %s = ",
506 flags, marshal_str ? marshal_str : " ", sig, esname);
507 fprintf (output, "%s\n", lit);
508 g_free (lit);
509 } else
510 fprintf (output, " .field %s %s%s%s %s%s\n",
511 attrs? attrs: "", flags, marshal_str ? marshal_str : " ", sig, esname, rva_desc);
512 g_free (attrs);
513 g_free (flags);
514 g_free (marshal_str);
515 g_free (sig);
516 g_free (esname);
517 dump_cattrs (m, MONO_TOKEN_FIELD_DEF | (i + 1), " ");
521 static dis_map_t method_access_map [] = {
522 { METHOD_ATTRIBUTE_COMPILER_CONTROLLED, "privatescope " },
523 { METHOD_ATTRIBUTE_PRIVATE, "private " },
524 { METHOD_ATTRIBUTE_FAM_AND_ASSEM, "famandassem " },
525 { METHOD_ATTRIBUTE_ASSEM, "assembly " },
526 { METHOD_ATTRIBUTE_FAMILY, "family " },
527 { METHOD_ATTRIBUTE_FAM_OR_ASSEM, "famorassem " },
528 { METHOD_ATTRIBUTE_PUBLIC, "public " },
529 { 0, NULL }
532 static dis_map_t method_flags_map [] = {
533 { METHOD_ATTRIBUTE_STATIC, "static " },
534 { METHOD_ATTRIBUTE_FINAL, "final " },
535 { METHOD_ATTRIBUTE_VIRTUAL, "virtual " },
536 { METHOD_ATTRIBUTE_HIDE_BY_SIG, "hidebysig " },
537 { METHOD_ATTRIBUTE_VTABLE_LAYOUT_MASK, "newslot " },
538 { METHOD_ATTRIBUTE_ABSTRACT, "abstract " },
539 { METHOD_ATTRIBUTE_SPECIAL_NAME, "specialname " },
540 { METHOD_ATTRIBUTE_RT_SPECIAL_NAME, "rtspecialname " },
541 { METHOD_ATTRIBUTE_UNMANAGED_EXPORT, "export " },
542 /* MS ilasm doesn't compile this statement - is must be added automagically when permissionset are present */
543 { METHOD_ATTRIBUTE_HAS_SECURITY, "" /*"hassecurity"*/ },
544 { METHOD_ATTRIBUTE_REQUIRE_SEC_OBJECT, "requiresecobj " },
545 { METHOD_ATTRIBUTE_PINVOKE_IMPL, "pinvokeimpl " },
546 { METHOD_ATTRIBUTE_STRICT, "strict " },
547 { 0, NULL }
551 * method_flags:
553 * Returns a stringified version of the Method's flags
555 static char *
556 method_flags (guint32 f)
558 GString *str = g_string_new ("");
559 int access = f & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK;
560 int rest = f & ~access;
561 char *s;
563 g_string_append (str, map (access, method_access_map));
564 g_string_append (str, flags (rest, method_flags_map));
566 s = str->str;
567 g_string_free (str, FALSE);
569 return s;
572 static dis_map_t pinvoke_flags_map [] = {
573 { PINVOKE_ATTRIBUTE_NO_MANGLE , "nomangle " },
574 { PINVOKE_ATTRIBUTE_SUPPORTS_LAST_ERROR, "lasterr " },
575 { PINVOKE_ATTRIBUTE_BEST_FIT_ENABLED, "bestfit:on " },
576 { PINVOKE_ATTRIBUTE_BEST_FIT_DISABLED, "bestfit:off " },
577 { PINVOKE_ATTRIBUTE_THROW_ON_UNMAPPABLE_ENABLED, "charmaperror:on " },
578 { PINVOKE_ATTRIBUTE_THROW_ON_UNMAPPABLE_DISABLED, "charmaperror:off " },
579 { 0, NULL }
582 static dis_map_t pinvoke_call_conv_map [] = {
583 { PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI, "winapi " },
584 { PINVOKE_ATTRIBUTE_CALL_CONV_CDECL, "cdecl " },
585 { PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL, "stdcall " },
586 { PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL, "thiscall " },
587 { PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL, "fastcall " },
588 { 0, "" },
589 { -1, NULL }
592 static dis_map_t pinvoke_char_set_map [] = {
593 { PINVOKE_ATTRIBUTE_CHAR_SET_NOT_SPEC, "" },
594 { PINVOKE_ATTRIBUTE_CHAR_SET_ANSI, "ansi " },
595 { PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE , "unicode " },
596 { PINVOKE_ATTRIBUTE_CHAR_SET_AUTO, "autochar " },
597 { 0, NULL }
601 * pinvoke_flags:
603 * Returns a stringified version of the Method's pinvoke flags
605 static char *
606 pinvoke_flags (guint32 f)
608 GString *str = g_string_new ("");
609 int cset = f & PINVOKE_ATTRIBUTE_CHAR_SET_MASK;
610 int cconv = f & PINVOKE_ATTRIBUTE_CALL_CONV_MASK;
611 int rest = f & ~(cset | cconv);
612 char *s;
614 g_string_append (str, map (cset, pinvoke_char_set_map));
615 g_string_append (str, map (cconv, pinvoke_call_conv_map));
616 g_string_append (str, flags (rest, pinvoke_flags_map));
618 s = g_strdup(str->str);
619 g_string_free (str, FALSE);
621 return s;
624 static void
625 dis_locals (MonoImage *m, MonoMethodHeader *mh, const char *ptr)
627 int i;
629 if (show_tokens) {
630 unsigned char flags = *(const unsigned char *) ptr;
631 unsigned char format = flags & METHOD_HEADER_FORMAT_MASK;
632 guint16 fat_flags;
633 guint32 local_var_sig_tok, init_locals;
635 g_assert (format == METHOD_HEADER_FAT_FORMAT);
636 fat_flags = read16 (ptr);
637 ptr += 2;
638 /* max_stack = read16 (ptr); */
639 ptr += 2;
640 /* code_size = read32 (ptr); */
641 ptr += 4;
642 local_var_sig_tok = read32 (ptr);
643 ptr += 4;
645 if (fat_flags & METHOD_HEADER_INIT_LOCALS)
646 init_locals = 1;
647 else
648 init_locals = 0;
650 fprintf(output, "\t.locals /*%08x*/ %s(\n",
651 local_var_sig_tok, init_locals ? "init " : "");
652 } else
653 fprintf(output, "\t.locals %s(\n", mh->init_locals ? "init " : "");
655 for (i=0; i < mh->num_locals; ++i) {
656 char * desc;
657 if (i)
658 fprintf(output, ",\n");
659 /* print also byref and pinned attributes */
660 desc = dis_stringify_type (m, mh->locals[i], TRUE);
661 fprintf(output, "\t\t%s\tV_%d", desc, i);
662 g_free(desc);
664 fprintf(output, ")\n");
667 static void
668 dis_code (MonoImage *m, guint32 token, guint32 rva, MonoGenericContainer *container)
670 ERROR_DECL (error);
671 MonoMethodHeader *mh;
672 const char *ptr = mono_image_rva_map (m, rva);
673 const char *loc;
674 gchar *override;
675 guint32 entry_point;
677 if (rva == 0)
678 return;
680 override = get_method_override (m, token, container);
681 if (override) {
682 fprintf (output, "\t.override %s\n", override);
683 g_free (override);
686 mh = mono_metadata_parse_mh_full (m, container, ptr, error);
687 entry_point = mono_image_get_entry_point (m);
688 if (entry_point && mono_metadata_token_index (entry_point) && mono_metadata_token_table (entry_point) == MONO_TABLE_METHOD) {
689 loc = mono_metadata_locate_token (m, entry_point);
690 if (rva == read32 (loc))
691 fprintf (output, "\t.entrypoint\n");
694 if (mh) {
695 fprintf (output, "\t// Code size %d (0x%x)\n", mh->code_size, mh->code_size);
696 fprintf (output, "\t.maxstack %d\n", mh->max_stack);
697 if (mh->num_locals)
698 dis_locals (m, mh, ptr);
699 disassemble_cil (m, mh, container);
701 hex_dump (mh->code, 0, mh->code_size);
702 printf ("\nAfter the code\n");
703 hex_dump (mh->code + mh->code_size, 0, 64);
705 mono_metadata_free_mh (mh);
706 } else {
707 mono_error_cleanup (error);
711 static char *
712 pinvoke_info (MonoImage *m, guint32 mindex)
714 MonoTableInfo *im = &m->tables [MONO_TABLE_IMPLMAP];
715 MonoTableInfo *mr = &m->tables [MONO_TABLE_MODULEREF];
716 guint32 im_cols [MONO_IMPLMAP_SIZE];
717 guint32 mr_cols [MONO_MODULEREF_SIZE];
718 const char *import, *scope;
719 char *flags;
720 int i;
722 for (i = 0; i < im->rows; i++) {
724 mono_metadata_decode_row (im, i, im_cols, MONO_IMPLMAP_SIZE);
726 if ((im_cols [MONO_IMPLMAP_MEMBER] >> 1) == mindex + 1) {
728 flags = pinvoke_flags (im_cols [MONO_IMPLMAP_FLAGS]);
730 import = mono_metadata_string_heap (m, im_cols [MONO_IMPLMAP_NAME]);
732 mono_metadata_decode_row (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1,
733 mr_cols, MONO_MODULEREF_SIZE);
735 scope = mono_metadata_string_heap (m, mr_cols [MONO_MODULEREF_NAME]);
737 return g_strdup_printf ("(\"%s\" as \"%s\" %s)", scope, import,
738 flags);
739 g_free (flags);
743 return NULL;
747 * dump_cattrs_for_type_params
749 * @m:
750 * @token: TypeOrMethodDef token, owner for GenericParam
752 * Dumps the custom attributes for @token's type parameters
754 static void
755 dump_cattrs_for_type_params (MonoImage *m, guint32 token, const char *indent)
757 MonoTableInfo *tdef = &m->tables [MONO_TABLE_GENERICPARAM];
758 guint32 cols [MONO_GENERICPARAM_SIZE];
759 guint32 owner = 0, i;
760 GList *list = NULL;
762 if (! (i = mono_metadata_get_generic_param_row (m, token, &owner)))
763 return;
765 mono_metadata_decode_row (tdef, i - 1, cols, MONO_GENERICPARAM_SIZE);
766 do {
767 list = dis_get_custom_attrs (m, mono_metadata_make_token (MONO_TABLE_GENERICPARAM, i));
768 if (list) {
769 fprintf (output, "%s.param type %s\n", indent, mono_metadata_string_heap (m, cols [MONO_GENERICPARAM_NAME]));
770 dump_cattrs_list (list, indent);
773 if (++i > tdef->rows)
774 break;
775 mono_metadata_decode_row (tdef, i - 1, cols, MONO_GENERICPARAM_SIZE);
776 } while (cols [MONO_GENERICPARAM_OWNER] == owner);
779 static void
780 dump_cattrs_for_method_params (MonoImage *m, guint32 midx, MonoMethodSignature *sig) {
781 MonoTableInfo *methodt;
782 MonoTableInfo *paramt;
783 guint param_index, lastp, i;
785 methodt = &m->tables [MONO_TABLE_METHOD];
786 paramt = &m->tables [MONO_TABLE_PARAM];
787 param_index = mono_metadata_decode_row_col (methodt, midx, MONO_METHOD_PARAMLIST);
788 if (midx + 1 < methodt->rows)
789 lastp = mono_metadata_decode_row_col (methodt, midx + 1, MONO_METHOD_PARAMLIST);
790 else
791 lastp = paramt->rows + 1;
792 for (i = param_index; i < lastp; ++i) {
793 char *lit;
794 int crow;
795 guint32 param_cols [MONO_PARAM_SIZE];
796 GList *list;
798 list = dis_get_custom_attrs (m, MONO_TOKEN_PARAM_DEF | i);
800 mono_metadata_decode_row (paramt, i-1, param_cols, MONO_PARAM_SIZE);
801 if (!(param_cols[MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_DEFAULT)) {
802 if(list != NULL)
803 fprintf (output, "\t.param [%d]\n", param_cols[MONO_PARAM_SEQUENCE]);
804 } else {
805 fprintf (output, "\t.param [%d] = ", param_cols[MONO_PARAM_SEQUENCE]);
807 if ((crow = mono_metadata_get_constant_index(m, MONO_TOKEN_PARAM_DEF | i, 0))) {
808 guint32 const_cols [MONO_CONSTANT_SIZE];
809 mono_metadata_decode_row( &m->tables[MONO_TABLE_CONSTANT], crow-1, const_cols, MONO_CONSTANT_SIZE);
810 lit = get_constant (m, (MonoTypeEnum)const_cols [MONO_CONSTANT_TYPE], const_cols [MONO_CONSTANT_VALUE]);
812 else {
813 lit = g_strdup ("not found");
815 fprintf(output, "%s\n", lit);
816 g_free(lit);
818 dump_cattrs_list (list, "\t");
823 * dis_method_list:
824 * @m: metadata context
825 * @start: starting index into the Method Table.
826 * @end: ending index into Method table.
828 * This routine displays the methods in the Method Table from @start to @end
830 static void
831 dis_method_list (const char *klass_name, MonoImage *m, guint32 start, guint32 end, MonoGenericContainer *type_container)
833 MonoTableInfo *t = &m->tables [MONO_TABLE_METHOD];
834 guint32 cols [MONO_METHOD_SIZE];
835 int i;
837 if (end > t->rows){
838 fprintf (output, "ERROR index out of range in methods");
839 /*exit (1);*/
840 end = t->rows;
843 for (i = start; i < end; i++){
844 ERROR_DECL (error);
845 MonoMethodSignature *ms;
846 MonoGenericContainer *container;
847 char *flags, *impl_flags;
848 const char *sig, *method_name;
849 char *sig_str;
850 guint32 token;
852 if (!should_include_method (i + 1))
853 continue;
854 mono_metadata_decode_row (t, i, cols, MONO_METHOD_SIZE);
856 flags = method_flags (cols [MONO_METHOD_FLAGS]);
857 impl_flags = get_method_impl_flags (cols [MONO_METHOD_IMPLFLAGS]);
859 sig = mono_metadata_blob_heap (m, cols [MONO_METHOD_SIGNATURE]);
860 mono_metadata_decode_blob_size (sig, &sig);
862 container = mono_metadata_load_generic_params (m, MONO_TOKEN_METHOD_DEF | (i + 1), type_container, NULL);
863 if (container) {
864 ERROR_DECL (error);
865 mono_metadata_load_generic_param_constraints_checked (m, MONO_TOKEN_METHOD_DEF | (i + 1), container, error);
866 g_assert (is_ok (error)); /*FIXME don't swallow the error message*/
867 } else {
868 container = type_container;
871 ms = mono_metadata_parse_method_signature_full (m, container, i + 1, sig, &sig, error);
872 if (ms != NULL){
873 sig_str = dis_stringify_method_signature (m, ms, i + 1, container, FALSE);
874 method_name = mono_metadata_string_heap (m, cols [MONO_METHOD_NAME]);
875 } else {
876 sig_str = NULL;
877 method_name = g_strdup ("<NULL METHOD SIGNATURE>");
878 mono_error_cleanup (error);
881 fprintf (output, " // method line %d\n", i + 1);
882 fprintf (output, " .method %s", flags);
884 if ((cols [MONO_METHOD_FLAGS] & METHOD_ATTRIBUTE_PINVOKE_IMPL) && (cols [MONO_METHOD_RVA] == 0)) {
885 gchar *pi = pinvoke_info (m, i);
886 if (pi) {
887 fprintf (output, "%s", pi);
888 g_free (pi);
892 fprintf (output, "\n %s", sig_str);
893 fprintf (output, " %s\n", impl_flags);
894 g_free (flags);
895 g_free (impl_flags);
897 token = MONO_TOKEN_METHOD_DEF | (i + 1);
899 fprintf (output, " {\n");
900 dump_cattrs (m, token, " ");
901 dump_cattrs_for_type_params (m, MONO_TOKEN_METHOD_DEF | (i + 1), " ");
902 dump_cattrs_for_method_params (m, i, ms);
904 fprintf (output, " // Method begins at RVA 0x%x\n", cols [MONO_METHOD_RVA]);
905 dump_declarative_security (m, OBJECT_TYPE_METHODDEF, i + 1, " ");
906 if (cols [MONO_METHOD_IMPLFLAGS] & METHOD_IMPL_ATTRIBUTE_NATIVE)
907 fprintf (output, " // Disassembly of native methods is not supported\n");
908 else
909 dis_code (m, token, cols [MONO_METHOD_RVA], container);
910 if (klass_name)
911 fprintf (output, " } // end of method %s::%s\n\n", klass_name, method_name);
912 else
913 fprintf (output, " } // end of global method %s\n\n", method_name);
914 mono_metadata_free_method_signature (ms);
915 g_free (sig_str);
919 typedef struct {
920 MonoTableInfo *t;
921 guint32 col_idx;
922 guint32 idx;
923 guint32 result;
924 } plocator_t;
926 static int
927 table_locator (const void *a, const void *b)
929 plocator_t *loc = (plocator_t *) a;
930 const char *bb = (const char *) b;
931 guint32 table_index = (bb - loc->t->base) / loc->t->row_size;
932 guint32 col;
934 col = mono_metadata_decode_row_col (loc->t, table_index, loc->col_idx);
936 if (loc->idx == col) {
937 loc->result = table_index;
938 return 0;
940 if (loc->idx < col)
941 return -1;
942 else
943 return 1;
946 static void
947 dis_property_methods (MonoImage *m, guint32 prop, MonoGenericContainer *container)
949 guint start, end;
950 MonoTableInfo *msemt = &m->tables [MONO_TABLE_METHODSEMANTICS];
951 guint32 cols [MONO_METHOD_SEMA_SIZE];
952 char *sig;
953 const char *type[] = {NULL, ".set", ".get", NULL, ".other"};
955 start = mono_metadata_methods_from_property (m, prop, &end);
956 for (; start < end; ++start) {
957 mono_metadata_decode_row (msemt, start, cols, MONO_METHOD_SEMA_SIZE);
958 if (!should_include_method (cols [MONO_METHOD_SEMA_METHOD]))
959 continue;
960 sig = dis_stringify_method_signature_full (m, NULL, cols [MONO_METHOD_SEMA_METHOD], container, TRUE, FALSE);
961 fprintf (output, "\t\t%s %s\n", type [cols [MONO_METHOD_SEMA_SEMANTICS]], sig);
962 g_free (sig);
965 static char*
966 dis_property_signature (MonoImage *m, guint32 prop_idx, MonoGenericContainer *container)
968 ERROR_DECL (error);
969 MonoTableInfo *propt = &m->tables [MONO_TABLE_PROPERTY];
970 const char *ptr;
971 guint32 pcount, i;
972 guint32 cols [MONO_PROPERTY_SIZE];
973 MonoType *type;
974 MonoType *param;
975 char *blurb, *qk;
976 const char *name;
977 int prop_flags;
978 GString *res = g_string_new ("");
980 mono_metadata_decode_row (propt, prop_idx, cols, MONO_PROPERTY_SIZE);
981 name = mono_metadata_string_heap (m, cols [MONO_PROPERTY_NAME]);
982 prop_flags = cols [MONO_PROPERTY_FLAGS];
983 ptr = mono_metadata_blob_heap (m, cols [MONO_PROPERTY_TYPE]);
984 mono_metadata_decode_blob_size (ptr, &ptr);
985 if (!(*ptr & 0x08))
986 g_warning("incorrect signature in property blob: 0x%x", *ptr);
987 if (*ptr & 0x20)
988 g_string_append (res, "instance ");
989 ptr++;
990 pcount = mono_metadata_decode_value (ptr, &ptr);
991 type = mono_metadata_parse_type_checked (m, container, 0, FALSE, ptr, &ptr, error);
992 if (type) {
993 blurb = dis_stringify_type (m, type, TRUE);
994 } else {
995 blurb = g_strdup_printf ("Invalid type due to %s", mono_error_get_message (error));
996 mono_error_cleanup (error);
998 if (prop_flags & 0x0200)
999 g_string_append (res, "specialname ");
1000 if (prop_flags & 0x0400)
1001 g_string_append (res, "rtspecialname ");
1002 qk = get_escaped_name (name);
1003 g_string_append_printf (res, "%s %s (", blurb, qk);
1004 g_free (qk);
1005 g_free (blurb);
1006 for (i = 0; i < pcount; i++) {
1007 if (i)
1008 g_string_append (res, ", ");
1009 param = mono_metadata_parse_type_checked (m, container, 0, FALSE, ptr, &ptr, error);
1010 if (type) {
1011 blurb = dis_stringify_param (m, param);
1012 } else {
1013 blurb = g_strdup_printf ("Invalid type due to %s", mono_error_get_message (error));
1014 mono_error_cleanup (error);
1017 g_string_append (res, blurb);
1018 g_free (blurb);
1020 g_string_append_c (res, ')');
1021 blurb = res->str;
1022 g_string_free (res, FALSE);
1023 return blurb;
1027 static void
1028 dis_property_list (MonoImage *m, guint32 typedef_row, MonoGenericContainer *container)
1030 guint start, end, i;
1031 start = mono_metadata_properties_from_typedef (m, typedef_row, &end);
1033 for (i = start; i < end; ++i) {
1034 char *sig = dis_property_signature (m, i, container);
1035 fprintf (output, "\t.property %s\n\t{\n", sig);
1036 dump_cattrs (m, MONO_TOKEN_PROPERTY | (i + 1), "\t\t");
1037 dis_property_methods (m, i, container);
1038 fprintf (output, "\t}\n");
1039 g_free (sig);
1043 static char*
1044 dis_event_signature (MonoImage *m, guint32 event_idx, MonoGenericContainer *container)
1046 MonoTableInfo *et = &m->tables [MONO_TABLE_EVENT];
1047 char *type, *result, *esname;
1048 guint32 cols [MONO_EVENT_SIZE];
1049 int event_flags;
1050 GString *res = g_string_new ("");
1052 mono_metadata_decode_row (et, event_idx, cols, MONO_EVENT_SIZE);
1053 esname = get_escaped_name (mono_metadata_string_heap (m, cols [MONO_EVENT_NAME]));
1054 type = get_typedef_or_ref (m, cols [MONO_EVENT_TYPE], container);
1055 event_flags = cols [MONO_EVENT_FLAGS];
1057 if (event_flags & 0x0200)
1058 g_string_append (res, "specialname ");
1059 if (event_flags & 0x0400)
1060 g_string_append (res, "rtspecialname ");
1061 g_string_append_printf (res, "%s %s", type, esname);
1063 g_free (type);
1064 g_free (esname);
1065 result = res->str;
1066 g_string_free (res, FALSE);
1067 return result;
1070 static void
1071 dis_event_methods (MonoImage *m, guint32 event, MonoGenericContainer *container)
1073 guint start, end;
1074 MonoTableInfo *msemt = &m->tables [MONO_TABLE_METHODSEMANTICS];
1075 guint32 cols [MONO_METHOD_SEMA_SIZE];
1076 char *sig;
1077 const char *type = "";
1079 start = mono_metadata_methods_from_event (m, event, &end);
1080 for (; start < end; ++start) {
1081 mono_metadata_decode_row (msemt, start, cols, MONO_METHOD_SEMA_SIZE);
1082 if (!should_include_method (cols [MONO_METHOD_SEMA_METHOD]))
1083 continue;
1084 sig = dis_stringify_method_signature_full (m, NULL, cols [MONO_METHOD_SEMA_METHOD], container, TRUE, FALSE);
1085 switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
1086 case METHOD_SEMANTIC_OTHER:
1087 type = ".other"; break;
1088 case METHOD_SEMANTIC_ADD_ON:
1089 type = ".addon"; break;
1090 case METHOD_SEMANTIC_REMOVE_ON:
1091 type = ".removeon"; break;
1092 case METHOD_SEMANTIC_FIRE:
1093 type = ".fire"; break;
1094 default:
1095 break;
1097 fprintf (output, "\t\t%s %s\n", type, sig);
1098 g_free (sig);
1102 static void
1103 dis_event_list (MonoImage *m, guint32 typedef_row, MonoGenericContainer *container)
1105 guint start, end, i;
1106 start = mono_metadata_events_from_typedef (m, typedef_row, &end);
1108 for (i = start; i < end; ++i) {
1109 char *sig = dis_event_signature (m, i, container);
1110 fprintf (output, "\t.event %s\n\t{\n", sig);
1111 dump_cattrs (m, MONO_TOKEN_EVENT | (i + 1), "\t\t");
1112 dis_event_methods (m, i, container);
1113 fprintf (output, "\t}\n");
1114 g_free (sig);
1118 static void
1119 dis_interfaces (MonoImage *m, guint32 typedef_row, MonoGenericContainer *container)
1121 plocator_t loc;
1122 guint start;
1123 gboolean first_interface = 1;
1124 guint32 cols [MONO_INTERFACEIMPL_SIZE];
1125 char *intf;
1126 MonoTableInfo *table = &m->tables [MONO_TABLE_INTERFACEIMPL];
1128 if (!table->base)
1129 return;
1131 loc.t = table;
1132 loc.col_idx = MONO_INTERFACEIMPL_CLASS;
1133 loc.idx = typedef_row;
1135 if (!mono_binary_search (&loc, table->base, table->rows, table->row_size, table_locator))
1136 return;
1138 start = loc.result;
1140 * We may end up in the middle of the rows...
1142 while (start > 0) {
1143 if (loc.idx == mono_metadata_decode_row_col (table, start - 1, MONO_INTERFACEIMPL_CLASS))
1144 start--;
1145 else
1146 break;
1148 while (start < table->rows) {
1149 mono_metadata_decode_row (table, start, cols, MONO_INTERFACEIMPL_SIZE);
1150 if (cols [MONO_INTERFACEIMPL_CLASS] != loc.idx)
1151 break;
1152 intf = get_typedef_or_ref (m, cols [MONO_INTERFACEIMPL_INTERFACE], container);
1153 if (first_interface) {
1154 fprintf (output, " \timplements %s", intf);
1155 first_interface = 0;
1156 } else {
1157 fprintf (output, ", %s", intf);
1159 g_free (intf);
1160 ++start;
1165 * dis_type:
1166 * @m: metadata context
1167 * @n: index of type to disassemble
1168 * @is_nested: nested type ?
1169 * @forward: forward declarations?
1171 * Disassembles the type whose index in the TypeDef table is @n.
1173 static void
1174 dis_type (MonoImage *m, int n, int is_nested, int forward)
1176 MonoTableInfo *t = &m->tables [MONO_TABLE_TYPEDEF];
1177 guint32 cols [MONO_TYPEDEF_SIZE];
1178 guint32 cols_next [MONO_TYPEDEF_SIZE];
1179 const char *name, *nspace;
1180 char *esname, *param;
1181 MonoGenericContainer *container;
1182 guint32 packing_size, class_size;
1183 gboolean next_is_valid, last;
1184 guint32 nested;
1186 if (!should_include_type (n + 1))
1187 return;
1188 mono_metadata_decode_row (t, n, cols, MONO_TYPEDEF_SIZE);
1190 if (t->rows > n + 1) {
1191 mono_metadata_decode_row (t, n + 1, cols_next, MONO_TYPEDEF_SIZE);
1192 next_is_valid = 1;
1193 } else
1194 next_is_valid = 0;
1196 name = mono_metadata_string_heap (m, cols [MONO_TYPEDEF_NAME]);
1197 nspace = mono_metadata_string_heap (m, cols [MONO_TYPEDEF_NAMESPACE]);
1198 if (*nspace && !is_nested) {
1199 char *esnspace;
1200 esnspace = get_escaped_name (nspace);
1201 fprintf (output, ".namespace %s\n{\n", esnspace);
1202 g_free (esnspace);
1205 container = mono_metadata_load_generic_params (m, MONO_TOKEN_TYPE_DEF | (n + 1), NULL, NULL);
1206 if (container) {
1207 ERROR_DECL (error);
1208 mono_metadata_load_generic_param_constraints_checked (m, MONO_TOKEN_TYPE_DEF | (n + 1), container, error);
1209 g_assert (is_ok (error)); /*FIXME don't swallow the error message*/
1212 esname = get_escaped_name (name);
1213 if ((cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_CLASS_SEMANTIC_MASK) == TYPE_ATTRIBUTE_CLASS){
1214 fprintf (output, " .class %s%s", typedef_flags (cols [MONO_TYPEDEF_FLAGS]), esname);
1216 param = get_generic_param (m, container);
1217 if (param) {
1218 fprintf (output, "%s", param);
1219 g_free (param);
1221 fprintf (output, "\n");
1222 if (cols [MONO_TYPEDEF_EXTENDS]) {
1223 char *base = get_typedef_or_ref (m, cols [MONO_TYPEDEF_EXTENDS], container);
1224 fprintf (output, " \textends %s\n", base);
1225 g_free (base);
1227 } else {
1228 fprintf (output, " .class interface %s%s", typedef_flags (cols [MONO_TYPEDEF_FLAGS]), esname);
1230 param = get_generic_param (m, container);
1231 if (param) {
1232 fprintf (output, "%s", param);
1233 g_free (param);
1235 fprintf (output, "\n");
1238 g_free (esname);
1239 dis_interfaces (m, n + 1, container);
1240 fprintf (output, " {\n");
1241 if (!forward) {
1242 dump_cattrs (m, MONO_TOKEN_TYPE_DEF | (n + 1), " ");
1243 dump_cattrs_for_type_params (m, MONO_TOKEN_TYPE_DEF | (n + 1), " ");
1244 dump_declarative_security (m, OBJECT_TYPE_TYPEDEF, (n + 1), " ");
1246 if (mono_metadata_packing_from_typedef (m, n + 1, &packing_size, &class_size)) {
1247 fprintf (output, " .pack %d\n", packing_size);
1248 fprintf (output, " .size %d\n", class_size);
1251 * The value in the table is always valid, we know we have fields
1252 * if the value stored is different than the next record.
1255 if (next_is_valid)
1256 last = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
1257 else
1258 last = m->tables [MONO_TABLE_FIELD].rows;
1260 if (cols [MONO_TYPEDEF_FIELD_LIST] && cols [MONO_TYPEDEF_FIELD_LIST] <= m->tables [MONO_TABLE_FIELD].rows)
1261 dis_field_list (m, cols [MONO_TYPEDEF_FIELD_LIST] - 1, last, container);
1262 fprintf (output, "\n");
1264 if (next_is_valid)
1265 last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
1266 else
1267 last = m->tables [MONO_TABLE_METHOD].rows;
1269 if (cols [MONO_TYPEDEF_METHOD_LIST] && cols [MONO_TYPEDEF_METHOD_LIST] <= m->tables [MONO_TABLE_METHOD].rows)
1270 dis_method_list (name, m, cols [MONO_TYPEDEF_METHOD_LIST] - 1, last, container);
1272 dis_property_list (m, n, container);
1273 dis_event_list (m, n, container);
1276 t = &m->tables [MONO_TABLE_NESTEDCLASS];
1277 nested = mono_metadata_nesting_typedef (m, n + 1, 1);
1278 while (nested) {
1279 dis_type (m, mono_metadata_decode_row_col (t, nested - 1, MONO_NESTED_CLASS_NESTED) - 1, 1, forward);
1280 nested = mono_metadata_nesting_typedef (m, n + 1, nested + 1);
1283 fprintf (output, " } // end of class %s%s%s\n", nspace, *nspace? ".": "", name);
1284 if (*nspace && !is_nested)
1285 fprintf (output, "}\n");
1286 fprintf (output, "\n");
1291 * dis_globals
1292 * @m: metadata context
1294 * disassembles all the global fields and methods
1296 static void
1297 dis_globals (MonoImage *m)
1299 MonoTableInfo *t = &m->tables [MONO_TABLE_TYPEDEF];
1300 guint32 cols [MONO_TYPEDEF_SIZE];
1301 guint32 cols_next [MONO_TYPEDEF_SIZE];
1302 gboolean next_is_valid, last;
1304 mono_metadata_decode_row (t, 0, cols, MONO_TYPEDEF_SIZE);
1306 if (t->rows > 1) {
1307 mono_metadata_decode_row (t, 1, cols_next, MONO_TYPEDEF_SIZE);
1308 next_is_valid = 1;
1309 } else
1310 next_is_valid = 0;
1313 * The value in the table is always valid, we know we have fields
1314 * if the value stored is different than the next record.
1317 if (next_is_valid)
1318 last = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
1319 else
1320 last = m->tables [MONO_TABLE_FIELD].rows;
1322 if (cols [MONO_TYPEDEF_FIELD_LIST] && cols [MONO_TYPEDEF_FIELD_LIST] <= m->tables [MONO_TABLE_FIELD].rows)
1323 dis_field_list (m, cols [MONO_TYPEDEF_FIELD_LIST] - 1, last, NULL);
1324 fprintf (output, "\n");
1326 if (next_is_valid)
1327 last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
1328 else
1329 last = m->tables [MONO_TABLE_METHOD].rows;
1331 if (cols [MONO_TYPEDEF_METHOD_LIST] && cols [MONO_TYPEDEF_METHOD_LIST] <= m->tables [MONO_TABLE_METHOD].rows)
1332 dis_method_list (NULL, m, cols [MONO_TYPEDEF_METHOD_LIST] - 1, last, NULL);
1336 static void dis_resources_worker (MonoImage *m, gboolean just_print)
1338 MonoTableInfo *t = &m->tables [MONO_TABLE_MANIFESTRESOURCE];
1339 int i;
1341 for (i = 0; i < t->rows; i++){
1342 guint32 cols [MONO_MANIFEST_SIZE];
1343 const char *name, *res;
1344 guint32 size;
1345 FILE* fp;
1347 mono_metadata_decode_row (t, i, cols, MONO_MANIFEST_SIZE);
1348 name = mono_metadata_string_heap (m, cols [MONO_MANIFEST_NAME]);
1350 if (just_print)
1351 fprintf (output, "%8x: %s", cols [MONO_MANIFEST_OFFSET], name);
1353 if (! (res = mono_image_get_resource (m, cols [MONO_MANIFEST_OFFSET], &size))) {
1354 if (just_print)
1355 fprintf (output, " (absent from image)\n");
1356 continue;
1359 if (just_print) {
1360 fprintf (output, " (size %u)\n", size);
1361 continue;
1364 if ( (fp = fopen (name, "ab")) ) {
1365 if (ftell (fp) == 0)
1366 fwrite (res, size, 1, fp);
1367 else
1368 g_warning ("Error creating managed resource - %s : File already exists.", name);
1370 fclose (fp);
1371 } else
1372 g_warning ("Error creating managed resource - %s : %s", name, g_strerror (errno));
1376 static void
1377 dis_mresource (MonoImage *m)
1379 dis_resources_worker (m, FALSE);
1382 static void
1383 dis_presource (MonoImage *m)
1385 dis_resources_worker (m, TRUE);
1388 static char *
1389 exported_type_flags (guint32 flags)
1391 static char buffer [1024];
1392 int visibility = flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
1394 buffer [0] = 0;
1396 if (flags & TYPE_ATTRIBUTE_FORWARDER) {
1397 strcat (buffer, "forwarder ");
1398 return buffer;
1401 strcat (buffer, map (visibility, visibility_map));
1402 return buffer;
1405 static char *
1406 get_escaped_fullname (MonoImage *m, guint32 nspace_idx, guint32 name_idx)
1408 const char *name, *nspace;
1409 char *fullname, *esfullname;
1411 nspace = mono_metadata_string_heap (m, nspace_idx);
1412 name = mono_metadata_string_heap (m, name_idx);
1414 fullname = g_strdup_printf ("%s%s%s", nspace, *nspace ? "." : "", name);
1415 esfullname = get_escaped_name (fullname);
1417 g_free (fullname);
1419 return esfullname;
1422 static void
1423 dis_exported_types (MonoImage *m)
1425 MonoTableInfo *t = &m->tables [MONO_TABLE_EXPORTEDTYPE];
1426 int i;
1428 for (i = 1; i <= t->rows; i++) {
1429 char *fullname;
1430 guint32 impl, idx, type_token;
1431 guint32 cols [MONO_EXP_TYPE_SIZE];
1433 mono_metadata_decode_row (t, i - 1, cols, MONO_EXP_TYPE_SIZE);
1435 fullname = get_escaped_fullname (m, cols [MONO_EXP_TYPE_NAMESPACE], cols [MONO_EXP_TYPE_NAME]);
1437 fprintf (output, "\n");
1438 fprintf (output, ".class extern %s%s\n", exported_type_flags (cols [MONO_EXP_TYPE_FLAGS]), fullname);
1439 fprintf (output, "{\n");
1441 g_free (fullname);
1443 impl = cols [MONO_EXP_TYPE_IMPLEMENTATION];
1444 if (impl) {
1445 idx = impl >> MONO_IMPLEMENTATION_BITS;
1446 switch (impl & MONO_IMPLEMENTATION_MASK) {
1447 case MONO_IMPLEMENTATION_FILE:
1448 fprintf (output, " .file '%s'\n",
1449 mono_metadata_string_heap (m, mono_metadata_decode_row_col (&m->tables [MONO_TABLE_FILE], idx - 1, MONO_FILE_NAME)));
1450 break;
1451 case MONO_IMPLEMENTATION_ASSEMBLYREF:
1452 fprintf (output, " .assembly extern '%s'\n",
1453 mono_metadata_string_heap (m, mono_metadata_decode_row_col (&m->tables [MONO_TABLE_ASSEMBLYREF], idx - 1, MONO_ASSEMBLYREF_NAME)));
1454 break;
1455 case MONO_IMPLEMENTATION_EXP_TYPE:
1456 fullname = get_escaped_fullname (
1458 mono_metadata_decode_row_col (&m->tables [MONO_TABLE_EXPORTEDTYPE], idx - 1, MONO_EXP_TYPE_NAMESPACE),
1459 mono_metadata_decode_row_col (&m->tables [MONO_TABLE_EXPORTEDTYPE], idx - 1, MONO_EXP_TYPE_NAME));
1460 fprintf (output, " .class extern %s\n", fullname);
1461 g_free (fullname);
1462 break;
1463 default:
1464 g_assert_not_reached ();
1465 break;
1469 type_token = cols [MONO_EXP_TYPE_TYPEDEF];
1470 if (type_token)
1471 fprintf (output, " .class 0x%08x\n", type_token | MONO_TOKEN_TYPE_DEF);
1473 fprintf (output, "}\n");
1478 * dis_types:
1479 * @m: metadata context
1481 * disassembles all types in the @m context
1483 static void
1484 dis_types (MonoImage *m, int forward)
1486 MonoTableInfo *t = &m->tables [MONO_TABLE_TYPEDEF];
1487 int i;
1488 guint32 flags;
1490 dis_globals (m);
1492 for (i = 1; i < t->rows; i++) {
1493 flags = mono_metadata_decode_row_col (t, i, MONO_TYPEDEF_FLAGS);
1494 flags &= TYPE_ATTRIBUTE_VISIBILITY_MASK;
1495 if (flags == TYPE_ATTRIBUTE_PUBLIC || flags == TYPE_ATTRIBUTE_NOT_PUBLIC)
1496 dis_type (m, i, 0, forward);
1500 static const char *
1501 get_uninitialized_data_type (guint32 size)
1503 switch (size) {
1504 case 1:
1505 return "int8";
1506 case 2:
1507 return "int16";
1508 case 4:
1509 return "int32";
1510 case 8:
1511 return "int64";
1512 default:
1513 g_error ("get_uninitialized_data_type for size: %d\n", size);
1515 return NULL;
1519 * dis_data:
1520 * @m: metadata context
1522 * disassembles all data blobs references in the FieldRVA table in the @m context
1524 static void
1525 dis_data (MonoImage *m)
1527 MonoTableInfo *t = &m->tables [MONO_TABLE_FIELDRVA];
1528 MonoTableInfo *ft = &m->tables [MONO_TABLE_FIELD];
1529 int i, b;
1530 const char *rva, *sig;
1531 guint32 size;
1532 gint align;
1533 guint32 cols [MONO_FIELD_RVA_SIZE];
1534 MonoType *type;
1536 for (i = 0; i < t->rows; i++) {
1537 ERROR_DECL (error);
1538 mono_metadata_decode_row (t, i, cols, MONO_FIELD_RVA_SIZE);
1539 rva = mono_image_rva_map (m, cols [MONO_FIELD_RVA_RVA]);
1540 sig = mono_metadata_blob_heap (m, mono_metadata_decode_row_col (ft, cols [MONO_FIELD_RVA_FIELD] -1, MONO_FIELD_SIGNATURE));
1541 mono_metadata_decode_value (sig, &sig);
1542 /* FIELD signature == 0x06 */
1543 g_assert (*sig == 0x06);
1544 type = mono_metadata_parse_type_checked (m, NULL, 0, FALSE, sig + 1, &sig, error);
1545 if (!type) {
1546 fprintf (output, "// invalid field %d due to %s\n", i, mono_error_get_message (error));
1547 mono_error_cleanup (error);
1548 continue;
1550 mono_class_init_internal (mono_class_from_mono_type_internal (type));
1551 size = mono_type_size (type, &align);
1553 if (rva) {
1554 fprintf (output, ".data D_%08x = bytearray (", cols [MONO_FIELD_RVA_RVA]);
1555 for (b = 0; b < size; ++b) {
1556 if (!(b % 16))
1557 fprintf (output, "\n\t");
1558 fprintf (output, " %02X", rva [b] & 0xff);
1560 fprintf (output, ") // size: %d\n", size);
1561 } else
1562 fprintf (output, ".data D_%08x = %s [%d]\n",
1563 cols [MONO_FIELD_RVA_RVA], get_uninitialized_data_type (size), size);
1567 struct {
1568 const char *name;
1569 int table;
1570 void (*dumper) (MonoImage *m);
1571 } table_list [] = {
1572 { "--assembly", MONO_TABLE_ASSEMBLY, dump_table_assembly },
1573 { "--assemblyref", MONO_TABLE_ASSEMBLYREF, dump_table_assemblyref },
1574 { "--classlayout", MONO_TABLE_CLASSLAYOUT, dump_table_class_layout },
1575 { "--constant", MONO_TABLE_CONSTANT, dump_table_constant },
1576 { "--customattr", MONO_TABLE_CUSTOMATTRIBUTE, dump_table_customattr },
1577 { "--declsec", MONO_TABLE_DECLSECURITY, dump_table_declsec },
1578 { "--event", MONO_TABLE_EVENT, dump_table_event },
1579 { "--exported", MONO_TABLE_EXPORTEDTYPE, dump_table_exported },
1580 { "--fields", MONO_TABLE_FIELD, dump_table_field },
1581 { "--file", MONO_TABLE_FILE, dump_table_file },
1582 { "--genericpar", MONO_TABLE_GENERICPARAM, dump_table_genericpar },
1583 { "--interface", MONO_TABLE_INTERFACEIMPL, dump_table_interfaceimpl },
1584 { "--manifest", MONO_TABLE_MANIFESTRESOURCE, dump_table_manifest },
1585 { "--marshal", MONO_TABLE_FIELDMARSHAL, dump_table_field_marshal },
1586 { "--memberref", MONO_TABLE_MEMBERREF, dump_table_memberref },
1587 { "--method", MONO_TABLE_METHOD, dump_table_method },
1588 { "--methodimpl", MONO_TABLE_METHODIMPL, dump_table_methodimpl },
1589 { "--methodsem", MONO_TABLE_METHODSEMANTICS, dump_table_methodsem },
1590 { "--methodspec", MONO_TABLE_METHODSPEC, dump_table_methodspec },
1591 { "--moduleref", MONO_TABLE_MODULEREF, dump_table_moduleref },
1592 { "--module", MONO_TABLE_MODULE, dump_table_module },
1593 { "--mresources", 0, dis_mresource },
1594 { "--presources", 0, dis_presource },
1595 { "--nested", MONO_TABLE_NESTEDCLASS, dump_table_nestedclass },
1596 { "--param", MONO_TABLE_PARAM, dump_table_param },
1597 { "--parconst", MONO_TABLE_GENERICPARAMCONSTRAINT, dump_table_parconstraint },
1598 { "--property", MONO_TABLE_PROPERTY, dump_table_property },
1599 { "--propertymap", MONO_TABLE_PROPERTYMAP, dump_table_property_map },
1600 { "--typedef", MONO_TABLE_TYPEDEF, dump_table_typedef },
1601 { "--typeref", MONO_TABLE_TYPEREF, dump_table_typeref },
1602 { "--typespec", MONO_TABLE_TYPESPEC, dump_table_typespec },
1603 { "--implmap", MONO_TABLE_IMPLMAP, dump_table_implmap },
1604 { "--fieldrva", MONO_TABLE_FIELDRVA, dump_table_fieldrva },
1605 { "--standalonesig", MONO_TABLE_STANDALONESIG, dump_table_standalonesig },
1606 { "--methodptr", MONO_TABLE_METHOD_POINTER, dump_table_methodptr },
1607 { "--fieldptr", MONO_TABLE_FIELD_POINTER, dump_table_fieldptr },
1608 { "--paramptr", MONO_TABLE_PARAM_POINTER, dump_table_paramptr },
1609 { "--eventptr", MONO_TABLE_EVENT_POINTER, dump_table_eventptr },
1610 { "--propertyptr", MONO_TABLE_PROPERTY_POINTER, dump_table_propertyptr },
1611 { "--blob", 0, dump_stream_blob },
1612 { "--strings", 0, dump_stream_strings },
1613 { "--userstrings", 0, dump_stream_us },
1614 { NULL, -1, }
1618 * disassemble_file:
1619 * @file: file containing CIL code.
1621 * Disassembles the @file file.
1623 static int
1624 disassemble_file (const char *file)
1626 MonoImageOpenStatus status;
1627 MonoImage *img;
1629 img = mono_image_open (file, &status);
1630 if (!img) {
1631 fprintf (stderr, "Error while trying to process %s\n", file);
1632 return 1;
1633 } else {
1634 /* FIXME: is this call necessary? */
1635 /* FIXME: if it's necessary, can it be refonly instead? */
1636 MonoAssemblyLoadRequest req;
1637 mono_assembly_request_prepare_load (&req, MONO_ASMCTX_DEFAULT, mono_domain_default_alc (mono_domain_get ()));
1639 mono_assembly_request_load_from (img, file, &req, &status);
1642 setup_filter (img);
1644 if (dump_table != -1){
1645 (*table_list [dump_table].dumper) (img);
1646 } else {
1647 dump_header_data (img);
1649 dis_directive_assemblyref (img);
1650 dis_directive_assembly (img);
1651 dis_directive_file (img);
1652 dis_directive_mresource (img);
1653 dis_directive_module (img);
1654 dis_directive_moduleref (img);
1655 dis_exported_types (img);
1656 dis_nt_header (img);
1657 if (dump_managed_resources)
1658 dis_mresource (img);
1659 if (dump_forward_decls) {
1660 fprintf (output, "// *************** Forward Declarations for Classes ***************\n\n");
1661 dis_types (img, 1);
1662 fprintf (output, "// *************** End-Of Forward Declarations for Classes ***************\n\n");
1664 dis_types (img, 0);
1665 dis_data (img);
1668 mono_image_close (img);
1669 return 0;
1672 typedef struct {
1673 int size;
1674 int count;
1675 int *elems;
1676 } TableFilter;
1678 typedef struct {
1679 char *name;
1680 char *guid;
1681 TableFilter types;
1682 TableFilter fields;
1683 TableFilter methods;
1684 } ImageFilter;
1686 static GList *filter_list = NULL;
1687 static ImageFilter *cur_filter = NULL;
1689 static void
1690 setup_filter (MonoImage *image)
1692 ImageFilter *ifilter;
1693 GList *item;
1694 const char *name = mono_image_get_name (image);
1696 for (item = filter_list; item; item = item->next) {
1697 ifilter = (ImageFilter *)item->data;
1698 if (strcmp (ifilter->name, name) == 0) {
1699 cur_filter = ifilter;
1700 return;
1703 cur_filter = NULL;
1706 static int
1707 int_cmp (const void *e1, const void *e2)
1709 const int *i1 = (const int *)e1;
1710 const int *i2 = (const int *)e2;
1711 return *i1 - *i2;
1714 static gboolean
1715 table_includes (TableFilter *tf, int idx)
1717 if (!tf->count)
1718 return FALSE;
1719 return mono_binary_search (&idx, tf->elems, tf->count, sizeof (int), int_cmp) != NULL;
1722 static gboolean
1723 should_include_type (int idx)
1725 if (!cur_filter)
1726 return TRUE;
1727 return table_includes (&cur_filter->types, idx);
1730 static gboolean
1731 should_include_method (int idx)
1733 if (!cur_filter)
1734 return TRUE;
1735 return table_includes (&cur_filter->methods, idx);
1738 static gboolean
1739 should_include_field (int idx)
1741 if (!cur_filter)
1742 return TRUE;
1743 return table_includes (&cur_filter->fields, idx);
1746 static ImageFilter*
1747 add_filter (const char *name)
1749 ImageFilter *ifilter;
1750 GList *item;
1752 for (item = filter_list; item; item = item->next) {
1753 ifilter = (ImageFilter *)item->data;
1754 if (strcmp (ifilter->name, name) == 0)
1755 return ifilter;
1757 ifilter = g_new0 (ImageFilter, 1);
1758 ifilter->name = g_strdup (name);
1759 filter_list = g_list_prepend (filter_list, ifilter);
1760 return ifilter;
1763 static void
1764 add_item (TableFilter *tf, int val)
1766 if (tf->count >= tf->size) {
1767 if (!tf->size) {
1768 tf->size = 8;
1769 tf->elems = (int *)g_malloc (sizeof (int) * tf->size);
1770 } else {
1771 tf->size *= 2;
1772 tf->elems = (int *)g_realloc (tf->elems, sizeof (int) * tf->size);
1775 tf->elems [tf->count++] = val;
1778 static void
1779 sort_filter_elems (void)
1781 ImageFilter *ifilter;
1782 GList *item;
1784 for (item = filter_list; item; item = item->next) {
1785 ifilter = (ImageFilter *)item->data;
1786 mono_qsort (ifilter->types.elems, ifilter->types.count, sizeof (int), int_cmp);
1787 mono_qsort (ifilter->fields.elems, ifilter->fields.count, sizeof (int), int_cmp);
1788 mono_qsort (ifilter->methods.elems, ifilter->methods.count, sizeof (int), int_cmp);
1792 static void
1793 load_filter (const char* filename)
1795 FILE *file;
1796 char buf [1024];
1797 char *p, *s, *endptr;
1798 int line = 0;
1799 ImageFilter *ifilter = NULL;
1800 int value = 0;
1802 if (!(file = fopen (filename, "r"))) {
1803 g_print ("Cannot open filter file '%s'\n", filename);
1804 exit (1);
1806 while (fgets (buf, sizeof (buf), file) != NULL) {
1807 ++line;
1808 s = buf;
1809 while (*s && g_ascii_isspace (*s)) ++s;
1810 switch (*s) {
1811 case 0:
1812 case '#':
1813 break;
1814 case '[':
1815 p = strchr (s, ']');
1816 if (!p)
1817 g_error ("No matching ']' in filter at line %d\n", line);
1818 *p = 0;
1819 ifilter = add_filter (s + 1);
1820 break;
1821 case 'T':
1822 if (!ifilter)
1823 g_error ("Invalid format in filter at line %d\n", line);
1824 if ((s [1] != ':') || !(value = strtol (s + 2, &endptr, 0)) || (endptr == s + 2))
1825 g_error ("Invalid type number in filter at line %d\n", line);
1826 add_item (&ifilter->types, value);
1827 break;
1828 case 'M':
1829 if (!ifilter)
1830 g_error ("Invalid format in filter at line %d\n", line);
1831 if ((s [1] != ':') || !(value = strtol (s + 2, &endptr, 0)) || (endptr == s + 2))
1832 g_error ("Invalid method number in filter at line %d\n", line);
1833 add_item (&ifilter->methods, value);
1834 break;
1835 case 'F':
1836 if (!ifilter)
1837 g_error ("Invalid format in filter at line %d\n", line);
1838 if ((s [1] != ':') || !(value = strtol (s + 2, &endptr, 0)) || (endptr == s + 2))
1839 g_error ("Invalid field number in filter at line %d\n", line);
1840 add_item (&ifilter->fields, value);
1841 break;
1842 default:
1843 g_error ("Invalid format in filter at line %d\n", line);
1846 fclose (file);
1847 sort_filter_elems ();
1851 static gboolean
1852 try_load_from (MonoAssembly **assembly,
1853 const gchar *path1, const gchar *path2,
1854 const gchar *path3, const gchar *path4,
1855 const MonoAssemblyOpenRequest *req)
1857 gchar *fullpath;
1859 *assembly = NULL;
1860 fullpath = g_build_filename (path1, path2, path3, path4, (const char*)NULL);
1861 if (g_file_test (fullpath, G_FILE_TEST_IS_REGULAR))
1862 *assembly = mono_assembly_request_open (fullpath, req, NULL);
1864 g_free (fullpath);
1865 return (*assembly != NULL);
1868 static MonoAssembly *
1869 real_load (gchar **search_path, const gchar *culture, const gchar *name, const MonoAssemblyOpenRequest *req)
1871 MonoAssembly *result = NULL;
1872 gchar **path;
1873 gchar *filename;
1874 const gchar *local_culture;
1875 gint len;
1877 if (!culture || *culture == '\0') {
1878 local_culture = "";
1879 } else {
1880 local_culture = culture;
1883 filename = g_strconcat (name, ".dll", (const char*)NULL);
1884 len = strlen (filename);
1886 for (path = search_path; *path; path++) {
1887 if (**path == '\0')
1888 continue; /* Ignore empty ApplicationBase */
1890 /* See test cases in bug #58992 and bug #57710 */
1891 /* 1st try: [culture]/[name].dll (culture may be empty) */
1892 strcpy (filename + len - 4, ".dll");
1893 if (try_load_from (&result, *path, local_culture, "", filename, req))
1894 break;
1896 /* 2nd try: [culture]/[name].exe (culture may be empty) */
1897 strcpy (filename + len - 4, ".exe");
1898 if (try_load_from (&result, *path, local_culture, "", filename, req))
1899 break;
1901 /* 3rd try: [culture]/[name]/[name].dll (culture may be empty) */
1902 strcpy (filename + len - 4, ".dll");
1903 if (try_load_from (&result, *path, local_culture, name, filename, req))
1904 break;
1906 /* 4th try: [culture]/[name]/[name].exe (culture may be empty) */
1907 strcpy (filename + len - 4, ".exe");
1908 if (try_load_from (&result, *path, local_culture, name, filename, req))
1909 break;
1912 g_free (filename);
1913 return result;
1917 * Try to load referenced assemblies from assemblies_path.
1919 static MonoAssembly *
1920 monodis_preload (MonoAssemblyLoadContext *alc,
1921 MonoAssemblyName *aname,
1922 gchar **assemblies_path,
1923 gboolean refonly,
1924 gpointer user_data,
1925 MonoError *error)
1927 MonoAssembly *result = NULL;
1929 if (assemblies_path && assemblies_path [0] != NULL) {
1930 MonoAssemblyOpenRequest req;
1931 mono_assembly_request_prepare_open (&req, refonly ? MONO_ASMCTX_REFONLY : MONO_ASMCTX_DEFAULT, alc);
1933 result = real_load (assemblies_path, aname->culture, aname->name, &req);
1936 return result;
1939 static GList *loaded_assemblies = NULL;
1941 static void
1942 monodis_assembly_load_hook (MonoAssemblyLoadContext *alc, MonoAssembly *assembly, gpointer user_data, MonoError *error)
1944 loaded_assemblies = g_list_prepend (loaded_assemblies, assembly);
1947 static MonoAssembly *
1948 monodis_assembly_search_hook (MonoAssemblyLoadContext *alc, MonoAssembly *requesting, MonoAssemblyName *aname, gboolean refonly, gboolean postload, gpointer user_data, MonoError *error)
1950 GList *tmp;
1952 for (tmp = loaded_assemblies; tmp; tmp = tmp->next) {
1953 MonoAssembly *ass = (MonoAssembly *)tmp->data;
1954 if (mono_assembly_check_name_match (aname, &ass->aname))
1955 return ass;
1957 return NULL;
1960 static void
1961 usage (void)
1963 GString *args = g_string_new ("[--output=filename] [--filter=filename]\n");
1964 int i;
1966 g_string_append (args, "[--help] [--mscorlib] [--show-tokens] [--show-method-tokens]\n");
1968 for (i = 0; table_list [i].name != NULL; i++){
1969 g_string_append (args, "[");
1970 g_string_append (args, table_list [i].name);
1971 g_string_append (args, "] ");
1972 if (((i-2) % 5) == 0)
1973 g_string_append_c (args, '\n');
1975 g_string_append (args, "[--forward-decls]");
1976 fprintf (stderr,
1977 "monodis -- Mono Common Intermediate Language Disassembler\n"
1978 "Usage is: monodis %s file ..\n", args->str);
1979 exit (1);
1982 static void
1983 monodis_thread_state_init (MonoThreadUnwindState *ctx)
1987 #define monodis_setup_async_callback NULL
1988 #define monodis_thread_state_init_from_sigctx NULL
1989 #define monodis_thread_state_init_from_handle NULL
1992 main (int argc, char *argv [])
1994 static const MonoThreadInfoRuntimeCallbacks ticallbacks = {
1995 MONO_THREAD_INFO_RUNTIME_CALLBACKS (MONO_INIT_CALLBACK, monodis)
1998 GList *input_files = NULL, *l;
1999 int i, j;
2001 output = stdout;
2002 init_key_table ();
2003 for (i = 1; i < argc; i++){
2004 if (argv [i][0] == '-'){
2005 if (argv [i][1] == 'h')
2006 usage ();
2007 else if (argv [i][1] == 'd')
2008 dump_header_data_p = TRUE;
2009 else if (strcmp (argv [i], "--mscorlib") == 0) {
2010 substitute_with_mscorlib_p = TRUE;
2011 continue;
2012 } else if (strcmp (argv [i], "--show-method-tokens") == 0) {
2013 show_method_tokens = TRUE;
2014 continue;
2015 } else if (strcmp (argv [i], "--show-tokens") == 0) {
2016 show_tokens = TRUE;
2017 continue;
2018 } else if (strncmp (argv [i], "--output=", 9) == 0) {
2019 output = fopen (argv [i]+9, "w");
2020 if (output == NULL) {
2021 fprintf (stderr, "Can't open output file `%s': %s\n",
2022 argv [i]+9, strerror (errno));
2023 exit (1);
2025 dump_managed_resources = TRUE;
2026 continue;
2027 } else if (strncmp (argv [i], "--filter=", 9) == 0) {
2028 load_filter (argv [i]+9);
2029 continue;
2030 } else if (strcmp (argv [i], "--forward-decls") == 0) {
2031 dump_forward_decls = TRUE;
2032 continue;
2033 } else if (strcmp (argv [i], "--help") == 0)
2034 usage ();
2035 for (j = 0; table_list [j].name != NULL; j++) {
2036 if (strcmp (argv [i], table_list [j].name) == 0)
2037 dump_table = j;
2039 if (dump_table < 0)
2040 usage ();
2041 } else
2042 input_files = g_list_append (input_files, argv [i]);
2045 if (input_files == NULL)
2046 usage ();
2048 CHECKED_MONO_INIT ();
2049 mono_counters_init ();
2050 mono_tls_init_runtime_keys ();
2051 #ifndef HOST_WIN32
2052 mono_w32handle_init ();
2053 #endif
2054 mono_thread_info_runtime_init (&ticallbacks);
2056 mono_install_assembly_load_hook_v2 (monodis_assembly_load_hook, NULL);
2057 mono_install_assembly_search_hook_v2 (monodis_assembly_search_hook, NULL, FALSE, FALSE);
2060 * If we just have one file, use the corlib version it requires.
2062 if (!input_files->next) {
2063 char *filename = (char *)input_files->data;
2065 mono_init_from_assembly (argv [0], filename);
2067 mono_install_assembly_preload_hook_v2 (monodis_preload, GUINT_TO_POINTER (FALSE), FALSE);
2069 return disassemble_file (filename);
2070 } else {
2071 mono_init (argv [0]);
2073 i = 0;
2074 for (l = input_files; l; l = l->next)
2075 if (disassemble_file ((const char *)l->data) == 1) i = 1;
2076 return i;
2079 return 0;