Metadata memory management -------------------------- Most metadata structures have a lifetime which is equal to the MonoImage where they are loaded from. These structures should be allocated from the memory pool of the corresponding MonoImage. The memory pool is protected by the loader lock. Examples of metadata structures in this category: - MonoClass - MonoMethod - MonoType Memory owned by these structures should be allocated from the image mempool as well. Examples include: klass->methods, klass->fields, method->signature etc. Generics complicates things. A generic class could have many instantinations where the generic arguments are from different assemblies. Where should we allocate memory for instantinations ? We can allocate from the mempool of the image which contains the generic type definition, but that would mean that the instantinations would remain in memory even after the assemblies containing their type arguments are unloaded, leading to a memory leak. Therefore, we do the following: - data structures representing the generic definitions are allocated from the image mempool as usual. These include: - generic class definition (MonoGenericClass->container_class) - generic method definitions - type parameters (MonoGenericParam) - data structures representing inflated classes/images are allocated from the heap. These structures are kept in a cache, indexed by type arguments of the instantinations. When an assembly is unloaded, this cache is searched and all instantinations referencing types from the assembly are freed. This is done by mono_metadata_clean_for_image () in metadata.c. The structures handled this way include: - MonoGenericClass - MonoGenericInst - inflated MonoMethods