summaryrefslogtreecommitdiffstats
path: root/src/corelib/io/qfsfileengine_unix.cpp
blob: 7b7cd7fb6a312705920e47eefcfd2ffbeca0d15f (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qplatformdefs.h"
#include "qabstractfileengine.h"
#include "private/qfsfileengine_p.h"
#include "private/qcore_unix_p.h"
#include "qfilesystementry_p.h"
#include "qfilesystemengine_p.h"

#ifndef QT_NO_FSFILEENGINE

#include "qfile.h"
#include "qdir.h"
#include "qdatetime.h"
#include "qvarlengtharray.h"

#include <sys/mman.h>
#include <stdlib.h>
#include <limits.h>
#if defined(Q_OS_SYMBIAN)
# include <sys/syslimits.h>
# include <f32file.h>
# include <pathinfo.h>
# include "private/qcore_symbian_p.h"
#endif
#include <errno.h>
#if !defined(QWS) && defined(Q_OS_MAC)
# include <private/qcore_mac_p.h>
#endif

QT_BEGIN_NAMESPACE

#if defined(Q_OS_SYMBIAN)
/*!
    \internal

    Returns true if supplied path is a relative path
*/
static bool isRelativePathSymbian(const QString& fileName)
{
    return !(fileName.startsWith(QLatin1Char('/'))
             || (fileName.length() >= 2
             && ((fileName.at(0).isLetter() && fileName.at(1) == QLatin1Char(':'))
             || (fileName.at(0) == QLatin1Char('/') && fileName.at(1) == QLatin1Char('/')))));
}

/*!
 \internal
 convert symbian error code to the one suitable for setError.
 example usage: setSymbianError(err, QFile::CopyError, QLatin1String("copy error"))
*/
void QFSFileEnginePrivate::setSymbianError(int symbianError, QFile::FileError defaultError, QString defaultString)
{
    Q_Q(QFSFileEngine);
    switch (symbianError) {
    case KErrNone:
        q->setError(QFile::NoError, QLatin1String(""));
        break;
    case KErrAccessDenied:
        q->setError(QFile::PermissionsError, QLatin1String("access denied"));
        break;
    case KErrPermissionDenied:
        q->setError(QFile::PermissionsError, QLatin1String("permission denied"));
        break;
    case KErrAbort:
        q->setError(QFile::AbortError, QLatin1String("aborted"));
        break;
    case KErrCancel:
        q->setError(QFile::AbortError, QLatin1String("cancelled"));
        break;
    case KErrTimedOut:
        q->setError(QFile::TimeOutError, QLatin1String("timed out"));
        break;
    default:
        q->setError(defaultError, defaultString);
        break;
    }
}

#endif

/*!
    \internal

    Returns the stdlib open string corresponding to a QIODevice::OpenMode.
*/
static inline QByteArray openModeToFopenMode(QIODevice::OpenMode flags, const QFileSystemEntry &fileEntry,
        QFileSystemMetaData &metaData)
{
    QByteArray mode;
    if ((flags & QIODevice::ReadOnly) && !(flags & QIODevice::Truncate)) {
        mode = "rb";
        if (flags & QIODevice::WriteOnly) {
            metaData.clearFlags(QFileSystemMetaData::FileType);
            if (!fileEntry.isEmpty()
                    && QFileSystemEngine::fillMetaData(fileEntry, metaData, QFileSystemMetaData::FileType)
                    && metaData.isFile()) {
                mode += '+';
            } else {
                mode = "wb+";
            }
        }
    } else if (flags & QIODevice::WriteOnly) {
        mode = "wb";
        if (flags & QIODevice::ReadOnly)
            mode += '+';
    }
    if (flags & QIODevice::Append) {
        mode = "ab";
        if (flags & QIODevice::ReadOnly)
            mode += '+';
    }

#if defined(__GLIBC__) && (__GLIBC__ * 0x100 + __GLIBC_MINOR__) >= 0x0207
    // must be glibc >= 2.7
    mode += 'e';
#endif

    return mode;
}

/*!
    \internal

    Returns the stdio open flags corresponding to a QIODevice::OpenMode.
*/
static inline int openModeToOpenFlags(QIODevice::OpenMode mode)
{
    int oflags = QT_OPEN_RDONLY;
#ifdef QT_LARGEFILE_SUPPORT
    oflags |= QT_OPEN_LARGEFILE;
#endif

    if ((mode & QFile::ReadWrite) == QFile::ReadWrite) {
        oflags = QT_OPEN_RDWR | QT_OPEN_CREAT;
    } else if (mode & QFile::WriteOnly) {
        oflags = QT_OPEN_WRONLY | QT_OPEN_CREAT;
    }

    if (mode & QFile::Append) {
        oflags |= QT_OPEN_APPEND;
    } else if (mode & QFile::WriteOnly) {
        if ((mode & QFile::Truncate) || !(mode & QFile::ReadOnly))
            oflags |= QT_OPEN_TRUNC;
    }

    return oflags;
}

/*!
    \internal

    Sets the file descriptor to close on exec. That is, the file
    descriptor is not inherited by child processes.
*/
static inline bool setCloseOnExec(int fd)
{
    return fd != -1 && fcntl(fd, F_SETFD, FD_CLOEXEC) != -1;
}

#ifdef Q_OS_SYMBIAN
/*!
    \internal
*/
bool QFSFileEnginePrivate::nativeOpen(QIODevice::OpenMode openMode)
{
    Q_Q(QFSFileEngine);
	
	fh = 0;
	fd = -1;

    QString fn(QFileSystemEngine::absoluteName(fileEntry).nativeFilePath());
    RFs& fs = qt_s60GetRFs();

    TUint symbianMode = 0;

    if(openMode & QIODevice::ReadOnly)
        symbianMode |= EFileRead;
    if(openMode & QIODevice::WriteOnly)
        symbianMode |= EFileWrite;
    if(openMode & QIODevice::Text)
        symbianMode |= EFileStreamText;

    // pre Symbian 9.4, file I/O is always unbuffered, and the enum values don't exist
    if(QSysInfo::symbianVersion() >= QSysInfo::SV_9_4) {
        if (openMode & QFile::Unbuffered) {
            if (openMode & QIODevice::WriteOnly)
                symbianMode |= 0x00001000; //EFileWriteDirectIO;
            if (openMode & QIODevice::ReadOnly)
                symbianMode |= 0x00004000; //EFileReadDirectIO;
        } else {
            if (openMode & QIODevice::WriteOnly)
                symbianMode |= 0x00000800; //EFileWriteBuffered;
            // use implementation defaults for read buffering
        }
    }

    // Until Qt supports file sharing, we can't support EFileShareReadersOrWriters safely,
    // but Qt does this on other platforms and autotests rely on it.
    // The reason is that Unix locks are only advisory - the application needs to test the
    // lock after opening the file. Symbian and Windows locks are mandatory - opening a
    // locked file will fail.
    symbianMode |= EFileShareReadersOrWriters;

    TInt r;
    //note QIODevice::Truncate only has meaning for read/write access
    //write-only files are always truncated unless append is specified
    //reference openModeToOpenFlags in qfsfileengine_unix.cpp
    if ((openMode & QIODevice::Truncate) || (!(openMode & QIODevice::ReadOnly) && !(openMode & QIODevice::Append))) {
        r = symbianFile.Replace(fs, qt_QString2TPtrC(fn), symbianMode);
    } else {
        r = symbianFile.Open(fs, qt_QString2TPtrC(fn), symbianMode);
        if (r == KErrNotFound && (openMode & QIODevice::WriteOnly)) {
            r = symbianFile.Create(fs, qt_QString2TPtrC(fn), symbianMode);
        }
    }

    if (r == KErrNone) {
#ifdef SYMBIAN_ENABLE_64_BIT_FILE_SERVER_API
        TInt64 size;
#else
        TInt size;
#endif
        r = symbianFile.Size(size);
        if (r==KErrNone) {
            if (openMode & QIODevice::Append)
                symbianFilePos = size;
            else
                symbianFilePos = 0;
            //TODO: port this (QFileSystemMetaData in open?)
            //cachedSize = size;
        }
    }

    if (r != KErrNone) {
        setSymbianError(r, QFile::OpenError, QLatin1String("open error"));
        symbianFile.Close();
        return false;
    }

    closeFileHandle = true;
    return true;
}
#else
/*!
    \internal
*/
bool QFSFileEnginePrivate::nativeOpen(QIODevice::OpenMode openMode)
{
    Q_Q(QFSFileEngine);

    if (openMode & QIODevice::Unbuffered) {
        int flags = openModeToOpenFlags(openMode);

        // Try to open the file in unbuffered mode.
        do {
            fd = QT_OPEN(fileEntry.nativeFilePath().constData(), flags, 0666);
        } while (fd == -1 && errno == EINTR);

        // On failure, return and report the error.
        if (fd == -1) {
            q->setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError,
                        qt_error_string(errno));
            return false;
        }

        if (!(openMode & QIODevice::WriteOnly)) {
            // we don't need this check if we tried to open for writing because then
            // we had received EISDIR anyway.
            if (QFileSystemEngine::fillMetaData(fd, metaData)
                    && metaData.isDirectory()) {
                q->setError(QFile::OpenError, QLatin1String("file to open is a directory"));
                QT_CLOSE(fd);
                return false;
            }
        }

        // Seek to the end when in Append mode.
        if (flags & QFile::Append) {
            int ret;
            do {
                ret = QT_LSEEK(fd, 0, SEEK_END);
            } while (ret == -1 && errno == EINTR);

            if (ret == -1) {
                q->setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError,
                            qt_error_string(int(errno)));
                return false;
            }
        }

        fh = 0;
    } else {
        QByteArray fopenMode = openModeToFopenMode(openMode, fileEntry, metaData);

        // Try to open the file in buffered mode.
        do {
            fh = QT_FOPEN(fileEntry.nativeFilePath().constData(), fopenMode.constData());
        } while (!fh && errno == EINTR);

        // On failure, return and report the error.
        if (!fh) {
            q->setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError,
                        qt_error_string(int(errno)));
            return false;
        }

        if (!(openMode & QIODevice::WriteOnly)) {
            // we don't need this check if we tried to open for writing because then
            // we had received EISDIR anyway.
            if (QFileSystemEngine::fillMetaData(QT_FILENO(fh), metaData)
                    && metaData.isDirectory()) {
                q->setError(QFile::OpenError, QLatin1String("file to open is a directory"));
                fclose(fh);
                return false;
            }
        }

        setCloseOnExec(fileno(fh)); // ignore failure

        // Seek to the end when in Append mode.
        if (openMode & QIODevice::Append) {
            int ret;
            do {
                ret = QT_FSEEK(fh, 0, SEEK_END);
            } while (ret == -1 && errno == EINTR);

            if (ret == -1) {
                q->setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError,
                            qt_error_string(int(errno)));
                return false;
            }
        }

        fd = -1;
    }

    closeFileHandle = true;
    return true;
}
#endif

/*!
    \internal
*/
bool QFSFileEnginePrivate::nativeClose()
{
    return closeFdFh();
}

/*!
    \internal

*/
bool QFSFileEnginePrivate::nativeFlush()
{
#ifdef Q_OS_SYMBIAN
    if (symbianFile.SubSessionHandle())
        return (KErrNone == symbianFile.Flush());
#endif
    return fh ? flushFh() : fd != -1;
}

/*!
    \internal
*/
qint64 QFSFileEnginePrivate::nativeRead(char *data, qint64 len)
{
    Q_Q(QFSFileEngine);

#ifdef Q_OS_SYMBIAN
    if (symbianFile.SubSessionHandle()) {
        if(len > KMaxTInt) {
            //this check is more likely to catch a corrupt length, since it isn't possible to allocate 2GB buffers (yet..)
            q->setError(QFile::ReadError, QLatin1String("Maximum 2GB in single read on this platform"));
            return -1;
        }
        TPtr8 ptr(reinterpret_cast<TUint8*>(data), static_cast<TInt>(len));
        TInt r = symbianFile.Read(ptr);
        if (r != KErrNone)
        {
            setSymbianError(r, QFile::ReadError, QLatin1String("read error"));
            return -1;
        }
        return qint64(ptr.Length());
    }
#endif
    if (fh && nativeIsSequential()) {
        size_t readBytes = 0;
        int oldFlags = fcntl(QT_FILENO(fh), F_GETFL);
        for (int i = 0; i < 2; ++i) {
            // Unix: Make the underlying file descriptor non-blocking
            if ((oldFlags & O_NONBLOCK) == 0)
                fcntl(QT_FILENO(fh), F_SETFL, oldFlags | O_NONBLOCK);

            // Cross platform stdlib read
            size_t read = 0;
            do {
                read = fread(data + readBytes, 1, size_t(len - readBytes), fh);
            } while (read == 0 && !feof(fh) && errno == EINTR);
            if (read > 0) {
                readBytes += read;
                break;
            } else {
                if (readBytes)
                    break;
                readBytes = read;
            }

            // Unix: Restore the blocking state of the underlying socket
            if ((oldFlags & O_NONBLOCK) == 0) {
                fcntl(QT_FILENO(fh), F_SETFL, oldFlags);
                if (readBytes == 0) {
                    int readByte = 0;
                    do {
                        readByte = fgetc(fh);
                    } while (readByte == -1 && errno == EINTR);
                    if (readByte != -1) {
                        *data = uchar(readByte);
                        readBytes += 1;
                    } else {
                        break;
                    }
                }
            }
        }
        // Unix: Restore the blocking state of the underlying socket
        if ((oldFlags & O_NONBLOCK) == 0) {
            fcntl(QT_FILENO(fh), F_SETFL, oldFlags);
        }
        if (readBytes == 0 && !feof(fh)) {
            // if we didn't read anything and we're not at EOF, it must be an error
            q->setError(QFile::ReadError, qt_error_string(int(errno)));
            return -1;
        }
        return readBytes;
    }

    return readFdFh(data, len);
}

