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