Where does the CLR allocate a local memory pool?

ECMA-335, I.12.3.2.4, states the following:

Part of each method state is a local memory pool. Memory can be explicitly allocated from the local memory pool using the localloc . All memory in the local memory pool is recovered when the method exits, and this is the only way to restore the memory of the memory pool (there is no instruction provided by the free local memory that was allocated during the call to this method). The local memory pool is used to allocate objects whose type or size is unknown at compile time and which the programmer does not want to allocate in the managed heap. Since the local memory pool cannot be reduced during the entire life cycle of a method, the language implementation cannot use the local memory pool to allocate shared memory.

Where does the CLR allocate this memory pool? This is a managed heap, stack stack, etc.

+6
source share
1 answer

This is all intentionally vague because it is a strong implementation detail that the CLI specification does not want to nail. He looks through the cracks in the MSDN article for Opcodes.Localloc , though:

A StackOverflowException is thrown if there is not enough memory to service the request.

Only one way that you ever get SOE: you need to allocate from the stack.

C # is less shy when it is distributed, it uses the stackalloc keyword. Program Example:

 class Program { static unsafe void Main(string[] args) { int* p = stackalloc int[42]; } } 

Produces this IL:

 .method private hidebysig static void Main(string[] args) cil managed { .entrypoint // Code size 9 (0x9) .maxstack 8 IL_0000: ldc.i4.s 42 IL_0002: conv.u IL_0003: ldc.i4.4 IL_0004: mul.ovf.un IL_0005: localloc // <=== Here IL_0007: pop IL_0008: ret } // end of method Program::Main 

Which creates this machine code at runtime:

 02E42620 push ebp 02E42621 mov ebp,esp 02E42623 sub esp,8 02E42626 mov dword ptr [ebp-4],esp 02E42629 mov dword ptr [ebp-8],6A029823h 02E42630 mov eax,esp 02E42632 test dword ptr [esp],esp 02E42635 sub eax,0A8h // <=== Here 02E4263A mov esp,eax 02E4263C mov dword ptr [ebp-4],esp 02E4263F cmp dword ptr [ebp-8],6A029823h 02E42646 je 02E4264D 02E42648 call 730CA5C0 02E4264D lea esp,[ebp] 02E42650 pop ebp 02E42651 ret 

The sub eax,0A8h instruction sub eax,0A8h subtracts 0xa8 = 168 = 42x4 bytes from the ESP register (stack pointer), the mov esp,eax command sets the stack pointer. So yes, it definitely comes from the stack.

+8
source

Source: https://habr.com/ru/post/956822/


All Articles