Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

memory-safe-c-cpp

БесплатноБез исполняемых скриптовНе проверен

Memory-safe C and C++ skill for hardening existing code without a rewrite. Use when choosing between -fhardened, FORTIFY, bounds annotations, library…

mohitmishra786от mohitmishra786★ 307 звёзд на GitHub

Об этом скилле

Memory-Safe C and C++

Purpose

Guide agents through making existing C and C++ safer (checked with GCC 16.2, Clang 23.1 and Fil-C 0.687): what each mitigation actually catches, how to enable it, and when a rewrite is the better answer.

Triggers

  • "How do I harden a C codebase without rewriting it?"
  • "What does -fhardened turn on?"
  • "Does FORTIFY catch heap overflows?"
  • "How do I use Arm MTE or a hardened allocator?"
  • "What is Fil-C and should I use it?"
  • "Harden, sanitize, or rewrite in Rust?"

Workflow

1. What catches what

Measured on one program with a heap overflow (writing 17 bytes into malloc(16)), a use-after-free read and a strcpy into char small[8]:

Build Heap OOB write UAF read strcpy stack overflow
gcc -O2 not caught not caught not caught
gcc -O2 -fhardened not caught not caught caught (*** buffer overflow detected ***)
Scudo allocator (clang -fsanitize=scudo) not caught (slack in chunk) not caught n/a; double free caught
Fil-C caught (filc safety error) caught caught when it leaves the allocation
ASan (testing only) caught caught caught

Mitigations that run in production reduce exploitability; they do not find all bugs. Use sanitizers and fuzzing in CI, and a safe language or Fil-C where you need guarantees.

Goal?
├── Cheap, ship today → -fhardened + library hardening + -ftrivial-auto-var-init (sections 2-3)
├── Catch bounds bugs on flexible arrays → counted_by + -fsanitize=bounds (section 4)
├── Probabilistic detection in production on Arm → MTE (section 5)
├── Heap metadata attacks → hardened allocator (section 6)
├── Full memory safety, accept slowdown → Fil-C (section 7) or CHERI hardware (section 8)
└── New component → write it in Rust (skills/rust/rust-ffi for the boundary)

2. -fhardened and friends (GCC 14+)

gcc -O2 -fhardened app.c -o app

On GCC 16.2 (aarch64) -fhardened defines _FORTIFY_SOURCE=3, _GLIBCXX_ASSERTIONS, enables -fstack-protector-strong (__SSP_STRONG__), PIE, and links with -pie -z now -z relro. On x86 it also enables -fcf-protection=full (__CET__ = 3). Without optimization FORTIFY is skipped: '_FORTIFY_SOURCE' is not enabled by '-fhardened' because optimizations are turned off.

Flags you set yourself win, and GCC says so with -Whardened:

warning: '_FORTIFY_SOURCE' is not enabled by '-fhardened' because it was specified in '-D' or '-U' [-Whardened]
warning: '-fstack-protector-strong' is not enabled by '-fhardened' because it was specified on the command line [-Whardened]

Clang has no -fhardened; spell the pieces out:

clang -O2 -D_FORTIFY_SOURCE=3 -fstack-protector-strong -fstack-clash-protection \
      -ftrivial-auto-var-init=zero -fPIE -pie -Wl,-z,relro,-z,now app.c

3. Uninitialized memory and library hardening

# Zero (or pattern-fill) every uninitialized local: removes a whole class of info leaks
gcc -ftrivial-auto-var-init=zero ...        # GCC 12+, Clang 16+
gcc -ftrivial-auto-var-init=pattern ...     # debugging: GCC fills 0xfe, Clang 0xaa

# C++ standard library precondition checks
g++ -D_GLIBCXX_ASSERTIONS ...                                        # libstdc++: abort with message
clang++ -stdlib=libc++ -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST ...   # libc++: trap

A function that returns an uninitialized int after another call left 0x41414141 on the stack returned 0x41414141 with Clang by default, 0 with =zero, and 0xaaaaaaaa with =pattern.

4. Bounds annotations: counted_by

/* cb.c — counted_by lets -fsanitize=bounds check a flexible array member */
#include <stdio.h>
#include <stdlib.h>

struct packet {
    size_t len;
    unsigned char data[] __attribute__((counted_by(len)));
};

int main(int argc, char **argv)
{
    (void)argv;
    struct packet *p = malloc(sizeof *p + 4);
    p->len = 4;
    int idx = argc + 3;              /* 4 when run without arguments: one past the end */
    p->data[idx] = 1;
    printf("wrote data[%d]\n", idx);
    free(p);
    return 0;
}
gcc -fsanitize=bounds cb.c                          # GCC 15+ (GCC 14 ignores counted_by); Clang 23 too
# runtime error: index 4 out of bounds for type 'unsigned char [*]'
gcc -fsanitize=bounds -fsanitize-trap=bounds cb.c   # production: trap instead of report

-fstrict-flex-arrays=3 makes only [] count as a flexible array, so buf[1]-style fake flexible arrays get bounds checks and FORTIFY coverage. Upstream Clang 23 has no -fbounds-safety driver flag; that extension is still being upstreamed from Apple's fork.

5. Arm Memory Tagging Extension (MTE)

MTE stores a 4-bit tag per 16-byte granule and in the top byte of pointers; a mismatch faults. It runs at near-native speed on Armv8.5+ CPUs that implement it (Pixel 8 and later, some servers).

/* Linux user-space MTE:
Полный SKILL.md на GitHub

Установить memory-safe-c-cpp в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл memory-safe-c-cpp?

Memory-safe C and C++ skill for hardening existing code without a rewrite. Use when choosing between -fhardened, FORTIFY, bounds annotations, library hardening, Arm MTE, hardened allocators, Fil-C or CHERI, deciding whether to harden in place or rewrite in Rust, or explaining which bug classes each mitigation catches. Activates on queries about -fhardened, _FORTIFY_SOURCE=3, counted_by, -fsanitize=bounds, -ftrivial-auto-var-init, _GLIBCXX_ASSERTIONS, libc++ hardening, MTE, memory tagging, Scudo, hardened_malloc, Fil-C, CHERI, or memory safety roadmaps.

Как установить скилл memory-safe-c-cpp?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл memory-safe-c-cpp запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить memory-safe-c-cpp с