是否可以在64位Linux中的同一可执行文件中同时使用64位和32位指令?

时间:2018-02-18 17:29:38

标签: linux assembly x86 x86-64 32bit-64bit

64位CPU(amd64)在兼容模式下支持32位Intel指令。此外,64位Linux安装允许运行包含32位指令的ELF,如果ELF标头表示它是32位可执行文件。

我想知道是否可以在ELF中放置一些汇编指令,在程序中间将CPU切换到32位兼容模式(然后再返回)?如果内核不允许这些汇编指令,我们是否可以通过某种方式让内核将已经运行的进程切换到32位?

这主要是出于好奇心的问题,因为我无法真正看到任何用例。

1 个答案:

答案 0 :(得分:5)

通过更改CS来完成长模式和兼容模式之间的切换。用户模式代码不能修改描述符表,但它可以对已经存在于描述符表中的代码段执行远程跳转或远程调用。我认为在Linux(例如)中存在所需的兼容性模式描述符。

以下是Linux(Ubuntu)的示例代码。用

构建
$ gcc -no-pie switch_mode.c switch_cs.s

switch_mode.c:

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>

extern bool switch_cs(int cs, bool (*f)());
extern bool check_mode();

int main(int argc, char **argv)
{
    int cs = 0x23;
    if (argc > 1)
        cs = strtoull(argv[1], 0, 16);
    printf("switch to CS=%02x\n", cs);

    bool r = switch_cs(cs, check_mode);

    if (r)
        printf("cs=%02x: 64-bit mode\n", cs);
    else
        printf("cs=%02x: 32-bit mode\n", cs);

    return 0;
}

switch_cs.s:

        .intel_syntax noprefix
        .code64
        .text
        .globl switch_cs
switch_cs:
        push    rbx
        push    rbp
        mov     rbp, rsp
        sub     rsp, 0x18

        mov     rbx, rsp
        movq    [rbx], offset .L1
        mov     [rbx+4], edi

        // Before the lcall, switch to a stack below 4GB.
        // This assumes that the data segment is below 4GB.
        mov     rsp, offset stack+0xf0
        lcall   [rbx]

        // restore rsp to the original stack
        leave
        pop     rbx
        ret

        .code32
.L1:
        call    esi
        lret


        .code64
        .globl check_mode
// returns false for 32-bit mode; true for 64-bit mode
check_mode:
        xor     eax, eax
        // In 32-bit mode, this instruction is executed as
        // inc eax; test eax, eax
        test    rax, rax
        setz    al
        ret

        .data
        .align  16
stack:  .space 0x100
相关问题