0

I'm trying to increment 1 to a variable in IA32 Assembly in Linux

section .data
num:    dd  0x1

section .text
global _start

_start:

   add    dword [num], 1

   mov    edx, 1
   mov    ecx, [num]
   mov    ebx,1
   mov    eax,4
   int    0x80

   mov    eax,1
   int    0x80

Not sure if it's possible to do.

In another literature I saw the follow code:

mov eax, num
inc eax
mov num, eax

Is it possible to increment a value to a var without moving to a register?

If so, do I have any advantage moving the value to a register?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Bruno Criado
  • 120
  • 7
  • 2
    Your actual bug is that the `write` system call wants a pointer to its data in `ecx`, not the data itself. So that should be `mov ecx, num`. And a dword is 4 bytes, not 1, and this will write it out as raw binary, not human-readable decimal or hex; you could pipe the output into `hexdump` if you want to see it. Otherwise you get to write a binary-to-decimal conversion routine, which will about triple the length of your program. – Nate Eldredge Feb 23 '21 at 04:37
  • Oh I see, thanks @NateEldredge – Bruno Criado Feb 23 '21 at 04:55

1 Answers1

4

Is it possible to increment a value to a var without moving to a register?

Certainly: inc dword [num].

Like practically all x86 instructions, inc can take either a register or memory operand. See the instruction description at http://felixcloutier.com/x86/inc; the form inc r/m32 indicates that you can give an operand which is either a 32-bit register or 32-bit memory operand (effective address).

If you're interested in micro-optimizations, it turns out that add dword [num], 1 may still be somewhat faster, though one byte larger, on certain CPUs. The specifics are pretty complicated and you can find a very extensive discussion at INC instruction vs ADD 1: Does it matter?. This is partly related to the slight difference in effect between the two, which is that add will set or clear the carry flag according to whether a carry occurs, while inc always leaves the carry flag unchanged.

If so, do I have any advantage moving the value to a register?

No. That would make your code larger and probably slower.

Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82
  • Great! Thank you again, @NateEldredge – Bruno Criado Feb 23 '21 at 04:55
  • 2
    @BrunoCriado: The usual reason for load / inc / store is if you also want the value again later, you still have it in a register. i.e. to avoid `mov ecx, [num]`, you'd do the increment in ECX. (Except that's not how to use `write(int fd, void *, size_t)`, but if it had been a printf call or something then you would want the value, not just its address.) – Peter Cordes Feb 23 '21 at 06:42
  • Yeah, makes sense. Thanks @PeterCordes – Bruno Criado Feb 23 '21 at 14:23