x86内存访问分段错误

时间:2015-11-24 09:06:44

标签: linux assembly x86 segmentation-fault nasm

我出于好奇而学习x86程序集。我目前正在使用基于Linux的操作系统和NASM汇编程序。我很难理解为什么

SECTION .text

global _start

_start:

    nop
    mov ebx, 25
    mov [0xFFF], ebx

   ;Exit the program
   mov eax, 1
   mov ebx, 0
   int 0x80

会导致分段错误(将ebx寄存器的内容移动到内存位置0xFFF时)。我当时认为用纯粹的asm构建一个程序会让我无限制地访问我的进程'虚拟地址空间。这不是这种情况吗?

你如何在汇编中实现类似堆的东西?

2 个答案:

答案 0 :(得分:6)

在Linux(x86)上 - 虽然您的进程中的虚拟地址范围为4gb,但并非所有地址都可访问。上部1gb是内核所在的位置,并且存在无法使用的低内存区域。虚拟内存地址0xfff无法写入或读取(默认情况下),因此您的程序会因段错而崩溃。

在后续评论中,您建议您打算在汇编程序中创建堆。这可以做到,一种方法是使用sys_brk系统调用。它可以通过int 0x80 EAX = 45访问。它需要 EBX 中的指针代表堆的新顶部。通常,堆区域的底部初始化为程序数据段之外的区域(在内存中的程序之上)。要获取初始堆位置的地址,可以在 EBX 设置为0的情况下调用 sys_break 。系统调用 EAX 将成为当前基础堆的指针。当您需要访问堆内存或分配更多堆空间时,可以将其保存起来。

此代码提供了一个示例,用于清晰(不是性能),但可能是理解如何操作堆区域的起点:

SECTION .data
heap_base: dd 0          ; Memory address for base of our heap

SECTION .text
global _start
_start:
    ; Use `brk` syscall to get current memory address
    ; For the bottom of our heap This can be achieved
    ; by calling brk with an address (EBX) of 0
    mov eax, 45          ; brk system call
    xor ebx, ebx         ; don't request additional space, we just want to 
                         ; get the memory address for the base of our processes heap area.
    int 0x80
    mov [heap_base], eax ; Save the heap base

    ;Now allocate some space (8192 bytes)
    mov eax, 45          ; brk system call
    mov ebx, [heap_base] ; ebx = address for base of heap
    add ebx, 0x2000      ; increase heap by 8192 bytes
    int 0x80

    ; Example usage
    mov eax, [heap_base]      ; Get pointer to the heap's base
    mov dword [eax+0xFFF], 25 ; mov value 25 to DWORD at heapbase+0xFFF

    ;Exit the program
    mov eax, 1
    xor ebx, ebx
    int 0x80

答案 1 :(得分:1)

您没有无限制的内存。此外,您不能无限制地访问由RAM支持的地址空间部分。代码页以只读方式映射。作为一个ring-3计划,你不能自己改变它。