In .:
[mono.git] / docs / memory-management.txt
1 Metadata memory management
2 --------------------------
3
4 Most metadata structures have a lifetime which is equal to the MonoImage where they are
5 loaded from. These structures should be allocated from the memory pool of the 
6 corresponding MonoImage. The memory pool is protected by the loader lock. 
7 Examples of metadata structures in this category:
8 - MonoClass
9 - MonoMethod
10 - MonoType
11 Memory owned by these structures should be allocated from the image mempool as well.
12 Examples include: klass->methods, klass->fields, method->signature etc.
13
14 Generics complicates things. A generic class could have many instantinations where the
15 generic arguments are from different assemblies. Where should we allocate memory for 
16 instantinations ? We can allocate from the mempool of the image which contains the 
17 generic type definition, but that would mean that the instantinations would remain in
18 memory even after the assemblies containing their type arguments are unloaded, leading
19 to a memory leak. Therefore, we do the following:
20 - data structures representing the generic definitions are allocated from the image
21   mempool as usual. These include:
22   - generic class definition (MonoGenericClass->container_class)
23   - generic method definitions
24   - type parameters (MonoGenericParam)
25 - data structures representing inflated classes/images are allocated from the heap. These
26   structures are kept in a cache, indexed by type arguments of the instantinations. When
27   an assembly is unloaded, this cache is searched and all instantinations referencing
28   types from the assembly are freed. This is done by mono_metadata_clean_for_image ()
29   in metadata.c. The structures handled this way include:
30   - MonoGenericClass
31   - MonoGenericInst
32   - inflated MonoMethods