NickAllanMiller
NickAllanMiller

Reputation: 73

Converting a snippit of x86 Assembly Code into C

this is a piece of an assignment on assembly code. I'm not sure if I'm quite grasping it. This is one of 5 switch statements where I must write the equivalent C code. Is it just me not understanding what is going on here, or is there a lot of unnecessary code?

Parameter p1 is stored at %ebp+8, Parameter p2 is at %ebp+12. The result is initialized to -1 and stored in %edx. .L19: sets the return value.

When I trace it my understanding is that the p1 is placed into %eax. Then the address pointed to by %eax (which is p1's value) is placed into %edx. Then the last 4 lines are unnecessary because the return register is not touched the rest of the switch.

    movl     8(%ebp), %eax
    movl     (%eax), %edx
    movl     12(%ebp), ecx
    movl     (%ecx), %eax
    movl     8(%ebp), %ecx
    movl     %eax, (%ecx)
    jmp      .L19

Is my book just trying to be tricky or am I completely missing the mark here? Thanks.

Upvotes: 4

Views: 294

Answers (1)

Ben Collins
Ben Collins

Reputation: 20686

Why is the result stored in %edx? The calling conventions I'm familiar with in x86 all use %eax as the return value for integer/pointer values.

I don't think you're really far off:

movl    8(%ebp), %eax
movl    (%eax), %edx

This is about like:

int value = *p1;

Then:

movl    12(%ebp), %ecx
movl    (%ecx), %eax

Which looks about like:

int value2 = *p2;

Then finally:

movl    8(%ebp), %ecx)
movl    %eax, (%ecx)
jmp     .L19

Which amounts to:

*p1 = value2;
break;

Summary:

int value = *p1;
int value2 = *p2;
*p1 = value2
break;

Heh. This must be a common homework question or an online MOOC or something. Check it out: C, Assembly : understanding the switch condition, edx eax ecx

Taken from this one, it looks like you're talking about MODE_A:

int switchmode(int *p1, int *p2, mode_t action)
{
  int result = 0;
  switch(action) {
    case MODE_A:
      result = *p1;
      *p1 = *p2;
      break;
    case MODE_B:
      *p2 += *p1;
      result = *p2;
      break;
    case MODE_C:
      *p2 = 15;
      result = *p1;
      break;
    case MODE_D:
      *p2 = *p1;
      /* Fall Through */
    case MODE_E:
      result = 17;
      break;
    default:
      result = -1;
  }
  return result;
}

As an aside, the result is transferred to %eax at the end, just like one would expect.

Upvotes: 2

Related Questions