Exemple 1
Ejemplo»Hello World» básico para crear un ejecutable en linux con assembler.
Helloworld.asm
;Copyright (c) 1999 Konstantin Boldyshev <konst@linuxassembly.org> ; ;"hello, world" in assembly language for Linux ; ;to build an executable: ; nasm -f elf hello.asm ; ld -s -o hello hello.o section .text ; Export the entry point to the ELF linker or loader. The conventional ; entry point is "_start". Use "ld -e foo" to override the default. global _start section .data msg db 'Hello, world!',0xa ;our dear string len equ $ - msg ;length of our dear string section .text ; linker puts the entry point here: _start: ; Write the string to stdout: mov edx,len ;message length mov ecx,msg ;message to write mov ebx,1 ;file descriptor (stdout) mov eax,4 ;system call number (sys_write) int 0x80 ;call kernel ; Exit via the kernel: mov ebx,0 ;process' exit code mov eax,1 ;system call number (sys_exit) int 0x80 ;call kernel - this interrupt won't return
Compilar
Compilar el ejecutable:
nasm -f elf hello.asm ld -s -o hello hello.o
compilar como 32 bits:
ld -m elf_i386 -s -o file file.o
Debugger
Depurador de código asm.
sudo apt install sasm
https://github.com/Dman95/SASM
Calculadora SASM
Per generar el codi en assemblador x86 per al compilador SASM, es pot utilitzar l’exemple anterior i adaptar-lo a la sintaxi de SASM. Aquí tens el mateix exemple de calculadora en assemblador x86 adaptat per al compilador SASM:
%include "io64.inc" section .data num1 db 0 num2 db 0 result db 0 msg1 db 'Introdueix el primer nombre: ', 0 len1 equ $-msg1 msg2 db 'Introdueix el segon nombre: ', 0 len2 equ $-msg2 msg3 db 'La suma es: ', 0 len3 equ $-msg3 msg4 db 'La resta es: ', 0 len4 equ $-msg4 section .text global CMAIN CMAIN: mov rbp, rsp; for correct debugging ; Demana el primer número mov eax, 4 mov ebx, 1 mov ecx , msg1 mov edx, len1 int 0x80 ; Captura el primer número mov eax, 3 mov ebx, 0 mov ecx, num1 mov edx, 1 int 0x80 ; Demana el segon número mov eax, 4 mov ebx, 1 mov ecx, msg2 mov edx, len2 int 0x80 ; Captura el segon número mov eax, 3 mov ebx, 0 mov ecx, num2 mov edx, 1 int 0x80 ; Suma els dos números mov al, [num1] sub al, 48 mov bl, [num2] sub bl, 48 add al, bl add al, 48 mov [result], al ; Mostra el resultat mov eax, 4 mov ebx, 1 mov ecx, msg3 mov edx, len3 int 0x80 mov eax, 4 mov ebx, 1 mov ecx, result mov edx, 1 int 0x80 ; Resta els dos números mov al, [num1] sub al, 48 mov bl, [num2] sub bl, 48 sub al, bl add al, 48 mov [result], al ; Mostra el resultat mov eax, 4 mov ebx, 1 mov ecx, msg4 mov edx, len4 int 0x80 mov eax, 4 mov ebx, 1 mov ecx, result mov edx, 1 int 0x80 ; Finalitza el programa mov eax, 1 xor ebx, ebx int 0x80
Per compilar aquest codi en SASM, cal guardar-lo en un arxiu amb extensió .asm i seleccionar la targeta de compilació adequada. A continuació, es pot compilar el programa i generar el fitxer executable corresponent.