MCPInstall

rust-unsafe-ffi

Design, implement, audit, and test unsafe Rust and foreign-function boundaries, including raw pointers, validity and aliasing invariants, MaybeUninit, layout, Pin, manual Send and Sync, allocators, C ABI declarations, callbacks, ownership transfer, unwinding, and Edition 2024 unsafe syntax. Use when safe Rust cannot express the required memory or ABI operation; require minimal unsafe blocks, explicit safety contracts, safe wrappers, Miri where applicable, and real platform integration tests.

Installs
111
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/full-stack-skills/rust-skills --skill rust-unsafe-ffi
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads rust-unsafe-ffi automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

Rust Unsafe and FFI

Treat unsafe as a proof obligation. An unsafe block permits specific operations; it does not relax validity, aliasing, initialization, lifetime, data-race, layout, or ABI requirements.

Scope and Routing

Use this skill for raw pointers, NonNull, unsafe functions and traits, unions, MaybeUninit, ManuallyDrop, layout, pinning, allocators, manual Send or Sync, C ABI bindings, callbacks, handles, and ownership transfer.

Route ordinary ownership design to rust-stable, concurrent architecture to rust-concurrency, UniFFI-generated multi-language bindings to rust-uniffi-building, general build scripts to rust-cargo-build, and review reporting to rust-code-review.

Workflow

1. Justify and isolate unsafe operations

Identify the operation safe Rust cannot express. Prefer an audited crate or standard-library abstraction when it preserves the required behavior. Keep unsafe blocks small and enable:

#![deny(unsafe_op_in_unsafe_fn)]

An unsafe fn must still place each unsafe operation in an explicit unsafe {} block. Expose a safe wrapper only when it can establish and preserve every invariant internally.

2. Write the safety contract before code

Document:

  • pointer provenance, non-nullness, alignment, and dereferenceable byte range;
  • initialization and validity requirements for the pointee type;
  • aliasing and mutation rules for the full access duration;
  • lifetime and ownership transfer, including who destroys or frees values;
  • thread-safety and reentrancy requirements;
  • ABI, layout, calling convention, integer width, and error conventions;
  • panic or foreign-exception behavior across the boundary.

Use # Safety documentation for unsafe public APIs and // SAFETY: comments at proof sites.

3. Implement raw-memory operations conservatively

pub unsafe fn read_i32(ptr: *const i32) -> i32 {
    // SAFETY: The caller guarantees that ptr is aligned, initialized,
    // dereferenceable for one i32, and not concurrently mutated.
    unsafe { ptr.read() }
}
  • Use ptr.add only within the same allocated object or one-past it.
  • Distinguish aligned and unaligned reads; never create a reference to an unaligned packed field.
  • Use MaybeUninit<T> while values may be uninitialized, and track exactly which elements were initialized before drop or assume_init.
  • Prefer from_ne_bytes, pointer casts with checked layout, or explicit field conversion over transmute.
  • Do not use ManuallyDrop to hide ownership ambiguity or double-drop risk.

4. Define layout and pinning precisely

  • Use #[repr(C)] for C-compatible struct layout and explicit reprs for shared enums.
  • Use #[repr(transparent)] only when its documented field restrictions hold.
  • Treat padding as potentially uninitialized; do not serialize a struct by copying its raw bytes.
  • Pin<P> protects the pointee only under the pinning contract. It does not make ordinary Unpin data immovable and does not by itself make a self-reference sound.
  • Prefer established projection helpers or structural pinning patterns over raw self-referential pointers.

5. Build a narrow FFI boundary

Edition 2024 requires unsafe extern blocks and unsafe attributes where applicable:

use std::ffi::{c_char, CStr};

unsafe extern "C" {
    fn foreign_name() -> *const c_char;
}

pub fn name() -> Option<String> {
    // SAFETY: The foreign contract promises either null or a valid,
    // NUL-terminated string that remains alive for this call.
    let ptr = unsafe { foreign_name() };
    (!ptr.is_null()).then(|| {
        // SAFETY: Non-nullness and termination follow from the contract above.
        unsafe { CStr::from_ptr(ptr) }.to_string_lossy().into_owned()
    })
}
  • Use std::ffi C types or generated bindings, not assumed Rust integer widths.
  • Convert nullable pointers, lengths, ownership, and error codes at one boundary.
  • Prevent unwinding across a C ABI unless the selected ABI explicitly permits it; catch panics at callbacks when necessary.
  • Make callback lifetime, thread, cancellation, and unregister behavior explicit.
  • Pair allocation and deallocation in the same allocator domain.

6. Verify the proof

Run applicable gates:

cargo fmt --all --check
cargo check --workspace --all-targets --all-features
cargo test --workspace --all-targets --all-features
cargo clippy --workspace --all-targets --all-features -- -D warnings
cargo miri test

