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