Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/pages/guides/safe-c.md
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ size_t length_of(struct object *o) {
}
```

**Contexts and containers of `void *`.** `struct server *s = context;` asks the runtime whether a `struct server` is at `context`; a wrong one stops with `bad-cast`, which names the type of the block that is there. `container_of` (a pointer to a member, less the member's offset) is checked the same way. Every block of the runtime's heap knows the type its allocation named, and so does every global and every local of a safe function whose address becomes a `void *`; memory with no record is believed, and `WEAVEC_RT_STATS=1` counts those conversions.
**Contexts and containers of `void *`.** `struct server *s = context;` asks the runtime whether a `struct server` is at `context`; a wrong one stops with `bad-cast`, which names the type of the block that is there. `container_of` (a pointer to a member, less the member's offset) is checked the same way. Every block of the runtime's heap knows the type its allocation named, and so does every global and every local of a safe function whose address becomes a `void *`; memory with no record is believed, and `WEAVEC_RT_STATS=1` counts those conversions. The converted pointer is bounded by the objects of its type the runtime finds from it: the rest of an array of the type, so a block grown through a `void *` (`void *g = realloc(items, n * sizeof *items); struct item *grown = g;`) is read to its new last element, and one object anywhere else.

## Converting a module

Expand Down
32 changes: 32 additions & 0 deletions docs/rfcs/0054-one-of-several-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -897,6 +897,38 @@ building it and from what S0 and the gates found. They override the body.
audit's.
21. **Reports name a block's type** wherever they describe a heap block,
in text and in JSON (`"type"`), not only after `bad-cast`.
22. **What a checked conversion gives is bounded by what the records show
(§2.1, amends amendment 2).** One object of the target's size is what
the fast mode believes and what an access at a constant offset needs no
check inside, but the root's bound is the run of objects of the target's
type that follow one another from the pointer, as the record of what
holds it shows: `__weavec_rt_cast` returns it, and the marker is
`__weavec.object(pointer, size, extent)`. The run reaches the end of a
heap block, global or recorded local that is an array of the type (its
size a multiple of the type's) from an element's start, and the last
element of an array member of that type; a plain scalar over a plain
object runs whole elements to the end; a block with no type that takes
the conversion's (amendment 14) is an array of it when its size is a
multiple of the type's. Everything else is one object: a member that is
not an array, a record nested in each element of an array member (the
element's other members lie between its copies, and the part's stride
is the element's), a header with data after it, memory with no record (a
believed conversion), a null pointer, and a polymorphic downcast, which
reads a vtable and not a record. The bound is not narrowed by the
operand's: what a conversion gives is a root of its own, as it was, and
every byte of the run is of the target's type, so a pointer loaded from
it is one that typed memory keeps. A local's declaration states no bound
(RFC 0042 gives it its value's), and the checker lets a converted
allocation be indexed (`index-single`), so one object stopped a program
the rules accept: `void *g = realloc(p, 7 * sizeof *p); struct b *q =
g;` stopped with `pointer-out-of-bounds` at `q[6]`, in every build
(RFC 0055's adversarial round, G10). A pointer the checker sees as one
object (a `void *` parameter's, a comparator's) still cannot be
indexed. `WEAVEC_RT_ABI` is 51 (the entry point returns a value);
pinned by `test/Guards/cast-extent.c`, `ir-cast.c`, cases
`test/cases/sum/cast-grown*.c` (`nested` stops at the second copy,
`scalars` past a `long` array member beside a pointer, which the
layout records as a part for this) and `rt_test` `type-at-run`.

## Measured gates

Expand Down
8 changes: 6 additions & 2 deletions lib/Frontend/GuardPassImpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -611,10 +611,14 @@ bool arrayNew(const llvm::CallBase &call);
void expandTypeMarkers(ModuleContext &module, llvm::Function &function);
/// Clang's declarations of the markers, once none is called.
void dropTypeMarkerDeclarations(const llvm::Module &ir);
/// §2.2: what a checked conversion gives, `__weavec.object(p, size)`, is
/// one object of `size` bytes: its size, when `value` is one.
/// §2.2: what a checked conversion gives, `__weavec.object(p, size,
/// extent)`, is one object of `size` bytes: its size, when `value` is one.
[[nodiscard]] std::optional<std::uint64_t>
checkedObject(const llvm::Value &value);
/// Amendment 22: the bytes from a checked object's start that are objects of
/// its type, as the runtime found them (at least `size`); null when `value`
/// is not one.
[[nodiscard]] llvm::Value *checkedExtent(llvm::Value &value);
/// In GuardExpand: the checked objects are their pointers again.
void dropObjects(const llvm::Module &ir);
/// §1.2: a safe function's recorded locals, pushed and popped with their
Expand Down
8 changes: 5 additions & 3 deletions lib/Frontend/GuardSafe.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1217,12 +1217,14 @@ class SafeBounds {
}
auto *call = llvm::cast<llvm::CallInst>(value);
llvm::IRBuilder<> builder(call->getNextNode());
// RFC 0054 §2.2: a checked conversion's object, among the objects of its
// type the runtime found after it (amendment 22); accesses inside the
// one object need no check.
if (const auto size = checkedObject(*call)) {
constantSizes[value] = {.bytes = *size, .mayBeNull = true};
return known[value] = {.lo = call,
.hi = builder.CreateGEP(
module.i8, call,
llvm::ConstantInt::get(module.i64, *size))};
.hi = builder.CreateGEP(module.i8, call,
checkedExtent(*call))};
}
llvm::Value *bytes = nullptr;
const FunctionBounds *callee = calleeBounds(module, *call);
Expand Down
45 changes: 32 additions & 13 deletions lib/Frontend/GuardTypes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@
// class with virtual functions, one comparison of the type information
// its vtable names, and the C++ ABI's dynamic cast when that is not
// equal; else a call of the runtime's `__weavec_rt_cast`. What it gives
// is `__weavec.object(pointer, size)`, one object of the target's size,
// which GuardSafe and the fast mode take as a root until GuardExpand
// removes it (§2.2);
// is `__weavec.object(pointer, size, extent)`, one object of the
// target's size among the `extent` bytes of objects of the type the
// runtime found there (amendment 22), which GuardSafe and the fast mode
// take as a root until GuardExpand removes it (§2.2);
// - each access of a tagged union's member (`__weavec.member`) is
// preceded by a load of the tag and its comparison with the member's
// values (`union-member` when it fails); each store of a tag
Expand Down Expand Up @@ -128,13 +129,14 @@ llvm::GlobalVariable *typeRecord(ModuleContext &module, std::uint64_t key,
return record;
}

