Last active
December 31, 2020 10:32
-
-
Save rethab/083e6a21b33c4d0be4c87d23e70522a0 to your computer and use it in GitHub Desktop.
string concat in x86-64 assembly AT&T. run with `gcc string-concat.s -o concat && ./concat`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.data | |
.stringfmt: | |
.string "'%s'\n" | |
.s1: | |
.asciz "ab" | |
.s2: | |
.asciz "cd" | |
.text | |
.global main | |
main: | |
PUSHQ %rbp | |
MOVQ %rsp, %rbp | |
LEA .s1(%rip), %rdi | |
LEA .s2(%rip), %rsi | |
CALL concat | |
MOVQ %rax, %rsi | |
LEA .stringfmt(%rip), %rdi | |
XOR %rax, %rax | |
CALL printf | |
LEAVE | |
RET | |
concat: | |
PUSHQ %rbp | |
MOVQ %rsp, %rbp | |
# calc strlen of s1 | |
CALL strlen # s1 is already in rdi | |
MOVQ %rax, %r8 # index in s1 | |
XOR %r10, %r10 # tmp character to copy | |
XOR %rbx, %rbx # index in s2 | |
# copy character by character | |
concat_copy: | |
MOVB 0(%rsi, %rbx, 1), %r10b # r10b=s2[rbx] | |
CMP $0, %r10b | |
JE concat_end # end if s2[rbx] is 0 | |
MOVB %r10b, 0(%rdi, %r8, 1) # s1[r8]=s2[rbx] | |
INC %rbx # rbx++ | |
INC %r8 # r8++ | |
JMP concat_copy | |
concat_end: | |
MOVB $0, 0(%rdi, %r8, 1) # terminate s1 with 0 | |
MOVQ %rdi, %rax | |
LEAVE | |
RET | |
strlen: | |
PUSHQ %rbp | |
MOVQ %rsp, %rbp | |
XOR %r10, %r10 # tmp character | |
XOR %rbx, %rbx # counter | |
strlen_loop: | |
MOVB 0(%rdi, %rbx, 1), %r10b | |
CMP $0, %r10b | |
JE strlen_end | |
INC %rbx | |
JMP strlen_loop | |
strlen_end: | |
MOVQ %rbx, %rax | |
LEAVE | |
RET |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment