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