[dali_2.3.29] Merge branch 'devel/master'
[platform/core/uifw/dali-adaptor.git] / dali / internal / system / common / shared-file.cpp
1 /*
2  * Copyright (c) 2014 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali/internal/system/common/shared-file.h>
20
21 // EXTERNAL INCLUDES
22 #include <fcntl.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <sys/file.h>
26 #include <sys/mman.h>
27 #include <sys/stat.h>
28 #include <sys/types.h>
29 #include <unistd.h>
30 #include <cstring>
31
32 namespace Dali
33 {
34 namespace Internal
35 {
36 namespace Adaptor
37 {
38 SharedFile* SharedFile::New(const char* filename, int size, bool isSystem)
39 {
40   SharedFile* sf = NULL;
41
42   sf = new SharedFile;
43
44   bool opened = sf->OpenFile(filename, size, isSystem);
45   if(!opened)
46   {
47     delete sf;
48     sf = NULL;
49   }
50   return sf;
51 }
52
53 SharedFile::SharedFile()
54 : mFileDescriptor(-1),
55   mSize(0),
56   mAddress(NULL),
57   mFilename()
58 {
59 }
60
61 SharedFile::~SharedFile()
62 {
63   Close();
64 }
65
66 void SharedFile::Close()
67 {
68   if(mAddress != NULL)
69   {
70     munmap(mAddress, mSize);
71     mAddress = NULL;
72   }
73
74   if(mFileDescriptor >= 0)
75   {
76     close(mFileDescriptor);
77     mFileDescriptor = -1;
78   }
79 }
80
81 unsigned char* SharedFile::GetAddress()
82 {
83   return static_cast<unsigned char*>(mAddress);
84 }
85
86 bool SharedFile::OpenFile(const char* filename, int size, bool isSystem)
87 {
88   bool opened = false;
89
90   mode_t mode;
91
92   mode = S_IRUSR | S_IWUSR;
93   if(isSystem)
94   {
95     mode |= S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
96   }
97
98   mFileDescriptor = Open(filename, size, O_RDONLY, mode);
99
100   if(mFileDescriptor >= 0)
101   {
102     mFilename = filename;
103
104     mSize    = size;
105     mAddress = mmap(NULL, mSize, PROT_READ, MAP_SHARED, mFileDescriptor, 0);
106
107 // MAP_FAILED is a macro with C cast
108 #pragma GCC diagnostic push
109 #pragma GCC diagnostic ignored "-Wold-style-cast"
110     if(mAddress != MAP_FAILED)
111     {
112       opened = true;
113     }
114 #pragma GCC diagnostic pop
115   }
116   return opened;
117 }
118
119 } // namespace Adaptor
120 } // namespace Internal
121 } // namespace Dali