blob: 4a4d5e437a85bf1309ac6a2bd868d64ff4abd997 [file] [log] [blame] [view]
Tom Sepezd647d842025-02-11 21:11:511# The Unsafe Buffers Clang plugin.
danakj4e625fb2024-03-06 20:47:462
Tom Sepezd647d842025-02-11 21:11:513Our compiler contains a [plugin](../tools/clang/plugins/UnsafeBuffersPlugin.cpp)
4which reports places in the code where unsafe buffer operations are present.
5
6[TOC]
7
8
9## Preventing OOB by removing Unsafe Buffers operations.
10
11Out-of-bounds (OOB) security bugs commonly happen through C-style pointers
12which have no bounds information associated with them. We can prevent such
13bugs by always using C++ containers. Furthermore, the plugin will warn
Tom Sepez9e7f6962024-06-13 00:21:5914warn about unsafe pointer usage that should be converted to containers.
15When an unsafe usage is detected, Clang prints a warning similar to
16```
17error: unsafe buffer access [-Werror,-Wunsafe-buffer-usage]
18```
Tom Sepezd647d842025-02-11 21:11:5119and directs developers to this file for more information. Several common
20[Techniques](#container-based-ecosystem) for fixing these issues are presented
21later in this document.
danakj4e625fb2024-03-06 20:47:4622
danakj22031fb12024-11-08 14:52:3023Clang documentation includes a guide to working with unsafe-buffer-usage
24warnings here: https://clang.llvm.org/docs/SafeBuffers.html
25
Tom Sepezb1428462025-01-27 21:44:4326## Preventing OOB by removing unsafe libc calls.
27
28OOB bugs also commonly happen through C-style library calls such as
Tom Sepezd647d842025-02-11 21:11:5129memcpy() and memset() where the programmer is responsible for specifying
30an (unchecked) length. In order to encourage safer alternatives, the
31plugin can warn about unsafe calls which should be converted to safer
32C++ alternatives. When an unsafe libc call is detected, Clang prints
33a warning similar to
34```
35error: function 'memcpy' is unsafe [-Werror,-Wunsafe-buffer-usage-in-libc-call]
36```
Tom Sepezd647d842025-02-11 21:11:5137## Unsafe buffer warning suppressions
danakj6a49deaa2024-06-04 21:31:5538
Tom Sepezd647d842025-02-11 21:11:5139Because the Chromium codebase is not yet compliant with these warnings,
40there are mechanisms to opt out code on a directory, file, or per-occurence
41basis.
42
43By default, all files are checked for unsafe-buffer-usage.
44
45### Opting out entire directories
danakj6a49deaa2024-06-04 21:31:5546
Tom Sepezb1428462025-01-27 21:44:4347Entire directories are opted out of unsafe buffer usage warnings through
Tom Sepez9e7f6962024-06-13 00:21:5948the [`//build/config/unsafe_buffers_paths.txt`](../build/config/unsafe_buffers_paths.txt)
49file. As work progresses, directories will be removed from this list, and
50non-compliant files marked on a per-file basis as below. Early results
51indicate that often 85%+ of files in a directory already happen to be
52compliant, so file-by-file suppression allows this code to be subject
53to enforcement.
54
Tom Sepezd647d842025-02-11 21:11:5155This mechanism opts directories out of all warning categories (unsafe
56buffers and unsafe libc calls).
57
58#### Syntax of Unsafe Buffer Paths file
59
60Note: Paths should be written as relative to the root of the source tree with
61unix-style path separators. Directory prefixes should end with `/`, such
62as `base/`.
63
64Empty lines are ignored.
65
66The `#` character introduces a comment until the end of the line.
67
Tom Sepezb1a81562025-02-20 17:28:5468Lines starting with `.` declare which checks are to be enforced, as
69a comma-separated list of values. Currently allowed values are `buffers`
70and `libc`.
71
72All other lines specify which paths are to be included/excluded.
73
Tom Sepezd647d842025-02-11 21:11:5174Lines that begin with `-` are immediately followed by path prefixes that
75will *not* be checked for unsafe-buffer-usage. They are known to do unsafe
76things and should be changed to use constructs like base::span or containers
77like base::HeapArray and std::vector instead. See https://crbug.com/40285824
78
79Lines that begin with `+` are immediately followed by path prefixes that will
80be checked for unsafe-buffer-usage. These have no such usage (or all such
81usage is annotated), and are protected against new unsafe pointer behaviour
82by the compiler. Generally, `+` lines are used to enable checks for
83sub-directories of a path that has previously disabled checks (with a
84`-` line).
85
86If a file matches both a `-` and `+` line, the longest matching prefix takes
87precedence.
88
89#### Removing directories from Unsafe Buffers Paths file
90
91The recommended process for removing a `-dir/` line from this file is:
92
931. Remove the `-dir/` line from this paths file. Possibly add some subdirectories
94now needed to reduce scope, like `-dir/sub_dir/`.
95
962. Add `#pragma allow_unsafe_buffers` to every file in the directory that now
97has a compilation error (see the next section).
98
99### Opting out individual files
100
Tom Sepez9e7f6962024-06-13 00:21:59101Individual files are opted out of unsafe pointer usage warnings though
102the use of the following snippet, which is to be placed immediately
103following the copyright header in a source file.
104```
105#ifdef UNSAFE_BUFFERS_BUILD
106// TODO(crbug.com/ABC): Remove this and convert code to safer constructs.
107#pragma allow_unsafe_buffers
108#endif
109```
110
Tom Sepezd647d842025-02-11 21:11:51111The above mechanism also suppress unsafe libc call warnings in addition
112to the unsafe buffer warnings.
113
114To prevent back-sliding on files which have been made safe with respect
115to unsafe buffers, there is now a per-file pragma which suppresses the
116libc warnings while still enforcing the unsafe buffer warnings.
117
118```
119#ifdef UNSAFE_BUFFERS_BUILD
120// TODO(crbug.com/ABC): Remove libc calls to fix these warnings.
121#pragma allow_unsafe_libc_calls
122#endif
123```
124
125An initial set of files containing allow\_unsafe\_libc\_calls has been
126uploaded; please keep these in place until the pending libc enforcement
127is enabled for Chromium.
128
129#### Removing pragmas from individual files.
130
131The recommended process for removing pragmas from individual files is:
132
1331. 1. Remove the pragma from the file.
134
1352. Use the compiler warnings now generated to identify the individual
136expressions to suppress (see the next section).
137
138### Opting out individual expressions
139
Tom Sepez9e7f6962024-06-13 00:21:59140Individual expressions or blocks of code are opted out by using the
Evan Stade8d390c52025-04-22 20:28:49141`UNSAFE_BUFFERS()` macro as defined in [`//base/compiler_specific.h`](../base/compiler_specific.h)
Tom Sepez9e7f6962024-06-13 00:21:59142file. These should be rare once a project is fully converted, except
143perhaps when working with C-style external APIs. These must
144always be accompanied by a `// SAFETY:` comment explaining in detail
145how the code has been evaluated to be safe for all possible input.
146
Evan Stade8d390c52025-04-22 20:28:49147Code introducing `UNSAFE_BUFFERS()` macro invocations without corresponding
Tom Sepez9e7f6962024-06-13 00:21:59148`// SAFETY:` comment should be summarily rejected during code review.
149
Tom Sepez3072e382024-08-14 22:42:44150To allow for incremental conversion, code can be temporarily opted out by
151using the `UNSAFE_TODO()` macro. This provides the same functionality as
152the `UNSAFE_BUFFERS()` macro, but allows easier searching for code in need
153of revision. Add TODO() comment, along the lines of
154`// TODO(crbug.com/xxxxxx): resolve safety issues`.
155
Tom Sepezd647d842025-02-11 21:11:51156This mechanism opts expressions out of all warning categories (unsafe
157buffers and unsafe libc calls).
Tom Sepezb1428462025-01-27 21:44:43158
Tom Sepezd647d842025-02-11 21:11:51159#### Removing UNSAFE_TODO() from individual expressions
Tom Sepezb1428462025-01-27 21:44:43160
Tom Sepezd647d842025-02-11 21:11:51161We seek to convert code to use owning containers like HeapArray and vector,
162as explained in the next section.
Tom Sepezb1428462025-01-27 21:44:43163
danakja4c42382024-06-18 19:05:44164## Container-based ecosystem
165
166Containers may be owning types or view types. The common owning containers that
167us contiguous storage are `std::vector`, `std::string`, `base::HeapArray`,
168`std::array`. Their common view types are `base::span`, `std::string_view`,
169`base::cstring_view`.
170
171Other owning containers include maps, sets, deques, etc. These are not
172compatible with `base::span` as they are not contiguous and generally do not
173have an associated view type at this time.
174
175We are using `base::span` instead of `std::span` in order to provide a type that
176can do more than the standard type. We also have other types and functions to
177work with ranges and spans instead of unbounded pointers and iterators.
178
179The common conversions to spans are:
180- `base::span<T>` replaces `T* ptr, size_t size`.
181- `base::span<T, N>` replaces `T (&ptr)[N]` (a reference to a compile-time-sized
182 array).
183- `base::raw_span<T>` replaces `base::span<T>` (and `T* ptr, size_t size`) for
184 class fields.
185
186### Span construction
Peter Kastinge825c6f2024-12-02 17:35:39187- `base::span()` makes a span, deducing the type and size, from any contiguous
188 range. It can also take explicit begin/end or data/size pairs.
189- `base::to_fixed_extent<N>()` makes a fixed-size span from a dynamic one.
danakja4c42382024-06-18 19:05:44190- `base::as_bytes()` and `base::as_chars()` convert a span’s inner type to
191 `uint8_t` or `char` respectively, making a byte-span or char-span.
192- `base::span_from_ref()` and `base::byte_span_from_ref()` make a span, or
193 byte-span, from a single object.
Peter Kastinge825c6f2024-12-02 17:35:39194- `base::as_byte_span()` and `base::as_writable_byte_span()` make a
195 byte-span from any contiguous range.
danakja4c42382024-06-18 19:05:44196
197#### Padding bytes
danakja4c42382024-06-18 19:05:44198Note that if the type contains padding bytes that were not somehow explicitly
199initialized, this can create reads of uninitialized memory. Conversion to a
200byte-span is most commonly used for spans of primitive types, such as going from
201`char` (such as in `std::string`) or `uint32_t` (in a `std::vector`) to
202`unit8_t`.
203
204### Dynamic read/write of a span
205- `base::SpanReader` reads heterogeneous values from a (typically, byte-) span
206 in a dynamic manner.
207- `base::SpanWriter` writes heterogeneous values into a (typically, byte-) span
208 in a dynamic manner.
209
210### Values to/from byte spans
211In [`//base/numerics/byte_conversions.h`](../base/numerics/byte_conversions.h)
212we have conversions between byte-arrays and big/little endian integers or
213floats. For example (and there are many other variations):
214- `base::U32FromBigEndian` converts from a big-endian byte-span to an unsigned
215 32-bit integer.
216- `base::U32FromLittleEndian` converts from a little-endian byte-span to an
217 unsigned
218- `base::U32ToBigEndian` converts from an integer to a big-endian-encoded
219 4-byte-array.
220- `base::U32ToLittleEndian` converts from an integer to a little-endian-encoded
221 4-byte-array.
222
223### Heap-allocated arrays
224- `base::HeapArray<T>` replaces `std::unique_ptr<T[]>` and places the bounds of
225the array inside the `HeapArray` which makes it a bounds-safe range.
226
227### Copying and filling arrays
228- `base::span::copy_from(span)` replaces `memcpy` and `memmove`, and verifies
229that the source and destination spans have the same size instead of writing
230out of bounds. It lowers to the same code as `memmove` when possible.
231 - Note `std::ranges::copy` is not bounds-safe (though its name sounds like
232 it should be).
233- `std::ranges::fill` replaces `memset` and works with a range so you don't
234 need explicit bounds.
235
236### String pointers
237
238A common form of pointer is `const char*` which is used (sometimes) to represent
239a NUL-terminated string. The standard library gives us two types to replace
240`char*`, which allow us to know the bounds of the character array and work with
241the string as a range:
242
243- `std::string` owns a NUL-terminated string.
244- `std::string_view` is a view of a non-NUL-terminated string.
245
246What’s missing is a view of a string that is guaranteed to be NUL-terminated so
247that you can call `.c_str()` to generate a `const char*` suitable for C APIs.
248
249- `base::cstring_view` is a view of a NUL-terminated string. This avoids the
250 need to construct a `std::string` in order to ensure a terminating NUL is
251 present. Use this as a view type whenever your code bottoms out in a C API
252 that needs NUL-terminated string pointer.
253
254### Use of std::array<T>.
Tom Sepez9e7f6962024-06-13 00:21:59255
256The clang plugin is very particular about indexing a C-style array (e.g.
257`int arr[100]`) with a variable index. Often these issues can be resolved
258by replacing this with `std::array<int, 100> arr`, which provides safe
259indexed operations. In particular, new code should prefer to use the
260`std::array<T, N>` mechanism.
261
262For arrays where the size is determined by the compiler (e.g.
263`int arr[] = { 1, 3, 5 };`), the `std::to_array<T>()` helper function
264should be used along with the `auto` keyword:
265`auto arr = std::to_array<int>({1, 3, 5});`
266
Tom Sepezd647d842025-02-11 21:11:51267### Avoid reinterpret_cast
danakja4c42382024-06-18 19:05:44268
Tom Sepezd647d842025-02-11 21:11:51269Casts to bytes are common and can be handled as follows.
270
271#### Writing to a byte span
danakja4c42382024-06-18 19:05:44272
273A common idiom in older code is to write into a byte array by casting
274the array into a pointer to a larger type (such as `uint32_t` or `float`)
danakjcdf43e22024-07-02 16:42:16275and then writing through that pointer. This can result in Undefined Behaviour
danakja4c42382024-06-18 19:05:44276and violates the rules of the C++ abstract machine.
277
278Instead, keep the byte array as a `base::span<uint8_t>`, and write to it
279directly by chunking it up into pieces of the size you want to write.
280
Peter Kasting448444f2024-12-13 01:25:36281Using `take_first()` (good for repeated modifications and loops):
danakja4c42382024-06-18 19:05:44282```cc
283void write_floats(base::span<uint8_t> out, float f1, float f2) {
Peter Kasting448444f2024-12-13 01:25:36284 // Write `f1` into `out`'s prefix, moving `out` forward.
285 out.take_first<4>().copy_from(base::byte_span_from_ref(f1));
286 // Write `f2` into `out`'s new prefix (after `f1`).
287 out.copy_prefix_from(base::byte_span_from_ref(f2));
danakja4c42382024-06-18 19:05:44288}
289```
290
Peter Kasting448444f2024-12-13 01:25:36291Using `split_at()` (good when there are exactly two pieces):
danakja4c42382024-06-18 19:05:44292```cc
293void write_floats(base::span<uint8_t> out, float f1, float f2) {
Peter Kasting448444f2024-12-13 01:25:36294 // Split `out` into a prefix to write `f1` into, and a remainder.
danakja4c42382024-06-18 19:05:44295 auto [write_f1, rem] = out.split_at<4>();
Peter Kasting448444f2024-12-13 01:25:36296 // Write `f1` into the prefix portion, `write_f1`.
danakja4c42382024-06-18 19:05:44297 write_f1.copy_from(base::byte_span_from_ref(f1));
Peter Kasting448444f2024-12-13 01:25:36298 // Write `f2` into the beginning of the remainder.
299 rem.copy_prefix_from(base::byte_span_from_ref(f2));
danakja4c42382024-06-18 19:05:44300}
301```
302
Peter Kasting448444f2024-12-13 01:25:36303Using `SpanWriter` and endian-aware `FloatToLittleEndian()` (good when non-fatal
304APIs are desired):
danakja4c42382024-06-18 19:05:44305```cc
306void write_floats(base::span<uint8_t> out, float f1, float f2) {
307 auto writer = base::SpanWriter(out);
308 CHECK(writer.Write(base::FloatToLittleEndian(f1)));
309 CHECK(writer.Write(base::FloatToLittleEndian(f2)));
310}
311```
312
313Writing big-endian, with `SpanWriter` and endian-aware `U32ToBigEndian()`:
314```cc
315void write_values(base::span<uint8_t> out, uint32_t i1, uint32_t i2) {
316 auto writer = base::SpanWriter(out);
317 CHECK(writer.Write(base::U32ToBigEndian(i1)));
318 // SpanWriter has a built-in shortcut to do the same thing.
319 CHECK(writer.WriteU32BigEndian(i2));
320 // Verify we wrote to the whole output. We can put a size parameter in the
321 // `out` span to push this check to compile-time when it's a constant.
322 CHECK_EQ(writer.remaining(), 0u);
323}
324```
325
326Writing an array to a byte span with `copy_from()`:
327```cc
328void write_floats(base::span<uint8_t> out, std::vector<const float> floats) {
329 base::span<const uint8_t> byte_floats = base::as_byte_span(floats);
Peter Kasting448444f2024-12-13 01:25:36330 // Or use copy_from() if you want to CHECK at runtime that all of `out` has
danakja4c42382024-06-18 19:05:44331 // been written to.
Peter Kasting448444f2024-12-13 01:25:36332 out.copy_prefix_from(byte_floats);
danakja4c42382024-06-18 19:05:44333}
334```
335
Tom Sepezd647d842025-02-11 21:11:51336#### Reading from a byte span
danakja4c42382024-06-18 19:05:44337
338Instead of turning a `span<const uint8_t>` into a pointer of a larger type,
339which can cause Undefined Behaviour, read values out of the byte span and
340convert each one as a value (not as a pointer).
341
Peter Kasting448444f2024-12-13 01:25:36342Using `take_first()` and endian-aware conversion `FloatFromLittleEndian`:
danakja4c42382024-06-18 19:05:44343```cc
344void read_floats(base::span<const uint8_t> in, float& f1, float& f2) {
Peter Kasting448444f2024-12-13 01:25:36345 f1 = base::FloatFromLittleEndian(in.take_first<4>());
346 f2 = base::FloatFromLittleEndian(in.take_first<4>());
danakja4c42382024-06-18 19:05:44347}
348```
349
350Using `SpanReader` and endian-aware `U32FromBigEndian()`:
351```cc
352void read_values(base::span<const uint8_t> in, int& i1, int& i2, int& i3) {
353 auto reader = base::SpanReader(in);
354 i1 = base::U32FromBigEndian(*reader.Read<4>());
355 i2 = base::U32FromBigEndian(*reader.Read<4>());
356 // SpanReader has a built-in shortcut to do the same thing.
357 CHECK(reader.ReadU32BigEndian(i3));
358 // Verify we read the whole input. We can put a size parameter in the `in`
359 // span to push this check to compile-time when it's a constant.
360 CHECK_EQ(reader.remaining(), 0u);
361}
362```
363
364## Patterns for spanification
Tom Sepez9e7f6962024-06-13 00:21:59365
366Most pointer issues ought to be resolved by converting to containers. In
367particular, one common conversion is to replace `T*` pointers with
368`base::span<T>` in a process known as spanification, since most pointers
369are unowned references into an array (or vector). The appropriate
370replacement for the pointer is
danakje7db1e3f32024-04-16 20:43:24371[`base::span`](../base/containers/span.h).
danakj4e625fb2024-03-06 20:47:46372
danakj6a49deaa2024-06-04 21:31:55373### Copying arrays (`memcpy`)
374
375You have:
376```cc
377uint8_t array1[12];
378uint8_t array2[16];
379uint64_t array3[2];
380memcpy(array1, array2 + 8, 4);
381memcpy(array1 + 4, array3, 8);
382```
383
384Spanified:
385```cc
386uint8_t array1[12];
387uint8_t array2[16];
388uint64_t array3[2];
Peter Kasting448444f2024-12-13 01:25:36389base::span<uint8_t> span1(array1);
390span1.take_first<4>().copy_from(base::span(array2).subspan<8, 4>());
391span1.copy_from(base::as_byte_span(array3).first<8>());
danakj6a49deaa2024-06-04 21:31:55392
393// Use `split_at()` to ensure `array1` is fully written.
Peter Kasting448444f2024-12-13 01:25:36394auto [from2, from3] = base::span(array1).split_at<4>();
395from2.copy_from(base::span(array2).subspan<8, 4>());
396from3.copy_from(base::as_byte_span(array3).first<8>());
danakj6a49deaa2024-06-04 21:31:55397```
398
399### Zeroing arrays (`memset`)
400
401`std::ranges::fill` works on any range/container and won't write out of
402bounds. Converting arbitrary types into a byte array (through
403`base::as_writable_byte_span`) is only valid when the type holds trivial
404types such as primitives. Unlike `memset`, a constructed object can be
405given as the value to use as in `std::ranges_fill(container, Object())`.
406
407You have:
408```cc
409uint8_t array1[12];
410uint64_t array2[2];
411Object array3[4];
412memset(array1, 0, 12);
413memset(array2, 0, 2 * sizeof(uint64_t));
414memset(array3, 0, 4 * sizeof(Object));
415```
416
417Spanified:
418```cc
419uint8_t array1[12];
420uint64_t array2[2];
421Object array3[4];
Peter Kasting448444f2024-12-13 01:25:36422std::ranges::fill(array1, 0);
423std::ranges::fill(array2, 0);
424std::ranges::fill(base::as_writable_byte_span(array3), 0);
danakj6a49deaa2024-06-04 21:31:55425```
426
427### Comparing arrays (`memcmp`)
428
429You have:
430```cc
431uint8_t array1[12] = {};
432uint8_t array2[12] = {};
433bool eq = memcmp(array1, array2, sizeof(array1)) == 0;
danakj8d29e182024-06-05 16:50:18434bool less = memcmp(array1, array2, sizeof(array1)) < 0;
danakj6a49deaa2024-06-04 21:31:55435
436// In tests.
437for (size_t i = 0; i < sizeof(array1); ++i) {
438 SCOPED_TRACE(i);
439 EXPECT_EQ(array1[i], array2[i]);
440}
441```
442
443Spanified:
444```cc
445uint8_t array1[12] = {};
446uint8_t array2[12] = {};
447// If one side is a span, the other will convert to span too.
448bool eq = base::span(array1) == array2;
danakj8d29e182024-06-05 16:50:18449bool less = base::span(array1) < array2;
danakj6a49deaa2024-06-04 21:31:55450
451// In tests.
452EXPECT_EQ(base::span(array1), array2);
453```
454
455### Copying array into an integer
456
457You have:
458```cc
459uint8_t array[44] = {};
460uint32_t v1;
461memcpy(&v1, array, sizeof(v1)); // Front.
462uint64_t v2;
463memcpy(&v2, array + 6, sizeof(v2)); // Middle.
464```
465
466Spanified:
467```cc
468#include "base/numerics/byte_conversions.h"
469...
470uint8_t array[44] = {};
471uint32_t v1 = base::U32FromLittleEndian(base::span(array).first<4u>()); // Front.
472uint64_t v2 = base::U64FromLittleEndian(base::span(array).subspan<6u, 8u>()); // Middle.
473```
474
475### Copy an array into an integer via cast
476
David Benjamin0ffdea72024-06-12 19:55:22477Note: This pattern is prone to more UB than out-of-bounds access. It is UB to
478cast pointers if the result is not aligned, so these cases are often buggy or
479were only correct due to subtle assumptions on buffer alignment. The spanified
480version avoids this pitfalls. It has no alignment requirement.
danakj6a49deaa2024-06-04 21:31:55481
482You have:
483```cc
484uint8_t array[44] = {};
485uint32_t v1 = *reinterpret_cast<const uint32_t*>(array); // Front.
David Benjamin0ffdea72024-06-12 19:55:22486uint64_t v2 = *reinterpret_cast<const uint64_t*>(array + 16); // Middle.
danakj6a49deaa2024-06-04 21:31:55487```
488
489Spanified:
490```cc
491#include "base/numerics/byte_conversions.h"
492...
493uint8_t array[44] = {};
494uint32_t v1 = base::U32FromLittleEndian(base::span(array).first<4u>()); // Front.
David Benjamin0ffdea72024-06-12 19:55:22495uint64_t v2 = base::U64FromLittleEndian(base::span(array).subspan<16u, 8u>()); // Middle.
danakj6a49deaa2024-06-04 21:31:55496```
497
498### Making a byte array (`span<uint8_t>`) from a string (or any array/range)
499
500You have:
501```cc
502std::string str = "hello world";
503func_with_const_ptr_size(reinterpret_cast<const uint8_t*>(str.data()), str.size());
504func_with_mut_ptr_size(reinterpret_cast<uint8_t*>(str.data()), str.size());
505```
506
507Spanified:
508```cc
509std::string str = "hello world";
510base::span<const uint8_t> bytes = base::as_byte_span(str);
511func_with_const_ptr_size(bytes.data(), bytes.size());
512base::span<uint8_t> mut_bytes = base::as_writable_byte_span(str);
513func_with_mut_ptr_size(mut_bytes.data(), mut_bytes.size());
514
515// Replace pointer and size with a span, though.
516func_with_const_span(base::as_byte_span(str));
517func_with_mut_span(base::as_writable_byte_span(str));
518```
519
520### Making a byte array (`span<uint8_t>`) from an object
521
522You have:
523```cc
524uint8_t array[8];
525uint64_t val;
526two_byte_arrays(array, reinterpret_cast<const uint8_t*>(&val));
527```
528
529Spanified:
530```cc
531uint8_t array[8];
532uint64_t val;
533base::span<uint8_t> val_span = base::byte_span_from_ref(val);
534two_byte_arrays(array, val_span.data());
535
536// Replace an unbounded pointer a span, though.
537two_byte_spans(base::span(array), base::byte_span_from_ref(val));
538```
danakje7db1e3f32024-04-16 20:43:24539
danakjb70695e2024-07-16 15:20:28540### Avoid std::next() for silencing warnings, use ranges
541
542When we convert `pointer + index` to `std::next(pointer, index)` we silence the
543`Wunsafe-buffer-usage` warning by pushing the unsafe pointer arithmetic into
544the `std::next()` function in a system header, but we have the same unsafety.
545`std::next()` does no additional bounds checking.
546
547Instead of using `std::next()`, rewrite away from using pointers (or iterators)
548entirely by using ranges. `span()` allows us to take a subset of a contiguous
549range without having to use iterators that we move with arithmetic or
550`std::next()`.
551
danakje64eb292024-10-22 19:02:33552Likewise, `std::advance()` can silence the warning but does not add any safety
553to the pointer arithmetic and should be avoided.
554
danakjb70695e2024-07-16 15:20:28555Instead of using pointer/iterator arithmetic:
556```cc
557// Unsafe buffers warning on the unchecked arithmetic.
558auto it = std::find(vec.begin() + offset, vec.end(), 20);
559// No warning... But has the same security risk!
560auto it = std::find(std::next(vec.begin(), offset), vec.end(), 20);
561```
562
563Use a range, with `span()` providing a view of a subset of the range:
564```cc
565auto it = std::ranges::find(base::span(vec).subspan(offset), 20);
566```
567
Tom Sepezd647d842025-02-11 21:11:51568### Functions with array pointer parameters
danakj4e625fb2024-03-06 20:47:46569
Tom Sepez9e7f6962024-06-13 00:21:59570Functions that receive a pointer argument into an array may read
571or write out of bounds of that array if subsequent manual size
572calculations are incorrect. Such functions should be avoided if
573possible, or marked with the `UNSAFE_BUFFER_USAGE` attribute macro
574otherwise. This macro propagates to their callers that they must
575be called from inside an `UNSAFE_BUFFERS()` region (along with
576a corresponding safety comment explaining how the caller knows
577the call will be safe).
danakj4e625fb2024-03-06 20:47:46578
579The same is true for functions that accept an iterator instead
danakje7db1e3f32024-04-16 20:43:24580of a range type. Some examples of each are `memcpy()` and
581`std::copy()`.
danakj4e625fb2024-03-06 20:47:46582
Tom Sepez9e7f6962024-06-13 00:21:59583Again, calling such functions is unsafe and should be avoided.
584Replace such functions with an API built on base::span
danakj4e625fb2024-03-06 20:47:46585or other range types which prevents any chance of OOB memory
586access. For instance, replace `memcpy()`, `std::copy()` and
587`std::ranges::copy()` with `base::span::copy_from()`. And
588replace `memset()` with `std::ranges::fill()`.
danakjb4705072024-11-06 20:54:09589
Tom Sepezd647d842025-02-11 21:11:51590### Aligned memory
danakjb4705072024-11-06 20:54:09591
592An aligned heap allocation can be constructed into a `base::HeapArray` through
593the `base::AlignedUninit<T>(size, alignment)` function in
594`//base/memory/aligned_memory.h`. It will allocate space for `size` many `T`
595objects aligned to `alignment`, and return a `base::AlignedHeapArray<T>` which
596is a `base::HeapArray` with an appropriate deleter. Note that the returned
597memory is uninitialized.
598```cc
599base::AlignedHeapArray<float> array = base::AlignedUninit<float>(size, alignment);
600```
601
602Some containers are built on top of buffers of `char`s that are aligned for
603some other `T` in order to manage the lifetimes of objects in the buffer
604through in-place construction (`std::construct_at`) and destruction. While the
605memory is allocated and destroyed as `char*`, it is accessed as `T*`. The
606`base::AlignedUninitCharArray<T>(size, alignment)` function in
607`//base/memory/aligned_memory.h` handles this by returning both:
608- A `base::AlignedHeapArray<char>` that will not call destructors on anything in its
609 buffer.
610- A `base::span<T>` that points to all of the (not-yet-created) objects in the
611 `AlignedHeapArray`. This span can be used to construct `T` objects in place in the
612 buffer, and the caller is responsible for destroying them as well.
613```cc
614auto [a, s] = base::AlignedUninitCharArray<float>(size, alignment);
615base::AlignedHeapArray<char> array = std::move(a);
616base::span<float> span = s;
617```
Tom Sepezd647d842025-02-11 21:11:51618