/// `ptr __weavec.object(ptr returned, i64 size)`.
/// `ptr __weavec.object(ptr returned, i64 size, i64 extent)`: one object of
/// `size` bytes, among `extent` bytes of objects of its type (amendment 22).
static llvm::FunctionCallee objectMarker(ModuleContext &module) {
llvm::Function *existing = module.module.getFunction(ObjectMarker);
if (existing != nullptr)
return existing;
auto *type =
llvm::FunctionType::get(module.ptr, {module.ptr, module.i64}, false);
auto *type = llvm::FunctionType::get(
module.ptr, {module.ptr, module.i64, module.i64}, false);
auto *function = llvm::Function::Create(
type, llvm::GlobalValue::ExternalLinkage, ObjectMarker, module.module);
function->setDoesNotThrow();
Expand Down Expand Up @@ -242,7 +244,12 @@ class Expansion {
module.i64, -static_cast<std::int64_t>(
record.delta))));
llvm::Constant *site = module.site(location, 0);
llvm::Constant *one = llvm::ConstantInt::get(module.i64, size);
// Amendment 22: the bytes of objects of the type from the object's start,
// as the runtime's records show them; one object where nothing asks them.
llvm::Value *extent = one;
{
llvm::BasicBlock *head = call.getParent();
llvm::Instruction *then = llvm::SplitBlockAndInsertIfThen(
builder.CreateNot(isNull), call.getIterator(), false);
llvm::IRBuilder<> check(then);
Expand Down Expand Up @@ -294,18 +301,22 @@ class Expansion {
{module.ptr, module.ptr, module.ptr}, false)),
{object, layout, site});
} else {
check.CreateCall(
module.runtime("cast",
llvm::FunctionType::get(
llvm::Type::getVoidTy(module.context),
{module.ptr, module.ptr, module.ptr}, false)),
llvm::Value *bytes = check.CreateCall(
module.runtime(
"cast",
llvm::FunctionType::get(
module.i64, {module.ptr, module.ptr, module.ptr}, false)),
{object, layout, site});
llvm::IRBuilder<> join(&call.getParent()->front());
llvm::PHINode *phi = join.CreatePHI(module.i64, 2);
phi->addIncoming(one, head);
phi->addIncoming(bytes, then->getParent());
extent = phi;
}
}
builder.SetInsertPoint(&call);
llvm::Value *checked =
builder.CreateCall(objectMarker(module),
{object, llvm::ConstantInt::get(module.i64, size)});
builder.CreateCall(objectMarker(module), {object, one, extent});
// What the code had: the pointer it converted, now derived from the
// checked object.
llvm::Value *given =
Expand Down Expand Up @@ -513,6 +524,14 @@ void dropObjects(const llvm::Module &ir) {
marker->eraseFromParent();
}

