Swarm-NG  1.1
fakemmap.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  * Copyright (C) 2005 by Mario Juric *
3  * mjuric@astro.Princeton.EDU *
4  * *
5  * This program is free software; you can redistribute it and/or modify *
6  * it under the terms of the GNU General Public License as published by *
7  * the Free Software Foundation; either version 2 of the License, or *
8  * (at your option) any later version. *
9  * *
10  * This program is distributed in the hope that it will be useful, *
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13  * GNU General Public License for more details. *
14  * *
15  * You should have received a copy of the GNU General Public License *
16  * along with this program; if not, write to the *
17  * Free Software Foundation, Inc., *
18  * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
19  ***************************************************************************/
20 
26 #include "fakemmap.h"
27 #include <map>
28 #include <assert.h>
29 #include <algorithm>
30 #include <stdio.h>
31 
32 using std::min;
33 
34 struct mapping_t {
35  int fd;
36  off_t offset;
37 };
38 
39 #undef SSIZE_MAX
40 const size_t SSIZE_MAX = 10240UL;
41 
42 std::map<size_t,mapping_t> mappings;
43 
44 void *fakemmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset){
45  // Allocate memory for the mapping
46  if(addr==0) addr = malloc(length);
47 
48  // Set up the file and memory
49  char* caddr = (char*)addr;
50  lseek(fd, offset, SEEK_SET);
51 
52  // Read the contents of the file into memory
53  int l = 0;
54  for(int i = 0; i < 10000; i++){
55  int s = read(fd,caddr+l,min(length-l,SSIZE_MAX));
56  //int s = read(fd,caddr+l,min(length-l,10240UL));
57  if(s==-1){
58  return MAP_FAILED;
59  }else if(s==0)
60  break;
61  else
62  l+=s;
63  }
64 
65  // Save mapping information
66  mappings[(size_t)addr].fd = fd;
67  mappings[(size_t)addr].offset = offset;
68 
69  // Same behavior as mmap
70  return addr;
71 }
72 
73 int fakemsync(void *addr, size_t length, int flags) {
74  // Load mapping information
75  int fd = mappings[(size_t)addr].fd;
76  off_t offset = mappings[(size_t)addr].offset;
77 
78  // Set up file and memory
79  char* caddr = (char*)addr;
80  lseek(fd, offset, SEEK_SET);
81 
82  // Write memory to file
83  int l = 0;
84  for(int i = 0; i < 10000; i++){
85  int s = write(fd,caddr+l,min(length-l,SSIZE_MAX));
86  //int s = write(fd,caddr+l,min(length-l,10240UL));
87  if(s==-1)
88  return -1;
89  else if( s == 0)
90  break;
91  else
92  l+=s;
93  }
94 
95  // Same behavior
96  return 0;
97 }
98 
99 int fakemunmap(void *addr, size_t length){
100  int r = fakemsync(addr,length,0);
101  free(addr);
102  return r;
103 }
104