linuxassemblyx86-64att

assembly store text into an external file


How to write data into an external file on Linux?

For instance, if I start the code with .include "output.s" and want to write "1111 0000" into it, then how to do this.


Solution

  • The best way to do file I/O is to use the libc. Envision how you would do it in C, then do the same thing in assembly. For example, in C you could do

    int main() {
        ssize_t n;
        int fd;
        char buf[9] = "1111 0000";
    
        fd = creat("output.s", 0666);
        if (fd == -1) {
            perror("output.s");
            return (EXIT_FAILURE);
        }
    
        n = write(fd, buf, sizeof buf);
        if (n == -1) {
            perror("output.s");
            return (EXIT_FAILURE);
        }
    
        close(fd);
    
        return (EXIT_SUCCESS);
    }
    

    Next, translate the code step by step into assembly:

            .data
    name:   .string "output.s"              # the file name
    buf:    .ascii  "1111 0000"
    buflen=         .-buf                   # the length of buf
    
            .text
            .globl  main
            .type   main, @function
    
    main:   push    %rbx                    # free rbx and align stack
    
            lea     name(%rip), %rdi        # file name
            mov     $0666, %esi             # initial permissions
            call    creat                   # create the file
            cmp     $-1, %eax               # was the call successful?
            je      .Lfail                  # if not, process error
    
            mov     %eax, %ebx              # stash a copy of the file descriptor
            mov     %eax, %edi              # file descriptor
            lea     buf(%rip), %rsi         # buffer
            mov     $buflen, %edx           # buffer length
            call    write                   # write data
            cmp     $-1, %rax               # was the call successful?
            je      .Lfail                  # if not, process error
    
            mov     %ebx, %edi              # file descriptor
            call    close                   # close the file
    
            xor     %eax, %eax              # return EXIT_SUCCESS
            pop     %rbx                    # restore %rbx
            ret
    
    .Lfail: lea     name(%rip), %rdi        # the file name
            call    perror                  # print an error message
    
            mov     $1, %eax                # return EXIT_FAILURE
            pop     %rbx                    # restore %rbx
            ret
    
            .size   main, .-main