1 // Copyright 2013 The Flutter Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "runtime/dart/utils/files.h"
6
7 #include <fcntl.h>
8 #include <stdint.h>
9
10 #include "runtime/dart/utils/inlines.h"
11 #include "runtime/dart/utils/logging.h"
12
13 namespace dart_utils {
14
15 namespace {
16
ReadFileDescriptor(int fd,std::string * result)17 bool ReadFileDescriptor(int fd, std::string* result) {
18 DEBUG_CHECK(result, LOG_TAG, "");
19 result->clear();
20
21 if (fd < 0) {
22 return false;
23 }
24
25 constexpr size_t kBufferSize = 1 << 16;
26 size_t offset = 0;
27 ssize_t bytes_read = 0;
28 do {
29 offset += bytes_read;
30 result->resize(offset + kBufferSize);
31 bytes_read = read(fd, &(*result)[offset], kBufferSize);
32 } while (bytes_read > 0);
33
34 if (bytes_read < 0) {
35 result->clear();
36 return false;
37 }
38
39 result->resize(offset + bytes_read);
40 return true;
41 }
42
WriteFileDescriptor(int fd,const char * data,ssize_t size)43 bool WriteFileDescriptor(int fd, const char* data, ssize_t size) {
44 ssize_t total = 0;
45 for (ssize_t partial = 0; total < size; total += partial) {
46 partial = write(fd, data + total, size - total);
47 if (partial < 0)
48 return false;
49 }
50 return true;
51 }
52
53 } // namespace
54
ReadFileToString(const std::string & path,std::string * result)55 bool ReadFileToString(const std::string& path, std::string* result) {
56 return ReadFileToStringAt(AT_FDCWD, path, result);
57 }
58
ReadFileToStringAt(int dirfd,const std::string & path,std::string * result)59 bool ReadFileToStringAt(int dirfd,
60 const std::string& path,
61 std::string* result) {
62 int fd = openat(dirfd, path.c_str(), O_RDONLY);
63 bool status = ReadFileDescriptor(fd, result);
64 close(fd);
65 return status;
66 }
67
WriteFile(const std::string & path,const char * data,ssize_t size)68 bool WriteFile(const std::string& path, const char* data, ssize_t size) {
69 int fd = openat(AT_FDCWD, path.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0666);
70 if (fd < 0) {
71 return false;
72 }
73 bool status = WriteFileDescriptor(fd, data, size);
74 close(fd);
75 return status;
76 }
77
78 } // namespace dart_utils
79