Skip to content

Instantly share code, notes, and snippets.

@rethab
Created December 31, 2020 11:11
Show Gist options
  • Save rethab/aae5b1a9c59cce2d28532c5a2452368b to your computer and use it in GitHub Desktop.
Save rethab/aae5b1a9c59cce2d28532c5a2452368b to your computer and use it in GitHub Desktop.
concat string in dynamic memory using malloc from x86-64 assembly with at&t syntax
.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
# store s2 and s1 on stack while doing prepration ops
PUSHQ %rsi
PUSHQ %rdi
# calc strlen of s2
MOVQ %rsi, %rdi
CALL strlen
MOVQ %rax, %r9 # length of s2
# allocate len(s1) + len(s2) + 1
ADDQ %r8, %r9
INC %r9 # terminating space
MOVQ %r9, %rdi
CALL malloc
MOVQ %rax, %rbx # rbx now points to the address of the allocated memory
MOVQ %rbx, %rdi # newly allocated memory
POPQ %rsi # pop s1 back from stack
CALL strcpy # copy 1
MOVQ %rax, %rdi # result of prev strcpy points to end of string
POPQ %rsi # pop s2 from stack
CALL strcat # append s2
MOVQ %rbx, %rax
LEAVE
RET
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment