Repository navigation
blaze-ladder front2: fix #[linkage] AttrMeta parsing, wasm64 weak linkage, and cached/in-body foreign statics - #2901
Conversation
…kage, and cached/in-body foreign statics 1. Fix 7416f35 #[linkage] regression: blaze_lower stores Attr { meta: AttrMeta::KeyValue, args } with the leading '=' already stripped (the expression after '='). linkage_of previously called strip_prefix('='), causing every #[linkage = ".."] (including std's extern_weak __dso_handle and statx, and compiler_builtins' weak math intrinsics) to fail as Malformed. - Split into parse_linkage(AttrMeta, &str) + linkage_of_for(AttrMeta, &str, is_wasm) as the one home across program.rs, statics.rs, export_shim.rs, and run/wasm64.rs. - Keep Linkge::Weak honestly refused on native (where blaze-export emits STB_GLOBAL/N_EXT), and genuinely carry Linkage::Weak on target_family = "wasm" where run/wasm64.rs's closed-world module linker tracks weak exports and resolves strong definitions over weak ones (covering compiler_builtins' round/libm wrappers and std's cabi_realloc). 2. Fix cached/in-body foreign statics (std::sys::env::unix::environ): - LazyProgram::make_static_value bypassed foreign_static_symbol and always evaluated via statics::one_static, causing warm cached-record verification (make_one.rs ReadKind::Static) of in-body extern "C" { static mut environ; } to fail with BodyError::NoBody. - Share statics::foreign_static_of across static_values, make_static_value, and ensure_foreign_static (also wired into make_one.rs for ReadKind::ForeignStatic and static_over DataTarget::Static relocations), and index in-body ExternBlock items in nested_exports::walk_every so unhinted cold locate_local finds them too.
|
Codex (@codex) review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0138c304b1
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "Codex (@codex) review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "Codex (@codex) address that feedback".
| match linkage_of_for(a.meta, t, is_wasm).map_err(|refused| Front2Refusal::Linkage { item: path.into(), refused })? { | ||
| Linkage::ExternWeak => out.extern_weak = true, | ||
| Linkage::External => {} | ||
| Linkage::External | Linkage::Weak => {} |
There was a problem hiding this comment.
Route Rust calls through the prevailing weak symbol
When a wasm crate contains a weak #[no_mangle] function plus a strong definition of the same symbol and Rust code calls the weak item through its module path, accepting Linkage::Weak here still tables that call by the weak function's ItemKey/fn_symbol_of_name. The new strong-first selection in collect_rust_c_exports is used only for C-symbol lookups, so such a direct Rust call executes the weak body instead of the prevailing strong definition required by linkage semantics; route these calls through the selected export or keep this form refused.
AGENTS.md reference: AGENTS.md:L116-L120
Useful? React with 👍 / 👎.
| // counted for the ordinals and indexed by `walk_every` (`self.every`) so cold | ||
| // `locate_local` finds body-local foreign statics/fns (e.g. `std`'s in-body | ||
| // `extern "C" { static mut environ; }`); a foreign item is never an export. | ||
| let decls = match super::foreign_locals::declared(item_text, self.reading.edition, &mut CrateCfg::with_version(self.reading.atoms, self.reading.cfg_version), alloc) { |
There was a problem hiding this comment.
Skip cfg-disabled extern blocks before reading declarations
When an in-body extern block is removed by an outer #[cfg]/#[cfg_attr], this branch still passes the block to foreign_locals::declared, which evaluates cfg only on the declarations inside the block. A valid disabled block containing a form that this reader refuses, such as a foreign type or macro declaration, therefore makes an unrelated cold local lookup fail with NestedRefusal::Foreign, even though Rust removes the entire extern block; apply the block's own cfg before inspecting its children.
AGENTS.md reference: AGENTS.md:L116-L120
Useful? React with 👍 / 👎.
| Ok((_, decls)) => decls, | ||
| Err(r) => { | ||
| let path = self.out.path(at, "extern", alloc)?; | ||
| return Err(NestedRefusal::Foreign { path, why: r.form() }); |
There was a problem hiding this comment.
Preserve module-backed extern macro declarations
When a body-local extern block contains a macro invocation whose declarations are represented by the names library's block module (for example ring's prefixed_extern! pattern), foreign_locals::declared returns Refused::MacroCall and this unconditional error aborts walk_every. Locals::keep explicitly skips that error when the scope has an owned module, so the new cold index must mirror that path; otherwise locating any cold local in such an enclosing body can fail before the module-backed foreign items are reached.
AGENTS.md reference: AGENTS.md:L116-L120
Useful? React with 👍 / 👎.
| /// `compiler_builtins`'s `#[linkage = "weak"]` math/soft-float wrappers and `std`'s | ||
| /// `cabi_realloc`) with no external ELF/Mach-O symbol table to clash against. | ||
| pub const fn carried_for(self, is_wasm: bool) -> bool { | ||
| self.carried() || (is_wasm && matches!(self, Linkage::Weak)) |
There was a problem hiding this comment.
Limit weak-linkage acceptance to the memory64 backend
This condition treats every target_family = "wasm" crate as if it will use run/wasm64.rs, so it also accepts #[linkage = "weak"] for targets such as wasm32-wasip1. The weak bit is not retained in Symbols or the ordinary code/static records and is recovered only by the memory64 linker's source scan, so a wasm32 definition is emitted as an ordinary strong definition and can conflict with or prevail over its intended override; gate this on the actual memory64 target/backend or carry the binding through every wasm emission path.
AGENTS.md reference: AGENTS.md:L116-L120
Useful? React with 👍 / 👎.
…dy extern blocks 1. Restrict `#[linkage = "weak"]` acceptance to the memory64 backend (`target_arch = "wasm64"`) via `is_wasm64_target`, so `wasm32-wasip1` continues to honestly refuse `Linkage::Weak`. 2. In `run/wasm64.rs`, redirect direct Rust path calls, fn-pointer coercions, and static references targeting an overridden weak `#[no_mangle]` / `#[export_name]` item to the prevailing strong definition so both C-symbol and Rust-path callers execute the prevailing strong export. 3. Evaluate an in-body `extern` block's own outer `#[cfg]` / `#[cfg_attr]` attributes in `foreign_locals::declared` before inspecting its children so cfg-disabled extern blocks (e.g. containing foreign types or macros) are skipped cleanly by both `nested_exports::walk_every` and `Locals::keep`. 4. Mirror `Locals::keep` in `nested_exports::walk_every` by skipping `foreign_locals::Refused::MacroCall` inside written block modules.
|
Addressed all 4 Codex R1 findings in
Verification:
Codex (@codex) review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 75b2f0adb5
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "Codex (@codex) review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "Codex (@codex) address that feedback".
| } else if path == "linkage" | ||
| && let Ok(args_text) = v.text_at(a.args) | ||
| && crate::front2::program::parse_linkage(a.meta, args_text) == Ok(crate::front2::program::Linkage::Weak) | ||
| { | ||
| weak = true; |
There was a problem hiding this comment.
Include block-local weak exports in override collection
When a function body declares a #[no_mangle] #[linkage = "weak"] function and another item provides the strong definition, a direct lexical call to the local function still executes the weak body. collect_rust_c_exports derives weak overrides only from Records::each_item, while block-local items use synthesized keys from nested_exports/Locals and never enter that iterator; consequently no override is recorded when this new branch recognizes weak linkage. Include nested exported definitions in the collection (or refuse weak linkage on them) so the worklist aliases their direct calls to the prevailing strong item.
AGENTS.md reference: AGENTS.md:L116-L120
Useful? React with 👍 / 👎.
| if !foreign_static_alias.iter().any(|&(from, _)| from == symbol.0) { | ||
| foreign_static_alias.push((symbol.0, winner_sym.0)); |
There was a problem hiding this comment.
Apply weak-static aliases when exporting globals
When compile_items_to_wasm64 roots a weak static that is superseded by a strong definition and opts.export_globals names the weak static's symbol, this branch skips emitting the weak datum and records only the weak-to-winner alias. Section 7 later looks up the unaliased requested symbol directly in static_datums, so the build returns UnresolvedSymbol instead of exporting the prevailing strong static's address; resolve exported-global symbols through foreign_static_alias just like function and datum relocations.
AGENTS.md reference: AGENTS.md:L116-L120
Useful? React with 👍 / 👎.
1. Walk block-local `#[no_mangle]` / `#[export_name]` items via `nested_exports::walk_in_body` during `collect_rust_c_exports`, and add an on-the-fly `find_local_weak_override` fallback in `compile_worklist_to_wasm64` (for written-block and post-macro block-local weak items) so direct lexical calls to any overridden block-local weak item route to the prevailing strong definition. 2. Resolve `Wasm64BuildOpts::export_globals` through `foreign_static_alias` before looking up `static_datums` so exporting a superseded weak static resolves cleanly to the prevailing strong static's address.
|
Addressed both Codex R2 findings in
Verification:
Codex (@codex) review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 72bbc84702
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "Codex (@codex) review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "Codex (@codex) address that feedback".
| cfg_version, | ||
| alloc, | ||
| }; | ||
| if let Ok(walked) = crate::front2::nested_exports::walk_in_body(top, top_body, reading) { |
There was a problem hiding this comment.
Do not discard nested-export scan failures
When an item body contains a valid form that walk_in_body currently refuses—such as an unwritten body-local extern block containing a macro declaration or foreign type—this if let Ok silently discards the entire walk, including unrelated block-local #[no_mangle] exports already found in that body. An extern "C" call to one of those exports then misses rust_exports and fails as an unresolved import; propagate the refusal or make the export-only walk skip irrelevant extern declarations instead. Fresh evidence in this revision is the new fallible walk_in_body call whose error path is ignored.
AGENTS.md reference: AGENTS.md:L121-L123
Useful? React with 👍 / 👎.
| && let Some(winner_item) = find_weak_override(weak_fn_overrides.as_slice(), tabled) | ||
| .or_else(|| find_local_weak_override(maker, tabled, false, rust_exports.as_slice(), alloc)) |
There was a problem hiding this comment.
Initialize local metadata before resolving a weak root
When a fresh Maker receives a written-block or post-macro block-local weak function/static as its first explicit root (or first walk row), the pre-scan intentionally lacks that synthesized local key and find_local_weak_override also returns None because Maker::local_weak_export_text only consults self.made, which is initialized by the later build. The branch therefore compiles the weak body or datum instead of aliasing it to the strong definition; resolve or locate the local before this lookup rather than depending on an earlier work item having initialized the maker. Fresh evidence is that the new fallback is invoked before the first build_lir_with_reach_in/make_static call.
AGENTS.md reference: AGENTS.md:L116-L120
Useful? React with 👍 / 👎.
| if !is_raw && inner.contains('"') { | ||
| return Err(malformed()); | ||
| } | ||
| Linkage::ALL.into_iter().find(|l| l.written() == inner).ok_or_else(|| LinkageRefused::Unknown { written: inner.into() }) |
There was a problem hiding this comment.
Decode linkage string literals before matching
When #[linkage] uses a valid escaped string such as #[linkage = "\x77eak"], Rust parses the literal value as weak, but this code compares the unescaped source text directly against the linkage names and returns Unknown. This rejects programs accepted by the pinned compiler—and on wasm64 prevents the intended weak-definition resolution—so parse the string literal with the normal literal decoder before matching it.
AGENTS.md reference: AGENTS.md:L116-L120
Useful? React with 👍 / 👎.
| if kind == RowKind::Static | ||
| && let Some(winner_item) = find_weak_override(weak_static_overrides.as_slice(), tabled) | ||
| .or_else(|| find_local_weak_override(maker, tabled, true, rust_exports.as_slice(), alloc)) |
There was a problem hiding this comment.
Apply weak overrides to thread-local statics
When a wasm64 target enables atomics, static_attrs_of preserves #[thread_local] statics as TLS, and the worklist consequently reaches a weak exported definition as RowKind::ThreadLocal. Although collection records it in weak_static_overrides, this branch only handles RowKind::Static and then hardcodes static_symbol plus a Static winner, so a direct Rust access emits the weak TLS datum while the same-symbol strong TLS definition may never be rooted. Resolve this case with tls_symbol/RowKind::ThreadLocal, or refuse weak thread-local definitions until that binding is supported.
AGENTS.md reference: AGENTS.md:L116-L120
Useful? React with 👍 / 👎.
1. Add export-only `nested_exports::walk_in_body_exports` skipping unrelated unreadable `extern` blocks (e.g. foreign types or unwritten-block macros) and unreadable sibling items, and propagate scan errors in `collect_rust_c_exports` instead of swallowing failures with `if let Ok`. 2. Lazily initialize the maker's `LazyProgram` and locate enclosing bodies via `Maker::local_weak_export_text` / `LazyProgram::local_weak_export_text` (reading `store.locals.head`) so a written-block or post-macro block-local weak root resolves its override even as the very first root on a fresh Maker. 3. Decode string-literal escapes in `front2::program::parse_linkage` through `blaze_expand::attr_literal` (the single attribute-literal reader) so valid escaped literals like `#[linkage = "\x77eak"]` match as in Rust. 4. Honestly refuse `#[thread_local]` + `#[linkage = "weak"]` in `statics::static_attrs_of` (and never alias `#[thread_local]` statics as weak overrides in `run/wasm64.rs`), even on `wasm64`.
|
Addressed all 4 Codex R3 findings in
Verification:
Codex (@codex) review |
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "Codex (@codex) address that feedback". |
Summary
Fixes two high-impact Linux
front2regressions uncovered onorigin/main(74c13a89b):1.
#[linkage]regression from7416f35a3+compiler_builtins::roundonwasm64blaze_lowerstoresAttr { meta: AttrMeta::KeyValue, args }withargsalready stripped of the leading=(just the value expression, e.g."extern_weak", while#[linkage("weak")]isAttrMeta::Tokensand#[linkage]isAttrMeta::Path).7416f35a3(committed uncompiled) requiredargs.trim().strip_prefix('='), causing every real#[linkage = ".."]attribute (includingstd's__dso_handleandstatx, pluslinkage_tests::a_fn_s_linkage_is_read_by_symbols_ofitself) to fail withLinkageRefused::Malformed.compiler_builtins::roundonwasm64):library/compiler-builtins/compiler-builtins/src/macros.rs:432emits#[unsafe(no_mangle)] #[cfg_attr(not(any(all(windows, target_env = "gnu"), target_os = "cygwin")), linkage = "weak")]on every intrinsic wrapper (includingmath::full_availability::round::round), sowasm64-blaze-wasip1proc-macros callingf64::round->core::num::imp::libm::roundhit#[linkage = "weak"]whenrun/wasm64.rslinkedcompiler_builtins::round.#[linkage]parsing intoparse_linkage(AttrMeta, &str)+linkage_of_for(AttrMeta, &str, is_wasm)incrates/blaze-ladder/src/front2/program.rsand wired all four readers (program.rs,statics.rs,export_shim.rs,run/wasm64.rs) through it (one home, Rule 30).Linkage::Weakhonestly refused on native targets (preserving7416f35a3/ Rule 3 whereblaze-exportwritesSTB_GLOBAL/N_EXT).Linkage::Weakontarget_family = "wasm":run/wasm64.rs's closed-world module linker now recordsweak: boolonRustCExportand sorts strong definitions ahead of weak ones so strong overrides weak and weak fallbacks (compiler_builtins::round,std::sys::pal::wasi::cabi_realloc, etc.) resolve internally.2. Cached / in-body foreign statics (
std::sys::env::unix::environ)LazyProgram::make_static_value(crates/blaze-ladder/src/front2/program/lazy/fill.rs) bypassedforeign_static_symboland unconditionally calledstatics::one_static(constant evaluation). On warm cached-record verification (make_one.rshandlingReadKind::Staticforstd::sys::env::unix::environ's in-bodyunsafe extern "C" { static mut environ: *const *const c_char; }),make_static_valueattempted to constant-evaluateenvironas a Rust static and failed withBodyError::NoBody(its text has no body).make_one.rsalso did not prepareReadKind::ForeignStaticrows orDataTarget::Staticforeign relocations instatic_over, andnested_exports::walk_everydid not recordNestedKind::ExternBlockitems intoWalk::localsfor unhinted coldlocate_local.statics::foreign_static_of(allocator-explicit, zeroGlobal/Box<str>signature additions) shared bystatics::static_values,LazyProgram::make_static_value, andLazyProgram::ensure_foreign_static.ReadKind::ForeignStaticalongsideReadKind::Staticinmake_one.rsand ensured foreignDataTarget::Statictargets instatic_over.NestedKind::ExternBlockdeclarations innested_exports::walk_every.Verification
cargo test -p blaze-ladder --lib linkage_tests: 5 passed, 0 failed (restoreda_fn_s_linkage_is_read_by_symbols_of, added malformed/unknown +target_family = "wasm"compiler_builtins::roundtests)cargo test -p blaze-ladder --test local_statics cold_typed_record_foreign_statics: 1 passed, 0 failedcargo test -p blaze-ladder --test local_statics warm_cached_walk: 1 passed, 0 failed (covers in-bodyenviron, in-bodyextern_weak__dso_handle, macro-expandedstatx, top-levelextern_weak, and Ruststatic LOCAL_VALcontrol across cold + warm cached walks with 0 re-makes)cargo test -p blaze-ladder --test wasm64_rust_e2e: 6 passed, 0 failed (includesweak_definition_resolves_fallback_and_yields_to_strong_on_wasm64)cargo test -p blaze-ladder --test front_equal_rules: 37 passed, 0 failedcargo test -p blaze-ladder --test front2_f128_routines: 2 passed, 0 failedorigin/main(blaze-ladder):stops1199->1199 (0),casts1258->1258 (0),clones61->60 (-1),allocsGlobal 558->558 / signatures 227->227 (0),ambientstd 286->286 / alloc 0->0 / vec_box 1375->1373 (-2),dups671->671 (0),homes/domains/rustcsites0 new sites.git merge-tree --write-tree origin/main HEAD: clean (b484a996523735e320e7fa59f6436ecfa138cb59).