/*!
    \internal
*/
qint64 QFSFileEnginePrivate::nativeReadLine(char *data, qint64 maxlen)
{
    return readLineFdFh(data, maxlen);
}

/*!
    \internal
*/
qint64 QFSFileEnginePrivate::nativeWrite(const char *data, qint64 len)
{
#ifdef Q_OS_SYMBIAN
    Q_Q(QFSFileEngine);
    if (symbianFile.SubSessionHandle()) {
        if(len > KMaxTInt) {
            //this check is more likely to catch a corrupt length, since it isn't possible to allocate 2GB buffers (yet..)
            q->setError(QFile::WriteError, QLatin1String("Maximum 2GB in single write on this platform"));
            return -1;
        }
        const TPtrC8 ptr(reinterpret_cast<const TUint8*>(data), static_cast<TInt>(len));
        TInt r = symbianFile.Write(ptr);
        if (r != KErrNone)
        {
            setSymbianError(r, QFile::WriteError, QLatin1String("write error"));
            return -1;
        }
        return len;
    }
#endif
    return writeFdFh(data, len);
}

/*!
    \internal
*/
qint64 QFSFileEnginePrivate::nativePos() const
{
#ifdef Q_OS_SYMBIAN
    if (symbianFile.SubSessionHandle()) {
#ifdef SYMBIAN_ENABLE_64_BIT_FILE_SERVER_API
        qint64 pos = 0;
#else
        TInt pos = 0;
#endif
        TInt err = symbianFile.Seek(ESeekCurrent, pos);
        if(err != KErrNone) {
            //TODO: error reporting
            //setSymbianError(err, QFile::PositionError, QLatin1String("seek failed"));
            return -1;
        }
        return pos;
    }
#endif
    return posFdFh();
}

