How to create raw binary from assembler “as” command-Collection of common programming errors

  • Yes, you can use otool after assembling and linking the file to extract the code. otool -t will extract the text (code) segment as ASCII hex. For example:

    $ cat hello.S
        .cstring
    LC0:
        .ascii "Hello world!\12\0"
        .text
        .align 4,0x90
    .globl _main
    _main:
        pushl   %ebp
        movl    %esp, %ebp
        subl    $24, %esp
        movl    $LC0, (%esp)
        call    _puts
        xorl    %eax, %eax
        leave
        ret
        .subsections_via_symbols
    $ gcc -m32 hello.S -o hello
    $ otool -t hello
    hello:
    (__TEXT,__text) section
    00001f20 6a 00 89 e5 83 e4 f0 83 ec 10 8b 5d 04 89 1c 24 
    00001f30 8d 4d 08 89 4c 24 04 83 c3 01 c1 e3 02 01 cb 89 
    00001f40 5c 24 08 8b 03 83 c3 04 85 c0 75 f7 89 5c 24 0c 
    00001f50 e8 0b 00 00 00 89 04 24 e8 19 00 00 00 f4 90 90 
    00001f60 55 89 e5 83 ec 18 c7 04 24 a4 1f 00 00 e8 0a 00 
    00001f70 00 00 31 c0 c9 c3 
    $ 
    

    Note that main actually starts at 00001f60:

    $ otool -tv hello
    hello:
    (__TEXT,__text) section
    start:
    00001f20    pushl   $0x00
    00001f22    movl    %esp,%ebp
    00001f24    andl    $0xf0,%esp
    00001f27    subl    $0x10,%esp
    00001f2a    movl    0x04(%ebp),%ebx
    00001f2d    movl    %ebx,(%esp)
    00001f30    leal    0x08(%ebp),%ecx
    00001f33    movl    %ecx,0x04(%esp)
    00001f37    addl    $0x01,%ebx
    00001f3a    shll    $0x02,%ebx
    00001f3d    addl    %ecx,%ebx
    00001f3f    movl    %ebx,0x08(%esp)
    00001f43    movl    (%ebx),%eax
    00001f45    addl    $0x04,%ebx
    00001f48    testl   %eax,%eax
    00001f4a    jne 0x00001f43
    00001f4c    movl    %ebx,0x0c(%esp)
    00001f50    calll   0x00001f60
    00001f55    movl    %eax,(%esp)
    00001f58    calll   0x00001f76
    00001f5d    hlt
    00001f5e    nop
    00001f5f    nop
    _main:
    00001f60    pushl   %ebp
    00001f61    movl    %esp,%ebp
    00001f63    subl    $0x18,%esp
    00001f66    movl    $0x00001fa4,(%esp)
    00001f6d    calll   0x00001f7c
    00001f72    xorl    %eax,%eax
    00001f74    leave
    00001f75    ret
    $
    
  • No, as assembler translates source code into object files, like most, if not all, assemblers do. Then you have to use linker in order to link one or more object files, possible with runtime libraries, in order to create an executable file.