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