/*!
    \internal
*/
bool QFSFileEnginePrivate::nativeSeek(qint64 pos)
{
#ifdef Q_OS_SYMBIAN
    Q_Q(QFSFileEngine);
    if (symbianFile.SubSessionHandle()) {
#ifdef SYMBIAN_ENABLE_64_BIT_FILE_SERVER_API
        TInt r = symbianFile.Seek(ESeekStart, pos);
#else
        if(pos > KMaxTInt) {
            q->setError(QFile::PositionError, QLatin1String("Maximum 2GB file position on this platform"));
            return false;
        }
        TInt pos32(pos);
        TInt r = symbianFile.Seek(ESeekStart, pos32);
#endif
        if (r != KErrNone)
        {
            setSymbianError(r, QFile::PositionError, QLatin1String("seek failed"));
            return false;
        }
        return true;
    }
#endif
    return seekFdFh(pos);
}

/*!
    \internal
*/
int QFSFileEnginePrivate::nativeHandle() const
{
    return fh ? fileno(fh) : fd;
}

/*!
    \internal
*/
bool QFSFileEnginePrivate::nativeIsSequential() const
{
#ifdef Q_OS_SYMBIAN
    if (symbianFile.SubSessionHandle())
        return false;
#endif
    return isSequentialFdFh();
}

bool QFSFileEngine::remove()
{
    Q_D(QFSFileEngine);
    bool ret = QFileSystemEngine::removeFile(d->fileEntry);
    d->metaData.clear();
    if (!ret) {
#ifdef Q_OS_SYMBIAN
        //TODO: error reporting
        d->setSymbianError(KErrGeneral, QFile::RemoveError, QLatin1String("remove error"));
#else
        setError(QFile::RemoveError, qt_error_string(errno));
#endif
    }
    return ret;
}

