rust-lang / rust-lang/rust-clippy

Lint against `#[no_mangle]` for non-`repr(C)` `pub static`s

Open
#11,219 6 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint G-Rust-for-Linux
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

What it does

The lint should lint against a #[no_mangle] pub static which has a type which is not repr(C) (or that has no explicit repr(Rust) set).

This would be similar to no_mangle_with_rust_abi from https://github.com/rust-lang/rust-clippy/issues/10347, but for pub statics.

Advantage

Avoids potential subtle mistakes and UB in programs that mix Rust and other languages like C: one cannot predict the layout of repr(Rust) types and thus an exported static marked with #[no_mangle] has a high chance of being a mistake.

Drawbacks

No response

Example
pub struct S(u8, u16);

#[no_mangle]
pub static X: S = S(0xFF, 0xFFFF);

Should be written as:

#[repr(C)]
pub struct S(u8, u16);

#[no_mangle]
pub static X: S = S(0xFF, 0xFFFF);

Otherwise, a C program with manually written bindings (e.g. projects not using cbindgen, which in this case would generate an incomplete type) trying to access X will break sooner or later, potentially silently (using -Zrandomize-layout would increase the chances of the issue being spotted, though), e.g.

#include <assert.h>
#include <stdint.h>

struct S {
    uint8_t a;
    uint16_t b;
};

extern const struct S X;

int main(void) {
    assert(X.a == 0xFF);
    assert(X.b == 0xFFFF);
    return 0;
}

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 by comparing the requested behavior with the related no_mangle_with_rust_abi lint referenced in the issue. Define coverage for #[no_mangle] public statics whose types lack an explicit repr(C), and use the provided Rust examples to verify that the lint catches the unsafe case without rejecting the corrected form.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.