【发布时间】:2019-02-17 12:07:36
【问题描述】:
无论出于何种原因,以下内联汇编(AT&T/gcc 风格)在新安装的 Debian GNU/Linux 64 位机器上不起作用;它可以在其他机器上编译并正常工作:
static void INIT_CODE kernel_entry (void) NORETURN;
void _start(void)
{
// ...other code here...
asm ("ljmp %0, %1"
:
: "n" (SELECTOR_KERNEL_CODE),
"p" (&kernel_entry));
}
static void INIT_CODE kernel_entry(void)
{
// ...
}
我得到的编译错误是,gcc 7 和 8:
$ gcc-7 -o init.o -Wall -Wextra -Wshadow -Wpointer-arith -Waggregate-return \
-Wredundant-decls -Winline -Werror -Wcast-align -Wsign-compare -Wmissing-declarations \
-Wmissing-noreturn -pipe -O0 -fno-builtin -fno-asynchronous-unwind-tables \
-funsigned-char -g -fomit-frame-pointer -ffreestanding -DPACKAGE_NAME=\"storm\" \
-DPACKAGE_VERSION=\"0.5.1+\" \
-DREVISION=\"`git rev-list HEAD --max-count 1 --abbrev-commit`\" \
-DCREATOR=\"`whoami`@`hostname -s`\" --std=gnu99 -Wbad-function-cast \
-Wmissing-prototypes -Wnested-externs -Wstrict-prototypes -m32 -I../include \
-I.. -I. -c init.c
init.c: Assembler messages:
init.c:151: Error: operand type mismatch for `ljmp'
我还尝试查看汇编代码(使用 -S 编译),它为什么不编译是完全有道理的:
#NO_APP
leal kernel_entry@GOTOFF(%eax), %eax
#APP
# 151 "init.c" 1
ljmp $8, %eax
# 0 "" 2
这行不通; ljmp 指令只接受两个常量操作数(即不将 %eax 作为第二个操作数)。
那么,我怎样才能让gcc 明白这一点呢?我需要更改p argument constraint 吗?我已经尝试将其更改为n,但后来我得到了这个错误:
init.c: In function ‘_start’:
init.c:151:5: warning: asm operand 1 probably doesn’t match constraints
asm ("ljmp %0, %1"
^~~
init.c:151:5: error: impossible constraint in ‘asm’
非常感谢。
【问题讨论】:
-
这看起来很可疑,好像您启用了 PIE(可能是默认情况下)。尝试以某种组合添加
-fno-PIC -fno-pic -no-pie开关。 gcc.godbolt.org 有效,除非我添加-fPIC或-fpic。 -
非常感谢@Jester - 添加
-fno-PIC或-fno-pic似乎确实可以解决问题。将发布后续答案,包括更多详细信息。