bool QFSFileEngine::copy(const QString &newName)
{
    Q_D(QFSFileEngine);
    bool ret = QFileSystemEngine::copyFile(d->fileEntry, QFileSystemEntry(newName));
    if (!ret) {
#ifdef Q_OS_SYMBIAN
        //TODO: error reporting
        d->setSymbianError(KErrGeneral, QFile::CopyError, QLatin1String("copy error"));
#else
        // ### Add copy code for Unix to the filesystem engine
        setError(QFile::UnspecifiedError, QLatin1String("Not implemented!"));
        //setError(QFile::CopyError, qt_error_string(errno));
#endif
    }
    return ret;
}

bool QFSFileEngine::rename(const QString &newName)
{
    Q_D(QFSFileEngine);
    bool ret = QFileSystemEngine::renameFile(d->fileEntry, QFileSystemEntry(newName));

    if (!ret) {
#ifdef Q_OS_SYMBIAN
        //TODO: error reporting
        d->setSymbianError(KErrGeneral, QFile::RenameError, QLatin1String("rename error"));
#else
        setError(QFile::RenameError, qt_error_string(errno));
#endif
    }

    return ret;
}

bool QFSFileEngine::link(const QString &newName)
{
    Q_D(QFSFileEngine);
    bool ret = QFileSystemEngine::createLink(d->fileEntry, QFileSystemEntry(newName));
    if (!ret) {
#ifdef Q_OS_SYMBIAN
        //TODO: error reporting
        d->setSymbianError(KErrNotSupported, QFile::RenameError, QLatin1String("not supported"));
#else
        setError(QFile::RenameError, qt_error_string(errno));
#endif
    }
    return ret;
}

qint64 QFSFileEnginePrivate::nativeSize() const
{
#ifdef Q_OS_SYMBIAN
    if (symbianFile.SubSessionHandle()) {
#ifdef SYMBIAN_ENABLE_64_BIT_FILE_SERVER_API
        qint64 size;
#else
        TInt size;
#endif
        TInt err = symbianFile.Size(size);
        if(err != KErrNone) {
            //TODO: error reporting
            return 0;
        }
        return size;
    }
#endif
    return sizeFdFh();
}

bool QFSFileEngine::mkdir(const QString &name, bool createParentDirectories) const
{
    return QFileSystemEngine::createDirectory(QFileSystemEntry(name), createParentDirectories);
}

bool QFSFileEngine::rmdir(const QString &name, bool recurseParentDirectories) const
{
    return QFileSystemEngine::removeDirectory(QFileSystemEntry(name), recurseParentDirectories);
}

bool QFSFileEngine::caseSensitive() const
{
#if defined(Q_OS_SYMBIAN)
    return false;
#else
    return true;
#endif
}

bool QFSFileEngine::setCurrentPath(const QString &path)
{
    return QFileSystemEngine::setCurrentPath(QFileSystemEntry(QDir::fromNativeSeparators(path)));
}

QString QFSFileEngine::currentPath(const QString &)
{
    return QFileSystemEngine::currentPath().filePath();
}

QString QFSFileEngine::homePath()
{
    return QFileSystemEngine::homePath();
}

QString QFSFileEngine::rootPath()
{
    return QFileSystemEngine::rootPath();
}

QString QFSFileEngine::tempPath()
{
    return QFileSystemEngine::tempPath();
}

QFileInfoList QFSFileEngine::drives()
{
    QFileInfoList ret;
#if defined(Q_OS_SYMBIAN)
    TDriveList driveList;
    RFs rfs = qt_s60GetRFs();
    TInt err = rfs.DriveList(driveList);
    if (err == KErrNone) {
        char driveName[] = "A:/";

        for (char i = 0; i < KMaxDrives; i++) {
            if (driveList[i]) {
                driveName[0] = 'A' + i;
                ret.append(QFileInfo(QLatin1String(driveName)));
            }
        }
    } else {
        qWarning("QFSFileEngine::drives: Getting drives failed");
    }
#else
    ret.append(QFileInfo(rootPath()));
#endif
    return ret;
}

bool QFSFileEnginePrivate::doStat(QFileSystemMetaData::MetaDataFlags flags) const
{
    if (!tried_stat || !metaData.hasFlags(flags)) {
        tried_stat = 1;

        int localFd = fd;
        if (fh && fileEntry.isEmpty())
            localFd = QT_FILENO(fh);
        if (localFd != -1)
            QFileSystemEngine::fillMetaData(localFd, metaData);

        if (metaData.missingFlags(flags) && !fileEntry.isEmpty())
            QFileSystemEngine::fillMetaData(fileEntry, metaData, metaData.missingFlags(flags));
    }

    return metaData.exists();
}

bool QFSFileEnginePrivate::isSymlink() const
{
    if (!metaData.hasFlags(QFileSystemMetaData::LinkType))
        QFileSystemEngine::fillMetaData(fileEntry, metaData, QFileSystemMetaData::LinkType);

    return metaData.isLink();
}

/*!
    \reimp
*/
QAbstractFileEngine::FileFlags QFSFileEngine::fileFlags(FileFlags type) const
{
    Q_D(const QFSFileEngine);

    if (type & Refresh)
        d->metaData.clear();

    QAbstractFileEngine::FileFlags ret = 0;

    if (type & FlagsMask)
        ret |= LocalDiskFlag;

    bool exists;
    {
        QFileSystemMetaData::MetaDataFlags queryFlags = 0;

        queryFlags |= QFileSystemMetaData::MetaDataFlags(uint(type))
                & QFileSystemMetaData::Permissions;

        if (type & TypesMask)
            queryFlags |= QFileSystemMetaData::AliasType
                    | QFileSystemMetaData::LinkType
                    | QFileSystemMetaData::FileType
                    | QFileSystemMetaData::DirectoryType
                    | QFileSystemMetaData::BundleType;

        if (type & FlagsMask)
            queryFlags |= QFileSystemMetaData::HiddenAttribute
                    | QFileSystemMetaData::ExistsAttribute;

        queryFlags |= QFileSystemMetaData::LinkType;

        exists = d->doStat(queryFlags);
    }

    if (!exists && !d->metaData.isLink())
        return ret;

    if (exists && (type & PermsMask))
        ret |= FileFlags(uint(d->metaData.permissions()));

    if (type & TypesMask) {
        if (d->metaData.isAlias()) {
            ret |= LinkType;
        } else {
            if ((type & LinkType) && d->metaData.isLink())
                ret |= LinkType;
            if (exists) {
                if (d->metaData.isFile()) {
                    ret |= FileType;
                } else if (d->metaData.isDirectory()) {
                    ret |= DirectoryType;
                    if ((type & BundleType) && d->metaData.isBundle())
                        ret |= BundleType;
                }
            }
        }
    }

    if (type & FlagsMask) {
        if (exists)
            ret |= ExistsFlag;
        if (d->fileEntry.isRoot())
            ret |= RootFlag;
        else if (d->metaData.isHidden())
            ret |= HiddenFlag;
    }

    return ret;
}

QString QFSFileEngine::fileName(FileName file) const
{
    Q_D(const QFSFileEngine);
    if (file == BundleName) {
        return QFileSystemEngine::bundleName(d->fileEntry);
    } else if (file == BaseName) {
        return d->fileEntry.fileName();
    } else if (file == PathName) {
        return d->fileEntry.path();
    } else if (file == AbsoluteName || file == AbsolutePathName) {
        QFileSystemEntry entry(QFileSystemEngine::absoluteName(d->fileEntry));
        if (file == AbsolutePathName) {
            return entry.path();
        }
        return entry.filePath();
    } else if (file == CanonicalName || file == CanonicalPathName) {
        QFileSystemEntry entry(QFileSystemEngine::canonicalName(d->fileEntry, d->metaData));
        if (file == CanonicalPathName)
            return entry.path();
        return entry.filePath();
    } else if (file == LinkName) {
        if (d->isSymlink()) {
            QFileSystemEntry entry = QFileSystemEngine::getLinkTarget(d->fileEntry, d->metaData);
            return entry.filePath();
        }
        return QString();
    }
    return d->fileEntry.filePath();
}

bool QFSFileEngine::isRelativePath() const
{
    Q_D(const QFSFileEngine);
#if defined(Q_OS_SYMBIAN)
    return isRelativePathSymbian(d->fileEntry.filePath());
#else
    return d->fileEntry.filePath().length() ? d->fileEntry.filePath()[0] != QLatin1Char('/') : true;
#endif
}

