Add ability to get the LDK and LDK-C-Bindings version
[ldk-c-bindings] / genbindings.sh
1 #!/usr/bin/env bash
2
3 set -e
4 set -x
5
6 if [ ! -d "$1/lightning" -o "$2" != "true" -a "$2" != "false" ]; then
7         echo "USAGE: $0 path-to-rust-lightning allow-std"
8         echo "allow-std must be either 'true' or 'false' to indicate if we should be built relying on time and pthread support"
9         exit 1
10 fi
11
12 # On reasonable systems, we can use realpath here, but OSX is a diva with 20-year-old software.
13 ORIG_PWD="$(pwd)"
14 cd "$1"
15 LIGHTNING_PATH="$(pwd)"
16 LIGHTNING_GIT="$(git describe --tag --dirty)"
17 cd "$ORIG_PWD"
18
19 # Generate (and reasonably test) C bindings
20
21 # First build the latest c-bindings-gen binary
22 cd c-bindings-gen && cargo build --release && cd ..
23
24 # Then wipe all the existing C bindings (because we're being run in the right directory)
25 # note that we keep the few manually-generated files first:
26 mv lightning-c-bindings/src/c_types/mod.rs ./
27 mv lightning-c-bindings/src/bitcoin ./
28
29 # Before we try to sed the Cargo.toml, generate version define tags
30 # (ignoring any files that we're about to generate)
31
32 git checkout lightning-c-bindings/src
33 git checkout lightning-c-bindings/include
34 BINDINGS_GIT="$(git describe --tag --dirty)"
35 echo -e "#ifndef _LDK_HEADER_VER" > lightning-c-bindings/include/ldk_ver.h
36 echo -e "static inline int _ldk_strncmp(const char *s1, const char *s2, uint64_t n) {" >> lightning-c-bindings/include/ldk_ver.h
37 echo -e "\tif (n && *s1 != *s2) return 1;" >> lightning-c-bindings/include/ldk_ver.h
38 echo -e "\twhile (n && *s1 != 0 && *s2 != 0) {" >> lightning-c-bindings/include/ldk_ver.h
39 echo -e "\t\ts1++; s2++; n--;" >> lightning-c-bindings/include/ldk_ver.h
40 echo -e "\t\tif (n && *s1 != *s2) return 1;" >> lightning-c-bindings/include/ldk_ver.h
41 echo -e "\t}" >> lightning-c-bindings/include/ldk_ver.h
42 echo -e "\treturn 0;" >> lightning-c-bindings/include/ldk_ver.h
43 echo -e "}" >> lightning-c-bindings/include/ldk_ver.h
44 echo -e "" >> lightning-c-bindings/include/ldk_ver.h
45 echo -e "#define _LDK_HEADER_VER \"$LIGHTNING_GIT\"" >> lightning-c-bindings/include/ldk_ver.h
46 echo -e "#define _LDK_C_BINDINGS_HEADER_VER \"$BINDINGS_GIT\"" >> lightning-c-bindings/include/ldk_ver.h
47 echo -e "static inline const char* check_get_ldk_version() {" >> lightning-c-bindings/include/ldk_ver.h
48 echo -e "\tLDKStr bin_ver = _ldk_get_compiled_version();" >> lightning-c-bindings/include/ldk_ver.h
49 echo -e "\tif (_ldk_strncmp(_LDK_HEADER_VER, (const char*)bin_ver.chars, bin_ver.len) != 0) {" >> lightning-c-bindings/include/ldk_ver.h
50 echo -e "\t// Version mismatch, we don't know what we're running!" >> lightning-c-bindings/include/ldk_ver.h
51 echo -e "\t\treturn 0;" >> lightning-c-bindings/include/ldk_ver.h
52 echo -e "\t}" >> lightning-c-bindings/include/ldk_ver.h
53 echo -e "\treturn _LDK_HEADER_VER;" >> lightning-c-bindings/include/ldk_ver.h
54 echo -e "}" >> lightning-c-bindings/include/ldk_ver.h
55 echo -e "static inline const char* check_get_ldk_bindings_version() {" >> lightning-c-bindings/include/ldk_ver.h
56 echo -e "\tLDKStr bin_ver = _ldk_c_bindings_get_compiled_version();" >> lightning-c-bindings/include/ldk_ver.h
57 echo -e "\tif (_ldk_strncmp(_LDK_C_BINDINGS_HEADER_VER, (const char*)bin_ver.chars, bin_ver.len) != 0) {" >> lightning-c-bindings/include/ldk_ver.h
58 echo -e "\t// Version mismatch, we don't know what we're running!" >> lightning-c-bindings/include/ldk_ver.h
59 echo -e "\t\treturn 0;" >> lightning-c-bindings/include/ldk_ver.h
60 echo -e "\t}" >> lightning-c-bindings/include/ldk_ver.h
61 echo -e "\treturn _LDK_C_BINDINGS_HEADER_VER;" >> lightning-c-bindings/include/ldk_ver.h
62 echo -e "}" >> lightning-c-bindings/include/ldk_ver.h
63 echo -e "#endif /* _LDK_HEADER_VER */" >> lightning-c-bindings/include/ldk_ver.h
64
65 rm -rf lightning-c-bindings/src
66
67 mkdir -p lightning-c-bindings/src/{c_types,lightning}
68 mv ./mod.rs lightning-c-bindings/src/c_types/
69 mv ./bitcoin lightning-c-bindings/src/
70
71 # Finally, run the c-bindings-gen binary, building fresh bindings.
72 OUT="$(pwd)/lightning-c-bindings/src"
73 OUT_TEMPL="$(pwd)/lightning-c-bindings/src/c_types/derived.rs"
74 OUT_F="$(pwd)/lightning-c-bindings/include/ldk_rust_types.h"
75 OUT_CPP="$(pwd)/lightning-c-bindings/include/lightningpp.hpp"
76 BIN="$(pwd)/c-bindings-gen/target/release/c-bindings-gen"
77
78 HOST_PLATFORM="$(rustc --version --verbose | grep "host:")"
79
80 function add_crate() {
81         pushd "$LIGHTNING_PATH/$1"
82         RUSTC_BOOTSTRAP=1 cargo rustc --profile=check $3 -- -Zunstable-options --pretty=expanded > /tmp/$1-crate-source.txt
83         popd
84         if [ "$HOST_PLATFORM" = "host: x86_64-apple-darwin" ]; then
85                 sed -i".original" "1i\\
86 pub mod $2 {
87 " /tmp/$1-crate-source.txt
88         else
89                 sed -i "1ipub mod $2 {\n" /tmp/$1-crate-source.txt
90         fi
91         echo "}" >> /tmp/$1-crate-source.txt
92         cat /tmp/$1-crate-source.txt >> /tmp/crate-source.txt
93         rm /tmp/$1-crate-source.txt
94         if [ "$HOST_PLATFORM" = "host: x86_64-apple-darwin" ]; then
95                 # OSX sed is for some reason not compatible with GNU sed
96                 sed -E -i '' 's|#?'$1' = \{ .*|'$1' = \{ path = "'"$LIGHTNING_PATH"'/'$1'" '"$4"' }|' lightning-c-bindings/Cargo.toml
97         else
98                 sed -E -i 's|#?'$1' = \{ .*|'$1' = \{ path = "'"$LIGHTNING_PATH"'/'$1'" '"$4"' }|' lightning-c-bindings/Cargo.toml
99         fi
100 }
101
102 function drop_crate() {
103         if [ "$HOST_PLATFORM" = "host: x86_64-apple-darwin" ]; then
104                 # OSX sed is for some reason not compatible with GNU sed
105                 sed -E -i '' 's|'$1' = \{ (.*)|#'$1' = \{ \1|' lightning-c-bindings/Cargo.toml
106         else
107                 sed -E -i 's|'$1' = \{ (.*)|#'$1' = \{ \1|' lightning-c-bindings/Cargo.toml
108         fi
109 }
110
111 echo > /tmp/crate-source.txt
112 if [ "$2" = "true" ]; then
113         add_crate lightning lightning --features=allow_wallclock_use ', features = ["allow_wallclock_use"]'
114         add_crate "lightning-persister" "lightning_persister"
115 else
116         add_crate lightning lightning
117         drop_crate "lightning-persister"
118 fi
119 add_crate "lightning-invoice" "lightning_invoice"
120
121 cat /tmp/crate-source.txt | RUST_BACKTRACE=1 "$BIN" "$OUT/" "$OUT_TEMPL" "$OUT_F" "$OUT_CPP"
122
123 echo -e '#[no_mangle]' >> lightning-c-bindings/src/version.rs
124 echo -e 'pub extern "C" fn _ldk_get_compiled_version() -> crate::c_types::Str {' >> lightning-c-bindings/src/version.rs
125 echo -e '\t"'"$LIGHTNING_GIT"'".into()' >> lightning-c-bindings/src/version.rs
126 echo -e '}' >> lightning-c-bindings/src/version.rs
127 echo -e '#[no_mangle]' >> lightning-c-bindings/src/version.rs
128 echo -e 'pub extern "C" fn _ldk_c_bindings_get_compiled_version() -> crate::c_types::Str {' >> lightning-c-bindings/src/version.rs
129 echo -e '\t"'"$BINDINGS_GIT"'".into()' >> lightning-c-bindings/src/version.rs
130 echo -e '}' >> lightning-c-bindings/src/version.rs
131
132 # Set path to include our rustc wrapper as well as cbindgen
133 PATH="$(pwd)/deterministic-build-wrappers:$PATH:~/.cargo/bin"
134 # Now cd to lightning-c-bindings, build the generated bindings, and call cbindgen to build a C header file
135 cd lightning-c-bindings
136
137 # Remap paths so that our builds are deterministic
138 export RUSTFLAGS="--remap-path-prefix $LIGHTNING_PATH=rust-lightning --remap-path-prefix $(pwd)=ldk-c-bindings --remap-path-prefix $HOME/.cargo= -C target-cpu=generic"
139
140 # If the C compiler supports it, also set -ffile-prefix-map
141 echo "int main() {}" > genbindings_path_map_test_file.c
142 clang -o /dev/null -ffile-prefix-map=$HOME/.cargo= genbindings_path_map_test_file.c > /dev/null 2>&1 &&
143 # Now that we've done our last non-LTO build, turn on LTO in CFLAGS as well
144 export CFLAGS="-ffile-prefix-map=$HOME/.cargo="
145 rm genbindings_path_map_test_file.c
146
147 cargo build
148 cbindgen -v --config cbindgen.toml -o include/lightning.h >/dev/null 2>&1
149
150 # cbindgen is relatively braindead when exporting typedefs -
151 # it happily exports all our typedefs for private types, even with the
152 # generics we specified in C mode! So we drop all those types manually here.
153 if [ "$HOST_PLATFORM" = "host: x86_64-apple-darwin" ]; then
154         # OSX sed is for some reason not compatible with GNU sed
155         sed -i '' 's/typedef LDKnative.*Import.*LDKnative.*;//g' include/lightning.h
156
157         # stdlib.h doesn't exist in clang's wasm sysroot, and cbindgen
158         # doesn't actually use it anyway, so drop the import.
159         sed -i '' 's/#include <stdlib.h>/#include <ldk_rust_types.h>/g' include/lightning.h
160 else
161         sed -i 's/typedef LDKnative.*Import.*LDKnative.*;//g' include/lightning.h
162
163         # stdlib.h doesn't exist in clang's wasm sysroot, and cbindgen
164         # doesn't actually use it anyway, so drop the import.
165         sed -i 's/#include <stdlib.h>/#include <ldk_rust_types.h>/g' include/lightning.h
166 fi
167
168 # Finally, sanity-check the generated C and C++ bindings with demo apps:
169
170 LOCAL_CFLAGS="-Wall -Wno-nullability-completeness -pthread -Iinclude/"
171
172 # Naively run the C demo app:
173 gcc $LOCAL_CFLAGS -Wall -g -pthread demo.c target/debug/libldk.a -ldl
174 ./a.out
175
176 # And run the C++ demo app in valgrind to test memory model correctness and lack of leaks.
177 g++ $LOCAL_CFLAGS -std=c++11 -Wall -g -pthread demo.cpp -Ltarget/debug/ -lldk -ldl
178 if [ -x "`which valgrind`" ]; then
179         LD_LIBRARY_PATH=target/debug/ valgrind --error-exitcode=4 --memcheck:leak-check=full --show-leak-kinds=all ./a.out
180         echo
181 else
182         echo "WARNING: Please install valgrind for more testing"
183 fi
184
185 # Test a statically-linked C++ version, tracking the resulting binary size and runtime
186 # across debug, LTO, and cross-language LTO builds (using the same compiler each time).
187 clang++ $LOCAL_CFLAGS -std=c++11 demo.cpp target/debug/libldk.a -ldl
188 strip ./a.out
189 echo " C++ Bin size and runtime w/o optimization:"
190 ls -lha a.out
191 time ./a.out > /dev/null
192
193 # Then, check with memory sanitizer, if we're on Linux and have rustc nightly
194 if [ "$HOST_PLATFORM" = "host: x86_64-unknown-linux-gnu" ]; then
195         if cargo +nightly --version >/dev/null 2>&1; then
196                 LLVM_V=$(rustc +nightly --version --verbose | grep "LLVM version" | awk '{ print substr($3, 0, 2); }')
197                 if [ -x "$(which clang-$LLVM_V)" ]; then
198                         cargo +nightly clean
199                         cargo +nightly rustc -Zbuild-std --target x86_64-unknown-linux-gnu -v -- -Zsanitizer=memory -Zsanitizer-memory-track-origins -Cforce-frame-pointers=yes
200                         mv target/x86_64-unknown-linux-gnu/debug/libldk.* target/debug/
201
202                         # Sadly, std doesn't seem to compile into something that is memsan-safe as of Aug 2020,
203                         # so we'll always fail, not to mention we may be linking against git rustc LLVM which
204                         # may differ from clang-llvm, so just allow everything here to fail.
205                         set +e
206
207                         # First the C demo app...
208                         clang-$LLVM_V $LOCAL_CFLAGS -fsanitize=memory -fsanitize-memory-track-origins -g demo.c target/debug/libldk.a -ldl
209                         ./a.out
210
211                         # ...then the C++ demo app
212                         clang++-$LLVM_V $LOCAL_CFLAGS -std=c++11 -fsanitize=memory -fsanitize-memory-track-origins -g demo.cpp target/debug/libldk.a -ldl
213                         ./a.out >/dev/null
214
215                         # restore exit-on-failure
216                         set -e
217                 else
218                         echo "WARNING: Can't use memory sanitizer without clang-$LLVM_V"
219                 fi
220         else
221                 echo "WARNING: Can't use memory sanitizer without rustc nightly"
222         fi
223 else
224         echo "WARNING: Can't use memory sanitizer on non-Linux, non-x86 platforms"
225 fi
226
227 RUSTC_LLVM_V=$(rustc --version --verbose | grep "LLVM version" | awk '{ print substr($3, 0, 2); }' | tr -d '.')
228
229 if [ "$HOST_PLATFORM" = "host: x86_64-apple-darwin" ]; then
230         # Apple is special, as always, and decided that they must ensure that there is no way to identify
231         # the LLVM version used. Why? Just to make your life hard.
232         # This list is taken from https://en.wikipedia.org/wiki/Xcode
233         APPLE_CLANG_V=$(clang --version | head -n1 | awk '{ print $4 }')
234         if [ "$APPLE_CLANG_V" = "10.0.0" ]; then
235                 CLANG_LLVM_V="6"
236         elif [ "$APPLE_CLANG_V" = "10.0.1" ]; then
237                 CLANG_LLVM_V="7"
238         elif [ "$APPLE_CLANG_V" = "11.0.0" ]; then
239                 CLANG_LLVM_V="8"
240         elif [ "$APPLE_CLANG_V" = "11.0.3" ]; then
241                 CLANG_LLVM_V="9"
242         elif [ "$APPLE_CLANG_V" = "12.0.0" ]; then
243                 CLANG_LLVM_V="10"
244         else
245                 echo "WARNING: Unable to identify Apple clang LLVM version"
246                 CLANG_LLVM_V="0"
247         fi
248 else
249         CLANG_LLVM_V=$(clang --version | head -n1 | awk '{ print substr($4, 0, 2); }' | tr -d '.')
250 fi
251
252 if [ "$CLANG_LLVM_V" = "$RUSTC_LLVM_V" ]; then
253         CLANG=clang
254         CLANGPP=clang++
255 elif [ "$(which clang-$RUSTC_LLVM_V)" != "" ]; then
256         CLANG="$(which clang-$RUSTC_LLVM_V)"
257         CLANGPP="$(which clang++-$RUSTC_LLVM_V)"
258 fi
259
260 if [ "$CLANG" != "" -a "$CLANGPP" = "" ]; then
261         echo "WARNING: It appears you have a clang-$RUSTC_LLVM_V but not clang++-$RUSTC_LLVM_V. This is common, but leaves us unable to compile C++ with LLVM $RUSTC_LLVM_V"
262         echo "You should create a symlink called clang++-$RUSTC_LLVM_V pointing to $CLANG in $(dirname $CLANG)"
263 fi
264
265 # Finally, if we're on OSX or on Linux, build the final debug binary with address sanitizer (and leave it there)
266 if [ "$HOST_PLATFORM" = "host: x86_64-unknown-linux-gnu" -o "$HOST_PLATFORM" = "host: x86_64-apple-darwin" ]; then
267         if [ "$CLANGPP" != "" ]; then
268                 if [ "$HOST_PLATFORM" = "host: x86_64-apple-darwin" ]; then
269                         # OSX sed is for some reason not compatible with GNU sed
270                         sed -i .bk 's/,"cdylib"]/]/g' Cargo.toml
271                 else
272                         sed -i.bk 's/,"cdylib"]/]/g' Cargo.toml
273                 fi
274                 RUSTC_BOOTSTRAP=1 cargo rustc -v -- -Zsanitizer=address -Cforce-frame-pointers=yes || ( mv Cargo.toml.bk Cargo.toml; exit 1)
275                 mv Cargo.toml.bk Cargo.toml
276
277                 # First the C demo app...
278                 $CLANG $LOCAL_CFLAGS -fsanitize=address -g demo.c target/debug/libldk.a -ldl
279                 ASAN_OPTIONS='detect_leaks=1 detect_invalid_pointer_pairs=1 detect_stack_use_after_return=1' ./a.out
280
281                 # ...then the C++ demo app
282                 $CLANGPP $LOCAL_CFLAGS -std=c++11 -fsanitize=address -g demo.cpp target/debug/libldk.a -ldl
283                 ASAN_OPTIONS='detect_leaks=1 detect_invalid_pointer_pairs=1 detect_stack_use_after_return=1' ./a.out >/dev/null
284         else
285                 echo "WARNING: Please install clang-$RUSTC_LLVM_V and clang++-$RUSTC_LLVM_V to build with address sanitizer"
286         fi
287 else
288         echo "WARNING: Can't use address sanitizer on non-Linux, non-OSX non-x86 platforms"
289 fi
290
291 # Now build with LTO on on both C++ and rust, but without cross-language LTO:
292 # Clear stale release build artifacts from previous runs
293 cargo clean --release
294 CARGO_PROFILE_RELEASE_LTO=true cargo rustc -v --release -- -C lto
295 clang++ $LOCAL_CFLAGS -std=c++11 -flto -O2 demo.cpp target/release/libldk.a -ldl
296
297 if [ "$HOST_PLATFORM" != "host: x86_64-apple-darwin" -a "$CLANGPP" != "" ]; then
298         # If we can use cross-language LTO, use it for building C dependencies (i.e. libsecp256k1) as well
299         export CC="$CLANG"
300         export CFLAGS_wasm32_wasi="-target wasm32 -flto"
301 fi
302
303 if [ "$2" = "false" -a "$(rustc --print target-list | grep wasm32-wasi)" != "" ]; then
304         # Test to see if clang supports wasm32 as a target (which is needed to build rust-secp256k1)
305         echo "int main() {}" > genbindings_wasm_test_file.c
306         clang -nostdlib -o /dev/null --target=wasm32-wasi -Wl,--no-entry genbindings_wasm_test_file.c > /dev/null 2>&1 &&
307         # And if it does, build a WASM binary without capturing errors
308         cargo rustc -v --target=wasm32-wasi -- -C embed-bitcode=yes &&
309         CARGO_PROFILE_RELEASE_LTO=true cargo rustc -v --release --target=wasm32-wasi -- -C opt-level=s -C linker-plugin-lto -C lto ||
310         echo "Cannot build WASM lib as clang does not seem to support the wasm32-wasi target"
311         rm genbindings_wasm_test_file.c
312 fi
313
314 strip ./a.out
315 echo "C++ Bin size and runtime with only RL (LTO) optimized:"
316 ls -lha a.out
317 time ./a.out > /dev/null
318
319 if [ "$HOST_PLATFORM" != "host: x86_64-apple-darwin" -a "$CLANGPP" != "" ]; then
320         # Finally, test cross-language LTO. Note that this will fail if rustc and clang++
321         # build against different versions of LLVM (eg when rustc is installed via rustup
322         # or Ubuntu packages). This should work fine on Distros which do more involved
323         # packaging than simply shipping the rustup binaries (eg Debian should Just Work
324         # here).
325         # The cc-rs crate tries to force -fdata-sections and -ffunction-sections on, which
326         # breaks -fembed-bitcode, so we turn off cc-rs' default flags and specify exactly
327         # what we want here.
328         export CFLAGS="$CFLAGS -O3 -fPIC -fembed-bitcode"
329         export CRATE_CC_NO_DEFAULTS=true
330         # Rust doesn't recognize CFLAGS changes, so we need to clean build artifacts
331         cargo clean --release
332         CARGO_PROFILE_RELEASE_LTO=true cargo rustc -v --release -- -C linker-plugin-lto -C lto -C link-arg=-fuse-ld=lld
333         $CLANGPP $LOCAL_CFLAGS -flto -fuse-ld=lld -O2 demo.cpp target/release/libldk.a -ldl
334         strip ./a.out
335         echo "C++ Bin size and runtime with cross-language LTO:"
336         ls -lha a.out
337         time ./a.out > /dev/null
338 else
339         echo "WARNING: Building with cross-language LTO is not avilable on OSX or without clang-$RUSTC_LLVM_V"
340 fi