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

查看:128
本文介绍了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 的第一个解决方案给出几乎相同的错误,但重定位类型已更改.而且type总是以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/code/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和通过dlsym()从外部C程序访问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天全站免登陆