blob: 3834ed42a35e0cc8f5ed43fa0e1d46cb1b643abd [file] [log] [blame]
Elliott Hughesdec12b22015-02-02 17:31:27 -08001/*
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 Hughes4f713192015-12-04 22:00:26 -080017#include "android-base/file.h"
Elliott Hughesdec12b22015-02-02 17:31:27 -080018
19#include <errno.h>
20#include <fcntl.h>
Colin Cross58021d12017-02-23 21:23:05 -080021#include <libgen.h>
Elliott Hughesdec12b22015-02-02 17:31:27 -080022#include <sys/stat.h>
23#include <sys/types.h>
Elliott Hughesd3ff6e52016-08-23 15:53:45 -070024#include <unistd.h>
Elliott Hughesdec12b22015-02-02 17:31:27 -080025
Josh Gao7307f092016-09-01 12:31:42 -070026#include <memory>
Colin Cross58021d12017-02-23 21:23:05 -080027#include <mutex>
Dan Albertc007bc32015-03-16 10:08:46 -070028#include <string>
Elliott Hughesd3ff6e52016-08-23 15:53:45 -070029#include <vector>
Elliott Hughesaf4885a2015-02-03 13:02:57 -080030
Elliott Hughese5dd71a2016-07-28 15:15:28 -070031#include "android-base/logging.h"
Christopher Ferris48d08c22017-04-05 12:09:17 -070032#include "android-base/macros.h" // For TEMP_FAILURE_RETRY on Darwin.
33#include "android-base/unique_fd.h"
Elliott Hughes4f713192015-12-04 22:00:26 -080034#include "android-base/utf8.h"
Dan Albertc007bc32015-03-16 10:08:46 -070035
Elliott Hughes82ff3152016-08-31 15:07:18 -070036#if defined(__APPLE__)
Josh Gao7307f092016-09-01 12:31:42 -070037#include <mach-o/dyld.h>
Elliott Hughes82ff3152016-08-31 15:07:18 -070038#endif
39#if defined(_WIN32)
40#include <windows.h>
Elliott Hughes282ec452017-05-15 17:31:15 -070041#define O_NOFOLLOW 0
Elliott Hughes82ff3152016-08-31 15:07:18 -070042#endif
43
Dan Albertc007bc32015-03-16 10:08:46 -070044namespace android {
45namespace base {
46
Elliott Hughesc1fd4922015-11-11 18:02:29 +000047// Versions of standard library APIs that support UTF-8 strings.
48using namespace android::base::utf8;
49
Dan Albertc007bc32015-03-16 10:08:46 -070050bool ReadFdToString(int fd, std::string* content) {
Elliott Hughesf682b472015-02-06 12:19:48 -080051 content->clear();
52
Elliott Hughes9bb79712017-03-20 19:16:18 -070053 // Although original we had small files in mind, this code gets used for
54 // very large files too, where the std::string growth heuristics might not
55 // be suitable. https://code.google.com/p/android/issues/detail?id=258500.
56 struct stat sb;
57 if (fstat(fd, &sb) != -1 && sb.st_size > 0) {
58 content->reserve(sb.st_size);
59 }
60
Elliott Hughesf682b472015-02-06 12:19:48 -080061 char buf[BUFSIZ];
62 ssize_t n;
63 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], sizeof(buf)))) > 0) {
64 content->append(buf, n);
65 }
66 return (n == 0) ? true : false;
67}
68
Josh Gaoffabc962016-09-14 16:11:45 -070069bool ReadFileToString(const std::string& path, std::string* content, bool follow_symlinks) {
Elliott Hughesdec12b22015-02-02 17:31:27 -080070 content->clear();
71
Josh Gaoffabc962016-09-14 16:11:45 -070072 int flags = O_RDONLY | O_CLOEXEC | O_BINARY | (follow_symlinks ? 0 : O_NOFOLLOW);
Christopher Ferris48d08c22017-04-05 12:09:17 -070073 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags)));
Elliott Hughesdec12b22015-02-02 17:31:27 -080074 if (fd == -1) {
75 return false;
76 }
Christopher Ferris48d08c22017-04-05 12:09:17 -070077 return ReadFdToString(fd, content);
Elliott Hughesdec12b22015-02-02 17:31:27 -080078}
79
Dan Albertc007bc32015-03-16 10:08:46 -070080bool WriteStringToFd(const std::string& content, int fd) {
Elliott Hughesdec12b22015-02-02 17:31:27 -080081 const char* p = content.data();
82 size_t left = content.size();
83 while (left > 0) {
84 ssize_t n = TEMP_FAILURE_RETRY(write(fd, p, left));
85 if (n == -1) {
Elliott Hughesdec12b22015-02-02 17:31:27 -080086 return false;
87 }
88 p += n;
89 left -= n;
90 }
Elliott Hughesdec12b22015-02-02 17:31:27 -080091 return true;
92}
Elliott Hughes202f0242015-02-04 13:19:13 -080093
94static bool CleanUpAfterFailedWrite(const std::string& path) {
95 // Something went wrong. Let's not leave a corrupt file lying around.
96 int saved_errno = errno;
97 unlink(path.c_str());
98 errno = saved_errno;
99 return false;
100}
101
Elliott Hughes31fa09c2015-02-04 19:38:28 -0800102#if !defined(_WIN32)
Dan Albertc007bc32015-03-16 10:08:46 -0700103bool WriteStringToFile(const std::string& content, const std::string& path,
Josh Gaoffabc962016-09-14 16:11:45 -0700104 mode_t mode, uid_t owner, gid_t group,
105 bool follow_symlinks) {
106 int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY |
107 (follow_symlinks ? 0 : O_NOFOLLOW);
Christopher Ferris48d08c22017-04-05 12:09:17 -0700108 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode)));
Elliott Hughes202f0242015-02-04 13:19:13 -0800109 if (fd == -1) {
Elliott Hughese5dd71a2016-07-28 15:15:28 -0700110 PLOG(ERROR) << "android::WriteStringToFile open failed";
Elliott Hughes202f0242015-02-04 13:19:13 -0800111 return false;
112 }
Elliott Hughesf682b472015-02-06 12:19:48 -0800113
Dan Albertc007bc32015-03-16 10:08:46 -0700114 // We do an explicit fchmod here because we assume that the caller really
115 // meant what they said and doesn't want the umask-influenced mode.
Elliott Hughes9d1f5152015-02-17 10:16:04 -0800116 if (fchmod(fd, mode) == -1) {
Elliott Hughese5dd71a2016-07-28 15:15:28 -0700117 PLOG(ERROR) << "android::WriteStringToFile fchmod failed";
Elliott Hughes9d1f5152015-02-17 10:16:04 -0800118 return CleanUpAfterFailedWrite(path);
119 }
120 if (fchown(fd, owner, group) == -1) {
Elliott Hughese5dd71a2016-07-28 15:15:28 -0700121 PLOG(ERROR) << "android::WriteStringToFile fchown failed";
Elliott Hughes9d1f5152015-02-17 10:16:04 -0800122 return CleanUpAfterFailedWrite(path);
123 }
124 if (!WriteStringToFd(content, fd)) {
Elliott Hughese5dd71a2016-07-28 15:15:28 -0700125 PLOG(ERROR) << "android::WriteStringToFile write failed";
Elliott Hughes9d1f5152015-02-17 10:16:04 -0800126 return CleanUpAfterFailedWrite(path);
127 }
Elliott Hughes9d1f5152015-02-17 10:16:04 -0800128 return true;
Elliott Hughes202f0242015-02-04 13:19:13 -0800129}
Elliott Hughes31fa09c2015-02-04 19:38:28 -0800130#endif
Elliott Hughes202f0242015-02-04 13:19:13 -0800131
Josh Gaoffabc962016-09-14 16:11:45 -0700132bool WriteStringToFile(const std::string& content, const std::string& path,
133 bool follow_symlinks) {
134 int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY |
135 (follow_symlinks ? 0 : O_NOFOLLOW);
Elliott Hughes282ec452017-05-15 17:31:15 -0700136 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, 0666)));
Elliott Hughes202f0242015-02-04 13:19:13 -0800137 if (fd == -1) {
138 return false;
139 }
Christopher Ferris48d08c22017-04-05 12:09:17 -0700140 return WriteStringToFd(content, fd) || CleanUpAfterFailedWrite(path);
Elliott Hughes202f0242015-02-04 13:19:13 -0800141}
Dan Albertc007bc32015-03-16 10:08:46 -0700142
Elliott Hughes56085ed2015-04-24 21:57:16 -0700143bool ReadFully(int fd, void* data, size_t byte_count) {
144 uint8_t* p = reinterpret_cast<uint8_t*>(data);
145 size_t remaining = byte_count;
146 while (remaining > 0) {
147 ssize_t n = TEMP_FAILURE_RETRY(read(fd, p, remaining));
148 if (n <= 0) return false;
149 p += n;
150 remaining -= n;
151 }
152 return true;
153}
154
Adam Lesinskide117e42017-06-19 10:27:38 -0700155#if defined(_WIN32)
156// Windows implementation of pread. Note that this DOES move the file descriptors read position,
157// but it does so atomically.
158static ssize_t pread(int fd, void* data, size_t byte_count, off64_t offset) {
159 DWORD bytes_read;
160 OVERLAPPED overlapped;
161 memset(&overlapped, 0, sizeof(OVERLAPPED));
162 overlapped.Offset = static_cast<DWORD>(offset);
163 overlapped.OffsetHigh = static_cast<DWORD>(offset >> 32);
164 if (!ReadFile(reinterpret_cast<HANDLE>(_get_osfhandle(fd)), data, static_cast<DWORD>(byte_count),
165 &bytes_read, &overlapped)) {
166 // In case someone tries to read errno (since this is masquerading as a POSIX call)
167 errno = EIO;
168 return -1;
169 }
170 return static_cast<ssize_t>(bytes_read);
171}
172#endif
173
174bool ReadFullyAtOffset(int fd, void* data, size_t byte_count, off64_t offset) {
175 uint8_t* p = reinterpret_cast<uint8_t*>(data);
176 while (byte_count > 0) {
177 ssize_t n = TEMP_FAILURE_RETRY(pread(fd, p, byte_count, offset));
178 if (n <= 0) return false;
179 p += n;
180 byte_count -= n;
181 offset += n;
182 }
183 return true;
184}
185
Elliott Hughes56085ed2015-04-24 21:57:16 -0700186bool WriteFully(int fd, const void* data, size_t byte_count) {
187 const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
188 size_t remaining = byte_count;
189 while (remaining > 0) {
190 ssize_t n = TEMP_FAILURE_RETRY(write(fd, p, remaining));
191 if (n == -1) return false;
192 p += n;
193 remaining -= n;
194 }
195 return true;
196}
197
Yabin Cuib6e314a2016-01-29 17:25:54 -0800198bool RemoveFileIfExists(const std::string& path, std::string* err) {
199 struct stat st;
200#if defined(_WIN32)
liwugangc63cb072018-07-11 13:24:49 +0800201 // TODO: Windows version can't handle symbolic links correctly.
Yabin Cuib6e314a2016-01-29 17:25:54 -0800202 int result = stat(path.c_str(), &st);
203 bool file_type_removable = (result == 0 && S_ISREG(st.st_mode));
204#else
205 int result = lstat(path.c_str(), &st);
206 bool file_type_removable = (result == 0 && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)));
207#endif
liwugangc63cb072018-07-11 13:24:49 +0800208 if (result == -1) {
209 if (errno == ENOENT || errno == ENOTDIR) return true;
210 if (err != nullptr) *err = strerror(errno);
211 return false;
212 }
213
Yabin Cuib6e314a2016-01-29 17:25:54 -0800214 if (result == 0) {
215 if (!file_type_removable) {
216 if (err != nullptr) {
liwugangc63cb072018-07-11 13:24:49 +0800217 *err = "is not a regular file or symbolic link";
Yabin Cuib6e314a2016-01-29 17:25:54 -0800218 }
219 return false;
220 }
221 if (unlink(path.c_str()) == -1) {
222 if (err != nullptr) {
223 *err = strerror(errno);
224 }
225 return false;
226 }
227 }
228 return true;
229}
230
Elliott Hughesd3ff6e52016-08-23 15:53:45 -0700231#if !defined(_WIN32)
232bool Readlink(const std::string& path, std::string* result) {
233 result->clear();
234
235 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
236 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
237 // waste memory to just start there. We add 1 so that we can recognize
238 // whether it actually fit (rather than being truncated to 4095).
239 std::vector<char> buf(4095 + 1);
240 while (true) {
241 ssize_t size = readlink(path.c_str(), &buf[0], buf.size());
242 // Unrecoverable error?
243 if (size == -1) return false;
244 // It fit! (If size == buf.size(), it may have been truncated.)
245 if (static_cast<size_t>(size) < buf.size()) {
246 result->assign(&buf[0], size);
247 return true;
248 }
249 // Double our buffer and try again.
250 buf.resize(buf.size() * 2);
251 }
252}
253#endif
254
Dimitry Ivanov840b6012016-09-09 10:49:21 -0700255#if !defined(_WIN32)
256bool Realpath(const std::string& path, std::string* result) {
257 result->clear();
258
259 char* realpath_buf = realpath(path.c_str(), nullptr);
260 if (realpath_buf == nullptr) {
261 return false;
262 }
263 result->assign(realpath_buf);
264 free(realpath_buf);
265 return true;
266}
267#endif
268
Elliott Hughes82ff3152016-08-31 15:07:18 -0700269std::string GetExecutablePath() {
270#if defined(__linux__)
271 std::string path;
272 android::base::Readlink("/proc/self/exe", &path);
273 return path;
274#elif defined(__APPLE__)
Elliott Hughes82ff3152016-08-31 15:07:18 -0700275 char path[PATH_MAX + 1];
Josh Gao7307f092016-09-01 12:31:42 -0700276 uint32_t path_len = sizeof(path);
277 int rc = _NSGetExecutablePath(path, &path_len);
278 if (rc < 0) {
279 std::unique_ptr<char> path_buf(new char[path_len]);
280 _NSGetExecutablePath(path_buf.get(), &path_len);
281 return path_buf.get();
282 }
Elliott Hughes82ff3152016-08-31 15:07:18 -0700283 return path;
284#elif defined(_WIN32)
285 char path[PATH_MAX + 1];
286 DWORD result = GetModuleFileName(NULL, path, sizeof(path) - 1);
287 if (result == 0 || result == sizeof(path) - 1) return "";
288 path[PATH_MAX - 1] = 0;
289 return path;
290#else
291#error unknown OS
292#endif
293}
294
Colin Crossbb3a5152017-02-23 17:41:56 -0800295std::string GetExecutableDirectory() {
296 return Dirname(GetExecutablePath());
297}
Colin Cross58021d12017-02-23 21:23:05 -0800298
Colin Crossbb3a5152017-02-23 17:41:56 -0800299std::string Basename(const std::string& path) {
Colin Cross58021d12017-02-23 21:23:05 -0800300 // Copy path because basename may modify the string passed in.
301 std::string result(path);
302
303#if !defined(__BIONIC__)
304 // Use lock because basename() may write to a process global and return a
305 // pointer to that. Note that this locking strategy only works if all other
306 // callers to basename in the process also grab this same lock, but its
307 // better than nothing. Bionic's basename returns a thread-local buffer.
308 static std::mutex& basename_lock = *new std::mutex();
309 std::lock_guard<std::mutex> lock(basename_lock);
310#endif
311
312 // Note that if std::string uses copy-on-write strings, &str[0] will cause
313 // the copy to be made, so there is no chance of us accidentally writing to
314 // the storage for 'path'.
315 char* name = basename(&result[0]);
316
317 // In case basename returned a pointer to a process global, copy that string
318 // before leaving the lock.
319 result.assign(name);
320
321 return result;
322}
323
324std::string Dirname(const std::string& path) {
325 // Copy path because dirname may modify the string passed in.
326 std::string result(path);
327
328#if !defined(__BIONIC__)
329 // Use lock because dirname() may write to a process global and return a
330 // pointer to that. Note that this locking strategy only works if all other
331 // callers to dirname in the process also grab this same lock, but its
332 // better than nothing. Bionic's dirname returns a thread-local buffer.
333 static std::mutex& dirname_lock = *new std::mutex();
334 std::lock_guard<std::mutex> lock(dirname_lock);
335#endif
336
337 // Note that if std::string uses copy-on-write strings, &str[0] will cause
338 // the copy to be made, so there is no chance of us accidentally writing to
339 // the storage for 'path'.
340 char* parent = dirname(&result[0]);
341
342 // In case dirname returned a pointer to a process global, copy that string
343 // before leaving the lock.
344 result.assign(parent);
345
346 return result;
347}
348
Dan Albertc007bc32015-03-16 10:08:46 -0700349} // namespace base
350} // namespace android