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