/
lvstream.cpp
4500 lines (4172 loc) · 130 KB
/
lvstream.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
/*******************************************************
CoolReader Engine
lvstream.cpp: stream classes implementation
(c) Vadim Lopatin, 2000-2009
This source code is distributed under the terms of
GNU General Public License
See LICENSE file for details
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* UNRAR library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you
* do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source
* files in the program, then also delete it here.
*******************************************************/
#include "../include/lvstream.h"
#include "../include/lvptrvec.h"
#include "../include/crtxtenc.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#define USE_UNRAR 1
#if (USE_ZLIB==1)
#include <zlib.h>
#endif
#if (USE_UNRAR==1)
#include <rar.hpp>
#endif
#if !defined(__SYMBIAN32__) && defined(_WIN32)
extern "C" {
#include <windows.h>
}
#else
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#endif
#ifdef _LINUX
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dlfcn.h>
#include <errno.h>
#endif
#ifndef USE_ANSI_FILES
#if !defined(__SYMBIAN32__) && defined(_WIN32)
#define USE_ANSI_FILES 0
#else
#define USE_ANSI_FILES 1
#endif
#endif
static LVAssetContainerFactory * _assetContainerFactory = NULL;
/// set container to handle filesystem access for paths started with ASSET_PATH_PREFIX (@ sign)
void LVSetAssetContainerFactory(LVAssetContainerFactory * asset) {
_assetContainerFactory = asset;
}
lString16 LVExtractAssetPath(lString16 fn) {
if (fn.length() < 2 || fn[0] != ASSET_PATH_PREFIX)
return lString16();
if (fn[1] == '/' || fn[1] == '\\')
return fn.substr(2);
return fn.substr(1);
}
// LVStorageObject stubs
const lChar16 * LVStorageObject::GetName()
{
return NULL;
}
LVContainer * LVStorageObject::GetParentContainer()
{
return NULL;
}
void LVStorageObject::SetName(const lChar16 *)
{
}
bool LVStorageObject::IsContainer()
{
return false;
}
lvsize_t LVStorageObject::GetSize( )
{
lvsize_t sz;
if ( GetSize( &sz )!=LVERR_OK )
return LV_INVALID_SIZE;
return sz;
}
/// calculate crc32 code for stream, if possible
lverror_t LVNamedStream::getcrc32( lUInt32 & dst )
{
if ( _crc!=0 ) {
dst = _crc;
return LVERR_OK;
} else {
if ( !_crcFailed ) {
lverror_t res = LVStream::getcrc32( dst );
if ( res==LVERR_OK ) {
_crc = dst;
return LVERR_OK;
}
_crcFailed = true;
}
dst = 0;
return LVERR_FAIL;
}
}
/// returns stream/container name, may be NULL if unknown
const lChar16 * LVNamedStream::GetName()
{
if (m_fname.empty())
return NULL;
return m_fname.c_str();
}
/// sets stream/container name, may be not implemented for some objects
void LVNamedStream::SetName(const lChar16 * name)
{
m_fname = name;
m_filename.clear();
m_path.clear();
if (m_fname.empty())
return;
const lChar16 * fn = m_fname.c_str();
const lChar16 * p = fn + m_fname.length() - 1;
for ( ;p>fn; p--) {
if (p[-1] == '/' || p[-1]=='\\')
break;
}
int pos = (int)(p - fn);
if (p>fn)
m_path = m_fname.substr(0, pos);
m_filename = m_fname.substr(pos, m_fname.length() - pos);
}
/// Universal Read or write buffer for stream region for non-meped streams
// default implementation, with RAM buffer
class LVDefStreamBuffer : public LVStreamBuffer
{
protected:
LVStreamRef m_stream;
lUInt8 * m_buf;
lvpos_t m_pos;
lvsize_t m_size;
bool m_readonly;
bool m_writeonly;
public:
static LVStreamBufferRef create( LVStreamRef stream, lvpos_t pos, lvsize_t size, bool readonly )
{
LVStreamBufferRef res;
switch ( stream->GetMode() ) {
case LVOM_ERROR: ///< to indicate error state
case LVOM_CLOSED: ///< to indicate closed state
return res;
case LVOM_READ: ///< readonly mode, use for r/o
if ( !readonly )
return res;
break;
case LVOM_WRITE: ///< writeonly mode
case LVOM_APPEND: ///< append (readwrite) mode, use for r/w
case LVOM_READWRITE: ///< readwrite mode
if ( readonly )
return res;
break;
}
lvsize_t sz;
if ( stream->GetSize(&sz)!=LVERR_OK )
return res;
if ( pos + size > sz )
return res; // wrong position/size
LVDefStreamBuffer * buf = new LVDefStreamBuffer( stream, pos, size, readonly );
if ( !buf->m_buf ) {
delete buf;
return res;
}
if ( stream->SetPos( pos )!=LVERR_OK ) {
delete buf;
return res;
}
lvsize_t bytesRead = 0;
if ( stream->Read( buf->m_buf, size, &bytesRead )!=LVERR_OK || bytesRead!=size ) {
delete buf;
return res;
}
return LVStreamBufferRef( buf );
}
LVDefStreamBuffer( LVStreamRef stream, lvpos_t pos, lvsize_t size, bool readonly )
: m_stream( stream ), m_buf( NULL ), m_pos(pos), m_size( size ), m_readonly( readonly )
{
m_buf = (lUInt8*)malloc( size );
m_writeonly = (m_stream->GetMode()==LVOM_WRITE);
}
/// get pointer to read-only buffer, returns NULL if unavailable
virtual const lUInt8 * getReadOnly()
{
return m_writeonly ? NULL : m_buf;
}
/// get pointer to read-write buffer, returns NULL if unavailable
virtual lUInt8 * getReadWrite()
{
return m_readonly ? NULL : m_buf;
}
/// get buffer size
virtual lvsize_t getSize()
{
return m_size;
}
/// write on close
virtual bool close()
{
bool res = true;
if ( m_buf ) {
if ( !m_readonly ) {
if ( m_stream->SetPos( m_pos )!=LVERR_OK ) {
res = false;
} else {
lvsize_t bytesWritten = 0;
if ( m_stream->Write( m_buf, m_size, &bytesWritten )!=LVERR_OK || bytesWritten!=m_size ) {
res = false;
}
}
}
free( m_buf );
}
m_buf = NULL;
m_stream = NULL;
m_size = 0;
m_pos = 0;
return res;
}
/// flush on destroy
virtual ~LVDefStreamBuffer()
{
close();
}
};
/// Get read buffer - default implementation, with RAM buffer
LVStreamBufferRef LVStream::GetReadBuffer( lvpos_t pos, lvpos_t size )
{
LVStreamBufferRef res;
res = LVDefStreamBuffer::create( LVStreamRef(this), pos, size, true );
return res;
}
/// Get read/write buffer - default implementation, with RAM buffer
LVStreamBufferRef LVStream::GetWriteBuffer( lvpos_t pos, lvpos_t size )
{
LVStreamBufferRef res;
res = LVDefStreamBuffer::create( LVStreamRef(this), pos, size, false );
return res;
}
#define CRC_BUF_SIZE 16384
/// calculate crc32 code for stream, if possible
lverror_t LVStream::getcrc32( lUInt32 & dst )
{
dst = 0;
if ( GetMode() == LVOM_READ || GetMode() == LVOM_APPEND ) {
lvpos_t savepos = GetPos();
lvsize_t size = GetSize();
lUInt8 buf[CRC_BUF_SIZE];
SetPos( 0 );
lvsize_t bytesRead = 0;
for ( lvpos_t pos = 0; pos<size; pos+=CRC_BUF_SIZE ) {
lvsize_t sz = size - pos;
if ( sz > CRC_BUF_SIZE )
sz = CRC_BUF_SIZE;
Read( buf, sz, &bytesRead );
if ( bytesRead!=sz ) {
SetPos(savepos);
return LVERR_FAIL;
}
dst = lStr_crc32( dst, buf, sz );
}
SetPos( savepos );
return LVERR_OK;
} else {
// not supported
return LVERR_NOTIMPL;
}
}
//#if USE__FILES==1
#if defined(_LINUX) || defined(_WIN32)
class LVFileMappedStream : public LVNamedStream
{
private:
#if defined(_WIN32)
HANDLE m_hFile;
HANDLE m_hMap;
#else
int m_fd;
#endif
lUInt8* m_map;
lvsize_t m_size;
lvpos_t m_pos;
/// Read or write buffer for stream region
class LVBuffer : public LVStreamBuffer
{
protected:
LVStreamRef m_stream;
lUInt8 * m_buf;
lvsize_t m_size;
bool m_readonly;
public:
LVBuffer( LVStreamRef stream, lUInt8 * buf, lvsize_t size, bool readonly )
: m_stream( stream ), m_buf( buf ), m_size( size ), m_readonly( readonly )
{
}
/// get pointer to read-only buffer, returns NULL if unavailable
virtual const lUInt8 * getReadOnly()
{
return m_buf;
}
/// get pointer to read-write buffer, returns NULL if unavailable
virtual lUInt8 * getReadWrite()
{
return m_readonly ? NULL : m_buf;
}
/// get buffer size
virtual lvsize_t getSize()
{
return m_size;
}
/// flush on destroy
virtual ~LVBuffer() { }
};
public:
/// Get read buffer (optimal for )
virtual LVStreamBufferRef GetReadBuffer( lvpos_t pos, lvpos_t size )
{
LVStreamBufferRef res;
if ( !m_map )
return res;
if ( (m_mode!=LVOM_APPEND && m_mode!=LVOM_READ) || pos + size > m_size || size==0 )
return res;
return LVStreamBufferRef ( new LVBuffer( LVStreamRef(this), m_map + pos, size, true ) );
}
/// Get read/write buffer (optimal for )
virtual LVStreamBufferRef GetWriteBuffer( lvpos_t pos, lvpos_t size )
{
LVStreamBufferRef res;
if ( !m_map )
return res;
if ( m_mode!=LVOM_APPEND || pos + size > m_size || size==0 )
return res;
return LVStreamBufferRef ( new LVBuffer( LVStreamRef(this), m_map + pos, size, false ) );
}
virtual lverror_t Seek( lvoffset_t offset, lvseek_origin_t origin, lvpos_t * pNewPos )
{
//
lvpos_t newpos = m_pos;
switch ( origin )
{
case LVSEEK_SET:
newpos = offset;
break;
case LVSEEK_CUR:
newpos += offset;
break;
case LVSEEK_END:
newpos = m_size + offset;
break;
}
if ( newpos>m_size )
return LVERR_FAIL;
if ( pNewPos!=NULL )
*pNewPos = newpos;
m_pos = newpos;
return LVERR_OK;
}
/// Tell current file position
/**
\param pNewPos points to place to store file position
\return lverror_t status: LVERR_OK if success
*/
virtual lverror_t Tell( lvpos_t * pPos )
{
*pPos = m_pos;
return LVERR_OK;
}
virtual lvpos_t SetPos(lvpos_t p)
{
if ( p<=m_size ) {
m_pos = p;
return m_pos;
}
return (lvpos_t)(~0);
}
/// Get file position
/**
\return lvpos_t file position
*/
virtual lvpos_t GetPos()
{
return m_pos;
}
/// Get file size
/**
\return lvsize_t file size
*/
virtual lvsize_t GetSize()
{
return m_size;
}
virtual lverror_t GetSize( lvsize_t * pSize )
{
*pSize = m_size;
return LVERR_OK;
}
lverror_t error()
{
#if defined(_WIN32)
if ( m_hFile!=NULL ) {
UnMap();
if ( !CloseHandle(m_hFile) )
CRLog::error("Error while closing file handle");
m_hFile = NULL;
}
#else
if ( m_fd!= -1 ) {
CRLog::trace("Closing mapped file %s", UnicodeToUtf8(GetName()).c_str() );
UnMap();
close(m_fd);
}
m_fd = -1;
#endif
m_map = NULL;
m_size = 0;
m_mode = LVOM_ERROR;
return LVERR_FAIL;
}
virtual lverror_t Read( void * buf, lvsize_t count, lvsize_t * nBytesRead )
{
if ( !m_map )
return LVERR_FAIL;
int cnt = (int)count;
if ( m_pos + cnt > m_size )
cnt = (int)(m_size - m_pos);
if ( cnt <= 0 )
return LVERR_FAIL;
memcpy( buf, m_map + m_pos, cnt );
m_pos += cnt;
if (nBytesRead)
*nBytesRead = cnt;
return LVERR_OK;
}
virtual bool Read( lUInt8 * buf )
{
if ( m_pos < m_size ) {
*buf = m_map[ m_pos++ ];
return true;
}
return false;
}
virtual bool Read( lUInt16 * buf )
{
if ( m_pos+1 < m_size ) {
*buf = m_map[ m_pos ] | ( ( (lUInt16)m_map[ m_pos+1 ] )<<8 );
m_pos += 2;
return true;
}
return false;
}
virtual bool Read( lUInt32 * buf )
{
if ( m_pos+3 < m_size ) {
*buf = m_map[ m_pos ] | ( ( (lUInt32)m_map[ m_pos+1 ] )<<8 )
| ( ( (lUInt32)m_map[ m_pos+2 ] )<<16 )
| ( ( (lUInt32)m_map[ m_pos+3 ] )<<24 )
;
m_pos += 4;
return true;
}
return false;
}
virtual int ReadByte()
{
if ( m_pos < m_size ) {
return m_map[ m_pos++ ];
}
return -1;
}
virtual lverror_t Write( const void * buf, lvsize_t count, lvsize_t * nBytesWritten )
{
if ( m_mode!=LVOM_APPEND )
return LVERR_FAIL;
lvsize_t maxSize = (lvsize_t)(m_size - m_pos);
if ( maxSize<=0 )
return LVERR_FAIL; // end of file reached: resize is not supported yet
if ( count > maxSize || count > m_size )
count = maxSize;
memcpy( m_map + m_pos, buf, count );
m_pos += count;
if ( nBytesWritten )
*nBytesWritten = count;
return LVERR_OK;
}
virtual bool Eof()
{
return (m_pos >= m_size);
}
static LVFileMappedStream * CreateFileStream( lString16 fname, lvopen_mode_t mode, int minSize )
{
LVFileMappedStream * f = new LVFileMappedStream();
if ( f->OpenFile( fname, mode, minSize )==LVERR_OK ) {
return f;
} else {
delete f;
return NULL;
}
}
lverror_t Map()
{
#if defined(_WIN32)
m_hMap = CreateFileMapping(
m_hFile,
NULL,
(m_mode==LVOM_READ)?PAGE_READONLY:PAGE_READWRITE, //flProtect,
0,
0,
NULL
);
if ( m_hMap==NULL ) {
DWORD err = GetLastError();
CRLog::error( "LVFileMappedStream::Map() -- Cannot map file to memory, err=%08x, hFile=%p", err, m_hFile );
return error();
}
m_map = (lUInt8*) MapViewOfFile(
m_hMap,
m_mode==LVOM_READ ? FILE_MAP_READ : FILE_MAP_READ|FILE_MAP_WRITE,
0,
0,
m_size
);
if ( m_map==NULL ) {
CRLog::error( "LVFileMappedStream::Map() -- Cannot map file to memory" );
return error();
}
return LVERR_OK;
#else
int mapFlags = (m_mode==LVOM_READ) ? PROT_READ : PROT_READ | PROT_WRITE;
m_map = (lUInt8*)mmap( 0, m_size, mapFlags, MAP_SHARED, m_fd, 0 );
if ( m_map == MAP_FAILED ) {
CRLog::error( "LVFileMappedStream::Map() -- Cannot map file to memory" );
return error();
}
return LVERR_OK;
#endif
}
lverror_t UnMap()
{
#if defined(_WIN32)
lverror_t res = LVERR_OK;
if ( m_map!=NULL ) {
if ( !UnmapViewOfFile( m_map ) ) {
CRLog::error("LVFileMappedStream::UnMap() -- Error while unmapping file");
res = LVERR_FAIL;
}
m_map = NULL;
}
if ( m_hMap!=NULL ) {
if ( !CloseHandle( m_hMap ) ) {
CRLog::error("LVFileMappedStream::UnMap() -- Error while unmapping file");
res = LVERR_FAIL;
}
m_hMap = NULL;
}
if ( res!=LVERR_OK )
return error();
return res;
#else
if ( m_map!=NULL && munmap( m_map, m_size ) == -1 ) {
m_map = NULL;
CRLog::error("LVFileMappedStream::UnMap() -- Error while unmapping file");
return error();
}
return LVERR_OK;
#endif
}
virtual lverror_t SetSize( lvsize_t size )
{
// support only size grow
if ( m_mode!=LVOM_APPEND )
return LVERR_FAIL;
if ( size == m_size )
return LVERR_OK;
//if ( size < m_size )
// return LVERR_FAIL;
bool wasMapped = false;
if ( m_map!=NULL ) {
wasMapped = true;
if ( UnMap()!=LVERR_OK )
return LVERR_FAIL;
}
m_size = size;
#if defined(_WIN32)
// WIN32
__int64 offset = size - 1;
lUInt32 pos_low = (lUInt32)((__int64)offset & 0xFFFFFFFF);
LONG pos_high = (long)(((__int64)offset >> 32) & 0xFFFFFFFF);
pos_low = SetFilePointer(m_hFile, pos_low, &pos_high, FILE_BEGIN );
if (pos_low == 0xFFFFFFFF) {
lUInt32 err = GetLastError();
if (err == ERROR_NOACCESS)
pos_low = (lUInt32)offset;
else if ( err != ERROR_SUCCESS)
return error();
}
DWORD bytesWritten = 0;
if ( !WriteFile( m_hFile, "", 1, &bytesWritten, NULL ) || bytesWritten!=1 )
return error();
#else
// LINUX
if ( lseek( m_fd, size-1, SEEK_SET ) == -1 ) {
CRLog::error("LVFileMappedStream::SetSize() -- Seek error");
return error();
}
if ( write(m_fd, "", 1) != 1 ) {
CRLog::error("LVFileMappedStream::SetSize() -- File resize error");
return error();
}
#endif
if ( wasMapped ) {
if ( Map() != LVERR_OK ) {
return error();
}
}
return LVERR_OK;
}
lverror_t OpenFile( lString16 fname, lvopen_mode_t mode, lvsize_t minSize = (lvsize_t)-1 )
{
m_mode = mode;
if ( mode!=LVOM_READ && mode!=LVOM_APPEND )
return LVERR_FAIL; // not supported
if ( minSize==(lvsize_t)-1 ) {
if ( !LVFileExists(fname) )
return LVERR_FAIL;
}
//if ( mode==LVOM_APPEND && minSize<=0 )
// return LVERR_FAIL;
SetName(fname.c_str());
lString8 fn8 = UnicodeToUtf8( fname );
#if defined(_WIN32)
//========================================================
// WIN32 IMPLEMENTATION
lUInt32 m = 0;
lUInt32 s = 0;
lUInt32 c = 0;
SetName(fname.c_str());
switch (mode) {
case LVOM_READWRITE:
m |= GENERIC_WRITE|GENERIC_READ;
s |= FILE_SHARE_WRITE|FILE_SHARE_READ;
c |= OPEN_ALWAYS;
break;
case LVOM_READ:
m |= GENERIC_READ;
s |= FILE_SHARE_READ;
c |= OPEN_EXISTING;
break;
case LVOM_WRITE:
m |= GENERIC_WRITE;
s |= FILE_SHARE_WRITE;
c |= CREATE_ALWAYS;
break;
case LVOM_APPEND:
m |= GENERIC_WRITE|GENERIC_READ;
s |= FILE_SHARE_WRITE;
c |= OPEN_ALWAYS;
break;
case LVOM_CLOSED:
case LVOM_ERROR:
crFatalError();
break;
}
m_hFile = CreateFileW( fname.c_str(), m, s, NULL, c, FILE_ATTRIBUTE_NORMAL, NULL);
if (m_hFile == INVALID_HANDLE_VALUE || !m_hFile) {
// unicode not implemented?
lUInt32 err = GetLastError();
if (err==ERROR_CALL_NOT_IMPLEMENTED)
m_hFile = CreateFileA( fn8.c_str(), m, s, NULL, c, FILE_ATTRIBUTE_NORMAL, NULL);
if ( (m_hFile == INVALID_HANDLE_VALUE) || (!m_hFile) ) {
CRLog::error("Error opening file %s", UnicodeToUtf8(fname).c_str() );
m_hFile = NULL;
// error
return error();
}
}
// check size
lUInt32 hw=0;
m_size = GetFileSize( m_hFile, (LPDWORD)&hw );
#if LVLONG_FILE_SUPPORT
if (hw)
m_size |= (((lvsize_t)hw)<<32);
#endif
if ( mode == LVOM_APPEND && m_size < minSize ) {
if ( SetSize( minSize ) != LVERR_OK ) {
CRLog::error( "Cannot set file size for %s", fn8.c_str() );
return error();
}
}
if ( Map()!=LVERR_OK )
return error();
return LVERR_OK;
#else
//========================================================
// LINUX IMPLEMENTATION
m_fd = -1;
int flags = (mode==LVOM_READ) ? O_RDONLY : O_RDWR | O_CREAT; // | O_SYNC
m_fd = open( fn8.c_str(), flags, (mode_t)0666);
if (m_fd == -1) {
CRLog::error( "Error opening file %s for %s, errno=%d, msg=%s", fn8.c_str(), (mode==LVOM_READ) ? "reading" : "read/write", (int)errno, strerror(errno) );
return error();
}
struct stat stat;
if ( fstat( m_fd, &stat ) ) {
CRLog::error( "Cannot get file size for %s", fn8.c_str() );
return error();
}
m_size = (lvsize_t) stat.st_size;
if ( mode == LVOM_APPEND && m_size < minSize ) {
if ( SetSize( minSize ) != LVERR_OK ) {
CRLog::error( "Cannot set file size for %s", fn8.c_str() );
return error();
}
}
int mapFlags = (mode==LVOM_READ) ? PROT_READ : PROT_READ | PROT_WRITE;
m_map = (lUInt8*)mmap( 0, m_size, mapFlags, MAP_SHARED, m_fd, 0 );
if ( m_map == MAP_FAILED ) {
CRLog::error( "Cannot map file %s to memory", fn8.c_str() );
return error();
}
return LVERR_OK;
#endif
}
LVFileMappedStream()
#if defined(_WIN32)
: m_hFile(NULL), m_hMap(NULL),
#else
: m_fd(-1),
#endif
m_map(NULL), m_size(0), m_pos(0)
{
m_mode=LVOM_ERROR;
}
virtual ~LVFileMappedStream()
{
// reuse error() to close file
error();
}
};
#endif
/// Open memory mapped file
/**
\param pathname is file name to open (unicode)
\param mode is mode file should be opened in (LVOM_READ or LVOM_APPEND only)
\param minSize is minimum file size for R/W mode
\return reference to opened stream if success, NULL if error
*/
LVStreamRef LVMapFileStream( const lChar8 * pathname, lvopen_mode_t mode, lvsize_t minSize )
{
lString16 fn = LocalToUnicode( lString8(pathname) );
return LVMapFileStream( fn.c_str(), mode, minSize );
}
//#ifdef _LINUX
#undef USE_ANSI_FILES
//#endif
#if (USE_ANSI_FILES==1)
class LVFileStream : public LVNamedStream
{
private:
FILE * m_file;
public:
virtual lverror_t Seek( lvoffset_t offset, lvseek_origin_t origin, lvpos_t * pNewPos )
{
//
int res = -1;
switch ( origin )
{
case LVSEEK_SET:
res = fseek( m_file, offset, SEEK_SET );
break;
case LVSEEK_CUR:
res = fseek( m_file, offset, SEEK_CUR );
break;
case LVSEEK_END:
res = fseek( m_file, offset, SEEK_END );
break;
}
if (res==0)
{
if ( pNewPos )
* pNewPos = ftell(m_file);
return LVERR_OK;
}
CRLog::error("error setting file position to %d (%d)", (int)offset, (int)origin );
return LVERR_FAIL;
}
virtual lverror_t SetSize( lvsize_t )
{
/*
int64 sz = m_file->SetSize( size );
if (sz==-1)
return LVERR_FAIL;
else
return LVERR_OK;
*/
return LVERR_FAIL;
}
virtual lverror_t Read( void * buf, lvsize_t count, lvsize_t * nBytesRead )
{
lvsize_t sz = fread( buf, 1, count, m_file );
if (nBytesRead)
*nBytesRead = sz;
if ( sz==0 )
{
return LVERR_FAIL;
}
return LVERR_OK;
}
virtual lverror_t Write( const void * buf, lvsize_t count, lvsize_t * nBytesWritten )
{
lvsize_t sz = fwrite( buf, 1, count, m_file );
if (nBytesWritten)
*nBytesWritten = sz;
handleAutoSync(sz);
if (sz < count)
{
return LVERR_FAIL;
}
return LVERR_OK;
}
/// flushes unsaved data from buffers to file, with optional flush of OS buffers
virtual lverror_t Flush( bool sync )
{
if ( !m_file )
return LVERR_FAIL;
fflush( m_file );
return LVERR_OK;
}
virtual bool Eof()
{
return feof(m_file)!=0;
}
static LVFileStream * CreateFileStream( lString16 fname, lvopen_mode_t mode )
{
LVFileStream * f = new LVFileStream;
if (f->OpenFile( fname, mode )==LVERR_OK) {
return f;
} else {
delete f;
return NULL;
}
}
lverror_t OpenFile( lString16 fname, lvopen_mode_t mode )
{
m_mode = mode;
m_file = NULL;
SetName(fname.c_str());
const char * modestr = "r";
switch (mode) {
case LVOM_READ:
modestr = "rb";
break;
case LVOM_WRITE:
modestr = "wb";
break;
case LVOM_READWRITE:
case LVOM_APPEND:
modestr = "a+b";
break;
case LVOM_CLOSED:
case LVOM_ERROR:
break;
}
FILE * file = fopen(UnicodeToLocal(fname).c_str(), modestr);
if (!file)
{
//printf("cannot open file %s\n", UnicodeToLocal(fname).c_str());
m_mode = LVOM_ERROR;
return LVERR_FAIL;
}
m_file = file;
//printf("file %s opened ok\n", UnicodeToLocal(fname).c_str());
// set filename
SetName( fname.c_str() );
return LVERR_OK;
}
LVFileStream() : m_file(NULL)
{
m_mode=LVOM_ERROR;
}
virtual ~LVFileStream()
{
if (m_file)
fclose(m_file);
}
};
#else
class LVDirectoryContainer;
class LVFileStream : public LVNamedStream
{
friend class LVDirectoryContainer;
protected:
#if defined(_WIN32)
HANDLE m_hFile;
#else
int m_fd;
#endif
//LVDirectoryContainer * m_parent;
lvsize_t m_size;