Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile ASM and C with ASM for debugging

I have two small files that I want to compile in CMake for debugging it with CLion and GDB

main.c

int my_strlen(char *);

int main()
{
    printf("Test: %d\n", my_strlen("Hello"));
}

and I have my ASM file that have a my_strlen file

    [BITS 64]

    global my_strlen
    section .text

my_strlen:
    push rbp
    mov rbp, rsp
    xor rcx, rcx

loop:
    cmp BYTE [rdi + rcx], 0
    jz end
    inc rcx
    jmp loop

end:
    mov rax, rcx
    mov rsp, rbp
    leave
    ret

I'm trying to compile with a CMakeList.txt I add set_source_files_properties but it still doesn't work

cmake_minimum_required(VERSION 3.9)
project(ASM)

set(CMAKE_CXX_STANDARD 11)
set_source_files_properties(src/strlen.asm PROPERTIES COMPILE_FLAGS "-x assembler-with-c")

add_executable(main
        src/strlen.asm
        tests/src/main.c)

Someone knows a good command to add ASM file in a C project and compile with a CMakeList.txt ?

like image 356
Benjamin Sx Avatar asked Mar 06 '18 13:03

Benjamin Sx


1 Answers

You'll probably have to enable NASM support in CMAKE with enable_language(ASM_NASM)and then set appropriate assembly options:

cmake_minimum_required(VERSION 3.9)
project(ASM)
enable_language(ASM_NASM)
set(CMAKE_ASM_NASM_OBJECT_FORMAT elf64)
set(CMAKE_ASM_NASM_COMPILE_OBJECT "<CMAKE_ASM_NASM_COMPILER> <INCLUDES> \
    <FLAGS> -f ${CMAKE_ASM_NASM_OBJECT_FORMAT} -o <OBJECT> <SOURCE>")

set_source_files_properties(src/strlen.asm PROPERTIES COMPILE_FLAGS "-g -Fdwarf")

set(CMAKE_CXX_STANDARD 11)

add_executable(main
        src/strlen.asm
        tests/src/main.c)

Since your code seems to be a 64-bit target I essentially pass -f elf64 as a command line option to NASM. I place the format type in its own environment variable CMAKE_ASM_NASM_OBJECT_FORMAT. To enable debug information in NASM you can use the -g -Fdwarf.


If doing Debug and Release builds you could check for the build type and set the flags accordingly with something like:

cmake_minimum_required(VERSION 3.9)
project(ASM)
enable_language(ASM_NASM)

set(CMAKE_ASM_NASM_OBJECT_FORMAT elf64)
set(CMAKE_ASM_NASM_COMPILE_OBJECT "<CMAKE_ASM_NASM_COMPILER> <INCLUDES> \
    <FLAGS> -f ${CMAKE_ASM_NASM_OBJECT_FORMAT} -o <OBJECT> <SOURCE>")

if(CMAKE_BUILD_TYPE STREQUAL "Debug")
    set(CMAKE_ASM_NASM_FLAGS "${ASM_NASM_FLAGS} -g -Fdwarf")
else()
    set(CMAKE_ASM_NASM_FLAGS "${ASM_NASM_FLAGS}")
endif()

set(CMAKE_CXX_STANDARD 11)

add_executable(main
        src/strlen.asm
        tests/src/main.c)
like image 82
Michael Petch Avatar answered Sep 23 '22 18:09

Michael Petch