-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathcpl_vsi_mem.cpp
1371 lines (1160 loc) · 45.1 KB
/
cpl_vsi_mem.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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************
*
* Project: VSI Virtual File System
* Purpose: Implementation of Memory Buffer virtual IO functions.
* Author: Frank Warmerdam, warmerdam@pobox.com
*
******************************************************************************
* Copyright (c) 2005, Frank Warmerdam <warmerdam@pobox.com>
* Copyright (c) 2007-2014, Even Rouault <even dot rouault at spatialys.com>
*
* SPDX-License-Identifier: MIT
****************************************************************************/
#include "cpl_port.h"
#include "cpl_vsi.h"
#include "cpl_vsi_virtual.h"
#include <cerrno>
#include <cstddef>
#include <cstring>
#include <ctime>
#if HAVE_FCNTL_H
#include <fcntl.h>
#endif
#if HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#include <algorithm>
#include <atomic>
#include <map>
#include <string>
#include <utility>
#include <memory>
#include <set>
#include <mutex>
// c++17 or VS2017
#if defined(HAVE_SHARED_MUTEX) || _MSC_VER >= 1910
#include <shared_mutex>
#define CPL_SHARED_MUTEX_TYPE std::shared_mutex
#define CPL_SHARED_LOCK std::shared_lock<std::shared_mutex>
#define CPL_EXCLUSIVE_LOCK std::unique_lock<std::shared_mutex>
#else
// Poor-man implementation of std::shared_mutex with an exclusive mutex
#define CPL_SHARED_MUTEX_TYPE std::mutex
#define CPL_SHARED_LOCK std::lock_guard<std::mutex>
#define CPL_EXCLUSIVE_LOCK std::lock_guard<std::mutex>
#endif
#include "cpl_atomic_ops.h"
#include "cpl_conv.h"
#include "cpl_error.h"
#include "cpl_multiproc.h"
#include "cpl_string.h"
//! @cond Doxygen_Suppress
// szHIDDEN_DIRNAME is for files created by VSIMemGenerateHiddenFilename(pszFilename).
// Such files are of the form "/vsimem/.#!HIDDEN!#./{counter}/{pszFilename}"
//
// The high-level design constraint is that "/vsimem/.#!HIDDEN!#." acts as a
// "side" hierarchy, but still under the "/vsimem/" namespace, so that code
// having special processing of filenames starting with /vsimem/ can still work.
// The structure of the returned filename is also such that those files form
// independent hierarchies, i.e. the tree generated by a
// VSIMemGenerateHiddenFilename() is "invisible" from the one returned by
// another call to it.
//
// As a consequence:
// - we don't want ".#!HIDDEN!#." to be listed in VSIReadDir("/vsimem/")
// - we don't want content under ""/vsimem/.#!HIDDEN!#" to be deleted by
// VSIRmdirRecursive("/vsimem/")
// - we don't want the creation of a file (or directory) called
// "/vsimem/.#!HIDDEN!#./{counter}/{pszFilename}"
// to cause the implicit creation of "/vsimem/.#!HIDDEN!#./{counter}" and
// "/vsimem/.#!HIDDEN!#". This is done so that users don't have to care about
// cleaning such implicit directories that are upper in the hierarchy w.r.t.
// to what we return to them.
// - But we want the creation of file or directory
// "/vsimem/.#!HIDDEN!#./{counter}/{pszFilename}/something_added_by_user"
// to cause "/vsimem/.#!HIDDEN!#./{counter}/{pszFilename}" to be implicitly
// created as a directory, so they can list it, or recursively delete it.
// - we want VSIReadDirRecursive("/vsimem/.#!HIDDEN!#.") to list everything
// under it (for debugging purposes)
// - we want VSIRmdirRecursive("/vsimem/.#!HIDDEN!#.") to remove everything
// under it (for debugging purposes)
//
constexpr const char *szHIDDEN_DIRNAME = "/vsimem/.#!HIDDEN!#.";
/*
** Notes on Multithreading:
**
** VSIMemFilesystemHandler: This class maintains a mutex to protect
** access and update of the oFileList array which has all the "files" in
** the memory filesystem area. It is expected that multiple threads would
** want to create and read different files at the same time and so might
** collide access oFileList without the mutex.
**
** VSIMemFile: A mutex protects accesses to the file
**
** VSIMemHandle: This is essentially a "current location" representing
** on accessor to a file, and is inherently intended only to be used in
** a single thread.
**
** In General:
**
** Multiple threads accessing the memory filesystem are ok as long as
** a given VSIMemHandle (i.e. FILE * at app level) isn't used by multiple
** threads at once.
*/
/************************************************************************/
/* ==================================================================== */
/* VSIMemFile */
/* ==================================================================== */
/************************************************************************/
class VSIMemFile
{
CPL_DISALLOW_COPY_ASSIGN(VSIMemFile)
public:
CPLString osFilename{};
bool bIsDirectory = false;
bool bOwnData = true;
GByte *pabyData = nullptr;
vsi_l_offset nLength = 0;
vsi_l_offset nAllocLength = 0;
vsi_l_offset nMaxLength = GUINTBIG_MAX;
time_t mTime = 0;
CPL_SHARED_MUTEX_TYPE m_oMutex{};
VSIMemFile();
virtual ~VSIMemFile();
bool SetLength(vsi_l_offset nNewSize);
};
/************************************************************************/
/* ==================================================================== */
/* VSIMemHandle */
/* ==================================================================== */
/************************************************************************/
class VSIMemHandle final : public VSIVirtualHandle
{
CPL_DISALLOW_COPY_ASSIGN(VSIMemHandle)
public:
std::shared_ptr<VSIMemFile> poFile = nullptr;
vsi_l_offset m_nOffset = 0;
bool m_bReadAllowed = false;
bool bUpdate = false;
bool bEOF = false;
bool m_bError = false;
VSIMemHandle() = default;
~VSIMemHandle() override;
int Seek(vsi_l_offset nOffset, int nWhence) override;
vsi_l_offset Tell() override;
size_t Read(void *pBuffer, size_t nSize, size_t nMemb) override;
size_t Write(const void *pBuffer, size_t nSize, size_t nMemb) override;
void ClearErr() override;
int Error() override;
int Eof() override;
int Close() override;
int Truncate(vsi_l_offset nNewSize) override;
bool HasPRead() const override
{
return true;
}
size_t PRead(void * /*pBuffer*/, size_t /* nSize */,
vsi_l_offset /*nOffset*/) const override;
};
/************************************************************************/
/* ==================================================================== */
/* VSIMemFilesystemHandler */
/* ==================================================================== */
/************************************************************************/
class VSIMemFilesystemHandler final : public VSIFilesystemHandler
{
const std::string m_osPrefix;
CPL_DISALLOW_COPY_ASSIGN(VSIMemFilesystemHandler)
public:
std::map<std::string, std::shared_ptr<VSIMemFile>> oFileList{};
CPLMutex *hMutex = nullptr;
explicit VSIMemFilesystemHandler(const char *pszPrefix)
: m_osPrefix(pszPrefix)
{
}
~VSIMemFilesystemHandler() override;
// TODO(schwehr): Fix VSIFileFromMemBuffer so that using is not needed.
using VSIFilesystemHandler::Open;
VSIVirtualHandle *Open(const char *pszFilename, const char *pszAccess,
bool bSetError,
CSLConstList /* papszOptions */) override;
int Stat(const char *pszFilename, VSIStatBufL *pStatBuf,
int nFlags) override;
int Unlink(const char *pszFilename) override;
int Mkdir(const char *pszDirname, long nMode) override;
int Rmdir(const char *pszDirname) override;
int RmdirRecursive(const char *pszDirname) override;
char **ReadDirEx(const char *pszDirname, int nMaxFiles) override;
int Rename(const char *oldpath, const char *newpath) override;
GIntBig GetDiskFreeSpace(const char *pszDirname) override;
static std::string NormalizePath(const std::string &in);
int Unlink_unlocked(const char *pszFilename);
VSIFilesystemHandler *Duplicate(const char *pszPrefix) override
{
return new VSIMemFilesystemHandler(pszPrefix);
}
};
/************************************************************************/
/* ==================================================================== */
/* VSIMemFile */
/* ==================================================================== */
/************************************************************************/
/************************************************************************/
/* VSIMemFile() */
/************************************************************************/
VSIMemFile::VSIMemFile()
{
time(&mTime);
}
/************************************************************************/
/* ~VSIMemFile() */
/************************************************************************/
VSIMemFile::~VSIMemFile()
{
if (bOwnData && pabyData)
CPLFree(pabyData);
}
/************************************************************************/
/* SetLength() */
/************************************************************************/
// Must be called under exclusive lock
bool VSIMemFile::SetLength(vsi_l_offset nNewLength)
{
if (nNewLength > nMaxLength)
{
CPLError(CE_Failure, CPLE_NotSupported, "Maximum file size reached!");
return false;
}
/* -------------------------------------------------------------------- */
/* Grow underlying array if needed. */
/* -------------------------------------------------------------------- */
if (nNewLength > nAllocLength)
{
// If we don't own the buffer, we cannot reallocate it because
// the return address might be different from the one passed by
// the caller. Hence, the caller would not be able to free
// the buffer.
if (!bOwnData)
{
CPLError(CE_Failure, CPLE_NotSupported,
"Cannot extended in-memory file whose ownership was not "
"transferred");
return false;
}
// If the first allocation is 1 MB or above, just take that value
// as the one to allocate
// Otherwise slightly reserve more to avoid too frequent reallocations.
const vsi_l_offset nNewAlloc =
(nAllocLength == 0 && nNewLength >= 1024 * 1024)
? nNewLength
: nNewLength + nNewLength / 10 + 5000;
GByte *pabyNewData = nullptr;
if (static_cast<vsi_l_offset>(static_cast<size_t>(nNewAlloc)) ==
nNewAlloc)
{
pabyNewData = static_cast<GByte *>(
nAllocLength == 0
? VSICalloc(1, static_cast<size_t>(nNewAlloc))
: VSIRealloc(pabyData, static_cast<size_t>(nNewAlloc)));
}
if (pabyNewData == nullptr)
{
CPLError(CE_Failure, CPLE_OutOfMemory,
"Cannot extend in-memory file to " CPL_FRMT_GUIB
" bytes due to out-of-memory situation",
nNewAlloc);
return false;
}
if (nAllocLength > 0)
{
// Clear the new allocated part of the buffer (only needed if
// there was already reserved memory, otherwise VSICalloc() has
// zeroized it already)
memset(pabyNewData + nAllocLength, 0,
static_cast<size_t>(nNewAlloc - nAllocLength));
}
pabyData = pabyNewData;
nAllocLength = nNewAlloc;
}
else if (nNewLength < nLength)
{
memset(pabyData + nNewLength, 0,
static_cast<size_t>(nLength - nNewLength));
}
nLength = nNewLength;
time(&mTime);
return true;
}
/************************************************************************/
/* ==================================================================== */
/* VSIMemHandle */
/* ==================================================================== */
/************************************************************************/
/************************************************************************/
/* ~VSIMemHandle() */
/************************************************************************/
VSIMemHandle::~VSIMemHandle()
{
VSIMemHandle::Close();
}
/************************************************************************/
/* Close() */
/************************************************************************/
int VSIMemHandle::Close()
{
if (poFile)
{
#ifdef DEBUG_VERBOSE
CPLDebug("VSIMEM", "Closing handle %p on %s: ref_count=%d (before)",
this, poFile->osFilename.c_str(),
static_cast<int>(poFile.use_count()));
#endif
poFile = nullptr;
}
return 0;
}
/************************************************************************/
/* Seek() */
/************************************************************************/
int VSIMemHandle::Seek(vsi_l_offset nOffset, int nWhence)
{
vsi_l_offset nLength;
{
CPL_SHARED_LOCK oLock(poFile->m_oMutex);
nLength = poFile->nLength;
}
if (nWhence == SEEK_CUR)
{
if (nOffset > INT_MAX)
{
// printf("likely negative offset intended\n");
}
m_nOffset += nOffset;
}
else if (nWhence == SEEK_SET)
{
m_nOffset = nOffset;
}
else if (nWhence == SEEK_END)
{
m_nOffset = nLength + nOffset;
}
else
{
errno = EINVAL;
return -1;
}
bEOF = false;
return 0;
}
/************************************************************************/
/* Tell() */
/************************************************************************/
vsi_l_offset VSIMemHandle::Tell()
{
return m_nOffset;
}
/************************************************************************/
/* Read() */
/************************************************************************/
size_t VSIMemHandle::Read(void *pBuffer, size_t nSize, size_t nCount)
{
const vsi_l_offset nOffset = m_nOffset;
size_t nBytesToRead = nSize * nCount;
if (nBytesToRead == 0)
return 0;
if (nCount > 0 && nBytesToRead / nCount != nSize)
{
bEOF = true;
return 0;
}
if (!m_bReadAllowed)
{
m_bError = true;
return 0;
}
bool bEOFTmp = bEOF;
// Do not access/modify bEOF under the lock to avoid confusing Coverity
// Scan since we access it in other methods outside of the lock.
const auto DoUnderLock =
[this, nOffset, pBuffer, nSize, &nBytesToRead, &nCount, &bEOFTmp]
{
CPL_SHARED_LOCK oLock(poFile->m_oMutex);
if (poFile->nLength <= nOffset || nBytesToRead + nOffset < nBytesToRead)
{
bEOFTmp = true;
return false;
}
if (nBytesToRead + nOffset > poFile->nLength)
{
nBytesToRead = static_cast<size_t>(poFile->nLength - nOffset);
nCount = nBytesToRead / nSize;
bEOFTmp = true;
}
if (nBytesToRead)
memcpy(pBuffer, poFile->pabyData + nOffset,
static_cast<size_t>(nBytesToRead));
return true;
};
bool bRet = DoUnderLock();
bEOF = bEOFTmp;
if (!bRet)
return 0;
m_nOffset += nBytesToRead;
return nCount;
}
/************************************************************************/
/* PRead() */
/************************************************************************/
size_t VSIMemHandle::PRead(void *pBuffer, size_t nSize,
vsi_l_offset nOffset) const
{
CPL_SHARED_LOCK oLock(poFile->m_oMutex);
if (nOffset < poFile->nLength)
{
const size_t nToCopy = static_cast<size_t>(
std::min(static_cast<vsi_l_offset>(poFile->nLength - nOffset),
static_cast<vsi_l_offset>(nSize)));
memcpy(pBuffer, poFile->pabyData + static_cast<size_t>(nOffset),
nToCopy);
return nToCopy;
}
return 0;
}
/************************************************************************/
/* Write() */
/************************************************************************/
size_t VSIMemHandle::Write(const void *pBuffer, size_t nSize, size_t nCount)
{
const vsi_l_offset nOffset = m_nOffset;
if (!bUpdate)
{
errno = EACCES;
return 0;
}
const size_t nBytesToWrite = nSize * nCount;
{
CPL_EXCLUSIVE_LOCK oLock(poFile->m_oMutex);
if (nCount > 0 && nBytesToWrite / nCount != nSize)
{
return 0;
}
if (nBytesToWrite + nOffset < nBytesToWrite)
{
return 0;
}
if (nBytesToWrite + nOffset > poFile->nLength)
{
if (!poFile->SetLength(nBytesToWrite + nOffset))
return 0;
}
if (nBytesToWrite)
memcpy(poFile->pabyData + nOffset, pBuffer, nBytesToWrite);
time(&poFile->mTime);
}
m_nOffset += nBytesToWrite;
return nCount;
}
/************************************************************************/
/* ClearErr() */
/************************************************************************/
void VSIMemHandle::ClearErr()
{
CPL_SHARED_LOCK oLock(poFile->m_oMutex);
bEOF = false;
m_bError = false;
}
/************************************************************************/
/* Error() */
/************************************************************************/
int VSIMemHandle::Error()
{
CPL_SHARED_LOCK oLock(poFile->m_oMutex);
return m_bError ? TRUE : FALSE;
}
/************************************************************************/
/* Eof() */
/************************************************************************/
int VSIMemHandle::Eof()
{
CPL_SHARED_LOCK oLock(poFile->m_oMutex);
return bEOF ? TRUE : FALSE;
}
/************************************************************************/
/* Truncate() */
/************************************************************************/
int VSIMemHandle::Truncate(vsi_l_offset nNewSize)
{
if (!bUpdate)
{
errno = EACCES;
return -1;
}
CPL_EXCLUSIVE_LOCK oLock(poFile->m_oMutex);
if (poFile->SetLength(nNewSize))
return 0;
return -1;
}
/************************************************************************/
/* ==================================================================== */
/* VSIMemFilesystemHandler */
/* ==================================================================== */
/************************************************************************/
/************************************************************************/
/* ~VSIMemFilesystemHandler() */
/************************************************************************/
VSIMemFilesystemHandler::~VSIMemFilesystemHandler()
{
oFileList.clear();
if (hMutex != nullptr)
CPLDestroyMutex(hMutex);
hMutex = nullptr;
}
/************************************************************************/
/* Open() */
/************************************************************************/
VSIVirtualHandle *VSIMemFilesystemHandler::Open(const char *pszFilename,
const char *pszAccess,
bool bSetError,
CSLConstList /* papszOptions */)
{
CPLMutexHolder oHolder(&hMutex);
const std::string osFilename = NormalizePath(pszFilename);
if (osFilename.empty())
return nullptr;
vsi_l_offset nMaxLength = GUINTBIG_MAX;
const size_t iPos = osFilename.find("||maxlength=");
if (iPos != std::string::npos)
{
nMaxLength = static_cast<vsi_l_offset>(CPLAtoGIntBig(
osFilename.substr(iPos + strlen("||maxlength=")).c_str()));
}
/* -------------------------------------------------------------------- */
/* Get the filename we are opening, create if needed. */
/* -------------------------------------------------------------------- */
std::shared_ptr<VSIMemFile> poFile = nullptr;
const auto oIter = oFileList.find(osFilename);
if (oIter != oFileList.end())
{
poFile = oIter->second;
}
// If no file and opening in read, error out.
if (strstr(pszAccess, "w") == nullptr &&
strstr(pszAccess, "a") == nullptr && poFile == nullptr)
{
if (bSetError)
{
VSIError(VSIE_FileError, "No such file or directory");
}
errno = ENOENT;
return nullptr;
}
// Create.
if (poFile == nullptr)
{
const std::string osFileDir = CPLGetPathSafe(osFilename.c_str());
if (VSIMkdirRecursive(osFileDir.c_str(), 0755) == -1)
{
if (bSetError)
{
VSIError(VSIE_FileError,
"Could not create directory %s for writing",
osFileDir.c_str());
}
errno = ENOENT;
return nullptr;
}
poFile = std::make_shared<VSIMemFile>();
poFile->osFilename = osFilename;
oFileList[poFile->osFilename] = poFile;
#ifdef DEBUG_VERBOSE
CPLDebug("VSIMEM", "Creating file %s: ref_count=%d", pszFilename,
static_cast<int>(poFile.use_count()));
#endif
poFile->nMaxLength = nMaxLength;
}
// Overwrite
else if (strstr(pszAccess, "w"))
{
CPL_EXCLUSIVE_LOCK oLock(poFile->m_oMutex);
poFile->SetLength(0);
poFile->nMaxLength = nMaxLength;
}
if (poFile->bIsDirectory)
{
errno = EISDIR;
return nullptr;
}
/* -------------------------------------------------------------------- */
/* Setup the file handle on this file. */
/* -------------------------------------------------------------------- */
VSIMemHandle *poHandle = new VSIMemHandle;
poHandle->poFile = poFile;
poHandle->m_nOffset = 0;
poHandle->bEOF = false;
poHandle->bUpdate = strchr(pszAccess, 'w') || strchr(pszAccess, '+') ||
strchr(pszAccess, 'a');
poHandle->m_bReadAllowed = strchr(pszAccess, 'r') || strchr(pszAccess, '+');
#ifdef DEBUG_VERBOSE
CPLDebug("VSIMEM", "Opening handle %p on %s: ref_count=%d", poHandle,
pszFilename, static_cast<int>(poFile.use_count()));
#endif
if (strchr(pszAccess, 'a'))
{
vsi_l_offset nOffset;
{
CPL_SHARED_LOCK oLock(poFile->m_oMutex);
nOffset = poFile->nLength;
}
poHandle->m_nOffset = nOffset;
}
return poHandle;
}
/************************************************************************/
/* Stat() */
/************************************************************************/
int VSIMemFilesystemHandler::Stat(const char *pszFilename,
VSIStatBufL *pStatBuf, int /* nFlags */)
{
CPLMutexHolder oHolder(&hMutex);
const std::string osFilename = NormalizePath(pszFilename);
memset(pStatBuf, 0, sizeof(VSIStatBufL));
if (osFilename == m_osPrefix || osFilename + '/' == m_osPrefix)
{
pStatBuf->st_size = 0;
pStatBuf->st_mode = S_IFDIR;
return 0;
}
auto oIter = oFileList.find(osFilename);
if (oIter == oFileList.end())
{
errno = ENOENT;
return -1;
}
std::shared_ptr<VSIMemFile> poFile = oIter->second;
memset(pStatBuf, 0, sizeof(VSIStatBufL));
CPL_SHARED_LOCK oLock(poFile->m_oMutex);
if (poFile->bIsDirectory)
{
pStatBuf->st_size = 0;
pStatBuf->st_mode = S_IFDIR;
}
else
{
pStatBuf->st_size = poFile->nLength;
pStatBuf->st_mode = S_IFREG;
pStatBuf->st_mtime = poFile->mTime;
}
return 0;
}
/************************************************************************/
/* Unlink() */
/************************************************************************/
int VSIMemFilesystemHandler::Unlink(const char *pszFilename)
{
CPLMutexHolder oHolder(&hMutex);
return Unlink_unlocked(pszFilename);
}
/************************************************************************/
/* Unlink_unlocked() */
/************************************************************************/
int VSIMemFilesystemHandler::Unlink_unlocked(const char *pszFilename)
{
const std::string osFilename = NormalizePath(pszFilename);
auto oIter = oFileList.find(osFilename);
if (oIter == oFileList.end())
{
errno = ENOENT;
return -1;
}
#ifdef DEBUG_VERBOSE
std::shared_ptr<VSIMemFile> poFile = oIter->second;
CPLDebug("VSIMEM", "Unlink %s: ref_count=%d (before)", pszFilename,
static_cast<int>(poFile.use_count()));
#endif
oFileList.erase(oIter);
return 0;
}
/************************************************************************/
/* Mkdir() */
/************************************************************************/
int VSIMemFilesystemHandler::Mkdir(const char *pszPathname, long /* nMode */)
{
CPLMutexHolder oHolder(&hMutex);
const std::string osPathname = NormalizePath(pszPathname);
if (STARTS_WITH(osPathname.c_str(), szHIDDEN_DIRNAME))
{
if (osPathname.size() == strlen(szHIDDEN_DIRNAME))
return 0;
// "/vsimem/.#!HIDDEN!#./{unique_counter}"
else if (osPathname.find('/', strlen(szHIDDEN_DIRNAME) + 1) ==
std::string::npos)
return 0;
// If "/vsimem/.#!HIDDEN!#./{unique_counter}/user_directory", then
// accept creating an explicit directory
}
if (oFileList.find(osPathname) != oFileList.end())
{
errno = EEXIST;
return -1;
}
std::shared_ptr<VSIMemFile> poFile = std::make_shared<VSIMemFile>();
poFile->osFilename = osPathname;
poFile->bIsDirectory = true;
oFileList[osPathname] = poFile;
#ifdef DEBUG_VERBOSE
CPLDebug("VSIMEM", "Mkdir on %s: ref_count=%d", pszPathname,
static_cast<int>(poFile.use_count()));
#endif
CPL_IGNORE_RET_VAL(poFile);
return 0;
}
/************************************************************************/
/* Rmdir() */
/************************************************************************/
int VSIMemFilesystemHandler::Rmdir(const char *pszPathname)
{
return Unlink(pszPathname);
}
/************************************************************************/
/* RmdirRecursive() */
/************************************************************************/
int VSIMemFilesystemHandler::RmdirRecursive(const char *pszDirname)
{
CPLMutexHolder oHolder(&hMutex);
const CPLString osPath = NormalizePath(pszDirname);
const size_t nPathLen = osPath.size();
int ret = 0;
if (osPath == "/vsimem")
{
// Clean-up all files under pszDirname, except hidden directories
// if called from "/vsimem"
for (auto iter = oFileList.begin(); iter != oFileList.end();
/* no automatic increment */)
{
const char *pszFilePath = iter->second->osFilename.c_str();
const size_t nFileLen = iter->second->osFilename.size();
if (nFileLen > nPathLen &&
memcmp(pszFilePath, osPath.c_str(), nPathLen) == 0 &&
pszFilePath[nPathLen] == '/' &&
!STARTS_WITH(pszFilePath, szHIDDEN_DIRNAME))
{
iter = oFileList.erase(iter);
}
else
{
++iter;
}
}
}
else
{
ret = -1;
for (auto iter = oFileList.begin(); iter != oFileList.end();
/* no automatic increment */)
{
const char *pszFilePath = iter->second->osFilename.c_str();
const size_t nFileLen = iter->second->osFilename.size();
if (nFileLen >= nPathLen &&
memcmp(pszFilePath, osPath.c_str(), nPathLen) == 0 &&
(nFileLen == nPathLen || pszFilePath[nPathLen] == '/'))
{
// If VSIRmdirRecursive() is used correctly, it should at
// least delete the directory on which it has been called
ret = 0;
iter = oFileList.erase(iter);
}
else
{
++iter;
}
}
// Make sure that it always succeed on the root hidden directory
if (osPath == szHIDDEN_DIRNAME)
ret = 0;
}
return ret;
}
/************************************************************************/
/* ReadDirEx() */
/************************************************************************/
char **VSIMemFilesystemHandler::ReadDirEx(const char *pszPath, int nMaxFiles)
{
CPLMutexHolder oHolder(&hMutex);
const CPLString osPath = NormalizePath(pszPath);
char **papszDir = nullptr;
const size_t nPathLen = osPath.size();
// In case of really big number of files in the directory, CSLAddString
// can be slow (see #2158). We then directly build the list.
int nItems = 0;
int nAllocatedItems = 0;
if (osPath == szHIDDEN_DIRNAME)
{
// Special mode for hidden filenames.
// "/vsimem/.#!HIDDEN!#./{counter}" subdirectories are not explicitly
// created so they do not appear in oFileList, but their subcontent
// (e.g "/vsimem/.#!HIDDEN!#./{counter}/foo") does
std::set<std::string> oSetSubDirs;
for (const auto &iter : oFileList)
{
const char *pszFilePath = iter.second->osFilename.c_str();
if (iter.second->osFilename.size() > nPathLen &&
memcmp(pszFilePath, osPath.c_str(), nPathLen) == 0)
{
char *pszItem = CPLStrdup(pszFilePath + nPathLen + 1);
char *pszSlash = strchr(pszItem, '/');
if (pszSlash)
*pszSlash = 0;
if (cpl::contains(oSetSubDirs, pszItem))
{
CPLFree(pszItem);
continue;
}
oSetSubDirs.insert(pszItem);
if (nItems == 0)
{
papszDir =
static_cast<char **>(CPLCalloc(2, sizeof(char *)));
nAllocatedItems = 1;
}
else if (nItems >= nAllocatedItems)
{
nAllocatedItems = nAllocatedItems * 2;
papszDir = static_cast<char **>(CPLRealloc(
papszDir, (nAllocatedItems + 2) * sizeof(char *)));
}
papszDir[nItems] = pszItem;
papszDir[nItems + 1] = nullptr;
nItems++;
if (nMaxFiles > 0 && nItems > nMaxFiles)
break;
}
}
}
else