Could not able to release a file. getting error: could not compile 'libc' - rust

I am very new to this language and coding field. Beginner to coding field as well.
I tried to build and release file but getting an error Compiling libc v0.2.62
error: Could not compile `libc`
pi#raspberrypi:~/Ganesh_Rust/Real_time/led_blink/src $ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.09s
Running `/home/pi/Ganesh_Rust/Real_time/led_blink/target/debug/led_blink`
pi#raspberrypi:~/Ganesh_Rust/Real_time/led_blink/src $ cargo build --release
Compiling libc v0.2.62
error: Could not compile `libc`.
Caused by:
process didn't exit successfully: `rustc --crate-name build_script_build /home/pi/.cargo/registry/src/github.com-1ecc6299db9ec823/libc-0.2.62/build.rs --color always --crate-type bin --emit=dep-info,link -C opt-level=3 --cfg 'feature="default"' --cfg 'feature="std"' -C metadata=b79e3ef31fa8c249 -C extra-filename=-b79e3ef31fa8c249 --out-dir /home/pi/Ganesh_Rust/Real_time/led_blink/target/release/build/libc-b79e3ef31fa8c249 -L dependency=/home/pi/Ganesh_Rust/Real_time/led_blink/target/release/deps --cap-lints allow` (signal: 11, SIGSEGV: invalid memory reference)
code: this program which i wrote in VS code to blink LED on raspberry pi 3
use rust_gpiozero::*;
use std::thread;
use std::time::Duration;
fn main() {
//create a new LEd attached to pin 17 of raspberry pi
let led = LED::new(17);
//blink the led 5 times
for _ in 0.. 5{
led.on();
thread::sleep(Duration::from_secs(10));
led.off();
thread::sleep(Duration::from_secs(10));
}
}
cargo.toml file:
[package]
name = "led_blink"
version = "0.1.0"
authors = ["pi"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rust_gpiozero = "0.2.0"
I am getting output on Raspberry pi but executable file and binary files are large (5MB). So i thought if i do release maybe i can reduce size so tried to release using cargo build --release command but getting this error.

If you're using rustup-provided binaries, then this is a known issue upstream. There is a workaround in that issue, which is to set the following in Cargo.toml:
[profile.release]
codegen-units = 1
As an alternative, you can use the Debian rustc and cargo packages instead of rustup, which should work just fine. You can either download the packages from https://packages.debian.org/rustc and https://packages.debian.org/cargo, or you can add an appropriate APT line into /etc/sources.list (see https://deb.debian.org/ for an example). Note that Debian does not always have the latest version, but they should work.

Related

error: the option `Z` is only accepted on the nightly compiler is not solved

I'm trying to use Address sanitizer in rust with this manual(https://github.com/japaric/rust-san),
but when I build this code with command RUSTFLAGS="-Z sanitier=address" cargo rustc -- --emit=llvm-ir, it cause error like this;
error: failed to run rustc to learn about target-specific information
Caused by:
process didn't exit successfully: rustc - --crate-name ___ --print=file-names -Z sanitier=address --crate-type bin --crate-type rlib --crate-type dylib --crate-type cdylib --crate-type staticlib --crate-type proc-macro --print=sysroot --print=cfg (exit status: 1)
--- stderr
error: the option Z is only accepted on the nightly compiler'
I think that "the option Z is only accepted on the nightly compiler" is problem, so I set up to nightly compiler with
rustup install nightly, rustup default nightly, but it cause same error when I build with that command.
How should I do?
Perhaps you should build your code with command:
RUSTFLAGS="-Z sanitier=address" cargo run ${your-binary-name} --target x86_64-unknown-linux-gnu -- --emit=llvm-ir
This works for me to check example in manual:
RUSTFLAGS="-Z sanitizer=address" cargo run --example out-of-bounds --target x86_64-unknown-linux-gnu -- --emit=llvm-ir
**==618620==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7fffbcbf1250 at pc 0x55adfda84e90 bp 0x7fffbcbf1210 sp 0x7fffbcbf1208
READ of size 4 at 0x7fffbcbf1250 thread T0
#0 0x55adfda84e8f in out_of_bounds::main::hf228b092630ab849 /tmp/rust-san/asan/examples/out-of-bounds.rs:3:22
#1 0x55adfda846fa in core::ops::function::FnOnce::call_once::h84454ea25b7d75ab /rustc/f1f721e64014863f41c1a386b04af04c2de25321/library/core/src/ops/function.rs:248:5
#2 0x55adfda84a94 in std::sys_common::backtrace::__rust_begin_short_backtrace::hbc7697f2c0b7e35d /rustc/f1f721e64014863f41c1a386b04af04c2de25321/library/std/src/sys_common/backtrace.rs:122:18
#3 0x55adfda853a3 in std::rt::lang_start::_$u7b$$u7b$closure$u7d$$u7d$::h01c2d6f3a231ead0 /rustc/f1f721e64014863f41c1a386b04af04c2de25321/library/std/src/rt.rs:145:18
#4 0x55adfda9704d in core::ops::function::impls::_$LT$impl$u20$core..ops..function..FnOnce$LT$A$GT$$u20$for$u20$$RF$F$GT$::call_once::hfce3f72e51a03fc4 /rustc/f1f721e64014863f41c1a386b04af04c2de25321/library/core/src/ops/function.rs:280:13
**
According to the manual, you should always pass --target x86_64-unknown-linux-gnu to Cargo.
Be sure to always pass --target x86_64-unknown-linux-gnu to Cargo or else you'll end up sanitizing the build scripts that Cargo runs or run into compilation error if your crate depends on a dylib.
And you could check your toolchain version with:
> rustup default
nightly-x86_64-unknown-linux-gnu (default)

Why does clap fail to compile when added to Cargo.toml?

Summary
I'm fairly new to Rust and decided to use it to port an existing project into it. I intended to use clap to handle CLI options, but I keep getting errors.
What do I need to do for clap to install correctly so that it's usable in my project as a dependency (e.g. extern crate clap; [...] use clap::App; [...]?
I haven't had problems with other crates (so far), so I'm not sure what's so different here or if there's a problem with the crate itself.
I've already seen a few questions (e.g. this one), which simply suggests that the dependency be added into the .toml file or don't seem to provide a solution to what I'm seeing.
I'm in Ubuntu Linux, if that makes a difference.
What I Tried
Adding clap = "2.33.0" to my Cargo.toml file (see https://crates.io/crates/clap) causes VSCode (through RLS) to log the following:
{
"resource": "[...]/Projects/takeout/Cargo.toml",
"owner": "rust",
"severity": 8,
"message": "Could not compile `clap`.\nprocess didn't exit successfully: `[...]/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/bin/rls --crate-name clap [...]/.cargo/registry/src/github.com-1ecc6299db9ec823/clap-2.33.0/src/lib.rs --color never --crate-type lib --emit=dep-info,metadata -C debuginfo=2 --cfg 'feature=\"ansi_term\"' --cfg 'feature=\"atty\"' --cfg 'feature=\"color\"' --cfg 'feature=\"default\"' --cfg 'feature=\"strsim\"' --cfg 'feature=\"suggestions\"' --cfg 'feature=\"vec_map\"' -C metadata=630980a214d5fd10 -C extra-filename=-630980a214d5fd10 --out-dir [...]/Projects/takeout/target/rls/debug/deps -L dependency=[...]/Projects/takeout/target/rls/debug/deps --extern ansi_term=[...]/Projects/takeout/target/rls/debug/deps/libansi_term-1510a9addefc0253.rmeta --extern atty=[...]/Projects/takeout/target/rls/debug/deps/libatty-7c4847fd9fc1e3d9.rmeta --extern bitflags=[...]/Projects/takeout/target/rls/debug/deps/libbitflags-8369a9aec15a5abb.rmeta --extern strsim=[...]/Projects/takeout/target/rls/debug/deps/libstrsim-301d1cf239e9cd24.rmeta --extern textwrap=[...]/Projects/takeout/target/rls/debug/deps/libtextwrap-a799d71e2d028df4.rmeta --extern unicode_width=[...]/Projects/takeout/target/rls/debug/deps/libunicode_width-58e38dd9d658dcfb.rmeta --extern vec_map=[...]/Projects/takeout/target/rls/debug/deps/libvec_map-4f8e59c92e9953d8.rmeta --cap-lints allow --error-format=json --sysroot [...]/.rustup/toolchains/stable-x86_64-unknown-linux-gnu` (exit code: 101)",
"startLineNumber": 1,
"startColumn": 1,
"endLineNumber": 10000,
"endColumn": 1
}
According to the README in the clap repo itself, just adding it should work:
For full usage, add clap as a dependency in your Cargo.toml to use from crates.io:
[dependencies]
clap = "~2.33"
But it doesn't.
I've tried it with and without the ~ prefix as well as clap = {version = "2.33", features = ["yaml"]}, which is also shown in the repo, but no luck. (Yes, I'm trying to load the CLI options from a .yaml file.)
Trying cargo install clap --version 2.33.0 from the shell simply returns an error message saying: error: specified package has no binaries.
Aiming directly at the Git repo also produces the same error message:
cargo install --git https://github.com/clap-rs/clap.git --tag v2.31.2 --features yaml 101 ↵
Updating git repository `https://github.com/clap-rs/clap.git`
Installing clap v2.31.2 (https://github.com/clap-rs/clap.git?tag=v2.31.2#07c15d28)
error: specified package has no binaries
Note that there's no v2.33.0 tag in the Git repo (at the time of this writing).
Bonus if you know how to get VSCode to stop marking everything as an error:
cargo install
There's misunderstanding about the cargo install command. You can learn more about it here.
This command manages Cargo’s local set of installed binary crates. Only packages which have executable [[bin]] or [[example]] targets can be installed, and all executables are installed into the installation root’s bin folder.
It's not your case. The only thing you have to do is to list clap in the dependencies section (Cargo.toml). That's all. No need to use cargo install at all. cargo build, cargo run, ... commands will download & compile & statically link all dependencies.
An example
Folder structure:
.
├── Cargo.toml
└── src
   ├── cli.yaml
   └── main.rs
Current directory:
$ pwd
/Users/robertvojta/Projects/stackoverflow/clap-yaml
Cargo.toml content:
[package]
name = "clap-yaml"
version = "0.1.0"
authors = ["Zrzka"]
edition = "2018"
[dependencies]
clap = { version = "2.33.0", features = ["yaml"] }
src/cli.yaml content:
name: clap-yaml
version: "1.0"
author: Zrzka
about: Stackoverflow sample
args:
- lang:
short: l
long: lang
default_value: cz
takes_value: true
possible_values:
- cz
- en
src/main.rs content:
use clap::{App, load_yaml};
fn main() {
let yaml = load_yaml!("cli.yaml");
let matches = App::from_yaml(yaml).get_matches();
match matches.value_of("lang").unwrap() {
"cz" => println!("Ahoj"),
"en" => println!("Hello"),
_ => unreachable!("see possible_values in yaml, handled by clap"),
};
}
Run it with cargo:
$ cargo -q run -- --lang en
Hello
Run it directly:
$ cargo build
...
Finished dev [unoptimized + debuginfo] target(s) in 0.01s
$ target/debug/clap-yaml --lang cz
Ahoj
Visual Studio Code
I still have vscode complaining and underlining everything in red in the Cargo.toml file. Any suggestions to fix this completely? It seems close to a full resolution.
I can confirm that this problem do exist in Rust 1.34.0. I did install this version and I've got same symptoms:
could not compile clap
the whole Cargo.toml is underlined (error)
There're two ways how to fix this.
Update your Cargo.toml file dependencies section manually if you'd like to stick with Rust 1.34.0:
[dependencies]
bitflags = "=1.0.4"
clap = { version = "2.33.0", features = ["yaml"] }
Or update your Rust toolchain to >= 1.35.0.
I just tested both ways and it works.
Related issues:
Could not compile clap. process didn't exit successfully
Compiler panics on latest RLS when compiling crates that depend on bitflags 1.0.5

Is it possible to avoid recompiling a crate when I haven't made any changes to it?

I have a Rust crate which is a wrapper for a large C API and takes several minutes to compile. Running cargo build in the directory without making any changes always results in a recompile. It seems that Cargo should not be recompiling this crate unless I make a change, which I have not done.
I would like to compile the crate once and avoid re-compiling the crate unless I make a change. Is there any way for me to avoid constantly recompiling this scrate?
It seems that something is likely incorrect in my crate's build script. I will try to create a minimal reproducible example, but in the meantime I have provided the build script below:
use std::env;
use std::fs::copy;
use std::path::Path;
use std::process::Command;
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let c_src_path = Path::new("parasail_c");
// configure the build
Command::new("cmake")
.arg(".")
.current_dir(&c_src_path)
.output()
.expect("Failed to configure parasail.");
// build the library
Command::new("make")
.current_dir(&c_src_path)
.output()
.expect("Failed to build parasail.");
// put the static library in the right directory so we can clean up
let target_file = format!("{}/libparasail.so", out_dir);
copy("parasail_c/libparasail.so", target_file)
.expect("Problem copying library to target directoy.");
let target_file = format!("{}/parasail.h", out_dir);
copy("parasail_c/parasail.h", target_file)
.expect("Problem copying header to target directoy.");
// clean up the temporary build files
Command::new("make")
.current_dir(&c_src_path)
.arg("clean")
.output()
.expect("Failed to clean up build files.");
// clean up the configuration files
Command::new("make")
.arg("distclean")
.current_dir(&c_src_path)
.output()
.expect("Failed to clean up configuration files.");
// let cargo know that it can find the file in the out directory
println!("cargo:rustc-link-search=native={}", out_dir);
println!("cargo:rustc-link-lib=dylib=parasail");
}
Here is the output from cargo build --verbose
cargo build --verbose
Compiling parasail-sys v0.1.0 (/home/fortier/testcode/rust/pairhmm/parasail-sys)
Fresh libc v0.2.51
Running `/home/fortier/testcode/rust/pairhmm/parasail-sys/target/debug/build/parasail-sys-f2d2d1f27a70b4d4/build-script-build`
Running `rustc --edition=2018 --crate-name parasail_sys src/lib.rs --color always --crate-type lib --emit=dep-info,link -C debuginfo=2 -C metadata=8879665b3d9bf7e1 -C extra-filename=-8879665b3d9bf7e1 --out-dir /home/fortier/testcode/rust/pairhmm/parasail-sys/target/debug/deps -C incremental=/home/fortier/testcode/rust/pairhmm/parasail-sys/target/debug/incremental -L dependency=/home/fortier/testcode/rust/pairhmm/parasail-sys/target/debug/deps --extern libc=/home/fortier/testcode/rust/pairhmm/parasail-sys/target/debug/deps/liblibc-bc949bf21f4fe772.rlib -L native=/home/fortier/testcode/rust/pairhmm/parasail-sys/target/debug/build/parasail-sys-2ac393455c1f3545/out -l dylib=parasail`
Finished dev [unoptimized + debuginfo] target(s) in 1m 58s
After further inspection I have discovered that the issue is somewhere in the C code that the sub-crate is wrapping. I replaced the current C code with an older version, while changing none of the Rust code and the issue has disappeared. I'll continue doing some further investigation to see exactly what was causing the problem and I'll update this post once I narrow it down.
Add to the build script println!("cargo:rerun-if-changed={}", &file); lines for each file and for each directory.

Statically linking ffmpeg-sys on Amazon Linux fails with undefined references

My project depends on the ffmpeg-sys crate which is configured to build statically, as follows:
[dependencies.ffmpeg-sys]
version = "3.4.1"
default-features = false
features = ["avcodec", "avformat", "swresample", "build", "static"]
My project consists of a single simple file:
extern crate ffmpeg_sys;
use ffmpeg_sys::av_register_all;
fn main() {
unsafe { av_register_all() };
println!("Hello, world!");
}
When compiling with cargo build I get the following error:
Compiling sample v0.1.0 (file:///home/ec2-user/sample)
error: linking with 'cc' failed: exit code: 1 | = note: "cc"
"-Wl,--as-needed" "-Wl,-z,noexecstack" "-m64" "-L"
[... elided for clarity ...]
In function 'sample::main::hbbb19855251826d6':
/home/ec2-user/sample/src/main.rs:6: undefined reference to 'av_register_all'
collect2: error: ld returned 1 exit status
The required static libraries, libavformat.a and friends, are found in the target/build/debug folder, showing that ffmpeg-sys successfully compiled the libraries.
Here's the rustc command that is failing:
Caused by: process didn't exit successfully: 'rustc --crate-name
sample src/main.rs --crate-type bin --emit=dep-info,link -C
debuginfo=2 -C metadata=250bf40eb277d05a -C
extra-filename=-250bf40eb277d05a --out-dir
/home/ec2-user/sample/target/debug/deps -C
incremental=/home/ec2-user/sample/target/debug/incremental -L
dependency=/home/ec2-user/sample/target/debug/deps --extern
ffmpeg_sys=/home/ec2-user/sample/target/debug/deps/libffmpeg_sys-fa3ff87f80f2d27e.rlib
-L native=/home/ec2-user/sample/target/debug/build/ffmpeg-sys-0b3c813f29a9a20e/out/dist/lib'
(exit code: 1)
libffmpeg_sys-fa3ff87f80f2d27e.rlib is 207M and I assume therefore contains all the statically compiled ffmpeg code.
This only happens when I build on an Amazon Linux instance. Compiling on my regular Fedora 28 desktop results in a working binary.
How would I go about figuring out the root cause of this error?
I solved this problem by building llvm 6.0.1 and then rebuilding with LIBCLANG_PATH set to point to the newer version.
It would appear that rustc has a minimum version requirement on libclang.so, but I could not find an official source documenting that. The version installed on amazon-linux is 3.6.2 which is evidently too old.

Linking to optimised crate from a debug build

I would like to separate some performance intensive code into a .so (I am running Kubuntu Linux) while the main quantity of my code is compiled in debug mode. I want the faster compiles and run time support in my code, but it's unacceptable to run the small amount of intensive code with all the debug checks in it.
Is it possible to do this using Cargo? It seems that Cargo propagates the top level profile to the dependencies, so they are all compiled as release or debug, depending on what is requested of the main crate.
This is possible as of Rust 1.41 via overrides:
[package]
name = "speedy"
version = "0.1.0"
authors = ["An Devloper <an.devloper#example.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
image = "0.21.1"
# All dependencies (but not this crate itself or any workspace member)
# will be compiled with -Copt-level=2 . This includes build dependencies.
[profile.dev.package."*"]
opt-level = 2
The output with some details elided:
$ cargo build --verbose
Compiling image v0.23.0
Running `rustc [...] --crate-name image [...] -C opt-level=2 -C debuginfo=2 -C debug-assertions=on [...]`
Compiling speedy v0.1.0 (/private/tmp/speedy)
Running `rustc [...] --crate-name speedy [...] -C debuginfo=2 [...]`

Resources