简体   繁体   English

如何使用x86程序集操作字符串?

[英]How to manipulate strings with x86 assembly?

I'm in the process of writing an assembly program that takes two strings as input and concatenates them. 我正在编写一个汇编程序,该程序将两个字符串作为输入并将它们连接起来。 Here's what I have: (using NASM syntax) 这是我所拥有的:( 使用NASM语法)

    SECTION .data
hello:  db "Hello ",0
world:  db "world!",0

    SECTION .text

; do the concatenation

Since I've never done any work with strings in x86 assembly before, I need to know how storing and manipulating strings work in the first place. 由于以前从未在x86汇编中对字符串进行过任何处理,因此我需要首先了解如何存储和操作字符串。

I'm guessing that once the length of each string is known, that concatenating would simply involve moving chunks of memory around. 我猜想一旦知道每个字符串的长度,那么连接将只涉及到移动内存块。 This part can be simplified by using libc . 可以使用libc简化此部分。 (I can use strlen() and strcat() .) (我可以使用strlen()strcat() 。)

My real problem is that I'm not familiar with the way strings are stored in x86 assembly. 我真正的问题是我对x86程序集中存储字符串的方式不熟悉。 Do they just get added to the stack...? 他们只是被添加到堆栈中吗...? Do they go on a heap somewhere? 他们会堆放在某个地方吗? Should I use malloc() (somehow)? 我应该使用malloc() (以某种方式)吗?

The strings in your example are stored the same way a global character array would be stored by a C program. 示例中的字符串的存储方式与C程序存储全局字符数组的方式相同。 They're just a series of bytes in the data section of your executable. 它们只是可执行文件的data部分中的一系列字节。 If you want to concatenate them, you're going to need some space to do it - either do it on the stack, or call malloc() to get yourself some memory. 如果要串联它们,则将需要一些空间来执行此操作-在堆栈上执行此操作,或调用malloc()获取一些内存。 As you say, you can just use strcat() if you are willing to call out to libc . 如您所说,如果您愿意调用libc ,则可以只使用strcat() Here's a quick example I made (AT&T syntax), using a global buffer to concatenate the strings, then print them out: 这是我制作的一个简单示例(AT&T语法),使用全局缓冲区连接字符串,然后将其打印出来:

  .data
hello:
  .asciz "Hello "
world:
  .asciz "world!"
buffer:
  .space 100

  .text
  .globl _main
  .globl _puts
  .globl _strcat

_main:
  push  %rbp
  mov   %rsp, %rbp
  leaq  buffer(%rip), %rdi
  leaq  hello(%rip), %rsi
  callq _strcat
  leaq  buffer(%rip), %rdi
  leaq  world(%rip), %rsi
  callq _strcat
  leaq  buffer(%rip), %rdi
  callq _puts
  mov   $0, %rax
  pop   %rbp
  retq

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM