2003-10-16 Martin Baulig <martin@ximian.com>
[mono.git] / mono / metadata / metadata.c
index d1a9aee7ba2a70dbd3c495e108bb2f52610a50de..447794d75466d550ff79c3d9e511e39833ec1ba6 100644 (file)
@@ -1,10 +1,11 @@
 /*
  * metadata.c: Routines for accessing the metadata
  *
- * Author:
+ * Authors:
  *   Miguel de Icaza (miguel@ximian.com)
+ *   Paolo Molaro (lupus@ximian.com)
  *
- * (C) 2001 Ximian, Inc.
+ * (C) 2001-2002 Ximian, Inc.
  */
 
 #include <config.h>
@@ -34,7 +35,7 @@ static void do_mono_metadata_parse_type (MonoType *type, MonoImage *m, const cha
  * information might refer to different tables.
  */
 
-static MonoMetaTable AssemblySchema [] = {
+const static MonoMetaTable AssemblySchema [] = {
        { MONO_MT_UINT32,     "HashId" },
        { MONO_MT_UINT16,     "Major" },  
        { MONO_MT_UINT16,     "Minor" },
@@ -47,19 +48,19 @@ static MonoMetaTable AssemblySchema [] = {
        { MONO_MT_END, NULL }
 };
        
-static MonoMetaTable AssemblyOSSchema [] = {
+const static MonoMetaTable AssemblyOSSchema [] = {
        { MONO_MT_UINT32,     "OSPlatformID" },
        { MONO_MT_UINT32,     "OSMajor" },
        { MONO_MT_UINT32,     "OSMinor" },
        { MONO_MT_END, NULL }
 };
 
-static MonoMetaTable AssemblyProcessorSchema [] = {
+const static MonoMetaTable AssemblyProcessorSchema [] = {
        { MONO_MT_UINT32,     "Processor" },
        { MONO_MT_END, NULL }
 };
 
-static MonoMetaTable AssemblyRefSchema [] = {
+const static MonoMetaTable AssemblyRefSchema [] = {
        { MONO_MT_UINT16,     "Major" },
        { MONO_MT_UINT16,     "Minor" },
        { MONO_MT_UINT16,     "Build" },
@@ -72,7 +73,7 @@ static MonoMetaTable AssemblyRefSchema [] = {
        { MONO_MT_END, NULL }
 };
 
-static MonoMetaTable AssemblyRefOSSchema [] = {
+const static MonoMetaTable AssemblyRefOSSchema [] = {
        { MONO_MT_UINT32,     "OSPlatformID" },
        { MONO_MT_UINT32,     "OSMajorVersion" },
        { MONO_MT_UINT32,     "OSMinorVersion" },
@@ -80,20 +81,20 @@ static MonoMetaTable AssemblyRefOSSchema [] = {
        { MONO_MT_END, NULL }
 };
 
-static MonoMetaTable AssemblyRefProcessorSchema [] = {
+const static MonoMetaTable AssemblyRefProcessorSchema [] = {
        { MONO_MT_UINT32,     "Processor" },
        { MONO_MT_TABLE_IDX,  "AssemblyRef:AssemblyRef" },
        { MONO_MT_END, NULL }   
 };
 
-static MonoMetaTable ClassLayoutSchema [] = {
+const static MonoMetaTable ClassLayoutSchema [] = {
        { MONO_MT_UINT16,     "PackingSize" },
        { MONO_MT_UINT32,     "ClassSize" },
        { MONO_MT_TABLE_IDX,  "Parent:TypeDef" },
        { MONO_MT_END, NULL }
 };
 
-static MonoMetaTable ConstantSchema [] = {
+const static MonoMetaTable ConstantSchema [] = {
        { MONO_MT_UINT8,      "Type" },
        { MONO_MT_UINT8,      "PaddingZero" },
        { MONO_MT_CONST_IDX,  "Parent" },
@@ -101,34 +102,34 @@ static MonoMetaTable ConstantSchema [] = {
        { MONO_MT_END, NULL }
 };
 
-static MonoMetaTable CustomAttributeSchema [] = {
+const static MonoMetaTable CustomAttributeSchema [] = {
        { MONO_MT_HASCAT_IDX, "Parent" },
        { MONO_MT_CAT_IDX,    "Type" },
        { MONO_MT_BLOB_IDX,   "Value" },
        { MONO_MT_END, NULL }
 };
 
-static MonoMetaTable DeclSecuritySchema [] = {
+const static MonoMetaTable DeclSecuritySchema [] = {
        { MONO_MT_UINT16,     "Action" },
        { MONO_MT_HASDEC_IDX, "Parent" },
        { MONO_MT_BLOB_IDX,   "PermissionSet" },
        { MONO_MT_END, NULL }   
 };
 
-static MonoMetaTable EventMapSchema [] = {
+const static MonoMetaTable EventMapSchema [] = {
        { MONO_MT_TABLE_IDX,  "Parent:TypeDef" },
        { MONO_MT_TABLE_IDX,  "EventList:Event" },
        { MONO_MT_END, NULL }   
 };
 
-static MonoMetaTable EventSchema [] = {
+const static MonoMetaTable EventSchema [] = {
        { MONO_MT_UINT16,     "EventFlags#EventAttribute" },
        { MONO_MT_STRING_IDX, "Name" },
        { MONO_MT_TABLE_IDX,  "EventType" }, /* TypeDef or TypeRef */
        { MONO_MT_END, NULL }   
 };
 
-static MonoMetaTable ExportedTypeSchema [] = {
+const static MonoMetaTable ExportedTypeSchema [] = {
        { MONO_MT_UINT32,     "Flags" },
        { MONO_MT_TABLE_IDX,  "TypeDefId" },
        { MONO_MT_STRING_IDX, "TypeName" },
@@ -137,37 +138,37 @@ static MonoMetaTable ExportedTypeSchema [] = {
        { MONO_MT_END, NULL }   
 };
 
-static MonoMetaTable FieldSchema [] = {
+const static MonoMetaTable FieldSchema [] = {
        { MONO_MT_UINT16,     "Flags" },
        { MONO_MT_STRING_IDX, "Name" },
        { MONO_MT_BLOB_IDX,   "Signature" },
        { MONO_MT_END, NULL }   
 };
-static MonoMetaTable FieldLayoutSchema [] = {
+const static MonoMetaTable FieldLayoutSchema [] = {
        { MONO_MT_UINT32,     "Offset" },
        { MONO_MT_TABLE_IDX,  "Field:Field" },
        { MONO_MT_END, NULL }   
 };
 
-static MonoMetaTable FieldMarshalSchema [] = {
+const static MonoMetaTable FieldMarshalSchema [] = {
        { MONO_MT_HFM_IDX,    "Parent" },
        { MONO_MT_BLOB_IDX,   "NativeType" },
        { MONO_MT_END, NULL }   
 };
-static MonoMetaTable FieldRVASchema [] = {
+const static MonoMetaTable FieldRVASchema [] = {
        { MONO_MT_UINT32,     "RVA" },
        { MONO_MT_TABLE_IDX,  "Field:Field" },
        { MONO_MT_END, NULL }   
 };
 
-static MonoMetaTable FileSchema [] = {
+const static MonoMetaTable FileSchema [] = {
        { MONO_MT_UINT32,     "Flags" },
        { MONO_MT_STRING_IDX, "Name" },
        { MONO_MT_BLOB_IDX,   "Value" }, 
        { MONO_MT_END, NULL }
 };
 
-static MonoMetaTable ImplMapSchema [] = {
+const static MonoMetaTable ImplMapSchema [] = {
        { MONO_MT_UINT16,     "MappingFlag" },
        { MONO_MT_MF_IDX,     "MemberForwarded" },
        { MONO_MT_STRING_IDX, "ImportName" },
@@ -175,13 +176,13 @@ static MonoMetaTable ImplMapSchema [] = {
        { MONO_MT_END, NULL }
 };
 
-static MonoMetaTable InterfaceImplSchema [] = {
+const static MonoMetaTable InterfaceImplSchema [] = {
        { MONO_MT_TABLE_IDX,  "Class:TypeDef" }, 
        { MONO_MT_TDOR_IDX,  "Interface=TypeDefOrRef" },
        { MONO_MT_END, NULL }
 };
 
-static MonoMetaTable ManifestResourceSchema [] = {
+const static MonoMetaTable ManifestResourceSchema [] = {
        { MONO_MT_UINT32,     "Offset" },
        { MONO_MT_UINT32,     "Flags" },
        { MONO_MT_STRING_IDX, "Name" },
@@ -189,14 +190,14 @@ static MonoMetaTable ManifestResourceSchema [] = {
        { MONO_MT_END, NULL }
 };
 
-static MonoMetaTable MemberRefSchema [] = {
+const static MonoMetaTable MemberRefSchema [] = {
        { MONO_MT_MRP_IDX,    "Class" },
        { MONO_MT_STRING_IDX, "Name" },
        { MONO_MT_BLOB_IDX,   "Signature" },
        { MONO_MT_END, NULL }
 };
 
-static MonoMetaTable MethodSchema [] = {
+const static MonoMetaTable MethodSchema [] = {
        { MONO_MT_UINT32,     "RVA" },
        { MONO_MT_UINT16,     "ImplFlags#MethodImplAttributes" },
        { MONO_MT_UINT16,     "Flags#MethodAttribute" },
@@ -206,21 +207,21 @@ static MonoMetaTable MethodSchema [] = {
        { MONO_MT_END, NULL }
 };
 
-static MonoMetaTable MethodImplSchema [] = {
+const static MonoMetaTable MethodImplSchema [] = {
        { MONO_MT_TABLE_IDX,  "Class:TypeDef" },
        { MONO_MT_MDOR_IDX,   "MethodBody" },
        { MONO_MT_MDOR_IDX,   "MethodDeclaration" },
        { MONO_MT_END, NULL }
 };
 
-static MonoMetaTable MethodSemanticsSchema [] = {
+const static MonoMetaTable MethodSemanticsSchema [] = {
        { MONO_MT_UINT16,     "MethodSemantic" },
        { MONO_MT_TABLE_IDX,  "Method:Method" },
        { MONO_MT_HS_IDX,     "Association" },
        { MONO_MT_END, NULL }
 };
 
-static MonoMetaTable ModuleSchema [] = {
+const static MonoMetaTable ModuleSchema [] = {
        { MONO_MT_UINT16,     "Generation" },
        { MONO_MT_STRING_IDX, "Name" },
        { MONO_MT_GUID_IDX,   "MVID" },
@@ -229,43 +230,43 @@ static MonoMetaTable ModuleSchema [] = {
        { MONO_MT_END, NULL }
 };
 
-static MonoMetaTable ModuleRefSchema [] = {
+const static MonoMetaTable ModuleRefSchema [] = {
        { MONO_MT_STRING_IDX, "Name" },
        { MONO_MT_END, NULL }
 };
 
-static MonoMetaTable NestedClassSchema [] = {
+const static MonoMetaTable NestedClassSchema [] = {
        { MONO_MT_TABLE_IDX,  "NestedClass:TypeDef" },
        { MONO_MT_TABLE_IDX,  "EnclosingClass:TypeDef" },
        { MONO_MT_END, NULL }
 };
 
-static MonoMetaTable ParamSchema [] = {
+const static MonoMetaTable ParamSchema [] = {
        { MONO_MT_UINT16,     "Flags" },
        { MONO_MT_UINT16,     "Sequence" },
        { MONO_MT_STRING_IDX, "Name" },
        { MONO_MT_END, NULL }   
 };
 
-static MonoMetaTable PropertySchema [] = {
+const static MonoMetaTable PropertySchema [] = {
        { MONO_MT_UINT16,     "Flags" },
        { MONO_MT_STRING_IDX, "Name" },
        { MONO_MT_BLOB_IDX,   "Type" },
        { MONO_MT_END, NULL }   
 };
 
-static MonoMetaTable PropertyMapSchema [] = {
+const static MonoMetaTable PropertyMapSchema [] = {
        { MONO_MT_TABLE_IDX,  "Parent:TypeDef" },
        { MONO_MT_TABLE_IDX,  "PropertyList:Property" },
        { MONO_MT_END, NULL }
 };
 
-static MonoMetaTable StandaloneSigSchema [] = {
+const static MonoMetaTable StandaloneSigSchema [] = {
        { MONO_MT_BLOB_IDX,   "Signature" },
        { MONO_MT_END, NULL }
 };
 
-static MonoMetaTable TypeDefSchema [] = {
+const static MonoMetaTable TypeDefSchema [] = {
        { MONO_MT_UINT32,     "Flags" },
        { MONO_MT_STRING_IDX, "Name" },
        { MONO_MT_STRING_IDX, "Namespace" },
@@ -275,20 +276,45 @@ static MonoMetaTable TypeDefSchema [] = {
        { MONO_MT_END, NULL }
 };
 
-static MonoMetaTable TypeRefSchema [] = {
+const static MonoMetaTable TypeRefSchema [] = {
        { MONO_MT_RS_IDX,     "ResolutionScope=ResolutionScope" },
        { MONO_MT_STRING_IDX, "Name" },
        { MONO_MT_STRING_IDX, "Namespace" },
        { MONO_MT_END, NULL }
 };
 
-static MonoMetaTable TypeSpecSchema [] = {
+const static MonoMetaTable TypeSpecSchema [] = {
        { MONO_MT_BLOB_IDX,   "Signature" },
        { MONO_MT_END, NULL }
 };
 
-static struct {
-       MonoMetaTable *table;
+const static MonoMetaTable GenericParamSchema [] = {
+       { MONO_MT_UINT16,     "Number" },
+       { MONO_MT_UINT16,     "Flags" },
+       { MONO_MT_TABLE_IDX,  "Owner" }, /* TypeDef or MethodDef */
+       { MONO_MT_STRING_IDX, "Name" },
+
+       /* soon to be removed */
+       { MONO_MT_TABLE_IDX,  "Kind" }, 
+       { MONO_MT_TABLE_IDX,  "DeprecatedConstraint" },
+       
+       { MONO_MT_END, NULL }
+};
+
+const static MonoMetaTable MethodSpecSchema [] = {
+       { MONO_MT_MDOR_IDX,   "Method" },
+       { MONO_MT_BLOB_IDX,   "Signature" },
+       { MONO_MT_END, NULL }
+};
+
+const static MonoMetaTable GenericParamConstraintSchema [] = {
+       { MONO_MT_TABLE_IDX,  "GenericParam" },
+       { MONO_MT_TDOR_IDX,   "Constraint" },
+       { MONO_MT_END, NULL }
+};
+
+const static struct {
+       const MonoMetaTable *table;
        const char    *name;
 } tables [] = {
        /*  0 */ { ModuleSchema,               "Module" },
@@ -333,8 +359,9 @@ static struct {
        /* 27 */ { ExportedTypeSchema,         "ExportedType" },
        /* 28 */ { ManifestResourceSchema,     "ManifestResource" },
        /* 29 */ { NestedClassSchema,          "NestedClass" },
-       /* 2A */ { NULL,                       NULL },
-       /* 2B */ { NULL,                       NULL },
+       /* 2A */ { GenericParamSchema,         "GenericParam" },
+       /* 2B */ { MethodSpecSchema,           "MethodSpec" },
+       /* 2C */ { GenericParamConstraintSchema, "GenericParamConstraint" },
 };
 
 /**
@@ -346,7 +373,7 @@ static struct {
 const char *
 mono_meta_table_name (int table)
 {
-       if ((table < 0) || (table > 0x29))
+       if ((table < 0) || (table > 0x2c))
                return "";
        
        return tables [table].name;
@@ -366,6 +393,18 @@ inverse of this mapping.
 #define idx_size(tableidx) (meta->tables [(tableidx)].rows < 65536 ? 2 : 4)
 
 /* Reference: Partition II - 23.2.6 */
+/*
+ * mono_metadata_compute_size:
+ * @meta: metadata context
+ * @tableindex: metadata table number
+ * @result_bitfield: pointer to guint32 where to store additional info
+ * 
+ * mono_metadata_compute_size() computes the lenght in bytes of a single
+ * row in a metadata table. The size of each column is encoded in the
+ * @result_bitfield return value along with the number of columns in the table.
+ * the resulting bitfield should be handed to the mono_metadata_table_size()
+ * and mono_metadata_table_count() macros.
+ */
 int
 mono_metadata_compute_size (MonoImage *meta, int tableindex, guint32 *result_bitfield)
 {
@@ -373,7 +412,7 @@ mono_metadata_compute_size (MonoImage *meta, int tableindex, guint32 *result_bit
        int size = 0, field_size;
        int i, n, code;
        int shift = 0;
-       MonoMetaTable *table = tables [tableindex].table;
+       const MonoMetaTable *table = tables [tableindex].table;
 
        for (i = 0; (code = table [i].code) != MONO_MT_END; i++){
                switch (code){
@@ -422,7 +461,8 @@ mono_metadata_compute_size (MonoImage *meta, int tableindex, guint32 *result_bit
                                break;
                        case MONO_TABLE_EXPORTEDTYPE:
                                g_assert (i == 1);
-                               field_size = idx_size (MONO_TABLE_TYPEDEF); break;
+                               /* the index is in another metadata file, so it must be 4 */
+                               field_size = 4; break;
                        case MONO_TABLE_FIELDLAYOUT:
                                g_assert (i == 1);
                                field_size = idx_size (MONO_TABLE_FIELD); break;
@@ -455,12 +495,26 @@ mono_metadata_compute_size (MonoImage *meta, int tableindex, guint32 *result_bit
                        case MONO_TABLE_TYPEDEF:
                                g_assert (i == 4 || i == 5);
                                field_size = i == 4 ? idx_size (MONO_TABLE_FIELD):
-                                       idx_size(MONO_TABLE_METHOD); 
+                                       idx_size(MONO_TABLE_METHOD);
+                       case MONO_TABLE_GENERICPARAM:
+                               g_assert (i == 2 || i == 4 || i == 5);
+                               if (i == 2)
+                                       field_size = MAX (idx_size (MONO_TABLE_METHOD), idx_size (MONO_TABLE_TYPEDEF));
+                               else if (i == 4)
+                                       field_size = idx_size (MONO_TABLE_TYPEDEF);
+                               else if (i == 5)
+                                       field_size = idx_size (MONO_TABLE_TYPEDEF);
+                               break;
+
+                       case MONO_TABLE_GENERICPARAMCONSTRAINT:
+                               g_assert (i == 0);
+                               field_size = idx_size (MONO_TABLE_GENERICPARAM);
                                break;
+                               
                        default:
                                g_assert_not_reached ();
                        }
-                       if (field_size != idx_size (tableindex))
+                       if (tableindex != MONO_TABLE_EXPORTEDTYPE && field_size != idx_size (tableindex))
                                g_warning ("size changed (%d to %d)", idx_size (tableindex), field_size);
                        
                        break;
@@ -669,7 +723,7 @@ void
 mono_metadata_compute_table_bases (MonoImage *meta)
 {
        int i;
-       char *base = meta->tables_base;
+       const char *base = meta->tables_base;
        
        for (i = 0; i < 64; i++){
                if (meta->tables [i].rows == 0)
@@ -691,7 +745,7 @@ mono_metadata_compute_table_bases (MonoImage *meta)
  * Returns a pointer to the @idx element in the metadata table
  * whose code is @table.
  */
-char *
+const char *
 mono_metadata_locate (MonoImage *meta, int table, int idx)
 {
        /* idx == 0 refers always to NULL */
@@ -700,7 +754,15 @@ mono_metadata_locate (MonoImage *meta, int table, int idx)
        return meta->tables [table].base + (meta->tables [table].row_size * (idx - 1));
 }
 
-char *
+/**
+ * mono_metadata_locate_token:
+ * @meta: metadata context
+ * @token: metadata token
+ *
+ * Returns a pointer to the data in the metadata represented by the
+ * token #token.
+ */
+const char *
 mono_metadata_locate_token (MonoImage *meta, guint32 token)
 {
        return mono_metadata_locate (meta, token >> 24, token & 0xffffff);
@@ -712,7 +774,7 @@ mono_metadata_locate_token (MonoImage *meta, guint32 token)
  *
  * Returns the MonoMetaTable structure for table @table
  */
-MonoMetaTable *
+const MonoMetaTable *
 mono_metadata_get_table (MonoMetaTableEnum table)
 {
        int x = (int) table;
@@ -736,6 +798,13 @@ mono_metadata_string_heap (MonoImage *meta, guint32 index)
        return meta->heap_strings.data + index;
 }
 
+/**
+ * mono_metadata_user_string:
+ * @meta: metadata context
+ * @index: index into the user string heap.
+ *
+ * Returns: an in-memory pointer to the @index in the user string heap ("#US").
+ */
 const char *
 mono_metadata_user_string (MonoImage *meta, guint32 index)
 {
@@ -757,10 +826,30 @@ mono_metadata_blob_heap (MonoImage *meta, guint32 index)
        return meta->heap_blob.data + index;
 }
 
+/**
+ * mono_metadata_guid_heap:
+ * @meta: metadata context
+ * @index: index into the guid heap.
+ *
+ * Returns: an in-memory pointer to the @index in the guid heap.
+ */
+const char *
+mono_metadata_guid_heap (MonoImage *meta, guint32 index)
+{
+       --index;
+       index *= 16; /* adjust for guid size and 1-based index */
+       g_return_val_if_fail (index < meta->heap_guid.size, "");
+       return meta->heap_guid.data + index;
+}
+
 static const char *
 dword_align (const char *ptr)
 {
+#if SIZEOF_VOID_P == 8
+       return (const char *) (((guint64) (ptr + 3)) & ~3);
+#else
        return (const char *) (((guint32) (ptr + 3)) & ~3);
+#endif
 }
 
 /**
@@ -777,7 +866,7 @@ mono_metadata_decode_row (MonoTableInfo *t, int idx, guint32 *res, int res_size)
 {
        guint32 bitfield = t->size_bitfield;
        int i, count = mono_metadata_table_count (bitfield);
-       char *data = t->base + idx * t->row_size;
+       const char *data = t->base + idx * t->row_size;
        
        g_assert (res_size == count);
        
@@ -814,7 +903,7 @@ mono_metadata_decode_row_col (MonoTableInfo *t, int idx, guint col)
 {
        guint32 bitfield = t->size_bitfield;
        int i;
-       register char *data = t->base + idx * t->row_size;
+       register const char *data = t->base + idx * t->row_size;
        register int n;
        
        g_assert (col < mono_metadata_table_count (bitfield));
@@ -883,7 +972,7 @@ mono_metadata_decode_blob_size (const char *xptr, const char **rptr)
 guint32
 mono_metadata_decode_value (const char *_ptr, const char **rptr)
 {
-       const unsigned char *ptr = (unsigned char *) _ptr;
+       const unsigned char *ptr = (const unsigned char *) _ptr;
        unsigned char b = *ptr;
        guint32 len;
        
@@ -906,6 +995,15 @@ mono_metadata_decode_value (const char *_ptr, const char **rptr)
        return len;
 }
 
+/*
+ * mono_metadata_parse_typedef_or_ref:
+ * @m: a metadata context.
+ * @ptr: a pointer to an encoded TypedefOrRef in @m
+ * @rptr: pointer updated to match the end of the decoded stream
+ *
+ * Returns: a token valid in the @m metadata decoded from
+ * the compressed representation.
+ */
 guint32
 mono_metadata_parse_typedef_or_ref (MonoImage *m, const char *ptr, const char **rptr)
 {
@@ -916,6 +1014,17 @@ mono_metadata_parse_typedef_or_ref (MonoImage *m, const char *ptr, const char **
        return mono_metadata_token_from_dor (token);
 }
 
+/*
+ * mono_metadata_parse_custom_mod:
+ * @m: a metadata context.
+ * @dest: storage where the info about the custom modifier is stored (may be NULL)
+ * @ptr: a pointer to (possibly) the start of a custom modifier list
+ * @rptr: pointer updated to match the end of the decoded stream
+ *
+ * Checks if @ptr points to a type custom modifier compressed representation.
+ *
+ * Returns: #TRUE if a custom modifier was found, #FALSE if not.
+ */
 int
 mono_metadata_parse_custom_mod (MonoImage *m, MonoCustomMod *dest, const char *ptr, const char **rptr)
 {
@@ -925,19 +1034,32 @@ mono_metadata_parse_custom_mod (MonoImage *m, MonoCustomMod *dest, const char *p
                if (!dest)
                        dest = &local;
                dest->required = *ptr == MONO_TYPE_CMOD_REQD ? 1 : 0;
-               dest->token = mono_metadata_parse_typedef_or_ref (m, ptr + 1, &ptr);
+               dest->token = mono_metadata_parse_typedef_or_ref (m, ptr + 1, rptr);
                return TRUE;
        }
        return FALSE;
 }
 
+/*
+ * mono_metadata_parse_array:
+ * @m: a metadata context.
+ * @ptr: a pointer to an encoded array description.
+ * @rptr: pointer updated to match the end of the decoded stream
+ *
+ * Decodes the compressed array description found in the metadata @m at @ptr.
+ *
+ * Returns: a #MonoArrayType structure describing the array type
+ * and dimensions.
+ */
 MonoArrayType *
 mono_metadata_parse_array (MonoImage *m, const char *ptr, const char **rptr)
 {
        int i;
        MonoArrayType *array = g_new0 (MonoArrayType, 1);
+       MonoType *etype;
        
-       array->type = mono_metadata_parse_type (m, MONO_PARSE_TYPE, 0, ptr, &ptr);
+       etype = mono_metadata_parse_type (m, MONO_PARSE_TYPE, 0, ptr, &ptr);
+       array->eklass = mono_class_from_mono_type (etype);
        array->rank = mono_metadata_decode_value (ptr, &ptr);
 
        array->numsizes = mono_metadata_decode_value (ptr, &ptr);
@@ -957,10 +1079,15 @@ mono_metadata_parse_array (MonoImage *m, const char *ptr, const char **rptr)
        return array;
 }
 
+/*
+ * mono_metadata_free_array:
+ * @array: array description
+ *
+ * Frees the array description returned from mono_metadata_parse_array().
+ */
 void
 mono_metadata_free_array (MonoArrayType *array)
 {
-       mono_metadata_free_type (array->type);
        g_free (array->sizes);
        g_free (array->lobounds);
        g_free (array);
@@ -1010,8 +1137,6 @@ builtin_types[] = {
        {{NULL}, 0,     MONO_TYPE_I,       0,     1,     0},
        {{NULL}, 0,     MONO_TYPE_U,       0,     0,     0},
        {{NULL}, 0,     MONO_TYPE_U,       0,     1,     0},
-       {{NULL}, 0,     MONO_TYPE_OBJECT,  0,     0,     0},
-       {{NULL}, 0,     MONO_TYPE_OBJECT,  0,     1,     0}
 };
 
 #define NBUILTIN_TYPES() (sizeof (builtin_types) / sizeof (builtin_types [0]))
@@ -1024,15 +1149,15 @@ static GHashTable *type_cache = NULL;
 static guint
 mono_type_hash (gconstpointer data)
 {
-       MonoType *type = (MonoType *) data;
+       const MonoType *type = (const MonoType *) data;
        return type->type | (type->byref << 8) | (type->attrs << 9);
 }
 
 static gint
 mono_type_equal (gconstpointer ka, gconstpointer kb)
 {
-       MonoType *a = (MonoType *) ka;
-       MonoType *b = (MonoType *) kb;
+       const MonoType *a = (const MonoType *) ka;
+       const MonoType *b = (const MonoType *) kb;
        
        if (a->type != b->type || a->byref != b->byref || a->attrs != b->attrs || a->pinned != b->pinned)
                return 0;
@@ -1040,23 +1165,48 @@ mono_type_equal (gconstpointer ka, gconstpointer kb)
        return 1;
 }
 
+/**
+ * mono_metadata_init:
+ *
+ *  Initialize the global variables of this module.
+ */
+void
+mono_metadata_init (void)
+{
+       int i;
+
+       type_cache = g_hash_table_new (mono_type_hash, mono_type_equal);
+
+       for (i = 0; i < NBUILTIN_TYPES (); ++i)
+               g_hash_table_insert (type_cache, &builtin_types [i], &builtin_types [i]);
+}
+
+/*
+ * mono_metadata_parse_type:
+ * @m: metadata context
+ * @mode: king of type that may be found at @ptr
+ * @opt_attrs: optional attributes to store in the returned type
+ * @ptr: pointer to the type representation
+ * @rptr: pointer updated to match the end of the decoded stream
+ * 
+ * Decode a compressed type description found at @ptr in @m.
+ * @mode can be one of MONO_PARSE_MOD_TYPE, MONO_PARSE_PARAM, MONO_PARSE_RET,
+ * MONO_PARSE_FIELD, MONO_PARSE_LOCAL, MONO_PARSE_TYPE.
+ * This function can be used to decode type descriptions in method signatures,
+ * field signatures, locals signatures etc.
+ *
+ * Returns: a #MonoType structure representing the decoded type.
+ */
 MonoType*
 mono_metadata_parse_type (MonoImage *m, MonoParseTypeMode mode, short opt_attrs, const char *ptr, const char **rptr)
 {
        MonoType *type, *cached;
 
-       if (!type_cache) {
-               int i;
-               type_cache = g_hash_table_new (mono_type_hash, mono_type_equal);
-
-               for (i = 0; i < NBUILTIN_TYPES (); ++i)
-                       g_hash_table_insert (type_cache, &builtin_types [i], &builtin_types [i]);
-       }
-
        switch (mode) {
        case MONO_PARSE_MOD_TYPE:
        case MONO_PARSE_PARAM:
        case MONO_PARSE_RET:
+       case MONO_PARSE_LOCAL: /* should not have modifiers according to the spec, but ms tools disagree */
        case MONO_PARSE_FIELD: {
                /* count the modifiers */
                const char *tmp_ptr = ptr;
@@ -1064,7 +1214,7 @@ mono_metadata_parse_type (MonoImage *m, MonoParseTypeMode mode, short opt_attrs,
                while (mono_metadata_parse_custom_mod (m, NULL, tmp_ptr, &tmp_ptr))
                        count++;
                if (count) {
-                       type = g_malloc0 (sizeof (MonoType) + (count - MONO_ZERO_LEN_ARRAY) * sizeof (MonoCustomMod));
+                       type = g_malloc0 (sizeof (MonoType) + ((gint32)count - MONO_ZERO_LEN_ARRAY) * sizeof (MonoCustomMod));
                        type->num_mods = count;
                        if (count > 64)
                                g_warning ("got more than 64 modifiers in type");
@@ -1075,7 +1225,6 @@ mono_metadata_parse_type (MonoImage *m, MonoParseTypeMode mode, short opt_attrs,
                        break;
                } /* fall through */
        }
-       case MONO_PARSE_LOCAL:
        case MONO_PARSE_TYPE:
                /*
                 * Later we can avoid doing this allocation.
@@ -1112,6 +1261,8 @@ mono_metadata_parse_type (MonoImage *m, MonoParseTypeMode mode, short opt_attrs,
        }
        if (rptr)
                *rptr = ptr;
+
+       /* No need to use locking since nobody is modifying the hash table */
        if (mode != MONO_PARSE_PARAM && !type->num_mods && (cached = g_hash_table_lookup (type_cache, type))) {
                mono_metadata_free_type (type);
                return cached;
@@ -1120,27 +1271,105 @@ mono_metadata_parse_type (MonoImage *m, MonoParseTypeMode mode, short opt_attrs,
        }
 }
 
+/*
+ * mono_metadata_parse_signature:
+ * @image: metadata context
+ * @toke: metadata token
+ *
+ * Decode a method signature stored in the STANDALONESIG table
+ *
+ * Returns: a MonoMethodSignature describing the signature.
+ */
+MonoMethodSignature *
+mono_metadata_parse_signature (MonoImage *image, guint32 token)
+{
+       MonoTableInfo *tables = image->tables;
+       guint32 idx = mono_metadata_token_index (token);
+       guint32 sig;
+       const char *ptr;
+
+       if (image->assembly->dynamic)
+               return mono_lookup_dynamic_token (image, token);
+
+       g_assert (mono_metadata_token_table(token) == MONO_TABLE_STANDALONESIG);
+               
+       sig = mono_metadata_decode_row_col (&tables [MONO_TABLE_STANDALONESIG], idx - 1, 0);
+
+       ptr = mono_metadata_blob_heap (image, sig);
+       mono_metadata_decode_blob_size (ptr, &ptr);
+
+       return mono_metadata_parse_method_signature (image, FALSE, ptr, NULL); 
+}
+
+MonoMethodSignature*
+mono_metadata_signature_alloc (MonoImage *m, guint32 nparams)
+{
+       MonoMethodSignature *sig;
+
+       /* later we want to allocate signatures with mempools */
+       sig = g_malloc0 (sizeof (MonoMethodSignature) + ((gint32)nparams - MONO_ZERO_LEN_ARRAY) * sizeof (MonoType*));
+       sig->param_count = nparams;
+
+       return sig;
+}
+
+/*
+ * mono_metadata_parse_method_signature:
+ * @m: metadata context
+ * @def: the MethodDef index or 0 for Ref signatures.
+ * @ptr: pointer to the signature metadata representation
+ * @rptr: pointer updated to match the end of the decoded stream
+ *
+ * Decode a method signature stored at @ptr.
+ *
+ * Returns: a MonoMethodSignature describing the signature.
+ */
 MonoMethodSignature *
 mono_metadata_parse_method_signature (MonoImage *m, int def, const char *ptr, const char **rptr)
 {
        MonoMethodSignature *method;
-       int i;
+       int i, ret_attrs = 0, *pattrs = NULL;
        guint32 hasthis = 0, explicit_this = 0, call_convention, param_count;
+       guint32 gen_param_count = 0;
 
+       if (*ptr & 0x10)
+               gen_param_count = 1;
        if (*ptr & 0x20)
                hasthis = 1;
        if (*ptr & 0x40)
                explicit_this = 1;
        call_convention = *ptr & 0x0F;
        ptr++;
+       if (gen_param_count)
+               gen_param_count = mono_metadata_decode_value (ptr, &ptr);
        param_count = mono_metadata_decode_value (ptr, &ptr);
+       pattrs = g_new0 (int, param_count);
 
-       method = g_malloc0 (sizeof (MonoMethodSignature) + (param_count - MONO_ZERO_LEN_ARRAY) * sizeof (MonoType*));
-       method->param_count = param_count;
+       if (def) {
+               MonoTableInfo *paramt = &m->tables [MONO_TABLE_PARAM];
+               MonoTableInfo *methodt = &m->tables [MONO_TABLE_METHOD];
+               guint32 cols [MONO_PARAM_SIZE];
+               guint lastp, param_index = mono_metadata_decode_row_col (methodt, def - 1, MONO_METHOD_PARAMLIST);
+
+               if (def < methodt->rows)
+                       lastp = mono_metadata_decode_row_col (methodt, def, MONO_METHOD_PARAMLIST);
+               else
+                       lastp = paramt->rows + 1;
+               for (i = param_index; i < lastp; ++i) {
+                       mono_metadata_decode_row (paramt, i - 1, cols, MONO_PARAM_SIZE);
+                       if (!cols [MONO_PARAM_SEQUENCE])
+                               ret_attrs = cols [MONO_PARAM_FLAGS];
+                       else
+                               pattrs [cols [MONO_PARAM_SEQUENCE] - 1] = cols [MONO_PARAM_FLAGS];
+               }
+       }
+       method = mono_metadata_signature_alloc (m, param_count);
        method->hasthis = hasthis;
        method->explicit_this = explicit_this;
        method->call_convention = call_convention;
-       method->ret = mono_metadata_parse_type (m, MONO_PARSE_RET, 0, ptr, &ptr);
+       method->generic_param_count = gen_param_count;
+       if (call_convention != 0xa)
+               method->ret = mono_metadata_parse_type (m, MONO_PARSE_RET, ret_attrs, ptr, &ptr);
 
        if (method->param_count) {
                method->sentinelpos = -1;
@@ -1152,7 +1381,29 @@ mono_metadata_parse_method_signature (MonoImage *m, int def, const char *ptr, co
                                method->sentinelpos = i;
                                ptr++;
                        }
-                       method->params [i] = mono_metadata_parse_type (m, MONO_PARSE_PARAM, 0, ptr, &ptr);
+                       method->params [i] = mono_metadata_parse_type (m, MONO_PARSE_PARAM, pattrs [i], ptr, &ptr);
+               }
+       }
+       g_free (pattrs);
+
+       if (method->generic_param_count) {
+               guint32 token;
+
+               g_assert (def);
+               token = mono_metadata_make_token (MONO_TABLE_METHOD, def);
+               method->gen_params = mono_metadata_load_generic_params (m, token, NULL, method);
+
+               for (i = 0; i < method->param_count; i++) {
+                       MonoGenericParam *param;
+                       guint32 index;
+
+                       if (method->params [i]->type != MONO_TYPE_MVAR)
+                               continue;
+
+                       index = method->params [i]->data.generic_param->num;
+                       method->params [i]->data.generic_param = param = &method->gen_params [index];
+
+                       mono_class_from_generic_parameter (param, m, TRUE);
                }
        }
 
@@ -1164,15 +1415,53 @@ mono_metadata_parse_method_signature (MonoImage *m, int def, const char *ptr, co
        return method;
 }
 
+/*
+ * mono_metadata_free_method_signature:
+ * @sig: signature to destroy
+ *
+ * Free the memory allocated in the signature @sig.
+ */
 void
-mono_metadata_free_method_signature (MonoMethodSignature *method)
+mono_metadata_free_method_signature (MonoMethodSignature *sig)
 {
        int i;
-       mono_metadata_free_type (method->ret);
-       for (i = 0; i < method->param_count; ++i)
-               mono_metadata_free_type (method->params [i]);
+       mono_metadata_free_type (sig->ret);
+       for (i = 0; i < sig->param_count; ++i)
+               mono_metadata_free_type (sig->params [i]);
 
-       g_free (method);
+       g_free (sig);
+}
+
+static MonoGenericInst *
+mono_metadata_parse_generic_inst (MonoImage *m, const char *ptr, const char **rptr)
+{
+       MonoGenericInst *generic_inst = g_new0 (MonoGenericInst, 1);
+       int i, count;
+       
+       generic_inst->generic_type = mono_metadata_parse_type (m, MONO_PARSE_TYPE, 0, ptr, &ptr);
+       generic_inst->type_argc = count = mono_metadata_decode_value (ptr, &ptr);
+       generic_inst->type_argv = g_new0 (MonoType*, count);
+
+       for (i = 0; i < generic_inst->type_argc; i++)
+               generic_inst->type_argv [i] = mono_metadata_parse_type (m, MONO_PARSE_TYPE, 0, ptr, &ptr);
+       
+       if (rptr)
+               *rptr = ptr;
+
+       return generic_inst;
+}
+
+static MonoGenericParam *
+mono_metadata_parse_generic_param (MonoImage *m, const char *ptr, const char **rptr)
+{
+       MonoGenericParam *generic_param = g_new0 (MonoGenericParam, 1);
+       
+       generic_param->num = mono_metadata_decode_value (ptr, &ptr);
+
+       if (rptr)
+               *rptr = ptr;
+
+       return generic_param;
 }
 
 /* 
@@ -1221,7 +1510,11 @@ do_mono_metadata_parse_type (MonoType *type, MonoImage *m, const char *ptr, cons
                type->data.klass = mono_class_get (m, token);
                break;
        }
-       case MONO_TYPE_SZARRAY:
+       case MONO_TYPE_SZARRAY: {
+               MonoType *etype = mono_metadata_parse_type (m, MONO_PARSE_MOD_TYPE, 0, ptr, &ptr);
+               type->data.klass = mono_class_from_mono_type (etype);
+               break;
+       }
        case MONO_TYPE_PTR:
                type->data.type = mono_metadata_parse_type (m, MONO_PARSE_MOD_TYPE, 0, ptr, &ptr);
                break;
@@ -1231,43 +1524,36 @@ do_mono_metadata_parse_type (MonoType *type, MonoImage *m, const char *ptr, cons
        case MONO_TYPE_ARRAY:
                type->data.array = mono_metadata_parse_array (m, ptr, &ptr);
                break;
+
+       case MONO_TYPE_MVAR:
+       case MONO_TYPE_VAR:
+               type->data.generic_param = mono_metadata_parse_generic_param (m, ptr, &ptr);
+               break;
+
+       case MONO_TYPE_GENERICINST:
+               type->data.generic_inst = mono_metadata_parse_generic_inst (m, ptr, &ptr);
+               break;
+               
        default:
-               g_error ("type 0x%02x not handled in mono_metadata_parse_type", type->type);
+               g_error ("type 0x%02x not handled in do_mono_metadata_parse_type", type->type);
        }
        
        if (rptr)
                *rptr = ptr;
 }
 
-#if 0
-/**
- * mono_metadata_parse_type:
- * @m: metadata context to scan
- * @ptr: pointer to encoded Type stream.
- * @rptr: the new position in the stream after parsing the type
+/*
+ * mono_metadata_free_type:
+ * @type: type to free
  *
- * Returns: A MonoType structure that has the parsed information
- * from the type stored at @ptr in the metadata table @m.
+ * Free the memory allocated for type @type.
  */
-MonoType *
-mono_metadata_parse_type (MonoImage *m, const char *ptr, const char **rptr)
-{
-       /* should probably be allocated in a memchunk */
-       MonoType *type = g_new0(MonoType, 1);
-
-       do_mono_metadata_parse_type (type, m, ptr, rptr);
-
-       return type;
-}
-#endif
-
 void
 mono_metadata_free_type (MonoType *type)
 {
        if (type >= builtin_types && type < builtin_types + NBUILTIN_TYPES ())
                return;
        switch (type->type){
-       case MONO_TYPE_SZARRAY:
        case MONO_TYPE_PTR:
                mono_metadata_free_type (type->data.type);
                break;
@@ -1281,6 +1567,7 @@ mono_metadata_free_type (MonoType *type)
        g_free (type);
 }
 
+#if 0
 static void
 hex_dump (const char *buffer, int base, int count)
 {
@@ -1301,6 +1588,7 @@ hex_dump (const char *buffer, int base, int count)
        }
        fflush (stdout);
 }
+#endif
 
 /** 
  * @mh: The Method header
@@ -1385,11 +1673,21 @@ parse_section_data (MonoMethodHeader *mh, const unsigned char *ptr)
        }
 }
 
+/*
+ * mono_metadata_parse_mh:
+ * @m: metadata context
+ * @ptr: pointer to the method header.
+ *
+ * Decode the method header at @ptr, including pointer to the IL code,
+ * info about local variables and optional exception tables.
+ *
+ * Returns: a MonoMethodHeader.
+ */
 MonoMethodHeader *
 mono_metadata_parse_mh (MonoImage *m, const char *ptr)
 {
        MonoMethodHeader *mh;
-       unsigned char flags = *(unsigned char *) ptr;
+       unsigned char flags = *(const unsigned char *) ptr;
        unsigned char format = flags & METHOD_HEADER_FORMAT_MASK;
        guint16 fat_flags;
        guint32 local_var_sig_tok, max_stack, code_size, init_locals;
@@ -1454,21 +1752,21 @@ mono_metadata_parse_mh (MonoImage *m, const char *ptr)
                       
        if (local_var_sig_tok) {
                MonoTableInfo *t = &m->tables [MONO_TABLE_STANDALONESIG];
-               const char *ptr;
+               const char *locals_ptr;
                guint32 cols [MONO_STAND_ALONE_SIGNATURE_SIZE];
                int len=0, i, bsize;
 
                mono_metadata_decode_row (t, (local_var_sig_tok & 0xffffff)-1, cols, 1);
-               ptr = mono_metadata_blob_heap (m, cols [MONO_STAND_ALONE_SIGNATURE]);
-               bsize = mono_metadata_decode_blob_size (ptr, &ptr);
-               if (*ptr != 0x07)
+               locals_ptr = mono_metadata_blob_heap (m, cols [MONO_STAND_ALONE_SIGNATURE]);
+               bsize = mono_metadata_decode_blob_size (locals_ptr, &locals_ptr);
+               if (*locals_ptr != 0x07)
                        g_warning ("wrong signature for locals blob");
-               ptr++;
-               len = mono_metadata_decode_value (ptr, &ptr);
+               locals_ptr++;
+               len = mono_metadata_decode_value (locals_ptr, &locals_ptr);
                mh = g_malloc0 (sizeof (MonoMethodHeader) + (len - MONO_ZERO_LEN_ARRAY) * sizeof (MonoType*));
                mh->num_locals = len;
                for (i = 0; i < len; ++i)
-                       mh->locals [i] = mono_metadata_parse_type (m, MONO_PARSE_LOCAL, 0, ptr, &ptr);
+                       mh->locals [i] = mono_metadata_parse_type (m, MONO_PARSE_LOCAL, 0, locals_ptr, &locals_ptr);
        } else {
                mh = g_new0 (MonoMethodHeader, 1);
        }
@@ -1481,6 +1779,12 @@ mono_metadata_parse_mh (MonoImage *m, const char *ptr)
        return mh;
 }
 
+/*
+ * mono_metadata_free_mh:
+ * @mh: a method header
+ *
+ * Free the memory allocated for the method header.
+ */
 void
 mono_metadata_free_mh (MonoMethodHeader *mh)
 {
@@ -1495,6 +1799,7 @@ mono_metadata_free_mh (MonoMethodHeader *mh)
  * mono_metadata_parse_field_type:
  * @m: metadata context to extract information from
  * @ptr: pointer to the field signature
+ * @rptr: pointer updated to match the end of the decoded stream
  *
  * Parses the field signature, and returns the type information for it. 
  *
@@ -1506,6 +1811,16 @@ mono_metadata_parse_field_type (MonoImage *m, short field_flags, const char *ptr
        return mono_metadata_parse_type (m, MONO_PARSE_FIELD, field_flags, ptr, rptr);
 }
 
+/**
+ * mono_metadata_parse_param:
+ * @m: metadata context to extract information from
+ * @ptr: pointer to the param signature
+ * @rptr: pointer updated to match the end of the decoded stream
+ *
+ * Parses the param signature, and returns the type information for it. 
+ *
+ * Returns: The MonoType that was extracted from @ptr.
+ */
 MonoType *
 mono_metadata_parse_param (MonoImage *m, const char *ptr, const char **rptr)
 {
@@ -1595,7 +1910,7 @@ static int
 typedef_locator (const void *a, const void *b)
 {
        locator_t *loc = (locator_t *) a;
-       char *bb = (char *) b;
+       const char *bb = (const char *) b;
        int typedef_index = (bb - loc->t->base) / loc->t->row_size;
        guint32 col, col_next;
 
@@ -1625,7 +1940,7 @@ static int
 table_locator (const void *a, const void *b)
 {
        locator_t *loc = (locator_t *) a;
-       char *bb = (char *) b;
+       const char *bb = (const char *) b;
        guint32 table_index = (bb - loc->t->base) / loc->t->row_size;
        guint32 col;
        
@@ -1641,6 +1956,15 @@ table_locator (const void *a, const void *b)
                return 1;
 }
 
+/*
+ * mono_metadata_typedef_from_field:
+ * @meta: metadata context
+ * @index: FieldDef token
+ *
+ * Returns the 1-based index into the TypeDef table of the type that
+ * declared the field described by @index.
+ * Returns 0 if not found.
+ */
 guint32
 mono_metadata_typedef_from_field (MonoImage *meta, guint32 index)
 {
@@ -1661,6 +1985,15 @@ mono_metadata_typedef_from_field (MonoImage *meta, guint32 index)
        return loc.result + 1;
 }
 
+/*
+ * mono_metadata_typedef_from_method:
+ * @meta: metadata context
+ * @index: MethodDef token
+ *
+ * Returns the 1-based index into the TypeDef table of the type that
+ * declared the method described by @index.
+ * Returns 0 if not found.
+ */
 guint32
 mono_metadata_typedef_from_method (MonoImage *meta, guint32 index)
 {
@@ -1681,6 +2014,14 @@ mono_metadata_typedef_from_method (MonoImage *meta, guint32 index)
        return loc.result + 1;
 }
 
+/*
+ * mono_metadata_interfaces_from_typedef:
+ * @meta: metadata context
+ * @index: typedef token
+ * 
+ * Returns and array of interfaces that the @index typedef token implements.
+ * The number of elemnts in the array is returned in @count.
+ */
 MonoClass**
 mono_metadata_interfaces_from_typedef (MonoImage *meta, guint32 index, guint *count)
 {
@@ -1727,8 +2068,13 @@ mono_metadata_interfaces_from_typedef (MonoImage *meta, guint32 index, guint *co
 }
 
 /*
- * Return the typedef token of the type index is defined into.
- * Return 0 if the index represents a toplevel type.
+ * mono_metadata_nested_in_typedef:
+ * @meta: metadata context
+ * @index: typedef token
+ * 
+ * Returns: the 1-based index into the TypeDef table of the type
+ * where the type described by @index is nested.
+ * Retruns 0 if @index describes a non-nested type.
  */
 guint32
 mono_metadata_nested_in_typedef (MonoImage *meta, guint32 index)
@@ -1750,38 +2096,48 @@ mono_metadata_nested_in_typedef (MonoImage *meta, guint32 index)
        return mono_metadata_decode_row_col (tdef, loc.result, MONO_NESTED_CLASS_ENCLOSING) | MONO_TOKEN_TYPE_DEF;
 }
 
+/*
+ * mono_metadata_nesting_typedef:
+ * @meta: metadata context
+ * @index: typedef token
+ * 
+ * Returns: the 1-based index into the TypeDef table of the first type
+ * that is nested inside the type described by @index. The search starts at
+ * @start_index.
+ * Returns 0 if no such type is found.
+ */
 guint32
-mono_metadata_nesting_typedef (MonoImage *meta, guint32 index)
+mono_metadata_nesting_typedef (MonoImage *meta, guint32 index, guint32 start_index)
 {
        MonoTableInfo *tdef = &meta->tables [MONO_TABLE_NESTEDCLASS];
-       locator_t loc;
        guint32 start;
+       guint32 class_index = mono_metadata_token_index (index);
        
        if (!tdef->base)
                return 0;
 
-       loc.idx = mono_metadata_token_index (index);
-       loc.col_idx = MONO_NESTED_CLASS_ENCLOSING;
-       loc.t = tdef;
-
-       if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
-               return 0;
-
-       start = loc.result;
+       start = start_index;
 
-       while (start > 0) {
-               if (loc.idx == mono_metadata_decode_row_col (tdef, start - 1, MONO_NESTED_CLASS_ENCLOSING))
-                       start--;
-               else
+       while (start <= tdef->rows) {
+               if (class_index == mono_metadata_decode_row_col (tdef, start - 1, MONO_NESTED_CLASS_ENCLOSING))
                        break;
+               else
+                       start++;
        }
 
-       /* loc_result is 0..1, needs to be mapped to table index (that is +1) */
-       return start + 1;
+       if (start > tdef->rows)
+               return 0;
+       else
+               return start;
 }
 
 /*
- * Return the info stored in the ClassLAyout table for the given typedef token.
+ * mono_metadata_packing_from_typedef:
+ * @meta: metadata context
+ * @index: token representing a type
+ * 
+ * Returns the info stored in the ClassLAyout table for the given typedef token
+ * into the @packing and @size pointers.
  * Returns 0 if the info is not found.
  */
 guint32
@@ -1811,8 +2167,58 @@ mono_metadata_packing_from_typedef (MonoImage *meta, guint32 index, guint32 *pac
        return loc.result + 1;
 }
 
+/*
+ * mono_metadata_custom_attrs_from_index:
+ * @meta: metadata context
+ * @index: token representing the parent
+ * 
+ * Returns: the 1-based index into the CustomAttribute table of the first 
+ * attribute which belongs to the metadata object described by @index.
+ * Returns 0 if no such attribute is found.
+ */
+guint32
+mono_metadata_custom_attrs_from_index (MonoImage *meta, guint32 index)
+{
+       MonoTableInfo *tdef = &meta->tables [MONO_TABLE_CUSTOMATTRIBUTE];
+       locator_t loc;
+       
+       if (!tdef->base)
+               return 0;
+
+       loc.idx = index;
+       loc.col_idx = MONO_CUSTOM_ATTR_PARENT;
+       loc.t = tdef;
+
+       if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
+               return 0;
+
+       /* Find the first entry by searching backwards */
+       while ((loc.result > 0) && (mono_metadata_decode_row_col (tdef, loc.result - 1, MONO_CUSTOM_ATTR_PARENT) == index))
+               loc.result --;
+
+       /* loc_result is 0..1, needs to be mapped to table index (that is +1) */
+       return loc.result + 1;
+}
+
+#ifdef DEBUG
+static void
+mono_backtrace (int limit)
+{
+       void *array[limit];
+       char **names;
+       int i;
+       backtrace (array, limit);
+       names = backtrace_symbols (array, limit);
+       for (i =0; i < limit; ++i) {
+               g_print ("\t%s\n", names [i]);
+       }
+       g_free (names);
+}
+#endif
+
 #ifndef __GNUC__
-#define __alignof__(a) sizeof(a)
+/*#define __alignof__(a) sizeof(a)*/
+#define __alignof__(type) G_STRUCT_OFFSET(struct { char c; type x; }, x)
 #endif
 
 /*
@@ -1839,23 +2245,17 @@ mono_type_size (MonoType *t, gint *align)
                *align = 1;
                return 0;
        case MONO_TYPE_BOOLEAN:
-               *align = __alignof__(char);
-               return sizeof (char);
-               
-       case MONO_TYPE_CHAR:
-               *align = __alignof__(short);
-               return sizeof (short);
-               
+               *align = __alignof__(gint8);
+               return 1;
        case MONO_TYPE_I1:
        case MONO_TYPE_U1:
-               *align = __alignof__(char);
+               *align = __alignof__(gint8);
                return 1;
-               
+       case MONO_TYPE_CHAR:
        case MONO_TYPE_I2:
        case MONO_TYPE_U2:
                *align = __alignof__(gint16);
-               return 2;
-               
+               return 2;               
        case MONO_TYPE_I4:
        case MONO_TYPE_U4:
                *align = __alignof__(gint32);
@@ -1863,50 +2263,48 @@ mono_type_size (MonoType *t, gint *align)
        case MONO_TYPE_R4:
                *align = __alignof__(float);
                return 4;
-               
        case MONO_TYPE_I8:
        case MONO_TYPE_U8:
                *align = __alignof__(gint64);
+               return 8;               
        case MONO_TYPE_R8:
                *align = __alignof__(double);
-               return 8;
-               
+               return 8;               
        case MONO_TYPE_I:
        case MONO_TYPE_U:
                *align = __alignof__(gpointer);
                return sizeof (gpointer);
-               
        case MONO_TYPE_STRING:
                *align = __alignof__(gpointer);
                return sizeof (gpointer);
-               
        case MONO_TYPE_OBJECT:
                *align = __alignof__(gpointer);
                return sizeof (gpointer);
-               
        case MONO_TYPE_VALUETYPE: {
-               guint32 size;
-
-               if (!t->data.klass->size_inited)
-                       mono_class_init (t->data.klass);
-
-               if (t->data.klass->enumtype) {
+               if (t->data.klass->enumtype)
                        return mono_type_size (t->data.klass->enum_basetype, align);
-               } else {
-                       size = mono_class_value_size (t->data.klass, align);
-                       return size;
-               }
+               else
+                       return mono_class_value_size (t->data.klass, align);
        }
        case MONO_TYPE_CLASS:
        case MONO_TYPE_SZARRAY:
        case MONO_TYPE_PTR:
        case MONO_TYPE_FNPTR:
        case MONO_TYPE_ARRAY:
-       case MONO_TYPE_TYPEDBYREF: /* we may want to use a struct {MonoType* type, void *data } instead ...*/
+               *align = __alignof__(gpointer);
+               return sizeof (gpointer);
+       case MONO_TYPE_TYPEDBYREF:
+               return mono_class_value_size (mono_defaults.typed_reference_class, align);
+       case MONO_TYPE_GENERICINST: {
+               MonoClass *iclass = mono_class_from_mono_type (t);
+               return mono_type_size (&iclass->byval_arg, align);
+       }
+       case MONO_TYPE_VAR:
+       case MONO_TYPE_MVAR:
                *align = __alignof__(gpointer);
                return sizeof (gpointer);
        default:
-               g_error ("type 0x%02x unknown", t->type);
+               g_error ("mono_type_size: type 0x%02x unknown", t->type);
        }
        return 0;
 }
@@ -1921,8 +2319,13 @@ mono_type_size (MonoType *t, gint *align)
 int
 mono_type_stack_size (MonoType *t, gint *align)
 {
+       int tmp;
+
        g_assert (t != NULL);
 
+       if (!align)
+               align = &tmp;
+
        if (t->byref) {
                *align = __alignof__(gpointer);
                return sizeof (gpointer);
@@ -1946,20 +2349,21 @@ mono_type_stack_size (MonoType *t, gint *align)
        case MONO_TYPE_PTR:
        case MONO_TYPE_FNPTR:
        case MONO_TYPE_ARRAY:
-       case MONO_TYPE_TYPEDBYREF:
                *align = __alignof__(gpointer);
                return sizeof (gpointer);
+       case MONO_TYPE_TYPEDBYREF:
+               *align = __alignof__(gpointer);
+               return sizeof (gpointer) * 2;
        case MONO_TYPE_R4:
                *align = __alignof__(float);
-               return 4;
-               
+               return sizeof (float);          
        case MONO_TYPE_I8:
        case MONO_TYPE_U8:
                *align = __alignof__(gint64);
+               return sizeof (gint64);         
        case MONO_TYPE_R8:
                *align = __alignof__(double);
-               return 8;
-               
+               return sizeof (double);
        case MONO_TYPE_VALUETYPE: {
                guint32 size;
 
@@ -1967,16 +2371,32 @@ mono_type_stack_size (MonoType *t, gint *align)
                        return mono_type_stack_size (t->data.klass->enum_basetype, align);
                else {
                        size = mono_class_value_size (t->data.klass, align);
-                       *align = __alignof__(gpointer);
+
+                       *align = *align + __alignof__(gpointer) - 1;
+                       *align &= ~(__alignof__(gpointer) - 1);
+
+                       size += sizeof (gpointer) - 1;
+                       size &= ~(sizeof (gpointer) - 1);
+
                        return size;
                }
        }
+       case MONO_TYPE_GENERICINST: {
+               MonoClass *iclass = mono_class_from_mono_type (t);
+               return mono_type_stack_size (&iclass->byval_arg, align);
+       }
        default:
                g_error ("type 0x%02x unknown", t->type);
        }
        return 0;
 }
 
+/*
+ * mono_metadata_type_hash:
+ * @t1: a type
+ *
+ * Computes an hash value for @t1 to be used in GHashTable.
+ */
 guint
 mono_metadata_type_hash (MonoType *t1)
 {
@@ -1986,15 +2406,27 @@ mono_metadata_type_hash (MonoType *t1)
        switch (t1->type) {
        case MONO_TYPE_VALUETYPE:
        case MONO_TYPE_CLASS:
+       case MONO_TYPE_SZARRAY:
                /* check if the distribution is good enough */
-               return hash << 7 | g_str_hash (t1->data.klass->name);
+               return ((hash << 5) - hash) ^ g_str_hash (t1->data.klass->name);
        case MONO_TYPE_PTR:
-       case MONO_TYPE_SZARRAY:
-               return hash << 7 | mono_metadata_type_hash (t1->data.type);
+               return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
+       case MONO_TYPE_ARRAY:
+               return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
+       case MONO_TYPE_GENERICINST:
+               return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.generic_inst->generic_type);
        }
        return hash;
 }
 
+/*
+ * mono_metadata_type_equal:
+ * @t1: a type
+ * @t2: another type
+ *
+ * Determine if @t1 and @t2 represent the same type.
+ * Returns: #TRUE if @t1 and @t2 are equal.
+ */
 gboolean
 mono_metadata_type_equal (MonoType *t1, MonoType *t2)
 {
@@ -2020,13 +2452,33 @@ mono_metadata_type_equal (MonoType *t1, MonoType *t2)
        case MONO_TYPE_I:
        case MONO_TYPE_U:
        case MONO_TYPE_OBJECT:
+       case MONO_TYPE_TYPEDBYREF:
                return TRUE;
        case MONO_TYPE_VALUETYPE:
        case MONO_TYPE_CLASS:
+       case MONO_TYPE_SZARRAY:
                return t1->data.klass == t2->data.klass;
        case MONO_TYPE_PTR:
-       case MONO_TYPE_SZARRAY:
                return mono_metadata_type_equal (t1->data.type, t2->data.type);
+       case MONO_TYPE_ARRAY:
+               if (t1->data.array->rank != t2->data.array->rank)
+                       return FALSE;
+               return t1->data.array->eklass == t2->data.array->eklass;
+       case MONO_TYPE_GENERICINST: {
+               int i;
+               if (t1->data.generic_inst->type_argc != t2->data.generic_inst->type_argc)
+                       return FALSE;
+               if (!mono_metadata_type_equal (t1->data.generic_inst->generic_type, t2->data.generic_inst->generic_type))
+                       return FALSE;
+               for (i = 0; i < t1->data.generic_inst->type_argc; ++i) {
+                       if (!mono_metadata_type_equal (t1->data.generic_inst->type_argv [i], t2->data.generic_inst->type_argv [i]))
+                               return FALSE;
+               }
+               return TRUE;
+       }
+       case MONO_TYPE_VAR:
+       case MONO_TYPE_MVAR:
+               return t1->data.generic_param == t2->data.generic_param;
        default:
                g_error ("implement type compare for %0x!", t1->type);
                return FALSE;
@@ -2035,6 +2487,15 @@ mono_metadata_type_equal (MonoType *t1, MonoType *t2)
        return FALSE;
 }
 
+/*
+ * mono_metadata_signature_equal:
+ * @sig1: a signature
+ * @sig2: another signature
+ *
+ * Determine if @sig1 and @sig2 represent the same signature, with the
+ * same number of arguments and the same types.
+ * Returns: #TRUE if @sig1 and @sig2 are equal.
+ */
 gboolean
 mono_metadata_signature_equal (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
 {
@@ -2048,16 +2509,39 @@ mono_metadata_signature_equal (MonoMethodSignature *sig1, MonoMethodSignature *s
                MonoType *p1 = sig1->params[i];
                MonoType *p2 = sig2->params[i];
                
-               if (p1->attrs != p2->attrs)
-                       return FALSE;
+               //if (p1->attrs != p2->attrs)
+               //      return FALSE;
                
                if (!mono_metadata_type_equal (p1, p2))
                        return FALSE;
        }
 
+       if (!mono_metadata_type_equal (sig1->ret, sig2->ret))
+               return FALSE;
        return TRUE;
 }
 
+guint
+mono_signature_hash (MonoMethodSignature *sig)
+{
+       guint i, res = sig->ret->type;
+
+       for (i = 0; i < sig->param_count; i++)
+               res = (res << 5) - res + sig->params[i]->type;
+
+       return res;
+}
+
+/*
+ * mono_metadata_encode_value:
+ * @value: value to encode
+ * @buf: buffer where to write the compressed representation
+ * @endbuf: pointer updated to point at the end of the encoded output
+ *
+ * Encodes the value @value in the compressed representation used
+ * in metadata and stores the result in @buf. @buf needs to be big
+ * enough to hold the data (4 bytes).
+ */
 void
 mono_metadata_encode_value (guint32 value, char *buf, char **endbuf)
 {
@@ -2086,18 +2570,19 @@ mono_metadata_encode_value (guint32 value, char *buf, char **endbuf)
  * @index: the index in the field table representing the field
  * @offset: a pointer to an integer where to store the offset that 
  * may have been specified for the field in a FieldLayout table
- * @rva: a pointer to the address of the field data in the image that
+ * @rva: a pointer to the RVA of the field data in the image that
  * may have been defined in a FieldRVA table
- * @marshal_info: a pointer to the marshal signature that may have been 
+ * @marshal_spec: a pointer to the marshal spec that may have been 
  * defined for the field in a FieldMarshal table.
  *
  * Gather info for field @index that may have been defined in the FieldLayout, 
  * FieldRVA and FieldMarshal tables.
- * Either of offset, rva and marshal_info can be NULL if you're not interested 
+ * Either of offset, rva and marshal_spec can be NULL if you're not interested 
  * in the data.
  */
 void
-mono_metadata_field_info (MonoImage *meta, guint32 index, guint32 *offset, const char **rva, const char **marshal_info)
+mono_metadata_field_info (MonoImage *meta, guint32 index, guint32 *offset, guint32 *rva, 
+                         MonoMarshalSpec **marshal_spec)
 {
        MonoTableInfo *tdef;
        locator_t loc;
@@ -2120,14 +2605,21 @@ mono_metadata_field_info (MonoImage *meta, guint32 index, guint32 *offset, const
 
                loc.col_idx = MONO_FIELD_RVA_FIELD;
                loc.t = tdef;
-
+               
                if (tdef->base && bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator)) {
                        /*
                         * LAMESPEC: There is no signature, no nothing, just the raw data.
                         */
-                       *rva = mono_cli_rva_map (meta->image_info, mono_metadata_decode_row_col (tdef, loc.result, MONO_FIELD_RVA_RVA));
+                       *rva = mono_metadata_decode_row_col (tdef, loc.result, MONO_FIELD_RVA_RVA);
                } else {
-                       *rva = NULL;
+                       *rva = 0;
+               }
+       }
+       if (marshal_spec) {
+               const char *p;
+               
+               if ((p = mono_metadata_get_marshal_info (meta, index, TRUE))) {
+                       *marshal_spec = mono_metadata_parse_marshal_spec (meta, p);
                }
        }
 
@@ -2175,6 +2667,15 @@ mono_metadata_get_constant_index (MonoImage *meta, guint32 token)
        return 0;
 }
 
+/*
+ * mono_metadata_events_from_typedef:
+ * @meta: metadata context
+ * @index: 0-based index (in the TypeDef table) describing a type
+ *
+ * Returns: the 0-based index in the Event table for the events in the
+ * type. The last event that belongs to the type (plus 1) is stored
+ * in the @end_idx pointer.
+ */
 guint32
 mono_metadata_events_from_typedef (MonoImage *meta, guint32 index, guint *end_idx)
 {
@@ -2205,6 +2706,15 @@ mono_metadata_events_from_typedef (MonoImage *meta, guint32 index, guint *end_id
        return start - 1;
 }
 
+/*
+ * mono_metadata_methods_from_event:
+ * @meta: metadata context
+ * @index: 0-based index (in the Event table) describing a event
+ *
+ * Returns: the 0-based index in the MethodDef table for the methods in the
+ * event. The last method that belongs to the event (plus 1) is stored
+ * in the @end_idx pointer.
+ */
 guint32
 mono_metadata_methods_from_event   (MonoImage *meta, guint32 index, guint *end_idx)
 {
@@ -2245,6 +2755,15 @@ mono_metadata_methods_from_event   (MonoImage *meta, guint32 index, guint *end_i
        return start;
 }
 
+/*
+ * mono_metadata_properties_from_typedef:
+ * @meta: metadata context
+ * @index: 0-based index (in the TypeDef table) describing a type
+ *
+ * Returns: the 0-based index in the Property table for the properties in the
+ * type. The last property that belongs to the type (plus 1) is stored
+ * in the @end_idx pointer.
+ */
 guint32
 mono_metadata_properties_from_typedef (MonoImage *meta, guint32 index, guint *end_idx)
 {
@@ -2275,6 +2794,15 @@ mono_metadata_properties_from_typedef (MonoImage *meta, guint32 index, guint *en
        return start - 1;
 }
 
+/*
+ * mono_metadata_methods_from_property:
+ * @meta: metadata context
+ * @index: 0-based index (in the PropertyDef table) describing a property
+ *
+ * Returns: the 0-based index in the MethodDef table for the methods in the
+ * property. The last method that belongs to the property (plus 1) is stored
+ * in the @end_idx pointer.
+ */
 guint32
 mono_metadata_methods_from_property   (MonoImage *meta, guint32 index, guint *end_idx)
 {
@@ -2315,9 +2843,31 @@ mono_metadata_methods_from_property   (MonoImage *meta, guint32 index, guint *en
        return start;
 }
 
+guint32
+mono_metadata_implmap_from_method (MonoImage *meta, guint32 method_idx)
+{
+       locator_t loc;
+       MonoTableInfo *tdef  = &meta->tables [MONO_TABLE_IMPLMAP];
+
+       if (!tdef->base)
+               return 0;
+
+       loc.t = tdef;
+       loc.col_idx = MONO_IMPLMAP_MEMBER;
+       loc.idx = ((method_idx + 1) << MEMBERFORWD_BITS) | MEMBERFORWD_METHODDEF;
+
+       if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
+               return 0;
+
+       return loc.result + 1;
+}
+
 /**
  * @image: context where the image is created
  * @type_spec:  typespec token
+ *
+ * Creates a MonoType representing the TypeSpec indexed by the @type_spec
+ * token.
  */
 MonoType *
 mono_type_create_from_typespec (MonoImage *image, guint32 type_spec)
@@ -2339,3 +2889,386 @@ mono_type_create_from_typespec (MonoImage *image, guint32 type_spec)
        return type;
 }
 
+MonoMarshalSpec *
+mono_metadata_parse_marshal_spec (MonoImage *image, const char *ptr)
+{
+       MonoMarshalSpec *res;
+       int len;
+       const char *start = ptr;
+
+       /* fixme: this is incomplete, but I cant find more infos in the specs */
+
+       res = g_new0 (MonoMarshalSpec, 1);
+       
+       len = mono_metadata_decode_value (ptr, &ptr);
+       res->native = *ptr++;
+
+       if (res->native == MONO_NATIVE_LPARRAY) {
+               if (ptr - start <= len)
+                       res->data.array_data.elem_type = *ptr++;
+               if (ptr - start <= len)
+                       res->data.array_data.param_num = mono_metadata_decode_value (ptr, &ptr);
+               if (ptr - start <= len)
+                       res->data.array_data.num_elem = mono_metadata_decode_value (ptr, &ptr);
+       } 
+
+       if (res->native == MONO_NATIVE_BYVALTSTR) {
+               if (ptr - start <= len)
+                       res->data.array_data.num_elem = mono_metadata_decode_value (ptr, &ptr);
+       }
+
+       if (res->native == MONO_NATIVE_BYVALARRAY) {
+               if (ptr - start <= len)
+                       res->data.array_data.num_elem = mono_metadata_decode_value (ptr, &ptr);
+       }
+       
+       if (res->native == MONO_NATIVE_CUSTOM) {
+               /* skip unused type guid */
+               len = mono_metadata_decode_value (ptr, &ptr);
+               ptr += len;
+               /* skip unused native type name */
+               len = mono_metadata_decode_value (ptr, &ptr);
+               ptr += len;
+               /* read custom marshaler type name */
+               len = mono_metadata_decode_value (ptr, &ptr);
+               res->data.custom_data.custom_name = g_strndup (ptr, len);               
+               ptr += len;
+               /* read cookie string */
+               len = mono_metadata_decode_value (ptr, &ptr);
+               res->data.custom_data.cookie = g_strndup (ptr, len);
+       }
+
+       return res;
+}
+
+guint32
+mono_type_to_unmanaged (MonoType *type, MonoMarshalSpec *mspec, gboolean as_field,
+                       gboolean unicode, MonoMarshalConv *conv) 
+{
+       MonoMarshalConv dummy_conv;
+       int t = type->type;
+
+       if (!conv)
+               conv = &dummy_conv;
+
+       *conv = MONO_MARSHAL_CONV_NONE;
+
+       if (type->byref)
+               return MONO_NATIVE_UINT;
+
+handle_enum:
+       switch (t) {
+       case MONO_TYPE_BOOLEAN: 
+               if (mspec) {
+                       switch (mspec->native) {
+                       case MONO_NATIVE_VARIANTBOOL:
+                               *conv = MONO_MARSHAL_CONV_BOOL_VARIANTBOOL;
+                               return MONO_NATIVE_VARIANTBOOL;
+                       case MONO_NATIVE_BOOLEAN:
+                               *conv = MONO_MARSHAL_CONV_BOOL_I4;
+                               return MONO_NATIVE_BOOLEAN;
+                       case MONO_NATIVE_I1:
+                       case MONO_NATIVE_U1:
+                               return mspec->native;
+                       default:
+                               g_error ("cant marshal bool to native type %02x", mspec->native);
+                       }
+               }
+               *conv = MONO_MARSHAL_CONV_BOOL_I4;
+               return MONO_NATIVE_BOOLEAN;
+       case MONO_TYPE_CHAR: return MONO_NATIVE_U2;
+       case MONO_TYPE_I1: return MONO_NATIVE_I1;
+       case MONO_TYPE_U1: return MONO_NATIVE_U1;
+       case MONO_TYPE_I2: return MONO_NATIVE_I2;
+       case MONO_TYPE_U2: return MONO_NATIVE_U2;
+       case MONO_TYPE_I4: return MONO_NATIVE_I4;
+       case MONO_TYPE_U4: return MONO_NATIVE_U4;
+       case MONO_TYPE_I8: return MONO_NATIVE_I8;
+       case MONO_TYPE_U8: return MONO_NATIVE_U8;
+       case MONO_TYPE_R4: return MONO_NATIVE_R4;
+       case MONO_TYPE_R8: return MONO_NATIVE_R8;
+       case MONO_TYPE_STRING:
+               if (mspec) {
+                       switch (mspec->native) {
+                       case MONO_NATIVE_BSTR:
+                               *conv = MONO_MARSHAL_CONV_STR_BSTR;
+                               return MONO_NATIVE_BSTR;
+                       case MONO_NATIVE_LPSTR:
+                               *conv = MONO_MARSHAL_CONV_STR_LPSTR;
+                               return MONO_NATIVE_LPSTR;
+                       case MONO_NATIVE_LPWSTR:
+                               *conv = MONO_MARSHAL_CONV_STR_LPWSTR;
+                               return MONO_NATIVE_LPWSTR;
+                       case MONO_NATIVE_LPTSTR:
+                               *conv = MONO_MARSHAL_CONV_STR_LPTSTR;
+                               return MONO_NATIVE_LPTSTR;
+                       case MONO_NATIVE_ANSIBSTR:
+                               *conv = MONO_MARSHAL_CONV_STR_ANSIBSTR;
+                               return MONO_NATIVE_ANSIBSTR;
+                       case MONO_NATIVE_TBSTR:
+                               *conv = MONO_MARSHAL_CONV_STR_TBSTR;
+                               return MONO_NATIVE_TBSTR;
+                       case MONO_NATIVE_BYVALTSTR:
+                               if (unicode)
+                                       *conv = MONO_MARSHAL_CONV_STR_BYVALWSTR;
+                               else
+                                       *conv = MONO_MARSHAL_CONV_STR_BYVALSTR;
+                               return MONO_NATIVE_BYVALTSTR;
+                       default:
+                               g_error ("cant marshal string to native type %02x", mspec->native);
+                       }
+               }       
+               *conv = MONO_MARSHAL_CONV_STR_LPTSTR;
+               return MONO_NATIVE_LPTSTR; 
+       case MONO_TYPE_PTR: return MONO_NATIVE_UINT;
+       case MONO_TYPE_VALUETYPE: /*FIXME*/
+               if (type->data.klass->enumtype) {
+                       t = type->data.klass->enum_basetype->type;
+                       goto handle_enum;
+               }
+               return MONO_NATIVE_STRUCT;
+       case MONO_TYPE_SZARRAY: 
+       case MONO_TYPE_ARRAY: 
+               if (mspec) {
+                       switch (mspec->native) {
+                       case MONO_NATIVE_BYVALARRAY:
+                               *conv = MONO_MARSHAL_CONV_ARRAY_BYVALARRAY;
+                               return MONO_NATIVE_BYVALARRAY;
+                       case MONO_NATIVE_SAFEARRAY:
+                               *conv = MONO_MARSHAL_CONV_ARRAY_SAVEARRAY;
+                               return MONO_NATIVE_SAFEARRAY;
+                       case MONO_NATIVE_LPARRAY:                               
+                               *conv = MONO_MARSHAL_CONV_ARRAY_LPARRAY;
+                               return MONO_NATIVE_LPARRAY;
+                       default:
+                               g_error ("cant marshal array as native type %02x", mspec->native);
+                       }
+               }       
+
+               *conv = MONO_MARSHAL_CONV_ARRAY_LPARRAY;
+               return MONO_NATIVE_LPARRAY;
+       case MONO_TYPE_I: return MONO_NATIVE_INT;
+       case MONO_TYPE_U: return MONO_NATIVE_UINT;
+       case MONO_TYPE_CLASS: 
+       case MONO_TYPE_OBJECT: {
+               /* FIXME : we need to handle ArrayList and StringBuilder here, probably */
+               if (mspec) {
+                       switch (mspec->native) {
+                       case MONO_NATIVE_STRUCT:
+                               return MONO_NATIVE_STRUCT;
+                       case MONO_NATIVE_INTERFACE:
+                               *conv = MONO_MARSHAL_CONV_OBJECT_INTERFACE;
+                               return MONO_NATIVE_INTERFACE;
+                       case MONO_NATIVE_IDISPATCH:
+                               *conv = MONO_MARSHAL_CONV_OBJECT_IDISPATCH;
+                               return MONO_NATIVE_IDISPATCH;
+                       case MONO_NATIVE_IUNKNOWN:
+                               *conv = MONO_MARSHAL_CONV_OBJECT_IUNKNOWN;
+                               return MONO_NATIVE_IUNKNOWN;
+                       default:
+                               g_error ("cant marshal object as native type %02x", mspec->native);
+                       }
+               }
+               if (t == MONO_TYPE_CLASS && (type->data.klass == mono_defaults.multicastdelegate_class ||
+                                            type->data.klass == mono_defaults.delegate_class || 
+                                            type->data.klass->parent == mono_defaults.multicastdelegate_class)) {
+                       *conv = MONO_MARSHAL_CONV_DEL_FTN;
+                       return MONO_NATIVE_FUNC;
+               }
+               *conv = MONO_MARSHAL_CONV_OBJECT_STRUCT;
+               return MONO_NATIVE_STRUCT;
+       }
+       case MONO_TYPE_FNPTR: return MONO_NATIVE_FUNC;
+       case MONO_TYPE_TYPEDBYREF:
+       default:
+               g_error ("type 0x%02x not handled in marshal", t);
+       }
+       return MONO_NATIVE_MAX;
+}
+
+const char*
+mono_metadata_get_marshal_info (MonoImage *meta, guint32 idx, gboolean is_field)
+{
+       locator_t loc;
+       MonoTableInfo *tdef  = &meta->tables [MONO_TABLE_FIELDMARSHAL];
+
+       if (!tdef->base)
+               return NULL;
+
+       loc.t = tdef;
+       loc.col_idx = MONO_FIELD_MARSHAL_PARENT;
+       loc.idx = ((idx + 1) << HAS_FIELD_MARSHAL_BITS) | (is_field? HAS_FIELD_MARSHAL_FIELDSREF: HAS_FIELD_MARSHAL_PARAMDEF);
+
+       if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
+               return NULL;
+
+       return mono_metadata_blob_heap (meta, mono_metadata_decode_row_col (tdef, loc.result, MONO_FIELD_MARSHAL_NATIVE_TYPE));
+}
+
+static MonoMethod*
+method_from_method_def_or_ref (MonoImage *m, guint32 tok)
+{
+       guint32 idx = tok >> METHODDEFORREF_BITS;
+       switch (tok & METHODDEFORREF_MASK) {
+       case METHODDEFORREF_METHODDEF:
+               return mono_get_method (m, MONO_TOKEN_METHOD_DEF | idx, NULL);
+       case METHODDEFORREF_METHODREF:
+               return mono_get_method (m, MONO_TOKEN_MEMBER_REF | idx, NULL);
+       }
+       g_assert_not_reached ();
+       return NULL;
+}
+
+MonoMethod**
+mono_class_get_overrides (MonoImage *image, guint32 type_token, gint32 *num_overrides)
+{
+       locator_t loc;
+       MonoTableInfo *tdef  = &image->tables [MONO_TABLE_METHODIMPL];
+       guint32 start, end;
+       gint32 i, num;
+       guint32 cols [MONO_METHODIMPL_SIZE];
+       MonoMethod **result;
+
+       if (num_overrides)
+               *num_overrides = 0;
+
+       if (!tdef->base)
+               return NULL;
+
+       loc.t = tdef;
+       loc.col_idx = MONO_METHODIMPL_CLASS;
+       loc.idx = mono_metadata_token_index (type_token);
+
+       if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
+               return NULL;
+
+       start = loc.result;
+       end = start + 1;
+       /*
+        * We may end up in the middle of the rows... 
+        */
+       while (start > 0) {
+               if (loc.idx == mono_metadata_decode_row_col (tdef, start - 1, MONO_METHODIMPL_CLASS))
+                       start--;
+               else
+                       break;
+       }
+       while (end < tdef->rows) {
+               if (loc.idx == mono_metadata_decode_row_col (tdef, end, MONO_METHODIMPL_CLASS))
+                       end++;
+               else
+                       break;
+       }
+       num = end - start;
+       result = g_new (MonoMethod*, num * 2);
+       for (i = 0; i < num; ++i) {
+               mono_metadata_decode_row (tdef, start + i, cols, MONO_METHODIMPL_SIZE);
+               result [i * 2] = method_from_method_def_or_ref (image, cols [MONO_METHODIMPL_DECLARATION]);
+               result [i * 2 + 1] = method_from_method_def_or_ref (image, cols [MONO_METHODIMPL_BODY]);
+       }
+
+       if (num_overrides)
+               *num_overrides = num;
+       return result;
+}
+
+/**
+ * mono_guid_to_string:
+ *
+ * Converts a 16 byte Microsoft GUID to the standard string representation.
+ */
+char *
+mono_guid_to_string (const guint8 *guid)
+{
+       return g_strdup_printf ("%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X", 
+                               guid[3], guid[2], guid[1], guid[0],
+                               guid[5], guid[4],
+                               guid[7], guid[6],
+                               guid[8], guid[9],
+                               guid[10], guid[11], guid[12], guid[13], guid[14], guid[15]);
+}
+
+static MonoClass**
+get_constraints (MonoImage *image, int owner)
+{
+       MonoTableInfo *tdef  = &image->tables [MONO_TABLE_GENERICPARAMCONSTRAINT];
+       guint32 cols [MONO_GENPARCONSTRAINT_SIZE];
+       guint32 i, token, found;
+       MonoClass *klass, **res;
+       GList *cons = NULL, *tmp;
+       
+
+       found = 0;
+       for (i = 0; i < tdef->rows; ++i) {
+               mono_metadata_decode_row (tdef, i, cols, MONO_GENPARCONSTRAINT_SIZE);
+               if (cols [MONO_GENPARCONSTRAINT_GENERICPAR] == owner) {
+                       token = mono_metadata_token_from_dor (cols [MONO_GENPARCONSTRAINT_CONSTRAINT]);
+                       klass = mono_class_get (image, token);
+                       cons = g_list_append (cons, klass);
+                       ++found;
+               } else {
+                       /* contiguous list finished */
+                       if (found)
+                               break;
+               }
+       }
+       if (!found)
+               return NULL;
+       res = g_new0 (MonoClass*, found + 1);
+       for (i = 0, tmp = cons; i < found; ++i, tmp = tmp->next) {
+               res [i] = tmp->data;
+       }
+       g_list_free (cons);
+       return res;
+}
+
+MonoGenericParam *
+mono_metadata_load_generic_params (MonoImage *image, guint32 token, guint32 *num, MonoMethod *method)
+{
+       MonoTableInfo *tdef  = &image->tables [MONO_TABLE_GENERICPARAM];
+       guint32 cols [MONO_GENERICPARAM_SIZE];
+       guint32 i, owner, last_num, n;
+       MonoGenericParam *params;
+
+       if (mono_metadata_token_table (token) == MONO_TABLE_TYPEDEF)
+               owner = MONO_TYPEORMETHOD_TYPE;
+       else if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
+               owner = MONO_TYPEORMETHOD_METHOD;
+       else {
+               g_error ("wrong token %x to load_generics_params", token);
+       }
+       owner |= mono_metadata_token_index (token) << MONO_TYPEORMETHOD_BITS;
+       if (num)
+               *num = 0;
+       if (!tdef->base)
+               return NULL;
+
+       for (i = 0; i < tdef->rows; ++i) {
+               mono_metadata_decode_row (tdef, i, cols, MONO_GENERICPARAM_SIZE);
+               if (cols [MONO_GENERICPARAM_OWNER] == owner)
+                       break;
+       }
+       last_num = 0;
+       if (i >= tdef->rows)
+               return NULL;
+       params = NULL;
+       n = 1;
+       do {
+               params = g_realloc (params, sizeof (MonoGenericParam) * n);
+               params [n - 1].pklass = NULL;
+               params [n - 1].method = method;
+               params [n - 1].flags = cols [MONO_GENERICPARAM_FLAGS];
+               params [n - 1].num = cols [MONO_GENERICPARAM_NUMBER];
+               params [n - 1].name = mono_metadata_string_heap (image, cols [MONO_GENERICPARAM_NAME]);
+               params [n - 1].constraints = get_constraints (image, i + 1);
+               if (++i >= tdef->rows)
+                       break;
+               mono_metadata_decode_row (tdef, i, cols, MONO_GENERICPARAM_SIZE);
+               n++;
+       } while (cols [MONO_GENERICPARAM_OWNER] == owner);
+       
+       if (num)
+               *num = n;
+       return params;
+}
+