Skip to content
Open
5 changes: 5 additions & 0 deletions cargo-near-build/src/env_keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ pub(crate) const CARGO_NEAR_VERSION: &str = "CARGO_NEAR_VERSION";
#[cfg(feature = "build_internal")]
pub(crate) const CARGO_NEAR_ABI_SCHEMA_VERSION: &str = "CARGO_NEAR_ABI_SCHEMA_VERSION";

/// C compiler flags, respected by the `cc` crate when compiling C dependencies
pub const CFLAGS_ENV: &str = "CFLAGS";
/// C++ compiler flags, respected by the `cc` crate when compiling C++ dependencies
pub const CXXFLAGS_ENV: &str = "CXXFLAGS";

pub const COLOR_PREFERENCE_NO_COLOR: &str = "NO_COLOR";

use std::collections::HashMap;
Expand Down
13 changes: 12 additions & 1 deletion cargo-near-build/src/near/build/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,18 @@ pub fn run(args: Opts) -> eyre::Result<CompilationArtifact> {
let abi_path_env = buildtime_env::AbiPath::new(args.no_embed_abi, &min_abi_path);

let build_env = {
let mut build_env = vec![(env_keys::RUSTFLAGS, "-C link-arg=-s")];
let mut build_env = vec![
(env_keys::RUSTFLAGS, "-C link-arg=-s"),
// Prevent C/C++ dependencies (compiled via the `cc` crate) from emitting
// post-MVP wasm instructions. LLVM 21+ enables `bulk-memory` and
// `bulk-memory-opt` by default for wasm32, which produces `memory.fill`/
// `memory.copy` instructions that NEAR's VM rejects.
// `-mcpu=mvp` restricts the C compiler to the MVP instruction set.
// Note: `-mno-bulk-memory` is insufficient as LLVM 21 ignores it for the
// separate `bulk-memory-opt` feature.
(env_keys::CFLAGS_ENV, "-mcpu=mvp"),
(env_keys::CXXFLAGS_ENV, "-mcpu=mvp"),
Copy link

Copilot AI Mar 23, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Setting CFLAGS/CXXFLAGS here will override any flags the user already has in their shell environment for the entire cargo build invocation (not just wasm-target C/C++ compilation). This can break builds that rely on additional CFLAGS or that compile any host-side C code during the build. Consider (a) appending -mcpu=mvp to any existing CFLAGS/CXXFLAGS values instead of replacing them, and/or (b) scoping the flags to the wasm32 target only (so host compilation isn’t affected) while still allowing --env to fully override when needed.

Suggested change
(env_keys::CFLAGS_ENV, "-mcpu=mvp"),
(env_keys::CXXFLAGS_ENV, "-mcpu=mvp"),
("CFLAGS_wasm32-unknown-unknown", "-mcpu=mvp"),
("CXXFLAGS_wasm32-unknown-unknown", "-mcpu=mvp"),

Copilot uses AI. Check for mistakes.
];
build_env.extend(
args.env
.iter()
Expand Down
Loading