2006-05-04 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / metadata / loader.c
index 7b62423cfbcea3ce0cf404177163994a13f6070c..2e755f4c9ef2b3318a801045672205f1d055e760 100644 (file)
@@ -43,10 +43,148 @@ MonoDefaults mono_defaults;
  */
 static CRITICAL_SECTION loader_mutex;
 
+
+/*
+ * This TLS variable contains the last type load error encountered by the loader.
+ */
+guint32 loader_error_thread_id;
+
 void
 mono_loader_init ()
 {
        InitializeCriticalSection (&loader_mutex);
+
+       loader_error_thread_id = TlsAlloc ();
+}
+
+void
+mono_loader_cleanup (void)
+{
+       TlsFree (loader_error_thread_id);
+
+       DeleteCriticalSection (&loader_mutex);
+}
+
+/*
+ * Handling of type load errors should be done as follows:
+ *
+ *   If something could not be loaded, the loader should call one of the
+ * mono_loader_set_error_XXX functions ()
+ * with the appropriate arguments, then return NULL to report the failure. The error 
+ * should be propagated until it reaches code which can throw managed exceptions. At that
+ * point, an exception should be thrown based on the information returned by
+ * mono_loader_get_error (). Then the error should be cleared by calling 
+ * mono_loader_clear_error ().
+ */
+
+static void
+set_loader_error (MonoLoaderError *error)
+{
+       TlsSetValue (loader_error_thread_id, error);
+}
+
+/*
+ * mono_loader_set_error_type_load:
+ *
+ *   Set the loader error for this thread. CLASS_NAME and ASSEMBLY_NAME should be
+ * dynamically allocated strings whose ownership is passed to this function.
+ */
+void
+mono_loader_set_error_type_load (char *class_name, char *assembly_name)
+{
+       MonoLoaderError *error;
+
+       if (mono_loader_get_last_error ()) {
+               g_free (class_name);
+               g_free (assembly_name);
+               return;
+       }
+
+       error = g_new0 (MonoLoaderError, 1);
+       error->kind = MONO_LOADER_ERROR_TYPE;
+       error->class_name = class_name;
+       error->assembly_name = assembly_name;
+
+       /* 
+        * This is not strictly needed, but some (most) of the loader code still
+        * can't deal with load errors, and this message is more helpful than an
+        * assert.
+        */
+       g_warning ("The class %s could not be loaded, used in %s", class_name, assembly_name);
+
+       set_loader_error (error);
+}
+
+/*
+ * mono_loader_set_error_method_load:
+ *
+ *   Set the loader error for this thread. MEMBER_NAME should point to a string
+ * inside metadata.
+ */
+void
+mono_loader_set_error_method_load (MonoClass *klass, const char *member_name)
+{
+       MonoLoaderError *error;
+
+       /* FIXME: Store the signature as well */
+       if (mono_loader_get_last_error ())
+               return;
+
+       error = g_new0 (MonoLoaderError, 1);
+       error->kind = MONO_LOADER_ERROR_METHOD;
+       error->klass = klass;
+       error->member_name = member_name;
+
+       set_loader_error (error);
+}
+
+/*
+ * mono_loader_set_error_field_load:
+ *
+ *   Set the loader error for this thread. MEMBER_NAME should point to a string
+ * inside metadata.
+ */
+void
+mono_loader_set_error_field_load (MonoClass *klass, const char *member_name)
+{
+       MonoLoaderError *error;
+
+       /* FIXME: Store the signature as well */
+       if (mono_loader_get_last_error ())
+               return;
+
+       error = g_new0 (MonoLoaderError, 1);
+       error->kind = MONO_LOADER_ERROR_FIELD;
+       error->klass = klass;
+       error->member_name = member_name;
+
+       set_loader_error (error);
+}
+
+/*
+ * mono_loader_get_last_error:
+ *
+ *   Returns information about the last type load exception encountered by the loader, or
+ * NULL. After use, the exception should be cleared by calling mono_loader_clear_error.
+ */
+MonoLoaderError*
+mono_loader_get_last_error (void)
+{
+       return (MonoLoaderError*)TlsGetValue (loader_error_thread_id);
+}
+
+void
+mono_loader_clear_error (void)
+{
+       MonoLoaderError *ex = (MonoLoaderError*)TlsGetValue (loader_error_thread_id);
+
+       g_assert (ex);  
+
+       g_free (ex->class_name);
+       g_free (ex->assembly_name);
+       g_free (ex);
+
+       TlsSetValue (loader_error_thread_id, NULL);
 }
 
 static MonoClassField*
@@ -54,6 +192,7 @@ field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
                      MonoGenericContext *context)
 {
        MonoClass *klass;
+       MonoClassField *field;
        MonoTableInfo *tables = image->tables;
        guint32 cols[6];
        guint32 nindex, class;
@@ -72,7 +211,7 @@ field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
        class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
 
        fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
-       
+
        ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
        mono_metadata_decode_blob_size (ptr, &ptr);
        /* we may want to check the signature here... */
@@ -81,7 +220,7 @@ field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
        case MONO_MEMBERREF_PARENT_TYPEREF:
                klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
                if (!klass) {
-                       char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_REF | nindex, context);
+                       char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_REF | nindex);
                        g_warning ("Missing field %s in class %s (typeref index %d)", fname, name, nindex);
                        g_free (name);
                        return NULL;
