How to generate a nasm compilable assembly code from c source code on Linux?

自作多情 提交于 2019-11-27 00:02:27

问题


Test platform is 32 bit Linux.

Basically, I know gcc can be used to generate both Intel and At&T style assembly code, but it seems that you can not directly use nasm/tasm to compile the Intel style assembly code gcc generated.

I am conducting a project analysis asm code on both windows and Linux platform, so I am thinking if they can be both compiled by platform independent assembler like nasm\yasm, I could have a much easier time...

So my question is how to generate a nasm compilable assembly code from c source code on Linux?


回答1:


I find it's a better approach to disassemble the object files rather than use assembly code generated by gcc.

  1. First, generate an object file from your source code:

    gcc -fno-asynchronous-unwind-tables -O2 -s -c -o main.o main.c
    

    -fno-asynchronous-unwind-tables: do not generate unnecessary sections like .eh_frame

    -O2 optimizes so the asm isn't horrible. Optionally use -Os (size over speed) or -O3 (full optimization including auto-vectorization). Also you can tune for a CPU and and use extensions it supports with -march=native or -march=haswell or -march=znver1 (Zen)

    -s: make smaller executable (strip)

    -c -o main.o: compile but don't link, generate an object file called main.o

  2. Use objconv to generate nasm code:

    objconv -fnasm main.o
    

    The result will be stored in main.asm.

  3. The result will be very close to Nasm syntax. However you might need to make some minor tweaks to eliminiate warnings/errors. Simply try to compile it with Nasm

    nasm -f elf32 main.asm
    

    and fix the errors/warnings by hand. For example:

    • remove the align=N and execute/noexecute words from .SECTION lines.
    • remove the text : function from global declarations
    • remove the default rel line
    • remove empty sections if you wish etc
  4. Link the resulting main.o which generated by Nasm in step 3 using gcc:

    gcc main.o
    

    You can also link it using ld but it's much harder.




回答2:


If you're lazy: https://github.com/diogovk/c2nasm

There I have a script that does Babken Vardanyan's suggestion automatically.




回答3:


Heres a way to do it without objconv

ndisasm -u <(objdump -j .text -d main.o | cut -d: -f2 | cut -d$'\t' -f 2 | perl -ne 'next if /file/; s/\s+//g; print' | xxd -r -p)


来源:https://stackoverflow.com/questions/20737947/how-to-generate-a-nasm-compilable-assembly-code-from-c-source-code-on-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!