Merge pull request #18 from TheBlueMatt/2021-04-invoice-incl
[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 # On reasonable systems, we can use realpath here, but OSX is a diva with 20-year-old software.
13 ORIG_PWD="$(pwd)"
14 cd "$1"
15 LIGHTNING_PATH="$(pwd)"
16 cd "$ORIG_PWD"
17
18 # Generate (and reasonably test) C bindings
19
20 # First build the latest c-bindings-gen binary
21 cd c-bindings-gen && cargo build --release && cd ..
22
23 # Then wipe all the existing C bindings (because we're being run in the right directory)
24 # note that we keep the few manually-generated files first:
25 mv lightning-c-bindings/src/c_types/mod.rs ./
26 mv lightning-c-bindings/src/bitcoin ./
27
28 rm -rf lightning-c-bindings/src
29
30 mkdir -p lightning-c-bindings/src/{c_types,lightning}
31 mv ./mod.rs lightning-c-bindings/src/c_types/
32 mv ./bitcoin lightning-c-bindings/src/
33
34 # Finally, run the c-bindings-gen binary, building fresh bindings.
35 OUT="$(pwd)/lightning-c-bindings/src"
36 OUT_TEMPL="$(pwd)/lightning-c-bindings/src/c_types/derived.rs"
37 OUT_F="$(pwd)/lightning-c-bindings/include/rust_types.h"
38 OUT_CPP="$(pwd)/lightning-c-bindings/include/lightningpp.hpp"
39 BIN="$(pwd)/c-bindings-gen/target/release/c-bindings-gen"
40
41 HOST_PLATFORM="$(rustc --version --verbose | grep "host:")"
42
43 function add_crate() {
44         pushd "$LIGHTNING_PATH/$1"
45         RUSTC_BOOTSTRAP=1 cargo rustc --profile=check $3 -- -Zunstable-options --pretty=expanded > /tmp/$1-crate-source.txt
46         popd
47         if [ "$HOST_PLATFORM" = "host: x86_64-apple-darwin" ]; then
48                 sed -i".original" "1i\\
49 pub mod $2 {
50 " /tmp/$1-crate-source.txt
51         else
52                 sed -i "1ipub mod $2 {\n" /tmp/$1-crate-source.txt
53         fi
54         echo "}" >> /tmp/$1-crate-source.txt
55         cat /tmp/$1-crate-source.txt >> /tmp/crate-source.txt
56         rm /tmp/$1-crate-source.txt
57         if [ "$HOST_PLATFORM" = "host: x86_64-apple-darwin" ]; then
58                 # OSX sed is for some reason not compatible with GNU sed
59                 sed -E -i '' 's|#?'$1' = \{ .*|'$1' = \{ path = "'"$LIGHTNING_PATH"'/'$1'" '"$4"' }|' lightning-c-bindings/Cargo.toml
60         else
61                 sed -E -i 's|#?'$1' = \{ .*|'$1' = \{ path = "'"$LIGHTNING_PATH"'/'$1'" '"$4"' }|' lightning-c-bindings/Cargo.toml
62         fi
63 }
64
65 function drop_crate() {
66         if [ "$HOST_PLATFORM" = "host: x86_64-apple-darwin" ]; then
67                 # OSX sed is for some reason not compatible with GNU sed
68                 sed -E -i '' 's|'$1' = \{ (.*)|#'$1' = \{ \1|' lightning-c-bindings/Cargo.toml
69         else
70                 sed -E -i 's|'$1' = \{ (.*)|#'$1' = \{ \1|' lightning-c-bindings/Cargo.toml
71         fi
72 }
73
74 echo > /tmp/crate-source.txt
75 if [ "$2" = "true" ]; then
76         add_crate lightning lightning --features=allow_wallclock_use ', features = ["allow_wallclock_use"]'
77         add_crate "lightning-persister" "lightning_persister"
78 else
79         add_crate lightning lightning
80         drop_crate "lightning-persister"
81 fi
82 add_crate "lightning-invoice" "lightning_invoice"
83
84 cat /tmp/crate-source.txt | RUST_BACKTRACE=1 "$BIN" "$OUT/" "$OUT_TEMPL" "$OUT_F" "$OUT_CPP"
85
86 # Set path to include our rustc wrapper as well as cbindgen
87 PATH="$(pwd)/deterministic-build-wrappers:$PATH:~/.cargo/bin"
88 # Now cd to lightning-c-bindings, build the generated bindings, and call cbindgen to build a C header file
89 cd lightning-c-bindings
90
91 # Remap paths so that our builds are deterministic
92 export RUSTFLAGS="--remap-path-prefix $LIGHTNING_PATH=rust-lightning --remap-path-prefix $(pwd)=ldk-c-bindings --remap-path-prefix $HOME/.cargo= -C target-cpu=generic"
93
94 # If the C compiler supports it, also set -ffile-prefix-map
95 echo "int main() {}" > genbindings_path_map_test_file.c
96 clang -o /dev/null -ffile-prefix-map=$HOME/.cargo= genbindings_path_map_test_file.c > /dev/null 2>&1 &&
97 # Now that we've done our last non-LTO build, turn on LTO in CFLAGS as well
98 export CFLAGS="-ffile-prefix-map=$HOME/.cargo="
99 rm genbindings_path_map_test_file.c
100
101 cargo build
102 cbindgen -v --config cbindgen.toml -o include/lightning.h >/dev/null 2>&1
103
104 # cbindgen is relatively braindead when exporting typedefs -
105 # it happily exports all our typedefs for private types, even with the
106 # generics we specified in C mode! So we drop all those types manually here.
107 if [ "$HOST_PLATFORM" = "host: x86_64-apple-darwin" ]; then
108         # OSX sed is for some reason not compatible with GNU sed
109         sed -i '' 's/typedef LDKnative.*Import.*LDKnative.*;//g' include/lightning.h
110
111         # stdlib.h doesn't exist in clang's wasm sysroot, and cbindgen
112         # doesn't actually use it anyway, so drop the import.
113         sed -i '' 's/#include <stdlib.h>//g' include/lightning.h
114 else
115         sed -i 's/typedef LDKnative.*Import.*LDKnative.*;//g' include/lightning.h
116
117         # stdlib.h doesn't exist in clang's wasm sysroot, and cbindgen
118         # doesn't actually use it anyway, so drop the import.
119         sed -i 's/#include <stdlib.h>//g' include/lightning.h
120 fi
121
122 # Finally, sanity-check the generated C and C++ bindings with demo apps:
123
124 LOCAL_CFLAGS="-Wall -Wno-nullability-completeness -pthread"
125
126 # Naively run the C demo app:
127 gcc $LOCAL_CFLAGS -Wall -g -pthread demo.c target/debug/libldk.a -ldl
128 ./a.out
129
130 # And run the C++ demo app in valgrind to test memory model correctness and lack of leaks.
131 g++ $LOCAL_CFLAGS -std=c++11 -Wall -g -pthread demo.cpp -Ltarget/debug/ -lldk -ldl
132 if [ -x "`which valgrind`" ]; then
133         LD_LIBRARY_PATH=target/debug/ valgrind --error-exitcode=4 --memcheck:leak-check=full --show-leak-kinds=all ./a.out
134         echo
135 else
136         echo "WARNING: Please install valgrind for more testing"
137 fi
138
139 # Test a statically-linked C++ version, tracking the resulting binary size and runtime
140 # across debug, LTO, and cross-language LTO builds (using the same compiler each time).
141 clang++ $LOCAL_CFLAGS -std=c++11 demo.cpp target/debug/libldk.a -ldl
142 strip ./a.out
143 echo " C++ Bin size and runtime w/o optimization:"
144 ls -lha a.out
145 time ./a.out > /dev/null
146
147 # Then, check with memory sanitizer, if we're on Linux and have rustc nightly
148 if [ "$HOST_PLATFORM" = "host: x86_64-unknown-linux-gnu" ]; then
149         if cargo +nightly --version >/dev/null 2>&1; then
150                 LLVM_V=$(rustc +nightly --version --verbose | grep "LLVM version" | awk '{ print substr($3, 0, 2); }')
151                 if [ -x "$(which clang-$LLVM_V)" ]; then
152                         cargo +nightly clean
153                         cargo +nightly rustc -Zbuild-std --target x86_64-unknown-linux-gnu -v -- -Zsanitizer=memory -Zsanitizer-memory-track-origins -Cforce-frame-pointers=yes
154                         mv target/x86_64-unknown-linux-gnu/debug/libldk.* target/debug/
155
156                         # Sadly, std doesn't seem to compile into something that is memsan-safe as of Aug 2020,
157                         # so we'll always fail, not to mention we may be linking against git rustc LLVM which
158                         # may differ from clang-llvm, so just allow everything here to fail.
159                         set +e
160
161                         # First the C demo app...
162                         clang-$LLVM_V $LOCAL_CFLAGS -fsanitize=memory -fsanitize-memory-track-origins -g demo.c target/debug/libldk.a -ldl
163                         ./a.out
164
165                         # ...then the C++ demo app
166                         clang++-$LLVM_V $LOCAL_CFLAGS -std=c++11 -fsanitize=memory -fsanitize-memory-track-origins -g demo.cpp target/debug/libldk.a -ldl
167                         ./a.out >/dev/null
168
169                         # restore exit-on-failure
170                         set -e
171                 else
172                         echo "WARNING: Can't use memory sanitizer without clang-$LLVM_V"
173                 fi
174         else
175                 echo "WARNING: Can't use memory sanitizer without rustc nightly"
176         fi
177 else
178         echo "WARNING: Can't use memory sanitizer on non-Linux, non-x86 platforms"
179 fi
180
181 RUSTC_LLVM_V=$(rustc --version --verbose | grep "LLVM version" | awk '{ print substr($3, 0, 2); }' | tr -d '.')
182
183 if [ "$HOST_PLATFORM" = "host: x86_64-apple-darwin" ]; then
184         # Apple is special, as always, and decided that they must ensure that there is no way to identify
185         # the LLVM version used. Why? Just to make your life hard.
186         # This list is taken from https://en.wikipedia.org/wiki/Xcode
187         APPLE_CLANG_V=$(clang --version | head -n1 | awk '{ print $4 }')
188         if [ "$APPLE_CLANG_V" = "10.0.0" ]; then
189                 CLANG_LLVM_V="6"
190         elif [ "$APPLE_CLANG_V" = "10.0.1" ]; then
191                 CLANG_LLVM_V="7"
192         elif [ "$APPLE_CLANG_V" = "11.0.0" ]; then
193                 CLANG_LLVM_V="8"
194         elif [ "$APPLE_CLANG_V" = "11.0.3" ]; then
195                 CLANG_LLVM_V="9"
196         elif [ "$APPLE_CLANG_V" = "12.0.0" ]; then
197                 CLANG_LLVM_V="10"
198         else
199                 echo "WARNING: Unable to identify Apple clang LLVM version"
200                 CLANG_LLVM_V="0"
201         fi
202 else
203         CLANG_LLVM_V=$(clang --version | head -n1 | awk '{ print substr($4, 0, 2); }' | tr -d '.')
204 fi
205
206 if [ "$CLANG_LLVM_V" = "$RUSTC_LLVM_V" ]; then
207         CLANG=clang
208         CLANGPP=clang++
209 elif [ "$(which clang-$RUSTC_LLVM_V)" != "" ]; then
210         CLANG="$(which clang-$RUSTC_LLVM_V)"
211         CLANGPP="$(which clang++-$RUSTC_LLVM_V)"
212 fi
213
214 if [ "$CLANG" != "" -a "$CLANGPP" = "" ]; then
215         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"
216         echo "You should create a symlink called clang++-$RUSTC_LLVM_V pointing to $CLANG in $(dirname $CLANG)"
217 fi
218
219 # Finally, if we're on OSX or on Linux, build the final debug binary with address sanitizer (and leave it there)
220 if [ "$HOST_PLATFORM" = "host: x86_64-unknown-linux-gnu" -o "$HOST_PLATFORM" = "host: x86_64-apple-darwin" ]; then
221         if [ "$CLANGPP" != "" ]; then
222                 if [ "$HOST_PLATFORM" = "host: x86_64-apple-darwin" ]; then
223                         # OSX sed is for some reason not compatible with GNU sed
224                         sed -i .bk 's/,"cdylib"]/]/g' Cargo.toml
225                 else
226                         sed -i.bk 's/,"cdylib"]/]/g' Cargo.toml
227                 fi
228                 RUSTC_BOOTSTRAP=1 cargo rustc -v -- -Zsanitizer=address -Cforce-frame-pointers=yes || ( mv Cargo.toml.bk Cargo.toml; exit 1)
229                 mv Cargo.toml.bk Cargo.toml
230
231                 # First the C demo app...
232                 $CLANG $LOCAL_CFLAGS -fsanitize=address -g demo.c target/debug/libldk.a -ldl
233                 ASAN_OPTIONS='detect_leaks=1 detect_invalid_pointer_pairs=1 detect_stack_use_after_return=1' ./a.out
234
235                 # ...then the C++ demo app
236                 $CLANGPP $LOCAL_CFLAGS -std=c++11 -fsanitize=address -g demo.cpp target/debug/libldk.a -ldl
237                 ASAN_OPTIONS='detect_leaks=1 detect_invalid_pointer_pairs=1 detect_stack_use_after_return=1' ./a.out >/dev/null
238         else
239                 echo "WARNING: Please install clang-$RUSTC_LLVM_V and clang++-$RUSTC_LLVM_V to build with address sanitizer"
240         fi
241 else
242         echo "WARNING: Can't use address sanitizer on non-Linux, non-OSX non-x86 platforms"
243 fi
244
245 # Now build with LTO on on both C++ and rust, but without cross-language LTO:
246 # Clear stale release build artifacts from previous runs
247 cargo clean --release
248 CARGO_PROFILE_RELEASE_LTO=true cargo rustc -v --release -- -C lto
249 clang++ $LOCAL_CFLAGS -std=c++11 -flto -O2 demo.cpp target/release/libldk.a -ldl
250
251 if [ "$HOST_PLATFORM" != "host: x86_64-apple-darwin" -a "$CLANGPP" != "" ]; then
252         # If we can use cross-language LTO, use it for building C dependencies (i.e. libsecp256k1) as well
253         export CC="$CLANG"
254         export CFLAGS_wasm32_wasi="-target wasm32"
255 fi
256
257 if [ "$2" = "false" -a "$(rustc --print target-list | grep wasm32-wasi)" != "" ]; then
258         # Test to see if clang supports wasm32 as a target (which is needed to build rust-secp256k1)
259         echo "int main() {}" > genbindings_wasm_test_file.c
260         clang -nostdlib -o /dev/null --target=wasm32-wasi -Wl,--no-entry genbindings_wasm_test_file.c > /dev/null 2>&1 &&
261         # And if it does, build a WASM binary without capturing errors
262         cargo rustc -v --target=wasm32-wasi -- -C embed-bitcode=yes &&
263         # Now that we've done our last non-LTO build, turn on LTO in CFLAGS as well
264         export CFLAGS="$CFLAGS -flto" &&
265         CARGO_PROFILE_RELEASE_LTO=true cargo rustc -v --release --target=wasm32-wasi -- -C opt-level=s -C linker-plugin-lto -C lto ||
266         echo "Cannot build WASM lib as clang does not seem to support the wasm32-wasi target"
267         rm genbindings_wasm_test_file.c
268 fi
269
270 strip ./a.out
271 echo "C++ Bin size and runtime with only RL (LTO) optimized:"
272 ls -lha a.out
273 time ./a.out > /dev/null
274
275 if [ "$HOST_PLATFORM" != "host: x86_64-apple-darwin" -a "$CLANGPP" != "" ]; then
276         # Finally, test cross-language LTO. Note that this will fail if rustc and clang++
277         # build against different versions of LLVM (eg when rustc is installed via rustup
278         # or Ubuntu packages). This should work fine on Distros which do more involved
279         # packaging than simply shipping the rustup binaries (eg Debian should Just Work
280         # here).
281         # The cc-rs crate tries to force -fdata-sections and -ffunction-sections on, which
282         # breaks -fembed-bitcode, so we turn off cc-rs' default flags and specify exactly
283         # what we want here.
284         export CFLAGS="$CFLAGS -O3 -fPIC -fembed-bitcode"
285         export CRATE_CC_NO_DEFAULTS=true
286         # Rust doesn't recognize CFLAGS changes, so we need to clean build artifacts
287         cargo clean --release
288         CARGO_PROFILE_RELEASE_LTO=true cargo rustc -v --release -- -C linker-plugin-lto -C lto -C link-arg=-fuse-ld=lld
289         $CLANGPP $LOCAL_CFLAGS -flto -fuse-ld=lld -O2 demo.cpp target/release/libldk.a -ldl
290         strip ./a.out
291         echo "C++ Bin size and runtime with cross-language LTO:"
292         ls -lha a.out
293         time ./a.out > /dev/null
294 else
295         echo "WARNING: Building with cross-language LTO is not avilable on OSX or without clang-$RUSTC_LLVM_V"
296 fi