1 /* 2 * Program memory segment support. 3 * 4 * Copyright (C) 2022 Paul Boddie <paul@boddie.org.uk> 5 * 6 * This program is free software; you can redistribute it and/or 7 * modify it under the terms of the GNU General Public License as 8 * published by the Free Software Foundation; either version 2 of 9 * the License, or (at your option) any later version. 10 * 11 * This program is distributed in the hope that it will be useful, 12 * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 * GNU General Public License for more details. 15 * 16 * You should have received a copy of the GNU General Public License 17 * along with this program; if not, write to the Free Software 18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, 19 * Boston, MA 02110-1301, USA 20 */ 21 22 #include <l4/sys/err.h> 23 24 #include <ipc/mem_ipc.h> 25 #include <mem/memory_utils.h> 26 27 #include <stdio.h> 28 #include <string.h> 29 30 #include "segment.h" 31 32 33 34 /* Initialise a memory segment. */ 35 36 Segment::Segment(offset_t base, offset_t size, l4re_rm_flags_t flags, 37 offset_t file_offset, offset_t file_contents) 38 : base(base), size(size), flags(flags), file_offset(file_offset), 39 file_contents(file_contents) 40 { 41 region_base = trunc(base, L4_PAGESIZE); 42 region_offset = base - region_base; 43 region_size = round(size, L4_PAGESIZE); 44 } 45 46 /* Allocate a region for the segment. */ 47 48 long Segment::allocate() 49 { 50 return ipc_allocate_align(size, L4RE_RM_F_SEARCH_ADDR | flags, 51 L4_PAGESHIFT, (void **) &buf, &ds); 52 } 53 54 /* Fill a segment region with file content. */ 55 56 long Segment::fill(file_t *file) 57 { 58 if (!file_contents) 59 return L4_EOK; 60 61 memset(buf, 0, region_size); 62 client_seek(file, file_offset, SEEK_SET); 63 offset_t nread = client_read(file, buf + region_offset, file_contents); 64 65 if (nread < file_contents) 66 return -L4_EIO; 67 else 68 return L4_EOK; 69 } 70 71 /* Define and return the mapped region for the segment. */ 72 73 MappedRegion &Segment::region() 74 { 75 _region = MappedRegion((l4_addr_t) buf, page_order(region_size), flags, region_base); 76 return _region; 77 } 78 79 /* Return the mapped address corresponding to the given address. */ 80 81 l4_addr_t Segment::region_address(char *address) 82 { 83 return (l4_addr_t) ((address - buf) + (char *) region_base); 84 } 85 86 l4_addr_t Segment::region_address(l4_addr_t address) 87 { 88 return (address - (l4_addr_t) buf) + region_base; 89 } 90 91 /* vim: tabstop=2 expandtab shiftwidth=2 92 */