Merge pull request #5714 from alexischr/update_bockbuild
[mono.git] / mono / metadata / loader.c
index e2a91f0975fb4ee6dea5c401e23e545c8038dad3..a5ef34da2d6e5901cd3c2e704b90bb3fdeeeb3b6 100644 (file)
@@ -1,5 +1,6 @@
-/*
- * loader.c: Image Loader 
+/**
+ * \file
+ * Image Loader
  *
  * Authors:
  *   Paolo Molaro (lupus@ximian.com)
@@ -34,7 +35,6 @@
 #include <mono/metadata/class-internals.h>
 #include <mono/metadata/debug-helpers.h>
 #include <mono/metadata/reflection.h>
-#include <mono/metadata/profiler.h>
 #include <mono/metadata/profiler-private.h>
 #include <mono/metadata/exception.h>
 #include <mono/metadata/marshal.h>
@@ -62,10 +62,10 @@ static mono_mutex_t global_loader_data_mutex;
 static gboolean loader_lock_inited;
 
 /* Statistics */
-static guint32 inflated_signatures_size;
-static guint32 memberref_sig_cache_size;
-static guint32 methods_size;
-static guint32 signatures_size;
+static gint32 inflated_signatures_size;
+static gint32 memberref_sig_cache_size;
+static gint32 methods_size;
+static gint32 signatures_size;
 
 /*
  * This TLS variable holds how many times the current thread has acquired the loader 
@@ -74,7 +74,10 @@ static guint32 signatures_size;
 MonoNativeTlsKey loader_lock_nest_id;
 
 static void dllmap_cleanup (void);
+static void cached_module_cleanup(void);
 
+/* Class lazy loading functions */
+GENERATE_GET_CLASS_WITH_CACHE (appdomain_unloaded_exception, "System", "AppDomainUnloadedException")
 
 static void
 global_loader_data_lock (void)
@@ -118,6 +121,7 @@ void
 mono_loader_cleanup (void)
 {
        dllmap_cleanup ();
+       cached_module_cleanup ();
 
        mono_native_tls_free (loader_lock_nest_id);
 
@@ -164,7 +168,7 @@ cache_memberref_sig (MonoImage *image, guint32 sig_idx, gpointer sig)
        else {
                g_hash_table_insert (image->memberref_signatures, GUINT_TO_POINTER (sig_idx), sig);
                /* An approximation based on glib 2.18 */
-               memberref_sig_cache_size += sizeof (gpointer) * 4;
+               InterlockedAdd (&memberref_sig_cache_size, sizeof (gpointer) * 4);
        }
        mono_image_unlock (image);
 
@@ -185,7 +189,7 @@ field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
        const char *ptr;
        guint32 idx = mono_metadata_token_index (token);
 
-       mono_error_init (error);
+       error_init (error);
 
        mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
        nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
@@ -194,7 +198,7 @@ field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
        fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
 
        if (!mono_verifier_verify_memberref_field_signature (image, cols [MONO_MEMBERREF_SIGNATURE], NULL)) {
-               mono_error_set_bad_image (error, image, "Bad field '%s' signature 0x%08x", class_index, token);
+               mono_error_set_bad_image (error, image, "Bad field '%u' signature 0x%08x", class_index, token);
                return NULL;
        }
 
@@ -209,7 +213,7 @@ field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
                klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, context, error);
                break;
        default:
-               mono_error_set_bad_image (error, image, "Bad field field '%s' signature 0x%08x", class_index, token);
+               mono_error_set_bad_image (error, image, "Bad field field '%u' signature 0x%08x", class_index, token);
        }
 
        if (!klass)
@@ -253,11 +257,11 @@ field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
        return field;
 }
 
