Token导航 LogoToken导航TokenDH.com
前端设计需要联网github未标认证来源可访问许可证需确认审计通过

rust-unsafeRust unsafe 命令行

Agent Skill

rust-unsafe 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

250

周安装

10

GitHub Stars

29

下载量

81
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:rust-unsafe(Rust unsafe 命令行)
来源仓库:https://github.com/huiali/rust-skills
仓库路径:skills/rust-unsafe
安装命令:
npx skills add https://github.com/huiali/rust-skills --skill rust-unsafe
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/huiali/rust-skills --skill rust-unsafe

简介

rust-unsafe 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息。

  • 适合在 Codex、Claude、Cursor、Gemini CLI 中使用 unsafe 代码时提供参考与支持。
  • 支持指针操作、FFI 边界与内存安全的权衡分析。
  • 安装前建议确认权限范围、维护状态及是否会触发代码检查或警告生成。
  • 可结合来源仓库和原始 README 继续核验具体用例与安全建议。

SKILL.md

When Unsafe is Justified

Use CaseExampleJustified?
FFI calls to Cextern "C" {fn libc_malloc(size: usize) -> *mut c_void;}✅ Yes
Low-level abstractionsInternal implementation of Vec, Arc✅ Yes
Performance optimization (measured)Hot path with proven bottleneck⚠️ Verify first
Escaping borrow checkerDon't know why you need it❌ No

SAFETY Comment Requirements

Every unsafe block must include a SAFETY comment:

// SAFETY: ptr must be non-null and properly aligned.
// This function is only called after a null check.
unsafe { *ptr = value; }

/// # Safety
///
/// * `ptr` must be properly aligned and not null
/// * `ptr` must point to initialized memory of type T
/// * The memory must not be accessed after this function returns
pub unsafe fn write(ptr: *mut T, value: &T) { ... }

Solution Patterns

Pattern 1: FFI with Safe Wrapper

use std::ffi::{CStr, CString};
use std::os::raw::c_char;

extern "C" {
    fn c_function(s: *const c_char) -> i32;
}

// ✅ Safe wrapper
pub fn safe_c_function(s: &str) -> Result<i32, Box<dyn Error>> {
    let c_str = CString::new(s)?;
    // SAFETY: c_str is a valid null-terminated string created from Rust data.
    // The pointer is valid for the duration of this call.
    let result = unsafe { c_function(c_str.as_ptr()) };
    Ok(result)
}

Pattern 2: Raw Pointer with Validation

use std::ptr::NonNull;

struct Buffer {
    ptr: NonNull<u8>,
    len: usize,
}

impl Buffer {
    pub fn write(&mut self, index: usize, value: u8) -> Result<(), String> {
        if index >= self.len {
            return Err("index out of bounds".to_string());
        }

        // SAFETY: We've checked index is within bounds.
        // ptr is NonNull and points to valid memory.
        unsafe {
            self.ptr.as_ptr().add(index).write(value);
        }
        Ok(())
    }
}

Pattern 3: Uninitialized Memory

use std::mem::MaybeUninit;

// ✅ Safe uninitialized memory handling
fn create_buffer(size: usize) -> Vec<u8> {
    let mut buffer: Vec<MaybeUninit<u8>> = Vec::with_capacity(size);

    for i in 0..size {
        buffer.push(MaybeUninit::new(0));
    }

    // SAFETY: All elements have been initialized to 0.
    unsafe { std::mem::transmute(buffer) }
}

// ❌ Avoid: deprecated pattern
fn bad_buffer(size: usize) -> Vec<u8> {
    let mut v = Vec::with_capacity(size);
    unsafe { v.set_len(size); }  // UB if not initialized!
    v
}

Pattern 4: Repr(C) for FFI

#[repr(C)]
pub struct Point {
    pub x: f64,
    pub y: f64,
}

#[repr(C)]
pub enum Status {
    Success = 0,
    Error = 1,
}

// SAFETY: Layout matches C struct exactly
extern "C" {
    fn process_point(p: *const Point) -> Status;
}

47 Unsafe Rules Reference

General Principles (3 rules)

RuleDescription
G-01Don't use unsafe to escape compiler safety checks
G-02Don't blindly use unsafe for performance
G-03Don't create "Unsafe" aliases for types/methods

Memory Layout (6 rules)

RuleDescription
M-01Choose appropriate memory layout for struct/tuple/enum
M-02Don't modify memory variables of other processes
M-03Don't let String/Vec auto-deallocate memory from other processes
M-04Prefer reentrant versions of C-API or syscalls
M-05Use third-party crates for bit fields
M-06Use MaybeUninit<T> for uninitialized memory

Raw Pointers (6 rules)

RuleDescription
P-01Don't share raw pointers across threads
P-02Prefer NonNull<T> over *mut T
P-03Use PhantomData<T> to mark variance and ownership
P-04Don't dereference pointers cast to misaligned types
P-05Don't manually convert immutable pointers to mutable
P-06Use ptr::cast instead of as for pointer casts

Unions (2 rules)

RuleDescription
U-01Avoid unions except for C interop
U-02Don't use union variants with different lifetimes

FFI (18 rules)

