|
| 1 | +#include "sys.h" |
| 2 | +#include <openkal/exec.h> |
| 3 | + |
| 4 | +// openkal.exec on this kernel. |
| 5 | +// |
| 6 | +// A mapping obtained writable and made executable afterwards. The kernel places |
| 7 | +// no condition upon either step, so this implementation provides the interface |
| 8 | +// unconditionally --- unlike one of the other systems, where the same interface |
| 9 | +// is available only to a program produced in a particular way, which clause 6.5 |
| 10 | +// covers and which is not this system's case. |
| 11 | +// |
| 12 | +// The reservation is not made executable at the outset even though this kernel |
| 13 | +// would permit it. Two of the three environments the specification targets |
| 14 | +// refuse a mapping that is both, so an implementation that returned one here |
| 15 | +// would be offering a program a shape it could not use elsewhere --- and the |
| 16 | +// program would discover that only on the other system. The interface states |
| 17 | +// the narrower contract and this implementation keeps to it. |
| 18 | + |
| 19 | +namespace { |
| 20 | + |
| 21 | +constexpr okl_uptr kPage = 4096; |
| 22 | + |
| 23 | +okl_uptr round_up(okl_uptr n, okl_uptr to) { return (n + to - 1) & ~(to - 1); } |
| 24 | + |
| 25 | +} // namespace |
| 26 | + |
| 27 | +extern "C" { |
| 28 | + |
| 29 | +void* kal_exec_alloc(kal_uintptr size) { |
| 30 | + if (size == 0) return nullptr; |
| 31 | + const okl_uptr bytes = round_up(static_cast<okl_uptr>(size), kPage); |
| 32 | + const okl_long r = okl::sys(okl::nr_mmap, 0, static_cast<okl_long>(bytes), |
| 33 | + okl::prot_read | okl::prot_write, |
| 34 | + okl::map_private | okl::map_anonymous, -1, 0); |
| 35 | + if (okl::failed(r)) return nullptr; |
| 36 | + return reinterpret_cast<void*>(r); |
| 37 | +} |
| 38 | + |
| 39 | +int kal_exec_publish(void* p, kal_uintptr size) { |
| 40 | + if (p == nullptr || size == 0) return kal_err_invalid; |
| 41 | + const okl_uptr bytes = round_up(static_cast<okl_uptr>(size), kPage); |
| 42 | + const okl_long r = okl::sys(okl::nr_mprotect, reinterpret_cast<okl_long>(p), |
| 43 | + static_cast<okl_long>(bytes), |
| 44 | + okl::prot_read | okl::prot_exec); |
| 45 | + if (okl::failed(r)) return okl::translate(r); |
| 46 | + return kal_ok; |
| 47 | +} |
| 48 | + |
| 49 | +void kal_exec_free(void* p, kal_uintptr size) { |
| 50 | + if (p == nullptr || size == 0) return; |
| 51 | + const okl_uptr bytes = round_up(static_cast<okl_uptr>(size), kPage); |
| 52 | + okl::sys(okl::nr_munmap, reinterpret_cast<okl_long>(p), |
| 53 | + static_cast<okl_long>(bytes)); |
| 54 | +} |
| 55 | + |
| 56 | +// A published region may be reserved for writing again: this kernel's |
| 57 | +// protection call is not one-way. The position is set accordingly, and a |
| 58 | +// caller that must change published bytes need not abandon the region. |
| 59 | +const kal_uintptr kal_exec_props = KAL_EXEC_PROP_REPUBLISH; |
| 60 | + |
| 61 | +} // extern "C" |
0 commit comments