Also use sanitizers or Valgrind where supported, ABI layout assertions, C-side integration tests, multiple optimization levels, and every supported operating system and architecture. Miri does not execute arbitrary foreign code, so isolate or mock the external call while testing the Rust-side memory contract.

Read Unsafe and FFI Reference for memory-type details. Read Execution Scenarios for representative boundaries.

Review Checklist

  • Is unsafe necessary, minimal, and locally justified?
  • Does each safety contract cover validity, aliasing, lifetime, layout, and concurrency?
  • Can a safe caller violate the wrapper's assumptions?
  • Are partial initialization and failure cleanup correct?
  • Are ownership and deallocation symmetric across FFI?
  • Can panic or foreign unwinding cross the ABI boundary?
  • Are manual Send and Sync implementations proven for every field and callback?
  • Do tests exercise null, empty, maximum, misaligned, error, callback, and shutdown paths?

Completion Criteria

  • Document every caller and implementation safety obligation.
  • Keep unsafe blocks minimal and safe wrappers impossible to misuse from safe Rust.
  • Verify ABI types, layout, ownership, error, and unwinding behavior.
  • Run Miri where applicable and real platform tests for the external boundary.
  • Record any property that could not be verified locally.

Upstream Sources

Data Privacy

This skill does not collect, store, or transmit user data. Do not send proprietary headers, generated bindings, crash dumps, or memory contents to external services without authorization.

FAQ

What does the rust-unsafe-ffi skill do?

Design, implement, audit, and test unsafe Rust and foreign-function boundaries, including raw pointers, validity and aliasing invariants, MaybeUninit, layout, Pin, manual Send and Sync, allocators, C ABI declarations, callbacks, ownership transfer, unwinding, and Edition 2024 unsafe syntax. Use when safe Rust cannot express the required memory or ABI operation; require minimal unsafe blocks, explicit safety contracts, safe wrappers, Miri where applicable, and real platform integration tests.

How do I install rust-unsafe-ffi?

Run npx skills add https://github.com/full-stack-skills/rust-skills --skill rust-unsafe-ffi in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/rust-unsafe-ffi/ (personal) or .claude/skills/rust-unsafe-ffi/ (project).

Which AI agents can use rust-unsafe-ffi?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is rust-unsafe-ffi safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains rust-unsafe-ffi?

It is published by full-stack-skills in full-stack-skills/rust-skills. It has 111 recorded installs.

More from full-stack-skills/rust-skills

View all →

rust-testing

full-stack-skills/rust-skills

Design, implement, and validate Rust tests, including unit, integration, doctest, compile-fail, property, fuzz, benchmark, coverage, async, concurrency, process, daemon, IPC, terminal, platform, and hardware-facing test strategies. Use when users ask for Rust test architecture, flaky-test diagnosis, coverage gates, benchmarks, trybuild, cargo-nextest, real-process tests, or failure-path verification.

Testing & QA148 installs

rust-style-clippy

full-stack-skills/rust-skills

Apply and diagnose Rust style, rustfmt, Clippy, compiler diagnostics, Edition migrations, lint policy, idiomatic control flow, error handling, allocation behavior, production Rust conventions, and the Rust API Guidelines ↔ Clippy lint mapping. Use when users ask to format or lint Rust, fix warning or error codes, migrate editions, review unwrap or clone usage, improve idioms, map a C- API guideline rule to the enforcing Clippy lint, or establish CI quality gates. Route API shape decisions (naming conventions, type/trait design, module layout, full C- guideline review) to the rust-api-design skill.

Backend & APIs137 installs

rust-concurrency

full-stack-skills/rust-skills

Design, implement, diagnose, and test Rust concurrency and parallelism with threads, Send and Sync, locks, atomics, channels, Tokio, Rayon, Crossbeam, bounded backpressure, actor ownership, task supervision, graceful shutdown, runtime diagnostics, and Loom model tests. Use when users ask about shared state, deadlocks, async tasks, CPU parallelism, high concurrency, daemon resource budgets, slow consumers, worker pools, lock-free structures, or concurrent correctness.

Backend & APIs137 installs

rust-performance

full-stack-skills/rust-skills

Measure, profile, optimize, and regression-test Rust performance across latency, throughput, CPU, allocations, memory, binary size, and compile time using representative workloads, Criterion, iai-callgrind, cargo-flamegraph, samply, DHAT, heap or pprof tools, cargo-bloat, cargo-llvm-lines, and build timings. Use when users report slow Rust code, high memory or CPU, large binaries, noisy benchmarks, tail-latency regressions, or need performance budgets and evidence-backed optimization.

Backend & APIs135 installs

rust-code-review

full-stack-skills/rust-skills

