From 24c61a3749eaaffffe48eba118f20a42df039158 Mon Sep 17 00:00:00 2001 From: Micah Snyder Date: Wed, 23 Sep 2020 14:59:53 -0700 Subject: [PATCH] Basic C CMake project with Rust static libs --- .gitignore | 90 +++++++++++++ CMakeLists.txt | 50 ++++++++ LICENSE-Apache-2.0.md | 202 +++++++++++++++++++++++++++++ LICENSE-MIT.md | 7 + README.md | 4 +- app/CMakeLists.txt | 14 ++ app/app.c | 28 ++++ cmake/FindRust.cmake | 232 ++++++++++++++++++++++++++++++++++ common/CMakeLists.txt | 9 ++ common/gen_uuid/Cargo.toml | 19 +++ common/gen_uuid/cbindgen.toml | 39 ++++++ common/gen_uuid/gen_uuid.h | 18 +++ common/gen_uuid/gen_uuid.rs | 36 ++++++ lib/CMakeLists.txt | 47 +++++++ lib/cmakerust-version.h.in | 29 +++++ lib/cmakerust.h | 15 +++ lib/colorlog/Cargo.toml | 15 +++ lib/colorlog/cbindgen.toml | 39 ++++++ lib/colorlog/colorlog.h | 22 ++++ lib/colorlog/colorlog.rs | 58 +++++++++ lib/lib.c | 20 +++ lib/lib_private.h | 11 ++ 22 files changed, 1003 insertions(+), 1 deletion(-) create mode 100644 .gitignore create mode 100644 CMakeLists.txt create mode 100644 LICENSE-Apache-2.0.md create mode 100644 LICENSE-MIT.md create mode 100644 app/CMakeLists.txt create mode 100644 app/app.c create mode 100644 cmake/FindRust.cmake create mode 100644 common/CMakeLists.txt create mode 100644 common/gen_uuid/Cargo.toml create mode 100644 common/gen_uuid/cbindgen.toml create mode 100644 common/gen_uuid/gen_uuid.h create mode 100644 common/gen_uuid/gen_uuid.rs create mode 100644 lib/CMakeLists.txt create mode 100644 lib/cmakerust-version.h.in create mode 100644 lib/cmakerust.h create mode 100644 lib/colorlog/Cargo.toml create mode 100644 lib/colorlog/cbindgen.toml create mode 100644 lib/colorlog/colorlog.h create mode 100644 lib/colorlog/colorlog.rs create mode 100644 lib/lib.c create mode 100644 lib/lib_private.h diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f3afb0e --- /dev/null +++ b/.gitignore @@ -0,0 +1,90 @@ +# CMake +CMakeLists.txt.user +CMakeCache.txt +CMakeFiles +CMakeScripts +Testing +Makefile +cmake_install.cmake +install_manifest.txt +compile_commands.json +CTestTestfile.cmake + +# Ninja +.ninja_deps +.ninja_log + +# C Prerequisites +*.d + +# C Object files +*.o +*.ko +*.obj +*.elf + +# C Linker output +*.ilk +*.map +*.exp + +# C Precompiled Headers +*.gch +*.pch + +# C Libraries +*.lib +*.a +*.la +*.lo + +# C Shared objects (inc. Windows DLLs) +*.dll +*.so +*.so.* +*.dylib + +# C Executables +*.exe +*.out +*.app +*.i*86 +*.x86_64 +*.hex + +# C Debug files +*.dSYM/ +*.su +*.idb +*.pdb + +# Editor save files +*~ + +# Vim Swap +[._]*.s[a-v][a-z] +[._]*.sw[a-p] +[._]s[a-rt-v][a-z] +[._]ss[a-gi-z] +[._]sw[a-p] + +# Vim Session +Session.vim + +# Vim Temporary +.netrwhist +*~ +# Vim Auto-generated tag files +tags +# Vim Persistent undo +[._]*.un~ + +# VScode config +.vscode + +# Build directories +install/* +build/* + +# Rust / Cargo files +Cargo.lock diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..f5739f5 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,50 @@ +# Copyright (C) 2020 Micah Snyder. + +cmake_minimum_required(VERSION 3.18) + +project( RustCMakeDemo + VERSION "0.1.0" + DESCRIPTION "A demo app to show a CMake project with components written in Rust." ) + +set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake" ${CMAKE_MODULE_PATH}) + +# +# Find Build Tools +# +set(MAINTAINER_MODE_DEFAULT OFF) +option(MAINTAINER_MODE + "Use `cbindgen` to generate Rust library API headers." + ${MAINTAINER_MODE_DEFAULT}) + +if(MAINTAINER_MODE) + set(cbindgen_REQUIRED 1) +endif() +find_package(Rust REQUIRED) + +# Always use '-fPIC'/'-fPIE' option. +set(CMAKE_POSITION_INDEPENDENT_CODE ON) + +# +# Build targets. +# +add_subdirectory( lib ) +add_subdirectory( common ) +add_subdirectory( app ) + +# +# The Summary Info. +# +string(TOUPPER "${CMAKE_BUILD_TYPE}" _build_type) +message(STATUS "Configuration Options Summary -- + Target system: ${CMAKE_SYSTEM} + Compiler: + Build type: ${CMAKE_BUILD_TYPE} + C compiler: ${CMAKE_C_COMPILER} + Rust toolchain: ${cargo_EXECUTABLE} (${cargo_VERSION}) + CFLAGS: ${CMAKE_C_FLAGS_${_build_type}} ${CMAKE_C_FLAGS} + Build Options: + Maintainer Mode: ${MAINTAINER_MODE}") +if(MAINTAINER_MODE) +message("\ + cbindgen: ${cbindgen_EXECUTABLE} (${cbindgen_VERSION})") +endif() \ No newline at end of file diff --git a/LICENSE-Apache-2.0.md b/LICENSE-Apache-2.0.md new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE-Apache-2.0.md @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE-MIT.md b/LICENSE-MIT.md new file mode 100644 index 0000000..61c4c88 --- /dev/null +++ b/LICENSE-MIT.md @@ -0,0 +1,7 @@ +Copyright 2020 Micah Snyder + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index cfee61c..e52d5d3 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ # Rust CMake Demo -Demo project to show off CMake Rust integration for C projects that use Rust static libs +A C CMake demo using Rust static library components. +The notable feature of this project is [cmake/FindRust.cmake](cmake/FindRust.cmake) +This project is dual-licensed under MIT and Apache 2.0. diff --git a/app/CMakeLists.txt b/app/CMakeLists.txt new file mode 100644 index 0000000..7f00304 --- /dev/null +++ b/app/CMakeLists.txt @@ -0,0 +1,14 @@ +# Copyright (C) 2020 Micah Snyder. + +# +# Build example app that used a static lib written in Rust and a traditional +# shared library writtne in C with some Rust sprinkled in. +# + +# The app. +add_executable( app ) +target_sources( app PRIVATE app.c ) +target_link_libraries( app + PRIVATE + CMakeRust::lib + CMakeRust::gen_uuid ) diff --git a/app/app.c b/app/app.c new file mode 100644 index 0000000..6b3d4ff --- /dev/null +++ b/app/app.c @@ -0,0 +1,28 @@ +/* + * Sample application that uses a common lib to generate a UUID + * and uses the CMakeRust library's colorlog featuer toe log the UUID. + * + * Copyright 2020 (C) Micah Snyder + */ + +#include +#include + +#include "cmakerust.h" +#include "gen_uuid.h" + +int main(void) { + char *my_uuid = {0}; + + my_uuid = gen_uuid(); + + printf("%s\n", (char*)my_uuid); + clog_debug((char*)my_uuid, strlen(my_uuid)); + clog_info((char*)my_uuid, strlen(my_uuid)); + clog_warning((char*)my_uuid, strlen(my_uuid)); + clog_error((char*)my_uuid, strlen(my_uuid)); + + free_uuid(my_uuid); + + return 0; +} \ No newline at end of file diff --git a/cmake/FindRust.cmake b/cmake/FindRust.cmake new file mode 100644 index 0000000..4588cd4 --- /dev/null +++ b/cmake/FindRust.cmake @@ -0,0 +1,232 @@ +# Find the Rust toolchain and add the `add_rust_library()` API to build Rust +# libraries. +# +# Copyright (C) 2020 Micah Snyder. +# +# Code to set the Cargo arguments was lifted from: +# https://github.com/Devolutions/CMakeRust +# +# This Module defines the following variables: +# - _FOUND - True if the program was found +# - _EXECUTABLE - path of the program +# - _VERSION - version number of the program +# +# ... for the following Rust toolchain programs: +# - cargo +# - rustc +# - rustup +# - rust-gdb +# - rust-lldb +# - rustdoc +# - rustfmt +# - bindgen +# - cbindgen +# +# Note that `cbindgen` is presently 3rd-party, and is not included with the +# standard Rust installation. +# +# Callers can make any program mandatory by setting `_REQUIRED` before +# the call to `find_package(Rust)` +# +# Eg: +# +# if(MAINTAINER_MODE) +# set(cbindgen_REQUIRED 1) +# endif() +# find_package(Rust REQUIRED) +# +# This module also provides an `add_rust_library()` function which allows a +# caller to create a Rust static library target which you can link to with +# `target_link_libraries()`. +# +# Your Rust static library target will itself depend on the native static libs +# you get from `cargo rustc -- --print native-static-libs` +# +# Example `add_rust_library()` usage: +# +# add_rust_library(TARGET yourlib WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}") +# add_library(YourProject::yourlib ALIAS yourlib) +# +# add_executable(yourexe) +# target_link_libraries(yourexe YourProject::yourlib) +# + +if(NOT DEFINED CARGO_HOME) + if(WIN32) + set(CARGO_HOME "$ENV{USERPROFILE}/.cargo") + else() + set(CARGO_HOME "$ENV{HOME}/.cargo") + endif() +endif() + +include(FindPackageHandleStandardArgs) + +function(find_rust_program RUST_PROGRAM) + find_program(${RUST_PROGRAM}_EXECUTABLE ${RUST_PROGRAM} + HINTS "${CARGO_HOME}" + PATH_SUFFIXES "bin" + ) + + if(${RUST_PROGRAM}_EXECUTABLE) + execute_process(COMMAND "${${RUST_PROGRAM}_EXECUTABLE}" --version + OUTPUT_VARIABLE ${RUST_PROGRAM}_VERSION_OUTPUT + ERROR_VARIABLE ${RUST_PROGRAM}_VERSION_ERROR + RESULT_VARIABLE ${RUST_PROGRAM}_VERSION_RESULT + ) + if(NOT ${${RUST_PROGRAM}_VERSION_RESULT} EQUAL 0) + message(STATUS "Rust program `${RUST_PROGRAM}` not found: Failed to determine version.") + unset(${RUST_PROGRAM}_EXECUTABLE) + else() + string(REGEX + MATCH "[0-9]+\\.[0-9]+(\\.[0-9]+)?(-nightly)?" + ${RUST_PROGRAM}_VERSION "${${RUST_PROGRAM}_VERSION_OUTPUT}" + ) + set(${RUST_PROGRAM}_VERSION "${${RUST_PROGRAM}_VERSION}" PARENT_SCOPE) + message(STATUS "Rust program `${RUST_PROGRAM}` found: ${${RUST_PROGRAM}_EXECUTABLE}, ${${RUST_PROGRAM}_VERSION}") + endif() + + mark_as_advanced(${RUST_PROGRAM}_EXECUTABLE ${RUST_PROGRAM}_VERSION) + else() + if(${${RUST_PROGRAM}_REQUIRED}) + message(FATAL_ERROR "Rust program `${RUST_PROGRAM}` not found.") + else() + message(STATUS "Rust program `${RUST_PROGRAM}` not found.") + endif() + endif() +endfunction() + +function(add_rust_library) + set(options) + set(oneValueArgs TARGET WORKING_DIRECTORY) + #set(multiValueArgs COMMAND INCLUDE_DIRS) + cmake_parse_arguments(ARGS "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) + + if(WIN32) + set(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${LIB_TARGET}/${LIB_BUILD_TYPE}/${ARGS_TARGET}.lib") + else() + set(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${LIB_TARGET}/${LIB_BUILD_TYPE}/lib${ARGS_TARGET}.a") + endif() + + file(GLOB_RECURSE LIB_SOURCES "${ARGS_WORKING_DIRECTORY}/*.rs") + + set(MY_CARGO_ARGS ${CARGO_ARGS}) + list(APPEND MY_CARGO_ARGS "--target-dir" ${CMAKE_CURRENT_BINARY_DIR}) + list(JOIN MY_CARGO_ARGS " " MY_CARGO_ARGS_STRING) + + # Build the library and generate the c-binding, if `cbindgen` is required. + if(${cbindgen_REQUIRED}) + add_custom_command( + OUTPUT "${OUTPUT}" + COMMAND ${CMAKE_COMMAND} -E env "CARGO_TARGET_DIR=${CMAKE_CURRENT_BINARY_DIR}" ${cargo_EXECUTABLE} ARGS ${MY_CARGO_ARGS} + COMMAND ${cbindgen_EXECUTABLE} --lang c -o ${ARGS_WORKING_DIRECTORY}/${ARGS_TARGET}.h ${ARGS_WORKING_DIRECTORY} + WORKING_DIRECTORY "${ARGS_WORKING_DIRECTORY}" + DEPENDS ${LIB_SOURCES} + COMMENT "Building ${ARGS_TARGET} in ${ARGS_WORKING_DIRECTORY} with:\n\t ${cargo_EXECUTABLE} ${MY_CARGO_ARGS_STRING}") + else() + add_custom_command( + OUTPUT "${OUTPUT}" + COMMAND ${CMAKE_COMMAND} -E env "CARGO_TARGET_DIR=${CMAKE_CURRENT_BINARY_DIR}" ${cargo_EXECUTABLE} ARGS ${MY_CARGO_ARGS} + WORKING_DIRECTORY "${ARGS_WORKING_DIRECTORY}" + DEPENDS ${LIB_SOURCES} + COMMENT "Building ${ARGS_TARGET} in ${ARGS_WORKING_DIRECTORY} with:\n\t ${cargo_EXECUTABLE} ${MY_CARGO_ARGS_STRING}") + endif() + + # Create a target from the build output + add_custom_target(${ARGS_TARGET}_target + DEPENDS ${OUTPUT}) + + # Determine native static lib dependencies + message(STATUS "COMMAND: ${cargo_EXECUTABLE} rustc -- --print native-static-libs") + execute_process( + COMMAND ${CMAKE_COMMAND} -E env "CARGO_TARGET_DIR=${CMAKE_CURRENT_BINARY_DIR}" ${cargo_EXECUTABLE} rustc -- --print native-static-libs + WORKING_DIRECTORY ${ARGS_WORKING_DIRECTORY} + OUTPUT_VARIABLE ${ARGS_TARGET}_NATIVE_STATIC_LIBS_OUTPUT + ERROR_VARIABLE ${ARGS_TARGET}_NATIVE_STATIC_LIBS_ERROR + RESULT_VARIABLE ${ARGS_TARGET}_NATIVE_STATIC_LIBS_RESULT + ) + string(REGEX MATCH "native-static-libs: .*Finished" ${ARGS_TARGET}_NATIVE_STATIC_LIBS "${${ARGS_TARGET}_NATIVE_STATIC_LIBS_ERROR}") + string(REPLACE "native-static-libs: " "" ${ARGS_TARGET}_NATIVE_STATIC_LIBS "${${ARGS_TARGET}_NATIVE_STATIC_LIBS}") + string(REPLACE "Finished" "" ${ARGS_TARGET}_NATIVE_STATIC_LIBS "${${ARGS_TARGET}_NATIVE_STATIC_LIBS}") + string(REGEX REPLACE " " "" ${ARGS_TARGET}_NATIVE_STATIC_LIBS "${${ARGS_TARGET}_NATIVE_STATIC_LIBS}") + string(REGEX REPLACE " $" "" ${ARGS_TARGET}_NATIVE_STATIC_LIBS "${${ARGS_TARGET}_NATIVE_STATIC_LIBS}") + string(REGEX REPLACE "\n" "" ${ARGS_TARGET}_NATIVE_STATIC_LIBS "${${ARGS_TARGET}_NATIVE_STATIC_LIBS}") + string(REGEX REPLACE " " ";" ${ARGS_TARGET}_NATIVE_STATIC_LIBS "${${ARGS_TARGET}_NATIVE_STATIC_LIBS}") + message(STATUS "${ARGS_TARGET} native static library dependencies: ${${ARGS_TARGET}_NATIVE_STATIC_LIBS}") + + # Create a static imported library target from library target + add_library(${ARGS_TARGET} STATIC IMPORTED GLOBAL) + add_dependencies(${ARGS_TARGET} ${ARGS_TARGET}_target) + target_link_libraries(${ARGS_TARGET} INTERFACE ${${ARGS_TARGET}_NATIVE_STATIC_LIBS}) + + # Specify where the library is and where to find the headers + set_target_properties(${ARGS_TARGET} + PROPERTIES + IMPORTED_LOCATION "${OUTPUT}" + INTERFACE_INCLUDE_DIRECTORIES "${ARGS_WORKING_DIRECTORY}" + ) +endfunction() + +# +# Cargo is the primary tool for using the Rust Toolchain to to build static +# libs that can include other crate dependencies. +# +find_rust_program(cargo) + +# These other programs may also be useful... +find_rust_program(rustc) +find_rust_program(rustup) +find_rust_program(rust-gdb) +find_rust_program(rust-lldb) +find_rust_program(rustdoc) +find_rust_program(rustfmt) +find_rust_program(bindgen) +find_rust_program(cbindgen) + +if(WIN32) + if(CMAKE_SIZEOF_VOID_P EQUAL 8) + set(LIB_TARGET "x86_64-pc-windows-msvc") + else() + set(LIB_TARGET "i686-pc-windows-msvc") + endif() +elseif(ANDROID) + if(ANDROID_SYSROOT_ABI STREQUAL "x86") + set(LIB_TARGET "i686-linux-android") + elseif(ANDROID_SYSROOT_ABI STREQUAL "x86_64") + set(LIB_TARGET "x86_64-linux-android") + elseif(ANDROID_SYSROOT_ABI STREQUAL "arm") + set(LIB_TARGET "arm-linux-androideabi") + elseif(ANDROID_SYSROOT_ABI STREQUAL "arm64") + set(LIB_TARGET "aarch64-linux-android") + endif() +elseif(IOS) + set(LIB_TARGET "universal") +elseif(CMAKE_SYSTEM_NAME STREQUAL Darwin) + set(LIB_TARGET "x86_64-apple-darwin") +else() + if(CMAKE_SIZEOF_VOID_P EQUAL 8) + set(LIB_TARGET "x86_64-unknown-linux-gnu") + else() + set(LIB_TARGET "i686-unknown-linux-gnu") + endif() +endif() + +if(IOS) + set(CARGO_ARGS "lipo") +else() + set(CARGO_ARGS "build") + list(APPEND CARGO_ARGS "--target" ${LIB_TARGET}) +endif() + +if(NOT CMAKE_BUILD_TYPE) + set(LIB_BUILD_TYPE "debug") +elseif(${CMAKE_BUILD_TYPE} STREQUAL "Release") + set(LIB_BUILD_TYPE "release") + list(APPEND CARGO_ARGS "--release") +else() + set(LIB_BUILD_TYPE "debug") +endif() + +find_package_handle_standard_args( Rust + REQUIRED_VARS cargo_EXECUTABLE + VERSION_VAR cargo_VERSION +) diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt new file mode 100644 index 0000000..4cea85b --- /dev/null +++ b/common/CMakeLists.txt @@ -0,0 +1,9 @@ +# Copyright (C) 2020 Micah Snyder. + +# +# Rust common libraries +# + +# log Rust replacement for cdiff +add_rust_library(TARGET gen_uuid WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/gen_uuid") +add_library(CMakeRust::gen_uuid ALIAS gen_uuid) diff --git a/common/gen_uuid/Cargo.toml b/common/gen_uuid/Cargo.toml new file mode 100644 index 0000000..cbedfd0 --- /dev/null +++ b/common/gen_uuid/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "gen_uuid" +version = "0.1.0" +authors = ["Micah Snyder "] +edition = "2018" + +[lib] +name = "gen_uuid" +path = "gen_uuid.rs" +crate-type = ["staticlib"] + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +libc = "0.2.77" + +[dependencies.uuid] +version = "0.8.1" +features = ["v4"] diff --git a/common/gen_uuid/cbindgen.toml b/common/gen_uuid/cbindgen.toml new file mode 100644 index 0000000..c6e92bd --- /dev/null +++ b/common/gen_uuid/cbindgen.toml @@ -0,0 +1,39 @@ +# To view thetemplate cbindgen.toml file with all of the default values, visit: +# https://github.com/eqrion/cbindgen/blob/master/template.toml +# +# See https://github.com/eqrion/cbindgen/blob/master/docs.md#cbindgentoml +# for detailed documentation of every option. + +language = "C" + +############## Options for Wrapping the Contents of the Header ################# + +header = "/* Copyright (C) 2020 Micah Snyder. */" +include_guard = "__GEN_UUID_H" +autogen_warning = "/* Warning, this file is autogenerated by cbindgen. Don't modify this manually. */" +sys_includes = [] +includes = [] +no_includes = false +after_includes = "" + +[export] +include = ["gen_uuid", "free_uuid"] +exclude = [] +# prefix = "CAPI_" +item_types = [] +renaming_overrides_prefixing = false + +############## Options for How Your Rust library Should Be Parsed ############## + +[parse] +parse_deps = false +# include = [] +exclude = [] +clean = false +extra_bindings = [] + +[parse.expand] +crates = [] +all_features = false +default_features = true +features = [] diff --git a/common/gen_uuid/gen_uuid.h b/common/gen_uuid/gen_uuid.h new file mode 100644 index 0000000..1323bde --- /dev/null +++ b/common/gen_uuid/gen_uuid.h @@ -0,0 +1,18 @@ +/* Copyright (C) 2020 Micah Snyder. */ + +#ifndef __GEN_UUID_H +#define __GEN_UUID_H + +/* Warning, this file is autogenerated by cbindgen. Don't modify this manually. */ + +#include +#include +#include +#include + + +void free_uuid(char *uuid_ptr); + +char *gen_uuid(void); + +#endif /* __GEN_UUID_H */ diff --git a/common/gen_uuid/gen_uuid.rs b/common/gen_uuid/gen_uuid.rs new file mode 100644 index 0000000..d000076 --- /dev/null +++ b/common/gen_uuid/gen_uuid.rs @@ -0,0 +1,36 @@ +/* + * Example static lib for use in project apps + * + * Copyright (C) 2020 Micah Snyder. + */ + +use libc::c_char; +use std::ffi::CString; + +use uuid::Uuid; + +#[no_mangle] +pub extern "C" fn gen_uuid() -> *mut c_char { + let uuid_str = Uuid::new_v4().to_string(); + + let c_uuid = CString::new(uuid_str).unwrap(); + c_uuid.into_raw() +} + +#[no_mangle] +pub extern "C" fn free_uuid(uuid_ptr: *mut c_char ) -> () { + unsafe { + if uuid_ptr.is_null() { + return; + } + CString::from_raw(uuid_ptr) + }; +} + +#[cfg(test)] +mod tests { + #[test] + fn it_works() { + assert_eq!(2 + 2, 4); + } +} diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt new file mode 100644 index 0000000..30b8bff --- /dev/null +++ b/lib/CMakeLists.txt @@ -0,0 +1,47 @@ +# Copyright (C) 2020 Micah Snyder. + +configure_file(cmakerust-version.h.in cmakerust-version.h) + +# +# Features written in Rust +# +# Note: These will be compiled to static library targets and must be added as +# dependencies to both the C object targets and shared/static library targets. +# + +# Colorful Logging +add_rust_library(TARGET colorlog WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/colorlog") + +configure_file(cmakerust-version.h.in cmakerust-version.h) + +# +# The cmakerust C library +# +add_library( cmakerust_obj OBJECT ) +target_sources( cmakerust_obj + PRIVATE lib.c lib_private.h + PUBLIC cmakerust.h ) +target_link_libraries( cmakerust_obj PUBLIC colorlog ) +target_include_directories( cmakerust_obj PUBLIC ${CMAKE_CURRENT_BINARY_DIR} ) + +# The cmakerust shared library. +add_library( cmakerust SHARED ) +target_sources( cmakerust PUBLIC cmakerust.h ) +target_link_libraries( cmakerust PUBLIC colorlog ) +target_include_directories( cmakerust PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ) +set_target_properties( cmakerust PROPERTIES + LINKER_LANGUAGE C) +if(WIN32) + set_target_properties( cmakerust PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS ON) +endif() +add_library( CMakeRust::lib ALIAS cmakerust ) + +# The cmakerust static library. +add_library( cmakerust_static STATIC ) +target_sources( cmakerust_static PUBLIC cmakerust.h ) +target_link_libraries( cmakerust_static PUBLIC colorlog ) +target_include_directories( cmakerust_static PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ) +set_target_properties( cmakerust_static PROPERTIES + ARCHIVE_OUTPUT_NAME cmakerust_static + LINKER_LANGUAGE C) +add_library( CMakeRust::static_lib ALIAS cmakerust_static ) diff --git a/lib/cmakerust-version.h.in b/lib/cmakerust-version.h.in new file mode 100644 index 0000000..2eaa3c3 --- /dev/null +++ b/lib/cmakerust-version.h.in @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2020 Micah Snyder. + * + * @GENERATE_WARNING@ + */ + +#ifndef __CMAKERUST_VER_H +#define __CMAKERUST_VER_H + +/** + * @macro + * Version number of the cmakerust library. + */ +#define LIBCMAKERUST_VERSION "@LIB_VERSION@" + +/** + * @macro + * Numerical representation of the version number of the cmakerust library. + * + * This is a 24 bit number with: + * - 8 bits for major number + * - 8 bits for minor number + * - 8 bits for patch number. + * + * Eg: Version 1.2.3 becomes 0x010203. + */ +#define LIBCMAKERUST_VERSION_NUM @LIB_VERSION_NUM@ + +#endif /* __CMAKERUST_VER_H */ diff --git a/lib/cmakerust.h b/lib/cmakerust.h new file mode 100644 index 0000000..c40bf7d --- /dev/null +++ b/lib/cmakerust.h @@ -0,0 +1,15 @@ +/* + * Copyright (C) 2020 Micah Snyder. + */ + +#ifndef __CMAKERUST_H +#define __CMAKERUST_H + +#include "cmakerust-version.h" +#include "colorlog.h" + +void cmakerust_init(); + +void cmakerust_fini(); + +#endif /* __CMAKERUST_H */ diff --git a/lib/colorlog/Cargo.toml b/lib/colorlog/Cargo.toml new file mode 100644 index 0000000..e190bd2 --- /dev/null +++ b/lib/colorlog/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "colorlog" +version = "0.1.0" +authors = ["Micah Snyder "] +edition = "2018" + +[lib] +name = "colorlog" +path = "colorlog.rs" +crate-type = ["staticlib"] + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +colored = "2.0.0" diff --git a/lib/colorlog/cbindgen.toml b/lib/colorlog/cbindgen.toml new file mode 100644 index 0000000..8f7ea7b --- /dev/null +++ b/lib/colorlog/cbindgen.toml @@ -0,0 +1,39 @@ +# To view thetemplate cbindgen.toml file with all of the default values, visit: +# https://github.com/eqrion/cbindgen/blob/master/template.toml +# +# See https://github.com/eqrion/cbindgen/blob/master/docs.md#cbindgentoml +# for detailed documentation of every option. + +language = "C" + +############## Options for Wrapping the Contents of the Header ################# + +header = "/* Copyright (C) 2020 Micah Snyder. */" +include_guard = "__COLORLOG_H" +autogen_warning = "/* Warning, this file is autogenerated by cbindgen. Don't modify this manually. */" +sys_includes = [] +includes = [] +no_includes = false +after_includes = "" + +[export] +include = ["clog_debug", "clog_info", "clog_warning", "clog_error"] +exclude = [] +# prefix = "CAPI_" +item_types = [] +renaming_overrides_prefixing = false + +############## Options for How Your Rust library Should Be Parsed ############## + +[parse] +parse_deps = false +# include = [] +exclude = [] +clean = false +extra_bindings = [] + +[parse.expand] +crates = [] +all_features = false +default_features = true +features = [] diff --git a/lib/colorlog/colorlog.h b/lib/colorlog/colorlog.h new file mode 100644 index 0000000..c287f4b --- /dev/null +++ b/lib/colorlog/colorlog.h @@ -0,0 +1,22 @@ +/* Copyright (C) 2020 Micah Snyder. */ + +#ifndef __COLORLOG_H +#define __COLORLOG_H + +/* Warning, this file is autogenerated by cbindgen. Don't modify this manually. */ + +#include +#include +#include +#include + + +void clog_debug(const uint8_t *message, uintptr_t message_len); + +void clog_error(const uint8_t *message, uintptr_t message_len); + +void clog_info(const uint8_t *message, uintptr_t message_len); + +void clog_warning(const uint8_t *message, uintptr_t message_len); + +#endif /* __COLORLOG_H */ diff --git a/lib/colorlog/colorlog.rs b/lib/colorlog/colorlog.rs new file mode 100644 index 0000000..fcc6480 --- /dev/null +++ b/lib/colorlog/colorlog.rs @@ -0,0 +1,58 @@ +/* + * Example static lib for use in project apps + * + * Copyright (C) 2020 Micah Snyder. + */ + +#![feature(c_variadic)] + +use colored::*; + +enum LogLevel { + Debug, + Info, + Warning, + Error, +} + +fn clog(level: LogLevel, message: &str) -> () { + match level { + LogLevel::Debug => println!("Debug: {}", message.green()), + LogLevel::Info => println!("{}", message), + LogLevel::Warning => println!("Warning: {}", message.yellow()), + LogLevel::Error => println!("ERROR: {}", message.bright_red()), + }; +} + +unsafe fn from_c_string<'t>(string: *const u8, string_len: usize) -> &'t str { + let slice = std::slice::from_raw_parts(string, string_len); + std::str::from_utf8(slice as &[u8]).unwrap() +} + +#[no_mangle] +pub unsafe extern "C" fn clog_debug(message: *const u8, message_len: usize) -> () { + clog(LogLevel::Debug, from_c_string(message, message_len)); +} + +#[no_mangle] +pub unsafe extern "C" fn clog_info(message: *const u8, message_len: usize) -> () { + clog(LogLevel::Info, from_c_string(message, message_len)); +} + +#[no_mangle] +pub unsafe extern "C" fn clog_warning(message: *const u8, message_len: usize) -> () { + clog(LogLevel::Warning, from_c_string(message, message_len)); +} + +#[no_mangle] +pub unsafe extern "C" fn clog_error(message: *const u8, message_len: usize) -> () { + clog(LogLevel::Error, from_c_string(message, message_len)); +} + +#[cfg(test)] +mod tests { + #[test] + fn it_works() { + assert_eq!(2 + 2, 4); + } +} diff --git a/lib/lib.c b/lib/lib.c new file mode 100644 index 0000000..f299877 --- /dev/null +++ b/lib/lib.c @@ -0,0 +1,20 @@ +/* + * Example library that has some features written in Rust. + * + * Copyright (C) 2020 Micah Snyder. + */ + +#include +#include + +#include "lib_private.h" +#include "cmakerust.h" +#include "colorlog.h" + +void cmakerust_init() { + clog_debug(init_message, strlen(init_message)); +} + +void cmakerust_fini() { + clog_debug(fini_message, strlen(fini_message)); +} diff --git a/lib/lib_private.h b/lib/lib_private.h new file mode 100644 index 0000000..c265413 --- /dev/null +++ b/lib/lib_private.h @@ -0,0 +1,11 @@ +/* + * Copyright (C) 2020 Micah Snyder. + */ + +#ifndef __LIB_PRIVATE_H +#define __LIB_PRIVATE_H + +const char* init_message = "Initialized!"; +const char* fini_message = "Finito!"; + +#endif /* __CMAKERUST_H */