Merge pull request #111 from TheBlueMatt/2023-07-0.0.115-aliasing-fix
[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:" | awk '{ print $2 }')"
25 ENV_TARGET=$(echo $HOST_PLATFORM | sed 's/-/_/g')
26
27 # Set path to include our rustc wrapper as well as cbindgen
28 export LDK_RUSTC_PATH="$(which rustc)"
29 export RUSTC="$(pwd)/deterministic-build-wrappers/rustc"
30 PATH="$PATH:~/.cargo/bin"
31
32 # Set up CFLAGS and RUSTFLAGS vars appropriately for building libsecp256k1 and demo apps...
33 BASE_CFLAGS="" # CFLAGS for libsecp256k1
34 LOCAL_CFLAGS="" # CFLAGS for demo apps
35
36 # Remap paths so that our builds are deterministic
37 BASE_RUSTFLAGS="--cfg=c_bindings --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 HOST_OSX=false
48 if [ "$HOST_PLATFORM" = "x86_64-apple-darwin" ]; then
49         HOST_OSX=true
50 elif [ "$HOST_PLATFORM" = "aarch64-apple-darwin" ]; then
51         HOST_OSX=true
52 fi
53
54 BASE_HOST_CFLAGS="$BASE_CFLAGS"
55
56 if [ "$MACOS_SDK" = "" -a "$HOST_OSX" = "true" ]; then
57         MACOS_SDK="$(xcrun --show-sdk-path)"
58         [ "$MACOS_SDK" = "" ] && exit 1
59 fi
60
61 if [ "$MACOS_SDK" != "" ]; then
62         export MACOSX_DEPLOYMENT_TARGET=10.9
63         BASE_HOST_OSX_CFLAGS="$BASE_HOST_CFLAGS -isysroot$MACOS_SDK -mmacosx-version-min=10.9"
64         export CFLAGS_aarch64_apple_darwin="$BASE_HOST_OSX_CFLAGS --target=aarch64-apple-darwin -mcpu=apple-a14"
65         export CFLAGS_x86_64_apple_darwin="$BASE_HOST_OSX_CFLAGS --target=x86_64-apple-darwin -march=sandybridge -mtune=sandybridge"
66         if [ "$HOST_OSX" = "true" ]; then
67                 LOCAL_CFLAGS="$LOCAL_CFLAGS --target=$HOST_PLATFORM -isysroot$MACOS_SDK -mmacosx-version-min=10.9"
68                 BASE_HOST_CFLAGS="$BASE_HOST_OSX_CFLAGS --target=$HOST_PLATFORM"
69         fi
70 fi
71
72 rm genbindings_path_map_test_file.c
73
74 case "$ENV_TARGET" in
75         "x86_64"*)
76                 export RUSTFLAGS="$BASE_RUSTFLAGS -C target-cpu=sandybridge"
77                 export BASE_HOST_CFLAGS="$BASE_HOST_CFLAGS -march=sandybridge -mcpu=sandybridge -mtune=sandybridge"
78                 export CFLAGS_$ENV_TARGET="$BASE_HOST_CFLAGS"
79                 ;;
80         "aarch64_apple_darwin")
81                 export RUSTFLAGS="$BASE_RUSTFLAGS -C target-cpu=apple-a14"
82                 export BASE_HOST_CFLAGS="$BASE_HOST_CFLAGS -mcpu=apple-a14"
83                 export CFLAGS_$ENV_TARGET="$BASE_HOST_CFLAGS"
84                 ;;
85         *)
86                 # Assume this isn't targeted at another host and build for the host's CPU.
87                 export RUSTFLAGS="$BASE_RUSTFLAGS -C target-cpu=native"
88                 export BASE_HOST_CFLAGS="$BASE_HOST_CFLAGS -mcpu=native"
89                 export CFLAGS_$ENV_TARGET="$BASE_HOST_CFLAGS"
90                 ;;
91 esac
92
93 # First build the latest c-bindings-gen binary
94 cd c-bindings-gen && cargo build --release && cd ..
95
96 # Then wipe all the existing C bindings (because we're being run in the right directory)
97 # note that we keep the few manually-generated files first:
98 mv lightning-c-bindings/src/c_types/mod.rs ./
99 mv lightning-c-bindings/src/bitcoin ./
100
101 # Before we try to sed the Cargo.toml, generate version define tags
102 # (ignoring any files that we're about to generate)
103
104 git checkout lightning-c-bindings/src
105 git checkout lightning-c-bindings/include
106 BINDINGS_GIT="$(git describe --tag --dirty --abbrev=16)"
107 echo "$(cat <<EOF
108 #ifndef _LDK_HEADER_VER
109 static inline int _ldk_strncmp(const char *s1, const char *s2, uint64_t n) {
110         if (n && *s1 != *s2) return 1;
111         while (n && *s1 != 0 && *s2 != 0) {
112                 s1++; s2++; n--;
113                 if (n && *s1 != *s2) return 1;
114         }
115         return 0;
116 }
117
118 #define _LDK_HEADER_VER "${LIGHTNING_GIT}"
119 #define _LDK_C_BINDINGS_HEADER_VER "${BINDINGS_GIT}"
120 static inline const char* check_get_ldk_version() {
121         LDKStr bin_ver = _ldk_get_compiled_version();
122         if (_ldk_strncmp(_LDK_HEADER_VER, (const char*)bin_ver.chars, bin_ver.len) != 0) {
123         // Version mismatch, we don't know what we're running!
124                 return 0;
125         }
126         return _LDK_HEADER_VER;
127 }
128 static inline const char* check_get_ldk_bindings_version() {
129         LDKStr bin_ver = _ldk_c_bindings_get_compiled_version();
130         if (_ldk_strncmp(_LDK_C_BINDINGS_HEADER_VER, (const char*)bin_ver.chars, bin_ver.len) != 0) {
131         // Version mismatch, we don't know what we're running!
132                 return 0;
133         }
134         return _LDK_C_BINDINGS_HEADER_VER;
135 }
136 #endif /* _LDK_HEADER_VER */
137 EOF
138 )" > lightning-c-bindings/include/ldk_ver.h
139
140 rm -rf lightning-c-bindings/src
141
142 mkdir -p lightning-c-bindings/src/{c_types,lightning}
143 mv ./mod.rs lightning-c-bindings/src/c_types/
144 mv ./bitcoin lightning-c-bindings/src/
145
146 # Finally, run the c-bindings-gen binary, building fresh bindings.
147 OUT="$(pwd)/lightning-c-bindings/src"
148 OUT_TEMPL="$(pwd)/lightning-c-bindings/src/c_types/derived.rs"
149 OUT_F="$(pwd)/lightning-c-bindings/include/ldk_rust_types.h"
150 OUT_CPP="$(pwd)/lightning-c-bindings/include/lightningpp.hpp"
151 BIN="$(pwd)/c-bindings-gen/target/release/c-bindings-gen"
152
153 function is_gnu_sed(){
154   sed --version >/dev/null 2>&1
155 }
156
157 function add_crate() {
158         pushd "$LIGHTNING_PATH/$1"
159         RUSTC_BOOTSTRAP=1 cargo rustc --profile=check --no-default-features $3 -- --cfg=c_bindings -Zunpretty=expanded > /tmp/$1-crate-source.txt
160         popd
161         if [ "$HOST_OSX" = "true" ]; then
162                 sed -i".original" "1i\\
163 pub mod $2 {
164 " /tmp/$1-crate-source.txt
165         else
166                 sed -i "1ipub mod $2 {\n" /tmp/$1-crate-source.txt
167         fi
168         echo "}" >> /tmp/$1-crate-source.txt
169         cat /tmp/$1-crate-source.txt >> /tmp/crate-source.txt
170         rm /tmp/$1-crate-source.txt
171         if is_gnu_sed; then
172                 sed -E -i 's|#*'$1' = \{ .*|'$1' = \{ path = "'"$LIGHTNING_PATH"'/'$1'", default-features = false }|' lightning-c-bindings/Cargo.toml
173         else
174                 # OSX sed is for some reason not compatible with GNU sed
175                 sed -E -i '' 's|#*'$1' = \{ .*|'$1' = \{ path = "'"$LIGHTNING_PATH"'/'$1'", default-features = false }|' lightning-c-bindings/Cargo.toml
176         fi
177 }
178
179 function drop_crate() {
180         if is_gnu_sed; then
181                 sed -E -i 's|'$1' = \{ (.*)|#'$1' = \{ \1|' lightning-c-bindings/Cargo.toml
182         else
183                 # OSX sed is for some reason not compatible with GNU sed
184                 sed -E -i '' 's|'$1' = \{ (.*)|#'$1' = \{ \1|' lightning-c-bindings/Cargo.toml
185         fi
186 }
187
188 echo > /tmp/crate-source.txt
189 if [ "$2" = "true" ]; then
190         add_crate lightning lightning --features=std
191         add_crate "lightning-persister" "lightning_persister"
192         add_crate "lightning-background-processor" "lightning_background_processor" --features=std
193         add_crate "lightning-invoice" "lightning_invoice" --features=std
194         add_crate "lightning-rapid-gossip-sync" "lightning_rapid_gossip_sync"
195         CARGO_BUILD_ARGS="--features=std"
196 else
197         add_crate lightning lightning --features=no-std
198         drop_crate "lightning-persister"
199         add_crate "lightning-background-processor" "lightning_background_processor"
200         add_crate "lightning-rapid-gossip-sync" "lightning_rapid_gossip_sync" --features=no-std
201         add_crate "lightning-invoice" "lightning_invoice" --features=no-std
202         CARGO_BUILD_ARGS="--features=no-std"
203 fi
204
205 cat /tmp/crate-source.txt | RUST_BACKTRACE=1 "$BIN" "$OUT/" "$OUT_TEMPL" "$OUT_F" "$OUT_CPP"
206
207 echo "$(cat <<EOF
208 #[no_mangle]
209 pub extern "C" fn _ldk_get_compiled_version() -> crate::c_types::Str {
210         "${LIGHTNING_GIT}".into()
211 }
212 #[no_mangle]
213 pub extern "C" fn _ldk_c_bindings_get_compiled_version() -> crate::c_types::Str {
214         "${BINDINGS_GIT}".into()
215 }
216 EOF
217 )" >> lightning-c-bindings/src/version.rs
218
219 # Now cd to lightning-c-bindings, build the generated bindings, and call cbindgen to build a C header file
220 cd lightning-c-bindings
221
222 RUSTFLAGS="$RUSTFLAGS --cfg=test_mod_pointers" cargo build $CARGO_BUILD_ARGS
223 if [ "$CFLAGS_aarch64_apple_darwin" != "" -a "$HOST_OSX" = "true" ]; then
224         RUSTFLAGS="$BASE_RUSTFLAGS -C target-cpu=apple-a14" cargo build $CARGO_BUILD_ARGS --target aarch64-apple-darwin
225 fi
226 cbindgen -v --config cbindgen.toml -o include/lightning.h >/dev/null 2>&1
227
228 # cbindgen is relatively braindead when exporting typedefs -
229 # it happily exports all our typedefs for private types, even with the
230 # generics we specified in C mode! So we drop all those types manually here.
231 if is_gnu_sed; then
232         sed -i 's/typedef LDKnative.*Import.*LDKnative.*;//g' include/lightning.h
233
234         # UnsafeCell is `repr(transparent)` so should be ignored here
235         sed -i 's/LDKUnsafeCell<\(.*\)> /\1 /g' include/lightning.h
236
237         # stdlib.h doesn't exist in clang's wasm sysroot, and cbindgen
238         # doesn't actually use it anyway, so drop the import.
239         sed -i 's/#include <stdlib.h>/#include "ldk_rust_types.h"/g' include/lightning.h
240 else
241         # OSX sed is for some reason not compatible with GNU sed
242         sed -i '' 's/typedef LDKnative.*Import.*LDKnative.*;//g' include/lightning.h
243
244         # UnsafeCell is `repr(transparent)` so should be ignored by cbindgen
245         sed -i '' 's/LDKUnsafeCell<\(.*\)> /\1 /g' include/lightning.h
246
247         # stdlib.h doesn't exist in clang's wasm sysroot, and cbindgen
248         # doesn't actually use it anyway, so drop the import.
249         sed -i '' 's/#include <stdlib.h>/#include "ldk_rust_types.h"/g' include/lightning.h
250 fi
251
252 # Build C++ class methods which call trait methods
253 echo "Updating C++ header, this may take some time, especially on macOS"
254 set +x # Echoing every command is very verbose here
255 OLD_IFS="$IFS"
256 export IFS=''
257 echo '#include <string.h>' > include/lightningpp_new.hpp
258 echo 'namespace LDK {' >> include/lightningpp_new.hpp
259 echo '// Forward declarations' >> include/lightningpp_new.hpp
260 cat include/lightningpp.hpp | sed -n 's/class \(.*\) {/class \1;/p' >> include/lightningpp_new.hpp
261 echo '' >> include/lightningpp_new.hpp
262
263 DECLS=""
264 while read LINE; do
265         case "$LINE" in
266                 "#include <string.h>")
267                         # We already printed this above.
268                         ;;
269                 "namespace LDK {")
270                         # We already printed this above.
271                         ;;
272                 "}")
273                         # We'll print this at the end
274                         ;;
275                 "XXX"*)
276                         NEW_STRUCT_NAME="$(echo "$LINE" | awk '{ print $2 }')"
277                         if [ "$NEW_STRUCT_NAME" != "$STRUCT_NAME" ]; then
278                                 STRUCT_CONTENTS="$(cat include/lightning.h  | sed -n -e "/struct LDK$NEW_STRUCT_NAME/{:s" -e "/\} LDK$NEW_STRUCT_NAME;/!{N" -e "b s" -e "}" -e p -e "}")"
279                         fi
280                         STRUCT_NAME="$NEW_STRUCT_NAME"
281                         METHOD_NAME="$(echo "$LINE" | awk '{ print $3 }')"
282                         METHOD="$(echo "$STRUCT_CONTENTS" | grep "(\*$METHOD_NAME)")"
283                         if [ "$METHOD" = "" ]; then
284                                 echo "Unable to find method declaration for $LINE"
285                                 exit 1
286                         fi
287                         RETVAL="$(echo "$METHOD" | sed 's/[ ]*\([A-Za-z0-9 _]*\)(\*\(.*\)).*/\1/' | sed -E 's/^(struct|enum) LDK/LDK::/g' | tr -d ' ')"
288                         [ "$RETVAL" = "LDK::SecretKey" ] && RETVAL="LDKSecretKey"
289                         [ "$RETVAL" = "LDK::PublicKey" ] && RETVAL="LDKPublicKey"
290                         [ "$RETVAL" = "LDK::ThirtyTwoBytes" ] && RETVAL="LDKThirtyTwoBytes"
291                         PARAMS="$(echo "$METHOD" | sed 's/.*(\*.*)(\(const \)*void \*this_arg\(, \)*\(.*\));/\3/')"
292
293                         echo -e "\tinline $RETVAL $METHOD_NAME($PARAMS);" >> include/lightningpp_new.hpp
294                         DECLS="$DECLS"$'\n'"inline $RETVAL $STRUCT_NAME::$METHOD_NAME($PARAMS) {"
295
296                         DECLS="$DECLS"$'\n'$'\t'
297                         [ "$RETVAL" != "void" ] && DECLS="$DECLS$RETVAL ret = "
298                         DECLS="$DECLS(self.$METHOD_NAME)(self.this_arg"
299
300                         IFS=','; for PARAM in $PARAMS; do
301                                 DECLS="$DECLS, "
302                                 DECLS="$DECLS$(echo $PARAM | sed 's/.* (*\**\([a-zA-Z0-9_]*\)\()[\[0-9\]*]\)*/\1/')"
303                         done
304                         IFS=''
305
306                         DECLS="$DECLS);"
307                         [ "$RETVAL" != "void" ] && DECLS="$DECLS"$'\n'$'\t'"return ret;"
308                         DECLS="$DECLS"$'\n'"}"
309                         ;;
310                 *)
311                         echo "$LINE" >> include/lightningpp_new.hpp
312         esac
313 done < include/lightningpp.hpp
314 echo "$DECLS" >> include/lightningpp_new.hpp
315 echo "}" >> include/lightningpp_new.hpp
316 export IFS="$OLD_IFS"
317 set -x
318 mv include/lightningpp_new.hpp include/lightningpp.hpp
319
320 # Finally, sanity-check the generated C and C++ bindings with demo apps:
321 # Naively run the C demo app:
322 gcc $LOCAL_CFLAGS -Wall -g -pthread demo.c target/debug/libldk.a -ldl -lm
323 ./a.out
324
325 # And run the C++ demo app
326 if [ "$2" = "true" ]; then
327         g++ $LOCAL_CFLAGS -std=c++11 -Wall -g -pthread demo.cpp -Ltarget/debug/ -lldk -ldl
328         LD_LIBRARY_PATH=target/debug/ ./a.out > /dev/null
329 fi
330
331 # Finally, run the C++ demo app with our native networking library
332 # in valgrind to test memory model correctness and lack of leaks.
333 gcc $LOCAL_CFLAGS -fPIC -std=c99 -Wall -g -pthread -I../ldk-net ../ldk-net/ldk_net.c -c -o ldk_net.o
334 if [ "$2" = "true" ]; then
335         g++ $LOCAL_CFLAGS -std=c++11 -Wall -g -pthread -DREAL_NET -I../ldk-net ldk_net.o demo.cpp target/debug/libldk.a -ldl -lm
336         if [ -x "`which valgrind`" -a "$(uname -m)" != "ppc64le" ]; then
337                 valgrind --error-exitcode=4 --memcheck:leak-check=full --show-leak-kinds=all ./a.out
338                 echo
339         else
340                 echo "WARNING: Please install valgrind for more testing"
341                 ./a.out
342         fi
343 fi
344
345
346 # Test a statically-linked C++ version, tracking the resulting binary size and runtime
347 # across debug, LTO, and cross-language LTO builds (using the same compiler each time).
348 if [ "$2" = "true" ]; then
349         clang++ $LOCAL_CFLAGS -std=c++11 demo.cpp target/debug/libldk.a -ldl
350         strip ./a.out
351         time ./a.out
352         echo " C++ Bin size and runtime w/o optimization:"
353         ls -lha a.out
354 fi
355
356 # Then, check with memory sanitizer, if we're on Linux and have rustc nightly
357 if [ "$HOST_PLATFORM" = "x86_64-unknown-linux-gnu" ]; then
358         if cargo +nightly --version >/dev/null 2>&1; then
359                 LLVM_V=$(rustc +nightly --version --verbose | grep "LLVM version" | awk '{ print substr($3, 0, 2); }')
360                 if [ -x "$(which clang-$LLVM_V)" ]; then
361                         cargo +nightly clean
362                         cargo +nightly rustc $CARGO_BUILD_ARGS -Zbuild-std=std,panic_abort --target x86_64-unknown-linux-gnu -v -- -Zsanitizer=memory -Zsanitizer-memory-track-origins -Cforce-frame-pointers=yes
363                         mv target/x86_64-unknown-linux-gnu/debug/libldk.* target/debug/
364
365                         # Sadly, std doesn't seem to compile into something that is memsan-safe as of Aug 2020,
366                         # so we'll always fail, not to mention we may be linking against git rustc LLVM which
367                         # may differ from clang-llvm, so just allow everything here to fail.
368                         set +e
369
370                         # First the C demo app...
371                         clang-$LLVM_V $LOCAL_CFLAGS -fsanitize=memory -fsanitize-memory-track-origins -g demo.c target/debug/libldk.a -ldl
372                         ./a.out
373
374                         if [ "$2" = "true" ]; then
375                                 # ...then the C++ demo app
376                                 clang++-$LLVM_V $LOCAL_CFLAGS -std=c++11 -fsanitize=memory -fsanitize-memory-track-origins -g demo.cpp target/debug/libldk.a -ldl
377                                 ./a.out >/dev/null
378
379                                 # ...then the C++ demo app with the ldk_net network implementation
380                                 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
381                                 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
382                                 ./a.out >/dev/null
383                         fi
384
385                         # restore exit-on-failure
386                         set -e
387                 else
388                         echo "WARNING: Can't use memory sanitizer without clang-$LLVM_V"
389                 fi
390         else
391                 echo "WARNING: Can't use memory sanitizer without rustc nightly"
392         fi
393 else
394         echo "WARNING: Can't use memory sanitizer on non-Linux, non-x86 platforms"
395 fi
396
397 RUSTC_LLVM_V=$(rustc --version --verbose | grep "LLVM version" | awk '{ print substr($3, 0, 2); }')
398
399 if [ "$HOST_OSX" = "true" ]; then
400         # Apple is special, as always, and their versions of clang aren't
401         # compatible with upstream LLVM.
402         if [ "$(clang --version | grep 'Apple clang')" != "" ]; then
403                 echo "Apple clang isn't compatible with upstream clang, install upstream clang"
404                 CLANG_LLVM_V="0"
405         else
406                 CLANG_LLVM_V=$(clang --version | head -n1 | awk '{ print substr($3, 0, 2); }')
407                 if [ -x "$(which ld64.lld)" ]; then
408                         LLD_LLVM_V="$(ld64.lld --version | awk '{ print substr($2, 0, 2); }')"
409                 fi
410         fi
411 else
412         CLANG_LLVM_V=$(clang --version | head -n1 | awk '{ print substr($4, 0, 2); }')
413         if [ -x "$(which ld.lld)" ]; then
414                 LLD_LLVM_V="$(ld.lld --version | awk '{ print $2; }')"
415                 if [ "$LLD_LLVM_V" = "LLD" ]; then # eg if the output is "Debian LLD ..."
416                         LLD_LLVM_V="$(ld.lld --version | awk '{ print substr($3, 0, 2); }')"
417                 else
418                         LLD_LLVM_V="$(ld.lld --version | awk '{ print substr($2, 0, 2); }')"
419                 fi
420         fi
421 fi
422
423
424 if [ "$CLANG_LLVM_V" = "$RUSTC_LLVM_V" ]; then
425         CLANG=clang
426         CLANGPP=clang++
427         if [ "$LLD_LLVM_V" = "$CLANG_LLVM_V" ]; then
428                 LLD=lld
429         fi
430 elif [ -x "$(which clang-$RUSTC_LLVM_V)" ]; then
431         CLANG="$(which clang-$RUSTC_LLVM_V)"
432         CLANGPP="$(which clang++-$RUSTC_LLVM_V || echo clang++)"
433         if [ "$($CLANG --version)" != "$($CLANGPP --version)" ]; then
434                 echo "$CLANG and $CLANGPP are not the same version of clang!"
435                 unset CLANG
436                 unset CLANGPP
437         fi
438         if [ "$LLD_LLVM_V" != "$RUSTC_LLVM_V" ]; then
439                 LLD="lld"
440                 [ -x "$(which lld-$RUSTC_LLVM_V)" ] && LLD="lld-$RUSTC_LLVM_V"
441                 LLD_LLVM_V="$(ld.lld-$RUSTC_LLVM_V --version | awk '{ print $2; }')"
442                 if [ "$LLD_LLVM_V" = "LLD" ]; then # eg if the output is "Debian LLD ..."
443                         LLD_LLVM_V="$(ld.lld-$RUSTC_LLVM_V --version | awk '{ print substr($3, 0, 2); }')"
444                 else
445                         LLD_LLVM_V="$(ld.lld-$RUSTC_LLVM_V --version | awk '{ print substr($2, 0, 2); }')"
446                 fi
447                 if [ "$LLD_LLVM_V" != "$RUSTC_LLVM_V" ]; then
448                         echo "Could not find a workable version of lld, not using cross-language LTO"
449                         unset LLD
450                 fi
451         fi
452 fi
453
454 if [ "$CLANG" != "" -a "$CLANGPP" = "" ]; then
455         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"
456         echo "You should create a symlink called clang++-$RUSTC_LLVM_V pointing to $CLANG in $(dirname $CLANG)"
457 fi
458
459 # Finally, if we're on Linux, build the final debug binary with address sanitizer (and leave it there)
460 if [ "$HOST_PLATFORM" = "x86_64-unknown-linux-gnu" ]; then
461         if [ "$CLANGPP" != "" ]; then
462                 if is_gnu_sed; then
463                         sed -i.bk 's/,"cdylib"]/]/g' Cargo.toml
464                 else
465                         # OSX sed is for some reason not compatible with GNU sed
466                         sed -i .bk 's/,"cdylib"]/]/g' Cargo.toml
467                 fi
468
469                 RUSTFLAGS="$RUSTFLAGS --cfg=test_mod_pointers" RUSTC_BOOTSTRAP=1 cargo rustc $CARGO_BUILD_ARGS -v -- -Zsanitizer=address -Cforce-frame-pointers=yes || ( mv Cargo.toml.bk Cargo.toml; exit 1)
470                 mv Cargo.toml.bk Cargo.toml
471
472                 # First the C demo app...
473                 $CLANG $LOCAL_CFLAGS -fsanitize=address -g demo.c target/debug/libldk.a -ldl
474                 ASAN_OPTIONS='detect_leaks=1 detect_invalid_pointer_pairs=1 detect_stack_use_after_return=1' ./a.out
475
476                 if [ "$2" = "true" ]; then
477                         # ...then the C++ demo app
478                         $CLANGPP $LOCAL_CFLAGS -std=c++11 -fsanitize=address -g demo.cpp target/debug/libldk.a -ldl
479                         ASAN_OPTIONS='detect_leaks=1 detect_invalid_pointer_pairs=1 detect_stack_use_after_return=1' ./a.out >/dev/null
480
481                         # ...then the C++ demo app with the ldk_net network implementation
482                         $CLANG $LOCAL_CFLAGS -fPIC -fsanitize=address -g -I../ldk-net ../ldk-net/ldk_net.c -c -o ldk_net.o
483                         $CLANGPP $LOCAL_CFLAGS -std=c++11 -fsanitize=address -g -DREAL_NET -I../ldk-net ldk_net.o demo.cpp target/debug/libldk.a -ldl
484                         ASAN_OPTIONS='detect_leaks=1 detect_invalid_pointer_pairs=1 detect_stack_use_after_return=1' ./a.out >/dev/null
485                 fi
486         else
487                 echo "WARNING: Please install clang-$RUSTC_LLVM_V and clang++-$RUSTC_LLVM_V to build with address sanitizer"
488         fi
489 else
490         echo "WARNING: Can't use address sanitizer on non-Linux, non-x86 platforms"
491 fi
492
493 # Now build with LTO on on both C++ and rust, but without cross-language LTO:
494 # Clear stale release build artifacts from previous runs
495 cargo clean --release
496 CARGO_PROFILE_RELEASE_LTO=true RUSTFLAGS="$RUSTFLAGS -C embed-bitcode=yes -C lto" cargo build $CARGO_BUILD_ARGS -v --release
497 if [ "$2" = "true" ]; then
498         clang++ $LOCAL_CFLAGS -std=c++11 -O2 demo.cpp target/release/libldk.a -ldl
499 fi
500
501 strip ./a.out
502 time ./a.out
503 echo "C++ Bin size and runtime with only RL (LTO) optimized:"
504 ls -lha a.out
505
506 if [ "$CLANGPP" != "" ]; then
507         # If we can use cross-language LTO, use it for building C dependencies (i.e. libsecp256k1) as well
508         export CC="$CLANG"
509         # The cc-rs crate tries to force -fdata-sections and -ffunction-sections on, which
510         # breaks -fembed-bitcode, so we turn off cc-rs' default flags and specify exactly
511         # what we want here.
512         export CFLAGS_$ENV_TARGET="$BASE_HOST_CFLAGS -fPIC -fembed-bitcode"
513         export CRATE_CC_NO_DEFAULTS=true
514 fi
515
516 if [ "$2" = "false" -a "$(rustc --print target-list | grep wasm32-wasi)" != "" ]; then
517         # Test to see if clang supports wasm32 as a target (which is needed to build rust-secp256k1)
518         echo "int main() {}" > genbindings_wasm_test_file.c
519         if clang -nostdlib -o /dev/null --target=wasm32-wasi -Wl,--no-entry genbindings_wasm_test_file.c > /dev/null 2>&1; then
520                 # And if it does, build a WASM binary without capturing errors
521                 export CFLAGS_wasm32_wasi="$BASE_CFLAGS -target wasm32-wasi -O1"
522                 RUSTFLAGS="$BASE_RUSTFLAGS -C opt-level=1 --cfg=test_mod_pointers" cargo build $CARGO_BUILD_ARGS -v --target=wasm32-wasi
523                 export CFLAGS_wasm32_wasi="$BASE_CFLAGS -fembed-bitcode -target wasm32-wasi -Oz"
524                 RUSTFLAGS="$BASE_RUSTFLAGS -C embed-bitcode=yes -C opt-level=z -C linker-plugin-lto -C lto" CARGO_PROFILE_RELEASE_LTO=true cargo build $CARGO_BUILD_ARGS -v --release --target=wasm32-wasi
525         else
526                 echo "Cannot build WASM lib as clang does not seem to support the wasm32-wasi target"
527         fi
528         rm genbindings_wasm_test_file.c
529 fi
530
531 EXTRA_TARGETS=( $LDK_C_BINDINGS_EXTRA_TARGETS )
532 EXTRA_CCS=( $LDK_C_BINDINGS_EXTRA_TARGET_CCS )
533
534 if [ ${#EXTRA_TARGETS[@]} != ${#EXTRA_CCS[@]} ]; then
535         echo "LDK_C_BINDINGS_EXTRA_TARGETS and LDK_C_BINDINGS_EXTRA_TARGET_CCS didn't have the same number of elements!"
536         exit 1
537 fi
538
539 for IDX in ${!EXTRA_TARGETS[@]}; do
540         EXTRA_ENV_TARGET=$(echo "${EXTRA_TARGETS[$IDX]}" | sed 's/-/_/g')
541         export CFLAGS_$EXTRA_ENV_TARGET="$BASE_CFLAGS"
542         export CC_$EXTRA_ENV_TARGET=${EXTRA_CCS[$IDX]}
543         RUSTFLAGS="$BASE_RUSTFLAGS -C embed-bitcode=yes -C lto -C linker=${EXTRA_CCS[$IDX]}" CARGO_PROFILE_RELEASE_LTO=true cargo build $CARGO_BUILD_ARGS -v --release --target "${EXTRA_TARGETS[$IDX]}"
544 done
545
546 if [ "$CLANGPP" != "" -a "$LLD" != "" ]; then
547         # Finally, test cross-language LTO. Note that this will fail if rustc and clang++
548         # build against different versions of LLVM (eg when rustc is installed via rustup
549         # or Ubuntu packages). This should work fine on Distros which do more involved
550         # packaging than simply shipping the rustup binaries (eg Debian should Just Work
551         # here).
552         LINK_ARG_FLAGS="-C link-arg=-fuse-ld=$LLD"
553         export LDK_CLANG_PATH=$(which $CLANG)
554         if [ "$MACOS_SDK" != "" ]; then
555                 export CLANG="$(pwd)/../deterministic-build-wrappers/clang-lto-link-osx"
556                 for ARG in $CFLAGS_aarch64_apple_darwin; do
557                         MANUAL_LINK_CFLAGS="$MANUAL_LINK_CFLAGS -C link-arg=$ARG"
558                 done
559                 export CFLAGS_aarch64_apple_darwin="$CFLAGS_aarch64_apple_darwin -O3 -fPIC -fembed-bitcode"
560                 RUSTC_BOOTSTRAP=1 RUSTFLAGS="$BASE_RUSTFLAGS -C target-cpu=apple-a14 -C embed-bitcode=yes -C linker-plugin-lto -C lto -C linker=$CLANG $MANUAL_LINK_CFLAGS $LINK_ARG_FLAGS -C link-arg=-mcpu=apple-a14" CARGO_PROFILE_RELEASE_LTO=true cargo build $CARGO_BUILD_ARGS -v --release --target aarch64-apple-darwin -Zbuild-std=std,panic_abort
561                 if [ "$HOST_OSX" != "true" ]; then
562                         # If we're not on OSX but can build OSX binaries, build the x86_64 OSX release now
563                         MANUAL_LINK_CFLAGS=""
564                         for ARG in $CFLAGS_x86_64_apple_darwin; do
565                                 MANUAL_LINK_CFLAGS="$MANUAL_LINK_CFLAGS -C link-arg=$ARG"
566                         done
567                         export CFLAGS_x86_64_apple_darwin="$CFLAGS_x86_64_apple_darwin -O3 -fPIC -fembed-bitcode"
568                         RUSTC_BOOTSTRAP=1 RUSTFLAGS="$BASE_RUSTFLAGS -C target-cpu=sandybridge -C embed-bitcode=yes -C linker-plugin-lto -C lto -C linker=$CLANG $MANUAL_LINK_CFLAGS $LINK_ARG_FLAGS -C link-arg=-mcpu=sandybridge -C link-arg=-mtune=sandybridge" CARGO_PROFILE_RELEASE_LTO=true cargo build $CARGO_BUILD_ARGS -v --release --target x86_64-apple-darwin -Zbuild-std=std,panic_abort
569                 fi
570         fi
571         # If we're on an M1 don't bother building X86 binaries
572         if [ "$HOST_PLATFORM" != "aarch64-apple-darwin" ]; then
573                 [ "$HOST_OSX" != "true" ] && export CLANG="$LDK_CLANG_PATH"
574                 export CFLAGS_$ENV_TARGET="$BASE_HOST_CFLAGS -O3 -fPIC -fembed-bitcode"
575                 # Rust doesn't recognize CFLAGS changes, so we need to clean build artifacts
576                 cargo clean --release
577                 CARGO_PROFILE_RELEASE_LTO=true RUSTFLAGS="$RUSTFLAGS -C embed-bitcode=yes -C linker-plugin-lto -C lto -C linker=$CLANG $LINK_ARG_FLAGS -C link-arg=-march=sandybridge -C link-arg=-mcpu=sandybridge -C link-arg=-mtune=sandybridge" cargo build $CARGO_BUILD_ARGS -v --release
578
579                 if [ "$2" = "true" ]; then
580                         $CLANGPP $LOCAL_CFLAGS -flto -fuse-ld=$LLD -O2 -c demo.cpp -o demo.o
581                         $CLANGPP $LOCAL_CFLAGS -flto -fuse-ld=$LLD -Wl,--lto-O2 -Wl,-O2 -O2 demo.o target/release/libldk.a -ldl
582                         strip ./a.out
583                         time ./a.out
584                         echo "C++ Bin size and runtime with cross-language LTO:"
585                         ls -lha a.out
586                 fi
587         fi
588 else
589         if [ "$CFLAGS_aarch64_apple_darwin" != "" ]; then
590                 RUSTFLAGS="$BASE_RUSTFLAGS -C embed-bitcode=yes -C lto -C target-cpu=apple-a14" CARGO_PROFILE_RELEASE_LTO=true cargo build $CARGO_BUILD_ARGS -v --release --target aarch64-apple-darwin
591         fi
592         echo "WARNING: Building with cross-language LTO is not avilable without clang-$RUSTC_LLVM_V and lld-$RUSTC_LLVM_V"
593 fi