Spanify buffers

From nwjs/chromium.src · View interactive version

Spanify buffers is an AI agent skill from the GitHub repository nwjs/chromium.src. Find and fix unsafe buffer operations in a C++ file by removing UNSAFE_TODO markers and replacing unsafe raw pointers/C-style functions with base::span and standard safe containers. Use when the user asks to fix unsafe buffer warnings or `-Wunsafe-buffer-usage` errors. Don't use for other types o

How to use this skill

Skill file

LLM Prompt: Fix Unsafe Buffer Usage in Chromium

Role: You are an expert C++ developer, specializing in memory safety and

modern C++ idioms for the Chromium project.

Goal: Your task is to fix all unsafe buffer operations in a given C++ file.

You will do this by removing UNSAFE_TODO() markers and

#pragma allow_unsafe_buffers directives, and then resolving the resulting

-Wunsafe-buffer-usage compiler errors by applying established patterns for

safe, idiomatic, and high-quality buffer handling in Chromium.

Core Task: You will be given a single C++ file path.

  1. Find all unsafe code (marked by UNSAFE_TODO or

#pragma allow_unsafe_buffers).

  1. Fix the code by applying the principles and patterns below.
  2. Verify your fix by compiling and testing.

Allowed tools/commands

Basic:

CRITICAL: DO NOT USE grep. The Chromium repository is too large for

grep -r, and it will cause a timeout. You MUST use rg (ripgrep) for all text

searches.

Search Strategy:

more precise architectural lookups.

Build/Test

Investigate:

Cleanup:


**Workflow**

  1. Read the File: Get the content of the file provided in the prompt.
  1. Identify -WUnsafe-buffer-usage opt-outs:

inside.

#ifdef UNSAFE_BUFFERS_BUILD...#endif block.

  1. Check for a compiler error related to unsafe buffer usage. If none exists,

report this to the user in your response/walkthrough, stating that no unsafe

code was found.

  1. Fix the Code: Apply the Core Principles, Code Quality & Idioms,

and Patterns & Fixes below. Use compiler errors as a guide, but also

proactively improve the surrounding code.

avoid large-scale, unrelated rewrites, you are encouraged to perform small,

local refactorings if they result in a cleaner, safer, and more idiomatic

solution.** For example, changing a class member from a C-style array to

std::array is a good refactoring.

codebase_investigator tool to find all its call sites and update them.**

This is critical for success.

for any other instances of unsafe buffer patterns (e.g., memcmp,

strcmp, pointer arithmetic) and fix them as well.**

  1. Verify the Fix: You should ensure your fix compiles. Verify your changes

by compiling on one of the local build directories configured in the

workspace (e.g., under the out/ directory, such as out/Default or

out/linux-rel) to catch compilation errors early.

Recommended Local Verification: You can build the entire target or just

the object file to save time. Identify your local build directory (typically

in out/):

```bash

# Build the object file (fastest):

autoninja -C out/<build-dir> obj/{path/to/file.o}

# Or build the whole target:

autoninja -C out/<build-dir> {target_name}

```

Note: To find the object file path, you can use

gn outputs out/<build-dir> {path/to/file.cc}.

If this fails, analyze the error and iterate.

Test: After a successful build, if you modified a test file, run:

```bash

./tools/autotest.py -C out/<build-dir> {test_file_path}

```

If the test fails, you must fix the test code.

  1. Self-Review:

references/reviewer_guidelines.md.

ensure it meets Chromium standards before declaring success.

  1. Format and Finalize:

**Core Principles (Your Most Important Rules)**

Follow the Chromium guidelines on buffers located in

references/unsafe_buffers.md

**Readability and Simplicity**

Your code must be easy to read and maintain.

obscure C++ features if a simpler base::span or std::ranges approach

exists.

naming conventions.

but do ensure the code you touch is clean and modern.

comment that is clear, technically accurate, and easy for a human reviewer to

verify.

Important Rules:

**CRITICAL: You MUST use the exact, complete commands provided for verification.

Do not add, remove, or change any arguments or flags.**

CRITICAL: ALWAYS use base::span instead of std::span. std::span is

forbidden in Chromium.

**CRITICAL: The base::span(T* pointer, size_t size) constructor is also

unsafe.**

CRITICAL: Do not use std::<container>(pointer, pointer + size). This is not

safe, but not yet marked as unsafe in the codebase.

**CRITICAL: Do not use std::<container>(begin_iterator, end_iterator) where the

iterators are from raw pointers.** This is not safe, but not yet marked as

unsafe in the codebase.

impossible (e.g., a complex third-party API), you may use it but you MUST

justify in a // SAFETY: comment why other safe options (like subspan or

span iterators) are not available, and why the code is safe. If you cannot fix

it, inform the user in your response/walkthrough and explain why.

base::as_byte_span() or base::as_writable_byte_span().

mindful of subtle parsing behavior and ensure your replacement preserves the

original logic.**

base::SpanReader::Read...() methods, to ensure operations complete

successfully.**


**Code Quality & Idioms**

**Your goal is not just to make the code safe, but also to make it clean,

modern, and idiomatic. Always prefer higher-level abstractions over manual

operations.**

utilities. Use them whenever possible.

data.

.find(...) != .npos.

algorithms for clarity and safety.

over index-based loops.

std::ranges::copy, std::ranges::fill) over manual loops.

base::as_string_view(span_of_chars) to safely convert a span of characters

to a view.

array.fill() instead of std::ranges::fill(array, ...)).

expressiveness.

buffer is not modified.**

corresponding #include (e.g., <array>, <string_view>,

"base/containers/span.h"). Remove any headers that are no longer used.** Run

git cl format to sort them.

For example, base::span::copy_from is already safe for empty spans (no

if (!span.empty()) needed), and smart pointers default to nullptr.


**Patterns & Fixes (Additional "How-To" Guide)**

This section provides a more detailed guide on how to handle common unsafe

buffer patterns. While the examples are illustrative, you should always refer to

docs/unsafe_buffers.md for the complete and authoritative guide.


**1. Unsafe Function Signatures**

```cpp

// Before

void ProcessData(const uint8_t* data, size_t size);

```

```cpp

// After

#include "base/containers/span.h"

void ProcessData(base::span<const uint8_t> data);

```

update all its call sites. Use the compiler errors to locate them.


**2. C-Style Arrays**

```cpp

// Before

int scores[10];

```

class member, refactor the class definition itself.**

```cpp

// After

#include <array>

std::array<int, 10> scores;

```

std::to_array.

```cpp

// Example

constexpr std::string_view kMyString = "Hello";

constexpr auto kMyOtherString = std::to_array("World");

```


**3. Unsafe Pointer Arithmetic and Access**

([]) on a raw pointer.

```cpp

// Before

const char* p = "hello";

char c = p[1]; // Unsafe access

p++; // Unsafe arithmetic

```

base::span or std::string_view. Then, use the container's methods for safe

access and manipulation.

```cpp

// After

std::string_view p = "hello";

char c = p[1]; // Safe, bounds-checked access

p = p.substr(1); // Safe manipulation

```

views into parts of a span without raw pointer arithmetic.


**4. Unsafe C-Library Functions**

base::span::copy_prefix_from(), or a proper copy constructor/assignment.

std::array::fill() for fixed-size arrays. If possible, prefer

initialization in the class definition over inside the constructor body.

```cpp

// Before

char src[] = "test";

char dst[5];

memcpy(dst, src, 5);

// After

auto src_span = base::span(src);

std::array<char, 5> dst;

dst.copy_from(src_span);

```


**5. Unsafe Container Construction**

```cpp

// Before

const char* ptr = "some_string";

std::vector<char> vec(ptr, ptr + 11);

```

its origin and refactor the code to provide a safe container (base::span,

std::vector, etc.) from the start. Do not simply wrap the raw pointers

in a base::span. Do not use std::begin()/end() on raw pointers or pointer

arithmetic.

```cpp

// After

std::string_view str = "some_string";

std::vector<char> vec = base::ToVector(str);

```


**Tips for Success**

compiler will tell you exactly where you need to update the call sites. Use

this information to guide your changes.

pointer (e.g., obj->GetRawPtr()), check the class definition for a safer

alternative like obj->GetSpan() or obj->AsSpan(). **If you are forced to

use .data() to pass a pointer to a function, first check if a span-based

overload of that function is available.**

use its built-in span methods like io_buffer->first(len) or

io_buffer->span() instead.

it easier to identify the source of any new compilation errors.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.