x86-64 汇编语言中的 ELF 共享对象 [英] ELF Shared Object in x86-64 Assembly language

查看:15
本文介绍了x86-64 汇编语言中的 ELF 共享对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 ASM 中创建一个共享库 (*.so),但我不确定我是否正确...

I'm trying to create a Shared library (*.so) in ASM and I'm not sure that i do it correct...

我的代码是:

    .section .data
    .globl var1
var1:
    .quad     0x012345

    .section .text
    .globl func1
func1:
    xor %rax, %rax
  # mov var1, %rcx       # this is commented
    ret

要编译它,我运行

gcc ker.s -g -fPIC -m64 -o ker.o
gcc ker.o -shared -fPIC -m64 -o libker.so

我可以从 C 程序中访问变量 var1 并使用 dlopen() 和 dlsym() 调用 func1.

I can access variable var1 and call func1 with dlopen() and dlsym() from a program in C.

问题出在变量 var1 中.当我尝试从 func1 访问它时,即取消注释该行时,编译器会生成错误:

The problem is in variable var1. When i try to access it from func1, i.e. uncomment that line, the compiler generates an error:

/usr/bin/ld: ker.o: relocation R_X86_64_32S against `var1' can not be used when making a shared object; recompile with -fPIC
ker.o: could not read symbols: Bad value
collect2: ld returned 1 exit status

我不明白.我已经用-fPIC编译过了,怎么回事?

I don't understand. I've already compiled with -fPIC, so what's wrong?

推荐答案

好吧,我想我找到了一些东西......

Ok, i think i found something...

drhirsch 的第一个解决方案给出了几乎相同的错误,但重定位类型已更改.而且类型总是以 32 结尾.这是为什么呢?为什么 64 位程序使用 32 位重定位?

First solution from drhirsch gives almost the same error but the relocation type is changed. And type is always ended with 32. Why is it? Why 64 bit program uses 32-bit relocation?

我通过谷歌搜索找到了这个:http://www.technovelty.org/代码/c/relocation-truncated.html

I found this from googling: http://www.technovelty.org/code/c/relocation-truncated.html

上面写着:

出于代码优化目的,mov的默认立即大小指令是一个 32 位的值

For code optimisation purposes, the default immediate size to the mov instructions is a 32-bit value

原来如此.我使用 64 位程序,但重定位是 32 位的,我只需要使用 movabs 指令将其强制为 64 位.

So that's the case. I use 64-bit program but relocation is 32-bit and all i need is to force it to be 64 bit with movabs instruction.

此代码正在组装和工作(从内部函数 func1 和外部 C 程序通过 dlsym() 访问 var1):

This code is assembling and working (access to var1 from internal function func1 and from external C program via dlsym()):

    .section .data 
    .globl var1 
var1: 
    .quad     0x012345

    .section .text 
    .globl func1 
func1: 
    movabs var1, %rax       # if one is symbol, other must be %rax
    inc %rax
    movabs %rax, var1
    ret

但我对全局偏移表存有疑问.我必须使用它,还是这种直接"访问是绝对正确的?

But i'm in doubt about Global Offset Table. Must i use it, or this "direct" access is absolutely correct?

这篇关于x86-64 汇编语言中的 ELF 共享对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