uint QFSFileEngine::ownerId(FileOwner own) const
{
    Q_D(const QFSFileEngine);
    static const uint nobodyID = (uint) -2;

    if (d->doStat(QFileSystemMetaData::OwnerIds))
        return d->metaData.ownerId(own);

    return nobodyID;
}

QString QFSFileEngine::owner(FileOwner own) const
{
#if !defined(QT_NO_THREAD) && defined(_POSIX_THREAD_SAFE_FUNCTIONS) && !defined(Q_OS_OPENBSD)
    int size_max = sysconf(_SC_GETPW_R_SIZE_MAX);
    if (size_max == -1)
        size_max = 1024;
    QVarLengthArray<char, 1024> buf(size_max);
#endif

    if (own == OwnerUser) {
        struct passwd *pw = 0;
#if !defined(QT_NO_THREAD) && defined(_POSIX_THREAD_SAFE_FUNCTIONS) && !defined(Q_OS_OPENBSD)
        struct passwd entry;
        getpwuid_r(ownerId(own), &entry, buf.data(), buf.size(), &pw);
#else
        pw = getpwuid(ownerId(own));
#endif
        if (pw)
            return QFile::decodeName(QByteArray(pw->pw_name));
    } else if (own == OwnerGroup) {
#if !defined(Q_OS_SYMBIAN)
        struct group *gr = 0;
#if !defined(QT_NO_THREAD) && defined(_POSIX_THREAD_SAFE_FUNCTIONS) && !defined(Q_OS_OPENBSD)
        size_max = sysconf(_SC_GETGR_R_SIZE_MAX);
        if (size_max == -1)
            size_max = 1024;
        buf.resize(size_max);
        struct group entry;
        // Some large systems have more members than the POSIX max size
        // Loop over by doubling the buffer size (upper limit 250k)
        for (unsigned size = size_max; size < 256000; size += size)
        {
            buf.resize(size);
            // ERANGE indicates that the buffer was too small
            if (!getgrgid_r(ownerId(own), &entry, buf.data(), buf.size(), &gr)
                || errno != ERANGE)
                break;
        }
#else
        gr = getgrgid(ownerId(own));
#endif
        if (gr)
            return QFile::decodeName(QByteArray(gr->gr_name));
#endif
    }
    return QString();
}

bool QFSFileEngine::setPermissions(uint perms)
{
    Q_D(QFSFileEngine);
    if (!QFileSystemEngine::setPermissions(d->fileEntry, QFile::Permissions(perms), 0)) {
        setError(QFile::PermissionsError,
#ifdef Q_OS_SYMBIAN
    //TODO: connect up error reporting properly
    QString());
#else
    qt_error_string(errno));
#endif
        return false;
    }
    return true;
}

#ifdef Q_OS_SYMBIAN
bool QFSFileEngine::setSize(qint64 size)
{
    Q_D(QFSFileEngine);
    bool ret = false;
    TInt err = KErrNone;
    if (d->symbianFile.SubSessionHandle()) {
        TInt err = d->symbianFile.SetSize(size);
        ret = (err == KErrNone);
    }
    else if (d->fd != -1)
        ret = QT_FTRUNCATE(d->fd, size) == 0;
    else if (d->fh)
        ret = QT_FTRUNCATE(QT_FILENO(d->fh), size) == 0;
    else {
        RFile tmp;
        QString symbianFilename(d->fileEntry.nativeFilePath());
        err = tmp.Open(qt_s60GetRFs(), qt_QString2TPtrC(symbianFilename), EFileWrite);
        if (err == KErrNone)
        {
            err = tmp.SetSize(size);
            tmp.Close();
        }
        ret = (err == KErrNone);
    }
    if (!ret) {
        if (err)
            d->setSymbianError(err, QFile::ResizeError, QString());
        else
            setError(QFile::ResizeError, qt_error_string(errno));
    }
    return ret;
}
#else
bool QFSFileEngine::setSize(qint64 size)
{
    Q_D(QFSFileEngine);
    bool ret = false;
    if (d->fd != -1)
        ret = QT_FTRUNCATE(d->fd, size) == 0;
    else if (d->fh)
        ret = QT_FTRUNCATE(QT_FILENO(d->fh), size) == 0;
    else
        ret = QT_TRUNCATE(d->fileEntry.nativeFilePath().constData(), size) == 0;
    if (!ret)
        setError(QFile::ResizeError, qt_error_string(errno));
    return ret;
}
#endif

