在64位系統(tǒng)中進(jìn)行32位匯編

在閱讀《Professional Assembly Language》(Richard Blum 著)第四章的示例程序時(shí),其中有演示在匯編中使用C語(yǔ)言庫(kù)函數(shù)--printf,但我在測(cè)試這段代碼時(shí)遇到了一些問(wèn)題。
首先說(shuō)明我的系統(tǒng)環(huán)境,運(yùn)行的是 Linux Mint 18.3 Cinnamon 64 bit。

兼容問(wèn)題

代碼測(cè)試中所遇到的問(wèn)題究其原因,是在64位系統(tǒng)中進(jìn)行了32位匯編,事實(shí)上就是不兼容的問(wèn)題,為了避免這個(gè)問(wèn)題,讓匯32位編代碼的匯編(as)和連接(ld)按書(shū)中指導(dǎo)正常進(jìn)行,需要安裝一些包含32位函數(shù)庫(kù)的軟件包,在終端運(yùn)行:
sudo apt install lib32z1 lib32ncurses5 g++-multilib libc6-dev-i386

指定生成32-bit程序

首先打開(kāi)匯編源碼文件cpuid2.s,在首行添加代碼 ".code32"

# cpuid2.s view the CPUID vendor id string using C library calls
.code32
.section .data
output:
    .asciz "the processor vendor id is '%s'\n"
.section .bss
    .lcomm buffer,12
.section .text
.globl _start
_start:
    movl $0,%eax
    cpuid
    movl $buffer,%edi
    movl %ebx,(%edi)
    movl %edx,4(%edi)
    movl %ecx,8(%edi)
    pushl $buffer
    pushl $output
    call printf
    addl $8,%esp
    pushl $0
    call exit

在終端運(yùn)行匯編器:
as --32 -o cpuid2.o cpuid2.s
生成32位目標(biāo)文件cpuid2.o
然后執(zhí)行連接操作:
ld -m elf_i386 -dynamic-linker /lib/ld-linux.so.2 -o cpuid2 -lc cpuid2.o
生成linux下可執(zhí)行程序cpuid2,可以查看文件類型
file cpuid2
結(jié)果為:

cpuid2: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, not stripped

至此,代碼測(cè)試成功,程序可以正常運(yùn)行。

編寫64-bit匯編代碼

# cpuid64.s using 64-bit assembly language
# view the CPUID   vendor id string using C library calls
.section .data
output:
    .asciz "the processor vendor id is '%s'\n"
.section .bss
    .lcomm buffer,12
.section .text
.globl _start
_start:
    movq $0, %rax
    cpuid
    movq $buffer, %rdi
    movq %rbx, (%rdi)
    movq %rdx, 4(%rdi)
    movq %rcx, 8(%rdi)
    movq $buffer, %rsi 
    movq $output, %rdi 
    movq $0, %rax
    call printf
    addq $8, %rsp
    pushq $0
    call exit
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容