@@ -89,7 +228,8 @@ field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
                mono_class_init (klass);
                if (retklass)
                        *retklass = klass;
-               return mono_class_get_field_from_name (klass, fname);
+               field = mono_class_get_field_from_name (klass, fname);
+               break;
        case MONO_MEMBERREF_PARENT_TYPESPEC: {
                /*guint32 bcols [MONO_TYPESPEC_SIZE];
                guint32 len;
@@ -108,12 +248,18 @@ field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
                mono_class_init (klass);
                if (retklass)
                        *retklass = klass;
-               return mono_class_get_field_from_name (klass, fname);
+               field = mono_class_get_field_from_name (klass, fname);
+               break;
        }
        default:
                g_warning ("field load from %x", class);
                return NULL;
        }
+
+       if (!field)
+               mono_loader_set_error_field_load (klass, fname);
+
+       return field;
 }
 
 MonoClassField*
@@ -154,7 +300,7 @@ mono_field_from_token (MonoImage *image, guint32 token, MonoClass **retklass,
        }
 
        mono_loader_lock ();
-       if (!field->parent->generic_class)
+       if (field && !field->parent->generic_class)
                g_hash_table_insert (image->field_cache, GUINT_TO_POINTER (token), field);
        mono_loader_unlock ();
        return field;
@@ -172,7 +318,7 @@ mono_metadata_signature_vararg_match (MonoMethodSignature *sig1, MonoMethodSigna
        for (i = 0; i < sig1->sentinelpos; i++) { 
                MonoType *p1 = sig1->params[i];
                MonoType *p2 = sig2->params[i];
-               
+
                /*if (p1->attrs != p2->attrs)
                        return FALSE;
                */
@@ -186,12 +332,46 @@ mono_metadata_signature_vararg_match (MonoMethodSignature *sig1, MonoMethodSigna
 }
 
 static MonoMethod *
-find_method (MonoClass *klass, MonoClass *ic, const char* name, MonoMethodSignature *sig)
+find_method_in_class (MonoClass *in_class, const char *name, const char *qname, const char *fqname,
+                     MonoMethodSignature *sig, MonoClass *from_class)
+{
+       int i;
+
+       mono_class_setup_methods (in_class);
+       for (i = 0; i < in_class->method.count; ++i) {
+               MonoMethod *m = in_class->methods [i];
+
+               if (!((fqname && !strcmp (m->name, fqname)) ||
+                     (qname && !strcmp (m->name, qname)) || !strcmp (m->name, name)))
+                       continue;
+
+               if (sig->call_convention == MONO_CALL_VARARG) {
+                       if (mono_metadata_signature_vararg_match (sig, mono_method_signature (m)))
+                               break;
+               } else {
+                       if (mono_metadata_signature_equal (sig, mono_method_signature (m)))
+                               break;
+               }
+       }
+
+       if (i < in_class->method.count) {
+               mono_class_setup_methods (from_class);
+               g_assert (from_class->method.count == in_class->method.count);
+               return from_class->methods [i];
+       }
+       return NULL;
+}
+
+static MonoMethod *
+find_method (MonoClass *in_class, MonoClass *ic, const char* name, MonoMethodSignature *sig, MonoClass *from_class)
 {
        int i;
        char *qname, *fqname, *class_name;
+       gboolean is_interface;
        MonoMethod *result = NULL;
 
+       is_interface = MONO_CLASS_IS_INTERFACE (in_class);
+
        if (ic) {
                class_name = mono_type_get_name_full (&ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
 
@@ -203,41 +383,32 @@ find_method (MonoClass *klass, MonoClass *ic, const char* name, MonoMethodSignat
        } else
                class_name = qname = fqname = NULL;
 
-       while (klass) {
-               MonoGenericContext *context = NULL;
+       while (in_class) {
+               g_assert (from_class);
+               result = find_method_in_class (in_class, name, qname, fqname, sig, from_class);
+               if (result)
+                       goto out;
 
-               if (klass->generic_container)
-                       context = &klass->generic_container->context;
-               else if (klass->generic_class)
-                       context = klass->generic_class->context;
-
-               mono_class_setup_methods (klass);
-               for (i = 0; i < klass->method.count; ++i) {
-                       MonoMethod *m = klass->methods [i];
+               if (name [0] == '.' && (!strcmp (name, ".ctor") || !strcmp (name, ".cctor")))
+                       break;
 
-                       if (!((fqname && !strcmp (m->name, fqname)) ||
-                             (qname && !strcmp (m->name, qname)) || !strcmp (m->name, name)))
-                               continue;
+               g_assert (from_class->interface_count == in_class->interface_count);
+               for (i = 0; i < in_class->interface_count; i++) {
+                       MonoClass *ic = in_class->interfaces [i];
+                       MonoClass *from_ic = from_class->interfaces [i];
 
-                       if (sig->call_convention == MONO_CALL_VARARG) {
-                               if (mono_metadata_signature_vararg_match (sig, mono_method_signature (m))) {
-                                       result = m;
-                                       goto out;
-                               }
-                       } else {
-                               MonoMethodSignature *msig = mono_method_signature_full (m, context);
-                               if (mono_metadata_signature_equal (sig, msig)) {
-                                       result = m;
-                                       goto out;
-                               }
-                       }
+                       result = find_method_in_class (ic, name, qname, fqname, sig, from_ic);
+                       if (result)
+                               goto out;
                }
 
-               if (name [0] == '.' && (strcmp (name, ".ctor") == 0 || strcmp (name, ".cctor") == 0))
-                       break;
-
-               klass = klass->parent;
+               in_class = in_class->parent;
+               from_class = from_class->parent;
        }
+       g_assert (!in_class == !from_class);
+
+       if (is_interface)
+               result = find_method_in_class (mono_defaults.object_class, name, qname, fqname, sig, mono_defaults.object_class);
 
  out:
        g_free (class_name);
@@ -246,6 +417,53 @@ find_method (MonoClass *klass, MonoClass *ic, const char* name, MonoMethodSignat
        return result;
 }
 
+static MonoMethodSignature*
+inflate_generic_signature (MonoImage *image, MonoMethodSignature *sig, MonoGenericContext *context)
+{
+       MonoMethodSignature *res;
+       gboolean is_open;
+       int i;
+
+       if (!context)
+               return sig;
+
+       res = mono_metadata_signature_alloc (image, sig->param_count);
+       res->ret = mono_class_inflate_generic_type (sig->ret, context);
+       is_open = mono_class_is_open_constructed_type (res->ret);
+       for (i = 0; i < sig->param_count; ++i) {
+               res->params [i] = mono_class_inflate_generic_type (sig->params [i], context);
+               if (!is_open)
+                       is_open = mono_class_is_open_constructed_type (res->params [i]);
+       }
+       res->hasthis = sig->hasthis;
+       res->explicit_this = sig->explicit_this;
+       res->call_convention = sig->call_convention;
+       res->pinvoke = sig->pinvoke;
+       res->generic_param_count = sig->generic_param_count;
+       res->sentinelpos = sig->sentinelpos;
+       res->has_type_parameters = is_open;
+       res->is_inflated = 1;
+       return res;
+}
+
+static MonoMethodHeader*
+inflate_generic_header (MonoMethodHeader *header, MonoGenericContext *context)
+{
+       MonoMethodHeader *res;
+       int i;
+       res = g_malloc0 (sizeof (MonoMethodHeader) + sizeof (gpointer) * header->num_locals);
+       res->code = header->code;
+       res->code_size = header->code_size;
+       res->max_stack = header->max_stack;
+       res->num_clauses = header->num_clauses;
+       res->init_locals = header->init_locals;
+       res->num_locals = header->num_locals;
+       res->clauses = header->clauses;
+       for (i = 0; i < header->num_locals; ++i)
+               res->locals [i] = mono_class_inflate_generic_type (header->locals [i], context);
+       return res;
+}
+
 /*
  * token is the method_ref or method_def token used in a call IL instruction.
  */
@@ -283,10 +501,11 @@ mono_method_get_signature_full (MonoMethod *method, MonoImage *image, guint32 to
        mono_loader_unlock ();
        if (!sig) {
                mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
-       
+
                ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
                mono_metadata_decode_blob_size (ptr, &ptr);
-               sig = mono_metadata_parse_method_signature_full (image, context, 0, ptr, NULL);
+               sig = mono_metadata_parse_method_signature_full (
+                       image, context ? context->container : NULL, 0, ptr, NULL);
 
                mono_loader_lock ();
                prev_sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (token));
@@ -300,7 +519,7 @@ mono_method_get_signature_full (MonoMethod *method, MonoImage *image, guint32 to
                mono_loader_unlock ();
        }
 
-       sig = mono_class_inflate_generic_signature (image, sig, context);
+       sig = inflate_generic_signature (image, sig, context);
 
        return sig;
 }
@@ -312,15 +531,13 @@ mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
 }
 
 static MonoMethod *
-method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *context)
+method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typespec_context)
 {
        MonoClass *klass = NULL;
        MonoMethod *method = NULL;
        MonoTableInfo *tables = image->tables;
        guint32 cols[6];
        guint32 nindex, class;
-       MonoGenericClass *gclass = NULL;
-       MonoGenericContainer *container = NULL;
        const char *mname;
        MonoMethodSignature *sig;
        const char *ptr;
@@ -337,16 +554,19 @@ method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *contex
        case MONO_MEMBERREF_PARENT_TYPEREF:
                klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
                if (!klass) {
-                       char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_REF | nindex, context);
+                       char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_REF | nindex);
                        g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
                        g_free (name);
                        return NULL;
                }
                break;
        case MONO_MEMBERREF_PARENT_TYPESPEC:
-               klass = mono_class_get_full (image, MONO_TOKEN_TYPE_SPEC | nindex, context);
+               /*
+                * Parse the TYPESPEC in the parent's context.
+                */
+               klass = mono_class_get_full (image, MONO_TOKEN_TYPE_SPEC | nindex, typespec_context);
                if (!klass) {
-                       char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_SPEC | nindex, context);
+                       char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_SPEC | nindex);
                        g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
                        g_free (name);
                        return NULL;
@@ -355,7 +575,7 @@ method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *contex
        case MONO_MEMBERREF_PARENT_TYPEDEF:
                klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | nindex);
                if (!klass) {
-                       char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_DEF | nindex, context);
+                       char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_DEF | nindex);
                        g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
                        g_free (name);
                        return NULL;
