Learn EVM Opcodes VIII
Time to learn the bytecode introduction block of the all solidity contracts. What is the mystery behind this fucking 3 opcodes ?
PUSH1 0x80
PUSH1 0x40
MSTORE
When you start to analyse a contract, you will see that the opcodes start as follows.
PUSH1 0x80
PUSH1 0x40
MSTORE
We can interpret this opcode block, isn’t it ?
Start saving to memory from the 64th byte (0x40) and the first value to be saved is 128 (0x80).
Well, 0x80 (what does the value 128 do) tells us that we have 4 slots.
{ Since each slot is 32 bytes; 128/32= 4 slots of memory initially }
Therefore, we learn what the size of the memory. You can use this EVM Playground for analysing the code.
The first operation is to save the value 0x80 in the free memory pointer location (0x40). You can watch the process from this playground.
The second operation is to calculate how much space is required for a 5-element array. If 32 bytes are allocated for each array element, we need to allocate 160 bytes (0xa0) for 5 elements.
free memory pointer (0x80) + space for array (0xa0) = new free memory pointer
Our new value will be 120 in hex and 288 in decimal.
At the moment only the number showing how much memory will grow. Memory hasn’t expanded yet.
Hex 120 is equal to 288 decimal.
We added an array of 5 elements to our contract.
Since each array value is 32 bytes, the existing memory has expanded by 160 bytes.
We specified this expansion at location 0x40 with the value 120 (hex), which is the sum of 80(hex) + 160(hex).
80(hex) =128 byte
128 byte / 32= We had 4 slot
New 5 byte = 160 byte
160 bytes / 32= 5 new slots
128 byte + 160 byte = 288 byte (120 hex )
288 byte / 32= We have 9 slots
Yes now Memory has expanded.
We try to execute the new code and we analyze in directly in remix screen.
In this example, we defined an array with 5 elements and assigned a value to each element. When you run this code on Remix and debug it, the view of the memory will be as follows.
We had opened 5 new slots, now we have made assignments to each slot.