aboutsummaryrefslogtreecommitdiff
path: root/source/Host/common/File.cpp
blob: 89587a999d93eb8c43994c4de78a73bd73258aa5 (plain) (blame)
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
//===-- File.cpp ------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/Host/File.h"

#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>

#ifdef _WIN32
#include "lldb/Host/windows/windows.h"
#else
#include <sys/ioctl.h>
#endif

#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/Process.h" // for llvm::sys::Process::FileDescriptorHasColors()

#include "lldb/Core/DataBufferHeap.h"
#include "lldb/Core/Error.h"
#include "lldb/Core/Log.h"
#include "lldb/Host/Config.h"
#include "lldb/Host/FileSpec.h"
#include "lldb/Host/FileSystem.h"

using namespace lldb;
using namespace lldb_private;

static const char *
GetStreamOpenModeFromOptions (uint32_t options)
{
    if (options & File::eOpenOptionAppend)
    {
        if (options & File::eOpenOptionRead)
        {
            if (options & File::eOpenOptionCanCreateNewOnly)
                return "a+x";
            else
                return "a+";
        }
        else if (options & File::eOpenOptionWrite)
        {
            if (options & File::eOpenOptionCanCreateNewOnly)
                return "ax";
            else
                return "a";
        }
    }
    else if (options & File::eOpenOptionRead && options & File::eOpenOptionWrite)
    {
        if (options & File::eOpenOptionCanCreate)
        {
            if (options & File::eOpenOptionCanCreateNewOnly)
                return "w+x";
            else
                return "w+";
        }
        else
            return "r+";
    }
    else if (options & File::eOpenOptionRead)
    {
        return "r";
    }
    else if (options & File::eOpenOptionWrite)
    {
        return "w";
    }
    return NULL;
}

int File::kInvalidDescriptor = -1;
FILE * File::kInvalidStream = NULL;

File::File(const char *path, uint32_t options, uint32_t permissions) :
    IOObject(eFDTypeFile, false),
    m_descriptor (kInvalidDescriptor),
    m_stream (kInvalidStream),
    m_options (),
    m_own_stream (false),
    m_is_interactive (eLazyBoolCalculate),
    m_is_real_terminal (eLazyBoolCalculate)
{
    Open (path, options, permissions);
}

File::File (const FileSpec& filespec,
            uint32_t options,
            uint32_t permissions) :
    IOObject(eFDTypeFile, false),
    m_descriptor (kInvalidDescriptor),
    m_stream (kInvalidStream),
    m_options (0),
    m_own_stream (false),
    m_is_interactive (eLazyBoolCalculate),
    m_is_real_terminal (eLazyBoolCalculate)

{
    if (filespec)
    {
        Open (filespec.GetPath().c_str(), options, permissions);
    }
}

File::~File()
{
    Close ();
}


int
File::GetDescriptor() const
{
    if (DescriptorIsValid())
        return m_descriptor;

    // Don't open the file descriptor if we don't need to, just get it from the
    // stream if we have one.
    if (StreamIsValid())
    {
#if defined(LLVM_ON_WIN32)
        return _fileno(m_stream);
#else
        return fileno(m_stream);
#endif
    }

    // Invalid descriptor and invalid stream, return invalid descriptor.
    return kInvalidDescriptor;
}

IOObject::WaitableHandle
File::GetWaitableHandle()
{
    return m_descriptor;
}


void
File::SetDescriptor (int fd, bool transfer_ownership)
{
    if (IsValid())
        Close();
    m_descriptor = fd;
    m_should_close_fd = transfer_ownership;
}


FILE *
File::GetStream ()
{
    if (!StreamIsValid())
    {
        if (DescriptorIsValid())
        {
            const char *mode = GetStreamOpenModeFromOptions (m_options);
            if (mode)
            {
                if (!m_should_close_fd)
                {
                    // We must duplicate the file descriptor if we don't own it because
                    // when you call fdopen, the stream will own the fd
#ifdef _WIN32
                    m_descriptor = ::_dup(GetDescriptor());
#else
                    m_descriptor = dup(GetDescriptor());
#endif
                    m_should_close_fd = true;
                }

                do
                {
                    m_stream = ::fdopen (m_descriptor, mode);
                } while (m_stream == NULL && errno == EINTR);

                // If we got a stream, then we own the stream and should no
                // longer own the descriptor because fclose() will close it for us

                if (m_stream)
                {
                    m_own_stream = true;
                    m_should_close_fd = false;
                }
            }
        }
    }
    return m_stream;
}

