Goal
Define an API for allocating/managing memory that:
- Makes it hard to forget checking for allocation failures
- Validates (in debug mode) the presence of these checks at runtime
- Prevents accidental leaks, e.g. when a multi-step allocation fails
For this RFC, I’m considering both simple allocation calls (new, make_unique) as well as container APIs that allocate memory implicitly. For containers, I am not considering objects whose move/copy operations require allocating memory (and can thus fail). If this is ever needed, it should be handled in a separate RFC. This topic should not impact matters discussed here as such objects will likely not use standard c++ copy/move operations (as those don’t have a way of reporting errors).
I am also not considering other failure modes (e.g. popping from an empty container), because these errors and their mitigations (checking for emptiness) are familiar to C++ programmers and more errors are likely to be introduced through the usage of unfamiliar APIs.
Motivation
We’re starting to implement more complicated parts of POSIX, and are running into the need for more complex memory management primitives. Currently we have a combination of specialized solutions (e.g., libc/src/__support/pwd/dynamic_buffer.h), inlined implementations (libc/src/__support/File/dir_scan_impl.h). There are at least a couple of bugs (src/__support/File/linux/file.cpp, src/__support/HashTable/table.h) where memory is leaked or other bad things happen when memory allocation fails. Some types (cpp::string) don’t even pretend to handle allocation failures. Using safer primitives for memory allocation would help avoid these kinds of issues.
Proposal
Of the three stated goals, the last one is the easiest to achieve. I propose banning ~all raw memory allocations (new, malloc, etc.) and require the use of RAII-enabled wrappers similar to std::unique_ptr, std::vector, etc. The only exception is the implementation of those RAII objects.
The other two goals can be achieved as follows.
CheckedPtr
This is a owning pointer, which enforces a null check on its value before the pointer can be accessed. It is a wrapper around unique_ptr with an additional (in debug mode) checked flag. The assertion fires regardless of the actual pointer value, which means we don’t have to inject actual allocation failures[1] to validate the existence of the check. The behavior is best explained by an example:
CheckedPtr<T> ptr = MakeUnique<T>(...);
ptr->foo(); // ERROR: value not checked
if (ptr) // check here
ptr->foo(); // OK: check above
The value can be converted to a regular unique_ptr (e.g., for long term storage) with an explicit operation:
unique_ptr<T> ptr;
// ...
if (!MakeUnique<T>(...).move_to(ptr)) // move_to is [[nodiscard]]
return ENOMEM;
Containers
All operations which can allocate memory (and thus fail) return a Checked object similar in spirit to CheckedPtr. This object wraps a bool and simply forces a check on the result. In particular, this means that containers cannot be initialized through a constructor (no way to return errors). This is how a vector-like container could look like[2][3]:
struct Vector {
Vector();
Vector(Vector &&); // if the storage can be moved or is inline
Vector(const Vector &) = delete; // allocates
void swap(Vector &); // if storage can be swapped
Checked assign(...); // various signatures, including a `const vector &` arg
T& operator[](size_t); // does not allocate, user checks for index validity
T &front(); // does not allocate, user checks for emptiness
T &back(); // ditto
iterator begin(); // and end(), etc.: as usual
Checked reserve(size_t);
Checked resize(size_t);
Checked push_back(); // May allocate
void pop_back(); // Does *NOT* allocate. User checks for emptiness
Checked append(...); // various signatures
void shrink_to_fit(); // Cannot fail. Worst case: we don't shrink
};
Checked just forces a check and it’s expected to be used directly in an if statement: if (!v.fallible_operation(...)) return ENOMEM;
I note the absence of insert/emplace member functions. I have skipped those for two reasons:
- Inserting into the middle of a vector is an expensive operation, and we currently have no need for it.
- Their return type is complicated. We either need a
CheckedIterator,pair<Checked, iterator>or some other way to communicate allocation failure (returning the end iterator is not an option as this can happen even in successful insertions)
Implementation plan
- Add
unique_ptrandCheckedPtr(as a wrapper over the former). - Migrate all/most raw malloc/new calls to
MakeUnique. - Create a
std::vector-like dynamically growing buffer. Handling of non-allocation related details to be done on the PR or (if necessary) with an additional RFC. - Use the class to replace
DynamicBufferand other manual memory management operations. - Adjust
FixedVectorAPI to match the class from the previous step. Possibly make it a special case of the latter. - Create a safe replacement for
cpp::stringandCharVector. This may also require an RFC, or it may be possible to follow the precedents made for the vector type.
Alternatives considered
Use AllocChecker
This is the problem that the AllocChecker class was meant to handle, but the “checking” part never came through. I’m proposing to replace it for two reasons:
- It’s essentially a by-ref return value, which makes it cumbersome to use:
AllocChecker ac;
unique_ptr<T> ptr = make_unique<T>(..., ac);
if (!ac) return ENOMEM;
// or
AllocChecker ac;
v.push_back(..., ac);
if (!ac) return ENOMEM;
- In the make_unique case, there is nothing that guarantees that a successful value implies a non-null result. A broken implementation could return a null pointer while still signaling success through the
AllocChecker(or vice versa).
A generic Checked<T> template
The main question here is how to represent the empty/failure case. If we store it in the template wrapper, then this creates AllocChecker-like ambiguity for types (like unique_ptr – our main use case) which already contain a natural empty state. If we use sentinel T value, then we need some sort of a traits class to determine what that sentinel is – and then use something like Checked<optional<iterator>> (can be simplified with aliases) for types that don’t have a sentinel value. A wrapper would also require some form of a double dereference syntax ((*ptr)->foo(), ptr.value()->foo()) to access the pointed-to value – or more traits to specify which operations can be forwarded by the wrapper.
All of this is solvable, but I think it’s better to start with a focused API and then reevaluate once we gain some experience.
But that’s something we may want to do anyway, as this cannot guarantee graceful handling of the allocation failure. ↩︎
Not all of them have to be implemented, but I’m listing them for completeness ↩︎
Storage type (inline vs. heap vs. small-vector) is irrelevant as we can treat appending to a fixed-size vector as a special kind of an allocation failure ↩︎