QDateTime QFSFileEngine::fileTime(FileTime time) const
{
    Q_D(const QFSFileEngine);

    if (d->doStat(QFileSystemMetaData::Times))
        return d->metaData.fileTime(time);

    return QDateTime();
}

#ifdef Q_OS_SYMBIAN
uchar *QFSFileEnginePrivate::map(qint64 offset, qint64 size, QFile::MemoryMapFlags flags)
{
    //Q_Q(QFSFileEngine);
    Q_UNUSED(flags)
    Q_UNUSED(offset)
    Q_UNUSED(size)
    return 0;
    //TODO: use RFileMap when available in symbian^4
}

bool QFSFileEnginePrivate::unmap(uchar *ptr)
{
    //TODO: RFileMap as the value in maps, unmap it here when API is available...
    //Q_Q(QFSFileEngine);
    //if (!maps.contains(ptr)) {
    //    q->setError(QFile::PermissionsError, qt_error_string(EACCES));
    //    return false;
    //}
    Q_UNUSED(ptr)

    return false;
}
#else
uchar *QFSFileEnginePrivate::map(qint64 offset, qint64 size, QFile::MemoryMapFlags flags)
{
    Q_Q(QFSFileEngine);
    Q_UNUSED(flags);
    if (openMode == QIODevice::NotOpen) {
        q->setError(QFile::PermissionsError, qt_error_string(int(EACCES)));
        return 0;
    }

    if (offset < 0 || offset != qint64(QT_OFF_T(offset))
            || size < 0 || quint64(size) > quint64(size_t(-1))) {
        q->setError(QFile::UnspecifiedError, qt_error_string(int(EINVAL)));
        return 0;
    }

    // If we know the mapping will extend beyond EOF, fail early to avoid
    // undefined behavior. Otherwise, let mmap have its say.
    if (doStat(QFileSystemMetaData::SizeAttribute)
            && (QT_OFF_T(size) > metaData.size() - QT_OFF_T(offset)))
        qWarning("QFSFileEngine::map: Mapping a file beyond its size is not portable");

    int access = 0;
    if (openMode & QIODevice::ReadOnly) access |= PROT_READ;
    if (openMode & QIODevice::WriteOnly) access |= PROT_WRITE;

    int pageSize = getpagesize();
    int extra = offset % pageSize;

    if (quint64(size + extra) > quint64((size_t)-1)) {
        q->setError(QFile::UnspecifiedError, qt_error_string(int(EINVAL)));
        return 0;
    }

    size_t realSize = (size_t)size + extra;
    QT_OFF_T realOffset = QT_OFF_T(offset);
    realOffset &= ~(QT_OFF_T(pageSize - 1));

#ifdef Q_OS_SYMBIAN
    void *mapAddress;
    TRAPD(err,     mapAddress = QT_MMAP((void*)0, realSize,
                   access, MAP_SHARED, nativeHandle(), realOffset));
    if (err != KErrNone) {
        qWarning("OpenC bug: leave from mmap %d", err);
        mapAddress = MAP_FAILED;
        errno = EINVAL;
    }
#else
    void *mapAddress = QT_MMAP((void*)0, realSize,
                   access, MAP_SHARED, nativeHandle(), realOffset);
#endif
    if (MAP_FAILED != mapAddress) {
        uchar *address = extra + static_cast<uchar*>(mapAddress);
        maps[address] = QPair<int,size_t>(extra, realSize);
        return address;
    }

    switch(errno) {
    case EBADF:
        q->setError(QFile::PermissionsError, qt_error_string(int(EACCES)));
        break;
    case ENFILE:
    case ENOMEM:
        q->setError(QFile::ResourceError, qt_error_string(int(errno)));
        break;
    case EINVAL:
        // size are out of bounds
    default:
        q->setError(QFile::UnspecifiedError, qt_error_string(int(errno)));
        break;
    }
    return 0;
}

bool QFSFileEnginePrivate::unmap(uchar *ptr)
{
    Q_Q(QFSFileEngine);
    if (!maps.contains(ptr)) {
        q->setError(QFile::PermissionsError, qt_error_string(EACCES));
        return false;
    }

    uchar *start = ptr - maps[ptr].first;
    size_t len = maps[ptr].second;
    if (-1 == munmap(start, len)) {
        q->setError(QFile::UnspecifiedError, qt_error_string(errno));
        return false;
    }
    maps.remove(ptr);
    return true;
}
#endif

QT_END_NAMESPACE

#endif // QT_NO_FSFILEENGINE