jedisct1 / libsodium

A modern, portable, easy to use crypto library.
https://libsodium.org
Other
12.08k stars 1.72k forks source link

Conditional compilation always returns 0 #1090

Closed Ravbug closed 2 years ago

Ravbug commented 2 years ago

When I compile libsodium 1.0.18 for Linux (gcc), iOS, or macOS (clang), I'm getting the unavailable definitions for functions, for example, crypto_aead_aes256gcm_is_available due to conditional compilation is defined as

int
crypto_aead_aes256gcm_is_available(void)
{
    return 0;
}

I'm compiling the library using CMake. My CMakeLists.txt (adapted from here) looks like this:

file(GLOB_RECURSE ALL_SRC "libsodium/src/*.c" "libsodium/src/*.h")
add_library(${PROJECT_NAME}
    ${ALL_SRC}
)

set_target_properties(${PROJECT_NAME}
    PROPERTIES
        C_STANDARD 99
)

target_include_directories(${PROJECT_NAME}
    PUBLIC
        libsodium/src/libsodium/include
    PRIVATE
        libsodium/src/libsodium/include/sodium
)

target_compile_definitions(${PROJECT_NAME}
    PUBLIC
        $<$<NOT:$<BOOL:${BUILD_SHARED_LIBS}>>:SODIUM_STATIC>
        $<$<BOOL:${SODIUM_MINIMAL}>:SODIUM_LIBRARY_MINIMAL>
    PRIVATE
        CONFIGURED
        $<$<BOOL:${BUILD_SHARED_LIBS}>:SODIUM_DLL_EXPORT>
        $<$<BOOL:${SODIUM_ENABLE_BLOCKING_RANDOM}>:USE_BLOCKING_RANDOM>
        $<$<BOOL:${SODIUM_MINIMAL}>:MINIMAL>
)

# Variables that need to be exported to version.h.in
set(VERSION 1.0.18)
set(SODIUM_LIBRARY_VERSION_MAJOR 10)
set(SODIUM_LIBRARY_VERSION_MINOR 3)

configure_file(
    libsodium/src/libsodium/include/sodium/version.h.in
    ${CMAKE_CURRENT_SOURCE_DIR}/libsodium/src/libsodium/include/sodium/version.h
)

When I use this CMake file on Windows (MSVC) it works correctly and I get the definition from line 914 as expected:

int
crypto_aead_aes256gcm_is_available(void)
{
    return sodium_runtime_has_pclmul() & sodium_runtime_has_aesni();
}

How can I resolve this for the other platforms?

mouse07410 commented 2 years ago

Perhaps try to pass to clang flags -maes -mpcmul -march=native?

Ravbug commented 2 years ago

I get the same result with those flags. I'm passing them like this:

if (NOT MSVC)
    target_compile_options(${PROJECT_NAME} PUBLIC -maes -mpclmul)
endif()

The -march=native flag does not work on Apple Clang but with g++ on Linux passing it did not have an effect either.

jedisct1 commented 2 years ago

Libsodium was never meant to be compiled with cmake. The source code doesn't include any support for cmake. Compiling it in a custom way explicitly prints that this is unsupported.

Of course, you are free to invent your own build system, but then, please understand that you are on your own. Bug reports for 3rd party projects such as libsodium-cmake should be reported there.