forked from NatronGitHub/Natron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MemoryFile.cpp
444 lines (397 loc) · 14.1 KB
/
MemoryFile.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
/* ***** BEGIN LICENSE BLOCK *****
* This file is part of Natron <https://natrongithub.github.io/>,
* (C) 2018-2021 The Natron developers
* (C) 2013-2018 INRIA and Alexandre Gauthier-Foichat
*
* Natron is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Natron is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Natron. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>
* ***** END LICENSE BLOCK ***** */
// ***** BEGIN PYTHON BLOCK *****
// from <https://docs.python.org/3/c-api/intro.html#include-files>:
// "Since Python may define some pre-processor definitions which affect the standard headers on some systems, you must include Python.h before any standard headers are included."
#include <Python.h>
// ***** END PYTHON BLOCK *****
#include "MemoryFile.h"
#ifdef __NATRON_WIN32__
# include <windows.h>
#else // unix
//# include <errno.h>
#include <fcntl.h>
#include <sys/mman.h> // mmap, munmap.
#include <sys/stat.h>
#include <sys/types.h> // struct stat.
#include <unistd.h> // sysconf.
#include <cstring>
#include <cerrno>
#include <cstdio>
#endif
#include <sstream> // stringstream
#include <iostream>
#include <cassert>
#include <stdexcept>
#include "Global/GlobalDefines.h"
#include "Global/StrUtils.h"
#define MIN_FILE_SIZE 4096
NATRON_NAMESPACE_ENTER
struct MemoryFilePrivate
{
std::string path; //< filepath of the backing file
char* data; //< pointer to the beginning of the mapped file
size_t size; //< the effective size of the file
#if defined(__NATRON_UNIX__)
int file_handle; //< unix file handle
#elif defined(__NATRON_WIN32__)
HANDLE file_handle; //< windows file handle
HANDLE file_mapping_handle; //< windows memory mapped handle
#else
#error Only Unix or Windows systems can use memory-mapped files.
#endif
MemoryFilePrivate(const std::string & filepath)
: path(filepath)
, data(0)
, size(0)
#if defined(__NATRON_UNIX__)
, file_handle(-1)
#elif defined(__NATRON_WIN32__)
, file_handle(INVALID_HANDLE_VALUE)
, file_mapping_handle(INVALID_HANDLE_VALUE)
#endif
{
}
void openInternal(MemoryFile::FileOpenModeEnum open_mode);
void closeMapping(bool drop_pages);
};
MemoryFile::MemoryFile()
: _imp( new MemoryFilePrivate( std::string() ) )
{
}
MemoryFile::MemoryFile(const std::string & filepath,
FileOpenModeEnum open_mode)
: _imp( new MemoryFilePrivate(filepath) )
{
_imp->openInternal(open_mode);
}
MemoryFile::MemoryFile(const std::string & filepath,
size_t size,
FileOpenModeEnum open_mode)
: _imp( new MemoryFilePrivate(filepath) )
{
_imp->openInternal(open_mode);
resize(size);
}
void
MemoryFile::open(const std::string & filepath,
FileOpenModeEnum open_mode)
{
if (!_imp->path.empty() || _imp->data) {
return;
}
_imp->path = filepath;
_imp->openInternal(open_mode);
}
void
MemoryFilePrivate::openInternal(MemoryFile::FileOpenModeEnum open_mode)
{
#if defined(__NATRON_UNIX__)
/*********************************************************
********************************************************
CHOOSING FILE OPEN MODE
********************************************************
*********************************************************/
int posix_open_mode = O_RDWR;
switch (open_mode) {
case MemoryFile::eFileOpenModeEnumIfExistsFailElseCreate:
posix_open_mode |= O_EXCL | O_CREAT;
break;
case MemoryFile::eFileOpenModeEnumIfExistsKeepElseFail:
break;
case MemoryFile::eFileOpenModeEnumIfExistsKeepElseCreate:
posix_open_mode |= O_CREAT;
break;
case MemoryFile::eFileOpenModeEnumIfExistsTruncateElseFail:
posix_open_mode |= O_TRUNC;
break;
case MemoryFile::eFileOpenModeEnumIfExistsTruncateElseCreate:
posix_open_mode |= O_TRUNC | O_CREAT;
break;
default:
return;
}
/*********************************************************
********************************************************
OPENING THE FILE WITH RIGHT PERMISSIONS:
- R/W user
- R Group
- R Other
********************************************************
*********************************************************/
file_handle = ::open(path.c_str(), posix_open_mode, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (file_handle == -1) {
std::stringstream ss;
ss << "MemoryFile EXC : Failed to open \"" << path << "\": " << std::strerror(errno) << " (" << errno << ")";
throw std::runtime_error( ss.str() );
}
/*********************************************************
********************************************************
GET FILE SIZE
********************************************************
*********************************************************/
struct stat sbuf;
if (::fstat(file_handle, &sbuf) == -1) {
std::stringstream ss;
ss << "MemoryFile EXC : Failed to get file info \"" << path << "\": " << std::strerror(errno) << " (" << errno << ")";
throw std::runtime_error( ss.str() );
}
/*********************************************************
********************************************************
IF FILE IS NOT EMPTY, MMAP IT
********************************************************
*********************************************************/
if (sbuf.st_size > 0) {
data = static_cast<char*>( ::mmap(
0, sbuf.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, file_handle, 0) );
if (data == MAP_FAILED) {
data = 0;
std::stringstream ss;
ss << "MemoryFile EXC : Failed to create mapping for \"" << path << "\": " << std::strerror(errno) << " (" << errno << ")";
throw std::runtime_error( ss.str() );
} else {
size = sbuf.st_size;
}
}
#elif defined(__NATRON_WIN32__)
/*********************************************************
********************************************************
CHOOSING FILE OPEN MODE
********************************************************
*********************************************************/
int windows_open_mode;
switch (open_mode) {
case MemoryFile::eFileOpenModeEnumIfExistsFailElseCreate:
windows_open_mode = CREATE_NEW;
break;
case MemoryFile::eFileOpenModeEnumIfExistsKeepElseFail:
windows_open_mode = OPEN_EXISTING;
break;
case MemoryFile::eFileOpenModeEnumIfExistsKeepElseCreate:
windows_open_mode = OPEN_ALWAYS;
break;
case MemoryFile::eFileOpenModeEnumIfExistsTruncateElseFail:
windows_open_mode = TRUNCATE_EXISTING;
break;
case MemoryFile::eFileOpenModeEnumIfExistsTruncateElseCreate:
windows_open_mode = CREATE_ALWAYS;
break;
default:
std::string str("MemoryFile EXC : Invalid open mode. ");
str.append(path);
throw std::runtime_error(str);
return;
}
/*********************************************************
********************************************************
OPENING THE FILE WITH RIGHT PERMISSIONS:
- R/W
********************************************************
*********************************************************/
std::wstring wpath = StrUtils::utf8_to_utf16(path);
file_handle = ::CreateFileW(wpath.c_str(), GENERIC_READ | GENERIC_WRITE,
0, 0, windows_open_mode, FILE_ATTRIBUTE_NORMAL, 0);
if (file_handle == INVALID_HANDLE_VALUE) {
std::string winError = StrUtils::GetLastErrorAsString();
std::string str("MemoryFile EXC : Failed to open file ");
str.append(path);
str.append(winError);
throw std::runtime_error(str);
}
/*********************************************************
********************************************************
GET FILE SIZE
********************************************************
*********************************************************/
size_t fileSize = ::GetFileSize(file_handle, 0);
/*********************************************************
********************************************************
IF FILE IS NOT EMPTY, MMAP IT
********************************************************
*********************************************************/
if (fileSize > 0) {
file_mapping_handle = ::CreateFileMapping(file_handle, 0, PAGE_READWRITE, 0, 0, 0);
data = static_cast<char*>( ::MapViewOfFile(file_mapping_handle, FILE_MAP_WRITE, 0, 0, 0) );
if (data) {
size = fileSize;
} else {
throw std::runtime_error("MemoryFile EXC : Failed to create mapping.");
}
}
#endif // if defined(__NATRON_UNIX__)
} // openInternal
char*
MemoryFile::data() const
{
return _imp->data;
}
size_t
MemoryFile::size() const
{
return _imp->size;
}
std::string
MemoryFile::path() const
{
return _imp->path;
}
void
MemoryFile::resize(size_t new_size)
{
#if defined(__NATRON_UNIX__)
if (_imp->data) {
if (::munmap(_imp->data, _imp->size) < 0) {
std::stringstream ss;
ss << "MemoryFile EXC : Failed to unmap \"" << _imp->path << "\": " << std::strerror(errno) << " (" << errno << ")";
throw std::runtime_error( ss.str() );
}
}
if (::ftruncate(_imp->file_handle, new_size) < 0) {
std::stringstream ss;
ss << "MemoryFile EXC : Failed to truncate the file \"" << _imp->path << "\": " << std::strerror(errno) << " (" << errno << ")";
throw std::runtime_error( ss.str() );
}
_imp->data = static_cast<char*>( ::mmap(
0, new_size, PROT_READ | PROT_WRITE, MAP_SHARED, _imp->file_handle, 0) );
if (_imp->data == MAP_FAILED) {
_imp->data = 0;
std::stringstream ss;
ss << "MemoryFile EXC : Failed to create mapping of \"" << _imp->path << "\": " << std::strerror(errno) << " (" << errno << ")";
throw std::runtime_error( ss.str() );
}
#elif defined(__NATRON_WIN32__)
::UnmapViewOfFile(_imp->data);
::CloseHandle(_imp->file_mapping_handle);
_imp->file_mapping_handle = ::CreateFileMapping(
_imp->file_handle, 0, PAGE_READWRITE, 0, new_size, 0);
_imp->data = static_cast<char*>( ::MapViewOfFile(
_imp->file_mapping_handle, FILE_MAP_WRITE, 0, 0, 0) );
#endif
if (!_imp->data) {
throw std::bad_alloc();
}
_imp->size = new_size;
}
void
MemoryFilePrivate::closeMapping(bool drop_pages)
{
#if defined(__NATRON_UNIX__)
if (drop_pages) {
int rc;
#ifdef MS_KILLPAGES
// Mac OS X always returns an error with MADV_FREE,
// so we'll use msync(MS_KILLPAGES) instead.
rc = msync(data, size, MS_KILLPAGES);
//if( rc ) return ERR_MEM_STR_NUM("drop_pages(MS_KILLPAGES) failed", rc);
#else
# ifdef MADV_FREE
rc = madvise(data, size, MADV_FREE);
//if( rc ) return ERR_MEM_STR_NUM("drop_pages(MADV_FREE) failed", rc);
# else
# ifdef POSIX_MADV_DONTNEED
// we just hope that DONTNEED will actually free
// the pages...
rc = posix_madvise(data, size, POSIX_MADV_DONTNEED);
//if( rc ) return ERR_MEM_STR_NUM("drop_pages(POSIX_MADV_DONTNEED) failed", rc);
# else
rc = madvise(data, size, MADV_DONTNEED);
//if( rc ) return ERR_MEM_STR_NUM("drop_pages(MADV_DONTNEED) failed", rc);
// end if POSIX_MADV_DONTNEED
# endif
// end if MADV_FREE
# endif
// end if MS_KILLPAGES
#endif
Q_UNUSED(rc);
}
if (::munmap(data, size) != 0) {
std::stringstream ss;
ss << "MemoryFile EXC : Failed to unmap \"" << path << "\": " << std::strerror(errno) << " (" << errno << ")";
throw std::runtime_error( ss.str() );
}
::close(file_handle);
#elif defined(__NATRON_WIN32__)
Q_UNUSED(drop_pages);
if (::UnmapViewOfFile(data) == 0) {
throw std::runtime_error("Failed to unmap the mapped file");
}
::CloseHandle(file_mapping_handle);
::CloseHandle(file_handle);
#endif
}
bool
MemoryFile::flush(FlushTypeEnum type, void* data, std::size_t size)
{
void* ptr = data ? data : _imp->data;
std::size_t n = data ? size : _imp->size;
#if defined(__NATRON_UNIX__)
switch (type) {
case eFlushTypeAsync:
return ::msync(ptr, n, MS_ASYNC) == 0;
case eFlushTypeSync:
return ::msync(ptr, n, MS_SYNC) == 0;
case eFlushTypeInvalidate:
return ::msync(ptr, n, MS_INVALIDATE) == 0;
default:
break;
}
#elif defined(__NATRON_WIN32__)
switch (type) {
case eFlushTypeSync: {
bool ret = (bool)::FlushViewOfFile(ptr, n) != 0;
if (ret) {
ret = (bool)::FlushFileBuffers(_imp->file_handle);
}
return ret;
} break;
case eFlushTypeAsync:
return (bool)::FlushViewOfFile(ptr, n) != 0;
case eFlushTypeInvalidate:
return true;
break;
}
#endif
return false;
}
MemoryFile::~MemoryFile()
{
if (_imp->data) {
try {
flush(eFlushTypeInvalidate, NULL, 0);
_imp->closeMapping(false);
} catch (const std::exception & e) {
std::cerr << e.what() << std::endl;
}
}
delete _imp;
}
void
MemoryFile::remove()
{
if ( !_imp->path.empty() ) {
if (_imp->data) {
_imp->closeMapping(true);
}
int ok = ::remove( _imp->path.c_str() );
Q_UNUSED(ok);
_imp->path.clear();
_imp->data = 0;
}
}
NATRON_NAMESPACE_EXIT