1 // Copyright 2020 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "aemu/base/misc/FileUtils.h"
16 #include "aemu/base/EintrWrapper.h"
17
18 #include <assert.h>
19 #include <fcntl.h>
20 #include <sys/stat.h>
21 #include <sys/types.h>
22 #include "aemu/base/msvc.h"
23 #ifdef _MSC_VER
24 //#include "aemu/base/msvc.h"
25 #else
26 #include <unistd.h>
27 #endif
28
29 #ifdef _WIN32
30 #include <io.h>
31 #endif
32
33 #include <fstream>
34 #include <sstream>
35 #include <string>
36 #include <utility>
37
38 namespace android {
39
readFileIntoString(int fd,std::string * file_contents)40 bool readFileIntoString(int fd, std::string* file_contents) {
41 #ifdef _MSC_VER
42 if (fd < 0) return false; // msvc does not handle fd -1 very well.
43 #endif
44
45 off_t size = lseek(fd, 0, SEEK_END);
46 if (size == (off_t)-1) {
47 return false;
48 }
49 off_t err = lseek(fd, 0, SEEK_SET);
50 if (err == (off_t)-1) {
51 return false;
52 }
53
54 std::string buf((size_t)size, '\0');
55 ssize_t result = HANDLE_EINTR(read(fd, &buf[0], size));
56 if (result != size) {
57 return false;
58 }
59 *file_contents = std::move(buf);
60 return true;
61 }
62
writeStringToFile(int fd,const std::string & file_contents)63 bool writeStringToFile(int fd, const std::string& file_contents) {
64 #ifdef _MSC_VER
65 // msvc does not handle fd -1 very well.
66 if (fd < 0) return false;
67
68 ssize_t result = HANDLE_EINTR(
69 _write(fd, file_contents.c_str(), file_contents.size()));
70 #else
71 ssize_t result = HANDLE_EINTR(
72 write(fd, file_contents.c_str(), file_contents.size()));
73 #endif
74 if (result != (ssize_t)file_contents.size()) {
75 return false;
76 }
77 return true;
78 }
79
readFileIntoString(const std::string & name)80 base::Optional<std::string> readFileIntoString(const std::string& name) {
81 std::ifstream is(name, std::ios_base::binary);
82 if (!is) {
83 return {};
84 }
85
86 std::ostringstream ss;
87 ss << is.rdbuf();
88 return ss.str();
89 }
90
setFileSize(int fd,int64_t size)91 bool setFileSize(int fd, int64_t size) {
92 #ifdef _WIN32
93 #ifdef _MSC_VER
94 if (fd < 0) return false; // msvc does not handle fd -1 very well.
95 #endif
96 return _chsize_s(fd, size) == 0;
97 #else
98 return ftruncate(fd, size) == 0;
99 #endif
100 }
101
102 } // namespace android
103