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