4 ms·
The author gives an example, you just have to fill in some blanks. To follow along, on Linux you can use the NASM assembler (sudo apt-get install nasm on Debia
by picomancer 14y ago
The author gives an example, you just have to fill in some blanks. To follow along, on Linux you can use the NASM assembler (sudo apt-get install nasm on Debian-like or Ubuntu-like systems).
Then you can copy-paste the assembly language from the article (I've changed the spacing for readability and added dummy definitions for the names so it will compile):
;demo1.asm
source_address equ 0x100
destination_address equ 0x200
loop_count equ 0x10
mov esi, source_address
mov edi, destination_address
mov ecx, loop_count
my_loop:
lodsd
;Do some calculations with eax here.
stosd
loop my_loop
And assemble it, in your favorite shell type:
nasm -l demo1.lst demo1.asm
Then here's my alternative implementation that uses different registers. You can no longer use LODSD, STOSD or LOOP instructions since these instructions only work if you chose the same registers as demo1.
;demo2.asm
source_address equ 0x100
destination_address equ 0x200
loop_count equ 0x10
mov ebx, source_address
mov edx, destination_address
mov esi, loop_count
my_loop:
mov eax,[ebx] ; these two instructions instead of stosd
add ebx,4
;Do some calculations with eax here.
mov [edx],eax ; these two instructions instead of lodsd
add edx,4
dec esi ; these two instructions instead of loop
jnz my_loop
I get a demo1 of 24 bytes and a demo2 of 38 bytes. The demo1.lst and demo2.lst files produced show how many bytes are taken up by each instruction. (And if you get addresses in a crash dump, they can be used to track down the corresponding source code line.)
If you want to actually run these programs, nasm's default output (raw machine language instructions) cannot be used by most OS's. (In DOS, you can -- just rename to .COM. But a DOS target needs to tell NASM 'bits 16', to have it emit the proper prefixes for those new-fangled 32-bit instructions, and will crash without the DOS exit syscall, INT 0x20.) The magic incantations for standalone Linux assembly language programs are here:
http://blog.markloiseau.com/2012/04/hello-world-nasm-linux/ http://blog.markloiseau.com/2012/04/hello-world-nasm-linux/
The .o file produced by an intermediate step of the instructions at the above link can be linked with C code (unless you use a Microsoft toolchain, in which case you have to instruct nasm to output .obj instead). Then you can call assembly language functions from C and vice versa. (Figuring out how to retrieve your function's arguments in assembly language is very interesting and will enlighten you about the implementation of high-level languages.) Most "real-world" assembly code does this: Most of the program is written in C, and only the functions that need the particular advantages of assembly language are written in it.