0

So I decided to learn a little bit about assembly. I want to write a program that simply adds two integers and outputs the value to stdout. I cannot get it done. I read somewhere that I am not able to load integer values, that is why I read strings and remove the '0'. When I try to build the object file, I get following error:

warning: byte data exceeds bounds [-w+number-overflow]
invalid combination of opcode and operands

I am not sure what does it mean. Unluckily, the documentation seems to be very scattered around the web :(

section .text
    global _main     ;must be declared for linker (ld)

_main:                          ;tells linker entry point
   mov  AH,'8'                  ; read first integer
   sub  AH, '0'     
   mov  CH, '10'                ; read second integer
   sub  CH, '0'
   add  AH, CH
   add  AH, '0'
   
   mov  RDX, 4
   mov  RSI, AH                 ;message to write
   mov  RDI, 1                  ;file descriptor (stdout)
   mov  RAX, 0x02000004         ;system call number (sys_write)
   syscall                      ;call kernel

   mov  RAX, 0x02000001         ;system call number (sys_exit)
   syscall                      ;call kernel

I am using macOS BigSur and compile the code with following command:

nasm -fmacho64 file_name.asm 
  • You cannot `mov CH, '10'`, because your are trying to `MOV` (a "string" of) two 8-bit chars (=16-bit) to an 8-bit register. That gives you the error. – zx485 Aug 16 '21 at 18:00
  • Oo, alright, that makes sense. So once I use 16-bit(or bigger) registers, this program should work, right? – Tomasz Staszkiewicz Aug 16 '21 at 18:06
  • Unfortunately not. You did the correct subtraction of `0` from the digit to transform the [ASCII](https://en.wikipedia.org/wiki/ASCII) value to the BYTE value. But this only works for one digit numbers. So, if you think about it, the `10` consists of `1` and `0`, hence the approach you use couldn't work - even with a 16-bit register. The are plenty of questions and answers on SO about this topic: See [Adding two numbers](https://stackoverflow.com/search?q=%5Bassembly%5D+adding+two+numbers). – zx485 Aug 16 '21 at 18:18
  • 1
    You left out line numbers in your [mcve], but `mov RSI, AH` is invalid because the operands aren't the same size. [Why can't I move directly a byte to a 64 bit register?](https://stackoverflow.com/q/22621340). A `write` system call takes a pointer in RSI, which must point to bytes in memory. Just like in C you can't `write(1, 0x30, 1)`; you need to give it a pointer to a string. – Peter Cordes Aug 16 '21 at 18:36

0 Answers0