@@ -368,26 +588,19 @@ method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *contex
                g_assert_not_reached ();
        }
        g_assert (klass);
-
-       if (klass->generic_class) {
-               gclass = klass->generic_class;
-               klass = gclass->container_class;
-       }
-       if (klass->generic_container)
-               container = klass->generic_container;
        mono_class_init (klass);
 
        ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
        mono_metadata_decode_blob_size (ptr, &ptr);
-       sig = mono_metadata_parse_method_signature_full (image, (MonoGenericContext *) container, 0, ptr, NULL);
+
+       sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
 
        switch (class) {
        case MONO_MEMBERREF_PARENT_TYPEREF:
-               method = find_method (klass, NULL, mname, sig);
-               if (!method)
-                       g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, mono_class_get_name (klass));
-               mono_metadata_free_method_signature (sig);
+       case MONO_MEMBERREF_PARENT_TYPEDEF:
+               method = find_method (klass, NULL, mname, sig, klass);
                break;
+
        case MONO_MEMBERREF_PARENT_TYPESPEC: {
                MonoType *type;
                MonoMethod *result;
@@ -395,19 +608,15 @@ method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *contex
                type = &klass->byval_arg;
 
                if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
-                       method = find_method (klass, NULL, mname, sig);
-                       if (!method)
-                               g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, mono_class_get_name (klass));
-                       else if (klass->generic_class && (klass != method->klass))
-                               method = mono_class_inflate_generic_method (
-                                       method, klass->generic_class->context, klass);
-                       mono_metadata_free_method_signature (sig);
+                       MonoClass *in_class = klass->generic_class ? klass->generic_class->container_class : klass;
+                       method = find_method (in_class, NULL, mname, sig, klass);
                        break;
                }
 
                result = (MonoMethod *)g_new0 (MonoMethodPInvoke, 1);
