cmake_minimum_required(VERSION 3.1)

set(EZTRACE_BINARY_INSTRUMENTATION_SOURCES
  binary.h
  errors.c
  include/eztrace-instrumentation/errors.h
  include/eztrace-instrumentation/linux.h
  include/eztrace-instrumentation/pptrace.h
  pptrace.c
  proc_maps.c
  proc_maps.h
  include/eztrace-instrumentation/tracing.h
  tracing.c
)

SET(COMPILE_FLAGS "")

if(ENABLE_BIN_INSTRUMENTATION)

  list(APPEND EZTRACE_BINARY_INSTRUMENTATION_SOURCES
    binary_instrumentation/bfd.c
    binary_instrumentation/binary.c
    binary_instrumentation/hijack.c
    binary_instrumentation/hijack.h
    binary_instrumentation/isize.h
    binary_instrumentation/memory.c
    binary_instrumentation/memory.h
    binary_instrumentation/opcodes.h
  )

if(CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "x86_64")
  list(APPEND EZTRACE_BINARY_INSTRUMENTATION_SOURCES
    binary_instrumentation/arch/x86_64/hijack.c
    binary_instrumentation/arch/x86_64/intel.c)

  if(LIBOPCODES_FOUND)
    list(APPEND EZTRACE_BINARY_INSTRUMENTATION_SOURCES
      binary_instrumentation/arch/x86_64/opcode.c)
  else()
    list(APPEND EZTRACE_BINARY_INSTRUMENTATION_SOURCES
      binary_instrumentation/arch/x86_64/trace.c)
  endif()

  string(APPEND COMPILE_FLAGS -DHAVE_CHECK_INSTRUCTIONS)

endif()

if(CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "arm")
  list(APPEND EZTRACE_BINARY_INSTRUMENTATION_SOURCES
    binary_instrumentation/arch/armv7/arm.c
    binary_instrumentation/arch/armv7/opcode.c
    binary_instrumentation/arch/armv7/trace.c)
endif()

  set(EZTRACE_BINARY_INSTRUMENTATION_DEPS
    PRIVATE
      bfd
      opcodes
  )
endif()

add_library(eztrace-instrumentation SHARED ${EZTRACE_BINARY_INSTRUMENTATION_SOURCES})

target_include_directories(eztrace-instrumentation
  PUBLIC
    $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
    $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDE_DIR}>
  PRIVATE
    ${CMAKE_CURRENT_SOURCE_DIR}/binary_instrumentation
    ${CMAKE_CURRENT_SOURCE_DIR}
)

target_compile_options(eztrace-instrumentation
  PUBLIC
    ${EZTRACE_BINARY_INSTRUMENTATION_FLAG}
  PRIVATE
    # -Werror # TODO
    ${COMPILE_FLAGS}
)

target_link_libraries(eztrace-instrumentation
    ${EZTRACE_BINARY_INSTRUMENTATION_DEPS}
  PUBLIC
    eztrace-core
)

if (ENABLE_BIN_INSTRUMENTATION)
  target_link_libraries(eztrace-instrumentation
    PRIVATE
  )
endif()


install(TARGETS eztrace-instrumentation EXPORT EZTraceInstrumentationTargets
  LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
)

install(EXPORT EZTraceInstrumentationTargets
  FILE EZTraceInstrumentation.cmake
  NAMESPACE EZTrace::
  DESTINATION cmake
)

install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/include/eztrace-instrumentation DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
