From 90d6c637c5f3cdfeac0eccb8b1315a500e18467b Mon Sep 17 00:00:00 2001 From: Peter Evans Date: Wed, 3 Jan 2018 21:10:25 -0600 Subject: [PATCH] Add function to copy a buffer into a segment --- include/vm_segment.h | 1 + src/vm_segment.c | 27 +++++++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/include/vm_segment.h b/include/vm_segment.h index 2ae1eda..7a2f2a5 100644 --- a/include/vm_segment.h +++ b/include/vm_segment.h @@ -54,6 +54,7 @@ struct vm_segment { }; extern int vm_segment_copy(vm_segment *, vm_segment *, size_t, size_t, size_t); +extern int vm_segment_copy_buf(vm_segment *, const vm_8bit *, size_t, size_t, size_t); extern int vm_segment_fread(vm_segment *, FILE *, size_t, size_t); extern int vm_segment_read_map(vm_segment *, size_t, vm_segment_read_fn); extern int vm_segment_set(vm_segment *, size_t, vm_8bit); diff --git a/src/vm_segment.c b/src/vm_segment.c index ffa4e0d..0c75bf0 100644 --- a/src/vm_segment.c +++ b/src/vm_segment.c @@ -186,6 +186,33 @@ vm_segment_copy(vm_segment *dest, return OK; } +/* + * Copy the contents of buf into the given dest segment. This is mostly + * governed by the same restrictions that copy() has, except that we + * can't do all of the bounds-checking we do there. This is just saying, + * hey, I have a bunch of bytes and I just need this copied into a + * segment, if you don't mind. + */ +int +vm_segment_copy_buf(vm_segment *dest, const vm_8bit *src, + size_t destoff, size_t srcoff, size_t len) +{ + if (destoff + len > dest->size) { + log_critical("Attempt to copy buffer out of bounds (%d + %d >= %d)", + destoff, len, dest->size); + return ERR_OOB; + } + + // Heh heh...there's no way of knowing if srcoff + len is out of + // bounds at any point of src, since it's just a dumb buffer. Here's + // hopin' it's not! Also, it'll be a fun day when sizeof(vm_8bit) is + // not 1, BUT HEY. Let's do it right. + memcpy(dest->memory + destoff, src + srcoff, + len * sizeof(vm_8bit)); + + return OK; +} + /* * Set the read mapper for a given address. We'll use this function * instead of the normal logic on a get for that address.