Pages

marți, 1 decembrie 2026

FASM : detect CPU hardware with cpuid .

Detect hardware CPU with FASM, see this source code:
format ELF64 executable 3

segment readable executable
entry main

main:
    ; Vendor: CPUID leaf 0 (EBX, EDX, ECX = 12 caractere)
    xor  eax, eax
    cpuid
    mov  dword [vendor],   ebx
    mov  dword [vendor+4], edx
    mov  dword [vendor+8], ecx

    lea  rsi, [lbl_vendor]
    mov  rdx, lbl_vendor_len
    call write
    lea  rsi, [vendor]
    mov  rdx, 12
    call write
    call newline

    ; Brand string: leaf-urile 0x80000002..0x80000004 (48 caractere)
    mov  eax, 0x80000000
    cpuid
    cmp  eax, 0x80000004
    jb   no_brand

    mov  r8d, 0x80000002
    lea  rdi, [brand]
brand_loop:
    mov  eax, r8d
    cpuid
    mov  dword [rdi],    eax
    mov  dword [rdi+4],  ebx
    mov  dword [rdi+8],  ecx
    mov  dword [rdi+12], edx
    add  rdi, 16
    inc  r8d
    cmp  r8d, 0x80000004
    jbe  brand_loop

    lea  rsi, [lbl_brand]
    mov  rdx, lbl_brand_len
    call write
    lea  rsi, [brand]
    mov  rdx, 48
    call write
    call newline
    jmp  features

no_brand:
    lea  rsi, [lbl_nobrand]
    mov  rdx, lbl_nobrand_len
    call write

features:
    ; Flaguri: CPUID leaf 1 - EDX bit 26 = SSE2, ECX bit 28 = AVX
    mov  eax, 1
    cpuid
    mov  dword [feat_edx], edx
    mov  dword [feat_ecx], ecx

    lea  rsi, [lbl_sse2]
    mov  rdx, lbl_sse2_len
    call write
    mov  eax, [feat_edx]
    shr  eax, 26
    and  eax, 1
    call print_yesno

    lea  rsi, [lbl_avx]
    mov  rdx, lbl_avx_len
    call write
    mov  eax, [feat_ecx]
    shr  eax, 28
    and  eax, 1
    call print_yesno

    call exit

; eax = 1 -> "DA", altfel "NU"
print_yesno:
    test eax, eax
    jz   .no
    lea  rsi, [yes]
    mov  rdx, 3
    call write
    ret
.no:
    lea  rsi, [no]
    mov  rdx, 3
    call write
    ret

; rsi = adresa, rdx = lungime
write:
    mov  eax, 1           ; sys_write
    mov  edi, 1           ; stdout
    syscall
    ret

newline:
    lea  rsi, [nl]
    mov  rdx, 1
    call write
    ret

exit:
    mov  eax, 60          ; sys_exit
    xor  edi, edi
    syscall

segment readable writeable

vendor        rb 12
brand         rb 48
feat_edx      dd 0
feat_ecx      dd 0

lbl_vendor     db "Vendor:  "
lbl_vendor_len = $ - lbl_vendor
lbl_brand      db "Model:  "
lbl_brand_len  = $ - lbl_brand
lbl_nobrand    db "Model:  necunoscut", 10
lbl_nobrand_len = $ - lbl_nobrand
lbl_sse2       db "SSE2:  "
lbl_sse2_len   = $ - lbl_sse2
lbl_avx        db "AVX:  "
lbl_avx_len    = $ - lbl_avx
yes            db "DA", 10
no             db "NU", 10
nl             db 10
Let's see result:
flat assembler  version 1.73.35  (16384 kilobytes memory, x64)
3 passes, 670 bytes.
Vendor:  AuthenticAMD
Model:  AMD Ryzen 5 3600 6-Core Processor              .
SSE2:  DA
AVX:  DA