Xpersona
F

Ffi Code Review

CLAWHUB · Unverified

Reviews Rust FFI code for type safety, memory layout compatibility, string handling, callback patterns, and unsafe boundary correctness. Use when reviewing e... Skill: Ffi Code Review Owner: anderskev Summary: Reviews Rust FFI code for type safety, memory layout compatibility, string handling, callback patterns, and unsafe boundary correctness. Use when reviewing e... Tags: latest:1.0.3 Version history: v1.0.3 | 2026-06-01T02:25:58.654Z | auto - Updated Gate 4 to reference the $1 skill instead of a specific protocol name. - Removed obsolete file: skill-card.md. - No changes

62
Rank
84
Safety
1.1k
Downloads

About

What it does, and when to use it.

Capability contract not published. No trust telemetry is available yet. 1.1K downloads reported by the source. Last updated 10/11/2026.

Avoid when

  • Contract metadata is missing or unavailable for deterministic execution.

Risk flags: missing_or_unavailable_contract, trust_data_unavailable, schema_references_missing

Install and run

Setup complexity: low.

clawhub skill install s17b1fzefm8nj8j1sdkzrze7gn83pfrg:ffi-code-review
  1. Setup complexity is LOW. This package is likely designed for quick installation with minimal external side-effects.
  2. Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data.

Contract: missing

curl -s "https://www.xpersona.co/api/v1/agents/clawhub-anderskev-ffi-code-review/snapshot"

Run-check

$0.02 USD

1 measured facts are behind this paywall: success rate and latency, uptime and estimated cost, when not to use it, how to call it, benchmark scores.

Agents pay $0.02 in USDC. A card payment is $0.50, the smallest a card allows.

Documentation

CLAWHUB

123,458 characters of source documentation, loaded on request.

Extracted files

5 files captured from the source.

SKILL.md

---
name: ffi-code-review
description: "Reviews Rust FFI code for type safety, memory layout compatibility, string handling, callback patterns, and unsafe boundary correctness. Use when reviewing extern blocks, #[repr(C)] types, bindgen output, or code calling C/C++ libraries."
---

# FFI Code Review

## Review Workflow

1. **Check Cargo.toml** -- Note Rust edition (2024 has breaking changes to extern blocks and unsafe attributes), `build-dependencies` (bindgen, cc, pkg-config), `crate-type` (`cdylib`, `staticlib`), and `links` key
2. **Check build.rs** -- Verify link directives (`cargo:rustc-link-lib`, `cargo:rustc-link-search`), bindgen configuration, and C source compilation
3. **Check extern blocks** -- Verify calling conventions, symbol declarations, and safety annotations
4. **Check type layout** -- Every type crossing FFI must be `#[repr(C)]` or a primitive FFI type
5. **Check string and pointer handling** -- CStr/CString usage, null checks, ownership transfers
6. **Check callbacks** -- `extern "C" fn` pointers, panic safety across FFI boundary
7. **Gates** -- Complete **Gates** below before reporting; do not skip ahead on “internal verification”

## Gates

Complete in order. **Do not emit findings** until **Gate 4** passes for each issue.

**Gate 1 — Crate context (on disk)**  
**PASS when:** You opened the reviewed crate’s `Cargo.toml` (workspace member path if applicable) and recorded `edition =`, plus any of `links`, `crate-type`, or `build-dependencies` that matter for this FFI.  
**Blocks rationalization:** Edition-specific findings (`unsafe extern "C" {}`, `#[unsafe(no_mangle)]`, etc.) require this — if `edition` is not 2024, do not flag 2024-only requirements.

**Gate 2 — Linkage and binding sources**  
**PASS when:** If the crate links native code or uses bindgen/pkg-config, you opened `build.rs` (or the checked-in bindings entry point). If there is no `build.rs`, you stated that bindings are hand-written and reviewed those `extern` / `include!` sites.  
**Artifact:** At least one path you opened (e.g. `build.rs`, `src/ffi.rs`, or `OUT_DIR` bindings via `include!`).

**Gate 3 — Code evidence**  
**PASS when:** Every planned finding has a target `[FILE:LINE]` from a full function/block you read, not only diff hunks or partial snippets.

**Gate 4 — Pre-report protocol**  
**PASS when:** You loaded and applied the [review-verification-protocol](../review-verification-protocol/SKILL.md) skill, including **FFI-Specific Verification** for `repr(C)`, safety comments, ownership/callbacks, or bindgen-heavy code.

## Output Format

Report findings as:

```text
[FILE:LINE] ISSUE_TITLE
Severity: Critical | Major | Minor | Informational
Description of the issue and why it matters.
```