-/*
+/**
  * mono_field_from_token:
- * @deprecated use the _checked variant
+ * \deprecated use the \c _checked variant
  * Notes: runtime code MUST not use this function
-*/
+ */
 MonoClassField*
 mono_field_from_token (MonoImage *image, guint32 token, MonoClass **retklass, MonoGenericContext *context)
 {
@@ -274,7 +278,7 @@ mono_field_from_token_checked (MonoImage *image, guint32 token, MonoClass **retk
        guint32 type;
        MonoClassField *field;
 
-       mono_error_init (error);
+       error_init (error);
 
        if (image_is_dynamic (image)) {
                MonoClassField *result;
@@ -313,13 +317,21 @@ mono_field_from_token_checked (MonoImage *image, guint32 token, MonoClass **retk
                mono_class_init (k);
                if (retklass)
                        *retklass = k;
-               field = mono_class_get_field (k, token);
-               if (!field) {
-                       mono_error_set_bad_image (error, image, "Could not resolve field token 0x%08x", token);
+               if (mono_class_has_failure (k)) {
+                       MonoError causedby_error;
+                       error_init (&causedby_error);
+                       mono_error_set_for_class_failure (&causedby_error, k);
+                       mono_error_set_bad_image (error, image, "Could not resolve field token 0x%08x, due to: %s", token, mono_error_get_message (&causedby_error));
+                       mono_error_cleanup (&causedby_error);
+               } else {
+                       field = mono_class_get_field (k, token);
+                       if (!field) {
+                               mono_error_set_bad_image (error, image, "Could not resolve field token 0x%08x", token);
+                       }
                }
        }
 
-       if (field && field->parent && !field->parent->generic_class && !field->parent->generic_container) {
+       if (field && field->parent && !mono_class_is_ginst (field->parent) && !mono_class_is_gtd (field->parent)) {
                mono_image_lock (image);
                mono_conc_hashtable_insert (image->field_cache, GUINT_TO_POINTER (token), field);
                mono_image_unlock (image);
@@ -360,17 +372,19 @@ find_method_in_class (MonoClass *klass, const char *name, const char *qname, con
        int i;
 
        /* Search directly in the metadata to avoid calling setup_methods () */
-       mono_error_init (error);
+       error_init (error);
 
-       /* FIXME: !from_class->generic_class condition causes test failures. */
-       if (klass->type_token && !image_is_dynamic (klass->image) && !klass->methods && !klass->rank && klass == from_class && !from_class->generic_class) {
-               for (i = 0; i < klass->method.count; ++i) {
+       /* FIXME: !mono_class_is_ginst (from_class) condition causes test failures. */
+       if (klass->type_token && !image_is_dynamic (klass->image) && !klass->methods && !klass->rank && klass == from_class && !mono_class_is_ginst (from_class)) {
+               int first_idx = mono_class_get_first_method_idx (klass);
+               int mcount = mono_class_get_method_count (klass);
+               for (i = 0; i < mcount; ++i) {
                        guint32 cols [MONO_METHOD_SIZE];
                        MonoMethod *method;
                        const char *m_name;
                        MonoMethodSignature *other_sig;
 
-                       mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
+                       mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, first_idx + i, cols, MONO_METHOD_SIZE);
 
                        m_name = mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]);
 
@@ -379,7 +393,7 @@ find_method_in_class (MonoClass *klass, const char *name, const char *qname, con
                                  (name && !strcmp (m_name, name))))
                                continue;
 
-                       method = mono_get_method_checked (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass, NULL, error);
+                       method = mono_get_method_checked (klass->image, MONO_TOKEN_METHOD_DEF | (first_idx + i + 1), klass, NULL, error);
                        if (!mono_error_ok (error)) //bail out if we hit a loader error
                                return NULL;
                        if (method) {
@@ -403,7 +417,8 @@ find_method_in_class (MonoClass *klass, const char *name, const char *qname, con
 
                return NULL;
        }
-       for (i = 0; i < klass->method.count; ++i) {
+       int mcount = mono_class_get_method_count (klass);
+       for (i = 0; i < mcount; ++i) {
                MonoMethod *m = klass->methods [i];
                MonoMethodSignature *msig;
 
@@ -431,7 +446,7 @@ find_method_in_class (MonoClass *klass, const char *name, const char *qname, con
                }
        }
 
-       if (i < klass->method.count)
+       if (i < mcount)
                return mono_class_get_method_by_index (from_class, i);
        return NULL;
 }
@@ -445,7 +460,7 @@ find_method (MonoClass *in_class, MonoClass *ic, const char* name, MonoMethodSig
        MonoMethod *result = NULL;
        MonoClass *initial_class = in_class;
 
-       mono_error_init (error);
+       error_init (error);
        is_interface = MONO_CLASS_IS_INTERFACE (in_class);
 
        if (ic) {
@@ -527,7 +542,7 @@ inflate_generic_signature_checked (MonoImage *image, MonoMethodSignature *sig, M
        gboolean is_open;
        int i;
 
-       mono_error_init (error);
+       error_init (error);
        if (!context)
                return sig;
 
@@ -567,10 +582,10 @@ fail:
        return NULL;
 }
 
-/*
+/**
  * mono_inflate_generic_signature:
  *
- *   Inflate SIG with CONTEXT, and return a canonical copy. On error, set ERROR, and return NULL.
+ * Inflate \p sig with \p context, and return a canonical copy. On error, set \p error, and return NULL.
  */
 MonoMethodSignature*
 mono_inflate_generic_signature (MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
@@ -605,7 +620,7 @@ inflate_generic_header (MonoMethodHeader *header, MonoGenericContext *context, M
 
        res->is_transient = TRUE;
 
-       mono_error_init (error);
+       error_init (error);
 
        for (int i = 0; i < header->num_locals; ++i) {
                res->locals [i] = mono_class_inflate_generic_type_checked (header->locals [i], context, error);
@@ -628,9 +643,10 @@ fail:
        return NULL;
 }
 
-/*
- * token is the method_ref/def/spec token used in a call IL instruction.
- * @deprecated use the _checked variant
+/**
+ * mono_method_get_signature_full:
+ * \p token is the method ref/def/spec token used in a \c call IL instruction.
+ * \deprecated use the \c _checked variant
  * Notes: runtime code MUST not use this function
  */
 MonoMethodSignature*
@@ -652,7 +668,7 @@ mono_method_get_signature_checked (MonoMethod *method, MonoImage *image, guint32
        MonoMethodSignature *sig;
        const char *ptr;
 
-       mono_error_init (error);
+       error_init (error);
 
        /* !table is for wrappers: we should really assign their own token to them */
        if (!table || table == MONO_TABLE_METHOD)
@@ -668,7 +684,7 @@ mono_method_get_signature_checked (MonoMethod *method, MonoImage *image, guint32
                return mono_method_signature_checked (method, error);
        }
 
-       if (method->klass->generic_class)
+       if (mono_class_is_ginst (method->klass))
                return mono_method_signature_checked (method, error);
 
        if (image_is_dynamic (image)) {
@@ -721,7 +737,7 @@ mono_method_get_signature_checked (MonoMethod *method, MonoImage *image, guint32
                if (cached != sig)
                        mono_metadata_free_inflated_signature (sig);
                else
-                       inflated_signatures_size += mono_metadata_signature_size (cached);
+                       InterlockedAdd (&inflated_signatures_size, mono_metadata_signature_size (cached));
                sig = cached;
        }
 
@@ -729,9 +745,10 @@ mono_method_get_signature_checked (MonoMethod *method, MonoImage *image, guint32
        return sig;
 }
 
-/*
- * token is the method_ref/def/spec token used in a call IL instruction.
- * @deprecated use the _checked variant
+/**
+ * mono_method_get_signature:
+ * \p token is the method_ref/def/spec token used in a call IL instruction.
+ * \deprecated use the \c _checked variant
  * Notes: runtime code MUST not use this function
  */
 MonoMethodSignature*
@@ -751,7 +768,8 @@ mono_method_search_in_array_class (MonoClass *klass, const char *name, MonoMetho
 
        mono_class_setup_methods (klass);
        g_assert (!mono_class_has_failure (klass)); /*FIXME this should not fail, right?*/
-       for (i = 0; i < klass->method.count; ++i) {
+       int mcount = mono_class_get_method_count (klass);
+       for (i = 0; i < mcount; ++i) {
                MonoMethod *method = klass->methods [i];
                if (strcmp (method->name, name) == 0 && sig->param_count == method->signature->param_count)
                        return method;
@@ -772,7 +790,7 @@ method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typesp
        MonoMethodSignature *sig;
        const char *ptr;
 
-       mono_error_init (error);
+       error_init (error);
 
        mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
        nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
@@ -854,7 +872,7 @@ method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typesp
                type = &klass->byval_arg;
 
                if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
-                       MonoClass *in_class = klass->generic_class ? klass->generic_class->container_class : klass;
+                       MonoClass *in_class = mono_class_is_ginst (klass) ? mono_class_get_generic_class (klass)->container_class : klass;
                        method = find_method (in_class, NULL, mname, sig, klass, error);
                        break;
                }
@@ -901,7 +919,7 @@ method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 i
        guint32 cols [MONO_METHODSPEC_SIZE];
        guint32 token, nindex, param_count;
 
-       mono_error_init (error);
+       error_init (error);
 
        mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
        token = cols [MONO_METHODSPEC_METHOD];
@@ -941,12 +959,12 @@ method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 i
 
        klass = method->klass;
 
-       if (klass->generic_class) {
+       if (mono_class_is_ginst (klass)) {
                g_assert (method->is_inflated);
                method = ((MonoMethodInflated *) method)->declaring;
        }
 
-       new_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
+       new_context.class_inst = mono_class_is_ginst (klass) ? mono_class_get_generic_class (klass)->context.class_inst : NULL;
        new_context.method_inst = inst;
 
        method = mono_class_inflate_generic_method_full_checked (method, klass, &new_context, error);
@@ -1018,32 +1036,33 @@ mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, cons
 
 /**
  * mono_dllmap_insert:
- * @assembly: if NULL, this is a global mapping, otherwise the remapping of the dynamic library will only apply to the specified assembly
- * @dll: The name of the external library, as it would be found in the DllImport declaration.  If prefixed with 'i:' the matching of the library name is done without case sensitivity
- * @func: if not null, the mapping will only applied to the named function (the value of EntryPoint)
- * @tdll: The name of the library to map the specified @dll if it matches.
- * @tfunc: The name of the function that replaces the invocation.  If NULL, it is replaced with a copy of @func.
+ * \param assembly if NULL, this is a global mapping, otherwise the remapping of the dynamic library will only apply to the specified assembly
+ * \param dll The name of the external library, as it would be found in the \c DllImport declaration.  If prefixed with <code>i:</code> the matching of the library name is done without case sensitivity
+ * \param func if not null, the mapping will only applied to the named function (the value of <code>EntryPoint</code>)
+ * \param tdll The name of the library to map the specified \p dll if it matches.
+ * \param tfunc The name of the function that replaces the invocation.  If NULL, it is replaced with a copy of \p func.
  *
  * LOCKING: Acquires the loader lock.
  *
- * This function is used to programatically add DllImport remapping in either
+ * This function is used to programatically add \c DllImport remapping in either
  * a specific assembly, or as a global remapping.   This is done by remapping
- * references in a DllImport attribute from the @dll library name into the @tdll
- * name.    If the @dll name contains the prefix "i:", the comparison of the 
+ * references in a \c DllImport attribute from the \p dll library name into the \p tdll
+ * name. If the \p dll name contains the prefix <code>i:</code>, the comparison of the 
  * library name is done without case sensitivity.
  *
- * If you pass @func, this is the name of the EntryPoint in a DllImport if specified
- * or the name of the function as determined by DllImport.    If you pass @func, you
- * must also pass @tfunc which is the name of the target function to invoke on a match.
+ * If you pass \p func, this is the name of the \c EntryPoint in a \c DllImport if specified
+ * or the name of the function as determined by \c DllImport. If you pass \p func, you
+ * must also pass \p tfunc which is the name of the target function to invoke on a match.
  *
  * Example:
- * mono_dllmap_insert (NULL, "i:libdemo.dll", NULL, relocated_demo_path, NULL);
  *
- * The above will remap DllImport statments for "libdemo.dll" and "LIBDEMO.DLL" to
- * the contents of relocated_demo_path for all assemblies in the Mono process.
+ * <code>mono_dllmap_insert (NULL, "i:libdemo.dll", NULL, relocated_demo_path, NULL);</code>
+ *
+ * The above will remap \c DllImport statements for \c libdemo.dll and \c LIBDEMO.DLL to
+ * the contents of \c relocated_demo_path for all assemblies in the Mono process.
  *
  * NOTE: This can be called before the runtime is initialized, for example from
- * mono_config_parse ().
+ * \c mono_config_parse.
  */
 void
 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc)
@@ -1131,12 +1150,29 @@ mono_loader_register_module (const char *name, MonoDl *module)
        g_hash_table_insert (global_module_map, g_strdup (name), module);
 }
 
+static void
+remove_cached_module(gpointer key, gpointer value, gpointer user_data)
+{
+       mono_dl_close((MonoDl*)value);
+}
+
+static void
+cached_module_cleanup(void)
+{
+       if (global_module_map != NULL) {
+               g_hash_table_foreach(global_module_map, remove_cached_module, NULL);
+
+               g_hash_table_destroy(global_module_map);
+               global_module_map = NULL;
+       }
+}
+
 static MonoDl *internal_module;
 
 static gboolean
 is_absolute_path (const char *path)
 {
-#ifdef PLATFORM_MACOSX
+#ifdef HOST_DARWIN
        if (!strncmp (path, "@executable_path/", 17) || !strncmp (path, "@loader_path/", 13) ||
            !strncmp (path, "@rpath/", 7))
            return TRUE;
@@ -1144,6 +1180,9 @@ is_absolute_path (const char *path)
        return g_path_is_absolute (path);
 }
 
+/**
+ * mono_lookup_pinvoke_call:
+ */
 gpointer
 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
 {
@@ -1162,6 +1201,7 @@ mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char
        int i,j;
        MonoDl *module = NULL;
        gboolean cached = FALSE;
+       gpointer addr = NULL;
 
        g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
 
@@ -1470,7 +1510,7 @@ mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char
                                "Searching for '%s'.", import);
 
        if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
-               error_msg = mono_dl_symbol (module, import, &piinfo->addr); 
+               error_msg = mono_dl_symbol (module, import, &addr); 
        } else {
                char *mangled_name = NULL, *mangled_name2 = NULL;
                int mangle_charset;
@@ -1492,7 +1532,7 @@ mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char
 #endif
                                for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
 
-                                       if (piinfo->addr)
+                                       if (addr)
                                                continue;
 
                                        mangled_name = (char*)import;
@@ -1543,9 +1583,9 @@ mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char
                                        mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
                                                                "Probing '%s'.", mangled_name2);
 
-                                       error_msg = mono_dl_symbol (module, mangled_name2, &piinfo->addr);
+                                       error_msg = mono_dl_symbol (module, mangled_name2, &addr);
 
-                                       if (piinfo->addr)
+                                       if (addr)
                                                mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
                                                                        "Found as '%s'.", mangled_name2);
                                        else
@@ -1564,7 +1604,7 @@ mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char
                }
        }
 
-       if (!piinfo->addr) {
+       if (!addr) {
                g_free (error_msg);
                if (exc_class) {
                        *exc_class = "EntryPointNotFoundException";
@@ -1572,7 +1612,8 @@ mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char
                }
                return NULL;
        }
-       return piinfo->addr;
+       piinfo->addr = addr;
+       return addr;
 }
 
 /*
@@ -1590,7 +1631,7 @@ mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
        const char *sig = NULL;
        guint32 cols [MONO_TYPEDEF_SIZE];
 
-       mono_error_init (error);
+       error_init (error);
 
        if (image_is_dynamic (image)) {
                MonoClass *handle_class;
@@ -1643,10 +1684,10 @@ mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
                result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethodPInvoke));
        } else {
                result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethod));
-               methods_size += sizeof (MonoMethod);
+               InterlockedAdd (&methods_size, sizeof (MonoMethod));
        }
 
-       mono_stats.method_count ++;
+       InterlockedIncrement (&mono_stats.method_count);
 
        result->slot = -1;
        result->klass = klass;
@@ -1659,7 +1700,7 @@ mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
                sig = mono_metadata_blob_heap (image, cols [4]);
        /* size = */ mono_metadata_decode_blob_size (sig, &sig);
 
-       container = klass->generic_container;
+       container = mono_class_try_get_generic_container (klass);
 
        /* 
         * load_generic_params does a binary search so only call it if the method 
@@ -1704,6 +1745,9 @@ mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
        return result;
 }
 
+/**
+ * mono_get_method:
+ */
 MonoMethod *
 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
 {
@@ -1713,6 +1757,9 @@ mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
        return result;
 }
 
+/**
+ * mono_get_method_full:
+ */
 MonoMethod *
 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
                      MonoGenericContext *context)
@@ -1731,7 +1778,7 @@ mono_get_method_checked (MonoImage *image, guint32 token, MonoClass *klass, Mono
 
        /* We do everything inside the lock to prevent creation races */
 
-       mono_error_init (error);
+       error_init (error);
 
        mono_image_lock (image);
 
@@ -1787,7 +1834,7 @@ get_method_constrained (MonoImage *image, MonoMethod *method, MonoClass *constra
        MonoGenericContext *method_context = NULL;
        MonoMethodSignature *sig, *original_sig;
 
-       mono_error_init (error);
+       error_init (error);
 
        mono_class_init (constrained_class);
        original_sig = sig = mono_method_signature_checked (method, error);
@@ -1849,12 +1896,10 @@ mono_get_method_constrained_with_method (MonoImage *image, MonoMethod *method, M
 
 /**
  * mono_get_method_constrained:
- *
- * This is used when JITing the `constrained.' opcode.
- *
- * This returns two values: the contrained method, which has been inflated
- * as the function return value;   And the original CIL-stream method as
- * declared in cil_method.  The later is used for verification.
+ * This is used when JITing the <code>constrained.</code> opcode.
+ * \returns The contrained method, which has been inflated
+ * as the function return value; and the original CIL-stream method as
+ * declared in \p cil_method. The latter is used for verification.
  */
 MonoMethod *
 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
@@ -1869,23 +1914,25 @@ mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constra
 MonoMethod *
 mono_get_method_constrained_checked (MonoImage *image, guint32 token, MonoClass *constrained_class, MonoGenericContext *context, MonoMethod **cil_method, MonoError *error)
 {
-       mono_error_init (error);
+       error_init (error);
 
-       *cil_method = mono_get_method_from_token (image, token, NULL, context, NULL, error);
+       *cil_method = mono_get_method_checked (image, token, NULL, context, error);
        if (!*cil_method)
                return NULL;
 
        return get_method_constrained (image, *cil_method, constrained_class, context, error);
 }
 
+/**
+ * mono_free_method:
+ */
 void
 mono_free_method  (MonoMethod *method)
 {
-       if (mono_profiler_get_events () & MONO_PROFILE_METHOD_EVENTS)
-               mono_profiler_method_free (method);
+       MONO_PROFILER_RAISE (method_free, (method));
        
        /* FIXME: This hack will go away when the profiler will support freeing methods */
-       if (mono_profiler_get_events () != MONO_PROFILE_NONE)
+       if (G_UNLIKELY (mono_profiler_installed ()))
                return;
        
        if (method->signature) {
@@ -1919,6 +1966,9 @@ mono_free_method  (MonoMethod *method)
        }
 }
 
+/**
+ * mono_method_get_param_names:
+ */
 void
 mono_method_get_param_names (MonoMethod *method, const char **names)
 {
@@ -1998,6 +2048,9 @@ mono_method_get_param_names (MonoMethod *method, const char **names)
        }
 }
 
+/**
+ * mono_method_get_param_token:
+ */
 guint32
 mono_method_get_param_token (MonoMethod *method, int index)
 {
@@ -2025,6 +2078,9 @@ mono_method_get_param_token (MonoMethod *method, int index)
        return 0;
 }
 
+/**
+ * mono_method_get_marshal_info:
+ */
 void
 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
 {
@@ -2087,6 +2143,9 @@ mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
        }
 }
 
+/**
+ * mono_method_has_marshal_info:
+ */
 gboolean
 mono_method_has_marshal_info (MonoMethod *method)
 {
@@ -2179,6 +2238,9 @@ mono_stack_walk (MonoStackWalk func, gpointer user_data)
        mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_LOOKUP_ALL, &ud);
 }
 
+/**
+ * mono_stack_walk_no_il:
+ */
 void
 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
 {
@@ -2218,10 +2280,9 @@ async_stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer
 }
 
 
-/*
+/**
  * mono_stack_walk_async_safe:
- *
- *   Async safe version callable from signal handlers.
+ * Async safe version callable from signal handlers.
  */
 void
 mono_stack_walk_async_safe (MonoStackWalkAsyncSafe func, void *initial_sig_context, void *user_data)
@@ -2243,6 +2304,9 @@ last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
        return managed;
 }
 
+/**
+ * mono_method_get_last_managed:
+ */
 MonoMethod*
 mono_method_get_last_managed (void)
 {
@@ -2256,7 +2320,7 @@ static gboolean loader_lock_track_ownership = FALSE;
 /**
  * mono_loader_lock:
  *
- * See docs/thread-safety.txt for the locking strategy.
+ * See \c docs/thread-safety.txt for the locking strategy.
  */
 void
 mono_loader_lock (void)
@@ -2267,6 +2331,9 @@ mono_loader_lock (void)
        }
 }
 
+/**
+ * mono_loader_unlock:
+ */
 void
 mono_loader_unlock (void)
 {
@@ -2324,7 +2391,7 @@ mono_loader_unlock_if_inited (void)
 }
 
 /**
- * mono_method_signature:
+ * mono_method_signature_checked:
  *
  * Return the signature of the method M. On failure, returns NULL, and ERR is set.
  */
@@ -2341,7 +2408,7 @@ mono_method_signature_checked (MonoMethod *m, MonoError *error)
 
        /* We need memory barriers below because of the double-checked locking pattern */ 
 
-       mono_error_init (error);
+       error_init (error);
 
        if (m->signature)
                return m->signature;
@@ -2356,7 +2423,7 @@ mono_method_signature_checked (MonoMethod *m, MonoError *error)
                if (!mono_error_ok (error))
                        return NULL;
 
-               inflated_signatures_size += mono_metadata_signature_size (signature);
+               InterlockedAdd (&inflated_signatures_size, mono_metadata_signature_size (signature));
 
                mono_image_lock (img);
 
@@ -2374,10 +2441,10 @@ mono_method_signature_checked (MonoMethod *m, MonoError *error)
 
        sig = mono_metadata_blob_heap (img, sig_offset = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
 
-       g_assert (!m->klass->generic_class);
+       g_assert (!mono_class_is_ginst (m->klass));
        container = mono_method_get_generic_container (m);
        if (!container)
-               container = m->klass->generic_container;
+               container = mono_class_try_get_generic_container (m->klass);
 
        /* Generic signatures depend on the container so they cannot be cached */
        /* icall/pinvoke signatures cannot be cached cause we modify them below */
@@ -2413,7 +2480,7 @@ mono_method_signature_checked (MonoMethod *m, MonoError *error)
                        mono_image_unlock (img);
                }
 
-               signatures_size += mono_metadata_signature_size (signature);
+               InterlockedAdd (&signatures_size, mono_metadata_signature_size (signature));
        }
 
        /* Verify metadata consistency */
@@ -2430,9 +2497,16 @@ mono_method_signature_checked (MonoMethod *m, MonoError *error)
                mono_error_set_method_load (error, m->klass, m->name, "generic_params table claims method has generic parameters, but signature says it doesn't for method 0x%08x from image %s", idx, img->name);
                return NULL;
        }
-       if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
+       if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
                signature->pinvoke = 1;
-       else if (m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
+#ifdef TARGET_WIN32
+               /*
+                * On Windows the default pinvoke calling convention is STDCALL but
+                * we need CDECL since this is actually an icall.
+                */
+               signature->call_convention = MONO_CALL_C;
+#endif
+       } else if (m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
                MonoCallConvention conv = (MonoCallConvention)0;
                MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
                signature->pinvoke = 1;
@@ -2476,8 +2550,7 @@ mono_method_signature_checked (MonoMethod *m, MonoError *error)
 
 /**
  * mono_method_signature:
- *
- * Return the signature of the method M. On failure, returns NULL.
+ * \returns the signature of the method \p m. On failure, returns NULL.
  */
 MonoMethodSignature*
 mono_method_signature (MonoMethod *m)
@@ -2496,18 +2569,27 @@ mono_method_signature (MonoMethod *m)
        return sig;
 }
 
+/**
+ * mono_method_get_name:
+ */
 const char*
 mono_method_get_name (MonoMethod *method)
 {
        return method->name;
 }
 
+/**
+ * mono_method_get_class:
+ */
 MonoClass*
 mono_method_get_class (MonoMethod *method)
 {
        return method->klass;
 }
 
+/**
+ * mono_method_get_token:
+ */
 guint32
 mono_method_get_token (MonoMethod *method)
 {
@@ -2523,7 +2605,7 @@ mono_method_get_header_checked (MonoMethod *method, MonoError *error)
        gpointer loc;
        MonoGenericContainer *container;
 
-       mono_error_init (error);
+       error_init (error);
        img = method->klass->image;
 
        if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) || (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) || (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) || (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
@@ -2579,10 +2661,13 @@ mono_method_get_header_checked (MonoMethod *method, MonoError *error)
         */
        container = mono_method_get_generic_container (method);
        if (!container)
-               container = method->klass->generic_container;
+               container = mono_class_try_get_generic_container (method->klass);
        return mono_metadata_parse_mh_full (img, container, (const char *)loc, error);
 }
 
+/**
+ * mono_method_get_header:
+ */
 MonoMethodHeader*
 mono_method_get_header (MonoMethod *method)
 {
@@ -2593,6 +2678,9 @@ mono_method_get_header (MonoMethod *method)
 }
 
 
+/**
+ * mono_method_get_flags:
+ */
 guint32
 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
 {
@@ -2601,8 +2689,9 @@ mono_method_get_flags (MonoMethod *method, guint32 *iflags)
        return method->flags;
 }
 
-/*
- * Find the method index in the metadata methodDef table.
+/**
+ * mono_method_get_index:
+ * Find the method index in the metadata \c MethodDef table.
  */
 guint32
 mono_method_get_index (MonoMethod *method)
@@ -2620,12 +2709,14 @@ mono_method_get_index (MonoMethod *method)
        mono_class_setup_methods (klass);
        if (mono_class_has_failure (klass))
                return 0;
-       for (i = 0; i < klass->method.count; ++i) {
+       int first_idx = mono_class_get_first_method_idx (klass);
+       int mcount = mono_class_get_method_count (klass);
+       for (i = 0; i < mcount; ++i) {
                if (method == klass->methods [i]) {
                        if (klass->image->uncompressed_metadata)
-                               return mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, klass->method.first + i + 1);
+                               return mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, first_idx + i + 1);
                        else
-                               return klass->method.first + i + 1;
+                               return first_idx + i + 1;
                }
        }
        return 0;