blob: 6284b04c9a8664c23837e3d2c003d90c7796189f [file] [log] [blame]
Dan Albertaac6b7c2015-03-16 10:08:46 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Elliott Hughesb6351622015-12-04 22:00:26 -080017#include "android-base/file.h"
Dan Albertaac6b7c2015-03-16 10:08:46 -070018
19#include <errno.h>
20#include <fcntl.h>
21#include <sys/stat.h>
22#include <sys/types.h>
Elliott Hughesa634a9a2016-08-23 15:53:45 -070023#include <unistd.h>
Dan Albertaac6b7c2015-03-16 10:08:46 -070024
Josh Gao58668ac2016-09-01 12:31:42 -070025#include <memory>
Dan Albertaac6b7c2015-03-16 10:08:46 -070026#include <string>
Elliott Hughesa634a9a2016-08-23 15:53:45 -070027#include <vector>
Dan Albertaac6b7c2015-03-16 10:08:46 -070028
Elliott Hughesb6351622015-12-04 22:00:26 -080029#include "android-base/macros.h" // For TEMP_FAILURE_RETRY on Darwin.
Elliott Hughes7d9a4792016-07-28 15:15:28 -070030#include "android-base/logging.h"
Elliott Hughesb6351622015-12-04 22:00:26 -080031#include "android-base/utf8.h"
Dan Albert5f770222015-03-26 23:33:28 -070032#include "utils/Compat.h"
Dan Albertaac6b7c2015-03-16 10:08:46 -070033
Elliott Hughes48f0eb52016-08-31 15:07:18 -070034#if defined(__APPLE__)
Josh Gao58668ac2016-09-01 12:31:42 -070035#include <mach-o/dyld.h>
Elliott Hughes48f0eb52016-08-31 15:07:18 -070036#endif
37#if defined(_WIN32)
38#include <windows.h>
39#endif
40
Dan Albertaac6b7c2015-03-16 10:08:46 -070041namespace android {
42namespace base {
43
Elliott Hughes774d7f62015-11-11 18:02:29 +000044// Versions of standard library APIs that support UTF-8 strings.
45using namespace android::base::utf8;
46
Dan Albertaac6b7c2015-03-16 10:08:46 -070047bool ReadFdToString(int fd, std::string* content) {
48 content->clear();
49
50 char buf[BUFSIZ];
51 ssize_t n;
52 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], sizeof(buf)))) > 0) {
53 content->append(buf, n);
54 }
55 return (n == 0) ? true : false;
56}
57
Josh Gao8e1f0d82016-09-14 16:11:45 -070058bool ReadFileToString(const std::string& path, std::string* content, bool follow_symlinks) {
Dan Albertaac6b7c2015-03-16 10:08:46 -070059 content->clear();
60
Josh Gao8e1f0d82016-09-14 16:11:45 -070061 int flags = O_RDONLY | O_CLOEXEC | O_BINARY | (follow_symlinks ? 0 : O_NOFOLLOW);
62 int fd = TEMP_FAILURE_RETRY(open(path.c_str(), flags));
Dan Albertaac6b7c2015-03-16 10:08:46 -070063 if (fd == -1) {
64 return false;
65 }
66 bool result = ReadFdToString(fd, content);
Nick Kralevich82921302015-05-20 08:59:21 -070067 close(fd);
Dan Albertaac6b7c2015-03-16 10:08:46 -070068 return result;
69}
70
71bool WriteStringToFd(const std::string& content, int fd) {
72 const char* p = content.data();
73 size_t left = content.size();
74 while (left > 0) {
75 ssize_t n = TEMP_FAILURE_RETRY(write(fd, p, left));
76 if (n == -1) {
77 return false;
78 }
79 p += n;
80 left -= n;
81 }
82 return true;
83}
84
85static bool CleanUpAfterFailedWrite(const std::string& path) {
86 // Something went wrong. Let's not leave a corrupt file lying around.
87 int saved_errno = errno;
88 unlink(path.c_str());
89 errno = saved_errno;
90 return false;
91}
92
93#if !defined(_WIN32)
94bool WriteStringToFile(const std::string& content, const std::string& path,
Josh Gao8e1f0d82016-09-14 16:11:45 -070095 mode_t mode, uid_t owner, gid_t group,
96 bool follow_symlinks) {
97 int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY |
98 (follow_symlinks ? 0 : O_NOFOLLOW);
Elliott Hughesd5f8ae62015-09-01 13:35:44 -070099 int fd = TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode));
Dan Albertaac6b7c2015-03-16 10:08:46 -0700100 if (fd == -1) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700101 PLOG(ERROR) << "android::WriteStringToFile open failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700102 return false;
103 }
104
105 // We do an explicit fchmod here because we assume that the caller really
106 // meant what they said and doesn't want the umask-influenced mode.
107 if (fchmod(fd, mode) == -1) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700108 PLOG(ERROR) << "android::WriteStringToFile fchmod failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700109 return CleanUpAfterFailedWrite(path);
110 }
111 if (fchown(fd, owner, group) == -1) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700112 PLOG(ERROR) << "android::WriteStringToFile fchown failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700113 return CleanUpAfterFailedWrite(path);
114 }
115 if (!WriteStringToFd(content, fd)) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700116 PLOG(ERROR) << "android::WriteStringToFile write failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700117 return CleanUpAfterFailedWrite(path);
118 }
Nick Kralevich82921302015-05-20 08:59:21 -0700119 close(fd);
Dan Albertaac6b7c2015-03-16 10:08:46 -0700120 return true;
121}
122#endif
123
Josh Gao8e1f0d82016-09-14 16:11:45 -0700124bool WriteStringToFile(const std::string& content, const std::string& path,
125 bool follow_symlinks) {
126 int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY |
127 (follow_symlinks ? 0 : O_NOFOLLOW);
Elliott Hughesd5f8ae62015-09-01 13:35:44 -0700128 int fd = TEMP_FAILURE_RETRY(open(path.c_str(), flags, DEFFILEMODE));
Dan Albertaac6b7c2015-03-16 10:08:46 -0700129 if (fd == -1) {
130 return false;
131 }
132
133 bool result = WriteStringToFd(content, fd);
Nick Kralevich82921302015-05-20 08:59:21 -0700134 close(fd);
Dan Albertaac6b7c2015-03-16 10:08:46 -0700135 return result || CleanUpAfterFailedWrite(path);
136}
137
Elliott Hughes20abc872015-04-24 21:57:16 -0700138bool ReadFully(int fd, void* data, size_t byte_count) {
139 uint8_t* p = reinterpret_cast<uint8_t*>(data);
140 size_t remaining = byte_count;
141 while (remaining > 0) {
142 ssize_t n = TEMP_FAILURE_RETRY(read(fd, p, remaining));
143 if (n <= 0) return false;
144 p += n;
145 remaining -= n;
146 }
147 return true;
148}
149
150bool WriteFully(int fd, const void* data, size_t byte_count) {
151 const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
152 size_t remaining = byte_count;
153 while (remaining > 0) {
154 ssize_t n = TEMP_FAILURE_RETRY(write(fd, p, remaining));
155 if (n == -1) return false;
156 p += n;
157 remaining -= n;
158 }
159 return true;
160}
161
Yabin Cui8f6a5a02016-01-29 17:25:54 -0800162bool RemoveFileIfExists(const std::string& path, std::string* err) {
163 struct stat st;
164#if defined(_WIN32)
165 //TODO: Windows version can't handle symbol link correctly.
166 int result = stat(path.c_str(), &st);
167 bool file_type_removable = (result == 0 && S_ISREG(st.st_mode));
168#else
169 int result = lstat(path.c_str(), &st);
170 bool file_type_removable = (result == 0 && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)));
171#endif
172 if (result == 0) {
173 if (!file_type_removable) {
174 if (err != nullptr) {
175 *err = "is not a regular or symbol link file";
176 }
177 return false;
178 }
179 if (unlink(path.c_str()) == -1) {
180 if (err != nullptr) {
181 *err = strerror(errno);
182 }
183 return false;
184 }
185 }
186 return true;
187}
188
Elliott Hughesa634a9a2016-08-23 15:53:45 -0700189#if !defined(_WIN32)
190bool Readlink(const std::string& path, std::string* result) {
191 result->clear();
192
193 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
194 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
195 // waste memory to just start there. We add 1 so that we can recognize
196 // whether it actually fit (rather than being truncated to 4095).
197 std::vector<char> buf(4095 + 1);
198 while (true) {
199 ssize_t size = readlink(path.c_str(), &buf[0], buf.size());
200 // Unrecoverable error?
201 if (size == -1) return false;
202 // It fit! (If size == buf.size(), it may have been truncated.)
203 if (static_cast<size_t>(size) < buf.size()) {
204 result->assign(&buf[0], size);
205 return true;
206 }
207 // Double our buffer and try again.
208 buf.resize(buf.size() * 2);
209 }
210}
211#endif
212
Elliott Hughes48f0eb52016-08-31 15:07:18 -0700213std::string GetExecutablePath() {
214#if defined(__linux__)
215 std::string path;
216 android::base::Readlink("/proc/self/exe", &path);
217 return path;
218#elif defined(__APPLE__)
Elliott Hughes48f0eb52016-08-31 15:07:18 -0700219 char path[PATH_MAX + 1];
Josh Gao58668ac2016-09-01 12:31:42 -0700220 uint32_t path_len = sizeof(path);
221 int rc = _NSGetExecutablePath(path, &path_len);
222 if (rc < 0) {
223 std::unique_ptr<char> path_buf(new char[path_len]);
224 _NSGetExecutablePath(path_buf.get(), &path_len);
225 return path_buf.get();
226 }
Elliott Hughes48f0eb52016-08-31 15:07:18 -0700227 return path;
228#elif defined(_WIN32)
229 char path[PATH_MAX + 1];
230 DWORD result = GetModuleFileName(NULL, path, sizeof(path) - 1);
231 if (result == 0 || result == sizeof(path) - 1) return "";
232 path[PATH_MAX - 1] = 0;
233 return path;
234#else
235#error unknown OS
236#endif
237}
238
Dan Albertaac6b7c2015-03-16 10:08:46 -0700239} // namespace base
240} // namespace android