## Quick Reference

| Issue Type | Reference |
|------------|-----------|
| C-to-Rust type mapping, repr(C) layout, enums, opaque types | [references/type-mapping.md](references/type-mapping.md) |
| Safe wrappers, ownership transfer, callbacks, build.rs, testing

_meta.json

{
  "ownerId": "kn79190nfmdb20hk6xjhzt2zv583844x",
  "slug": "ffi-code-review",
  "version": "1.0.3",
  "publishedAt": 1780280758654
}

references/safety-patterns.md

# Safety Patterns

## Wrapping Unsafe FFI in Safe Rust

The goal of FFI bindings is a safe public API built on unsafe internals. The safe wrapper must enforce all invariants that the C library documents.

```rust
// Raw FFI (typically in a -sys crate)
unsafe extern "C" {
    fn widget_create() -> *mut Widget;
    fn widget_set_name(w: *mut Widget, name: *const c_char) -> c_int;
    fn widget_destroy(w: *mut Widget);
}

// Safe wrapper
pub struct Widget {
    ptr: NonNull<ffi::Widget>,
}

impl Widget {
    pub fn new() -> Result<Self, Error> {
        // SAFETY: widget_create returns null on failure, valid pointer otherwise
        let ptr = unsafe { ffi::widget_create() };
        NonNull::new(ptr).map(|p| Widget { ptr: p }).ok_or(Error::CreateFailed)
    }

    pub fn set_name(&mut self, name: &str) -> Result<(), Error> {
        let c_name = CString::new(name)?;
        // SAFETY: self.ptr is valid (maintained by construction),
        // c_name is null-terminated and lives through this call
        let ret = unsafe { ffi::widget_set_name(self.ptr.as_ptr(), c_name.as_ptr()) };
        if ret == 0 { Ok(()) } else { Err(Error::SetNameFailed) }
    }
}

impl Drop for Widget {
    fn drop(&mut self) {
        // SAFETY: self.ptr was allocated by widget_create
        // and has not been freed (we own it)
        unsafe { ffi::widget_destroy(self.ptr.as_ptr()) }
    }
}
```

### Key principles for safe wrappers:
- Capture `&` vs `&mut` accurately -- if C mutates behind a pointer, take `&mut self`
- Use Rust lifetimes to enforce C's lifetime requirements (e.g., `Device<'ctx>` borrows `Context`)
- Do not implement `Send`/`Sync` unless the C library documents thread safety
- Use `PhantomData<*const ()>` to suppress auto-`Send`/`Sync` for thread-unsafe types

## Ownership Transfer Patterns

### Rust-to-C (giving ownership)

```rust
// Give C a heap-allocated Rust object
#[unsafe(no_mangle)]
pub extern "C" fn create_config() -> *mut Config {
    Box::into_raw(Box::new(Config::default()))
}

// C must call this to free -- never free with C's free()
#[unsafe(no_mangle)]
pub extern "C" fn destroy_config(ptr: *mut Config) {
    if ptr.is_null() { return; }
    // SAFETY: ptr was created by create_config via Box::into_raw
    // and has not been freed yet (caller contract)
    unsafe { drop(Box::from_raw(ptr)) }
}
```

### C-to-Rust (borrowing C memory)

```rust
// C owns the buffer, Rust borrows it
pub fn process_buffer(ptr: *const u8, len: usize) -> Result<(), Error> {
    if ptr.is_null() { return Err(Error::NullPointer); }
    // SAFETY: caller guarantees ptr is valid for len bytes
    // and the memory won't be freed during this call
    let slice = unsafe { std::slice::from_raw_parts(ptr, len) };
    // ... use slice ...
    Ok(())
}
```

### The Golden Rule
Rust-allocated memory must be freed by Rust. C-allocated memory must be freed by C. Never mix allocators.

## CString Lifetime Pitfall

The most common FFI bug: dropping a `CString` while C still ho

references/type-mapping.md

# Type Mapping

## C-to-Rust Primitive Type Table

Always use `std::ffi` or `std::os::raw` types for C interop. Never assume `int` is `i32` on all platforms.

| C Type | Rust Type | Notes |
|--------|-----------|-------|
| `int` | `c_int` | Platform-dependent width |
| `unsigned int` | `c_uint` | Platform-dependent width |
| `char` | `c_char` | Signed or unsigned depending on platform |
| `short` | `c_short` | |
| `long` | `c_long` | 32-bit on Windows, 64-bit on LP64 Unix |
| `long long` | `c_longlong` | |
| `float` | `c_float` / `f32` | |
| `double` | `c_double` / `f64` | |
| `size_t` | `usize` | |
| `ssize_t` | `isize` | |
| `void` | `()` (return) / `c_void` (pointer) | |
| `void*` | `*mut c_void` | |
| `const void*` | `*const c_void` | |
| `char*` | `*mut c_char` | |
| `const char*` | `*const c_char` | |
| `bool` / `_Bool` | `bool` | Only with `#[repr(C)]`; C99+ |
| `int8_t` | `i8` | Fixed-width, always safe |
| `uint8_t` | `u8` | Fixed-width, always safe |
| `int32_t` | `i32` | Fixed-width, always safe |
| `uint64_t` | `u64` | Fixed-width, always safe |
| `__be32` | `[u8; 4]` | Big-endian; don't use `i32` |

