rust-lang / rust-lang/rust

Wrong expansion of `extern "C" u8/u16` returns on bpfel

Open
#158,028 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-ABI C-bug O-eBPF S-needs-info T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

bpf.rs

#![feature(no_core, lang_items, auto_traits)]
#![no_core]
#![allow(internal_features)]
#![crate_type = "lib"]

#[lang = "copy"] trait Copy {}
#[lang = "pointee_sized"] pub trait PointeeSized {}
#[lang = "meta_sized"] pub trait MetaSized: PointeeSized {}
#[lang = "sized"] pub trait Sized: MetaSized {}
#[lang = "freeze"] auto trait Freeze {}
#[lang = "drop_glue"] fn drop_glue<T>(_: &mut T) {}

unsafe extern "C" {
    fn c_read_value(x: u32) -> u16;
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn observe(x: u32) -> u64 {
    unsafe { c_read_value(x) as u64 }
}
RUSTC_BOOTSTRAP=1 rustc +nightly-2026-05-10 --target bpfel-unknown-none -C opt-level=2 --emit=asm,llvm-ir --out-dir . bpf.rs

sed -n '/^observe:/,/^\.Lfunc_end/p' bpf.s

This prints:

observe:
   call c_read_value
   exit
.Lfunc_end0:

On BPF the returned value is r0. There is no r0 &= 65535 between call and exit, so if c_read_value leaves r0 = 0x12340016, observe returns 0x12340016 instead of 0x0000000000000016

EDIT: That's the root cause. This zeroext so that LLVM believes the upper bits are already zeroed, so it doesn't emits r0 &= 65535 and doesn't return the correct value

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the bpf.rs reproducer and its emitted assembly, then read compiler/rustc_target/src/callconv/bpf.rs at the cited lines to understand the zero-extension assumption. Verify the fix by compiling the example for bpfel and checking that observe masks the u16 return before exit, producing 0x0000000000000016.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Clearly specified
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.