GCD: algorithme d’Euclide dans un « Master Boot Record »¶
Python¶
def gcd(a, b):
while a != b:
if a > b:
a = a - b
else:
b = b - a
return a
import sys
print(gcd(int(sys.argv[1]), int(sys.argv[2])))
https://tenthousandmeters.com/blog/python-behind-the-scenes-5-how-variables-are-implemented-in-cpython/
C¶
#include <stdio.h>
#include <stdlib.h>
int gcd(unsigned short a, unsigned short b)
{
while (a != b)
if (a > b)
a = a - b;
else
b = b - a;
return a;
}
int main(int ac, char *av[])
{
unsigned short a, b, r;
a = atoi(av[1]);
b = atoi(av[2]);
r = gcd(a, b);
printf("%d\n", r);
return 0;
}
Rust¶
pub fn gcd(mut a: u16, mut b: u16) -> u16 {
while a != b {
if a > b {
a = a - b;
} else {
b = b - a;
}
}
a
}
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
let a = args[1].parse::<u16>().expect("not a valid number");
let b = args[2].parse::<u16>().expect("not a valid number");
let r = gcd(a, b);
println!("{r}");
}
Assembleur x86¶
http://ref.x86asm.net/index.html
https://www.felixcloutier.com/x86/
https://software.intel.com/en-us/download/intel-64-and-ia-32-architectures-sdm-combined-volumes-1-2a-2b-2c-2d-3a-3b-3c-3d-and-4
https://stackoverflow.com/questions/8287181/how-to-do-source-level-debugging-of-x86-code-with-gdb-inside-qemu
https://diablohorn.com/2010/01/09/bootloader-development-environment/
https://binarydebt.wordpress.com/2018/10/06/how-does-an-x86-processor-boot/
mov ax, 2345
mov bx, 35
gcd:
cmp ax, bx
je end
jl else
sub ax, bx
jmp gcd
else:
sub bx, ax
jmp gcd
end:
mov cx, ax
padding:
times 510-($-$$) db 0
dw 0xaa55
Compilation en format « bin » (ou « raw », ou « com »):
nasm -o gcd_x8086.bin -f bin gcd_x8086.S
ndisasm gcd_x8086.bin
Compilation en format ELF:
nasm -o gcd_x8086.elf -f elf -g gcd_x8086.S
objdump -d gcd_x8086.elf
Exécution du code binaire avec QEMU en mode « déboguable » (-s -S
):
qemu-system-i386 -s -S -fda gcd_x8086.bin -boot a
Visualisation de l’exécution du code avec GDB:
$ gdb
target remote localhost:1234
set architecture i8086
display /i ($cs*16)+$pc
stepi # step into the guest BIOS (seabios)
stepi
stepi
stepi
stepi
stepi
stepi
stepi
stepi
stepi
stepi
br *0x7c00 # set breakpoint in the MBR
cont
stepi
br *0x7c14
layout asm
layout regs
stepi
stepi