-               result->klass = mono_class_get (image, MONO_TOKEN_TYPE_SPEC | nindex);
+               result->klass = klass;
                result->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
+               result->flags = METHOD_ATTRIBUTE_PUBLIC;
                result->signature = sig;
                result->name = mname;
 
@@ -415,7 +624,7 @@ method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *contex
                        /* we special-case this in the runtime. */
                        return result;
                }
-               
+
                if (!strcmp (mname, "Set")) {
                        g_assert (sig->hasthis);
                        g_assert (type->data.array->rank + 1 == sig->param_count);
@@ -440,19 +649,27 @@ method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *contex
                g_assert_not_reached ();
                break;
        }
-       case MONO_MEMBERREF_PARENT_TYPEDEF:
-               method = find_method (klass, NULL, mname, sig);
-               if (!method)
-                       g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, mono_class_get_name (klass));
-               mono_metadata_free_method_signature (sig);
-               break;
        default:
                g_error ("Memberref parent unknown: class: %d, index %d", class, nindex);
                g_assert_not_reached ();
        }
 
-       if (gclass)
-               method = mono_class_inflate_generic_method (method, gclass->context, gclass->klass);
+       if (!method) {
+               char *msig = mono_signature_get_desc (sig, FALSE);
+               GString *s = g_string_new (mname);
+               if (sig->generic_param_count)
+                       g_string_append_printf (s, "<[%d]>", sig->generic_param_count);
+               g_string_append_printf (s, "(%s)", msig);
+               g_free (msig);
+               msig = g_string_free (s, FALSE);
+
+               g_warning (
+                       "Missing method %s::%s in assembly %s, referenced in assembly %s",
+                       mono_type_get_name (&klass->byval_arg), msig, klass->image->name, image->name);
+               g_free (msig);
+               mono_loader_set_error_method_load (klass, mname);
+       }
+       mono_metadata_free_method_signature (sig);
 
        return method;
 }
@@ -467,52 +684,89 @@ method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 i
        MonoGenericContainer *container = NULL;
        const char *ptr;
        guint32 cols [MONO_METHODSPEC_SIZE];
-       guint32 token, param_count;
+       guint32 token, nindex, param_count;
 
        mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
        token = cols [MONO_METHODSPEC_METHOD];
-       if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF)
-               token = MONO_TOKEN_METHOD_DEF | (token >> MONO_METHODDEFORREF_BITS);
-       else
-               token = MONO_TOKEN_MEMBER_REF | (token >> MONO_METHODDEFORREF_BITS);
-
-       method = mono_get_method (image, token, NULL);
+       nindex = token >> MONO_METHODDEFORREF_BITS;
 
        ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
-       
+
        mono_metadata_decode_value (ptr, &ptr);
        ptr++;
        param_count = mono_metadata_decode_value (ptr, &ptr);
-
        g_assert (param_count);
-       if (method->is_inflated)
-               container = ((MonoMethodNormal *) ((MonoMethodInflated *) method)->declaring)->generic_container;
+
+       /*
+        * Be careful with the two contexts here:
+        *
+        * ----------------------------------------
+        * class Foo<S> {
+        *   static void Hello<T> (S s, T t) { }
+        *
+        *   static void Test<U> (U u) {
+        *     Foo<U>.Hello<string> (u, "World");
+        *   }
+        * }
+        * ----------------------------------------
+        *
+        * Let's assume we're currently JITing Foo<int>.Test<long>
+        * (ie. `S' is instantiated as `int' and `U' is instantiated as `long').
+        *
+        * The call to Hello() is encoded with a MethodSpec with a TypeSpec as parent
+        * (MONO_MEMBERREF_PARENT_TYPESPEC).
+        *
+        * The TypeSpec is encoded as `Foo<!!0>', so we need to parse it in the current
+        * context (S=int, U=long) to get the correct `Foo<long>'.
+        * 
+        * After that, we parse the memberref signature in the new context
+        * (S=int, T=uninstantiated) and get the open generic method `Foo<long>.Hello<T>'.
+        *
+        */
+       if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF)
+               method = mono_get_method_full (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, context);
        else
