forked from libbpf/blazesym
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This change moves all C API functionality into the cblazesym crate in the existing workspace. Doing so ensures better isolation between the core Rust part and the C API and it will allow us to version the C API different from the main Rust crate. Closes: libbpf#344 Signed-off-by: Daniel Müller <[email protected]>
- Loading branch information
Showing
18 changed files
with
396 additions
and
215 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
../.cargo |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
[package] | ||
name = "cblazesym" | ||
version = "0.0.0" | ||
edition = "2021" | ||
rust-version = "1.64" | ||
|
||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | ||
|
||
[lib] | ||
name = "cblazesym" | ||
# `lib` is necessary for end-to-end tests. | ||
crate-type = ["lib", "cdylib", "staticlib"] | ||
|
||
[features] | ||
# Enable this feature to re-generate the library's C header file. An | ||
# up-to-date version of this header should already be available in the | ||
# include/ directory, so this feature is only necessary when APIs are | ||
# changed. | ||
generate-c-header = ["cbindgen", "which"] | ||
|
||
[build-dependencies] | ||
cbindgen = {version = "0.26", optional = true} | ||
which = {version = "5.0.0", optional = true} | ||
|
||
[dependencies] | ||
# Pinned, because we use #[doc(hidden)] APIs. | ||
blazesym = {version = "=0.2.0-alpha.8", path = "../"} | ||
libc = "0.2.137" | ||
|
||
[dev-dependencies] | ||
env_logger = "0.10" | ||
test-log = {version = "0.2.13", default-features = false, features = ["trace"]} | ||
tracing-subscriber = {version = "0.3", default-features = false, features = ["env-filter", "fmt"]} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
[![pipeline](https://github.com/libbpf/blazesym/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/libbpf/blazesym/actions/workflows/test.yml) | ||
[![rustc](https://img.shields.io/badge/rustc-1.65+-blue.svg)](https://blog.rust-lang.org/2022/11/03/Rust-1.65.0.html) | ||
|
||
cblazesym | ||
========= | ||
|
||
**cblazesym** provides C language bindings for the | ||
[**blazesym**][blazesym] library. | ||
|
||
## Build & Use | ||
**cblazesym** requires a standard Rust toolchain and can be built using | ||
the Cargo project manager (e.g., `cargo build`). | ||
|
||
The build will produce `libcblazesym.a` as well as `libcblazesym.so` in | ||
the respective target folder (e.g., `<project-root>/target/debug/`). | ||
|
||
In your C programs include [`blazesym.h`](include/blazesym.h) (provided as part | ||
of the crate) from your source code and then link against the static or | ||
shared library, respectively. When linking statically, you may also need | ||
to link: | ||
```text | ||
-lrt -ldl -lpthread -lm | ||
``` | ||
|
||
An example of usage of the C API is in available in **libbpf-bootstrap**: | ||
<https://github.com/libbpf/libbpf-bootstrap/blob/master/examples/c/profile.c> | ||
|
||
This example periodically samples the running process of every processor | ||
in a system and prints their stack traces. | ||
|
||
A detailed [documentation of the C API](https://docs.rs/cblazesym/latest/) | ||
is available as part of the Rust documentation or can be generated locally from | ||
the current repository snapshot using `cargo doc`. | ||
|
||
[blazesym]: https://crates.io/crates/blazesym |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,170 @@ | ||
#![allow(clippy::let_unit_value)] | ||
|
||
use std::env; | ||
use std::ffi::OsStr; | ||
use std::io::Error; | ||
use std::io::ErrorKind; | ||
use std::io::Result; | ||
use std::ops::Deref as _; | ||
use std::path::Path; | ||
use std::process::Command; | ||
use std::process::Stdio; | ||
|
||
|
||
/// Format a command with the given list of arguments as a string. | ||
fn format_command<C, A, S>(command: C, args: A) -> String | ||
where | ||
C: AsRef<OsStr>, | ||
A: IntoIterator<Item = S>, | ||
S: AsRef<OsStr>, | ||
{ | ||
args.into_iter().fold( | ||
command.as_ref().to_string_lossy().into_owned(), | ||
|mut cmd, arg| { | ||
cmd += " "; | ||
cmd += arg.as_ref().to_string_lossy().deref(); | ||
cmd | ||
}, | ||
) | ||
} | ||
|
||
/// Run a command with the provided arguments. | ||
fn run<C, A, S>(command: C, args: A) -> Result<()> | ||
where | ||
C: AsRef<OsStr>, | ||
A: IntoIterator<Item = S> + Clone, | ||
S: AsRef<OsStr>, | ||
{ | ||
let instance = Command::new(command.as_ref()) | ||
.stdin(Stdio::null()) | ||
.stdout(Stdio::null()) | ||
.env_clear() | ||
.envs(env::vars().filter(|(k, _)| k == "PATH")) | ||
.args(args.clone()) | ||
.output() | ||
.map_err(|err| { | ||
Error::new( | ||
ErrorKind::Other, | ||
format!( | ||
"failed to run `{}`: {err}", | ||
format_command(command.as_ref(), args.clone()) | ||
), | ||
) | ||
})?; | ||
|
||
if !instance.status.success() { | ||
let code = if let Some(code) = instance.status.code() { | ||
format!(" ({code})") | ||
} else { | ||
" (terminated by signal)".to_string() | ||
}; | ||
|
||
let stderr = String::from_utf8_lossy(&instance.stderr); | ||
let stderr = stderr.trim_end(); | ||
let stderr = if !stderr.is_empty() { | ||
format!(": {stderr}") | ||
} else { | ||
String::new() | ||
}; | ||
|
||
Err(Error::new( | ||
ErrorKind::Other, | ||
format!( | ||
"`{}` reported non-zero exit-status{code}{stderr}", | ||
format_command(command, args) | ||
), | ||
)) | ||
} else { | ||
Ok(()) | ||
} | ||
} | ||
|
||
/// Compile `src` into `dst` using the provided compiler. | ||
fn compile(compiler: &str, src: &Path, dst: &str, options: &[&str]) { | ||
let dst = src.with_file_name(dst); | ||
println!("cargo:rerun-if-changed={}", src.display()); | ||
println!("cargo:rerun-if-changed={}", dst.display()); | ||
|
||
let () = run( | ||
compiler, | ||
options | ||
.iter() | ||
.map(OsStr::new) | ||
.chain([src.as_os_str(), "-o".as_ref(), dst.as_os_str()]), | ||
) | ||
.unwrap_or_else(|err| panic!("failed to run `{compiler}`: {err}")); | ||
} | ||
|
||
/// Compile `src` into `dst` using `cc`. | ||
#[cfg_attr(not(feature = "generate-c-header"), allow(dead_code))] | ||
fn cc(src: &Path, dst: &str, options: &[&str]) { | ||
compile("cc", src, dst, options) | ||
} | ||
|
||
fn main() { | ||
#[cfg(feature = "generate-c-header")] | ||
{ | ||
use std::fs::copy; | ||
use std::fs::write; | ||
|
||
let crate_dir = env!("CARGO_MANIFEST_DIR"); | ||
|
||
cbindgen::Builder::new() | ||
.with_crate(crate_dir) | ||
.with_config(cbindgen::Config::from_root_or_default(crate_dir)) | ||
.generate() | ||
.expect("Unable to generate bindings") | ||
.write_to_file(Path::new(crate_dir).join("include").join("blazesym.h")); | ||
|
||
// Generate a C program that just included blazesym.h as a basic | ||
// smoke test that cbindgen didn't screw up completely. | ||
let out_dir = env::var_os("OUT_DIR").unwrap(); | ||
let out_dir = Path::new(&out_dir); | ||
let blaze_src_c = out_dir.join("blazesym.c"); | ||
let () = write( | ||
&blaze_src_c, | ||
r#" | ||
#include <blazesym.h> | ||
int main() { | ||
return 0; | ||
} | ||
"#, | ||
) | ||
.unwrap(); | ||
|
||
let blaze_src_cxx = out_dir.join("blazesym.cpp"); | ||
let _bytes = copy(&blaze_src_c, &blaze_src_cxx).expect("failed to copy file"); | ||
|
||
cc( | ||
&blaze_src_c, | ||
"blazesym.bin", | ||
&[ | ||
"-Wall", | ||
"-Wextra", | ||
"-Werror", | ||
"-I", | ||
Path::new(crate_dir).join("include").to_str().unwrap(), | ||
], | ||
); | ||
|
||
// Best-effort check that C++ can compile the thing as well. Hopefully | ||
// all flags are supported... | ||
for cxx in ["clang++", "g++"] { | ||
if which::which(cxx).is_ok() { | ||
compile( | ||
cxx, | ||
&blaze_src_cxx, | ||
&format!("blazesym_cxx_{cxx}.bin"), | ||
&[ | ||
"-Wall", | ||
"-Wextra", | ||
"-Werror", | ||
"-I", | ||
Path::new(crate_dir).join("include").to_str().unwrap(), | ||
], | ||
); | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.