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(l4_addr_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 /* Make regions writable if they need to be filled. */ 51 52 l4re_rm_flags_t allocation_flags = flags; 53 54 if (file_contents) 55 allocation_flags |= L4RE_RM_F_W; 56 57 return ipc_allocate_align(size, L4RE_RM_F_SEARCH_ADDR | allocation_flags, 58 L4_PAGESHIFT, (void **) &buf, &ds); 59 } 60 61 /* Fill a segment region with file content. */ 62 63 long Segment::fill(file_t *file) 64 { 65 if (!file_contents) 66 return L4_EOK; 67 68 memset(buf, 0, region_size); 69 client_seek(file, file_offset, SEEK_SET); 70 offset_t nread = client_read(file, buf + region_offset, file_contents); 71 72 if (nread < file_contents) 73 return -L4_EIO; 74 else 75 return L4_EOK; 76 } 77 78 /* Define and return the mapped region for the segment. */ 79 80 MappedRegion &Segment::region() 81 { 82 _region = MappedRegion((l4_addr_t) buf, page_order(region_size), flags, region_base); 83 return _region; 84 } 85 86 /* Return the mapped address corresponding to the given address. */ 87 88 l4_addr_t Segment::region_address(char *address) 89 { 90 return (l4_addr_t) ((address - buf) + (char *) region_base); 91 } 92 93 l4_addr_t Segment::region_address(l4_addr_t address) 94 { 95 return (address - (l4_addr_t) buf) + region_base; 96 } 97 98 /* vim: tabstop=2 expandtab shiftwidth=2 99 */