汇编共享库

1. 共享库

  • 在编程中,共享代码文件被称为共享库、共享对象、动态链接库、DLL文件等。

2. 使用共享库

  1. 生成命令:
    ld helloworld-lib.o -o helloworld-lib.out -dynamic-linker /lib/ld-linux.so.2 -lc -m elf_i386
    
    • -dynamic-linker /lib/ld-linux.so.2 操作系统将加载程序/lib/ld-linux.so.2,以加载外部库并将其链接到程序。/lib/ld-linux.so.2这样的程序成为动态链接器
    • -lc 链接库c,该库在GNU、Linux系统上的文件名为libc.so,给定库名,在本例中为c(通常不止一个字符),GNU/Linux链接器将字符串lib加至库名之前,将字符串.so加到库名之后,构成库文件名。这个库包含许多函数以自动执行各种任务。我们使用其中两个,即打印字符串的printf和退出程序的exit。
  2. 关于静态/动态链接可执行文件:
    • 未使用共享库的程序称为静态链接
    • 使用共享库的程序称为动态链接
  3. 使用ldd查看链接文件位置
    ldd ./helloworld-lib
    输出:
        linux-gate.so.1 (0xf7fb8000)
        libc.so.6 => /lib32/libc.so.6 (0xf7dbf000)
        /lib/ld-linux.so.2 (0xf7fb9000)
    

3. printf

  1. 原型
    int printf(char *string, ...);
    
  2. Example
    .section .data
firststring:
 .ascii "Hello! %s is a %s who loves the number %d\n\0"
name:
 .ascii "Jonathan\0"
personstring:
 .ascii "person\0"
numberloved:
 .long 3
 .section .text
 .globl _start

_start:
 pushl numberloved
 pushl $personstring
 pushl $name
 pushl $firststring

 call printf

 pushl $0
 call exit

在这里插入图片描述

  • 为什么prinft函数知道一共有多少个参数?该函数会在字符串中搜索,计算一种找到多少%d和%s,接着从栈中抓取相应数目的参数。

4. 构建一个共享库

    # 将.o 文件链接为共享库
    ld -shared write-record.o read-record.o -o librecord.so
    # 动态链接到这个库
    ld write-records.o -o write-records.out -L . -dynamic-linker /lib/ld-linux.so.2 -lrecord
    # 运行时 设置环境变量
        LD_LIBRARY_PATH=.
        export LD_LIBRARY_PATH
    # then
    ./write-records.out

3. 其他

  • 计算一段ascii的长度
    helloeworld:
     .ascii "hello world\n"
    helloworld_end:
     .equ helloworld_len, helloworld_end - helloworld
    
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值