-               container = ((MonoMethodNormal *) method)->generic_container;
-       g_assert (container && container->is_method);
-
-       if (context) {
-               g_assert (context->container);
-               container->parent = context->container;
-               if (container->parent->is_method)
-                       container->parent = container->parent->parent;
-       }
+               method = method_from_memberref (image, nindex, context);
+
+       method = mono_get_inflated_method (method);
+
+       container = method->generic_container;
+       g_assert (container);
 
        gmethod = g_new0 (MonoGenericMethod, 1);
        gmethod->generic_class = method->klass->generic_class;
        gmethod->container = container;
 
-       if (context && context->gmethod)
-               new_context = context->gmethod->container;
-       else if (context && context->gclass)
-               new_context = context->gclass->container_class->generic_container;
-       else
-               new_context = context ? context->container : NULL;
+       new_context = g_new0 (MonoGenericContext, 1);
+       new_context->container = container;
+       new_context->gmethod = gmethod;
+       if (container->parent)
+               new_context->gclass = container->parent->context.gclass;
 
-       gmethod->inst = mono_metadata_parse_generic_inst (
-               image, new_context, param_count, ptr, &ptr);
+       /*
+        * When parsing the methodspec signature, we're in the old context again:
+        *
+        * ----------------------------------------
+        * class Foo {
+        *   static void Hello<T> (T t) { }
+        *
+        *   static void Test<U> (U u) {
+        *     Foo.Hello<U> (u);
+        *   }
+        * }
+        * ----------------------------------------
+        *
+        * Let's assume we're currently JITing "Foo.Test<float>".
+        *
+        * In this case, we already parsed the memberref as "Foo.Hello<T>" and the methodspec
+        * signature is "<!!0>".  This means that we must instantiate the method type parameter
+        * `T' from the new method with the method type parameter `U' from the current context;
+        * ie. instantiate the method as `Foo.Hello<float>.
+        */
 
-       if (context)
+       gmethod->inst = mono_metadata_parse_generic_inst (image, context ? context->container : NULL, param_count, ptr, &ptr);
+
+       if (context && gmethod->inst->is_open)
                gmethod->inst = mono_metadata_inflate_generic_inst (gmethod->inst, context);
 
        if (!container->method_hash)
@@ -522,32 +776,18 @@ method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 i
        inflated = g_hash_table_lookup (container->method_hash, gmethod);
        if (inflated) {
                g_free (gmethod);
+               g_free (new_context);
                return inflated;
        }
 
-       if (!context) {
-               new_context = g_new0 (MonoGenericContext, 1);
-               new_context->container = container;
-               new_context->gmethod = gmethod;
-
-               context = new_context;
-       } else {
-               new_context = g_new0 (MonoGenericContext, 1);
-               new_context->container = container;
-               new_context->gmethod = gmethod;
-               new_context->gclass = context->gclass;
-
-               context = new_context;
-       }
+       context = new_context;
 
        mono_stats.generics_metadata_size += sizeof (MonoGenericMethod) +
                sizeof (MonoGenericContext) + param_count * sizeof (MonoType);
 
-       inflated = mono_class_inflate_generic_method (method, context, NULL);
+       inflated = mono_class_inflate_generic_method_full (method, method->klass, new_context);
        g_hash_table_insert (container->method_hash, gmethod, inflated);
 
-       if (new_context)
-               context->gclass = inflated->klass->generic_class;
        return inflated;
 }
 
@@ -579,7 +819,7 @@ mono_dllmap_lookup_hash (GHashTable *dll_map, const char *dll, const char* func,
                return 0;
        }
        *rdll = map->target? map->target: dll;
