1 /* 2 * A file accessor employing a "host" file provided via the C library. 3 * 4 * Copyright (C) 2021 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 <stdio.h> 23 #include <string.h> 24 #include <sys/types.h> 25 #include <sys/stat.h> 26 27 #include "host_file_accessor.h" 28 29 HostFileAccessor::HostFileAccessor(FILE *fp, fileid_t fileid) 30 : Accessor(fileid), _fp(fp) 31 { 32 /* Initialise the size of the file. */ 33 34 struct stat buf; 35 36 if (!fstat(fileno(fp), &buf)) 37 _size = buf.st_size; 38 else 39 _size = 0; 40 } 41 42 /* Return the size of the file. */ 43 44 offset_t HostFileAccessor::get_size() 45 { 46 return _size; 47 } 48 49 /* Update the size of the file. */ 50 51 void HostFileAccessor::set_size(offset_t size) 52 { 53 _size = size; 54 } 55 56 /* Perform any closing operation on the file. */ 57 58 void HostFileAccessor::close() 59 { 60 if (_closed) 61 return; 62 63 fclose(_fp); 64 _closed = true; 65 } 66 67 /* Data transfer helper methods. */ 68 69 void HostFileAccessor::fill_populated(Flexpage *flexpage) 70 { 71 offset_t filepos = flexpage->base_offset; 72 offset_t addr = flexpage->base_addr; 73 74 /* Seek to the offset in the file. */ 75 76 fseek(_fp, filepos, SEEK_SET); 77 78 /* Tag the region with file state. */ 79 80 flexpage->region->fill(fileid, filepos); 81 82 /* Fill the region with file content. */ 83 84 size_t nread = fread((void *) addr, sizeof(char), flexpage->size, _fp); 85 86 /* Pad the flexpage with zero. */ 87 88 memset((void *) (addr + nread), 0, flexpage->size - nread); 89 } 90 91 void HostFileAccessor::flush_populated(Flexpage *flexpage) 92 { 93 flexpage->region->flush(); 94 } 95 96 // vim: tabstop=4 expandtab shiftwidth=4