void
File::SetStream (FILE *fh, bool transfer_ownership)
{
    if (IsValid())
        Close();
    m_stream = fh;
    m_own_stream = transfer_ownership;
}

Error
File::Open (const char *path, uint32_t options, uint32_t permissions)
{
    Error error;
    if (IsValid())
        Close ();

    int oflag = 0;
    const bool read = options & eOpenOptionRead;
    const bool write = options & eOpenOptionWrite;
    if (write)
    {
        if (read)
            oflag |= O_RDWR;
        else
            oflag |= O_WRONLY;
        
        if (options & eOpenOptionAppend)
            oflag |= O_APPEND;

        if (options & eOpenOptionTruncate)
            oflag |= O_TRUNC;

        if (options & eOpenOptionCanCreate)
            oflag |= O_CREAT;
        
        if (options & eOpenOptionCanCreateNewOnly)
            oflag |= O_CREAT | O_EXCL;
    }
    else if (read)
    {
        oflag |= O_RDONLY;

#ifndef _WIN32
        if (options & eOpenOptionDontFollowSymlinks)
            oflag |= O_NOFOLLOW;
#endif
    }
    
#ifndef _WIN32
    if (options & eOpenOptionNonBlocking)
        oflag |= O_NONBLOCK;
    if (options & eOpenOptionCloseOnExec)
        oflag |= O_CLOEXEC;
#else
    oflag |= O_BINARY;
#endif

    mode_t mode = 0;
    if (oflag & O_CREAT)
    {
        if (permissions & lldb::eFilePermissionsUserRead)     mode |= S_IRUSR;
        if (permissions & lldb::eFilePermissionsUserWrite)    mode |= S_IWUSR;
        if (permissions & lldb::eFilePermissionsUserExecute)  mode |= S_IXUSR;
        if (permissions & lldb::eFilePermissionsGroupRead)    mode |= S_IRGRP;
        if (permissions & lldb::eFilePermissionsGroupWrite)   mode |= S_IWGRP;
        if (permissions & lldb::eFilePermissionsGroupExecute) mode |= S_IXGRP;
        if (permissions & lldb::eFilePermissionsWorldRead)    mode |= S_IROTH;
        if (permissions & lldb::eFilePermissionsWorldWrite)   mode |= S_IWOTH;
        if (permissions & lldb::eFilePermissionsWorldExecute) mode |= S_IXOTH;
    }

    do
    {
#ifdef _WIN32
        std::wstring wpath;
        if (!llvm::ConvertUTF8toWide(path, wpath))
        {
            m_descriptor = -1;
            error.SetErrorString("Error converting path to UTF-16");
            return error;
        }
        ::_wsopen_s(&m_descriptor, wpath.c_str(), oflag, _SH_DENYNO, mode);
#else
        m_descriptor = ::open(path, oflag, mode);
#endif
    } while (m_descriptor < 0 && errno == EINTR);

    if (!DescriptorIsValid())
        error.SetErrorToErrno();
    else
    {
        m_should_close_fd = true;
        m_options = options;
    }
    
    return error;
}

uint32_t
File::GetPermissions(const FileSpec &file_spec, Error &error)
{
    if (file_spec)
    {
        struct stat file_stats;
        int stat_result = FileSystem::Stat(file_spec.GetCString(), &file_stats);
        if (stat_result == -1)
            error.SetErrorToErrno();
        else
        {
            error.Clear();
            return file_stats.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
        }
    }
    else
        error.SetErrorString ("empty file spec");
    return 0;
}

uint32_t
File::GetPermissions(Error &error) const
{
    int fd = GetDescriptor();
    if (fd != kInvalidDescriptor)
    {
        struct stat file_stats;
        if (::fstat (fd, &file_stats) == -1)
            error.SetErrorToErrno();
        else
        {
            error.Clear();
            return file_stats.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
        }
    }
    else
    {
        error.SetErrorString ("invalid file descriptor");
    }
    return 0;
}


Error
File::Close ()
{
    Error error;
    if (StreamIsValid() && m_own_stream)
    {
        if (::fclose (m_stream) == EOF)
            error.SetErrorToErrno();
    }
    
    if (DescriptorIsValid() && m_should_close_fd)
    {
        if (::close (m_descriptor) != 0)
            error.SetErrorToErrno();
    }
    m_descriptor = kInvalidDescriptor;
    m_stream = kInvalidStream;
    m_options = 0;
    m_own_stream = false;
    m_should_close_fd = false;
    m_is_interactive = eLazyBoolCalculate;
    m_is_real_terminal = eLazyBoolCalculate;
    return error;
}