Review Rust changes for correctness, memory and thread safety, error semantics, unnecessary allocation or cloning, lock scope, API compatibility, test gaps, documentation, and dependency risk, applying the Rust API Guidelines checklist (C-PANIC, C-UNWRAP, C-TRANSMUTE, C-BOOL, C-NEWTYPE, C-COMMON-TRAITS, C-CONVERT, C-SEALED, C-NON-EXHAUSTIVE). Use when reviewing Rust diffs, pull requests, libraries, unsafe boundaries, or production incidents; report actionable findings by severity before summaries, route automated formatting or lint policy to rust-style-clippy, and route API shape decisions (trait sealing, error taxonomy, newtype design, builder patterns) to rust-api-design.

rust-cargo-build

full-stack-skills/rust-skills

Configure, operate, diagnose, and automate Cargo for Rust packages and workspaces. Cover manifests and targets, commands, dependency resolution and features, profiles, build scripts, configuration and environment variables, caches and build diagnostics, cross-compilation, registries, packaging, publishing, metadata, CI reproducibility, and stable-versus-nightly feature gates. Use for Cargo.toml, Cargo.lock, .cargo/config.toml, cargo build/check/run/tree/metadata/package/publish, resolver or feature problems, build output and performance, private registries, and beginner Cargo workflows. Route crate selection and supply-chain audits to rust-dependencies, workspace topology to rust-workspace, test design to rust-testing, documentation design to rust-documentation, lint policy to rust-style-clippy, and API compatibility decisions to rust-semver.

Backend & APIs123 installs

Popular backend & apis skills

View category →

find-skills

vercel-labs/skills

Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.

OfficialBackend & APIs4.1M installs

entra-app-registration

microsoft/azure-skills

Guides Microsoft Entra ID app registration, OAuth 2.0 authentication, and MSAL integration. USE FOR: create app registration, register Azure AD app, configure OAuth, set up authentication, add API permissions, generate service principal, MSAL example, console app auth, Entra ID setup, Azure AD authentication. DO NOT USE FOR: Key Vault secrets (use azure-keyvault-expiration-audit), general Azure resource security guidance.

OfficialBackend & APIs566.7K installs

This skill should be used when the user wants to "write agent code", "build an agent with ADK", "add a tool", "create a callback", "define an agent", "use state management" — in a project that needs ADK (Agent Development Kit) API patterns and code examples. It provides a quick reference for agent types, tool definitions, orchestration patterns, callbacks, state management, the graph Workflow API, and reference recipes to study. Do NOT use for scaffolding (use google-agents-cli-scaffold) or deployment (use google-agents-cli-deploy).

Backend & APIs514.8K installs

embedded-captions

heygen-com/hyperframes

Add captions or subtitles to an existing single-subject talking-head video without editing the footage. Use for plain verbatim captions, cinematic captions embedded behind the subject, VFX captions, “炸/特效/酷炫字幕,” or a named identity from the 35-style catalog. Route by visual identity, not by backend engine. The quiet anchor rail is the default; embed every word only when the user explicitly wants a fully cinematic treatment. The workflow runs locally end to end, including transcription and subject matting; split multi-shot footage before applying it.

Backend & APIs453.3K installs

entra-agent-id

microsoft/azure-skills

Provision Microsoft Entra Agent Identity Blueprints, BlueprintPrincipals, and per-instance Agent Identities via Microsoft Graph, and configure OAuth 2.0 token exchange (fmipath, OBO, cross-tenant) including the Microsoft Entra SDK for AgentID sidecar. USE FOR: Agent Identity Blueprint, BlueprintPrincipal, agent OAuth, fmipath token exchange, agent OBO, Workload Identity Federation for agents, polyglot agent auth, Microsoft.Identity.Web.AgentIdentities. DO NOT USE FOR: standard Entra app registration (use entra-app-registration), Microsoft Foundry agent authoring (use microsoft-foundry).

OfficialBackend & APIs336.6K installs

neon

neondatabase/agent-skills

Overview of Neon, a complete set of cloud backend primitives around Lakebase Postgres: Auth, Object Storage, Functions, the AI Gateway, and Realtime. Start here to choose Neon for undecided login, files, APIs, and LLM calls, set up the CLI or MCP server, and follow the branch-first workflow. Use when building an app or backend on Neon, or when "Neon" or "Lakebase Postgres" is mentioned. Child skill neon-postgres wins for an existing DATABASEURL, SQL, schema, inspect, or search. Child skill neon-auth wins for login, users, sessions, identity routing, and Managed Better Auth setup. Child skill neon-realtime wins for live queries in reactive apps and agents. Also use for object storage, S3, buckets, serverless functions, function triggers, cron, AI gateway, LLM calls, realtime, logs, Loki, Grafana, observability, postgres, database, backend, Claimable Neon, neon.new, or a no-signup database.

Backend & APIs237.1K installs