repo_name stringlengths 1 62 | dataset stringclasses 1 value | lang stringclasses 11 values | pr_id int64 1 20.1k | owner stringlengths 2 34 | reviewer stringlengths 2 39 | diff_hunk stringlengths 15 262k | code_review_comment stringlengths 1 99.6k |
|---|---|---|---|---|---|---|---|
cheriot-rtos | github_2023 | cpp | 121 | CHERIoT-Platform | nwf-msr | @@ -291,10 +294,70 @@ static uint16_t crc16(MVM_LONG_PTR_TYPE lp, uint16_t size) {
* The `context` passed to these macros is whatever value that the host passes
* to `mvm_restore`. It can be any value that fits in a pointer.
*/
-#define MVM_CONTEXTUAL_MALLOC(size, context) ({ Timeout t = {0, 0}; heap_allocate(&t, context, size); })
+#define MVM_CONTEXTUAL_MALLOC(size, context) \
+ ({ \
+ Timeout t = {0, 0}; \
+ heap_allocate(&t, context, size); \
+ })
#define MVM_CONTEXTUAL_FREE(ptr, context) heap_free(context, ptr)
/**
* Expose the timeout APIs.
*/
#define MVM_GAS_COUNTER
+
+/**
+ * Helper for Microvium to convert strings to integers.
+ */
+__always_inline static int mvm_int_to_string_helper(char buffer[12],
+ int32_t value)
+{
+ char *insert = buffer;
+
+ // If this is negative, add a minus sign and negate it.
+ if (value < 0)
+ {
+ *(insert++) = '-';
+ value = 0 - value;
+ }
+ const char Digits[] = "0123456789";
+ // To skip leading zeroes, write the value backwards into this buffer and
+ // then scan it forward, skipping zeroes, inserting into the output buffer.
+ char tmp[10];
+ for (int i = sizeof(tmp) - 1; i >= 0; i--)
+ {
+ tmp[i] = Digits[value % 10];
+ value /= 10;
+ }
+ bool skipZero = true;
+ for (int i = 0; i < sizeof(tmp); i++)
+ {
+ char c = tmp[i];
+ if (skipZero && (c == '0'))
+ {
+ continue;
+ }
+ skipZero = false;
+ *(insert++) = c;
+ }
+ if (skipZero)
+ {
+ *(insert++) = '0';
+ }
+ return insert - buffer;
+}
+
+#define MVM_INT32TOSTRING(buffer, i) mvm_int_to_string_helper(buffer, i)
+
+/**
+ * Apply bounds to the buffer.
+ */
+#define MVM_POINTER_SET_BOUNDS(ptr, bounds) \
+ __builtin_cheri_bounds_set(ptr, bounds)
+
+/**
+ * Remove all permissions except load and global.
+ *
+ * TODO: This should use symbolic constants, once they're defined in C. | https://github.com/microsoft/cheriot-rtos/blob/65cf11b8a4c07e2fddfc3bb0ba23d9490e3bdbe7/sdk/include/cheri-builtins.h#L7-L18 |
cheriot-rtos | github_2023 | cpp | 121 | CHERIoT-Platform | nwf-msr | @@ -291,10 +294,70 @@ static uint16_t crc16(MVM_LONG_PTR_TYPE lp, uint16_t size) {
* The `context` passed to these macros is whatever value that the host passes
* to `mvm_restore`. It can be any value that fits in a pointer.
*/
-#define MVM_CONTEXTUAL_MALLOC(size, context) ({ Timeout t = {0, 0}; heap_allocate(&t, context, size); })
+#define MVM_CONTEXTUAL_MALLOC(size, context) \
+ ({ \
+ Timeout t = {0, 0}; \
+ heap_allocate(&t, context, size); \
+ })
#define MVM_CONTEXTUAL_FREE(ptr, context) heap_free(context, ptr)
/**
* Expose the timeout APIs.
*/
#define MVM_GAS_COUNTER
+
+/**
+ * Helper for Microvium to convert strings to integers.
+ */
+__always_inline static int mvm_int_to_string_helper(char buffer[12], | Why `__always_inline`? Single call site? |
cheriot-rtos | github_2023 | cpp | 121 | CHERIoT-Platform | nwf-msr | @@ -291,10 +294,70 @@ static uint16_t crc16(MVM_LONG_PTR_TYPE lp, uint16_t size) {
* The `context` passed to these macros is whatever value that the host passes
* to `mvm_restore`. It can be any value that fits in a pointer.
*/
-#define MVM_CONTEXTUAL_MALLOC(size, context) ({ Timeout t = {0, 0}; heap_allocate(&t, context, size); })
+#define MVM_CONTEXTUAL_MALLOC(size, context) \
+ ({ \
+ Timeout t = {0, 0}; \ | I realize this hunk is just reformatting, but...
Should this tie into the "gas counter" below somehow? I know that counts in units of VM instructions, and maybe we want to consider `malloc` to be O(1) within a VM instruction, so perhaps not, but OTOH maybe we want to tell `malloc` to give up after `gas_left * rough_time_per_vm_instr` time? |
cheriot-rtos | github_2023 | cpp | 120 | CHERIoT-Platform | rmn30 | @@ -58,7 +58,11 @@ compartment_error_handler(ErrorState *frame, size_t mcause, size_t mtval)
frame->get_register_value<CHERI::RegisterNumber::CRA>()};
if (registerNumber == CHERI::RegisterNumber::CRA &&
returnCapability.address() == 0 &&
+ // Ibex currently has a bug with exception priorities and so
+ // reports these with the wrong error code. | ```suggestion
// reports these with the wrong error code, therefore relax the condition a bit.
``` |
cheriot-rtos | github_2023 | others | 113 | CHERIoT-Platform | nwf-msr | @@ -234,8 +242,10 @@ SECTIONS
@software_revoker_header@
- # Magic number
- LONG(0x43f6af90);
+ # Magic number.
+ # New versions of this can be generated with:
+ # head /dev/random | shasum | cut -c 0-8 | While you're adding commentary, xref `sdk/core/loader/types.h:/is_magic_valid`? |
cheriot-rtos | github_2023 | others | 106 | CHERIoT-Platform | nwf-msr | @@ -13,6 +15,10 @@
# error Memory map was not configured with a revoker device
#endif
+DECLARE_AND_DEFINE_INTERRUPT_CAPABILITY(revokerInterruptCapability,
+ RevokerInterrupt, | We expect this to come in from the `board.json`? |
cheriot-rtos | github_2023 | cpp | 106 | CHERIoT-Platform | nwf-msr | @@ -129,6 +129,65 @@ namespace
return (Capability{timeout}.is_valid() && timeout->may_block());
}
+ template<typename T = Revocation::Revoker>
+ bool wait_for_background_revoker(
+ Timeout *timeout,
+ uint32_t epoch,
+ LockGuard<decltype(lock)> &g,
+ T &r = revoker) requires(Revocation::SupportsInterruptNotification<T>)
+ {
+ // Wait for the revocation sweep to finish and then
+ // reacquire the lock. If either fails, give up
+ // and return nullptr. | Stale comment. |
cheriot-rtos | github_2023 | cpp | 106 | CHERIoT-Platform | nwf-msr | @@ -129,6 +129,65 @@ namespace
return (Capability{timeout}.is_valid() && timeout->may_block());
}
+ template<typename T = Revocation::Revoker>
+ bool wait_for_background_revoker(
+ Timeout *timeout,
+ uint32_t epoch,
+ LockGuard<decltype(lock)> &g,
+ T &r = revoker) requires(Revocation::SupportsInterruptNotification<T>)
+ {
+ // Wait for the revocation sweep to finish and then
+ // reacquire the lock. If either fails, give up
+ // and return nullptr.
+ if (!r.wait_for_completion(timeout, epoch) ||
+ !with_interrupts_disabled([&]() {
+ if (Capability{timeout}.is_valid())
+ {
+ return g.try_lock(timeout);
+ }
+ return false;
+ }))
+ {
+ return false;
+ }
+ return true;
+ }
+
+ template<typename T = Revocation::Revoker>
+ bool wait_for_background_revoker(
+ Timeout *timeout,
+ uint32_t epoch,
+ LockGuard<decltype(lock)> &g,
+ T &r = revoker) requires(!Revocation::SupportsInterruptNotification<T>)
+ {
+ // Yield while until a revocation pass has finished.
+ while (!revoker.has_revocation_finished_for_epoch<true>(epoch))
+ {
+ g.unlock();
+ Timeout smallSleep{1};
+ thread_sleep(&smallSleep);
+ // It's possible that, while we slept,
+ // `*timeout` was freed. Check that the pointer
+ // is still valid so that we don't fault if this
+ // happens. We are not holding the lock at this
+ // point and so we must do the check with
+ // interrupts disabled to protect against
+ // concurrent free. | This comment might belong on the copy above and then be referenced here? |
cheriot-rtos | github_2023 | others | 106 | CHERIoT-Platform | nwf-msr | @@ -101,12 +101,19 @@ SECTIONS
}
.scheduler_globals_end = .;
+ .allocator_sealed_objects : CAPALIGN
+ {
+ .allocator_sealed_objects = .;
+ */cherimcu.allocator.compartment(.sealed_objects)
+ }
+ .allocator_sealed_objects_end = .;
+
.allocator_globals : CAPALIGN
{
.allocator_globals = .;
*/cherimcu.allocator.compartment(.data .data.* .sdata .sdata.*);
.allocator_bss_start = .;
- */cherimcu.allocator.compartment(.sbss .sbss.* .bss .bss.*)
+ */cherimcu.allocator.compartment(.sbss .sbss.* .bss .bss.*); | This change could be dropped, if desired (or kept, either way is fine). |
cheriot-rtos | github_2023 | others | 106 | CHERIoT-Platform | nwf-msr | @@ -161,6 +192,43 @@ namespace Ibex
// value because we know it will be the last value + 1.
epoch++;
}
+
+ /**
+ * Block until the revocation epoch specified by `epoch` has completed.
+ */
+ bool wait_for_completion(Timeout *timeout, uint32_t epoch)
+ {
+ uint32_t interruptValue;
+ do
+ {
+ // Read the current interrupt futex word. We want to retry if
+ // an interrupt happens after this point.
+ interruptValue = *interruptFutex;
+ // Make sure that the compiler doesn't reorder the read of the
+ // futex word with respect to the read of the revocation epoch.
+ __c11_atomic_signal_fence(__ATOMIC_SEQ_CST);
+ // If the requested epoch has finished, return success.
+ if (has_revocation_finished_for_epoch<true>(epoch))
+ {
+ return true;
+ }
+ // Request the interrupt
+ revoker_device().interruptRequested = 1;
+ // There is a possible race: if the revocation pass finished
+ // before we requested the interrupt, we won't get the
+ // interrupt. Check again before we wait.
+ if (has_revocation_finished_for_epoch<true>(epoch)) | Something about this seems fishy. If it completed after our read of `*interruptFutex` above, then `futex_timed_wait` should bounce us out. So for this asynchrony to result in us missing a wakeup, it would have had to complete before that read, but we checked `has_revocation_finished` after that read. |
cheriot-rtos | github_2023 | cpp | 106 | CHERIoT-Platform | nwf-msr | @@ -129,6 +129,92 @@ namespace
return (Capability{timeout}.is_valid() && timeout->may_block());
}
+ /**
+ * Helper to reacquire the lock after sleeping. This assumes that
+ * `timeout` *was* valid but may have been freed and so checks only that it
+ * has not been invalidated across yielding. If `timeout` remains valid
+ * then this adds any time passed as `elapsed` to the timeout and then
+ * tries to reacquire the lock, blocking for no longer than the remaining
+ * time on this timeout.
+ *
+ * This runs with interrupts disabled to ensure that the timeout remains
+ * valid in between checking that it is valid and reacquiring the lock.
+ * Once the lock is held, the timeout cannot be freed concurrently. | While true at the moment, we have, in the past, discussed supporting multiple allocators. Fortunately I think it doesn't much change the story? |
cheriot-rtos | github_2023 | others | 109 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,103 @@
+#!/bin/sh
+
+# Helper script to build multiple configurations of a benchmark. Patches the
+# board description files to enable and disable different combinations of
+# hardware features. Also patches include paths to keep track of the original
+# locations.
+
+set -eo pipefail
+
+SCRIPTPATH=$(dirname $(readlink -f $0))
+SDKPATH=$(realpath ${SCRIPTPATH}/../sdk) | Stale? |
cheriot-rtos | github_2023 | others | 109 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,103 @@
+#!/bin/sh
+
+# Helper script to build multiple configurations of a benchmark. Patches the
+# board description files to enable and disable different combinations of
+# hardware features. Also patches include paths to keep track of the original
+# locations.
+
+set -eo pipefail | Debian's `dash`, which it uses as `/bin/sh`, apparently doesn't like `-o pipefail`, which seems surprising. |
cheriot-rtos | github_2023 | others | 109 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,103 @@
+#!/bin/sh
+
+# Helper script to build multiple configurations of a benchmark. Patches the
+# board description files to enable and disable different combinations of
+# hardware features. Also patches include paths to keep track of the original
+# locations.
+
+set -eo pipefail
+
+SCRIPTPATH=$(dirname $(readlink -f $0))
+SDKPATH=$(realpath ${SCRIPTPATH}/../sdk)
+
+BOARD=$(realpath $1)
+BENCHMARK=$(realpath $2)
+SDK=$(realpath $3)
+BOARDPATH=$(dirname ${BOARD})
+BOARDNAME=$(basename -s .json ${BOARD})
+
+if [ ! -f "${BOARD}" ] ; then
+ echo "First argument must be the path of a board description file. '${BOARD}' is not a valid file"
+ exit 1
+fi
+if [ ! -f "${BENCHMARK}/xmake.lua" ] ; then
+ echo "Second argument must be the path of a benchmark file. '${BENCHMARK}' does not contain an xmake.lua file"
+ exit 1
+fi
+if [ ! -d "${SDK}" ] ; then
+ echo "Third argument must be the path of the sdk. '${SDK}' does not exist"
+ exit 1
+fi
+if [ ! -f "${SDK}/bin/clang" ] ; then
+ echo "Third argument must be the path of the sdk. '${SDK}/bin/clang' does not exist"
+ exit 1
+fi
+
+# Set up a temporary directory to work in.
+DIR=$(mktemp -d benchmark.XXX) || exit 1
+echo Working in ${DIR}...
+DIR=$(pwd)/${DIR}
+cd ${DIR}
+
+
+# Create a directory for the board files
+
+mkdir boards
+cd boards
+
+
+# Our JSON files are slightly extended JSON, parse them with xmake's JSON
+# parser and spit them out as standard JSON so that jq can consume them.
+cp ${BOARD} basic.json
+cat <<EOF > xmake.lua
+target('fake')
+ on_load(function (target)
+ import("core.base.json")
+ local board = json.loadfile(path.join(os.scriptdir(), 'basic.json'))
+ json.savefile(path.join(os.scriptdir(), 'standard.json'), board)
+ end
+ )
+EOF
+xmake f > /dev/null
+rm xmake.lua basic.json
+rm -rf .xmake
+
+# Create variants of the board with different versions of the revoker and with
+# and without the stack high watermark.
+
+jq '.revoker="software" | .stack_high_water_mark=false' < standard.json > ${BOARDNAME}-software-revoker.json
+jq '.revoker="software" | .stack_high_water_mark=true' < standard.json > ${BOARDNAME}-software-revoker-shwm.json
+jq '.revoker="hardware" | .stack_high_water_mark=false' < standard.json > ${BOARDNAME}-hardware-revoker.json
+jq '.revoker="hardware" | .stack_high_water_mark=true' < standard.json > ${BOARDNAME}-hardware-revoker-shwm.json
+jq 'del(.revoker) | .stack_high_water_mark=false' < standard.json > ${BOARDNAME}-no-revoker.json
+jq 'del(.revoker) | .stack_high_water_mark=false | .defines[.defines| length]|= .+"CHERIOT_FAKE_REVOKER"' < standard.json > ${BOARDNAME}-fake-revoker.json
+rm standard.json
+
+CONFIGS="${BOARDNAME}-software-revoker ${BOARDNAME}-software-revoker-shwm ${BOARDNAME}-hardware-revoker ${BOARDNAME}-hardware-revoker-shwm ${BOARDNAME}-no-revoker ${BOARDNAME}-fake-revoker"
+
+# Patch the include directories so that relative paths become absolute relative
+# to the board file.
+for I in ${CONFIGS}; do
+ # Fix up includes if they expect to be relative to the board file path
+ jq ".driver_includes = (.driver_includes | map_values(. = if . | startswith(\"/\") then . else \"${BOARDPATH}/\" + . end))" < $I.json > $I.json.fixed | I think this also needs to probe for starting with `$`, as in `${sdk}`, which will be expanded by `xmake`?
```suggestion
jq ".driver_includes = (.driver_includes | map_values(. = if . | startswith(\"/\") or startswith(\"\$\") then . else \"${BOARDPATH}/\" + . end))" < $I.json > $I.json.fixed
``` |
cheriot-rtos | github_2023 | others | 72 | CHERIoT-Platform | nwf-msr | @@ -59,29 +75,43 @@ class FlagLock
*/
bool try_lock(Timeout *timeout)
{
- Flag old = Flag::Unlocked;
- if (flag.compare_exchange_strong(old, Flag::Locked))
+ uint32_t old = Flag::Unlocked;
+ auto threadBits = thread_id();
+ uint32_t desired = Flag::Locked | threadBits;
+ if (flag.compare_exchange_strong(old, desired))
{
return true;
}
+ // Next time, try to acquire, acquire with waiters so that we don't
+ // lose wakes if we win a race. | It's not particularly relevant for the PR, but remind me what race we're worried about here? |
cheriot-rtos | github_2023 | cpp | 72 | CHERIoT-Platform | nwf-msr | @@ -250,14 +250,9 @@ namespace
"allocation, sleeping",
bytes);
// Drop the lock while yielding
+ auto expected = ++freeFutex; | Again, not really part of _this_ PR, but while you're here: I not sure this dance works as expected. Consider a situation involving three threads:
* T1 makes it to the `g.unlock()` below, having incremented `freeFutex` to `1`.
* T2 performs a `free` that could satisfy `T1`, sees `freeFutex > 0`, resets it to `0`, and calls `freeFutex.notify_all()`. Nobody awakens.
* T3, asking for more than T2 freed, also makes it to the `g.unlock()` below, having caused `freeFutex` to `1`.
* T3 will sleep, and that's fine, but so will T1, which is perhaps less fine. |
cheriot-rtos | github_2023 | cpp | 72 | CHERIoT-Platform | nwf-msr | @@ -59,6 +59,27 @@ namespace
*/
sched::Thread *futexWaitingList;
+ /**
+ * Returns the boosted priority provided by waiters on a futex.
+ *
+ * This finds the maximum priority of all threads waiting on the futex.
+ * Callers may be about to add a new thread to that list and so another
+ * priority can be provided, which will be used if it is larger than any of
+ * the priorities of the other waiters.
+ */
+ uint8_t priority_boost_for_thread(uint16_t threadID, uint8_t priority = 0) | `threadID` is unused?
The comment speaks of "the futex" but this looks to compute the maximum priority of any waiting thread whose priority is boosted?
I was expecting, I think, this function to take the `futexWaitAddress` that some thread is about to block on and filter the `futexWaitingList` for just that address? |
cheriot-rtos | github_2023 | cpp | 72 | CHERIoT-Platform | nwf-msr | @@ -553,14 +599,45 @@ int futex_timed_wait(Timeout *timeout,
return 0;
}
Thread *currentThread = Thread::current_get();
- Debug::log("{} waiting on futex {} for {} ticks",
- currentThread,
+ Debug::log("Thread {} waiting on futex {} for {} ticks",
+ currentThread->id_get(),
address,
timeout->remaining);
- currentThread->futexWaitAddress = Capability{address}.address();
+ bool isPriorityInheriting = flags & FutexPriorityInheritance;
+ ptraddr_t key = Capability{address}.address();
+ currentThread->futexWaitAddress = key;
+ currentThread->futexPriorityInheriting = isPriorityInheriting;
+ Thread *blockingThread = nullptr;
+ uint16_t blockingThreadID;
+ if (isPriorityInheriting)
+ {
+ // For PI futexes, the low 16 bits store the thread ID.
+ blockingThreadID = *address;
+ blockingThread = get_thread(blockingThreadID);
+ // If we try to block ourself, that's a mistake.
+ if ((blockingThread == currentThread) || (blockingThread == nullptr))
+ {
+ return -EINVAL;
+ }
+ Debug::log("Thread {} boosting priority of {} for futex {}",
+ currentThread->id_get(),
+ blockingThread->id_get(),
+ key);
+ blockingThread->priority_boost(priority_boost_for_thread(
+ blockingThreadID, currentThread->priority_get())); | Since `*address` is not marked `volatile` (and is marked `const`), it seems like there risk the compiler could replace `blockingThreadID` with `*address` in each occurrence. I know we're running with IRQs off here but thinking about the impending DMA-capable future...
If we really need its ID, perhaps `blockingThread->id`, but I suspect we don't? |
cheriot-rtos | github_2023 | cpp | 72 | CHERIoT-Platform | nwf-msr | @@ -553,14 +599,45 @@ int futex_timed_wait(Timeout *timeout,
return 0;
}
Thread *currentThread = Thread::current_get();
- Debug::log("{} waiting on futex {} for {} ticks",
- currentThread,
+ Debug::log("Thread {} waiting on futex {} for {} ticks",
+ currentThread->id_get(),
address,
timeout->remaining);
- currentThread->futexWaitAddress = Capability{address}.address();
+ bool isPriorityInheriting = flags & FutexPriorityInheritance;
+ ptraddr_t key = Capability{address}.address();
+ currentThread->futexWaitAddress = key;
+ currentThread->futexPriorityInheriting = isPriorityInheriting;
+ Thread *blockingThread = nullptr; | 🚲🏚️ing: Maybe `owning` rather than `blocking`? Yes, that thread is blocking our progress, so I understand, but also *we're* about to block on that thread's ownership of this futex. (Naming things is _hard_!) |
cheriot-rtos | github_2023 | cpp | 72 | CHERIoT-Platform | nwf-msr | @@ -512,11 +564,25 @@ namespace sched
/// right after waking up (but before clearing the bits if
/// clearOnExit is set). 0 if it's woken up due to timer expiry.
EventBits eventWaitBits;
- /**
- * If this thread is blocked on a futex, this holds the address of
- * the futex. This is set to 0 if woken via timeout.
- */
- ptraddr_t futexWaitAddress;
+ /// State associated with waiting on a futex.
+ struct
+ {
+ /**
+ * If this thread is blocked on a futex, this holds the address
+ * of the futex. This is set to 0 if woken via timeout.
+ */
+ ptraddr_t futexWaitAddress;
+ /**
+ * The thread that we're priority boosting. This is ignored if
+ * `futexPriorityInheriting` is false.
+ */
+ uint16_t futexPriorityBoostingThread : 16; | Ah, I realized part of my confusion above: I was sometimes reading this with subject and object switched, as the thread that's boosting us. Maybe (⚠️:🚲🏠) `futexPriorityBoostedThread` instead? |
cheriot-rtos | github_2023 | others | 108 | CHERIoT-Platform | nwf | @@ -81,6 +81,10 @@ The name is used to refer to this in software and must be a valid C identifier.
The number is the interrupt number.
The priority is the priority with which this interrupt will be configured in the interrupt controller.
+Interrupts may optionally have an `edge_triggered` property (if this is omitted, it is assumed to be false).
+If this exists and is set to true then the interrupt is assumed to fire when a condition first holds, rather than to remain raised as long as a condition holds.
+Interrupts that are edge triggered are automatically completed by the scheduler, they do not require a call to `interrupt_complete`. | ```suggestion
Interrupts that are edge triggered are automatically completed by the scheduler; they do not require a call to `interrupt_complete`.
``` |
cheriot-rtos | github_2023 | others | 108 | CHERIoT-Platform | nwf | @@ -361,7 +361,11 @@ rule("firmware")
local interruptConfiguration = "CHERIOT_INTERRUPT_CONFIGURATION="
for _, interrupt in ipairs(board.interrupts) do
interruptNames = interruptNames .. interrupt.name .. "=" .. math.floor(interrupt.number) .. ", "
- interruptConfiguration = interruptConfiguration .. "{" .. math.floor(interrupt.number) .. "," .. math.floor(interrupt.priority) .. "},"
+ interruptConfiguration = interruptConfiguration .. "{"
+ .. math.floor(interrupt.number) .. ","
+ .. math.floor(interrupt.priority) .. ","
+ .. (interrupt.edge_triggered and "true" or "false")
+ .. "}," | While you're in the neighborhood, could you add a comment that these are initializers for `sched::InterruptController::Interrupt` structures? |
cheriot-rtos | github_2023 | cpp | 108 | CHERIoT-Platform | nwf | @@ -139,6 +145,10 @@ namespace sched
{
if (ConfiguredInterrupts[i].number == uint32_t(source))
{
+ if (ConfiguredInterrupts[i].isEdgeTriggered) | Is this really the right place to do this? `futex_word_for_source` is called by `interrupt_futex_get`, which is (AIUI) meant to be used in initialization, not necessarily when an interrupt has happened. Perhaps this belongs in the other caller of `futex_word_for_source`, namely `do_external_interrupt`?
Separately, because we're in IRQ context, and so running with IRQs disabled, I don't think there's concern about the order in which completing the interrupt and incrementing the futex word happens, but it'd be good to document that fact (assuming it is, in fact, a fact). |
cheriot-rtos | github_2023 | cpp | 98 | CHERIoT-Platform | davidchisnall | @@ -523,6 +534,11 @@ namespace loader
return compartments[Allocator];
}
+ [[nodiscard]] const PrivilegedCompartment &token_server() const | Maybe add a comment here explaining what it is? I don't really like the token_server name anymore: it's not a token server, it's a helper library that does a fast path for some allocator functions. We possibly want to move `heap_can_free` and `heap_quota_remaining` it as well at some point, since these are pure functions that depend only on access to the unseal capability. |
cheriot-rtos | github_2023 | cpp | 98 | CHERIoT-Platform | davidchisnall | @@ -1066,6 +1080,7 @@ extern "C" SchedulerEntryInfo loader_entry_point(const ImgHdr &imgHdr,
switcherKey.bounds() = 1;
setSealingKey(imgHdr.scheduler(), Scheduler);
setSealingKey(imgHdr.allocator(), Allocator);
+ setSealingKey(imgHdr.token_server(), Allocator); | Perhaps remove PermitSeal from this one? |
cheriot-rtos | github_2023 | others | 98 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,101 @@
+#include <compartment-macros-asm.S>
+#include <cheri-builtins.h>
+#include "../allocator/token.h"
+
+/*
+ * An in-assembler, libcall-able implementation of
+ *
+ * [[cheri::interrupt_state(disabled)]] void *__cheri_compartment("token_server") | This should be `__cheri_libcall` not `__cheri_compartment`. |
cheriot-rtos | github_2023 | others | 98 | CHERIoT-Platform | davidchisnall | @@ -37,12 +37,14 @@ echo Sources: ${SOURCES}
rm -f tidy-*.fail
# sh syntax is -c "string" [name [args ...]], so "tidy" here is the name and not included in "$@"
-echo ${HEADERS} ${SOURCES} | xargs -P${PARALLEL_JOBS} -n5 sh -c "${CLANG_TIDY} -export-fixes=\$(mktemp -p. tidy.fail-XXXX) \$@" tidy
-if [ $(find . -maxdepth 1 -name 'tidy.fail-*' -size +0 | wc -l) -gt 0 ] ; then
- # clang-tidy put non-empty output in one of the tidy-*.fail files
- cat tidy.fail-*
- exit 1
-fi
+[ -n "${CHERIOT_SKIP_CLANG_TIDY-}" ] || { | What is this about? I think it might be accidentally included with this PR? |
cheriot-rtos | github_2023 | cpp | 98 | CHERIoT-Platform | davidchisnall | @@ -1066,6 +1084,11 @@ extern "C" SchedulerEntryInfo loader_entry_point(const ImgHdr &imgHdr,
switcherKey.bounds() = 1;
setSealingKey(imgHdr.scheduler(), Scheduler);
setSealingKey(imgHdr.allocator(), Allocator);
+ setSealingKey(imgHdr.object_fast_paths(), | I still don't really like this name. Object is very broad. This is the allocator fast paths library: it holds the allocator's key and adding anything that is not logically part of the allocator to it could break the security. |
cheriot-rtos | github_2023 | cpp | 98 | CHERIoT-Platform | davidchisnall | @@ -492,6 +501,8 @@ namespace loader
Scheduler,
/// The memory allocator
Allocator,
+ /// The token server
+ TokenServer, | This probably wants to be consistently named with the accessor. I'd suggest `AllocatorLibrary`. |
cheriot-rtos | github_2023 | others | 98 | CHERIoT-Platform | davidchisnall | @@ -167,6 +169,17 @@ rule("cherimcu.privileged-compartment")
target:add("defines", "CHERIOT_AVOID_CAPRELOCS")
end)
+rule("cherimcu.privileged-library")
+ add_deps("cherimcu.component")
+ on_load(function (target)
+ -- Mark this target as a CHERIoT compartment.
+ target:set("cherimcu.type", "compartment")
+ target:set("extension", ".compartment") | Shouldn't these be library? |
cheriot-rtos | github_2023 | others | 98 | CHERIoT-Platform | davidchisnall | @@ -188,6 +201,13 @@ target("cherimcu.allocator")
target:set('cherimcu.debug-name', "allocator")
end)
+target("cheriot.object_fast_paths")
+ add_rules("cherimcu.privileged-library", "cherimcu.component-debug")
+ add_files(path.join(coredir, "object_fast_paths/token_unseal.S"))
+ on_load(function (target)
+ target:set("cherimcu.compartment", "object_fast_paths") | Is this needed? It's used to override the compartment flag value, but we shouldn't be passing that at all when building a library. |
cheriot-rtos | github_2023 | cpp | 104 | CHERIoT-Platform | rmn30 | @@ -176,6 +177,24 @@ size_t __cheri_compartment("alloc")
*/
void __cheri_compartment("alloc") heap_quarantine_empty(void);
+/**
+ * Returns true if `object` points to a valid heap address, false otherwise.
+ * Note that this does *not* check that this is a valid pointer. This should
+ * be used in conjunction with check_pointer to check validity. The principle
+ * use of this function is checking whether an object needs to be claimed. If
+ * this returns false but the pointer has global permission, it must be a
+ * global and so does not need to be claimed. If the pointer lacks global
+ * permission then it cannot be claimed, but if this function returns false
+ * then it is guaranteed not to go away for the duration of the call.
+ */
+__if_c(static) inline _Bool heap_address_is_valid(void *object)
+{
+ ptraddr_t heap_start = LA_ABS(__export_mem_heap);
+ ptraddr_t heap_end = LA_ABS(__export_mem_heap_end);
+ ptraddr_t address = (ptraddr_t)object;
+ return (address >= heap_start) && (address <= heap_end); | Is `address==heap_end` really on the heap? Would expect `<` there. |
cheriot-rtos | github_2023 | cpp | 90 | CHERIoT-Platform | rmn30 | @@ -183,26 +183,40 @@ namespace Revocation
* Otherwise, there are at least two words of the bitmap that need
* to be updated with the masks, and possibly some in between that
* just need to be set wholesale.
+ *
+ * We paint ranges "backwards", from highest address to lowest, so
+ * that we never create a window in which an interior pointer has a
+ * clear shadow bit while the lower adjacent address has an asserted
+ * shadow bit, as that would open the door to confusing the interior
+ * pointer with a pointer to the start of an object (recall that
+ * object headers are marked in the shadow bitmap).
*/
WordT midWord;
if (fill)
{
- shadowCap[baseWordIx] |= maskLo;
shadowCap[topWordIx] |= maskHi;
midWord = ~WordT(0);
}
else
{
- shadowCap[baseWordIx] &= ~maskLo;
shadowCap[topWordIx] &= ~maskHi;
midWord = 0;
}
- for (size_t shadowWordIx = baseWordIx + 1; shadowWordIx < topWordIx;
- shadowWordIx++)
+ for (size_t shadowWordIx = topWordIx - 1; baseWordIx < shadowWordIx; | Could `topWordIdx` ever be `0`? |
cheriot-rtos | github_2023 | others | 96 | CHERIoT-Platform | rmn30 | @@ -405,11 +405,20 @@ rule("firmware")
"\n\t\tbootTStack = .;" ..
"\n\t\t. += " .. loader_trusted_stack_size .. ";" ..
"\n\t}\n"
+ -- Stacks must be less than this size or truncating them in compartment
+ -- switch will encounter precision errors. | ```suggestion
-- switch will encounter precision errors.
```
```suggestion
-- switch may encounter precision errors.
``` |
cheriot-rtos | github_2023 | cpp | 95 | CHERIoT-Platform | nwf-msr | @@ -39,19 +39,17 @@ EXPORT_ASSEMBLY_OFFSET(TrustedStack, mshwmb, (17 * 8) + 4)
// unwinding information, and then a single trusted stack frame used for the
// unwind state of the initial thread. (7 * 8) is the size of TrustedStackFrame | Comment wants updating, too? |
cheriot-rtos | github_2023 | others | 95 | CHERIoT-Platform | nwf-msr | @@ -31,7 +31,7 @@ riscv32-unknown-unknown
-DDEVICE_EXISTS_shadow
-DDEVICE_EXISTS_uart
-DDEVICE_EXISTS_clint
--DCHERIOT_LOADER_TRUSTED_STACK_SIZE=208
+-DCHERIOT_LOADER_TRUSTED_STACK_SIZE=192 | Please add a comment explaining how this number is calculated, if it can't be made formulaic. |
cheriot-rtos | github_2023 | others | 95 | CHERIoT-Platform | nwf-msr | @@ -639,7 +639,7 @@ target("cheriot.loader")
target:set('cherimcu.debug-name', "loader")
local config = {
-- Size in bytes of the trusted stack.
- loader_trusted_stack_size = 224,
+ loader_trusted_stack_size = 208, | Please add a comment explaining how this number is calculated, if it can't be made formulaic. |
cheriot-rtos | github_2023 | cpp | 95 | CHERIoT-Platform | nwf-msr | @@ -39,19 +39,17 @@ EXPORT_ASSEMBLY_OFFSET(TrustedStack, mshwmb, (17 * 8) + 4)
// unwinding information, and then a single trusted stack frame used for the
// unwind state of the initial thread. (7 * 8) is the size of TrustedStackFrame
// and will match the value below.
-EXPORT_ASSEMBLY_SIZE(TrustedStack, TSTACK_REGFRAME_SZ + TSTACK_HEADER_SZ + (8 * 8))
+EXPORT_ASSEMBLY_SIZE(TrustedStack, TSTACK_REGFRAME_SZ + TSTACK_HEADER_SZ + (8 * 6))
EXPORT_ASSEMBLY_OFFSET(TrustedStack, frames, TSTACK_REGFRAME_SZ + TSTACK_HEADER_SZ)
EXPORT_ASSEMBLY_OFFSET(TrustedStack, frameoffset, TSTACK_REGFRAME_SZ)
EXPORT_ASSEMBLY_OFFSET(TrustedStack, inForcedUnwind, TSTACK_REGFRAME_SZ + 2)
EXPORT_ASSEMBLY_OFFSET(TrustedStackFrame, pcc, 0)
EXPORT_ASSEMBLY_OFFSET(TrustedStackFrame, cgp, 8)
EXPORT_ASSEMBLY_OFFSET(TrustedStackFrame, csp, 16)
-EXPORT_ASSEMBLY_OFFSET(TrustedStackFrame, cs0, 24)
-EXPORT_ASSEMBLY_OFFSET(TrustedStackFrame, cs1, 32)
-EXPORT_ASSEMBLY_OFFSET(TrustedStackFrame, calleeExportTable, 40)
-EXPORT_ASSEMBLY_OFFSET(TrustedStackFrame, errorHandlerCount, 48)
-EXPORT_ASSEMBLY_SIZE(TrustedStackFrame, (8 * 8))
+EXPORT_ASSEMBLY_OFFSET(TrustedStackFrame, calleeExportTable, 24)
+EXPORT_ASSEMBLY_OFFSET(TrustedStackFrame, errorHandlerCount, 32)
+EXPORT_ASSEMBLY_SIZE(TrustedStackFrame, (8 * 6)) | While here, maybe `6 * sizeof(uintptr_t)` would be more clear (and also above, if you agree). |
cheriot-rtos | github_2023 | cpp | 91 | CHERIoT-Platform | davidchisnall | @@ -1011,18 +1011,15 @@ __noinline static SealedAllocation unseal_internal(SKey rawKey, SObj obj)
return unsealed;
}
+extern "C" void *
+token_obj_unseal_internal(struct SKeyStruct *, struct SObjStruct *);
+
void *token_obj_unseal(SKey rawKey, SObj obj)
{
- LockGuard g{lock};
- auto unsealed = unseal_internal(rawKey, obj);
- if (unsealed == nullptr)
- {
- return nullptr;
- }
- size_t newSize = unsealed.length() - ObjHdrSize;
- unsealed.address() += ObjHdrSize;
- unsealed.bounds() = newSize;
- return unsealed;
+ return CHERI::with_interrupts_disabled(
+ [=]{
+ return token_obj_unseal_internal(rawKey, obj);
+ }); | This wrapper is a bit unfortunate, since it now means two indirect and one direct function call to land in the right place. The right thing to do is probably to create the export table entry in assembly (ideally with some macos added to `compartment-macros.h`. |
cheriot-rtos | github_2023 | others | 91 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,73 @@
+#include <cheri-builtins.h>
+#include "token.h"
+
+/*
+ * void *
+ * token_obj_unseal_internal(struct SKeyStruct *ca0, struct SObjStruct *ca1)
+ *
+ * Register allocation:
+ *
+ * - ca0 holds a sealing key, either the user's or the real deal, and is
+ * replaced with the unsealed value or NULL
+ *
+ * - ca1 holds the user's sealed object pointer
+ *
+ * - t0/ct0 holds a copy of the user key
+ *
+ * - t1/ct1 is used within each local computation and never holds secrets
+ */
+
+.global token_obj_unseal_internal
+token_obj_unseal_internal:
+
+ // Verify key tag
+ cgettag t1, ca0
+ beqz t1, 9f
+
+ // Verify key address == base and len > 0
+ cgetbase t1, ca0
+ bne a0, t1, 9f // as-integer access to ca0 gives address
+ cgetlen t1, ca0
+ beqz t1, 9f
+
+ // Verify key has unseal permission
+ cgetperm t1, ca0
+ andi t1, t1, CHERI_PERM_UNSEAL
+ beqz t1, 9f
+
+ // Copy key capability to scratch register
+ cmove ct0, ca0
+
+ // Load unsealing root capability, to be clobbered by return value
+ // This faults only if something has gone very, very wrong
+1:
+ auipcc ca0, %cheri_compartment_pccrel_hi(__sealingkey)
+ clc ca0, %cheri_compartment_pccrel_lo(1b)(ca0)
+
+ // Unseal, clobbering authority
+ cunseal ca0, ca1, ca0
+
+ // Verify tag of unsealed form
+ cgettag t1, ca0
+ beqz t1, 9f
+
+ // Load software type. This will not trap, thanks to above tag check.
+ clw t1, TokenSObj_offset_type(ca0)
+
+ // Verify that the loaded value matches the address of the key (via
+ // as-integer access to capability register ct0).
+ bne t0, t1, 9f
+
+ // Subset bounds to ->data
+ cgetlen t1, ca0
+ cincoffset ca0, ca0, TokenSObj_offset_data
+ addi t1, t1, -TokenSObj_offset_data
+ csetboundsexact ca0, ca0, t1
+
+ // And that's an unwrap.
+ cret
+
+9: | Since this isn't inline assembly, can we give labels sensible names (e.g. `.Lexit_failure`)? |
cheriot-rtos | github_2023 | others | 91 | CHERIoT-Platform | davidchisnall | @@ -182,6 +182,7 @@ target("cherimcu.switcher")
target("cherimcu.allocator")
add_rules("cherimcu.privileged-compartment", "cherimcu.component-debug")
add_files(path.join(coredir, "allocator/main.cc"))
+ add_files(path.join(coredir, "allocator/token_unseal.S")) | I wonder if the right thing to do is allow compartments to export library functions. I think that might actually work in the loader already. A library function exported from a compartment will have access to the compartment's PCC but not the CGP. That said, we may want to give the library function a much smaller PCC, so maybe we do want this to be a separate thing. |
cheriot-rtos | github_2023 | others | 91 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,73 @@
+#include <cheri-builtins.h>
+#include "token.h"
+
+/*
+ * void *
+ * token_obj_unseal_internal(struct SKeyStruct *ca0, struct SObjStruct *ca1)
+ *
+ * Register allocation:
+ *
+ * - ca0 holds a sealing key, either the user's or the real deal, and is
+ * replaced with the unsealed value or NULL
+ *
+ * - ca1 holds the user's sealed object pointer
+ *
+ * - t0/ct0 holds a copy of the user key
+ *
+ * - t1/ct1 is used within each local computation and never holds secrets
+ */
+
+.global token_obj_unseal_internal
+token_obj_unseal_internal:
+
+ // Verify key tag
+ cgettag t1, ca0
+ beqz t1, 9f
+
+ // Verify key address == base and len > 0
+ cgetbase t1, ca0
+ bne a0, t1, 9f // as-integer access to ca0 gives address
+ cgetlen t1, ca0
+ beqz t1, 9f
+
+ // Verify key has unseal permission
+ cgetperm t1, ca0
+ andi t1, t1, CHERI_PERM_UNSEAL
+ beqz t1, 9f
+
+ // Copy key capability to scratch register
+ cmove ct0, ca0
+
+ // Load unsealing root capability, to be clobbered by return value
+ // This faults only if something has gone very, very wrong
+1:
+ auipcc ca0, %cheri_compartment_pccrel_hi(__sealingkey)
+ clc ca0, %cheri_compartment_pccrel_lo(1b)(ca0)
+
+ // Unseal, clobbering authority
+ cunseal ca0, ca1, ca0
+
+ // Verify tag of unsealed form
+ cgettag t1, ca0
+ beqz t1, 9f
+
+ // Load software type. This will not trap, thanks to above tag check. | And the fact that we're running with interrupts disabled, so the object can't be cleared out from under us. This means that this approach can't work on multicore systems, which is a shame. |
cheriot-rtos | github_2023 | others | 91 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,73 @@
+#include <cheri-builtins.h>
+#include "token.h"
+
+/*
+ * void *
+ * token_obj_unseal_internal(struct SKeyStruct *ca0, struct SObjStruct *ca1)
+ *
+ * Register allocation:
+ *
+ * - ca0 holds a sealing key, either the user's or the real deal, and is
+ * replaced with the unsealed value or NULL
+ *
+ * - ca1 holds the user's sealed object pointer
+ *
+ * - t0/ct0 holds a copy of the user key
+ *
+ * - t1/ct1 is used within each local computation and never holds secrets
+ */
+
+.global token_obj_unseal_internal
+token_obj_unseal_internal:
+
+ // Verify key tag
+ cgettag t1, ca0
+ beqz t1, 9f
+
+ // Verify key address == base and len > 0
+ cgetbase t1, ca0
+ bne a0, t1, 9f // as-integer access to ca0 gives address | Why are we checking that the base == address? We probably could optimise for size later by providing compartments with ranges of sealing keys.
The check that we might want is that the address > 16, to make sure that it's a software key and we don't accidentally allow unsealing zeroed things. |
cheriot-rtos | github_2023 | others | 91 | CHERIoT-Platform | davidchisnall | @@ -31,6 +31,10 @@ SECTIONS
*/cherimcu.allocator.compartment(.compartment_export_table);
.allocator_export_table_end = .;
+ .token_server_export_table = ALIGN(8);
+ */cherimcu.token_server.compartment(.compartment_export_table); | At some point soon, I intend to do an s/cherimcu/cheriot/ in the xmake for these things. Can you do this preemptively for the new things so that we don't regress? |
cheriot-rtos | github_2023 | cpp | 91 | CHERIoT-Platform | davidchisnall | @@ -482,6 +482,15 @@ namespace loader
{
return code.start();
}
+
+ /**
+ * Privileged libraries are privileged compartments without data
+ * segments.
+ */
+ [[nodiscard]] bool is_privileged_library() const
+ {
+ return (data.start() == 0) && (data.size() == 0); | This possibly should check that the length is 0. It's possible that some memory layout will make address 0 usable memory. |
cheriot-rtos | github_2023 | others | 91 | CHERIoT-Platform | davidchisnall | @@ -37,12 +37,14 @@ echo Sources: ${SOURCES}
rm -f tidy-*.fail
# sh syntax is -c "string" [name [args ...]], so "tidy" here is the name and not included in "$@"
-echo ${HEADERS} ${SOURCES} | xargs -P${PARALLEL_JOBS} -n5 sh -c "${CLANG_TIDY} -export-fixes=\$(mktemp -p. tidy.fail-XXXX) \$@" tidy
-if [ $(find . -maxdepth 1 -name 'tidy.fail-*' -size +0 | wc -l) -gt 0 ] ; then
- # clang-tidy put non-empty output in one of the tidy-*.fail files
- cat tidy.fail-*
- exit 1
-fi
+[ -n "${CHERIOT_SKIP_CLANG_TIDY-}" ] || { | What is this and where is it set? |
cheriot-rtos | github_2023 | cpp | 91 | CHERIoT-Platform | davidchisnall | @@ -38,6 +38,8 @@ __BEGIN_DECLS
*/
SKey __cheri_compartment("alloc") token_key_new(void);
+typedef __cheri_callback void *(*Token_Allocator)(Timeout *, SObj, size_t); | This is odd capitalisation. Doesn't clang-tidy tell you to remove the underscore? |
cheriot-rtos | github_2023 | cpp | 91 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,82 @@
+#include <cheri.hh>
+#include <debug.hh>
+#include <token.h>
+
+#include "../allocator/token.h"
+
+using Debug = ConditionalDebug<DEBUG_TOKEN_SERVER, "Token Server">;
+
+using namespace CHERI;
+
+/**
+ * Helper that allocates a sealed object and returns the sealed and
+ * unsealed capabilities to the object. Requires that the sealing key have
+ * all of the permissions in `permissions`.
+ */
+static std::pair<SObj, void *>
+ __noinline ts_allocate_sealed_unsealed(Token_Allocator heapAlloc,
+ Timeout *timeout,
+ SObj heapCapability,
+ SealingKey key,
+ size_t sz,
+ PermissionSet permissions)
+{
+ if (!permissions.can_derive_from(key.permissions()))
+ {
+ Debug::log(
+ "Operation requires {}, cannot derive from {}", permissions, key);
+ return {nullptr, nullptr};
+ }
+
+ if (sz > 0xfe8 - ObjHdrSize)
+ {
+ Debug::log("Cannot allocate sealed object of {} bytes, too large", sz);
+ // TODO: Properly handle imprecision.
+ return {nullptr, nullptr};
+ }
+
+ SealedAllocation obj{
+ static_cast<SObj>(heapAlloc(timeout, heapCapability, sz + ObjHdrSize))};
+ if (obj == nullptr)
+ {
+ Debug::log("Underlying allocation failed for sealed object");
+ return {nullptr, nullptr};
+ }
+
+ obj->type = key.address();
+ auto sealed = obj;
+ sealed.seal(SEALING_CAP());
+ obj.address() += ObjHdrSize; // Exclude the header.
+ obj.bounds() = obj.length() - ObjHdrSize; | This chunk probably needs to run with interrupts disabled. I'm a bit nervous about this decoupling because the security of this code depends on the invariant that no unsealed pointer to the outer object exists anywhere in the system other than in the allocator / token code. Now that the allocator is untrused, it's trivial to break this. I can pass a `heapAlloc` function that returns a pointer to something and also stores that pointer in a global, and then I can change the sealing type in the first word. This makes it trivial for me to fake sealed capabilities. For example:
|
cheriot-rtos | github_2023 | others | 93 | CHERIoT-Platform | nwf-msr | @@ -89,8 +89,19 @@ start:
cspecialrw ca3, mscratchc, ca3
// ca4 still has the RW memory root; nothing to change
// The return value is SchedEntryInfo.
- cincoffset csp, csp, -16 - CONFIG_THREADS_NUM * BOOT_THREADINFO_SZ
- csetbounds ca0, csp, 16 + CONFIG_THREADS_NUM * BOOT_THREADINFO_SZ
+
+ // Calculate space for the structure passed from the loader to the
+ // scheduler. | Assuming it's correct...
```suggestion
// scheduler. This is a `class ThreadInfo` from `loader/types.h`.
``` |
cheriot-rtos | github_2023 | others | 93 | CHERIoT-Platform | nwf-msr | @@ -31,8 +31,7 @@ riscv32-unknown-unknown
-DDEVICE_EXISTS_shadow
-DDEVICE_EXISTS_uart
-DDEVICE_EXISTS_clint
--DCONFIG_THREADS={{1,2,1024,5},{2,1,1024,5},{3,1,1024,5},}
--DCONFIG_THREADS_ENTRYPOINTS={LA_ABS(__export_test_runner__Z9run_testsv),LA_ABS(__export_thread_pool__Z15thread_pool_runv),LA_ABS(__export_thread_pool__Z15thread_pool_runv),}
+-DCHERIOT_LOADER_TRUSTED_STACK_SIZE=208 | You might explain why 208? This is also set to 224 down in sdk/xmake.lua? |
cheriot-rtos | github_2023 | others | 93 | CHERIoT-Platform | nwf-msr | @@ -352,24 +352,69 @@ rule("firmware")
add_defines(interruptConfiguration)
end
+ local loader = target:deps()['cheriot.loader'];
+ local loader_stack_size = loader:get('loader_stack_size')
+ local loader_trusted_stack_size = loader:get('loader_trusted_stack_size')
+
-- Get the threads config and prepare the predefined macros that describe them
local threads = target:values("threads")
+
+
+ local thread_stack_template =
+ "\n\t. = ALIGN(16);" ..
+ "\n\t.thread_stack_${thread_id} : CAPALIGN" ..
+ "\n\t{" ..
+ "\n\t\t.thread_${thread_id}_stack_start = .;" ..
+ "\n\t\t. += ${stack_size};" ..
+ "\n\t\t.thread_${thread_id}_stack_end = .;" ..
+ "\n\t}\n"
+ local thread_trusted_stack_template =
+ "\n\t. = ALIGN(8);" ..
+ "\n\t.thread_trusted_stack_${thread_id} : CAPALIGN" ..
+ "\n\t{" ..
+ "\n\t\t.thread_${thread_id}_trusted_stack_start = .;" ..
+ "\n\t\t. += ${trusted_stack_size};" ..
+ "\n\t\t.thread_${thread_id}_trusted_stack_end = .;" ..
+ "\n\t}\n"
+ local thread_template = | ```suggestion
-- Build a `class ThreadConfig` for a thread
local thread_template =
``` |
cheriot-rtos | github_2023 | others | 93 | CHERIoT-Platform | nwf-msr | @@ -352,24 +352,69 @@ rule("firmware")
add_defines(interruptConfiguration)
end
+ local loader = target:deps()['cheriot.loader'];
+ local loader_stack_size = loader:get('loader_stack_size')
+ local loader_trusted_stack_size = loader:get('loader_trusted_stack_size')
+
-- Get the threads config and prepare the predefined macros that describe them
local threads = target:values("threads")
+
+
+ local thread_stack_template = | ```suggestion
-- Declare space and start and end symbols for a thread's C stack
local thread_stack_template =
``` |
cheriot-rtos | github_2023 | others | 93 | CHERIoT-Platform | nwf-msr | @@ -352,24 +352,69 @@ rule("firmware")
add_defines(interruptConfiguration)
end
+ local loader = target:deps()['cheriot.loader'];
+ local loader_stack_size = loader:get('loader_stack_size')
+ local loader_trusted_stack_size = loader:get('loader_trusted_stack_size')
+
-- Get the threads config and prepare the predefined macros that describe them
local threads = target:values("threads")
+
+
+ local thread_stack_template =
+ "\n\t. = ALIGN(16);" ..
+ "\n\t.thread_stack_${thread_id} : CAPALIGN" ..
+ "\n\t{" ..
+ "\n\t\t.thread_${thread_id}_stack_start = .;" ..
+ "\n\t\t. += ${stack_size};" ..
+ "\n\t\t.thread_${thread_id}_stack_end = .;" ..
+ "\n\t}\n"
+ local thread_trusted_stack_template = | ```suggestion
-- Declare space and start and end symbols for a thread's trusted stack
local thread_trusted_stack_template =
``` |
cheriot-rtos | github_2023 | others | 93 | CHERIoT-Platform | nwf-msr | @@ -192,12 +193,23 @@ SECTIONS
SHORT(@library_count@);
# Number of compartment headers.
SHORT(@compartment_count@);
-
@compartment_headers@
+ }
+ # Thread configuration. This follows the compartment headers but is in a
+ # separate section to make auditing easier. | ```suggestion
# separate section to make auditing easier.
# This section holds a `class ThreadInfo` (loader/types.h)
``` |
cheriot-rtos | github_2023 | cpp | 93 | CHERIoT-Platform | nwf-msr | @@ -1004,6 +933,17 @@ extern "C" SchedulerEntryInfo loader_entry_point(const ImgHdr &imgHdr,
void *almightySeal,
void *almightyRW)
{
+ // This relies on a slightly surprising combination of two C++ features: | Can you expand on what "This" is? I'm sure it's quite informative, but this comment (or, at least, the `SchedulerEntryInfo` type) seems unrelated to the rest of the PR? |
cheriot-rtos | github_2023 | others | 93 | CHERIoT-Platform | nwf-msr | @@ -89,8 +89,19 @@ start:
cspecialrw ca3, mscratchc, ca3
// ca4 still has the RW memory root; nothing to change
// The return value is SchedEntryInfo.
- cincoffset csp, csp, -16 - CONFIG_THREADS_NUM * BOOT_THREADINFO_SZ
- csetbounds ca0, csp, 16 + CONFIG_THREADS_NUM * BOOT_THREADINFO_SZ
+
+ // Calculate space for the structure passed from the loader to the
+ // scheduler.
+ la_abs s1, __thread_count
+ csetaddr cs1, ca4, s1
+ clhu s1, 0(cs1)
+ li t0, -BOOT_THREADINFO_SZ
+ mul s1, s1, t0
+ addi s1, s1, -16 | What's 16, here? |
cheriot-rtos | github_2023 | cpp | 93 | CHERIoT-Platform | nwf-msr | @@ -124,8 +124,10 @@ namespace sched
for (size_t i = 0; auto *threadSpace : threadSpaces)
{
+ Debug::log("Created thread for trusted stack {}",
+ info[i].trustedStack);
Thread *th = new (threadSpace)
- Thread(info[i].trustedStack, info[i].threadid, info[i].priority);
+ Thread(info[i].trustedStack, i + 1, info[i].priority); | This seems a little strange to me, since it means that the small-integer thread IDs are now assigned by link order (and will eventually be assigned by the outcome of sorting stacks for capalign packing), right? If they show up in logging output, their mysterious sourcing might be unsettling? (I don't think they show up in APIs, tho', so at least there's that!) |
cheriot-rtos | github_2023 | others | 93 | CHERIoT-Platform | nwf-msr | @@ -126,7 +136,8 @@ start:
// All other registers will be cleared in the clear-regs block
// Pass the array of threadInfos as first argument.
- csetbounds ca0, csp, CONFIG_THREADS_NUM * BOOT_THREADINFO_SZ
+ addi s1, s1, -16 | This one, too, could benefit from being an `EXPORT_ASSEMBLY_OFFSET`. |
cheriot-rtos | github_2023 | others | 89 | CHERIoT-Platform | rmn30 | @@ -0,0 +1,220 @@
+Writing a CHERIoT Device Driver
+===============================
+
+CHERIoT aims to be small and easy to customize.
+It does not have a generic device driver interface but it does have a number of tools that make it possible to write modular device drivers.
+
+What is a device?
+-----------------
+
+From the perspective of the CPU, a device is something that you communicate with via a memory-mapped I/O interface, which may (optionally) generate interrupts.
+There are several devices that the core parts of the RTOS interact with:
+
+ - The UART, which is used for writing debug output during development.
+ - The core-local interrupt controller, which is used for managing timer interrupts.
+ - The platform interrupt controller, which is used for managing external interrupts.
+ - The revoker, which scans memory for dangling capabilities (pointers) and invalidates them.
+
+Specifying a device's locations
+-------------------------------
+
+Devices are specified in the [board description file](BoardDescriptions.md).
+The two relevant parts are the `devices` node, which specifies the memory-mapped I/O devices and the `interrupts` section that describes how external interrupts should be configured.
+For example, our initial FPGA prototyping platform had sections like this describing its Ethernet device:
+
+```json
+ "devices" : {
+ "ethernet" : {
+ "start" : 0x98000000,
+ "length": 0x204
+ },
+ ...
+ },
+ "interrupts": [
+ {
+ "name": "Ethernet",
+ "number": 16,
+ "priority": 3
+ }
+ ],
+```
+
+The first part says that the ethernet device's MMIO space is 0x204 bytes, starting at address 0x98000000.
+The second says that interrupt number 16 is used for the ethernet device.
+
+Accessing the memory-mapped I/O region
+--------------------------------------
+
+The `MMIO_CAPABILITY` macros is used to get a pointer to memory-mapped I/O devices. | ```suggestion
The `MMIO_CAPABILITY` macro is used to get a pointer to memory-mapped I/O devices.
``` |
cheriot-rtos | github_2023 | others | 89 | CHERIoT-Platform | rmn30 | @@ -0,0 +1,220 @@
+Writing a CHERIoT Device Driver
+===============================
+
+CHERIoT aims to be small and easy to customize.
+It does not have a generic device driver interface but it does have a number of tools that make it possible to write modular device drivers.
+
+What is a device?
+-----------------
+
+From the perspective of the CPU, a device is something that you communicate with via a memory-mapped I/O interface, which may (optionally) generate interrupts.
+There are several devices that the core parts of the RTOS interact with:
+
+ - The UART, which is used for writing debug output during development.
+ - The core-local interrupt controller, which is used for managing timer interrupts.
+ - The platform interrupt controller, which is used for managing external interrupts.
+ - The revoker, which scans memory for dangling capabilities (pointers) and invalidates them.
+
+Specifying a device's locations
+-------------------------------
+
+Devices are specified in the [board description file](BoardDescriptions.md).
+The two relevant parts are the `devices` node, which specifies the memory-mapped I/O devices and the `interrupts` section that describes how external interrupts should be configured.
+For example, our initial FPGA prototyping platform had sections like this describing its Ethernet device:
+
+```json
+ "devices" : {
+ "ethernet" : {
+ "start" : 0x98000000,
+ "length": 0x204
+ },
+ ...
+ },
+ "interrupts": [
+ {
+ "name": "Ethernet",
+ "number": 16,
+ "priority": 3
+ }
+ ],
+```
+
+The first part says that the ethernet device's MMIO space is 0x204 bytes, starting at address 0x98000000.
+The second says that interrupt number 16 is used for the ethernet device.
+
+Accessing the memory-mapped I/O region
+--------------------------------------
+
+The `MMIO_CAPABILITY` macros is used to get a pointer to memory-mapped I/O devices.
+This takes two arguments.
+The first is the C/C++ type of the pointer, the second is the name from the board configuration file.
+For example, to get a pointer to the memory-mapped I/O space for the ethernet device above, we might do something like:
+
+```c
+struct EthernetMMIO
+{
+ // Control register layout here:
+ ...
+};
+
+volatile struct EthernetMMIO *ethernet_device()
+{
+ return MMIO_CAPABILITY(struct EthernetMMIO, ethernet);
+}
+```
+
+Note that this macro must be used in code, it cannot be used for static initialisation.
+The macro expands to a load from the compartment's import table and so there is no point assigning the result to a global: you will get smaller code using it directly.
+
+Now that you have a `volatile` pointer to the device's MMIO region, you can access its control registers directly. | I hate to nit pick but isn't it the struct that is volatile, not the pointer? |
cheriot-rtos | github_2023 | others | 89 | CHERIoT-Platform | rmn30 | @@ -0,0 +1,220 @@
+Writing a CHERIoT Device Driver
+===============================
+
+CHERIoT aims to be small and easy to customize.
+It does not have a generic device driver interface but it does have a number of tools that make it possible to write modular device drivers.
+
+What is a device?
+-----------------
+
+From the perspective of the CPU, a device is something that you communicate with via a memory-mapped I/O interface, which may (optionally) generate interrupts.
+There are several devices that the core parts of the RTOS interact with:
+
+ - The UART, which is used for writing debug output during development.
+ - The core-local interrupt controller, which is used for managing timer interrupts.
+ - The platform interrupt controller, which is used for managing external interrupts.
+ - The revoker, which scans memory for dangling capabilities (pointers) and invalidates them.
+
+Specifying a device's locations
+-------------------------------
+
+Devices are specified in the [board description file](BoardDescriptions.md).
+The two relevant parts are the `devices` node, which specifies the memory-mapped I/O devices and the `interrupts` section that describes how external interrupts should be configured.
+For example, our initial FPGA prototyping platform had sections like this describing its Ethernet device:
+
+```json
+ "devices" : {
+ "ethernet" : {
+ "start" : 0x98000000,
+ "length": 0x204
+ },
+ ...
+ },
+ "interrupts": [
+ {
+ "name": "Ethernet",
+ "number": 16,
+ "priority": 3
+ }
+ ],
+```
+
+The first part says that the ethernet device's MMIO space is 0x204 bytes, starting at address 0x98000000.
+The second says that interrupt number 16 is used for the ethernet device.
+
+Accessing the memory-mapped I/O region
+--------------------------------------
+
+The `MMIO_CAPABILITY` macros is used to get a pointer to memory-mapped I/O devices.
+This takes two arguments.
+The first is the C/C++ type of the pointer, the second is the name from the board configuration file.
+For example, to get a pointer to the memory-mapped I/O space for the ethernet device above, we might do something like:
+
+```c
+struct EthernetMMIO
+{
+ // Control register layout here:
+ ...
+};
+
+volatile struct EthernetMMIO *ethernet_device()
+{
+ return MMIO_CAPABILITY(struct EthernetMMIO, ethernet);
+}
+```
+
+Note that this macro must be used in code, it cannot be used for static initialisation.
+The macro expands to a load from the compartment's import table and so there is no point assigning the result to a global: you will get smaller code using it directly.
+
+Now that you have a `volatile` pointer to the device's MMIO region, you can access its control registers directly.
+Any device can be accessed from any compartment in this way, but that access will appear in the linker audit report.
+
+For this device, you will see an entry like this for any compartment that accesses the device:
+
+```json
+ {
+ "kind": "MMIO",
+ "length": 516,
+ "start": 2550136832
+ },
+```
+
+You can then audit whether a firmware image enforces whatever policy you want (for example, no compartment other than a device driver may access the device directly).
+Note that the linker reports will always provide the addresses and lengths in decimal, because they are standard JSON.
+We support a small number of extensions to JSON in the files that we consume, to improve usability, but don't use these in files that we produce, to improve interoperability.
+
+There is no requirement to expose a device as a single MMIO region.
+You may wish to define multiple regions, which can be as small as a single byte, so that you can privilege separate your device driver.
+
+Some devices have a very large control structure.
+For example, the platform-local interrupt controller is many KiBs.
+We don't define a C structure that covers every single field for this and instead just use `uint32_t` as the type for `MMIO_CAPABILITY`, which lets us treat the space as an array of 32-bit control registers.
+
+Handling interrupts
+-------------------
+
+To be able to handle interrupts, you must have a [software capability](SoftwareCapabilities.md) that [authorises access to the interrupt](Interrupts.md).
+For the ethernet device that we've been using as an example, you would typically request one with this macro invocation:
+
+```c
+DECLARE_AND_DEFINE_INTERRUPT_CAPABILITY(ethernetInterruptCapability, Ethernet, true, true);
+```
+
+If you wish to share this between multiple compilation units, you can use the separate `DECLARE_` and `DEFINE_` forms (see [`interrupt.h`](../sdk/include/interrupt.h)) but the combined form is normally most convenient.
+This macro takes four arguments:
+
+ 1. The name that we're going to use to refer to this capability.
+ The name `ethernetInterruptCapability` is arbitrary, you can use whatever makes sense to you.
+ 2. The name of the interrupt, from the board description file (`Ethernet`, in this case).
+ 3. Whether this capability authorises waiting for this interrupt (this will almost always be `true`).
+ 4. Whether this capability authorises acknowledging the interrupt so that it can fire again.
+ This will almost always be true in device drivers but should generally be true for only one compartment (for each interrupt), whereas multiple compartments may wish to observe interrupts for monitoring.
+
+As with the MMIO capabilities, compartments | incomplete sentence. |
cheriot-rtos | github_2023 | others | 89 | CHERIoT-Platform | rmn30 | @@ -0,0 +1,220 @@
+Writing a CHERIoT Device Driver
+===============================
+
+CHERIoT aims to be small and easy to customize.
+It does not have a generic device driver interface but it does have a number of tools that make it possible to write modular device drivers.
+
+What is a device?
+-----------------
+
+From the perspective of the CPU, a device is something that you communicate with via a memory-mapped I/O interface, which may (optionally) generate interrupts.
+There are several devices that the core parts of the RTOS interact with:
+
+ - The UART, which is used for writing debug output during development.
+ - The core-local interrupt controller, which is used for managing timer interrupts.
+ - The platform interrupt controller, which is used for managing external interrupts.
+ - The revoker, which scans memory for dangling capabilities (pointers) and invalidates them.
+
+Specifying a device's locations
+-------------------------------
+
+Devices are specified in the [board description file](BoardDescriptions.md).
+The two relevant parts are the `devices` node, which specifies the memory-mapped I/O devices and the `interrupts` section that describes how external interrupts should be configured.
+For example, our initial FPGA prototyping platform had sections like this describing its Ethernet device:
+
+```json
+ "devices" : {
+ "ethernet" : {
+ "start" : 0x98000000,
+ "length": 0x204
+ },
+ ...
+ },
+ "interrupts": [
+ {
+ "name": "Ethernet",
+ "number": 16,
+ "priority": 3
+ }
+ ],
+```
+
+The first part says that the ethernet device's MMIO space is 0x204 bytes, starting at address 0x98000000.
+The second says that interrupt number 16 is used for the ethernet device.
+
+Accessing the memory-mapped I/O region
+--------------------------------------
+
+The `MMIO_CAPABILITY` macros is used to get a pointer to memory-mapped I/O devices.
+This takes two arguments.
+The first is the C/C++ type of the pointer, the second is the name from the board configuration file.
+For example, to get a pointer to the memory-mapped I/O space for the ethernet device above, we might do something like:
+
+```c
+struct EthernetMMIO
+{
+ // Control register layout here:
+ ...
+};
+
+volatile struct EthernetMMIO *ethernet_device()
+{
+ return MMIO_CAPABILITY(struct EthernetMMIO, ethernet);
+}
+```
+
+Note that this macro must be used in code, it cannot be used for static initialisation.
+The macro expands to a load from the compartment's import table and so there is no point assigning the result to a global: you will get smaller code using it directly.
+
+Now that you have a `volatile` pointer to the device's MMIO region, you can access its control registers directly.
+Any device can be accessed from any compartment in this way, but that access will appear in the linker audit report.
+
+For this device, you will see an entry like this for any compartment that accesses the device:
+
+```json
+ {
+ "kind": "MMIO",
+ "length": 516,
+ "start": 2550136832
+ },
+```
+
+You can then audit whether a firmware image enforces whatever policy you want (for example, no compartment other than a device driver may access the device directly).
+Note that the linker reports will always provide the addresses and lengths in decimal, because they are standard JSON.
+We support a small number of extensions to JSON in the files that we consume, to improve usability, but don't use these in files that we produce, to improve interoperability.
+
+There is no requirement to expose a device as a single MMIO region.
+You may wish to define multiple regions, which can be as small as a single byte, so that you can privilege separate your device driver.
+
+Some devices have a very large control structure.
+For example, the platform-local interrupt controller is many KiBs.
+We don't define a C structure that covers every single field for this and instead just use `uint32_t` as the type for `MMIO_CAPABILITY`, which lets us treat the space as an array of 32-bit control registers.
+
+Handling interrupts
+-------------------
+
+To be able to handle interrupts, you must have a [software capability](SoftwareCapabilities.md) that [authorises access to the interrupt](Interrupts.md).
+For the ethernet device that we've been using as an example, you would typically request one with this macro invocation:
+
+```c
+DECLARE_AND_DEFINE_INTERRUPT_CAPABILITY(ethernetInterruptCapability, Ethernet, true, true);
+```
+
+If you wish to share this between multiple compilation units, you can use the separate `DECLARE_` and `DEFINE_` forms (see [`interrupt.h`](../sdk/include/interrupt.h)) but the combined form is normally most convenient.
+This macro takes four arguments:
+
+ 1. The name that we're going to use to refer to this capability.
+ The name `ethernetInterruptCapability` is arbitrary, you can use whatever makes sense to you.
+ 2. The name of the interrupt, from the board description file (`Ethernet`, in this case).
+ 3. Whether this capability authorises waiting for this interrupt (this will almost always be `true`).
+ 4. Whether this capability authorises acknowledging the interrupt so that it can fire again.
+ This will almost always be true in device drivers but should generally be true for only one compartment (for each interrupt), whereas multiple compartments may wish to observe interrupts for monitoring.
+
+As with the MMIO capabilities, compartments
+
+```json
+ {
+ "contents": "10000101",
+ "kind": "SealedObject",
+ "sealing_type": {
+ "compartment": "sched",
+ "key": "InterruptKey",
+ "provided_by": "build/cheriot/cheriot/release/example-firmware.scheduler.compartment",
+ "symbol": "__export.sealing_type.sched.InterruptKey"
+ }
+```
+
+The sealing type tells you that this is an interrupt capability (it's sealed with the `InterruptKey` type, provided by the scheduler).
+The contents lets you audit what this authorises.
+The first two bytes are a 16-bit (little-endian on all currently supported targets) integer containing the interrupt number, so 1000 means 16 (our Ethernet interrupt number).
+The next two bytes are boolean values reflecting the last two arguments to the macro, so this authorises both waiting and clearing the macro.
+Again, this can form part of your firmware auditing. | We really need tooling for this. Manually interpreting binary representation of structs is not fun. |
cheriot-rtos | github_2023 | others | 89 | CHERIoT-Platform | rmn30 | @@ -0,0 +1,220 @@
+Writing a CHERIoT Device Driver
+===============================
+
+CHERIoT aims to be small and easy to customize.
+It does not have a generic device driver interface but it does have a number of tools that make it possible to write modular device drivers.
+
+What is a device?
+-----------------
+
+From the perspective of the CPU, a device is something that you communicate with via a memory-mapped I/O interface, which may (optionally) generate interrupts.
+There are several devices that the core parts of the RTOS interact with:
+
+ - The UART, which is used for writing debug output during development.
+ - The core-local interrupt controller, which is used for managing timer interrupts.
+ - The platform interrupt controller, which is used for managing external interrupts.
+ - The revoker, which scans memory for dangling capabilities (pointers) and invalidates them.
+
+Specifying a device's locations
+-------------------------------
+
+Devices are specified in the [board description file](BoardDescriptions.md).
+The two relevant parts are the `devices` node, which specifies the memory-mapped I/O devices and the `interrupts` section that describes how external interrupts should be configured.
+For example, our initial FPGA prototyping platform had sections like this describing its Ethernet device:
+
+```json
+ "devices" : {
+ "ethernet" : {
+ "start" : 0x98000000,
+ "length": 0x204
+ },
+ ...
+ },
+ "interrupts": [
+ {
+ "name": "Ethernet",
+ "number": 16,
+ "priority": 3
+ }
+ ],
+```
+
+The first part says that the ethernet device's MMIO space is 0x204 bytes, starting at address 0x98000000.
+The second says that interrupt number 16 is used for the ethernet device.
+
+Accessing the memory-mapped I/O region
+--------------------------------------
+
+The `MMIO_CAPABILITY` macros is used to get a pointer to memory-mapped I/O devices.
+This takes two arguments.
+The first is the C/C++ type of the pointer, the second is the name from the board configuration file.
+For example, to get a pointer to the memory-mapped I/O space for the ethernet device above, we might do something like:
+
+```c
+struct EthernetMMIO
+{
+ // Control register layout here:
+ ...
+};
+
+volatile struct EthernetMMIO *ethernet_device()
+{
+ return MMIO_CAPABILITY(struct EthernetMMIO, ethernet);
+}
+```
+
+Note that this macro must be used in code, it cannot be used for static initialisation.
+The macro expands to a load from the compartment's import table and so there is no point assigning the result to a global: you will get smaller code using it directly.
+
+Now that you have a `volatile` pointer to the device's MMIO region, you can access its control registers directly.
+Any device can be accessed from any compartment in this way, but that access will appear in the linker audit report.
+
+For this device, you will see an entry like this for any compartment that accesses the device:
+
+```json
+ {
+ "kind": "MMIO",
+ "length": 516,
+ "start": 2550136832
+ },
+```
+
+You can then audit whether a firmware image enforces whatever policy you want (for example, no compartment other than a device driver may access the device directly).
+Note that the linker reports will always provide the addresses and lengths in decimal, because they are standard JSON.
+We support a small number of extensions to JSON in the files that we consume, to improve usability, but don't use these in files that we produce, to improve interoperability.
+
+There is no requirement to expose a device as a single MMIO region.
+You may wish to define multiple regions, which can be as small as a single byte, so that you can privilege separate your device driver.
+
+Some devices have a very large control structure.
+For example, the platform-local interrupt controller is many KiBs.
+We don't define a C structure that covers every single field for this and instead just use `uint32_t` as the type for `MMIO_CAPABILITY`, which lets us treat the space as an array of 32-bit control registers.
+
+Handling interrupts
+-------------------
+
+To be able to handle interrupts, you must have a [software capability](SoftwareCapabilities.md) that [authorises access to the interrupt](Interrupts.md).
+For the ethernet device that we've been using as an example, you would typically request one with this macro invocation:
+
+```c
+DECLARE_AND_DEFINE_INTERRUPT_CAPABILITY(ethernetInterruptCapability, Ethernet, true, true);
+```
+
+If you wish to share this between multiple compilation units, you can use the separate `DECLARE_` and `DEFINE_` forms (see [`interrupt.h`](../sdk/include/interrupt.h)) but the combined form is normally most convenient.
+This macro takes four arguments:
+
+ 1. The name that we're going to use to refer to this capability.
+ The name `ethernetInterruptCapability` is arbitrary, you can use whatever makes sense to you.
+ 2. The name of the interrupt, from the board description file (`Ethernet`, in this case).
+ 3. Whether this capability authorises waiting for this interrupt (this will almost always be `true`).
+ 4. Whether this capability authorises acknowledging the interrupt so that it can fire again.
+ This will almost always be true in device drivers but should generally be true for only one compartment (for each interrupt), whereas multiple compartments may wish to observe interrupts for monitoring.
+
+As with the MMIO capabilities, compartments
+
+```json
+ {
+ "contents": "10000101",
+ "kind": "SealedObject",
+ "sealing_type": {
+ "compartment": "sched",
+ "key": "InterruptKey",
+ "provided_by": "build/cheriot/cheriot/release/example-firmware.scheduler.compartment",
+ "symbol": "__export.sealing_type.sched.InterruptKey"
+ }
+```
+
+The sealing type tells you that this is an interrupt capability (it's sealed with the `InterruptKey` type, provided by the scheduler).
+The contents lets you audit what this authorises.
+The first two bytes are a 16-bit (little-endian on all currently supported targets) integer containing the interrupt number, so 1000 means 16 (our Ethernet interrupt number).
+The next two bytes are boolean values reflecting the last two arguments to the macro, so this authorises both waiting and clearing the macro.
+Again, this can form part of your firmware auditing.
+
+### Waiting on an interrupt
+
+Now that you're authorised to handle interrupts, you will need something that you can wait on.
+Each interrupt is mapped to a futex word, which can be used with scheduler waiting primitives.
+You can get the word associated with an interrupt by passing the authorising capability to the `interrupt_futex_get` function exported by the scheduler:
+
+```c
+const uint32_t *ethernetFutex = ethernetFutex = interrupt_futex_get(STATIC_SEALED_VALUE(ethernetInterruptCapability));
+```
+
+The `ethernetFutex` pointer is now a read-only capability (attempting to store through it will trap) that contains a number that is incremented every time that an interrupt fires. | ```suggestion
The `ethernetFutex` pointer is now a read-only capability (attempting to store through it will trap) that contains a number that is incremented every time the ethernet interrupt fires.
``` |
cheriot-rtos | github_2023 | cpp | 52 | CHERIoT-Platform | davidchisnall | @@ -52,6 +52,18 @@ namespace Revocation
shadowCap = const_cast<WordT *>(MMIO_CAPABILITY(WordT, shadow));
}
+ WordT shadow_paint_bits_above(ptraddr_t addr)
+ {
+ size_t capoffset = (addr - TCMBaseAddr) >> MallocAlignShift; | This bit of arithmetic appears four times in the patch, it would probably be good to move it to a separate helper function. |
cheriot-rtos | github_2023 | cpp | 52 | CHERIoT-Platform | davidchisnall | @@ -87,41 +99,58 @@ namespace Revocation
*/
void shadow_paint_range(ptraddr_t base, ptraddr_t top, bool fill)
{
- constexpr size_t ShadowWordAddrMask =
- (1U << (ShadowWordShift + MallocAlignShift)) - 1;
- ptraddr_t baseUp =
- (base + ShadowWordAddrMask) & ~ShadowWordAddrMask;
- ptraddr_t topDown = top & ~ShadowWordAddrMask;
-
- // There isn't a single aligned shadow word for this range, so paint
- // one bit at a time.
- if (baseUp >= topDown)
+ size_t baseCapOffset = (base - TCMBaseAddr) >> MallocAlignShift;
+ size_t topCapOffset = (top - TCMBaseAddr) >> MallocAlignShift; | These are the other two cases of the same arithmetic. |
cheriot-rtos | github_2023 | cpp | 52 | CHERIoT-Platform | davidchisnall | @@ -52,6 +52,18 @@ namespace Revocation
shadowCap = const_cast<WordT *>(MMIO_CAPABILITY(WordT, shadow));
}
+ WordT shadow_paint_bits_above(ptraddr_t addr)
+ {
+ size_t capoffset = (addr - TCMBaseAddr) >> MallocAlignShift;
+ return ~((1U << (capoffset & ShadowWordMask)) - 1); | ```suggestion
return ~shadow_paint_bits_below();
```
If I understand the logic here correctly, then these two functions must, between them, set all bits when called on the same value. I think you can make them both `constexpr` and then `static_assert` this for some values. |
cheriot-rtos | github_2023 | cpp | 52 | CHERIoT-Platform | davidchisnall | @@ -52,6 +52,18 @@ namespace Revocation
shadowCap = const_cast<WordT *>(MMIO_CAPABILITY(WordT, shadow));
}
+ WordT shadow_paint_bits_above(ptraddr_t addr) | Minor pedantry, but I don't really like the names of these two. `paint` is both a verb and a noun (and we have a style guide rule to avoid those words!) and it took me a couple of reads of the function to realise that you meant the noun and not the verb form. Maybe `shadow_bits_below_address`? |
cheriot-rtos | github_2023 | cpp | 52 | CHERIoT-Platform | davidchisnall | @@ -87,41 +99,58 @@ namespace Revocation
*/
void shadow_paint_range(ptraddr_t base, ptraddr_t top, bool fill)
{
- constexpr size_t ShadowWordAddrMask =
- (1U << (ShadowWordShift + MallocAlignShift)) - 1;
- ptraddr_t baseUp =
- (base + ShadowWordAddrMask) & ~ShadowWordAddrMask;
- ptraddr_t topDown = top & ~ShadowWordAddrMask;
-
- // There isn't a single aligned shadow word for this range, so paint
- // one bit at a time.
- if (baseUp >= topDown)
+ size_t baseCapOffset = (base - TCMBaseAddr) >> MallocAlignShift;
+ size_t topCapOffset = (top - TCMBaseAddr) >> MallocAlignShift;
+ size_t baseWordIx = baseCapOffset >> ShadowWordShift;
+ size_t topWordIx = topCapOffset >> ShadowWordShift;
+
+ WordT maskLo = shadow_paint_bits_above(base);
+ WordT maskHi = shadow_paint_bits_below(top);
+
+ if (baseWordIx == topWordIx)
{
- for (ptraddr_t ptr = base; ptr < top; ptr += MallocAlignment)
+ /*
+ * This object is entirely contained within one word of the
+ * bitmap. We must AND the mask{Hi,Lo} together and use that
+ * to update the right bits.
+ */
+ WordT mask = maskHi & maskLo;
+ if (fill)
+ {
+ shadowCap[baseWordIx] |= mask;
+ }
+ else
{
- shadow_paint_single(ptr, fill);
+ shadowCap[baseWordIx] &= ~mask;
}
+
return;
}
- // First, paint the individual bits at the beginning.
- for (ptraddr_t ptr = base; ptr < baseUp; ptr += MallocAlignment)
+ /*
+ * Otherwise, there are at least two words of the bitmap that need
+ * to be updated with the masks, and possibly some in between that
+ * just need to be set wholesale.
+ */
+
+ WordT midWord;
+ if (fill)
{
- shadow_paint_single(ptr, fill);
+ shadowCap[baseWordIx] |= maskLo;
+ shadowCap[topWordIx] |= maskHi;
+ midWord = ~0; | ```suggestion
midWord = ~WordT(0);
```
You are currently relying on `WordT` being smaller than `int` or signed, implicitly. |
cheriot-rtos | github_2023 | cpp | 52 | CHERIoT-Platform | davidchisnall | @@ -52,6 +52,18 @@ namespace Revocation
shadowCap = const_cast<WordT *>(MMIO_CAPABILITY(WordT, shadow));
}
+ WordT shadow_paint_bits_above(ptraddr_t addr)
+ {
+ size_t capoffset = (addr - TCMBaseAddr) >> MallocAlignShift;
+ return ~((1U << (capoffset & ShadowWordMask)) - 1);
+ }
+
+ WordT shadow_paint_bits_below(ptraddr_t addr)
+ {
+ size_t capoffset = (addr - TCMBaseAddr) >> MallocAlignShift;
+ return (1U << (capoffset & ShadowWordMask)) - 1; | ```suggestion
return (WordT(1) << (capoffset & ShadowWordMask)) - 1;
``` |
cheriot-rtos | github_2023 | cpp | 52 | CHERIoT-Platform | mjp41 | @@ -87,52 +120,69 @@ namespace Revocation
*/
void shadow_paint_range(ptraddr_t base, ptraddr_t top, bool fill)
{
- constexpr size_t ShadowWordAddrMask =
- (1U << (ShadowWordShift + MallocAlignShift)) - 1;
- ptraddr_t baseUp =
- (base + ShadowWordAddrMask) & ~ShadowWordAddrMask;
- ptraddr_t topDown = top & ~ShadowWordAddrMask;
-
- // There isn't a single aligned shadow word for this range, so paint
- // one bit at a time.
- if (baseUp >= topDown)
+ size_t baseCapOffset = shadow_offset_bits(base); | Would it be better to make `fill` a template parameter? It is statically known at both call sites. Might increase code size, but might be neutral?
|
cheriot-rtos | github_2023 | cpp | 88 | CHERIoT-Platform | rmn30 | @@ -1223,13 +1223,24 @@ class MState
{
return nullptr;
}
- if (revoker.shadow_bit_get(address))
+ // If we don't have shadow bits, skip this check and just assume that
+ // this is the start of a capability. This mode is for benchmark | ```suggestion
// this is the start of an allocation. This mode is for benchmark
``` |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,97 @@
+The CHERIoT RTOS memory allocator
+=================================
+
+The CHERIoT platform was designed to support a (safe) shared heap.
+This means that embedded systems that contain multiple mutually distrusting components do not need to pre-reserve memory and so the total SRAM requirement is the peak of all concurrently executing components, not the peak of all components.
+This can be a significant cost reduction for systems that have relatively high memory requirements for different phases of computation, for example doing a post-quantum key exchange at boot followed by running a memory-intensive loop after initialisation.
+
+This document describes the memory model.
+
+Allocator capabilities
+----------------------
+
+Allocating memory requires a capability that authorises memory allocation.
+These are created by the `DECLARE_AND_DEFINE_DEFINE_ALLOCATOR_CAPABILITY` macros, which takes two arguments.
+The first is the name of the capability, the second is the amount of memory that this capability authorises the holder to allocate.
+This capability may then be accessed with the `STATIC_SEALED_VALUE`, which takes the name as the argument.
+If you wish to refer to the same capability from multiple C compilation units, you can use the separate `DECLARE_` and `DEFINE_` versions of this combined macro.
+See [the documentation on software-defined capabilities](SoftwareCapabilities.md) for more information.
+
+
+Compartments may hold more than one allocation capability.
+The design embodies the principle of intentionality: you must explicitly specify the quota against which an allocation counts when performing that allocation. | This might be a good place to mention the default one used by `malloc()`? Or at least foreshadow the section below.
It's a shame there isn't a good way to link to a symbol in the source tree (absent using something like Sphinx, but that's a whole world view unto itself); I guess just referring to
https://github.com/microsoft/cheriot-rtos/blob/0a99d279cd21de801b05c1c9b08b12b0d25590d0/sdk/include/stdlib.h#L71
in prose will have to suffice. |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,97 @@
+The CHERIoT RTOS memory allocator
+=================================
+
+The CHERIoT platform was designed to support a (safe) shared heap.
+This means that embedded systems that contain multiple mutually distrusting components do not need to pre-reserve memory and so the total SRAM requirement is the peak of all concurrently executing components, not the peak of all components.
+This can be a significant cost reduction for systems that have relatively high memory requirements for different phases of computation, for example doing a post-quantum key exchange at boot followed by running a memory-intensive loop after initialisation.
+
+This document describes the memory model.
+
+Allocator capabilities
+----------------------
+
+Allocating memory requires a capability that authorises memory allocation.
+These are created by the `DECLARE_AND_DEFINE_DEFINE_ALLOCATOR_CAPABILITY` macros, which takes two arguments.
+The first is the name of the capability, the second is the amount of memory that this capability authorises the holder to allocate.
+This capability may then be accessed with the `STATIC_SEALED_VALUE`, which takes the name as the argument.
+If you wish to refer to the same capability from multiple C compilation units, you can use the separate `DECLARE_` and `DEFINE_` versions of this combined macro.
+See [the documentation on software-defined capabilities](SoftwareCapabilities.md) for more information.
+
+
+Compartments may hold more than one allocation capability.
+The design embodies the principle of intentionality: you must explicitly specify the quota against which an allocation counts when performing that allocation.
+
+When inspecting the linker audit report for a firmware image, you will see an entry like this for each allocator capability:
+
+```json
+ {
+ "contents": "00001000 00000000 00000000 00000000 00000000 00000000",
+ "kind": "SealedObject",
+ "sealing_type": {
+ "compartment": "alloc",
+ "key": "MallocKey",
+ "provided_by": "build/cheriot/cheriot/release/cherimcu.allocator.compartment",
+ "symbol": "__export.sealing_type.alloc.MallocKey"
+ }
+ },
+```
+
+The `contents` is a hex encoding of the contents of the allocator.
+The first word is the size, so 0x00001000 here indicates that this capability authorises 4096 bytes of allocation.
+The remaining space is reserved for use by the allocator (the object must be 6 words long).
+The sealing type describes the kind of sealed capability that this is, in particular it is a type exposed by the `alloc` compartment as `MallocKey`.
+
+
+Core APIs
+---------
+
+The allocator APIs all begin `heap_`.
+The `heap_allocate` and `heap_allocate_array` functions allocate memory (the latter is safe in the presence of arithmetic overflow).
+All memory allocated by these functions is guaranteed to be zeroed.
+These functions will fail if the allocator capability does not have sufficient remaining quota to handle the allocation.
+All allocations have an eight-byte header and this counts towards the quota, so the total quota required is the sum of the size of all objects plus eight times the number of live objects.
+
+The amount of quota remaining in a allocator capability can be queried with `heap_quota_remaining`.
+
+The `heap_free` function deallocates memory.
+This must be called with the same allocator capability that allocated the memory (you may not free memory unless authorised to do so).
+This function is also used to remove claims (see below).
+
+Claims
+------
+
+In some situations it is important for a compartment to be able to guarantee that another compartment cannot deallocate memory that was delegated to it.
+This is done with the `heap_claim` function, which adds a claim on the memory.
+This prevents the object from being deallocated until the claim is dropped.
+This requires an allocator capability because it can prevent an object from being deallocated and so can increase peak memory consumption in a system.
+This function returns the size of object that has been claimed (or zero on failure) because the object can be larger than the bounds of the capability but there is no way to claim part of an object and allow the remainder to be freed.
+
+Claims are dropped with `heap_free`, which allows cleanup code to relinquish ownership without knowing whether an object was allocated locally or claimed.
+In particular, it is safe to claim an object that you originally allocated, as long as you free it the correct number of times.
+
+Standard APIs
+-------------
+
+The C `malloc` and `free` and C++ `new` and `delete` functions are implemented as inline wrappers around the core functions.
+These use the default malloc capability for the compartment, with a quota defined by the `MALLOC_QUOTA` macro.
+This currently defaults to 4096 bytes.
+
+These APIs are provided for compatibility.
+They are not ideal in embedded systems or with mutual distrust because they do not take explicit allocator capabilities and because they do not provide timeouts (and so can block indefinitely).
+
+We do not provide an implementation of `realloc` because it is dangerous in a single-provenance model. | ```suggestion
We do not provide an implementation of `realloc` because it is dangerous in a single-provenance pointer model.
``` |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,97 @@
+The CHERIoT RTOS memory allocator
+=================================
+
+The CHERIoT platform was designed to support a (safe) shared heap.
+This means that embedded systems that contain multiple mutually distrusting components do not need to pre-reserve memory and so the total SRAM requirement is the peak of all concurrently executing components, not the peak of all components.
+This can be a significant cost reduction for systems that have relatively high memory requirements for different phases of computation, for example doing a post-quantum key exchange at boot followed by running a memory-intensive loop after initialisation.
+
+This document describes the memory model.
+
+Allocator capabilities
+----------------------
+
+Allocating memory requires a capability that authorises memory allocation.
+These are created by the `DECLARE_AND_DEFINE_DEFINE_ALLOCATOR_CAPABILITY` macros, which takes two arguments.
+The first is the name of the capability, the second is the amount of memory that this capability authorises the holder to allocate.
+This capability may then be accessed with the `STATIC_SEALED_VALUE`, which takes the name as the argument.
+If you wish to refer to the same capability from multiple C compilation units, you can use the separate `DECLARE_` and `DEFINE_` versions of this combined macro.
+See [the documentation on software-defined capabilities](SoftwareCapabilities.md) for more information.
+
+
+Compartments may hold more than one allocation capability.
+The design embodies the principle of intentionality: you must explicitly specify the quota against which an allocation counts when performing that allocation.
+
+When inspecting the linker audit report for a firmware image, you will see an entry like this for each allocator capability:
+
+```json
+ {
+ "contents": "00001000 00000000 00000000 00000000 00000000 00000000",
+ "kind": "SealedObject",
+ "sealing_type": {
+ "compartment": "alloc",
+ "key": "MallocKey",
+ "provided_by": "build/cheriot/cheriot/release/cherimcu.allocator.compartment",
+ "symbol": "__export.sealing_type.alloc.MallocKey"
+ }
+ },
+```
+
+The `contents` is a hex encoding of the contents of the allocator.
+The first word is the size, so 0x00001000 here indicates that this capability authorises 4096 bytes of allocation.
+The remaining space is reserved for use by the allocator (the object must be 6 words long).
+The sealing type describes the kind of sealed capability that this is, in particular it is a type exposed by the `alloc` compartment as `MallocKey`.
+
+
+Core APIs
+---------
+
+The allocator APIs all begin `heap_`.
+The `heap_allocate` and `heap_allocate_array` functions allocate memory (the latter is safe in the presence of arithmetic overflow).
+All memory allocated by these functions is guaranteed to be zeroed.
+These functions will fail if the allocator capability does not have sufficient remaining quota to handle the allocation.
+All allocations have an eight-byte header and this counts towards the quota, so the total quota required is the sum of the size of all objects plus eight times the number of live objects.
+
+The amount of quota remaining in a allocator capability can be queried with `heap_quota_remaining`.
+
+The `heap_free` function deallocates memory.
+This must be called with the same allocator capability that allocated the memory (you may not free memory unless authorised to do so).
+This function is also used to remove claims (see below).
+
+Claims
+------
+
+In some situations it is important for a compartment to be able to guarantee that another compartment cannot deallocate memory that was delegated to it.
+This is done with the `heap_claim` function, which adds a claim on the memory.
+This prevents the object from being deallocated until the claim is dropped.
+This requires an allocator capability because it can prevent an object from being deallocated and so can increase peak memory consumption in a system.
+This function returns the size of object that has been claimed (or zero on failure) because the object can be larger than the bounds of the capability but there is no way to claim part of an object and allow the remainder to be freed.
+
+Claims are dropped with `heap_free`, which allows cleanup code to relinquish ownership without knowing whether an object was allocated locally or claimed.
+In particular, it is safe to claim an object that you originally allocated, as long as you free it the correct number of times.
+
+Standard APIs
+-------------
+
+The C `malloc` and `free` and C++ `new` and `delete` functions are implemented as inline wrappers around the core functions.
+These use the default malloc capability for the compartment, with a quota defined by the `MALLOC_QUOTA` macro.
+This currently defaults to 4096 bytes.
+
+These APIs are provided for compatibility.
+They are not ideal in embedded systems or with mutual distrust because they do not take explicit allocator capabilities and because they do not provide timeouts (and so can block indefinitely).
+
+We do not provide an implementation of `realloc` because it is dangerous in a single-provenance model.
+Realloc may not do in-place size reduction usefully because there may be dangling capabilities that have wider bounds.
+Doing length extension in place would cause problems with existing pointers being able to access only a subset of the object.
+The only safe way of implementing realloc is as an allocate, copy, deallocate sequence and users are free to provide their own implementation that does this.
+
+Restricting allocation for a compartment
+----------------------------------------
+
+Compartments can opt out of C malloc by defining `CHERIOT_NO_AMBIENT_MALLOC`.
+This will prevent the `malloc` family of functions being exposed in the compartment.
+It will also prevent the compartment from having a default allocator capability.
+This makes it easy to audit the property that some compartments should not allocate memory: their linker audit report will not contain a capability of the form described above.
+
+The C++ `new` / `delete` functions wrap `malloc` and friends.
+These can be hidden by defining the `CHERIOT_NO_NEW_DELETE` macro. | (But the old delete is just fine? ;)) |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,64 @@
+CHERIoT RTOS Board Descriptions
+===============================
+
+CHERIoT RTOS is intended to run on any core that implements the CHERIoT ISA.
+Our initial prototype was a modification of the Flute core, our initial production implementation is based on Ibex, and we also use a software simulator generated from the Sail formal model.
+The formal model is fairly standard but the cores can run in simulation, FPGA, or as ASICs with different on-chip peripherals, address space layouts, and so on.
+
+To allow software to be portable across these and other implementations, we use a board description file.
+This is a JSON document that contains a single object describing the board.
+The parser supports a small superset of JSON, in particular it permits hex numbers as well as decimal, which is particularly useful for memory addresses. | Aside: does/should it support comments as well, a la something like hjson? (Annoyingly, hjson does not support hex numbers, which is significantly more important for our use, otherwise I'd suggest we just point people at that.) |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,64 @@
+CHERIoT RTOS Board Descriptions
+===============================
+
+CHERIoT RTOS is intended to run on any core that implements the CHERIoT ISA.
+Our initial prototype was a modification of the Flute core, our initial production implementation is based on Ibex, and we also use a software simulator generated from the Sail formal model.
+The formal model is fairly standard but the cores can run in simulation, FPGA, or as ASICs with different on-chip peripherals, address space layouts, and so on.
+
+To allow software to be portable across these and other implementations, we use a board description file.
+This is a JSON document that contains a single object describing the board.
+The parser supports a small superset of JSON, in particular it permits hex numbers as well as decimal, which is particularly useful for memory addresses.
+
+Memory layout
+------------- | This section probably needs a bit more verbiage and/or some worked examples. As a naïve reader, I don't think I'd understand what's here. Maybe something like...
If a shared heap is in use, our security guarantees depend on its backing memory being subject to the "capability load filter".
(This further requires the concomitant `shadow` MMIO device; see below.)
Some architectures may choose to offer this mechanism for only a subset of their memories, restricting the possible placements of the heap.
Instructions and (per-compartment) data do not need to be placed in memory subject to the load filter, but can be if necessary. |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,64 @@
+CHERIoT RTOS Board Descriptions
+===============================
+
+CHERIoT RTOS is intended to run on any core that implements the CHERIoT ISA.
+Our initial prototype was a modification of the Flute core, our initial production implementation is based on Ibex, and we also use a software simulator generated from the Sail formal model.
+The formal model is fairly standard but the cores can run in simulation, FPGA, or as ASICs with different on-chip peripherals, address space layouts, and so on.
+
+To allow software to be portable across these and other implementations, we use a board description file.
+This is a JSON document that contains a single object describing the board.
+The parser supports a small superset of JSON, in particular it permits hex numbers as well as decimal, which is particularly useful for memory addresses.
+
+Memory layout
+-------------
+
+Instruction memory is described by the `instruction_memory` property.
+This must be an object with a `start` and `end` property, each of which is an address.
+
+The region available for the heap is described in the `heap` property.
+This must describe the region over which the load filter is defined.
+If its `start` property is omitted, then it is assumed to start in the same place as instruction memory. | Is that not also true of `end`? |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,64 @@
+CHERIoT RTOS Board Descriptions
+===============================
+
+CHERIoT RTOS is intended to run on any core that implements the CHERIoT ISA.
+Our initial prototype was a modification of the Flute core, our initial production implementation is based on Ibex, and we also use a software simulator generated from the Sail formal model.
+The formal model is fairly standard but the cores can run in simulation, FPGA, or as ASICs with different on-chip peripherals, address space layouts, and so on.
+
+To allow software to be portable across these and other implementations, we use a board description file.
+This is a JSON document that contains a single object describing the board.
+The parser supports a small superset of JSON, in particular it permits hex numbers as well as decimal, which is particularly useful for memory addresses.
+
+Memory layout
+-------------
+
+Instruction memory is described by the `instruction_memory` property. | This is a little misnamed at the moment because it also includes data, right? (In principle we could have ((E)EP)ROM or FLASH backing instructions, RAM backing data, and RAM+shadow backing the heap, yes?) |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,64 @@
+CHERIoT RTOS Board Descriptions
+===============================
+
+CHERIoT RTOS is intended to run on any core that implements the CHERIoT ISA.
+Our initial prototype was a modification of the Flute core, our initial production implementation is based on Ibex, and we also use a software simulator generated from the Sail formal model.
+The formal model is fairly standard but the cores can run in simulation, FPGA, or as ASICs with different on-chip peripherals, address space layouts, and so on.
+
+To allow software to be portable across these and other implementations, we use a board description file.
+This is a JSON document that contains a single object describing the board.
+The parser supports a small superset of JSON, in particular it permits hex numbers as well as decimal, which is particularly useful for memory addresses.
+
+Memory layout
+-------------
+
+Instruction memory is described by the `instruction_memory` property.
+This must be an object with a `start` and `end` property, each of which is an address.
+
+The region available for the heap is described in the `heap` property.
+This must describe the region over which the load filter is defined.
+If its `start` property is omitted, then it is assumed to start in the same place as instruction memory.
+
+MMIO Devices
+------------ | Mention the "shadow" MMIO device (and maybe we should take this as motivation to rename that to something better... "heap_load_filter_bitmap"?) |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,64 @@
+CHERIoT RTOS Board Descriptions
+===============================
+
+CHERIoT RTOS is intended to run on any core that implements the CHERIoT ISA.
+Our initial prototype was a modification of the Flute core, our initial production implementation is based on Ibex, and we also use a software simulator generated from the Sail formal model.
+The formal model is fairly standard but the cores can run in simulation, FPGA, or as ASICs with different on-chip peripherals, address space layouts, and so on.
+
+To allow software to be portable across these and other implementations, we use a board description file.
+This is a JSON document that contains a single object describing the board.
+The parser supports a small superset of JSON, in particular it permits hex numbers as well as decimal, which is particularly useful for memory addresses.
+
+Memory layout
+-------------
+
+Instruction memory is described by the `instruction_memory` property.
+This must be an object with a `start` and `end` property, each of which is an address.
+
+The region available for the heap is described in the `heap` property.
+This must describe the region over which the load filter is defined.
+If its `start` property is omitted, then it is assumed to start in the same place as instruction memory.
+
+MMIO Devices
+------------
+
+Each memory-mapped I/O device is listed as an object within the `devices` field.
+The name of the field is the name of the device and must be an object that contains a `start` and either a `length` or `end` property that, between them, describe the memory range for the device.
+Software can then use the `MMIO_CAPABILITY` macro with the name of the device to get a capability to that device's MMIO range and can use `#if DEVICE_EXISTS(device_name)` to conditionally compile code if that device exists.
+
+Interrupts
+----------
+
+External interrupts should be defined in an array in the `interrupts` property.
+Each element has a `name`, a `number` and a `priority`.
+The name is used to refer to this in software and must be a valid C identifier.
+The number is the interrupt number.
+The priority is the priority with which this interrupt will be configured in the interrupt controller.
+
+Hardware features
+-----------------
+
+Some properties define base parts of hardware support.
+The `revoker` property is either absent (no temporal safety support), `"software"` (revocation is implemented via a software sweep) or `"hardware"` (there is a hardware revoker).
+We expect this to be `"hardware"` on all real implementations, the software revoker exists primarily for the Sail model and the no temporal safety mode only for benchmarking the overhead of revocation.
+
+If the `stack_high_water_mark` property is set to true, then we assume the CPU provides CSRs for tracking stack usage.
+This property is primarily present for benchmarking as all of our targets currently implement this feature.
+
+Clock configuration
+-------------------
+
+The clock rate is configured by two properties.
+The `timer_hz` field is the number of timer increments per second, typically the clock speed of the chip (the RISC-V timer is defined in terms of cycles).
+The `tickrate_hz` specifies how many scheduler ticks should happen per second. | Maybe better describe this as the preemptive scheduling quantum. We have pondered moving to tickless scheduling and could, I think, pretty readily decouple the sleep quantum from the scheduling quantum (if we haven't already?). |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,53 @@
+Interrupt handling in CHERIoT RTOS
+==================================
+
+CHERIoT RTOS does not allow user code to run directly from the interrupt handler.
+The scheduler has a separate stack that is used to run interrupt handler and this then maps interrupts to scheduler events.
+This allows interrupts from asynchronous sources to be handled by threads of any priority.
+
+Futex primer
+------------
+
+Interrupts are mapped to futexes and so it's first important to understand how futexes work. | Maybe this is an American vs British English thing, but I'd prefer a split infinitive or
```suggestion
Interrupts are mapped to futexes and so it's important to understand how futexes work, first.
``` |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,53 @@
+Interrupt handling in CHERIoT RTOS
+==================================
+
+CHERIoT RTOS does not allow user code to run directly from the interrupt handler.
+The scheduler has a separate stack that is used to run interrupt handler and this then maps interrupts to scheduler events.
+This allows interrupts from asynchronous sources to be handled by threads of any priority.
+
+Futex primer
+------------
+
+Interrupts are mapped to futexes and so it's first important to understand how futexes work.
+
+A futex (fast userspace futex) is something of a misnomer on CHERIoT RTOS, where there is no kernel / userspace distinction (the scheduler is a component that is not trusted by the rest of the system for confidentiality or integrity). | ```suggestion
A futex (fast userspace mutex) is traditional but something of a misnomer on CHERIoT RTOS, where there is no kernel / userspace distinction (the scheduler is a component that is not trusted by the rest of the system for confidentiality or integrity).
``` |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,53 @@
+Interrupt handling in CHERIoT RTOS
+==================================
+
+CHERIoT RTOS does not allow user code to run directly from the interrupt handler.
+The scheduler has a separate stack that is used to run interrupt handler and this then maps interrupts to scheduler events.
+This allows interrupts from asynchronous sources to be handled by threads of any priority.
+
+Futex primer
+------------
+
+Interrupts are mapped to futexes and so it's first important to understand how futexes work.
+
+A futex (fast userspace futex) is something of a misnomer on CHERIoT RTOS, where there is no kernel / userspace distinction (the scheduler is a component that is not trusted by the rest of the system for confidentiality or integrity).
+The core idea for a futex is an atomic compare-and-wait operation.
+A `futex_wait` call tests whether a 32-bit word contains the expected value and, if it does, suspends the calling thread until another thread calls `futex_wake` on the futex-word address.
+
+This mechanism is intended to avoid missed wakeups. | ```suggestion
This primitive readily enables sleeping while avoiding missed wakeups.
``` |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,53 @@
+Interrupt handling in CHERIoT RTOS
+==================================
+
+CHERIoT RTOS does not allow user code to run directly from the interrupt handler.
+The scheduler has a separate stack that is used to run interrupt handler and this then maps interrupts to scheduler events.
+This allows interrupts from asynchronous sources to be handled by threads of any priority.
+
+Futex primer
+------------
+
+Interrupts are mapped to futexes and so it's first important to understand how futexes work.
+
+A futex (fast userspace futex) is something of a misnomer on CHERIoT RTOS, where there is no kernel / userspace distinction (the scheduler is a component that is not trusted by the rest of the system for confidentiality or integrity).
+The core idea for a futex is an atomic compare-and-wait operation.
+A `futex_wait` call tests whether a 32-bit word contains the expected value and, if it does, suspends the calling thread until another thread calls `futex_wake` on the futex-word address.
+
+This mechanism is intended to avoid missed wakeups.
+Threads waking waiters are expected to modify the futex word and then call `futex_wake`.
+This ensures that either the modification happens before the wait, in which case the comparison fails and the `futex_wait` call returns immediately, or after in which case it is fine to ignore this `futex_wake` because it is not related to the current value.
+
+This primitive can be used to implement locks. | ```suggestion
This primitive can be used to implement locks (that yield the CPU, avoiding spin-waits).
``` |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,53 @@
+Interrupt handling in CHERIoT RTOS
+==================================
+
+CHERIoT RTOS does not allow user code to run directly from the interrupt handler.
+The scheduler has a separate stack that is used to run interrupt handler and this then maps interrupts to scheduler events.
+This allows interrupts from asynchronous sources to be handled by threads of any priority.
+
+Futex primer
+------------
+
+Interrupts are mapped to futexes and so it's first important to understand how futexes work.
+
+A futex (fast userspace futex) is something of a misnomer on CHERIoT RTOS, where there is no kernel / userspace distinction (the scheduler is a component that is not trusted by the rest of the system for confidentiality or integrity).
+The core idea for a futex is an atomic compare-and-wait operation.
+A `futex_wait` call tests whether a 32-bit word contains the expected value and, if it does, suspends the calling thread until another thread calls `futex_wake` on the futex-word address.
+
+This mechanism is intended to avoid missed wakeups.
+Threads waking waiters are expected to modify the futex word and then call `futex_wake`.
+This ensures that either the modification happens before the wait, in which case the comparison fails and the `futex_wait` call returns immediately, or after in which case it is fine to ignore this `futex_wake` because it is not related to the current value.
+
+This primitive can be used to implement locks.
+The [`locks.hh`](../sdk/include/locks.hh) file contains a flag lock and a ticket lock that use a futex, for example.
+
+Futexes for interrupts
+----------------------
+
+Each interrupt number has a futex associated with it.
+This futex contains a number that is incremented every time that the interrupt fires.
+The scheduler then wakes any threads that are sleeping on that futex.
+A thread that wants to block waiting for an interrupt reads the value of this futex word and then calls `futex_wait` to be notified when the word has been incremented one or more times.
+
+This mechanism allows multiple threads to wait for the same interrupt and perform different bits of processing, for example a network stack may receive an interrupt to detect that a packet needs handling and a lower-priority thread may record telemetry on the number of packets that have been received. | ```suggestion
This mechanism allows multiple threads to wait for the same interrupt and perform different bits of processing, for example a network stack may receive an interrupt to detect that a packet needs handling and a lower-priority thread may record telemetry on the number of packet interrupts that have been received.
``` |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,53 @@
+Interrupt handling in CHERIoT RTOS
+==================================
+
+CHERIoT RTOS does not allow user code to run directly from the interrupt handler.
+The scheduler has a separate stack that is used to run interrupt handler and this then maps interrupts to scheduler events.
+This allows interrupts from asynchronous sources to be handled by threads of any priority.
+
+Futex primer
+------------
+
+Interrupts are mapped to futexes and so it's first important to understand how futexes work.
+
+A futex (fast userspace futex) is something of a misnomer on CHERIoT RTOS, where there is no kernel / userspace distinction (the scheduler is a component that is not trusted by the rest of the system for confidentiality or integrity).
+The core idea for a futex is an atomic compare-and-wait operation.
+A `futex_wait` call tests whether a 32-bit word contains the expected value and, if it does, suspends the calling thread until another thread calls `futex_wake` on the futex-word address.
+
+This mechanism is intended to avoid missed wakeups.
+Threads waking waiters are expected to modify the futex word and then call `futex_wake`.
+This ensures that either the modification happens before the wait, in which case the comparison fails and the `futex_wait` call returns immediately, or after in which case it is fine to ignore this `futex_wake` because it is not related to the current value.
+
+This primitive can be used to implement locks.
+The [`locks.hh`](../sdk/include/locks.hh) file contains a flag lock and a ticket lock that use a futex, for example.
+
+Futexes for interrupts
+----------------------
+
+Each interrupt number has a futex associated with it.
+This futex contains a number that is incremented every time that the interrupt fires.
+The scheduler then wakes any threads that are sleeping on that futex.
+A thread that wants to block waiting for an interrupt reads the value of this futex word and then calls `futex_wait` to be notified when the word has been incremented one or more times.
+
+This mechanism allows multiple threads to wait for the same interrupt and perform different bits of processing, for example a network stack may receive an interrupt to detect that a packet needs handling and a lower-priority thread may record telemetry on the number of packets that have been received.
+
+The `interrupt_futex_get` requests the futex for a particular interrupt.
+This returns a read-only capability that can be read directly to get the number of times that an interrupt has fired and can be used for `futex_wait`.
+
+Note that, because interrupt futexes are just normal futexes, they can also be used with the [multiwaiter](../sdk/include/multiwater.h) API, for example to wait for an interrupt or a message from another thread, whichever happens first. | ```suggestion
Because interrupt futexes are just normal futexes, they can also be used with the [multiwaiter](../sdk/include/multiwater.h) API, for example to wait for an interrupt or a message from another thread, whichever happens first.
``` |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,53 @@
+Interrupt handling in CHERIoT RTOS
+==================================
+
+CHERIoT RTOS does not allow user code to run directly from the interrupt handler.
+The scheduler has a separate stack that is used to run interrupt handler and this then maps interrupts to scheduler events.
+This allows interrupts from asynchronous sources to be handled by threads of any priority.
+
+Futex primer
+------------
+
+Interrupts are mapped to futexes and so it's first important to understand how futexes work.
+
+A futex (fast userspace futex) is something of a misnomer on CHERIoT RTOS, where there is no kernel / userspace distinction (the scheduler is a component that is not trusted by the rest of the system for confidentiality or integrity).
+The core idea for a futex is an atomic compare-and-wait operation.
+A `futex_wait` call tests whether a 32-bit word contains the expected value and, if it does, suspends the calling thread until another thread calls `futex_wake` on the futex-word address.
+
+This mechanism is intended to avoid missed wakeups.
+Threads waking waiters are expected to modify the futex word and then call `futex_wake`.
+This ensures that either the modification happens before the wait, in which case the comparison fails and the `futex_wait` call returns immediately, or after in which case it is fine to ignore this `futex_wake` because it is not related to the current value.
+
+This primitive can be used to implement locks.
+The [`locks.hh`](../sdk/include/locks.hh) file contains a flag lock and a ticket lock that use a futex, for example.
+
+Futexes for interrupts
+----------------------
+
+Each interrupt number has a futex associated with it.
+This futex contains a number that is incremented every time that the interrupt fires.
+The scheduler then wakes any threads that are sleeping on that futex.
+A thread that wants to block waiting for an interrupt reads the value of this futex word and then calls `futex_wait` to be notified when the word has been incremented one or more times.
+
+This mechanism allows multiple threads to wait for the same interrupt and perform different bits of processing, for example a network stack may receive an interrupt to detect that a packet needs handling and a lower-priority thread may record telemetry on the number of packets that have been received.
+
+The `interrupt_futex_get` requests the futex for a particular interrupt.
+This returns a read-only capability that can be read directly to get the number of times that an interrupt has fired and can be used for `futex_wait`. | Are these exposed in the linker's audit summary? (I don't think they necessarily have to be, but it could be a side-channel between compartments.) |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,53 @@
+Interrupt handling in CHERIoT RTOS
+==================================
+
+CHERIoT RTOS does not allow user code to run directly from the interrupt handler.
+The scheduler has a separate stack that is used to run interrupt handler and this then maps interrupts to scheduler events.
+This allows interrupts from asynchronous sources to be handled by threads of any priority.
+
+Futex primer
+------------
+
+Interrupts are mapped to futexes and so it's first important to understand how futexes work.
+
+A futex (fast userspace futex) is something of a misnomer on CHERIoT RTOS, where there is no kernel / userspace distinction (the scheduler is a component that is not trusted by the rest of the system for confidentiality or integrity).
+The core idea for a futex is an atomic compare-and-wait operation.
+A `futex_wait` call tests whether a 32-bit word contains the expected value and, if it does, suspends the calling thread until another thread calls `futex_wake` on the futex-word address.
+
+This mechanism is intended to avoid missed wakeups.
+Threads waking waiters are expected to modify the futex word and then call `futex_wake`.
+This ensures that either the modification happens before the wait, in which case the comparison fails and the `futex_wait` call returns immediately, or after in which case it is fine to ignore this `futex_wake` because it is not related to the current value.
+
+This primitive can be used to implement locks.
+The [`locks.hh`](../sdk/include/locks.hh) file contains a flag lock and a ticket lock that use a futex, for example.
+
+Futexes for interrupts
+----------------------
+
+Each interrupt number has a futex associated with it.
+This futex contains a number that is incremented every time that the interrupt fires.
+The scheduler then wakes any threads that are sleeping on that futex.
+A thread that wants to block waiting for an interrupt reads the value of this futex word and then calls `futex_wait` to be notified when the word has been incremented one or more times.
+
+This mechanism allows multiple threads to wait for the same interrupt and perform different bits of processing, for example a network stack may receive an interrupt to detect that a packet needs handling and a lower-priority thread may record telemetry on the number of packets that have been received.
+
+The `interrupt_futex_get` requests the futex for a particular interrupt.
+This returns a read-only capability that can be read directly to get the number of times that an interrupt has fired and can be used for `futex_wait`.
+
+Note that, because interrupt futexes are just normal futexes, they can also be used with the [multiwaiter](../sdk/include/multiwater.h) API, for example to wait for an interrupt or a message from another thread, whichever happens first.
+
+Acknowledging interrupts
+------------------------
+
+The scheduler will not acknowledge external interrupts until explicitly told to do so.
+The `interrupt_complete` function marks the interrupt as having been handled.
+An interrupt will not be delivered again until it has been acknowledged. | This probably needs some more blinkenlights: if multiple threads wait on an interrupt, only one of them should acknowledge each firing, right? Do I need anything but the read-only count capability to call `interrupt_complete`? |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,96 @@
+Static sealed objects in CHERIoT RTOS
+=====================================
+
+CHERIoT is a capability system.
+This extends from the hardware (all memory accesses require an authorising capability in a register, provided as an operand to an instruction) up through the software abstractions in the RTOS.
+In a capability system, any privileged operation requires an explicit capability to authorise it.
+
+Privilege is a somewhat fluid notion in a system with fine-grained mutual distrust but, in general, any operation that affects state beyond the current compartment is considered privileged.
+This includes actions such as:
+
+ - Acknowledging interrupts
+ - Allocating heap memory
+ - Establishing network connections | More generally, external hardware is "state beyond the current compartment"... include "updating das blinkenlights" and "firing the missiles" in that list? |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,96 @@
+Static sealed objects in CHERIoT RTOS
+=====================================
+
+CHERIoT is a capability system.
+This extends from the hardware (all memory accesses require an authorising capability in a register, provided as an operand to an instruction) up through the software abstractions in the RTOS.
+In a capability system, any privileged operation requires an explicit capability to authorise it.
+
+Privilege is a somewhat fluid notion in a system with fine-grained mutual distrust but, in general, any operation that affects state beyond the current compartment is considered privileged.
+This includes actions such as:
+
+ - Acknowledging interrupts
+ - Allocating heap memory
+ - Establishing network connections
+
+Each of these should require that the caller present a capability that authorises the callee to perform the action on behalf of the caller.
+
+Delegation is an important part of a capability system.
+A capability may be passed from compartment A to compartment B, which can then use it to ask C to perform some privileged operation.
+The identity of the immediate caller does not matter.
+
+CHERI capabilities to software-defined capabilities
+---------------------------------------------------
+
+CHERI provides a hardware mechanism for building software-defined capabilities: sealing.
+The sealing mechanism allows a pointer (a CHERI capability) to be made immutable and unusable until it is unsealed using an authorising capability.
+The CHERIoT ISA has a limited set of space for sealing types and so these are virtualised with the allocator's [token](../sdk/include/token.h) APIs.
+These APIs combine allocation and sealing, returning both sealed and unsealed capabilities to an object.
+The unsealed capability can be used directly, the sealed capability can be passed to other code and unsealed only by calling the allocator's `token_unseal` function with the capability used to allocate the object.
+
+A compartment can use this to generate software-defined capabilities that represent dynamic resources.
+For example, a network stack can use it to allocate the state associated with a connection.
+The scheduler uses the same mechanism for providing capabilities for cross-thread communication so that, for example, only a holder of the relevant capability can send or receive messages in a message queue.
+
+Static software-defined capabilities
+------------------------------------
+
+In addition to the dynamic software-defined capabilities, it is often useful to provision a set of capabilities to a compartment at build time. | Maybe draw out the distinction a bit more... something like this, perhaps:
```suggestion
Dynamic software-defined capabilities are (by necessity) exposed to the allocating compartment and must be passed to other compartments (usually in response to some request).
It is often useful to be able to provide software-defined capabilities (managed by one compartment) to another compartment at _build time_, avoiding the need to manage request-response handshake(s) early in initialization.
``` |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,96 @@
+Static sealed objects in CHERIoT RTOS
+=====================================
+
+CHERIoT is a capability system.
+This extends from the hardware (all memory accesses require an authorising capability in a register, provided as an operand to an instruction) up through the software abstractions in the RTOS.
+In a capability system, any privileged operation requires an explicit capability to authorise it.
+
+Privilege is a somewhat fluid notion in a system with fine-grained mutual distrust but, in general, any operation that affects state beyond the current compartment is considered privileged.
+This includes actions such as:
+
+ - Acknowledging interrupts
+ - Allocating heap memory
+ - Establishing network connections
+
+Each of these should require that the caller present a capability that authorises the callee to perform the action on behalf of the caller.
+
+Delegation is an important part of a capability system.
+A capability may be passed from compartment A to compartment B, which can then use it to ask C to perform some privileged operation.
+The identity of the immediate caller does not matter.
+
+CHERI capabilities to software-defined capabilities
+---------------------------------------------------
+
+CHERI provides a hardware mechanism for building software-defined capabilities: sealing.
+The sealing mechanism allows a pointer (a CHERI capability) to be made immutable and unusable until it is unsealed using an authorising capability.
+The CHERIoT ISA has a limited set of space for sealing types and so these are virtualised with the allocator's [token](../sdk/include/token.h) APIs.
+These APIs combine allocation and sealing, returning both sealed and unsealed capabilities to an object.
+The unsealed capability can be used directly, the sealed capability can be passed to other code and unsealed only by calling the allocator's `token_unseal` function with the capability used to allocate the object.
+
+A compartment can use this to generate software-defined capabilities that represent dynamic resources.
+For example, a network stack can use it to allocate the state associated with a connection.
+The scheduler uses the same mechanism for providing capabilities for cross-thread communication so that, for example, only a holder of the relevant capability can send or receive messages in a message queue.
+
+Static software-defined capabilities
+------------------------------------
+
+In addition to the dynamic software-defined capabilities, it is often useful to provision a set of capabilities to a compartment at build time.
+The simplest case for this is (allocator capabilities)[Allocator.md], which authorise allocation and so are necessary to be able to create any dynamic software-defined capabilities. | ```suggestion
The simplest case for this is (allocator capabilities)[Allocator.md], which authorise allocation (and so are necessary to be able to create any dynamic software-defined capabilities!).
``` |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,96 @@
+Static sealed objects in CHERIoT RTOS
+=====================================
+
+CHERIoT is a capability system.
+This extends from the hardware (all memory accesses require an authorising capability in a register, provided as an operand to an instruction) up through the software abstractions in the RTOS.
+In a capability system, any privileged operation requires an explicit capability to authorise it.
+
+Privilege is a somewhat fluid notion in a system with fine-grained mutual distrust but, in general, any operation that affects state beyond the current compartment is considered privileged.
+This includes actions such as:
+
+ - Acknowledging interrupts
+ - Allocating heap memory
+ - Establishing network connections
+
+Each of these should require that the caller present a capability that authorises the callee to perform the action on behalf of the caller.
+
+Delegation is an important part of a capability system.
+A capability may be passed from compartment A to compartment B, which can then use it to ask C to perform some privileged operation.
+The identity of the immediate caller does not matter.
+
+CHERI capabilities to software-defined capabilities
+---------------------------------------------------
+
+CHERI provides a hardware mechanism for building software-defined capabilities: sealing.
+The sealing mechanism allows a pointer (a CHERI capability) to be made immutable and unusable until it is unsealed using an authorising capability.
+The CHERIoT ISA has a limited set of space for sealing types and so these are virtualised with the allocator's [token](../sdk/include/token.h) APIs.
+These APIs combine allocation and sealing, returning both sealed and unsealed capabilities to an object.
+The unsealed capability can be used directly, the sealed capability can be passed to other code and unsealed only by calling the allocator's `token_unseal` function with the capability used to allocate the object.
+
+A compartment can use this to generate software-defined capabilities that represent dynamic resources.
+For example, a network stack can use it to allocate the state associated with a connection.
+The scheduler uses the same mechanism for providing capabilities for cross-thread communication so that, for example, only a holder of the relevant capability can send or receive messages in a message queue.
+
+Static software-defined capabilities
+------------------------------------
+
+In addition to the dynamic software-defined capabilities, it is often useful to provision a set of capabilities to a compartment at build time.
+The simplest case for this is (allocator capabilities)[Allocator.md], which authorise allocation and so are necessary to be able to create any dynamic software-defined capabilities.
+The scheduler also uses this mechanism for capabilities that allow interaction with [interrupts](Interrupts.md).
+
+Objects created in this way are allocated outside of a compartment's global region but are accessed only via capabilities provided by the loader.
+These capabilities use the allocator's sealing mechanism and so can be unsealed only by the owner of the relevant sealing capability. | ```suggestion
These capabilities use the allocator's token mechanism and so can be unsealed only with the relevant authorising capability.
``` |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,96 @@
+Static sealed objects in CHERIoT RTOS
+=====================================
+
+CHERIoT is a capability system.
+This extends from the hardware (all memory accesses require an authorising capability in a register, provided as an operand to an instruction) up through the software abstractions in the RTOS.
+In a capability system, any privileged operation requires an explicit capability to authorise it.
+
+Privilege is a somewhat fluid notion in a system with fine-grained mutual distrust but, in general, any operation that affects state beyond the current compartment is considered privileged.
+This includes actions such as:
+
+ - Acknowledging interrupts
+ - Allocating heap memory
+ - Establishing network connections
+
+Each of these should require that the caller present a capability that authorises the callee to perform the action on behalf of the caller.
+
+Delegation is an important part of a capability system.
+A capability may be passed from compartment A to compartment B, which can then use it to ask C to perform some privileged operation.
+The identity of the immediate caller does not matter.
+
+CHERI capabilities to software-defined capabilities
+---------------------------------------------------
+
+CHERI provides a hardware mechanism for building software-defined capabilities: sealing.
+The sealing mechanism allows a pointer (a CHERI capability) to be made immutable and unusable until it is unsealed using an authorising capability.
+The CHERIoT ISA has a limited set of space for sealing types and so these are virtualised with the allocator's [token](../sdk/include/token.h) APIs.
+These APIs combine allocation and sealing, returning both sealed and unsealed capabilities to an object.
+The unsealed capability can be used directly, the sealed capability can be passed to other code and unsealed only by calling the allocator's `token_unseal` function with the capability used to allocate the object.
+
+A compartment can use this to generate software-defined capabilities that represent dynamic resources.
+For example, a network stack can use it to allocate the state associated with a connection.
+The scheduler uses the same mechanism for providing capabilities for cross-thread communication so that, for example, only a holder of the relevant capability can send or receive messages in a message queue.
+
+Static software-defined capabilities
+------------------------------------
+
+In addition to the dynamic software-defined capabilities, it is often useful to provision a set of capabilities to a compartment at build time.
+The simplest case for this is (allocator capabilities)[Allocator.md], which authorise allocation and so are necessary to be able to create any dynamic software-defined capabilities.
+The scheduler also uses this mechanism for capabilities that allow interaction with [interrupts](Interrupts.md).
+
+Objects created in this way are allocated outside of a compartment's global region but are accessed only via capabilities provided by the loader. | ```suggestion
Objects created in this way are allocated outside of any compartment's global region and are accessed only via capabilities provided by the loader.
The initial contents of these objects are specified during definition, which is often located within a compartment that does not have the rights to unseal the resulting object.
Therefore, these contents, as well as the type of the software-defined capability, are reported in the linker's audit summary and must be validated; see below.
``` |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,96 @@
+Static sealed objects in CHERIoT RTOS
+=====================================
+
+CHERIoT is a capability system.
+This extends from the hardware (all memory accesses require an authorising capability in a register, provided as an operand to an instruction) up through the software abstractions in the RTOS.
+In a capability system, any privileged operation requires an explicit capability to authorise it.
+
+Privilege is a somewhat fluid notion in a system with fine-grained mutual distrust but, in general, any operation that affects state beyond the current compartment is considered privileged.
+This includes actions such as:
+
+ - Acknowledging interrupts
+ - Allocating heap memory
+ - Establishing network connections
+
+Each of these should require that the caller present a capability that authorises the callee to perform the action on behalf of the caller.
+
+Delegation is an important part of a capability system.
+A capability may be passed from compartment A to compartment B, which can then use it to ask C to perform some privileged operation.
+The identity of the immediate caller does not matter.
+
+CHERI capabilities to software-defined capabilities
+---------------------------------------------------
+
+CHERI provides a hardware mechanism for building software-defined capabilities: sealing.
+The sealing mechanism allows a pointer (a CHERI capability) to be made immutable and unusable until it is unsealed using an authorising capability.
+The CHERIoT ISA has a limited set of space for sealing types and so these are virtualised with the allocator's [token](../sdk/include/token.h) APIs.
+These APIs combine allocation and sealing, returning both sealed and unsealed capabilities to an object.
+The unsealed capability can be used directly, the sealed capability can be passed to other code and unsealed only by calling the allocator's `token_unseal` function with the capability used to allocate the object.
+
+A compartment can use this to generate software-defined capabilities that represent dynamic resources.
+For example, a network stack can use it to allocate the state associated with a connection.
+The scheduler uses the same mechanism for providing capabilities for cross-thread communication so that, for example, only a holder of the relevant capability can send or receive messages in a message queue.
+
+Static software-defined capabilities
+------------------------------------
+
+In addition to the dynamic software-defined capabilities, it is often useful to provision a set of capabilities to a compartment at build time.
+The simplest case for this is (allocator capabilities)[Allocator.md], which authorise allocation and so are necessary to be able to create any dynamic software-defined capabilities.
+The scheduler also uses this mechanism for capabilities that allow interaction with [interrupts](Interrupts.md).
+
+Objects created in this way are allocated outside of a compartment's global region but are accessed only via capabilities provided by the loader.
+These capabilities use the allocator's sealing mechanism and so can be unsealed only by the owner of the relevant sealing capability.
+
+For more detail on how to use the static sealing mechanism, see [`compartment-macros.h`](../sdk/include/compartment-macros.h).
+
+### Exporting a sealing type
+
+The `STATIC_SEALING_TYPE` macro defines a new sealing type that the loader can use to seal static objects.
+This macro also evaluates to the capability that permits unsealing.
+
+Static sealing capabilities are defined by both their name and the name of the compartment that exports them and so the name that you pick does not need to be unique (though, for documentation purposes, it should not be too generic).
+
+### Creating a sealed value
+
+Static sealed values are created with the `DECLARE_STATIC_SEALED_VALUE` and `DEFINE_STATIC_SEALED_VALUE` macros.
+These construct an object with the specified type and contents.
+
+**Note:** These objects may not contain pointers. | What goes wrong if I try? Is the explosion at compile time, link time, load time, or run time? If run time, do I just see a 0 tag on the pointer value? |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | rmn30 | @@ -0,0 +1,98 @@
+The CHERIoT RTOS memory allocator
+=================================
+
+The CHERIoT platform was designed to support a (safe) shared heap.
+This means that embedded systems that contain multiple mutually distrusting components do not need to pre-reserve memory and so the total SRAM requirement is the peak of all concurrently executing components, not the peak of all components.
+This can be a significant cost reduction for systems that have relatively high memory requirements for different phases of computation, for example doing a post-quantum key exchange at boot followed by running a memory-intensive loop after initialisation.
+
+This document describes the memory model.
+
+Allocator capabilities
+----------------------
+
+Allocating memory requires a capability that authorises memory allocation.
+These are created by the `DECLARE_AND_DEFINE_DEFINE_ALLOCATOR_CAPABILITY` macros, which takes two arguments. | ```suggestion
These are created by the `DECLARE_AND_DEFINE_DEFINE_ALLOCATOR_CAPABILITY` macro, which takes two arguments.
``` |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | rmn30 | @@ -0,0 +1,98 @@
+The CHERIoT RTOS memory allocator
+=================================
+
+The CHERIoT platform was designed to support a (safe) shared heap.
+This means that embedded systems that contain multiple mutually distrusting components do not need to pre-reserve memory and so the total SRAM requirement is the peak of all concurrently executing components, not the peak of all components.
+This can be a significant cost reduction for systems that have relatively high memory requirements for different phases of computation, for example doing a post-quantum key exchange at boot followed by running a memory-intensive loop after initialisation.
+
+This document describes the memory model.
+
+Allocator capabilities
+----------------------
+
+Allocating memory requires a capability that authorises memory allocation.
+These are created by the `DECLARE_AND_DEFINE_DEFINE_ALLOCATOR_CAPABILITY` macros, which takes two arguments.
+The first is the name of the capability, the second is the amount of memory that this capability authorises the holder to allocate.
+This capability may then be accessed with the `STATIC_SEALED_VALUE`, which takes the name as the argument. | ```suggestion
This capability may then be accessed with the `STATIC_SEALED_VALUE` macro, which takes the name as the argument.
``` |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | rmn30 | @@ -0,0 +1,98 @@
+The CHERIoT RTOS memory allocator
+=================================
+
+The CHERIoT platform was designed to support a (safe) shared heap.
+This means that embedded systems that contain multiple mutually distrusting components do not need to pre-reserve memory and so the total SRAM requirement is the peak of all concurrently executing components, not the peak of all components.
+This can be a significant cost reduction for systems that have relatively high memory requirements for different phases of computation, for example doing a post-quantum key exchange at boot followed by running a memory-intensive loop after initialisation.
+
+This document describes the memory model.
+
+Allocator capabilities
+----------------------
+
+Allocating memory requires a capability that authorises memory allocation.
+These are created by the `DECLARE_AND_DEFINE_DEFINE_ALLOCATOR_CAPABILITY` macros, which takes two arguments.
+The first is the name of the capability, the second is the amount of memory that this capability authorises the holder to allocate.
+This capability may then be accessed with the `STATIC_SEALED_VALUE`, which takes the name as the argument.
+If you wish to refer to the same capability from multiple C compilation units, you can use the separate `DECLARE_` and `DEFINE_` versions of this combined macro.
+See [the documentation on software-defined capabilities](SoftwareCapabilities.md) for more information.
+
+
+Compartments may hold more than one allocation capability.
+The design embodies the principle of intentionality: you must explicitly specify the quota against which an allocation counts when performing that allocation.
+The standard C/C++ interfaces do not respect this principle and so are implemented as wrappers (see below). | ```suggestion
The standard C/C++ interfaces do not respect this principle and so are implemented as wrappers that use a default allocator capability (see below).
``` |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | rmn30 | @@ -0,0 +1,98 @@
+The CHERIoT RTOS memory allocator
+=================================
+
+The CHERIoT platform was designed to support a (safe) shared heap.
+This means that embedded systems that contain multiple mutually distrusting components do not need to pre-reserve memory and so the total SRAM requirement is the peak of all concurrently executing components, not the peak of all components.
+This can be a significant cost reduction for systems that have relatively high memory requirements for different phases of computation, for example doing a post-quantum key exchange at boot followed by running a memory-intensive loop after initialisation.
+
+This document describes the memory model.
+
+Allocator capabilities
+----------------------
+
+Allocating memory requires a capability that authorises memory allocation.
+These are created by the `DECLARE_AND_DEFINE_DEFINE_ALLOCATOR_CAPABILITY` macros, which takes two arguments.
+The first is the name of the capability, the second is the amount of memory that this capability authorises the holder to allocate.
+This capability may then be accessed with the `STATIC_SEALED_VALUE`, which takes the name as the argument.
+If you wish to refer to the same capability from multiple C compilation units, you can use the separate `DECLARE_` and `DEFINE_` versions of this combined macro.
+See [the documentation on software-defined capabilities](SoftwareCapabilities.md) for more information.
+
+
+Compartments may hold more than one allocation capability.
+The design embodies the principle of intentionality: you must explicitly specify the quota against which an allocation counts when performing that allocation.
+The standard C/C++ interfaces do not respect this principle and so are implemented as wrappers (see below).
+
+When inspecting the linker audit report for a firmware image, you will see an entry like this for each allocator capability:
+
+```json
+ {
+ "contents": "00001000 00000000 00000000 00000000 00000000 00000000",
+ "kind": "SealedObject",
+ "sealing_type": {
+ "compartment": "alloc",
+ "key": "MallocKey",
+ "provided_by": "build/cheriot/cheriot/release/cherimcu.allocator.compartment",
+ "symbol": "__export.sealing_type.alloc.MallocKey"
+ }
+ },
+```
+
+The `contents` is a hex encoding of the contents of the allocator. | ```suggestion
The `contents` is a hex encoding of the contents of the allocator capability.
``` |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | rmn30 | @@ -0,0 +1,98 @@
+The CHERIoT RTOS memory allocator
+=================================
+
+The CHERIoT platform was designed to support a (safe) shared heap.
+This means that embedded systems that contain multiple mutually distrusting components do not need to pre-reserve memory and so the total SRAM requirement is the peak of all concurrently executing components, not the peak of all components.
+This can be a significant cost reduction for systems that have relatively high memory requirements for different phases of computation, for example doing a post-quantum key exchange at boot followed by running a memory-intensive loop after initialisation.
+
+This document describes the memory model.
+
+Allocator capabilities
+----------------------
+
+Allocating memory requires a capability that authorises memory allocation.
+These are created by the `DECLARE_AND_DEFINE_DEFINE_ALLOCATOR_CAPABILITY` macros, which takes two arguments.
+The first is the name of the capability, the second is the amount of memory that this capability authorises the holder to allocate.
+This capability may then be accessed with the `STATIC_SEALED_VALUE`, which takes the name as the argument.
+If you wish to refer to the same capability from multiple C compilation units, you can use the separate `DECLARE_` and `DEFINE_` versions of this combined macro.
+See [the documentation on software-defined capabilities](SoftwareCapabilities.md) for more information.
+
+
+Compartments may hold more than one allocation capability.
+The design embodies the principle of intentionality: you must explicitly specify the quota against which an allocation counts when performing that allocation.
+The standard C/C++ interfaces do not respect this principle and so are implemented as wrappers (see below).
+
+When inspecting the linker audit report for a firmware image, you will see an entry like this for each allocator capability:
+
+```json
+ {
+ "contents": "00001000 00000000 00000000 00000000 00000000 00000000",
+ "kind": "SealedObject",
+ "sealing_type": {
+ "compartment": "alloc",
+ "key": "MallocKey",
+ "provided_by": "build/cheriot/cheriot/release/cherimcu.allocator.compartment",
+ "symbol": "__export.sealing_type.alloc.MallocKey"
+ }
+ },
+```
+
+The `contents` is a hex encoding of the contents of the allocator.
+The first word is the size, so 0x00001000 here indicates that this capability authorises 4096 bytes of allocation.
+The remaining space is reserved for use by the allocator (the object must be 6 words long).
+The sealing type describes the kind of sealed capability that this is, in particular it is a type exposed by the `alloc` compartment as `MallocKey`.
+
+
+Core APIs
+---------
+
+The allocator APIs all begin `heap_`.
+The `heap_allocate` and `heap_allocate_array` functions allocate memory (the latter is safe in the presence of arithmetic overflow).
+All memory allocated by these functions is guaranteed to be zeroed.
+These functions will fail if the allocator capability does not have sufficient remaining quota to handle the allocation. | ```suggestion
These functions will fail if the allocator capability does not have sufficient remaining quota to handle the allocation (or if the allocator itself is out of memory).
``` |
cheriot-rtos | github_2023 | others | 84 | CHERIoT-Platform | rmn30 | @@ -0,0 +1,111 @@
+CHERIoT RTOS Board Descriptions
+===============================
+
+CHERIoT RTOS is intended to run on any core that implements the CHERIoT ISA.
+Our initial prototype was a modification of the Flute core, our initial production implementation is based on Ibex, and we also use a software simulator generated from the Sail formal model.
+The formal model is fairly standard but the cores can run in simulation, FPGA, or as ASICs with different on-chip peripherals, address space layouts, and so on.
+
+To allow software to be portable across these and other implementations, we use a board description file.
+This is a JSON document that contains a single object describing the board.
+The parser supports a small superset of JSON, in particular it permits hex numbers as well as decimal, which is particularly useful for memory addresses.
+
+The [`boards`](../sdk/boards) directory contains some existing examples.
+
+Memory layout
+-------------
+
+Our security guarantees for the shared heap depend the mechanism that allows the allocator to mark memory as quarantined. | ```suggestion
Our security guarantees for the shared heap depend on the mechanism that allows the allocator to mark memory as quarantined.
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.