3

I have been trying to understand how assembly code works,spending lots of hours, but I could not.

Please help me

Basically, I am digging into a proxy contract, and I do not really understand calldatacopy and delegatecall.

Would you please explain it ?

fallback() external { bytes4 sig; assembly { sig := calldataload(0) } uint len = _sizes[sig]; address target = _dest; assembly { calldatacopy(0x0, 0x0, calldatasize()) let result := delegatecall(sub(gas(), 10000), target, 0x0, calldatasize(), 0, len) return(0, len) //we throw away any return data } } 

I do not really understand how the assembly code delegatecall works.

so The EIP-7 said

  1. gas: the amount of gas the code may use in order to execute;
  2. to: the destination address whose code is to be executed;
  3. in_offset: the offset into memory of the input;
  4. in_size: the size of the input in bytes;
  5. out_offset: the offset into memory of the output;
  6. out_size: the size of the scratch pad for the output.

so, let's assume that I deployed "MyContract"

I sent the msg.data "0x360058390000000000000000000000000000000000000000000000000000000000000003" to the "MyContract"

0x36005839 : a function selector 0000000000000000000000000000000000000000000000000000000000000003 : input value 

However, there was no function selector for the "MyContract",

So the fallback function took care of it!

assembly { calldatacopy(0x0, 0x0, calldatasize()) let result := delegatecall(sub(gas(), 10000), target, 0x0, calldatasize(), 0, len) return(0, len) //we throw away any return data } 

I used the event to print out calldatasize() and it was 36. I think it was because 4bytes for the function selctor + 32bytes for the input value

calldatacopy(0x0, 0x0, calldatasize()) 

I guess, In assembly, it will copy the exact same msg.data I sent.

Do I clearly understand calldatacopy?

But what is this for ? It does not even return the value..

delegatecall(sub(gas(), 10000), target, 0x0, calldatasize(), 0, len) 

Okay, for this part, I understand gas, target address.

But why does the in_offset start at 0 and is the in_size calldatasize?

1 Answer 1

2

From the docs:

calldatacopy(t, f, s) - copy s bytes from calldata at position f to mem at position t

To address your questions:

But what is this for ? It does not even return the value..

calldatacopy is copying data from calldata to memory. Since the first 64 bytes of memory are reserved for scratch space, it's a convenient place to put your calldata.

But why does the in_offset start at 0 and is the in_size calldatasize?

Your second and third parameters to calldatacopy stated you wanted to copy everything in calldata to memory at 0x00.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.