| #!/bin/bash | |
| # Copyright 2026 The Fuchsia Authors. All rights reserved. | |
| # Use of this source code is governed by a BSD-style license that can be | |
| # found in the LICENSE file. | |
| # | |
| # This script generates Rust bindings for libpcap. | |
| # Run `./bindgen.sh check` to validate that the bindings haven't changed. | |
| # Determine paths for this script and its directory, and set $FUCHSIA_DIR. | |
| readonly FULL_PATH="${BASH_SOURCE[0]}" | |
| readonly SCRIPT_DIR="$(cd "$(dirname "${FULL_PATH}")" >/dev/null 2>&1 && pwd)" | |
| source "${SCRIPT_DIR}/../../../../../../tools/devshell/lib/vars.sh" | |
| set -Eeuo pipefail | |
| cd "${SCRIPT_DIR}" | |
| readonly RELPATH="${SCRIPT_DIR#${FUCHSIA_DIR}/}/bindgen.sh" | |
| readonly BINDGEN="${PREBUILT_RUST_BINDGEN_DIR}/bindgen" | |
| # Generate annotations for the top of the generated source file. | |
| readonly RAW_LINES="// Copyright 2026 The Fuchsia Authors. All rights reserved. | |
| // Use of this source code is governed by a BSD-style license that can be | |
| // found in the LICENSE file. | |
| // WARNING - This file was generated by ${RELPATH} using | |
| // $("${BINDGEN}" --version). Do not modify this file! It should be | |
| // regenerated by running ${RELPATH}. | |
| #![allow(non_camel_case_types)] | |
| #![allow(clippy::missing_safety_doc)] | |
| #![allow(missing_docs)] | |
| use zerocopy::{Immutable, IntoBytes}; | |
| " | |
| readonly RUST_FILE="bindings.rs" | |
| # Output to a tempfile in check mode, or the actual file when generating. | |
| if [[ $# -ge 1 && "$1" = "check" ]] ; then | |
| readonly OUTPUT="$(mktemp -p "${PWD}" --suffix=.rs)" | |
| trap "rm -f ${OUTPUT}" EXIT | |
| else | |
| readonly OUTPUT="${RUST_FILE}" | |
| fi | |
| "${BINDGEN}" \ | |
| "wrapper.h" \ | |
| --disable-header-comment \ | |
| --raw-line "${RAW_LINES}" \ | |
| --no-layout-tests \ | |
| --allowlist-function "^(pcap_open_dead|pcap_compile|pcap_freecode|pcap_close)$" \ | |
| --with-derive-custom "bpf_insn=IntoBytes,Immutable" \ | |
| --output "${OUTPUT}" \ | |
| -- \ | |
| -I "${FUCHSIA_DIR}/third_party/libpcap/src" \ | |
| -I . | |
| # Use rustfmt directly instead of `fx format-code` because that requires the | |
| # file to be within FUCHSIA_DIR, and in check mode we'll be running it on a | |
| # temp file in TEMPDIR. | |
| "${PREBUILT_RUST_DIR}"/bin/rustfmt \ | |
| "${OUTPUT}" \ | |
| --config-path "${FUCHSIA_DIR}"/rustfmt.toml \ | |
| --unstable-features \ | |
| --skip-children | |
| if [[ $# -ge 1 && "$1" = "check" ]] && ! diff "${OUTPUT}" "${RUST_FILE}" ; then | |
| echo "The libpcap bindings have changed without updating the rust bindings." | |
| echo "Please run './bindgen.sh' in ${PWD}." | |
| exit 1 | |
| fi |