Brian Silverman | 20350ac | 2021-11-17 18:19:55 -0800 | [diff] [blame] | 1 | function(find_objcopy_with_weaken) |
| 2 | find_program(OBJCOPY_EXECUTABLE "objcopy") |
| 3 | message(STATUS "Looking for objcopy that supports weaken - ${OBJCOPY_EXECUTABLE}") |
| 4 | if(NOT OBJCOPY_EXECUTABLE) |
| 5 | return() |
| 6 | endif() |
| 7 | set(objcopy_test_src "${CMAKE_CURRENT_BINARY_DIR}/objcopy_test.c") |
| 8 | set(objcopy_test_exe "${CMAKE_CURRENT_BINARY_DIR}/objcopy_test") |
| 9 | file(WRITE ${objcopy_test_src} "void foo() {} int main() { return 0; }") |
| 10 | try_compile(objcopy_test_compiled |
| 11 | ${CMAKE_CURRENT_BINARY_DIR} ${objcopy_test_src} |
| 12 | COPY_FILE ${objcopy_test_exe}) |
| 13 | if(objcopy_test_compiled AND EXISTS ${objcopy_test_exe}) |
| 14 | execute_process( |
| 15 | COMMAND ${OBJCOPY_EXECUTABLE} -W foo ${objcopy_test_exe} |
| 16 | RESULT_VARIABLE objcopy_result) |
| 17 | file(REMOVE ${objcopy_test_exe}) |
| 18 | endif() |
| 19 | if(objcopy_result EQUAL 0) |
| 20 | set(objcopy_weaken ON) |
| 21 | endif() |
| 22 | file(REMOVE ${objcopy_test_src}) |
| 23 | if(objcopy_weaken) |
| 24 | set(objcopy_has_weaken "Success") |
| 25 | set(HAVE_OBJCOPY_WEAKEN TRUE PARENT_SCOPE) |
| 26 | set(OBJCOPY_EXECUTABLE "${OBJCOPY_EXECUTABLE}" PARENT_SCOPE) |
| 27 | else() |
| 28 | set(objcopy_has_weaken "Failed") |
| 29 | endif() |
| 30 | message(STATUS "objcopy has weaken support - ${objcopy_has_weaken}") |
| 31 | endfunction(find_objcopy_with_weaken) |
| 32 | |
| 33 | function(weaken_object target) |
| 34 | if(NOT HAVE_OBJCOPY_WEAKEN) |
| 35 | return() |
| 36 | endif() |
| 37 | # If we have objcopy, make malloc/free/etc weak symbols. That way folks |
| 38 | # can override our malloc if they want to (they can still use tc_malloc). |
| 39 | # Note: the weird-looking symbols are the c++ memory functions: |
| 40 | # (in order) new, new(nothrow), new[], new[](nothrow), delete, delete[] |
| 41 | # In theory this will break if mangling changes, but that seems pretty |
| 42 | # unlikely at this point. Just in case, I throw in versions with an |
| 43 | # extra underscore as well, which may help on OS X. |
| 44 | add_custom_command(TARGET ${target} POST_BUILD |
| 45 | COMMAND "${OBJCOPY_EXECUTABLE}" |
| 46 | -W malloc -W free -W realloc -W calloc -W cfree |
| 47 | -W memalign -W posix_memalign -W valloc -W pvalloc |
| 48 | -W aligned_alloc |
| 49 | -W malloc_stats -W mallopt -W mallinfo -W nallocx |
| 50 | -W _Znwm -W _ZnwmRKSt9nothrow_t -W _Znam -W _ZnamRKSt9nothrow_t |
| 51 | -W _ZdlPv -W _ZdaPv |
| 52 | -W __Znwm -W __ZnwmRKSt9nothrow_t -W __Znam -W __ZnamRKSt9nothrow_t |
| 53 | -W __ZdlPv -W __ZdaPv "$<TARGET_FILE:${target}>") |
| 54 | endfunction() |