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