llvm::Value *checkedExtent(llvm::Value &value) {
const auto *call = llvm::dyn_cast<llvm::CallInst>(&value);
if (call == nullptr || call->getCalledFunction() == nullptr ||
call->getCalledFunction()->getName() != ObjectMarker)
return nullptr;
return call->getArgOperand(2);
}

std::optional<std::uint64_t> checkedObject(const llvm::Value &value) {
const auto *call = llvm::dyn_cast<llvm::CallInst>(&value);
if (call == nullptr || call->getCalledFunction() == nullptr ||
Expand Down
11 changes: 11 additions & 0 deletions lib/Frontend/SafeTypes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -593,6 +593,17 @@ void TypeLayouts::flatten(clang::QualType type, std::uint64_t offset,
static_cast<std::uint32_t>(
ast.getTypeSizeInChars(array->getElementType()).getQuantity()),
static_cast<std::uint32_t>(array->getZExtSize()), flags | inside);
} else if (array != nullptr && stride == 0 &&
(element->isArithmeticType() || element->isEnumeralType())) {
// An array member of a scalar: a conversion to its element at one of
// its elements runs to its last (amendment 22).
out.parts.push_back(
{.identity = identityOf(element),
.offset = static_cast<std::uint32_t>(at),
.stride = static_cast<std::uint32_t>(
ast.getTypeSizeInChars(element).getQuantity()),
.elements = static_cast<std::uint32_t>(array->getZExtSize()),
.flags = flags | inside});
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion resources/safe/rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ A pointer converts to another pointer type in one of two ways. The forms that pi
- `container_of`: `(struct d *)((char *)m - offsetof(struct d, f))` with `m` a pointer to the type of `f`;
- a `void *` to a pointer to a scalar that is not a pointer or a `bool` (`int *`, `unsigned char *`): the object must hold no pointer.

What the conversion gives is a pointer to one object, with the bound and the ownership its declaration states. A struct taken as its first member (`&circle->base`, or `(struct shape *)circle`) needs no check.
What the conversion gives is a pointer to one object, with the bound and the ownership its declaration states; where its value is an allocation, the elements of the type the runtime finds there from the pointer, the rest of an array of the type, so `void *g = realloc(p, n * sizeof *p); struct item *q = g;` reads `q[n - 1]`. A struct taken as its first member (`&circle->base`, or `(struct shape *)circle`) needs no check.

Every other conversion is rejected, because it could forge a pointer: memory that holds pointers converts to nothing but `void` and `const` bytes; a struct converts to no unrelated struct; function pointers do not convert. An allocation that becomes a `T *` is sized by `T` when its size names a type (`malloc(sizeof *p)`, `calloc(n, sizeof(struct node))`), since its block is reused for the type its size names; bytes of a type without pointers may be any such type's (`char *b = malloc(sizeof(struct header) + n)`).

Expand Down
138 changes: 138 additions & 0 deletions runtime/test/rt_test.c
Original file line number Diff line number Diff line change
Expand Up @@ -2217,6 +2217,143 @@ static void testTypeAtArray(void) {
free(castBlock);
}

/* `struct cell { struct circle c; char *p; }` (24 bytes) and `struct row {
* struct cell cells[2]; }`, flattened as a unit gives them: the circle in
* each cell has the cell's stride. */
struct TestLayout4 {
struct __weavec_rt_layout head;
struct __weavec_rt_part parts[4];
};
static char cellName[] = "struct cell";
static char rowName[] = "struct row";
static struct TestLayout4 cellLayout;
static struct TestLayout4 rowLayout;
static struct __weavec_rt_type rowType = {0x6107, 0, &rowLayout.head, 0};

static void makeRowLayouts(void) {
static int made;
if (made)
return;
made = 1;
cellLayout.head.identity = 0x5106;
cellLayout.head.size = 24;
cellLayout.head.count = 3;
cellLayout.head.name =
(int64_t)((intptr_t)cellName - (intptr_t)&cellLayout.head.name);
cellLayout.parts[0].identity = 0x5102;
cellLayout.parts[0].elements = 1;
cellLayout.parts[1].identity = 0x5101;
cellLayout.parts[1].elements = 1;
cellLayout.parts[2].offset = 16;
cellLayout.parts[2].elements = 1;
cellLayout.parts[2].flags = WeavecRtPartPointer;
rowLayout.head.identity = 0x5107;
rowLayout.head.size = 48;
rowLayout.head.count = 4;
rowLayout.head.name =
(int64_t)((intptr_t)rowName - (intptr_t)&rowLayout.head.name);
rowLayout.parts[0].identity = 0x5106;
rowLayout.parts[0].stride = 24;
rowLayout.parts[0].elements = 2;
rowLayout.parts[1].identity = 0x5102;
rowLayout.parts[1].stride = 24;
rowLayout.parts[1].elements = 2;
rowLayout.parts[2].identity = 0x5101;
rowLayout.parts[2].stride = 24;
rowLayout.parts[2].elements = 2;
rowLayout.parts[3].offset = 16;
rowLayout.parts[3].stride = 24;
rowLayout.parts[3].elements = 2;
rowLayout.parts[3].flags = WeavecRtPartPointer;
}

/* `struct tally { long xs[4]; char *p; }`: an array member of a scalar
* beside a pointer. */
static char tallyName[] = "struct tally";
static struct TestLayout4 tallyLayout;
static struct __weavec_rt_type tallyType = {0x6108, 0, &tallyLayout.head, 0};

static void makeTallyLayout(void) {
static int made;
if (made)
return;
made = 1;
tallyLayout.head.identity = 0x5108;
tallyLayout.head.size = 40;
tallyLayout.head.count = 2;
tallyLayout.head.name =
(int64_t)((intptr_t)tallyName - (intptr_t)&tallyLayout.head.name);
tallyLayout.parts[0].identity = 0x5104;
tallyLayout.parts[0].stride = 8;
tallyLayout.parts[0].elements = 4;
tallyLayout.parts[1].offset = 32;
tallyLayout.parts[1].elements = 1;
tallyLayout.parts[1].flags = WeavecRtPartPointer;
}

static void testTypeAtRun(void) {
/* Amendment 22: a conversion is told the bytes of objects of its type that
* follow one another from the pointer, to the end of an array of the type;
* one object of a member, and of memory with no record. */
long local[4];
makeLayouts();
castBlock = opaque(malloc(64));
__weavec_rt_note_type(castBlock, &circleType);
CHECK(__weavec_rt_cast(castBlock, &circleLayout.head, &trapSite) == 64);
CHECK(__weavec_rt_cast((char *)castBlock + 32, &circleLayout.head,
&trapSite) == 32);
CHECK(__weavec_rt_cast(castBlock, &shapeLayout, &trapSite) == 4);
free(castBlock);
/* A header with data after it: one object. */
castBlock = opaque(malloc(24));
__weavec_rt_note_type(castBlock, &circleType);
CHECK(__weavec_rt_cast(castBlock, &circleLayout.head, &trapSite) == 16);
free(castBlock);
/* A block with no type takes the conversion's, as an array when its size
* is a multiple of the type's. */
castBlock = opaque(malloc(48));
CHECK(__weavec_rt_cast(castBlock, &squareLayout.head, &trapSite) == 48);
CHECK(__weavec_rt_cast((char *)castBlock + 16, &squareLayout.head,
&trapSite) == 32);
free(castBlock);
castBlock = opaque(malloc(40));
CHECK(__weavec_rt_cast(castBlock, &squareLayout.head, &trapSite) == 16);
free(castBlock);
/* A plain scalar: whole elements to the block's end. */
castBlock = opaque(malloc(24));
CHECK(__weavec_rt_cast(castBlock, &longLayout, &trapSite) == 24);
CHECK(__weavec_rt_cast((char *)castBlock + 8, &longLayout, &trapSite) ==
16);
free(castBlock);
/* A scalar in a struct beside a pointer: one. */
castBlock = opaque(malloc(32));
__weavec_rt_note_type(castBlock, &holderType);
CHECK(__weavec_rt_cast(castBlock, &longLayout, &trapSite) == 8);
free(castBlock);
/* No record: believed, one object. */
CHECK(__weavec_rt_cast(opaque(local), &circleLayout.head, &trapSite) == 16);
/* An array member of cells, each a circle and a pointer: the cells follow
* one another, the circles in them do not (one object). */
makeRowLayouts();
castBlock = opaque(malloc(48));
__weavec_rt_note_type(castBlock, &rowType);
CHECK(__weavec_rt_cast(castBlock, &cellLayout.head, &trapSite) == 48);
CHECK(__weavec_rt_cast((char *)castBlock + 24, &cellLayout.head,
&trapSite) == 24);
CHECK(__weavec_rt_cast(castBlock, &circleLayout.head, &trapSite) == 16);
CHECK(__weavec_rt_cast((char *)castBlock + 24, &circleLayout.head,
&trapSite) == 16);
free(castBlock);
/* A scalar array member beside a pointer: to its last element. */
makeTallyLayout();
castBlock = opaque(malloc(40));
__weavec_rt_note_type(castBlock, &tallyType);
CHECK(__weavec_rt_cast(castBlock, &longLayout, &trapSite) == 32);
CHECK(__weavec_rt_cast((char *)castBlock + 16, &longLayout, &trapSite) ==
16);
free(castBlock);
}

static void castMiddle(void) {
__weavec_rt_cast((char *)castBlock + 8, &circleLayout.head, &trapSite);
}
Expand Down Expand Up @@ -2335,6 +2472,7 @@ static const struct {
{"heap-stacks", testHeapStacks},
{"type-at-heap", testTypeAtHeap},
{"type-at-array", testTypeAtArray},
{"type-at-run", testTypeAtRun},
{"type-at-untyped", testTypeAtUntyped},
{"frame-records", testFrameRecords},
{"union-member", testUnionMember},
Expand Down
Loading
Loading