Home > Blockchain >  Step-by-step explanation of basic C / x86 assembly code for pointer dereference and multiply
Step-by-step explanation of basic C / x86 assembly code for pointer dereference and multiply

Time:09-16

I come here today because I am currently on a university work on introduction with assembly x86. As we did C prior this, our teacher asked us to explain this portion of code. c code associated with the problem

my basic understanding of what it does is:

  • EAX will contain the value of the memory area associated with y.
  • ECX will contain the value of the memory zone associated with EAX, ie the pointer to y.
  • imul will multiply the value of the pointer eax (i.e. the pointer to y) and the value of x.
  • We move the pointer of y in EDX, then we move the value of the multiplication to the pointer of y.

Am I right? If not, could someone give me a better explaination of the part I misunderstood?

Thank you in advance.

CodePudding user response:

As with any assembler, you pretty much need to sit with the ISA manual at hand, because each instruction comes with a lot of flavours depending on what you pass to it.

First check out What does `dword ptr` mean? So basically this 32 bit accesses the contents at a certain address.

Since y is a pointer, the contents of y is the address where *y can be found. So first the y address will get moved into eax and then the contents of the address just uploaded into eax will be moved into ecx.

imul with two operands goes like this:

  • Two-operand form. With this form the destination operand (the first operand) is multiplied by the source operand (second operand). The destination operand is a general-purpose register and the source operand is an immediate value, a general-purpose register, or a memory location. The product is then stored in the destination operand location.

So it multiplies ecx with whatever was stored at dword ptr[x], that is the contents of x. And stores the result in ecx.

Then again the address y is uploaded to a register edx (maybe an optimization flaw, because eax already holds it). And then the result of the multiplication stored in exc is moved to that location.

CodePudding user response:

Code with comments:

        mov     eax,dword ptr [y]         ;eax = y
        mov     ecx,dword ptr [eax]       ;ecx = *y
        imul    ecx,dword ptr [x]         ;ecx = (*y) * x
        mov     edx,dword ptr [y]         ;edx = y
        mov     dword ptr[edx], ecx       ;(*y) = (*y) * x
  • Related