void
File::Clear ()
{
    m_stream = nullptr;
    m_descriptor = -1;
    m_options = 0;
    m_own_stream = false;
    m_is_interactive = m_supports_colors = m_is_real_terminal = eLazyBoolCalculate;
}

Error
File::GetFileSpec (FileSpec &file_spec) const
{
    Error error;
#ifdef LLDB_CONFIG_FCNTL_GETPATH_SUPPORTED
    if (IsValid ())
    {
        char path[PATH_MAX];
        if (::fcntl(GetDescriptor(), F_GETPATH, path) == -1)
            error.SetErrorToErrno();
        else
            file_spec.SetFile (path, false);
    }
    else 
    {
        error.SetErrorString("invalid file handle");
    }
#elif defined(__linux__)
    char proc[64];
    char path[PATH_MAX];
    if (::snprintf(proc, sizeof(proc), "/proc/self/fd/%d", GetDescriptor()) < 0)
        error.SetErrorString ("cannot resolve file descriptor");
    else
    {
        ssize_t len;
        if ((len = ::readlink(proc, path, sizeof(path) - 1)) == -1)
            error.SetErrorToErrno();
        else
        {
            path[len] = '\0';
            file_spec.SetFile (path, false);
        }
    }
#else
    error.SetErrorString ("File::GetFileSpec is not supported on this platform");
#endif

    if (error.Fail())
        file_spec.Clear();
    return error;
}

off_t
File::SeekFromStart (off_t offset, Error *error_ptr)
{
    off_t result = 0;
    if (DescriptorIsValid())
    {
        result = ::lseek (m_descriptor, offset, SEEK_SET);

        if (error_ptr)
        {
            if (result == -1)
                error_ptr->SetErrorToErrno();
            else
                error_ptr->Clear();
        }
    }
    else if (StreamIsValid ())
    {
        result = ::fseek(m_stream, offset, SEEK_SET);
        
        if (error_ptr)
        {
            if (result == -1)
                error_ptr->SetErrorToErrno();
            else
                error_ptr->Clear();
        }
    }
    else if (error_ptr)
    {
        error_ptr->SetErrorString("invalid file handle");
    }
    return result;
}

off_t
File::SeekFromCurrent (off_t offset,  Error *error_ptr)
{
    off_t result = -1;
    if (DescriptorIsValid())
    {
        result = ::lseek (m_descriptor, offset, SEEK_CUR);
        
        if (error_ptr)
        {
            if (result == -1)
                error_ptr->SetErrorToErrno();
            else
                error_ptr->Clear();
        }
    }
    else if (StreamIsValid ())
    {
        result = ::fseek(m_stream, offset, SEEK_CUR);
        
        if (error_ptr)
        {
            if (result == -1)
                error_ptr->SetErrorToErrno();
            else
                error_ptr->Clear();
        }
    }
    else if (error_ptr)
    {
        error_ptr->SetErrorString("invalid file handle");
    }
    return result;
}

off_t
File::SeekFromEnd (off_t offset, Error *error_ptr)
{
    off_t result = -1;
    if (DescriptorIsValid())
    {
        result = ::lseek (m_descriptor, offset, SEEK_END);
        
        if (error_ptr)
        {
            if (result == -1)
                error_ptr->SetErrorToErrno();
            else
                error_ptr->Clear();
        }
    }
    else if (StreamIsValid ())
    {
        result = ::fseek(m_stream, offset, SEEK_END);
        
        if (error_ptr)
        {
            if (result == -1)
                error_ptr->SetErrorToErrno();
            else
                error_ptr->Clear();
        }
    }
    else if (error_ptr)
    {
        error_ptr->SetErrorString("invalid file handle");
    }
    return result;
}

Error
File::Flush ()
{
    Error error;
    if (StreamIsValid())
    {
        int err = 0;
        do
        {
            err = ::fflush (m_stream);
        } while (err == EOF && errno == EINTR);
        
        if (err == EOF)
            error.SetErrorToErrno();
    }
    else if (!DescriptorIsValid())
    {
        error.SetErrorString("invalid file handle");
    }
    return error;
}