-               
+
        for (tmp = map->next; tmp; tmp = tmp->next) {
                if (strcmp (func, tmp->name) == 0) {
                        *rfunc = tmp->name;
@@ -702,11 +942,11 @@ mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char
        /* we allow a special name to dlopen from the running process namespace */
        if (strcmp (new_scope, "__Internal") == 0)
                gmodule = g_module_open (NULL, G_MODULE_BIND_LAZY);
-               
+
        /*
         * Try loading the module using a variety of names
         */
-       for (i = 0; i < 3; ++i) {
+       for (i = 0; i < 4; ++i) {
                switch (i) {
                case 0:
                        /* Try the original name */
@@ -721,13 +961,26 @@ mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char
                        else
                                continue;
                        break;
-               default:
+               case 2:
                        if (strstr (new_scope, "lib") != new_scope) {
                                file_name = g_strdup_printf ("lib%s", new_scope);
                        }
                        else
                                continue;
                        break;
+               default:
+#ifndef PLATFORM_WIN32
+                       if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
+                           !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
+                           !g_ascii_strcasecmp ("user32", new_scope) ||
+                           !g_ascii_strcasecmp ("kernel", new_scope)) {
+                               file_name = g_strdup ("libMonoSupportW.so");
+                       } else
+#endif
+                                   continue;
+#ifndef PLATFORM_WIN32
+                       break;
+#endif
                }
 
                if (!gmodule) {
@@ -825,6 +1078,10 @@ mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char
 #ifdef PLATFORM_WIN32
                                                if (mangle_charset == 0)
                                                        mangled_name = g_strconcat (import, "W", NULL);
+#else
+                                               /* Try the mangled name last */
+                                               if (mangle_charset == 1)
+                                                       mangled_name = g_strconcat (import, "A", NULL);
 #endif
                                                break;
                                        case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
@@ -883,6 +1140,17 @@ mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char
        return piinfo->addr;
 }
 
+MonoGenericMethod *
+mono_get_shared_generic_method (MonoGenericContainer *container)
+{
+       MonoGenericMethod *gmethod = g_new0 (MonoGenericMethod, 1);
+       gmethod->container = container;
+       gmethod->generic_class = container->context.gclass;
+       gmethod->inst = mono_get_shared_generic_inst (container);
+
+       return gmethod;
+}
+
 static MonoMethod *
 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
                            MonoGenericContext *context)
@@ -900,11 +1168,6 @@ mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
                return mono_lookup_dynamic_token (image, token);
 
        if (table != MONO_TABLE_METHOD) {
-               MonoGenericContainer *generic_container = NULL;
-               if (context) {
-                       g_assert (context->container);
-                       generic_container = context->container;
-               }
                if (table == MONO_TABLE_METHODSPEC)
                        return method_from_methodspec (image, context, idx);
                if (table != MONO_TABLE_MEMBERREF)
@@ -919,10 +1182,15 @@ mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
 
        if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
            (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
-               result = (MonoMethod *)g_new0 (MonoMethodPInvoke, 1);
-       else 
-               result = (MonoMethod *)g_new0 (MonoMethodNormal, 1);
-       
+               result = (MonoMethod *)mono_mempool_alloc0 (image->mempool, sizeof (MonoMethodPInvoke));
+       else
+               result = (MonoMethod *)mono_mempool_alloc0 (image->mempool, sizeof (MonoMethodNormal));
+
+       if (!klass) {
+               guint32 type = mono_metadata_typedef_from_method (image, token);
+               klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
+       }
+
        result->slot = -1;
        result->klass = klass;
        result->flags = cols [2];
@@ -930,30 +1198,28 @@ mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
        result->token = token;
        result->name = mono_metadata_string_heap (image, cols [3]);
 
-       if (klass)
-               container = klass->generic_container;
+       container = klass->generic_container;
+       generic_container = mono_metadata_load_generic_params (image, token, container);
+       if (generic_container) {
+               MonoGenericContext *context = &generic_container->context;
+               if (container)
+                       context->gclass = container->context.gclass;
+               context->gmethod = mono_get_shared_generic_method (generic_container);
+               mono_metadata_load_generic_param_constraints (image, token, generic_container);
 
-       if (!(cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
-           (!(cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) || cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
-               generic_container = mono_metadata_load_generic_params (image, token, container);
-               if (generic_container)
-                       container = generic_container;
+               for (i = 0; i < generic_container->type_argc; i++) {
+                       generic_container->type_params [i].method = result;
+
+                       mono_class_from_generic_parameter (
+                               &generic_container->type_params [i], image, TRUE);
+               }
+
+               container = generic_container;
        }
 
        if (!sig) /* already taken from the methodref */
                sig = mono_metadata_blob_heap (image, cols [4]);
        size = mono_metadata_decode_blob_size (sig, &sig);
-       
-       /* there are generic params, or a container. FIXME: be lazy here for generics*/
-       if (* sig & 0x10 || container)
-               result->signature = mono_metadata_parse_method_signature_full (
-                   image, (MonoGenericContext *) container, idx, sig, NULL);
-
-
-       if (!result->klass) {
-               guint32 type = mono_metadata_typedef_from_method (image, token);
-               result->klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
-       }
 
        if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
                if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
@@ -961,46 +1227,22 @@ mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
        } else if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) && (!(cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE))) {
                MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
                MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
-               
+
                piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
                piinfo->piflags = mono_metadata_decode_row_col (im, piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
-       } else {
-               if (result->signature && result->signature->generic_param_count) {
-                       MonoMethodSignature *sig = result->signature;
-
-                       for (i = 0; i < sig->generic_param_count; i++) {
-                               generic_container->type_params [i].method = result;
-
-                               mono_class_from_generic_parameter (
-                                       &generic_container->type_params [i], image, TRUE);
-                       }
-
-                       if (sig->ret->type == MONO_TYPE_MVAR) {
-                               int num = sig->ret->data.generic_param->num;
-                               sig->ret->data.generic_param = &generic_container->type_params [num];
-                       }
+       }
 
-                       for (i = 0; i < sig->param_count; i++) {
-                               MonoType *t = sig->params [i];
-                               if (t->type == MONO_TYPE_MVAR) {
-                                       int num = t->data.generic_param->num;
-                                       sig->params [i]->data.generic_param = &generic_container->type_params [num];
-                               }
-                       }
-               }
-               
-               /* FIXME: lazyness for generics too, but how? */
-               if (!result->klass->dummy && !(result->flags & METHOD_ATTRIBUTE_ABSTRACT) &&
-                   !(result->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) && container) {
-                       gpointer loc = mono_image_rva_map (image, cols [0]);
-                       g_assert (loc);
-                       ((MonoMethodNormal *) result)->header = mono_metadata_parse_mh_full (
-                               image, (MonoGenericContext *) container, loc);
-               }
-               
-               ((MonoMethodNormal *) result)->generic_container = generic_container;
+       /* FIXME: lazyness for generics too, but how? */
+       if (!result->klass->dummy && !(result->flags & METHOD_ATTRIBUTE_ABSTRACT) &&
+           !(cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
+           !(result->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) && container) {
+               gpointer loc = mono_image_rva_map (image, cols [0]);
+               g_assert (loc);
+               ((MonoMethodNormal *) result)->header = mono_metadata_parse_mh_full (image, container, loc);
        }
 
+       result->generic_container = generic_container;
+
        return result;
 }
 
@@ -1037,13 +1279,19 @@ mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
        return result;
 }
 
+/**
+ * mono_get_method_constrained:
+ *
+ * This is used when JITing the `constrained.' opcode.
+ */
 MonoMethod *
 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
                             MonoGenericContext *context)
 {
        MonoMethod *method, *result;
        MonoClass *ic = NULL;
-       MonoGenericClass *gclass = NULL;
+       MonoGenericContext *class_context = NULL, *method_context = NULL;
+       MonoMethodSignature *sig;
 
        mono_loader_lock ();
 
@@ -1055,20 +1303,32 @@ mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constra
 
        mono_class_init (constrained_class);
        method = mono_get_inflated_method (method);
+       sig = mono_method_signature (method);
+
+       if (method->is_inflated && sig->generic_param_count) {
+               MonoMethodInflated *imethod = (MonoMethodInflated *) method;
+               sig = mono_method_signature (imethod->declaring);
+               method_context = imethod->context;
+       }
 
        if ((constrained_class != method->klass) && (method->klass->interface_id != 0))
                ic = method->klass;
 
        if (constrained_class->generic_class)
-               gclass = constrained_class->generic_class;
+               class_context = constrained_class->generic_class->context;
 
-       result = find_method (constrained_class, ic, method->name, mono_method_signature (method));
-       if (!result)
-               g_warning ("Missing method %s in assembly %s token %x", method->name,
-                          image->name, token);
+       result = find_method (constrained_class, ic, method->name, sig, constrained_class);
+       if (!result) {
+               g_warning ("Missing method %s.%s.%s in assembly %s token %x", method->klass->name_space,
+                          method->klass->name, method->name, image->name, token);
+               mono_loader_unlock ();
+               return NULL;
+       }
 
-       if (gclass)
-               result = mono_class_inflate_generic_method (result, gclass->context, gclass->klass);
+       if (class_context)
+               result = mono_class_inflate_generic_method (result, class_context);
+       if (method_context)
+               result = mono_class_inflate_generic_method (result, method_context);
 
        mono_loader_unlock ();
        return result;
@@ -1083,7 +1343,7 @@ mono_free_method  (MonoMethod *method)
                 * locals are shared.
                 */
                /* mono_metadata_free_method_signature (method->signature); */
-               g_free (method->signature);
+               /* g_free (method->signature); */
        }
 
        if (method->dynamic) {
@@ -1095,13 +1355,14 @@ mono_free_method  (MonoMethod *method)
                g_free (mw->method_data);
        }
 
-       if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && ((MonoMethodNormal *)method)->header) {
+       if (method->dynamic && !(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && ((MonoMethodNormal *)method)->header) {
                /* FIXME: Ditto */
                /* mono_metadata_free_mh (((MonoMethodNormal *)method)->header); */
                g_free (((MonoMethodNormal*)method)->header);
        }
 
-       g_free (method);
+       if (method->dynamic)
+               g_free (method);
 }
 
 void
@@ -1268,7 +1529,7 @@ mono_method_has_marshal_info (MonoMethod *method)
        if (idx > 0) {
                guint32 cols [MONO_PARAM_SIZE];
                guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
-               
+
                if (idx + 1 < methodt->rows)
                        lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
                else
@@ -1353,47 +1614,92 @@ mono_loader_unlock (void)
        LeaveCriticalSection (&loader_mutex);
 }
 
-MonoMethodSignature* 
+MonoMethodSignature*
 mono_method_signature (MonoMethod *m)
-{
-       return mono_method_signature_full (m, NULL);
-}
-
-MonoMethodSignature* 
-mono_method_signature_full (MonoMethod *m, MonoGenericContext *context)
 {
        int idx;
        int size;
        MonoImage* img;
        const char *sig;
-       
+       gboolean can_cache_signature;
+       MonoGenericContainer *container;
+       int *pattrs;
+
        if (m->signature)
                return m->signature;
-               
+
        mono_loader_lock ();
-       
+
        if (m->signature) {
                mono_loader_unlock ();
                return m->signature;
        }
-       
+
+       if (m->is_inflated) {
+               MonoMethodInflated *imethod = (MonoMethodInflated *) m;
+               MonoMethodSignature *signature;
+               /* the lock is recursive */
+               signature = mono_method_signature (imethod->declaring);
+               m->signature = inflate_generic_signature (imethod->declaring->klass->image, signature, imethod->context);
+               mono_loader_unlock ();
+               return m->signature;
+       }
+
        g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
        idx = mono_metadata_token_index (m->token);
        img = m->klass->image;
-       
+
        sig = mono_metadata_blob_heap (img, mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
-       size = mono_metadata_decode_blob_size (sig, &sig);
-       
-       m->signature = mono_metadata_parse_method_signature_full (img, context, idx, sig, NULL);
-       
+
+       g_assert (!m->klass->generic_class);
+       container = m->generic_container;
+       if (!container)
+               container = m->klass->generic_container;
+
+       /* Generic signatures depend on the container so they cannot be cached */
+       /* icall/pinvoke signatures cannot be cached cause we modify them below */
+       can_cache_signature = !(m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && !(m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && !container;
+
+       /* If the method has parameter attributes, that can modify the signature */
+       pattrs = mono_metadata_get_param_attrs (img, idx);
+       if (pattrs) {
+               can_cache_signature = FALSE;
+               g_free (pattrs);
+       }
+
+       if (can_cache_signature)
+               m->signature = g_hash_table_lookup (img->method_signatures, sig);
+
+       if (!m->signature) {
+               const char *sig_body;
+
+               size = mono_metadata_decode_blob_size (sig, &sig_body);
+
+               m->signature = mono_metadata_parse_method_signature_full (img, container, idx, sig_body, NULL);
+
+               if (can_cache_signature)
+                       g_hash_table_insert (img->method_signatures, (gpointer)sig, m->signature);
+       }
+
+       /* Verify metadata consistency */
+       if (m->signature->generic_param_count) {
+               if (!container || !container->is_method)
+                       g_error ("Signature claims method has generic parameters, but generic_params table says it doesn't");
+               if (container->type_argc != m->signature->generic_param_count)
+                       g_error ("Inconsistent generic parameter count.  Signature says %d, generic_params table says %d",
+                                m->signature->generic_param_count, container->type_argc);
+       } else if (container && container->is_method && container->type_argc)
+               g_error ("generic_params table claims method has generic parameters, but signature says it doesn't");
+
        if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
                m->signature->pinvoke = 1;
        else if ((m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && (!(m->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE))) {
                MonoCallConvention conv = 0;
                MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
                m->signature->pinvoke = 1;
-               
+
                switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
+               case 0: /* no call conv, so using default */
                case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
                        conv = MONO_CALL_DEFAULT;
                        break;
@@ -1412,12 +1718,12 @@ mono_method_signature_full (MonoMethod *m, MonoGenericContext *context)
                case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
                case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
                default:
-                       g_warning ("unsupported calling convention");
+                       g_warning ("unsupported calling convention : 0x%04x", piinfo->piflags);
                        g_assert_not_reached ();
-               }       
+               }
                m->signature->call_convention = conv;
        }
-       
+
        mono_loader_unlock ();
        return m->signature;
 }
@@ -1440,7 +1746,7 @@ mono_method_get_token (MonoMethod *method)
        return method->token;
 }
 
-MonoMethodHeader* 
+MonoMethodHeader*
 mono_method_get_header (MonoMethod *method)
 {
        int idx;
@@ -1448,34 +1754,44 @@ mono_method_get_header (MonoMethod *method)
        MonoImage* img;
        gpointer loc;
        MonoMethodNormal* mn = (MonoMethodNormal*) method;
-       
+
+       if (method->klass->dummy || (method->flags & METHOD_ATTRIBUTE_ABSTRACT) || (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) || (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) || (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
+               return NULL;
+
 #ifdef G_LIKELY
        if (G_LIKELY (mn->header))
 #else
        if (mn->header)
 #endif
                return mn->header;
-       
-       if (method->klass->dummy || (method->flags & METHOD_ATTRIBUTE_ABSTRACT) || (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) || (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) || (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
-               return NULL;
-       
+
        mono_loader_lock ();
-       
+
        if (mn->header) {
                mono_loader_unlock ();
                return mn->header;
        }
-       
+
+       if (method->is_inflated) {
+               MonoMethodInflated *imethod = (MonoMethodInflated *) method;
+               MonoMethodHeader *header;
+               /* the lock is recursive */
+               header = mono_method_get_header (imethod->declaring);
+               mn->header = inflate_generic_header (header, imethod->context);
+               mono_loader_unlock ();
+               return mn->header;
+       }
+
        g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
        idx = mono_metadata_token_index (method->token);
        img = method->klass->image;
        rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
        loc = mono_image_rva_map (img, rva);
-       
+
        g_assert (loc);
-       
-       mn->header = mono_metadata_parse_mh_full (img, (MonoGenericContext *) mn->generic_container, loc);
-       
+
+       mn->header = mono_metadata_parse_mh_full (img, method->generic_container, loc);
+
        mono_loader_unlock ();
        return mn->header;
 }
@@ -1496,6 +1812,9 @@ mono_method_get_index (MonoMethod *method) {
        MonoClass *klass = method->klass;
        int i;
 
+       if (method->token)
+               return mono_metadata_token_index (method->token);
+
        mono_class_setup_methods (klass);
        for (i = 0; i < klass->method.count; ++i) {
                if (method == klass->methods [i])