diff --git a/docs/pages/guides/safe-c.md b/docs/pages/guides/safe-c.md index d2303db..0a41ee9 100644 --- a/docs/pages/guides/safe-c.md +++ b/docs/pages/guides/safe-c.md @@ -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 diff --git a/docs/rfcs/0054-one-of-several-types.md b/docs/rfcs/0054-one-of-several-types.md index 706657a..b98dce7 100644 --- a/docs/rfcs/0054-one-of-several-types.md +++ b/docs/rfcs/0054-one-of-several-types.md @@ -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 diff --git a/lib/Frontend/GuardPassImpl.h b/lib/Frontend/GuardPassImpl.h index 2360eaf..06e3f2f 100644 --- a/lib/Frontend/GuardPassImpl.h +++ b/lib/Frontend/GuardPassImpl.h @@ -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 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 diff --git a/lib/Frontend/GuardSafe.cpp b/lib/Frontend/GuardSafe.cpp index 53b0b22..fdc2bbe 100644 --- a/lib/Frontend/GuardSafe.cpp +++ b/lib/Frontend/GuardSafe.cpp @@ -1217,12 +1217,14 @@ class SafeBounds { } auto *call = llvm::cast(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); diff --git a/lib/Frontend/GuardTypes.cpp b/lib/Frontend/GuardTypes.cpp index 3aa914a..f6b62da 100644 --- a/lib/Frontend/GuardTypes.cpp +++ b/lib/Frontend/GuardTypes.cpp @@ -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 @@ -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(); @@ -242,7 +244,12 @@ class Expansion { module.i64, -static_cast( 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); @@ -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 = @@ -513,6 +524,14 @@ void dropObjects(const llvm::Module &ir) { marker->eraseFromParent(); } +llvm::Value *checkedExtent(llvm::Value &value) { + const auto *call = llvm::dyn_cast(&value); + if (call == nullptr || call->getCalledFunction() == nullptr || + call->getCalledFunction()->getName() != ObjectMarker) + return nullptr; + return call->getArgOperand(2); +} + std::optional checkedObject(const llvm::Value &value) { const auto *call = llvm::dyn_cast(&value); if (call == nullptr || call->getCalledFunction() == nullptr || diff --git a/lib/Frontend/SafeTypes.cpp b/lib/Frontend/SafeTypes.cpp index be066a7..457b1bf 100644 --- a/lib/Frontend/SafeTypes.cpp +++ b/lib/Frontend/SafeTypes.cpp @@ -593,6 +593,17 @@ void TypeLayouts::flatten(clang::QualType type, std::uint64_t offset, static_cast( ast.getTypeSizeInChars(array->getElementType()).getQuantity()), static_cast(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(at), + .stride = static_cast( + ast.getTypeSizeInChars(element).getQuantity()), + .elements = static_cast(array->getZExtSize()), + .flags = flags | inside}); } } } diff --git a/resources/safe/rules.md b/resources/safe/rules.md index 3110c15..a270a28 100644 --- a/resources/safe/rules.md +++ b/resources/safe/rules.md @@ -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)`). diff --git a/runtime/test/rt_test.c b/runtime/test/rt_test.c index 937c3d8..33cee13 100644 --- a/runtime/test/rt_test.c +++ b/runtime/test/rt_test.c @@ -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); } @@ -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}, diff --git a/runtime/weavec_rt.h b/runtime/weavec_rt.h index e8523c4..f766fc9 100644 --- a/runtime/weavec_rt.h +++ b/runtime/weavec_rt.h @@ -336,10 +336,13 @@ WEAVEC_RT_API void __weavec_rt_note_type(const void *block, struct __weavec_rt_type *type); /* RFC 0054 section 2.2: a safe function converts a pointer to `address` * into a pointer to `target`: `bad-cast` unless an object of that type is - * there, or the memory has no record of its type (believed). */ -WEAVEC_RT_API void __weavec_rt_cast(const void *address, - const struct __weavec_rt_layout *target, - const struct __weavec_rt_site *site); + * there, or the memory has no record of its type (believed). Returns the + * bytes from `address` that are objects of `target` one after another, as + * the record of what holds it shows: the rest of an array of the type, or + * one object (amendment 22). */ +WEAVEC_RT_API uint64_t __weavec_rt_cast(const void *address, + const struct __weavec_rt_layout *target, + const struct __weavec_rt_site *site); /* The C++ downcast's check failed (the class's own test said no). */ WEAVEC_RT_API void __weavec_rt_cast_fail(const void *address, const struct __weavec_rt_layout *target, @@ -1008,7 +1011,7 @@ void weavecRtSymbolize(const uintptr_t *pcs, unsigned count, /* The library's interface version (libweavec_rt.so., * libweavec_rt..dylib), raised whenever an entry point, the shadow * encoding or a site record changes. */ -#define WEAVEC_RT_ABI 50 +#define WEAVEC_RT_ABI 51 /*===-- Internal -----------------------------------------------------------===*/ diff --git a/runtime/weavec_types.c b/runtime/weavec_types.c index ddbe0a7..f3f37ff 100644 --- a/runtime/weavec_types.c +++ b/runtime/weavec_types.c @@ -203,9 +203,6 @@ static const struct FrameRecord *recordAt(uintptr_t address) { enum Answer { No, Yes, Believed }; -/* Whether an object of `target` is `offset` bytes into an object of - * `object`, which holds `extent` bytes from that object's start (an array - * of it, when larger). */ /* Whether a pointer of `object`'s own bytes overlaps [offset, end). */ static int coversPointer(const struct __weavec_rt_layout *object, uint64_t offset, uint64_t end) { @@ -224,9 +221,16 @@ static int coversPointer(const struct __weavec_rt_layout *object, return 0; } +/* Whether an object of `target` is `offset` bytes into an object of + * `object`, which holds `extent` bytes from that object's start (an array + * of it, when larger); when it is, `*run` may be set to the bytes from there + * that are objects of `target` one after another (amendment 22). */ static enum Answer objectHolds(const struct __weavec_rt_layout *object, uint64_t offset, uint64_t extent, - const struct __weavec_rt_layout *target) { + const struct __weavec_rt_layout *target, + uint64_t *run) { + const uint64_t start = offset; + uint64_t limit = extent; uint32_t i; if (target->size != 0 && offset + target->size > extent) return No; @@ -236,16 +240,25 @@ static enum Answer objectHolds(const struct __weavec_rt_layout *object, if (object->size != 0 && offset >= object->size && extent % object->size != 0) return Believed; + /* Amendment 22: the bytes the record describes, from which the objects of + * `target` that follow one another at `start` are counted. */ + if (object->size != 0 && extent % object->size != 0) + limit = object->size; if (object->size != 0) offset %= object->size; - if (offset == 0 && object->identity == target->identity) + if (offset == 0 && object->identity == target->identity) { + *run = limit - start; return Yes; - /* Section 2.1 (d): a plain scalar views bytes where no pointer is. */ + } + /* Section 2.1 (d): a plain scalar views bytes where no pointer is; over a + * plain object, whole elements to the end. */ if ((target->flags & WeavecRtLayoutScalar) != 0 && (target->flags & WeavecRtLayoutPlain) != 0 && - ((object->flags & WeavecRtLayoutPlain) != 0 || - !coversPointer(object, offset, offset + target->size))) + (object->flags & WeavecRtLayoutPlain) != 0) { + if (target->size != 0) + *run = (limit - start) / target->size * target->size; return Yes; + } for (i = 0; i < object->count; ++i) { const struct __weavec_rt_part *part = &object->parts[i]; uint64_t at; @@ -256,15 +269,31 @@ static enum Answer objectHolds(const struct __weavec_rt_layout *object, at = offset - part->offset; if (part->stride == 0 ? at == 0 : at % part->stride == 0 && - at / part->stride < part->elements) + at / part->stride < part->elements) { + /* An array member's elements, from this one to its last, when they + * follow one another. A record nested in each element of an array + * member has the element's stride, with the element's other members + * between: one object of it. */ + if (part->stride != 0 && part->stride == target->size) + *run = (part->elements - at / part->stride) * part->stride; return Yes; + } } + /* Over an object that holds pointers, a plain scalar that is not in an + * array member of its type (above) is one. */ + if ((target->flags & WeavecRtLayoutScalar) != 0 && + (target->flags & WeavecRtLayoutPlain) != 0 && + !coversPointer(object, offset, offset + target->size)) + return Yes; return No; } -/* The answer for `address`, and the layout of what holds it, if any. */ +/* The answer for `address`. `*run` is left as one object of `target`, or + * set to the bytes from `address` that the record of what holds it shows + * to be objects of `target`, one after another (amendment 22). */ static enum Answer answer(uintptr_t address, - const struct __weavec_rt_layout *target) { + const struct __weavec_rt_layout *target, + uint64_t *run) { struct weavecRtHeapObject block = weavecRtHeapObjectAt(address); if (block.found) { const struct __weavec_rt_layout *object = weavecRtTypeLayout(block.type); @@ -279,11 +308,15 @@ static enum Answer answer(uintptr_t address, const uint32_t index = weavecRtTypeIndex(target); if (index != 0) weavecRtSetBlockType(block.base, index); + /* It now holds an array of the type when its size is a multiple of + * the type's, as objectHolds reads a typed block. */ + if (index != 0 && target->size != 0 && block.size % target->size == 0) + *run = block.size; return Yes; } return Believed; } - return objectHolds(object, offset, block.size, target); + return objectHolds(object, offset, block.size, target, run); } { const struct __weavec_rt_global *global = weavecRtGlobalAt(address); @@ -297,7 +330,7 @@ static enum Answer answer(uintptr_t address, if (object == NULL) return Believed; return objectHolds(object, address - global->address, global->size, - target); + target, run); } } { @@ -308,7 +341,7 @@ static enum Answer answer(uintptr_t address, const struct FrameRecord *record = recordAt(address); if (record != NULL) return objectHolds(record->layout, address - record->address, - record->size, target); + record->size, target, run); } } return Believed; @@ -325,18 +358,22 @@ badCast(const void *address, const struct __weavec_rt_layout *target, weavecRtFailTyped("bad-cast", message, (uintptr_t)address, site); } -void __weavec_rt_cast(const void *address, - const struct __weavec_rt_layout *target, - const struct __weavec_rt_site *site) { +uint64_t __weavec_rt_cast(const void *address, + const struct __weavec_rt_layout *target, + const struct __weavec_rt_site *site) { enum Answer result; + uint64_t run; if (address == NULL || target == NULL) - return; + return target != NULL ? target->size : 0; + run = target->size; weavecRtCount(WeavecRtStatCasts); - result = answer((uintptr_t)address, target); + result = answer((uintptr_t)address, target, &run); if (result == Believed) weavecRtCount(WeavecRtStatBelieved); else if (result == No) badCast(address, target, site); + /* Never less than the one object the conversion gives (section 2.1). */ + return result == Yes && run > target->size ? run : target->size; } void __weavec_rt_cast_fail(const void *address, diff --git a/test/Guards/cast-extent.c b/test/Guards/cast-extent.c new file mode 100644 index 0000000..ae2958b --- /dev/null +++ b/test/Guards/cast-extent.c @@ -0,0 +1,46 @@ +// RFC 0054 §2.2, amendment 22: a safe C function's pointer converted from a +// `void *` is bounded by the objects of its type the runtime finds from it, +// the rest of an array of the type. A block `calloc` made for 6 elements and +// `realloc` grew to 7 through a `void *` is read at element 6 in the fast, +// the checked and the unoptimized build; a read at element 7, past the new +// size, stops with `pointer-out-of-bounds`. +// RUN: %weavec_cc -O2 -fweavec-safe %s -o %t.fast +// RUN: %weavec_cc -O2 -fweavec-safe -fweavec-safe-checks=full %s -o %t.full +// RUN: %weavec_cc -O0 -fweavec-safe %s -o %t.O0 +// RUN: %t.fast 6 | FileCheck %s --check-prefix=OK +// RUN: %t.full 6 | FileCheck %s --check-prefix=OK +// RUN: %t.O0 6 | FileCheck %s --check-prefix=OK +// RUN: not --crash %t.fast 7 2>&1 | FileCheck %s --check-prefix=PAST +// RUN: not --crash %t.full 7 2>&1 | FileCheck %s --check-prefix=PAST +// RUN: not --crash %t.O0 7 2>&1 | FileCheck %s --check-prefix=PAST +#include +#include +#include + +struct b { long n; long m; }; + +__attribute__((noinline)) long grow(int i) { + struct b *WEAVEC_OWNED bs = calloc(6, sizeof *bs); + if (bs == NULL) + return -1; + void *WEAVEC_OWNED g = realloc(bs, 7 * sizeof *bs); + if (g == NULL) { + free(bs); + return -1; + } + struct b *WEAVEC_OWNED ds = g; + ds[6].n = 42; + long v = ds[i].n; + free(ds); + return v; +} + +WEAVEC_GUARDED int main(int argc, char **argv) { + if (argc < 2) + return 1; + printf("grow %ld\n", grow(atoi(argv[1]))); + return 0; +} +// OK: grow 42 +// PAST: weavec: pointer-out-of-bounds at {{.*}}cast-extent.c:[[@LINE-12]]:18: read of 8 bytes at 0x{{[0-9a-f]+}} +// PAST: weavec: 0x{{[0-9a-f]+}} is 0 bytes after the 112-byte bounds of the pointer at 0x{{[0-9a-f]+}} diff --git a/test/Guards/ir-cast.c b/test/Guards/ir-cast.c index dd44d8e..d024721 100644 --- a/test/Guards/ir-cast.c +++ b/test/Guards/ir-cast.c @@ -16,7 +16,7 @@ struct circle { struct shape base; double radius; }; // CHECK-LABEL: define {{.*}} @radius{{(.weavec.safe)?}}( // CHECK: %[[NULL:[0-9]+]] = icmp eq ptr %s, null -// CHECK: call void @__weavec_rt_cast(ptr %s, ptr @[[CIRCLE]], ptr @__weavec.site +// CHECK: call i64 @__weavec_rt_cast(ptr %s, ptr @[[CIRCLE]], ptr @__weavec.site // CHECK-NOT: __weavec.object // CHECK: ret double // OFF-LABEL: define {{.*}} @radius{{(.weavec.safe)?}}( @@ -38,3 +38,21 @@ WEAVEC_SAFE double record(void) { // CHECK: %[[BLOCK:[^ ]*]] = call {{.*}}ptr @calloc( // CHECK-NEXT: call void @__weavec_rt_note_type(ptr %[[BLOCK]], ptr @[[TYPE]]) struct circle *make(void) { return calloc(1, sizeof(struct circle)); } + +// Amendment 22: what a conversion gives is bounded by the bytes of objects of +// its type the runtime found from the pointer (one object for null), so an +// allocation's elements stay readable through a `void *`. +// CHECK-LABEL: define {{.*}} @element{{(.weavec.safe)?}}( +// CHECK: %[[FOUND:[0-9]+]] = call i64 @__weavec_rt_cast(ptr %[[BLOCK:[^,]+]], ptr @[[CIRCLE]], ptr @__weavec.site +// CHECK: %[[EXTENT:[0-9]+]] = phi i64 [ 16, %{{[^ ]+}} ], [ %[[FOUND]], %{{[0-9]+}} ] +// CHECK: %[[END:[0-9]+]] = getelementptr i8, ptr %[[BLOCK]], i64 %[[EXTENT]] +// CHECK: %[[HI:[0-9]+]] = ptrtoint ptr %[[END]] to i64 +// CHECK: call preserve_allcc void @__weavec_rt_bounds_fail(i64 %{{[0-9]+}}, i64 8, i64 %{{[0-9]+}}, i64 %{{[0-9]+}}, ptr +// CHECK: ret double +WEAVEC_SAFE double element(int n, int i) { + void *WEAVEC_OWNED v = calloc(n, sizeof(struct circle)); + struct circle *WEAVEC_OWNED c = v; + double r = c[i].radius; + free(c); + return r; +} diff --git a/test/Guards/ir-cast.cpp b/test/Guards/ir-cast.cpp index faa55ab..607b884 100644 --- a/test/Guards/ir-cast.cpp +++ b/test/Guards/ir-cast.cpp @@ -26,9 +26,9 @@ struct Wide : Plain { long a = 0; }; double radius(const Shape &shape) { return static_cast(shape).r; } // CHECK-LABEL: define {{.*}} @_Z4wideP5Plain( -// CHECK: call void @__weavec_rt_cast(ptr {{.*}}, ptr nonnull @__weavec.layout.{{[0-9A-F]+}}, ptr nonnull @__weavec.site +// CHECK: call i64 @__weavec_rt_cast(ptr {{.*}}, ptr nonnull @__weavec.layout.{{[0-9A-F]+}}, ptr nonnull @__weavec.site long wide(Plain *p) { return static_cast(p)->a; } // CHECK-LABEL: define {{.*}} @_Z5ticksPv( -// CHECK: call void @__weavec_rt_cast( +// CHECK: call i64 @__weavec_rt_cast( long ticks(void *context) { return static_cast(context)->a; } diff --git a/test/Guards/report-json.c b/test/Guards/report-json.c index 57cd7c6..e56d044 100644 --- a/test/Guards/report-json.c +++ b/test/Guards/report-json.c @@ -12,6 +12,6 @@ int main(void) { free(p); return sink[2]; } -// CHECK: {"weavec":50,"kind":"heap-use-after-free","proven":false,"site":{"file":"{{.*}}report-json.c","line":13,"column":{{[0-9]+}}},"what":"read of 1 bytes at 0x{{[0-9a-f]+}}","access":{"op":"read","width":1,"address":"0x{{[0-9a-f]+}}"},"thread":{"id":0},"stack":[{"pc":"0x{{[0-9a-f]+}}","module":"{{.*}}","offset":"0x{{[0-9a-f]+}}","function":"main","file":"{{.*}}report-json.c","line":13, +// CHECK: {"weavec":51,"kind":"heap-use-after-free","proven":false,"site":{"file":"{{.*}}report-json.c","line":13,"column":{{[0-9]+}}},"what":"read of 1 bytes at 0x{{[0-9a-f]+}}","access":{"op":"read","width":1,"address":"0x{{[0-9a-f]+}}"},"thread":{"id":0},"stack":[{"pc":"0x{{[0-9a-f]+}}","module":"{{.*}}","offset":"0x{{[0-9a-f]+}}","function":"main","file":"{{.*}}report-json.c","line":13, // CHECK-SAME: "object":{"memory":"heap","base":"0x{{[0-9a-f]+}}","size":8{{(,"type":"[^"]*")?}},"state":"released","released":[{"pc":"0x{{[0-9a-f]+}}",{{.*}}"line":12, // CHECK-SAME: "allocated":[{"pc":"0x{{[0-9a-f]+}}",{{.*}}"line":10, diff --git a/test/cases/sum/cast-grown.c b/test/cases/sum/cast-grown.c new file mode 100644 index 0000000..7a46cf7 --- /dev/null +++ b/test/cases/sum/cast-grown.c @@ -0,0 +1,100 @@ +// RFC 0054 §2.2, amendment 22: a pointer converted from a `void *` is +// bounded by the objects of its type the runtime finds there, the rest of an +// array of the type: after `realloc` grows a block to 7 elements through a +// `void *`, a read of element 7 stops, as does a read past an `int` array +// converted the same way, a read past one struct that is only the first +// member of the block's type, and a read of the second copy of a struct +// nested in each element of an array member, which the element's other +// member separates from the first, and a read past a `long` array member +// into the pointer after it. +// FLAGS: -O2 -fweavec-safe +// RUN-INPUT: grown +// RUN-INPUT: ints +// RUN-INPUT: member +// RUN-INPUT: nested +// RUN-INPUT: scalars +#include +#include +#include +#include + +struct b { long n; long m; }; +struct outer { struct b first; long rest[2]; }; +struct cell { struct b c; long y; }; +struct row { struct cell cells[3]; }; +struct tally { long xs[4]; char *p; }; + +__attribute__((noinline)) long grown(int i) { + struct b *WEAVEC_OWNED bs = calloc(6, sizeof *bs); + if (bs == NULL) + return -1; + void *WEAVEC_OWNED g = realloc(bs, 7 * sizeof *bs); + if (g == NULL) { + free(bs); + return -1; + } + struct b *WEAVEC_OWNED ds = g; + long v = ds[i].n; // TRAP: pointer-out-of-bounds + free(ds); + return v; +} + +__attribute__((noinline)) long ints(int i) { + void *WEAVEC_OWNED g = calloc(5, sizeof(int)); + if (g == NULL) + return -1; + int *WEAVEC_OWNED xs = g; + long v = xs[i]; // TRAP: pointer-out-of-bounds + free(xs); + return v; +} + +__attribute__((noinline)) long member(int i) { + struct outer *WEAVEC_OWNED os = calloc(4, sizeof *os); + if (os == NULL) + return -1; + void *WEAVEC_OWNED g = os; + struct b *WEAVEC_OWNED first = g; + long v = first[i].n; // TRAP: pointer-out-of-bounds + free(first); + return v; +} + +__attribute__((noinline)) long nested(int i) { + struct row *WEAVEC_OWNED rs = calloc(1, sizeof *rs); + if (rs == NULL) + return -1; + void *WEAVEC_OWNED g = rs; + struct b *WEAVEC_OWNED c = g; + long v = c[i].n; // TRAP: pointer-out-of-bounds + free(c); + return v; +} + +__attribute__((noinline)) long scalars(int i) { + void *WEAVEC_OWNED g = calloc(1, sizeof(struct tally)); + if (g == NULL) + return -1; + long *WEAVEC_OWNED xs = g; + long v = xs[i]; // TRAP: pointer-out-of-bounds + free(xs); + return v; +} + +WEAVEC_GUARDED int main(int argc, char **argv) { + long v = 0; + if (argc < 2) + return 1; + if (strcmp(argv[1], "grown") == 0) + v = grown(7); + else if (strcmp(argv[1], "ints") == 0) + v = ints(5); + else if (strcmp(argv[1], "member") == 0) + v = member(1); + else if (strcmp(argv[1], "nested") == 0) + v = nested(1); + else if (strcmp(argv[1], "scalars") == 0) + v = scalars(4); + printf("%ld\n", v); + return 0; +} diff --git a/test/cases/sum/cast-grown_ok.c b/test/cases/sum/cast-grown_ok.c new file mode 100644 index 0000000..bb34bbb --- /dev/null +++ b/test/cases/sum/cast-grown_ok.c @@ -0,0 +1,85 @@ +// RFC 0054 §2.2, amendment 22: the twin of cast-grown.c: a block `calloc` +// made for 6 elements and `realloc` grew to 7 through a `void *` is read at +// element 6; an `int` array converted from a `void *` is +// read at its last element; the first struct of a block whose type +// begins with it is read; and so is the first copy of a struct nested in +// each element of an array member, and the last element of a `long` array +// member beside a pointer. +// CLEAN +// FLAGS: -O2 -fweavec-safe +#include +#include +#include + +struct b { long n; long m; }; +struct outer { struct b first; long rest[2]; }; +struct cell { struct b c; long y; }; +struct row { struct cell cells[3]; }; +struct tally { long xs[4]; char *p; }; + +__attribute__((noinline)) long grown(void) { + struct b *WEAVEC_OWNED bs = calloc(6, sizeof *bs); + if (bs == NULL) + return -1; + void *WEAVEC_OWNED g = realloc(bs, 7 * sizeof *bs); + if (g == NULL) { + free(bs); + return -1; + } + struct b *WEAVEC_OWNED ds = g; + ds[6].n = 42; + long v = ds[6].n; + free(ds); + return v; +} + +__attribute__((noinline)) long ints(void) { + void *WEAVEC_OWNED g = calloc(5, sizeof(int)); + if (g == NULL) + return -1; + int *WEAVEC_OWNED xs = g; + xs[4] = 7; + long v = xs[4]; + free(xs); + return v; +} + +__attribute__((noinline)) long member(void) { + struct outer *WEAVEC_OWNED os = calloc(4, sizeof *os); + if (os == NULL) + return -1; + void *WEAVEC_OWNED g = os; + struct b *WEAVEC_OWNED first = g; + long v = first[0].m; + free(first); + return v; +} + +__attribute__((noinline)) long nested(void) { + struct row *WEAVEC_OWNED rs = calloc(1, sizeof *rs); + if (rs == NULL) + return -1; + void *WEAVEC_OWNED g = rs; + struct b *WEAVEC_OWNED c = g; + c[0].m = 5; + long v = c[0].m; + free(c); + return v; +} + +__attribute__((noinline)) long scalars(void) { + void *WEAVEC_OWNED g = calloc(1, sizeof(struct tally)); + if (g == NULL) + return -1; + long *WEAVEC_OWNED xs = g; + xs[3] = 9; + long v = xs[3]; + free(xs); + return v; +} + +WEAVEC_GUARDED int main(void) { + printf("%ld %ld %ld %ld %ld\n", grown(), ints(), member(), nested(), + scalars()); + return 0; +}