Error
File::Sync ()
{
    Error error;
    if (DescriptorIsValid())
    {
#ifdef _WIN32
        int err = FlushFileBuffers((HANDLE)_get_osfhandle(m_descriptor));
        if (err == 0)
            error.SetErrorToGenericError();
#else
        int err = 0;
        do
        {
            err = ::fsync (m_descriptor);
        } while (err == -1 && errno == EINTR);
        
        if (err == -1)
            error.SetErrorToErrno();
#endif
    }
    else 
    {
        error.SetErrorString("invalid file handle");
    }
    return error;
}

#if defined (__APPLE__)
// Darwin kernels only can read/write <= INT_MAX bytes
#define MAX_READ_SIZE INT_MAX
#define MAX_WRITE_SIZE INT_MAX
#endif

Error
File::Read (void *buf, size_t &num_bytes)
{
    Error error;

#if defined (MAX_READ_SIZE)
    if (num_bytes > MAX_READ_SIZE)
    {
        uint8_t *p = (uint8_t *)buf;
        size_t bytes_left = num_bytes;
        // Init the num_bytes read to zero
        num_bytes = 0;

        while (bytes_left > 0)
        {
            size_t curr_num_bytes;
            if (bytes_left > MAX_READ_SIZE)
                curr_num_bytes = MAX_READ_SIZE;
            else
                curr_num_bytes = bytes_left;

            error = Read (p + num_bytes, curr_num_bytes);

            // Update how many bytes were read
            num_bytes += curr_num_bytes;
            if (bytes_left < curr_num_bytes)
                bytes_left = 0;
            else
                bytes_left -= curr_num_bytes;

            if (error.Fail())
                break;
        }
        return error;
    }
#endif

    ssize_t bytes_read = -1;
    if (DescriptorIsValid())
    {
        do
        {
            bytes_read = ::read (m_descriptor, buf, num_bytes);
        } while (bytes_read < 0 && errno == EINTR);

        if (bytes_read == -1)
        {
            error.SetErrorToErrno();
            num_bytes = 0;
        }
        else
            num_bytes = bytes_read;
    }
    else if (StreamIsValid())
    {
        bytes_read = ::fread (buf, 1, num_bytes, m_stream);

        if (bytes_read == 0)
        {
            if (::feof(m_stream))
                error.SetErrorString ("feof");
            else if (::ferror (m_stream))
                error.SetErrorString ("ferror");
            num_bytes = 0;
        }
        else
            num_bytes = bytes_read;
    }
    else 
    {
        num_bytes = 0;
        error.SetErrorString("invalid file handle");
    }
    return error;
}
          
Error
File::Write (const void *buf, size_t &num_bytes)
{
    Error error;

#if defined (MAX_WRITE_SIZE)
    if (num_bytes > MAX_WRITE_SIZE)
    {
        const uint8_t *p = (const uint8_t *)buf;
        size_t bytes_left = num_bytes;
        // Init the num_bytes written to zero
        num_bytes = 0;

        while (bytes_left > 0)
        {
            size_t curr_num_bytes;
            if (bytes_left > MAX_WRITE_SIZE)
                curr_num_bytes = MAX_WRITE_SIZE;
            else
                curr_num_bytes = bytes_left;

            error = Write (p + num_bytes, curr_num_bytes);

            // Update how many bytes were read
            num_bytes += curr_num_bytes;
            if (bytes_left < curr_num_bytes)
                bytes_left = 0;
            else
                bytes_left -= curr_num_bytes;

            if (error.Fail())
                break;
        }
        return error;
    }
#endif

    ssize_t bytes_written = -1;
    if (DescriptorIsValid())
    {
        do
        {
            bytes_written = ::write (m_descriptor, buf, num_bytes);
        } while (bytes_written < 0 && errno == EINTR);

        if (bytes_written == -1)
        {
            error.SetErrorToErrno();
            num_bytes = 0;
        }
        else
            num_bytes = bytes_written;
    }
    else if (StreamIsValid())
    {
        bytes_written = ::fwrite (buf, 1, num_bytes, m_stream);

        if (bytes_written == 0)
        {
            if (::feof(m_stream))
                error.SetErrorString ("feof");
            else if (::ferror (m_stream))
                error.SetErrorString ("ferror");
            num_bytes = 0;
        }
        else
            num_bytes = bytes_written;
        
    }
    else 
    {
        num_bytes = 0;
        error.SetErrorString("invalid file handle");
    }

    return error;
}


