1.1 --- a/file.cc Sat Mar 13 17:49:23 2021 +0100
1.2 +++ b/file.cc Sat Mar 13 22:38:33 2021 +0100
1.3 @@ -22,6 +22,8 @@
1.4 #include <ipc/cap_alloc.h>
1.5 #include <ipc/mem_ipc.h>
1.6
1.7 +#include <string.h>
1.8 +
1.9 #include "dataspace_client.h"
1.10 #include "opener_client.h"
1.11 #include "opener_context_client.h"
1.12 @@ -76,6 +78,17 @@
1.13 file->ref = L4_INVALID_CAP;
1.14 }
1.15
1.16 +/* Open a file using the given structure and context. */
1.17 +
1.18 +long file_open(file_t *file, file_t *context)
1.19 +{
1.20 + client_OpenerContext openercontext(context->ref);
1.21 + file_init(file);
1.22 + return openercontext.open(L4_FPAGE_RW, &file->size, &file->ref);
1.23 +}
1.24 +
1.25 +
1.26 +
1.27 /* Map a region of the given file to a memory region. */
1.28
1.29 long file_mmap(file_t *file, offset_t position, offset_t length)
1.30 @@ -86,16 +99,7 @@
1.31 if (err)
1.32 return err;
1.33
1.34 - return ipc_attach_dataspace(file->ref, file->end_pos - file->start_pos, (void **) &file->memory);
1.35 -}
1.36 -
1.37 -/* Open a file using the given structure and context. */
1.38 -
1.39 -long file_open(file_t *file, file_t *context)
1.40 -{
1.41 - client_OpenerContext openercontext(context->ref);
1.42 - file_init(file);
1.43 - return openercontext.open(L4_FPAGE_RW, &file->size, &file->ref);
1.44 + return ipc_attach_dataspace(file->ref, file_span(file), (void **) &file->memory);
1.45 }
1.46
1.47 /* Return the amount of data in the mapped region for the given file. */
1.48 @@ -113,4 +117,50 @@
1.49 return file->end_pos - file->start_pos;
1.50 }
1.51
1.52 +
1.53 +
1.54 +/* Get a pointer to any terminated string at the given offset or NULL if the
1.55 + data from offset is not terminated. */
1.56 +
1.57 +char *file_string_get(file_t *file, offset_t offset)
1.58 +{
1.59 + offset_t limit = file_span(file) - offset;
1.60 +
1.61 + if (strnlen(file->memory + offset, limit) < limit)
1.62 + return file->memory + offset;
1.63 + else
1.64 + return NULL;
1.65 +}
1.66 +
1.67 +/* Copy a string to the mapped region at the given offset, returning the number
1.68 + of copied characters excluding the zero terminator. */
1.69 +
1.70 +offset_t file_string_set(file_t *file, const char *data, offset_t offset)
1.71 +{
1.72 + offset_t i, pos, limit = file_span(file) - 1;
1.73 +
1.74 + /* Do not attempt to copy data with an invalid offset. */
1.75 +
1.76 + if (offset > limit)
1.77 + return 0;
1.78 +
1.79 + /* Copy the data to the given offset, stopping before the final byte of the
1.80 + region. */
1.81 +
1.82 + for (i = 0, pos = offset; pos < limit; i++, pos++)
1.83 + {
1.84 + file->memory[pos] = data[i];
1.85 +
1.86 + /* Terminator written, can return immediately. */
1.87 +
1.88 + if (!data[i])
1.89 + return pos - offset - 1;
1.90 + }
1.91 +
1.92 + /* Terminate the incomplete string at the end of the region. */
1.93 +
1.94 + file->memory[limit] = '\0';
1.95 + return limit - offset;
1.96 +}
1.97 +
1.98 // vim: tabstop=2 expandtab shiftwidth=2