0

I am trying to write some assembly code to print a string using the write syscall on ubuntu 32 bit machine. So far what I've got working is:

main.c file:

extern int my_write();


int main(){
    my_write();
    return 0;
}

my_write.s file:

.globl my_write
.type my_write, @function


.section .data
    str: .ascii "this is my string\n"
    len: .quad . - str

.section .text
my_write:

    mov $0x4, %eax # use the write syscall
    mov $0x1, %ebx # write to standard output
    mov $str, %ecx
    mov $len, %edx
    int $0x80      #trap

    mov $0x1, %eax #exit syscall
    mov $0x0, %ebx #exit status of 0
    int $0x80 #trap

I compiled the files with the following command: gcc -Wall main.c my_write.s -o main

It does work and prints "this is my string"

But the string is hardcoded in assembly. My question is - how can I pass my own string from the C file? Something like:

extern int my_write(char *str, int len);


int main(){
    char str[] = "this is my string\n";
    my_write(str, 18);
    return 0;
}
Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Danny
  • 125
  • 1
  • 7
  • 2
    https://stackoverflow.com/questions/2535989/what-are-the-calling-conventions-for-unix-linux-system-calls-and-user-space-f, look for "User interface: function calling". – Nate Eldredge May 16 '21 at 17:25
  • 2
    In 32-bit code the parameters are pushed on the stack before the return address, right to left, so you could do `mov 4(%esp), %ecx ; mov 8(%esp), %edx`. Keep in mind that you're writing 32-bit asm so you'll have to compile your C code with `-m32` to match it, unless you are on an older 32-bit system where this is the default. – Nate Eldredge May 16 '21 at 17:28

0 Answers0