RuleDescription
F-01Avoid passing strings directly to C
F-02Carefully read std::ffi types documentation
F-03Implement Drop for wrapped C pointers
F-04Handle panics across FFI boundaries
F-05Use portable type aliases from std or libc
F-06Ensure C-ABI string compatibility
F-07Don't implement Drop for types passed to extern code
F-08Handle errors properly in FFI
F-09Use references instead of raw pointers in safe wrappers
F-10Exported functions must be thread-safe
F-11Be careful with references to repr(packed) fields
F-12Document invariant assumptions for C parameters
F-13Ensure consistent data layout for custom types
F-14FFI types should have stable layout
F-15Validate robustness of external values
F-16Separate data and code for C closures
F-17Use opaque types instead of c_void
F-18Avoid passing trait objects to C

Safe Abstractions (11 rules)

RuleDescription
S-01Be aware of memory safety issues from panics
S-02Unsafe code authors must verify safety invariants
S-03Don't expose uninitialized memory in public APIs
S-04Avoid double-free from panics
S-05Consider safety when manually implementing Auto Traits
S-06Don't expose raw pointers in public APIs
S-07Provide safe alternatives for performance
S-08Returning mutable reference from immutable parameter is wrong
S-09Add SAFETY comment before each unsafe block
S-10Add Safety section to public unsafe function docs
S-11Use assert! instead of debug_assert! in unsafe functions

I/O Safety (1 rule)

RuleDescription
I-01Ensure I/O safety when using raw handles

Workflow

Step 1: Question the Need

Do I really need unsafe?
  → Can I use safe abstractions?
  → Is this for FFI? (justified)
  → Is this for measured performance? (profile first)
  → Am I fighting the borrow checker? (redesign instead)

Step 2: Write SAFETY Comments

For every unsafe block:
1. Document preconditions
2. Explain why they hold
3. Reference invariants maintained

For public unsafe functions:
1. Add /// # Safety section
2. List all requirements
3. Document consequences of violations

Step 3: Validate with Tools

# Detect undefined behavior
cargo +nightly miri test

# Memory leak detection
valgrind ./target/release/program

# Data race detection
RUST_BACKTRACE=1 cargo test --features tsan

Step 4: Build Safe Wrappers

Raw unsafe code
  ↓
Safe private functions (validate inputs)
  ↓
Safe public API (no unsafe visible)

Common Errors and Fixes

ErrorFix
Null pointer dereferenceCheck for null before dereferencing
Use after freeEnsure lifetime validity
Data raceAdd synchronization
Alignment violationUse #[repr(C)], check alignment
Invalid bit patternUse MaybeUninit
Missing SAFETY commentAdd comment

Deprecated Patterns

DeprecatedModern Alternative
mem::uninitialized()MaybeUninit<T>
mem::zeroed() (for reference types)MaybeUninit<T>
Raw pointer arithmeticNonNull<T>, ptr::add
CString::new().unwrap().as_ptr()Store CString first
static mutAtomicT or Mutex
Manual extern declarationsbindgen

FFI Tools

DirectionTool
C → Rustbindgen
Rust → Ccbindgen
PythonPyO3
Node.jsnapi-rs
C++cxx

Review Checklist

When reviewing unsafe code:

  • Unsafe usage is justified (FFI, low-level abstraction, measured perf)
  • Every unsafe block has SAFETY comment
  • Public unsafe functions document Safety requirements
  • Raw pointers are validated before dereferencing
  • No raw pointer sharing across threads without sync
  • FFI boundaries properly handle panics
  • Memory layout explicitly specified for FFI types
  • Uninitialized memory uses MaybeUninit
  • Safe public API wraps unsafe internals
  • Tested with Miri for undefined behavior

Verification Commands

# Check for undefined behavior
cargo +nightly miri test

# Run with address sanitizer
RUSTFLAGS="-Z sanitizer=address" cargo +nightly test

# Check FFI bindings
cargo check --features ffi

# Verify memory safety
valgrind --leak-check=full ./target/release/program

# Documentation check
cargo doc --no-deps --open

Common Pitfalls

1. Dangling Pointers

Symptom: Use-after-free, segfault

// ❌ Bad: pointer outlives data
fn bad() -> *const i32 {
    let x = 42;
    &x as *const i32  // Dangling!
}

// ✅ Good: proper lifetime management
fn good(x: &i32) -> *const i32 {
    x as *const i32  // Lifetime tied to input
}

2. Uninitialized Memory

Symptom: Undefined behavior, random values

// ❌ Bad: reading uninitialized memory
let x: i32;
unsafe { println!("{}", x); }  // UB!

// ✅ Good: use MaybeUninit
let mut x = MaybeUninit::<i32>::uninit();
x.write(42);
let x = unsafe { x.assume_init() };  // Safe

3. Invalid Repr

Symptom: FFI crashes, data corruption

// ❌ Bad: default repr with FFI
struct Point { x: f64, y: f64 }
extern "C" { fn use_point(p: Point); }

// ✅ Good: explicit C layout
#[repr(C)]
struct Point { x: f64, y: f64 }
extern "C" { fn use_point(p: Point); }

Related Skills

  • rust-ownership - Lifetime and borrowing fundamentals
  • rust-ffi - Advanced FFI patterns
  • rust-performance - When unsafe optimization is justified
  • rust-coding - SAFETY comment conventions
  • rust-concurrency - Thread-safe unsafe patterns

Localized Reference

  • Chinese version: SKILL_ZH.md - 完整中文版本,包含所有内容

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

35.06%
按下载量换算28

Claude

28.06%
按下载量换算23

Cursor

18.27%
按下载量换算15

Gemini CLI

8.87%
按下载量换算7

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills