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