String 汇编程序中的mmap和字符串操作
我试图编写一些代码,为字符串分配一些内存,并用随机字符填充内存。 现在我决定采用mmap系统调用的方式,而不使用malloc函数 这是我的密码:String 汇编程序中的mmap和字符串操作,string,assembly,x86,mmap,gnu-assembler,String,Assembly,X86,Mmap,Gnu Assembler,我试图编写一些代码,为字符串分配一些内存,并用随机字符填充内存。 现在我决定采用mmap系统调用的方式,而不使用malloc函数 这是我的密码: .code32 .data random: .ascii "/dev/random\0" .section .data c: .ascii "t" #just a test static character, for test n: .ascii "\n" #end of string .text .global
.code32
.data
random: .ascii "/dev/random\0"
.section .data
c: .ascii "t" #just a test static character, for test
n: .ascii "\n" #end of string
.text
.global _start
_start:
pushl $0 # offset of 0
pushl $-1 # the file handle of the open file
pushl $33 # MAP_SHARED flag set to write changed data back to file
pushl $3 # PROT_READ and PROT_WRITE permissions
pushl $42
pushl $0 # Allow the system to select the location in memory to start
movl %esp,%ebx # copy the parameters location to EBX
movl $90,%eax # set the system call value
int $0x80
movl %eax,%edi #the adress of allocated memory is stored in edi
pushl %eax #save the adress on stack
movl $42, %ecx #now i want to generate 42 random symbols and print them
loop:
dec %ecx
pushl %ecx #generate a random number, using the kernel Entropy Collector
movl $5,%eax # sys_open
movl $random,%ebx # Filename string
movl $0,%ecx # O_RDONLY flag
int $0x80
# Read one random number
movl %eax,%ebx # The result of sys_open
movl $3,%eax # sys_read
movl (%esp),%ecx # The stack is our buffer
movl $1,%edx #
int $0x80 #random number on stack
popl %eax #eax represents the random number
movl $100,%ebx
divl %ebx #modulo 223
leal 34(%edx),%eax
stosb #load a random char into allocated memory
popl %ecx
cmpl $0,%ecx
jne loop
movl $4,%eax #syscall write
movl $1,%ebx
movl $43,%edx
popl %ecx #pop the saved adress of string
int $0x80
movl $1,%eax #exit
int $0x80
`
这会导致MOVSB
-操作中出现SEGSB故障
因此,有几件事我不确定:
ESI
前面的MOVSB
,希望整数能被识别为ascii符号,它代表着一个ascii符号LEAL
-操作的正确性,
它的目标是每次跳转到一个新的字节时,只在分配的(42°)字节内存中移动。尽管此故障不能导致segfault,因为它发生在导致MOVSB
的错误之后#####编辑:通过在mmap调用中设置正确的标志并将movsb更改为STOSB,可以修复堆栈错误。您可以使用
strace
检查系统调用。此外,您还应该检查返回的指针。您是否正在尝试将stdin映射为读写?还要保持堆栈平衡(另外我不确定32位进程是否可以在64位机器上使用红色区域)不,32位代码中没有红色区域。机器的底层架构并不重要。就您的代码而言,它运行在32位处理器上,这些调用约定适用。您将在TagWiki中找到关于各种调用约定的信息。mmap的系统调用是从另一篇关于mmap的stackoverflow文章中复制粘贴的。单独运行它可以工作(无故障)。我的字符串处理是否正确?在mmap系统调用之后,eax(指向分配区域的指针应在其中返回)的值为-19,您可以使用strace
检查系统调用。此外,您还应该检查返回的指针。您是否正在尝试将stdin映射为读写?还要保持堆栈平衡(另外我不确定32位进程是否可以在64位机器上使用红色区域)不,32位代码中没有红色区域。机器的底层架构并不重要。就您的代码而言,它运行在32位处理器上,这些调用约定适用。您将在TagWiki中找到关于各种调用约定的信息。mmap的系统调用是从另一篇关于mmap的stackoverflow文章中复制粘贴的。单独运行它可以工作(无故障)。我的字符串处理是否正确?在mmap系统调用之后,eax(应该返回指向已分配区域的指针)的值为-19