Error
File::Read (void *buf, size_t &num_bytes, off_t &offset)
{
    Error error;

#if defined (MAX_READ_SIZE)
    if (num_bytes > MAX_READ_SIZE)
    {
        uint8_t *p = (uint8_t *)buf;
        size_t bytes_left = num_bytes;
        // Init the num_bytes read to zero
        num_bytes = 0;

        while (bytes_left > 0)
        {
            size_t curr_num_bytes;
            if (bytes_left > MAX_READ_SIZE)
                curr_num_bytes = MAX_READ_SIZE;
            else
                curr_num_bytes = bytes_left;

            error = Read (p + num_bytes, curr_num_bytes, offset);

            // Update how many bytes were read
            num_bytes += curr_num_bytes;
            if (bytes_left < curr_num_bytes)
                bytes_left = 0;
            else
                bytes_left -= curr_num_bytes;

            if (error.Fail())
                break;
        }
        return error;
    }
#endif

#ifndef _WIN32
    int fd = GetDescriptor();
    if (fd != kInvalidDescriptor)
    {
        ssize_t bytes_read = -1;
        do
        {
            bytes_read = ::pread (fd, buf, num_bytes, offset);
        } while (bytes_read < 0 && errno == EINTR);

        if (bytes_read < 0)
        {
            num_bytes = 0;
            error.SetErrorToErrno();
        }
        else
        {
            offset += bytes_read;
            num_bytes = bytes_read;
        }
    }
    else 
    {
        num_bytes = 0;
        error.SetErrorString("invalid file handle");
    }
#else
    long cur = ::lseek(m_descriptor, 0, SEEK_CUR);
    SeekFromStart(offset);
    error = Read(buf, num_bytes);
    if (!error.Fail())
        SeekFromStart(cur);
#endif
    return error;
}

Error
File::Read (size_t &num_bytes, off_t &offset, bool null_terminate, DataBufferSP &data_buffer_sp)
{
    Error error;
    
    if (num_bytes > 0)
    {
        int fd = GetDescriptor();
        if (fd != kInvalidDescriptor)
        {
            struct stat file_stats;
            if (::fstat (fd, &file_stats) == 0)
            {
                if (file_stats.st_size > offset)
                {
                    const size_t bytes_left = file_stats.st_size - offset;
                    if (num_bytes > bytes_left)
                        num_bytes = bytes_left;
                        
                    size_t num_bytes_plus_nul_char = num_bytes + (null_terminate ? 1 : 0);
                    std::unique_ptr<DataBufferHeap> data_heap_ap;
                    data_heap_ap.reset(new DataBufferHeap());
                    data_heap_ap->SetByteSize(num_bytes_plus_nul_char);
                        
                    if (data_heap_ap.get())
                    {
                        error = Read (data_heap_ap->GetBytes(), num_bytes, offset);
                        if (error.Success())
                        {
                            // Make sure we read exactly what we asked for and if we got
                            // less, adjust the array
                            if (num_bytes_plus_nul_char < data_heap_ap->GetByteSize())
                                data_heap_ap->SetByteSize(num_bytes_plus_nul_char);
                            data_buffer_sp.reset(data_heap_ap.release());
                            return error;
                        }
                    }
                }
                else 
                    error.SetErrorString("file is empty");
            }
            else
                error.SetErrorToErrno();
        }
        else 
            error.SetErrorString("invalid file handle");
    }
    else
        error.SetErrorString("invalid file handle");

    num_bytes = 0;
    data_buffer_sp.reset();
    return error;
}

