forked from Exiv2/exiv2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasicio.cpp
1738 lines (1530 loc) · 50.8 KB
/
basicio.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
// SPDX-License-Identifier: GPL-2.0-or-later
// included header files
#include "basicio.hpp"
#include "config.h"
#include "datasets.hpp"
#include "enforce.hpp"
#include "error.hpp"
#include "futils.hpp"
#include "http.hpp"
#include "image_int.hpp"
#include "types.hpp"
#include <cstdio> // for remove, rename
#include <cstdlib> // for alloc, realloc, free
#include <cstring> // std::memcpy
#include <ctime> // timestamp for the name of temporary file
#include <fstream> // write the temporary file
#include <iostream>
// + standard includes
#include <fcntl.h> // _O_BINARY in FileIo::FileIo
#if __has_include(<sys/mman.h>)
#include <sys/mman.h> // for mmap and munmap
#endif
#if __has_include(<process.h>)
#include <process.h>
#endif
#if __has_include(<unistd.h>)
#include <unistd.h>
#endif
#ifdef EXV_USE_CURL
#include <curl/curl.h>
#endif
#ifdef _WIN32
#include <io.h>
#include <windows.h>
#endif
#if __has_include(<filesystem>)
#include <filesystem>
namespace fs = std::filesystem;
#else
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#endif
// *****************************************************************************
// class member definitions
namespace {
/// @brief replace each substring of the subject that matches the given search string with the given replacement.
void ReplaceStringInPlace(std::string& subject, std::string_view search, std::string_view replace) {
auto pos = subject.find(search);
while (pos != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += subject.find(search, pos + replace.length());
}
}
} // namespace
namespace Exiv2 {
void BasicIo::readOrThrow(byte* buf, size_t rcount, ErrorCode err) {
const size_t nread = read(buf, rcount);
Internal::enforce(nread == rcount, err);
Internal::enforce(!error(), err);
}
void BasicIo::seekOrThrow(int64_t offset, Position pos, ErrorCode err) {
const int r = seek(offset, pos);
Internal::enforce(r == 0, err);
}
//! Internal Pimpl structure of class FileIo.
class FileIo::Impl {
public:
//! Constructor
explicit Impl(fs::path path);
~Impl() = default;
// Enumerations
//! Mode of operation
enum OpMode { opRead, opWrite, opSeek };
// DATA
fs::path path_; //!< (Standard) path
std::string openMode_; //!< File open mode
FILE* fp_{}; //!< File stream pointer
OpMode opMode_{opSeek}; //!< File open mode
#if defined _WIN32
HANDLE hFile_{}; //!< Duplicated fd
HANDLE hMap_{}; //!< Handle from CreateFileMapping
#endif
byte* pMappedArea_{}; //!< Pointer to the memory-mapped area
size_t mappedLength_{}; //!< Size of the memory-mapped area
bool isMalloced_{}; //!< Is the mapped area allocated?
bool isWriteable_{}; //!< Can the mapped area be written to?
// TYPES
//! Simple struct stat wrapper for internal use
struct StructStat {
fs::perms st_mode{}; //!< Permissions
std::uintmax_t st_size{}; //!< Size
};
// #endif
// METHODS
/*!
@brief Switch to a new access mode, reopening the file if needed.
Optimized to only reopen the file when it is really necessary.
@param opMode The mode to switch to.
@return 0 if successful
*/
int switchMode(OpMode opMode);
//! stat wrapper for internal use
int stat(StructStat& buf) const;
// NOT IMPLEMENTED
Impl(const Impl&) = delete; //!< Copy constructor
Impl& operator=(const Impl&) = delete; //!< Assignment
};
FileIo::Impl::Impl(fs::path path) : path_(std::move(path)) {
}
int FileIo::Impl::switchMode(OpMode opMode) {
if (opMode_ == opMode)
return 0;
OpMode oldOpMode = opMode_;
opMode_ = opMode;
bool reopen = true;
switch (opMode) {
case opRead:
// Flush if current mode allows reading, else reopen (in mode "r+b"
// as in this case we know that we can write to the file)
if (openMode_.at(0) == 'r' || openMode_.at(1) == '+')
reopen = false;
break;
case opWrite:
// Flush if current mode allows writing, else reopen
if (openMode_.at(0) != 'r' || openMode_.at(1) == '+')
reopen = false;
break;
case opSeek:
reopen = false;
break;
}
if (!reopen) {
// Don't do anything when switching _from_ opSeek mode; we
// flush when switching _to_ opSeek.
if (oldOpMode == opSeek)
return 0;
// Flush. On msvcrt fflush does not do the job
std::fseek(fp_, 0, SEEK_CUR);
return 0;
}
// Reopen the file
#ifdef _WIN32
auto offset = _ftelli64(fp_);
#else
auto offset = ftello(fp_);
#endif
if (offset == -1)
return -1;
// 'Manual' open("r+b") to avoid munmap()
std::fclose(fp_);
openMode_ = "r+b";
opMode_ = opSeek;
fp_ = std::fopen(path_.string().c_str(), openMode_.c_str());
if (!fp_)
return 1;
#ifdef _WIN32
return _fseeki64(fp_, offset, SEEK_SET);
#else
return fseeko(fp_, offset, SEEK_SET);
#endif
} // FileIo::Impl::switchMode
int FileIo::Impl::stat(StructStat& buf) const {
try {
buf.st_size = fs::file_size(path_);
buf.st_mode = fs::status(path_).permissions();
return 0;
} catch (const fs::filesystem_error&) {
return -1;
}
} // FileIo::Impl::stat
FileIo::FileIo(const std::string& path) : p_(std::make_unique<Impl>(path)) {
}
FileIo::~FileIo() {
close();
}
int FileIo::munmap() {
int rc = 0;
if (p_->pMappedArea_) {
#if defined _WIN32
UnmapViewOfFile(p_->pMappedArea_);
CloseHandle(p_->hMap_);
p_->hMap_ = nullptr;
CloseHandle(p_->hFile_);
p_->hFile_ = nullptr;
#elif __has_include(<sys/mman.h>)
if (::munmap(p_->pMappedArea_, p_->mappedLength_) != 0) {
rc = 1;
}
#else
#error Platforms without mmap are not supported. See https://github.com/Exiv2/exiv2/issues/2380
if (p_->isWriteable_) {
seek(0, BasicIo::beg);
write(p_->pMappedArea_, p_->mappedLength_);
}
if (p_->isMalloced_) {
delete[] p_->pMappedArea_;
p_->isMalloced_ = false;
}
#endif
}
if (p_->isWriteable_) {
if (p_->fp_)
p_->switchMode(Impl::opRead);
p_->isWriteable_ = false;
}
p_->pMappedArea_ = nullptr;
p_->mappedLength_ = 0;
return rc;
}
byte* FileIo::mmap(bool isWriteable) {
if (munmap() != 0) {
throw Error(ErrorCode::kerCallFailed, path(), strError(), "munmap");
}
p_->mappedLength_ = size();
p_->isWriteable_ = isWriteable;
if (p_->isWriteable_ && p_->switchMode(Impl::opWrite) != 0) {
throw Error(ErrorCode::kerFailedToMapFileForReadWrite, path(), strError());
}
#if __has_include(<sys/mman.h>)
int prot = PROT_READ;
if (p_->isWriteable_) {
prot |= PROT_WRITE;
}
void* rc = ::mmap(nullptr, p_->mappedLength_, prot, MAP_SHARED, fileno(p_->fp_), 0);
if (MAP_FAILED == rc) {
throw Error(ErrorCode::kerCallFailed, path(), strError(), "mmap");
}
p_->pMappedArea_ = static_cast<byte*>(rc);
#elif defined _WIN32
// Windows implementation
// TODO: An attempt to map a file with a length of 0 (zero) fails with
// an error code of ERROR_FILE_INVALID.
// Applications should test for files with a length of 0 (zero) and
// reject those files.
DWORD dwAccess = FILE_MAP_READ;
DWORD flProtect = PAGE_READONLY;
if (isWriteable) {
dwAccess = FILE_MAP_WRITE;
flProtect = PAGE_READWRITE;
}
HANDLE hPh = GetCurrentProcess();
auto hFd = reinterpret_cast<HANDLE>(_get_osfhandle(fileno(p_->fp_)));
if (hFd == INVALID_HANDLE_VALUE) {
throw Error(ErrorCode::kerCallFailed, path(), "MSG1", "_get_osfhandle");
}
if (!DuplicateHandle(hPh, hFd, hPh, &p_->hFile_, 0, false, DUPLICATE_SAME_ACCESS)) {
throw Error(ErrorCode::kerCallFailed, path(), "MSG2", "DuplicateHandle");
}
p_->hMap_ = CreateFileMapping(p_->hFile_, nullptr, flProtect, 0, static_cast<DWORD>(p_->mappedLength_), nullptr);
if (p_->hMap_ == nullptr) {
throw Error(ErrorCode::kerCallFailed, path(), "MSG3", "CreateFileMapping");
}
void* rc = MapViewOfFile(p_->hMap_, dwAccess, 0, 0, 0);
if (rc == nullptr) {
throw Error(ErrorCode::kerCallFailed, path(), "MSG4", "CreateFileMapping");
}
p_->pMappedArea_ = static_cast<byte*>(rc);
#else
#error Platforms without mmap are not supported. See https://github.com/Exiv2/exiv2/issues/2380
// Workaround for platforms without mmap: Read the file into memory
byte* buf = new byte[p_->mappedLength_];
const long offset = std::ftell(p_->fp_);
std::fseek(p_->fp_, 0, SEEK_SET);
if (read(buf, p_->mappedLength_) != p_->mappedLength_) {
delete[] buf;
throw Error(ErrorCode::kerCallFailed, path(), strError(), "FileIo::read");
}
std::fseek(p_->fp_, offset, SEEK_SET);
if (error()) {
delete[] buf;
throw Error(ErrorCode::kerCallFailed, path(), strError(), "FileIo::mmap");
}
p_->pMappedArea_ = buf;
p_->isMalloced_ = true;
#endif
return p_->pMappedArea_;
}
void FileIo::setPath(const std::string& path) {
close();
p_->path_ = path;
}
size_t FileIo::write(const byte* data, size_t wcount) {
if (p_->switchMode(Impl::opWrite) != 0)
return 0;
return std::fwrite(data, 1, wcount, p_->fp_);
}
size_t FileIo::write(BasicIo& src) {
if (static_cast<BasicIo*>(this) == &src)
return 0;
if (!src.isopen())
return 0;
if (p_->switchMode(Impl::opWrite) != 0)
return 0;
byte buf[4096];
size_t writeTotal = 0;
size_t readCount = src.read(buf, sizeof(buf));
while (readCount != 0) {
size_t writeCount = std::fwrite(buf, 1, readCount, p_->fp_);
writeTotal += writeCount;
if (writeCount != readCount) {
// try to reset back to where write stopped
src.seek(writeCount - readCount, BasicIo::cur);
break;
}
readCount = src.read(buf, sizeof(buf));
}
return writeTotal;
}
void FileIo::transfer(BasicIo& src) {
const bool wasOpen = (p_->fp_ != nullptr);
const std::string lastMode(p_->openMode_);
if (auto fileIo = dynamic_cast<FileIo*>(&src)) {
// Optimization if src is another instance of FileIo
fileIo->close();
// Check if the file can be written to, if it already exists
if (open("a+b") != 0) {
// Remove the (temporary) file
fs::remove(fileIo->path());
throw Error(ErrorCode::kerFileOpenFailed, path(), "a+b", strError());
}
close();
bool statOk = true;
fs::perms origStMode = {};
auto pf = path();
Impl::StructStat buf1;
if (p_->stat(buf1) == -1) {
statOk = false;
}
origStMode = buf1.st_mode;
{
#if defined(_WIN32) && defined(REPLACEFILE_IGNORE_MERGE_ERRORS)
// Windows implementation that deals with the fact that ::rename fails
// if the target filename still exists, which regularly happens when
// that file has been opened with FILE_SHARE_DELETE by another process,
// like a virus scanner or disk indexer
// (see also http://stackoverflow.com/a/11023068)
auto ret =
ReplaceFileA(pf.c_str(), fileIo->path().c_str(), nullptr, REPLACEFILE_IGNORE_MERGE_ERRORS, nullptr, nullptr);
if (ret == 0) {
if (GetLastError() != ERROR_FILE_NOT_FOUND)
throw Error(ErrorCode::kerFileRenameFailed, fileIo->path(), pf, strError());
fs::rename(fileIo->path(), pf);
fs::remove(fileIo->path());
} else {
if (fileExists(pf) && fs::remove(pf) != 0)
throw Error(ErrorCode::kerCallFailed, pf, strError(), "fs::remove");
fs::rename(fileIo->path(), pf);
fs::remove(fileIo->path());
}
#else
if (fileExists(pf) && fs::remove(pf) != 0) {
throw Error(ErrorCode::kerCallFailed, pf, strError(), "fs::remove");
}
fs::rename(fileIo->path(), pf);
fs::remove(fileIo->path());
#endif
// Check permissions of new file
auto newStMode = fs::status(pf).permissions();
// Set original file permissions
if (statOk && origStMode != newStMode) {
fs::permissions(pf, origStMode);
#ifndef SUPPRESS_WARNINGS
EXV_WARNING << Error(ErrorCode::kerCallFailed, pf, strError(), "::chmod") << "\n";
#endif
}
}
} // if (fileIo)
else {
// Generic handling, reopen both to reset to start
if (open("w+b") != 0) {
throw Error(ErrorCode::kerFileOpenFailed, path(), "w+b", strError());
}
if (src.open() != 0) {
throw Error(ErrorCode::kerDataSourceOpenFailed, src.path(), strError());
}
write(src);
src.close();
}
if (wasOpen) {
if (open(lastMode) != 0) {
throw Error(ErrorCode::kerFileOpenFailed, path(), lastMode, strError());
}
} else
close();
if (error() || src.error()) {
throw Error(ErrorCode::kerTransferFailed, path(), strError());
}
} // FileIo::transfer
int FileIo::putb(byte data) {
if (p_->switchMode(Impl::opWrite) != 0)
return EOF;
return putc(data, p_->fp_);
}
int FileIo::seek(int64_t offset, Position pos) {
int fileSeek = 0;
switch (pos) {
case BasicIo::cur:
fileSeek = SEEK_CUR;
break;
case BasicIo::beg:
fileSeek = SEEK_SET;
break;
case BasicIo::end:
fileSeek = SEEK_END;
break;
}
if (p_->switchMode(Impl::opSeek) != 0)
return 1;
#ifdef _WIN32
return _fseeki64(p_->fp_, offset, fileSeek);
#else
return fseeko(p_->fp_, offset, fileSeek);
#endif
}
size_t FileIo::tell() const {
#ifdef _WIN32
auto pos = _ftelli64(p_->fp_);
#else
auto pos = ftello(p_->fp_);
#endif
Internal::enforce(pos >= 0, ErrorCode::kerInputDataReadFailed);
return static_cast<size_t>(pos);
}
size_t FileIo::size() const {
// Flush and commit only if the file is open for writing
if (p_->fp_ && (p_->openMode_.at(0) != 'r' || p_->openMode_.at(1) == '+')) {
std::fflush(p_->fp_);
#ifdef _MSC_VER
// This is required on msvcrt before stat after writing to a file
_commit(_fileno(p_->fp_));
#endif
}
Impl::StructStat buf;
if (p_->stat(buf))
return std::numeric_limits<size_t>::max();
return buf.st_size;
}
int FileIo::open() {
// Default open is in read-only binary mode
return open("rb");
}
int FileIo::open(const std::string& mode) {
close();
p_->openMode_ = mode;
p_->opMode_ = Impl::opSeek;
p_->fp_ = ::fopen(path().c_str(), mode.c_str());
if (!p_->fp_)
return 1;
return 0;
}
bool FileIo::isopen() const {
return p_->fp_ != nullptr;
}
int FileIo::close() {
int rc = 0;
if (munmap() != 0)
rc = 2;
if (p_->fp_) {
if (std::fclose(p_->fp_) != 0)
rc |= 1;
p_->fp_ = nullptr;
}
return rc;
}
DataBuf FileIo::read(size_t rcount) {
if (rcount > size())
throw Error(ErrorCode::kerInvalidMalloc);
DataBuf buf(rcount);
size_t readCount = read(buf.data(), buf.size());
if (readCount == 0) {
throw Error(ErrorCode::kerInputDataReadFailed);
}
buf.resize(readCount);
return buf;
}
size_t FileIo::read(byte* buf, size_t rcount) {
if (p_->switchMode(Impl::opRead) != 0) {
return 0;
}
return std::fread(buf, 1, rcount, p_->fp_);
}
int FileIo::getb() {
if (p_->switchMode(Impl::opRead) != 0)
return EOF;
return getc(p_->fp_);
}
int FileIo::error() const {
return p_->fp_ ? ferror(p_->fp_) : 0;
}
bool FileIo::eof() const {
return std::feof(p_->fp_) != 0;
}
std::string FileIo::path() const noexcept {
return p_->path_.string();
}
void FileIo::populateFakeData() {
}
//! Internal Pimpl structure of class MemIo.
class MemIo::Impl final {
public:
Impl() = default; //!< Default constructor
Impl(const byte* data, size_t size); //!< Constructor 2
~Impl() = default;
// DATA
byte* data_{nullptr}; //!< Pointer to the start of the memory area
size_t idx_{0}; //!< Index into the memory area
size_t size_{0}; //!< Size of the memory area
size_t sizeAlloced_{0}; //!< Size of the allocated buffer
bool isMalloced_{false}; //!< Was the buffer allocated?
bool eof_{false}; //!< EOF indicator
// METHODS
void reserve(size_t wcount); //!< Reserve memory
// NOT IMPLEMENTED
Impl(const Impl&) = delete; //!< Copy constructor
Impl& operator=(const Impl&) = delete; //!< Assignment
};
MemIo::Impl::Impl(const byte* data, size_t size) : data_(const_cast<byte*>(data)), size_(size) {
}
/*!
@brief Utility class provides the block mapping to the part of data. This avoids allocating
a single contiguous block of memory to the big data.
*/
class BlockMap {
public:
//! the status of the block.
enum blockType_e { bNone, bKnown, bMemory };
//! @name Creators
//@{
//! Default constructor. the init status of the block is bNone.
BlockMap() = default;
//! Destructor. Releases all managed memory.
~BlockMap() {
delete[] data_;
}
BlockMap(const BlockMap&) = delete;
BlockMap& operator=(const BlockMap&) = delete;
//! @brief Populate the block.
//! @param source The data populate to the block
//! @param num The size of data
void populate(const byte* source, size_t num) {
size_ = num;
data_ = new byte[size_];
type_ = bMemory;
std::memcpy(data_, source, size_);
}
/*!
@brief Change the status to bKnow. bKnow blocks do not contain the data,
but they keep the size of data. This avoids allocating memory for parts
of the file that contain image-date (non-metadata/pixel data) which never change in exiv2.
@param num The size of the data
*/
void markKnown(size_t num) {
type_ = bKnown;
size_ = num;
}
[[nodiscard]] bool isNone() const {
return type_ == bNone;
}
[[nodiscard]] bool isKnown() const {
return type_ == bKnown;
}
[[nodiscard]] byte* getData() const {
return data_;
}
[[nodiscard]] size_t getSize() const {
return size_;
}
private:
blockType_e type_{bNone};
byte* data_{nullptr};
size_t size_{0};
};
void MemIo::Impl::reserve(size_t wcount) {
const size_t need = wcount + idx_;
size_t blockSize = 32 * 1024; // 32768
const size_t maxBlockSize = 4 * 1024 * 1024;
if (!isMalloced_) {
// Minimum size for 1st block
auto size = std::max<size_t>(blockSize * (1 + need / blockSize), size_);
auto data = static_cast<byte*>(std::malloc(size));
if (!data) {
throw Error(ErrorCode::kerMallocFailed);
}
if (data_) {
std::memcpy(data, data_, size_);
}
data_ = data;
sizeAlloced_ = size;
isMalloced_ = true;
}
if (need > size_) {
if (need > sizeAlloced_) {
blockSize = 2 * sizeAlloced_;
if (blockSize > maxBlockSize)
blockSize = maxBlockSize;
// Allocate in blocks
size_t want = blockSize * (1 + need / blockSize);
data_ = static_cast<byte*>(std::realloc(data_, want));
if (!data_) {
throw Error(ErrorCode::kerMallocFailed);
}
sizeAlloced_ = want;
}
size_ = need;
}
}
MemIo::MemIo() : p_(std::make_unique<Impl>()) {
}
MemIo::MemIo(const byte* data, size_t size) : p_(std::make_unique<Impl>(data, size)) {
}
MemIo::~MemIo() {
if (p_->isMalloced_) {
std::free(p_->data_);
}
}
size_t MemIo::write(const byte* data, size_t wcount) {
p_->reserve(wcount);
if (data) {
std::memcpy(&p_->data_[p_->idx_], data, wcount);
}
p_->idx_ += wcount;
return wcount;
}
void MemIo::transfer(BasicIo& src) {
if (auto memIo = dynamic_cast<MemIo*>(&src)) {
// Optimization if src is another instance of MemIo
if (p_->isMalloced_) {
std::free(p_->data_);
}
p_->idx_ = 0;
p_->data_ = memIo->p_->data_;
p_->size_ = memIo->p_->size_;
p_->isMalloced_ = memIo->p_->isMalloced_;
memIo->p_->idx_ = 0;
memIo->p_->data_ = nullptr;
memIo->p_->size_ = 0;
memIo->p_->isMalloced_ = false;
} else {
// Generic reopen to reset position to start
if (src.open() != 0) {
throw Error(ErrorCode::kerDataSourceOpenFailed, src.path(), strError());
}
p_->idx_ = 0;
write(src);
src.close();
}
if (error() || src.error())
throw Error(ErrorCode::kerMemoryTransferFailed, strError());
}
size_t MemIo::write(BasicIo& src) {
if (this == &src)
return 0;
if (!src.isopen())
return 0;
byte buf[4096];
size_t writeTotal = 0;
size_t readCount = src.read(buf, sizeof(buf));
while (readCount != 0) {
write(buf, readCount);
writeTotal += readCount;
readCount = src.read(buf, sizeof(buf));
}
return writeTotal;
}
int MemIo::putb(byte data) {
p_->reserve(1);
p_->data_[p_->idx_++] = data;
return data;
}
int MemIo::seek(int64_t offset, Position pos) {
int64_t newIdx = 0;
switch (pos) {
case BasicIo::cur:
newIdx = p_->idx_ + offset;
break;
case BasicIo::beg:
newIdx = offset;
break;
case BasicIo::end:
newIdx = p_->size_ + offset;
break;
}
if (newIdx < 0)
return 1;
if (newIdx > static_cast<int64_t>(p_->size_)) {
p_->eof_ = true;
return 1;
}
p_->idx_ = static_cast<size_t>(newIdx);
p_->eof_ = false;
return 0;
}
byte* MemIo::mmap(bool /*isWriteable*/) {
return p_->data_;
}
int MemIo::munmap() {
return 0;
}
size_t MemIo::tell() const {
return p_->idx_;
}
size_t MemIo::size() const {
return p_->size_;
}
int MemIo::open() {
p_->idx_ = 0;
p_->eof_ = false;
return 0;
}
bool MemIo::isopen() const {
return true;
}
int MemIo::close() {
return 0;
}
DataBuf MemIo::read(size_t rcount) {
DataBuf buf(rcount);
size_t readCount = read(buf.data(), buf.size());
buf.resize(readCount);
return buf;
}
size_t MemIo::read(byte* buf, size_t rcount) {
const auto avail = std::max<size_t>(p_->size_ - p_->idx_, 0);
const auto allow = std::min<size_t>(rcount, avail);
if (allow > 0) {
std::memcpy(buf, &p_->data_[p_->idx_], allow);
}
p_->idx_ += allow;
if (rcount > avail) {
p_->eof_ = true;
}
return allow;
}
int MemIo::getb() {
if (p_->idx_ >= p_->size_) {
p_->eof_ = true;
return EOF;
}
return p_->data_[p_->idx_++];
}
int MemIo::error() const {
return 0;
}
bool MemIo::eof() const {
return p_->eof_;
}
std::string MemIo::path() const noexcept {
static std::string _path{"MemIo"};
return _path;
}
void MemIo::populateFakeData() {
}
#if EXV_XPATH_MEMIO
XPathIo::XPathIo(const std::string& path) {
Protocol prot = fileProtocol(path);
if (prot == pStdin)
ReadStdin();
else if (prot == pDataUri)
ReadDataUri(path);
}
void XPathIo::ReadStdin() {
if (isatty(fileno(stdin)))
throw Error(ErrorCode::kerInputDataReadFailed);
#ifdef _O_BINARY
// convert stdin to binary
if (_setmode(_fileno(stdin), _O_BINARY) == -1)
throw Error(ErrorCode::kerInputDataReadFailed);
#endif
char readBuf[100 * 1024];
std::streamsize readBufSize = 0;
do {
std::cin.read(readBuf, sizeof(readBuf));
readBufSize = std::cin.gcount();
if (readBufSize > 0) {
write((byte*)readBuf, (long)readBufSize);
}
} while (readBufSize);
}
void XPathIo::ReadDataUri(const std::string& path) {
size_t base64Pos = path.find("base64,");
if (base64Pos == std::string::npos)
throw Error(ErrorCode::kerErrorMessage, "No base64 data");
std::string data = path.substr(base64Pos + 7);
auto decodeData = new char[data.length()];
auto size = base64decode(data.c_str(), decodeData, data.length());
if (size > 0)
write((byte*)decodeData, size);
else
throw Error(ErrorCode::kerErrorMessage, "Unable to decode base 64.");
delete[] decodeData;
}
#else
XPathIo::XPathIo(const std::string& orgPath) : FileIo(XPathIo::writeDataToFile(orgPath)), tempFilePath_(path()) {
}
XPathIo::~XPathIo() {
if (isTemp_ && !fs::remove(tempFilePath_)) {
// error when removing file
// printf ("Warning: Unable to remove the temp file %s.\n", tempFilePath_.c_str());
}
}
void XPathIo::transfer(BasicIo& src) {
if (isTemp_) {
// replace temp path to gent path.
auto currentPath = path();
ReplaceStringInPlace(currentPath, XPathIo::TEMP_FILE_EXT, XPathIo::GEN_FILE_EXT);
setPath(currentPath);
tempFilePath_ = path();
fs::rename(currentPath, tempFilePath_);
isTemp_ = false;
// call super class method
FileIo::transfer(src);
}
}
std::string XPathIo::writeDataToFile(const std::string& orgPath) {
Protocol prot = fileProtocol(orgPath);
// generating the name for temp file.
std::time_t timestamp = std::time(nullptr);
std::stringstream ss;
ss << timestamp << XPathIo::TEMP_FILE_EXT;
std::string path = ss.str();
if (prot == pStdin) {
if (isatty(fileno(stdin)))
throw Error(ErrorCode::kerInputDataReadFailed);
#ifdef _WIN32
// convert stdin to binary
if (_setmode(_fileno(stdin), _O_BINARY) == -1)
throw Error(ErrorCode::kerInputDataReadFailed);
#endif
std::ofstream fs(path.c_str(), std::ios::out | std::ios::binary | std::ios::trunc);
// read stdin and write to the temp file.
char readBuf[100 * 1024];
std::streamsize readBufSize = 0;
do {
std::cin.read(readBuf, sizeof(readBuf));
readBufSize = std::cin.gcount();
if (readBufSize > 0) {
fs.write(readBuf, readBufSize);
}
} while (readBufSize);
fs.close();
} else if (prot == pDataUri) {
std::ofstream fs(path.c_str(), std::ios::out | std::ios::binary | std::ios::trunc);
// read data uri and write to the temp file.
size_t base64Pos = orgPath.find("base64,");
if (base64Pos == std::string::npos) {
fs.close();
throw Error(ErrorCode::kerErrorMessage, "No base64 data");
}
std::string data = orgPath.substr(base64Pos + 7);
std::vector<char> decodeData(data.length());
auto size = base64decode(data.c_str(), decodeData.data(), data.length());
if (size > 0) {
fs.write(decodeData.data(), size);
fs.close();
} else {
fs.close();
throw Error(ErrorCode::kerErrorMessage, "Unable to decode base 64.");
}
}
return path;
}
#endif
//! Internal Pimpl abstract structure of class RemoteIo.
class RemoteIo::Impl {
public:
//! Constructor
Impl(const std::string& url, size_t blockSize);
//! Destructor. Releases all managed memory.
virtual ~Impl();
Impl(const Impl&) = delete;
Impl& operator=(const Impl&) = delete;
// DATA
std::string path_; //!< (Standard) path
size_t blockSize_; //!< Size of the block memory.
BlockMap* blocksMap_{nullptr}; //!< An array contains all blocksMap
size_t size_{0}; //!< The file size
size_t idx_{0}; //!< Index into the memory area
bool isMalloced_{false}; //!< Was the blocksMap_ allocated?
bool eof_{false}; //!< EOF indicator