I'm new to hardware near programming with assembly code. So I read a book about it and found this sample code for the NASM assembler:
segment .text ;code segment
global main ;must be declared for linker
main: ;tell linker entry point
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
mov eax,1 ;system call number (sys_exit)
int 0x80 ;call kernel
segment .data ;data segment
msg db 'Hello, world!',0xa ;our dear string
len equ $ - msg ;length of our dear string
So I compiled it with the following commands:
nasm -f elf64 helloworld.asm
ld -s -o helloworld.exe helloworld.o
The assembler has no problem to assemble it and gives no errors, but the program crashes instantly. I read about different assembly-languages, but the point is that the assembly-code varies with different compilers not with different operating systems, so where is my mistake?
The code that you're showing is x86_32 linux code.
You can tell, because it uses int
calls which Windows does not and this line:
nasm -f elf64 helloworld.asm
Produces output in ELF format, which is a linux executable.
Windows uses PE (portable executable) which is the MS EEE variant of COFF .
x64 code uses RAX
, RBX
...., although the 32-bit variant registers EAX
etc also feature heavily.
Before you can learn how to write assembly.
You need to know the ABI (calling conventions) and the API of a system.
For the ABI have a look at: Calling Conventions - PDF
If you want to know how to do API calls in Windows, write a simple C program that does the job and then get a disassembler and look at the x86 code.
For more info on the API calls have a look at MSDN, specifically:
Overview of x64 Calling Conventions
Windows Console functions
ExitProcess function
Assemble your executable on PE format and change the int 0x80
to a call ExecuteInterrupt128
. You can give it a same name. You can learn how to write a PE executable on NASM. Just go to the homepage of Stack Overflow.
The ExecuteInterrupt128 function must look like this:
push ebp
mov ebp, esp
cmp eax, byte +1
je SleepSystem
cmp eax, byte +4
je PrintString
...
SleepSystem:
push byte -1
call Sleep
leave
ret
PrintString:
push -11
call GetStdHandle
push byte +0
push byte +6
lea esi, [ebp-4]
push edx
push ecx
push eax
call WriteConsoleA
leave
ret
Or try this commands:
nasm -f win32 -o executable.o executable.asm
ld -o executable.exe executable.o
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.