Error
File::Write (const void *buf, size_t &num_bytes, off_t &offset)
{
    Error error;

#if defined (MAX_WRITE_SIZE)
    if (num_bytes > MAX_WRITE_SIZE)
    {
        const uint8_t *p = (const uint8_t *)buf;
        size_t bytes_left = num_bytes;
        // Init the num_bytes written to zero
        num_bytes = 0;

        while (bytes_left > 0)
        {
            size_t curr_num_bytes;
            if (bytes_left > MAX_WRITE_SIZE)
                curr_num_bytes = MAX_WRITE_SIZE;
            else
                curr_num_bytes = bytes_left;

            error = Write (p + num_bytes, curr_num_bytes, offset);

            // Update how many bytes were read
            num_bytes += curr_num_bytes;
            if (bytes_left < curr_num_bytes)
                bytes_left = 0;
            else
                bytes_left -= curr_num_bytes;

            if (error.Fail())
                break;
        }
        return error;
    }
#endif

    int fd = GetDescriptor();
    if (fd != kInvalidDescriptor)
    {
#ifndef _WIN32
        ssize_t bytes_written = -1;
        do
        {
            bytes_written = ::pwrite (m_descriptor, buf, num_bytes, offset);
        } while (bytes_written < 0 && errno == EINTR);

        if (bytes_written < 0)
        {
            num_bytes = 0;
            error.SetErrorToErrno();
        }
        else
        {
            offset += bytes_written;
            num_bytes = bytes_written;
        }
#else
        long cur = ::lseek(m_descriptor, 0, SEEK_CUR);
        error = Write(buf, num_bytes);
        long after = ::lseek(m_descriptor, 0, SEEK_CUR);

        if (!error.Fail())
            SeekFromStart(cur);

        offset = after;
#endif
    }
    else 
    {
        num_bytes = 0;
        error.SetErrorString("invalid file handle");
    }
    return error;
}

//------------------------------------------------------------------
// Print some formatted output to the stream.
//------------------------------------------------------------------
size_t
File::Printf (const char *format, ...)
{
    va_list args;
    va_start (args, format);
    size_t result = PrintfVarArg (format, args);
    va_end (args);
    return result;
}

//------------------------------------------------------------------
// Print some formatted output to the stream.
//------------------------------------------------------------------
size_t
File::PrintfVarArg (const char *format, va_list args)
{
    size_t result = 0;
    if (DescriptorIsValid())
    {
        char *s = NULL;
        result = vasprintf(&s, format, args);
        if (s != NULL)
        {
            if (result > 0)
            {
                size_t s_len = result;
                Write (s, s_len);
                result = s_len;
            }
            free (s);
        }
    }
    else if (StreamIsValid())
    {
        result = ::vfprintf (m_stream, format, args);
    }
    return result;
}

mode_t
File::ConvertOpenOptionsForPOSIXOpen (uint32_t open_options)
{
    mode_t mode = 0;
    if (open_options & eOpenOptionRead && open_options & eOpenOptionWrite)
        mode |= O_RDWR;
    else if (open_options & eOpenOptionWrite)
        mode |= O_WRONLY;
    
    if (open_options & eOpenOptionAppend)
        mode |= O_APPEND;

    if (open_options & eOpenOptionTruncate)
        mode |= O_TRUNC;

    if (open_options & eOpenOptionNonBlocking)
        mode |= O_NONBLOCK;

    if (open_options & eOpenOptionCanCreateNewOnly)
        mode |= O_CREAT | O_EXCL;
    else if (open_options & eOpenOptionCanCreate)
        mode |= O_CREAT;

    return mode;
}

void
File::CalculateInteractiveAndTerminal ()
{
    const int fd = GetDescriptor();
    if (fd >= 0)
    {
        m_is_interactive = eLazyBoolNo;
        m_is_real_terminal = eLazyBoolNo;
#if defined(_WIN32)
        if (_isatty(fd))
        {
            m_is_interactive = eLazyBoolYes;
            m_is_real_terminal = eLazyBoolYes;
        }
#else
        if (isatty(fd))
        {
            m_is_interactive = eLazyBoolYes;
            struct winsize window_size;
            if (::ioctl (fd, TIOCGWINSZ, &window_size) == 0)
            {
                if (window_size.ws_col > 0)
                {
                    m_is_real_terminal = eLazyBoolYes;
                    if (llvm::sys::Process::FileDescriptorHasColors(fd))
                        m_supports_colors = eLazyBoolYes;
                }
            }
        }
#endif
    }
}

bool
File::GetIsInteractive ()
{
    if (m_is_interactive == eLazyBoolCalculate)
        CalculateInteractiveAndTerminal ();
    return m_is_interactive == eLazyBoolYes;
}

bool
File::GetIsRealTerminal ()
{
    if (m_is_real_terminal == eLazyBoolCalculate)
        CalculateInteractiveAndTerminal();
    return m_is_real_terminal == eLazyBoolYes;
}

bool
File::GetIsTerminalWithColors ()
{
    if (m_supports_colors == eLazyBoolCalculate)
        CalculateInteractiveAndTerminal();
    return m_supports_colors == eLazyBoolYes;
}