1 // Copyright (c) 1999-2018 David Muse
2 // See the file COPYING for more information
3
4 #include <rudiments/file.h>
5 #include <rudiments/permissions.h>
6 #include <rudiments/sys.h>
7 #include <rudiments/charstring.h>
8 #include <rudiments/memorymap.h>
9 #include <rudiments/process.h>
10 #include <rudiments/error.h>
11 #include <rudiments/stringbuffer.h>
12 #include <rudiments/stdio.h>
13 #include "test.cpp"
14
main(int argc,const char ** argv)15 int main(int argc, const char **argv) {
16
17 header("memorymap");
18
19 if (!memorymap::supported()) {
20 stdoutput.printf(" not supported\n\n");
21 return 0;
22 }
23
24 size_t allocgran=sys::getAllocationGranularity();
25
26 // create a file to test with
27 file::remove("memorymap.txt");
28 file fd;
29 test("create file",fd.create("memorymap.txt",
30 permissions::evalPermString("rw-r--r--")));
31
32 char *buffer=new char[allocgran];
33 for (uint16_t i=0; i<10; i++) {
34 for (size_t j=0; j<allocgran; j++) {
35 buffer[j]='0'+i;
36 }
37 fd.write(buffer,allocgran);
38 }
39 delete[] buffer;
40
41 // loop, mapping blocks of the file
42 memorymap mm;
43 for (uint16_t i=0; i<10; i++) {
44
45 // attach to the next block
46 test("attach",mm.attach(fd.getFileDescriptor(),
47 i*allocgran,allocgran,
48 PROT_READ,MAP_PRIVATE));
49
50 // get a pointer to the block
51 const char *ptr=(const char *)mm.getData();
52 test("valid ptr",(ptr!=NULL));
53
54 // see if it contains the correct data
55 bool success=true;
56 for (size_t j=0; j<allocgran; j++) {
57 if (*(ptr+j)!='0'+i) {
58 success=false;
59 break;
60 }
61 }
62 stringbuffer blockname;
63 blockname.append("block ")->append(i);
64 test(blockname.getString(),success);
65
66 // detach from the block
67 test("detach",mm.detach());
68 }
69 stdoutput.printf("\n");
70
71 // close the file
72 fd.close();
73
74 // clean up
75 file::remove("memorymap.txt");
76 }
77