## String Types

```rust
use std::ffi::{CStr, CString, c_char};

// Borrowing a C string (incoming from C, null-terminated)
// SAFETY: ptr is a valid null-terminated C string
let c_str: &CStr = unsafe { CStr::from_ptr(ptr) };
let rust_str: &str = c_str.to_str()?; // Fails if not UTF-8

// Creating a C string to pass to C
let c_string = CString::new("hello")?; // Err if contains \0
let ptr: *const c_char = c_string.as_ptr();
// c_string MUST outlive ptr -- dropping c_string invalidates ptr
```

For OS-native paths, use `OsStr`/`OsString` which handle platform encoding.

## Struct Layout with repr(C)

`#[repr(C)]` guarantees field ordering, padding, and alignment match the C ABI.

```rust
// C definition:
// struct Point { int32_t x; int32_t y; };

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

// C definition with padding:
// struct Mixed { char tag; int32_t value; };
// Has 3 bytes of padding between tag and value

#[repr(C)]
pub struct Mixed {
    pub tag: c_char,
    // 3 bytes padding inserted by repr(C) to align value
    pub value: i32,
}
```

### Size and Alignment Verification

Always verify layout matches at compile time or in tests:

```rust
// Compile-time assertions
const _: () = assert!(std::mem::size_of::<Point>() == 8);
const _: () = assert!(std::mem::align_of::<Point>() == 4);

// In tests, compare against C sizeof/alignof if available
#[test]
fn layout_matches_c() {
    assert_eq!(std::mem::size_of::<Mixed>(), 8); // 1 + 3pad + 4
    assert_eq!(std::mem::align_of::<Mixed>(), 4);
}
```

## Enum Representation

### Fieldless Enums (C-style)

```rust
// Maps to: enum Status { OK = 0, ERR = 1, BUSY = 2 };
#[repr(C)]
pub enum Status {
    Ok = 0,
    Err = 1,
    Busy = 2,
}
```

Use `#[repr(u32)]` or `#[repr(i32)]` when C specifies an exact underlying type.

### Bitflag Enums -- Do NOT Use Rust Enums

C enums

skill-card.md

## Description:

Reviews Rust FFI code for type safety, memory layout compatibility, string handling, callback patterns, and unsafe boundary correctness.

This skill is ready for commercial/non-commercial use.

## Publisher:

[anderskev](https://clawhub.ai/user/anderskev)

### License/Terms of Use:

MIT-0

## Use Case:

Developers and code reviewers use this skill to review Rust FFI boundaries, including extern declarations, repr(C) layout, C string and pointer ownership, callback safety, bindgen output, and build/linkage configuration.

### Deployment Geography for Use:

Global

## Known Risks and Mitigations:

Risk: The skill may over-apply edition-specific Rust FFI rules if the reviewed crate edition is not checked first.

Mitigation: Follow Gate 1 by opening Cargo.toml and recording the crate edition before reporting edition-specific issues.

Risk: FFI findings can be inaccurate when based only on partial diffs or isolated snippets.

Mitigation: Follow Gate 3 by reading the full relevant function or block and citing a concrete file and line for each finding.

## Reference(s):

- [ClawHub Skill Page](https://clawhub.ai/anderskev/skills/ffi-code-review)
- [Type Mapping](references/type-mapping.md)
- [Safety Patterns](references/safety-patterns.md)

## Skill Output:

**Output Type(s):** [text, markdown, guidance]

**Output Format:** [Markdown review findings with file-line citations and severity labels]

**Output Parameters:** [1D]

**Other Properties Related to Output:** [Findings are gated on crate context, linkage and binding sources, and full code evidence before reporting.]

## Skill Version(s):

1.0.3 (source: server release evidence)

## Ethical Considerations:

Users should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment.

Sponsored

Ads related to Ffi Code Review and adjacent AI workflows.