blob: d6fe753d1704b9a07eda89c2d3a38e3708fdb94b [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>
Colin Cross2e732e22017-02-23 21:23:05 -080021#include <libgen.h>
Dan Albertaac6b7c2015-03-16 10:08:46 -070022#include <sys/stat.h>
23#include <sys/types.h>
Elliott Hughesa634a9a2016-08-23 15:53:45 -070024#include <unistd.h>
Dan Albertaac6b7c2015-03-16 10:08:46 -070025
Josh Gao58668ac2016-09-01 12:31:42 -070026#include <memory>
Colin Cross2e732e22017-02-23 21:23:05 -080027#include <mutex>
Dan Albertaac6b7c2015-03-16 10:08:46 -070028#include <string>
Elliott Hughesa634a9a2016-08-23 15:53:45 -070029#include <vector>
Dan Albertaac6b7c2015-03-16 10:08:46 -070030
Elliott Hughes7d9a4792016-07-28 15:15:28 -070031#include "android-base/logging.h"
Christopher Ferrisbf0929f2017-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 Hughesb6351622015-12-04 22:00:26 -080034#include "android-base/utf8.h"
Dan Albertaac6b7c2015-03-16 10:08:46 -070035
Elliott Hughes48f0eb52016-08-31 15:07:18 -070036#if defined(__APPLE__)
Josh Gao58668ac2016-09-01 12:31:42 -070037#include <mach-o/dyld.h>
Elliott Hughes48f0eb52016-08-31 15:07:18 -070038#endif
39#if defined(_WIN32)
40#include <windows.h>
Elliott Hughes62ecbaa2017-05-15 17:31:15 -070041#define O_CLOEXEC O_NOINHERIT
42#define O_NOFOLLOW 0
Elliott Hughes48f0eb52016-08-31 15:07:18 -070043#endif
44
Dan Albertaac6b7c2015-03-16 10:08:46 -070045namespace android {
46namespace base {
47
Elliott Hughes774d7f62015-11-11 18:02:29 +000048// Versions of standard library APIs that support UTF-8 strings.
49using namespace android::base::utf8;
50
Dan Albertaac6b7c2015-03-16 10:08:46 -070051bool ReadFdToString(int fd, std::string* content) {
52 content->clear();
53
Elliott Hughese9ab7ad2017-03-20 19:16:18 -070054 // Although original we had small files in mind, this code gets used for
55 // very large files too, where the std::string growth heuristics might not
56 // be suitable. https://code.google.com/p/android/issues/detail?id=258500.
57 struct stat sb;
58 if (fstat(fd, &sb) != -1 && sb.st_size > 0) {
59 content->reserve(sb.st_size);
60 }
61
Dan Albertaac6b7c2015-03-16 10:08:46 -070062 char buf[BUFSIZ];
63 ssize_t n;
64 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], sizeof(buf)))) > 0) {
65 content->append(buf, n);
66 }
67 return (n == 0) ? true : false;
68}
69
Josh Gao8e1f0d82016-09-14 16:11:45 -070070bool ReadFileToString(const std::string& path, std::string* content, bool follow_symlinks) {
Dan Albertaac6b7c2015-03-16 10:08:46 -070071 content->clear();
72
Josh Gao8e1f0d82016-09-14 16:11:45 -070073 int flags = O_RDONLY | O_CLOEXEC | O_BINARY | (follow_symlinks ? 0 : O_NOFOLLOW);
Christopher Ferrisbf0929f2017-04-05 12:09:17 -070074 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags)));
Dan Albertaac6b7c2015-03-16 10:08:46 -070075 if (fd == -1) {
76 return false;
77 }
Christopher Ferrisbf0929f2017-04-05 12:09:17 -070078 return ReadFdToString(fd, content);
Dan Albertaac6b7c2015-03-16 10:08:46 -070079}
80
81bool WriteStringToFd(const std::string& content, int fd) {
82 const char* p = content.data();
83 size_t left = content.size();
84 while (left > 0) {
85 ssize_t n = TEMP_FAILURE_RETRY(write(fd, p, left));
86 if (n == -1) {
87 return false;
88 }
89 p += n;
90 left -= n;
91 }
92 return true;
93}
94
95static bool CleanUpAfterFailedWrite(const std::string& path) {
96 // Something went wrong. Let's not leave a corrupt file lying around.
97 int saved_errno = errno;
98 unlink(path.c_str());
99 errno = saved_errno;
100 return false;
101}
102
103#if !defined(_WIN32)
104bool WriteStringToFile(const std::string& content, const std::string& path,
Josh Gao8e1f0d82016-09-14 16:11:45 -0700105 mode_t mode, uid_t owner, gid_t group,
106 bool follow_symlinks) {
107 int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY |
108 (follow_symlinks ? 0 : O_NOFOLLOW);
Christopher Ferrisbf0929f2017-04-05 12:09:17 -0700109 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode)));
Dan Albertaac6b7c2015-03-16 10:08:46 -0700110 if (fd == -1) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700111 PLOG(ERROR) << "android::WriteStringToFile open failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700112 return false;
113 }
114
115 // We do an explicit fchmod here because we assume that the caller really
116 // meant what they said and doesn't want the umask-influenced mode.
117 if (fchmod(fd, mode) == -1) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700118 PLOG(ERROR) << "android::WriteStringToFile fchmod failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700119 return CleanUpAfterFailedWrite(path);
120 }
121 if (fchown(fd, owner, group) == -1) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700122 PLOG(ERROR) << "android::WriteStringToFile fchown failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700123 return CleanUpAfterFailedWrite(path);
124 }
125 if (!WriteStringToFd(content, fd)) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700126 PLOG(ERROR) << "android::WriteStringToFile write failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700127 return CleanUpAfterFailedWrite(path);
128 }
Dan Albertaac6b7c2015-03-16 10:08:46 -0700129 return true;
130}
131#endif
132
Josh Gao8e1f0d82016-09-14 16:11:45 -0700133bool WriteStringToFile(const std::string& content, const std::string& path,
134 bool follow_symlinks) {
135 int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY |
136 (follow_symlinks ? 0 : O_NOFOLLOW);
Elliott Hughes62ecbaa2017-05-15 17:31:15 -0700137 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, 0666)));
Dan Albertaac6b7c2015-03-16 10:08:46 -0700138 if (fd == -1) {
139 return false;
140 }
Christopher Ferrisbf0929f2017-04-05 12:09:17 -0700141 return WriteStringToFd(content, fd) || CleanUpAfterFailedWrite(path);
Dan Albertaac6b7c2015-03-16 10:08:46 -0700142}
143
Elliott Hughes20abc872015-04-24 21:57:16 -0700144bool ReadFully(int fd, void* data, size_t byte_count) {
145 uint8_t* p = reinterpret_cast<uint8_t*>(data);
146 size_t remaining = byte_count;
147 while (remaining > 0) {
148 ssize_t n = TEMP_FAILURE_RETRY(read(fd, p, remaining));
149 if (n <= 0) return false;
150 p += n;
151 remaining -= n;
152 }
153 return true;
154}
155
Adam Lesinski6d6f9b32017-06-19 10:27:38 -0700156#if defined(_WIN32)
157// Windows implementation of pread. Note that this DOES move the file descriptors read position,
158// but it does so atomically.
159static ssize_t pread(int fd, void* data, size_t byte_count, off64_t offset) {
160 DWORD bytes_read;
161 OVERLAPPED overlapped;
162 memset(&overlapped, 0, sizeof(OVERLAPPED));
163 overlapped.Offset = static_cast<DWORD>(offset);
164 overlapped.OffsetHigh = static_cast<DWORD>(offset >> 32);
165 if (!ReadFile(reinterpret_cast<HANDLE>(_get_osfhandle(fd)), data, static_cast<DWORD>(byte_count),
166 &bytes_read, &overlapped)) {
167 // In case someone tries to read errno (since this is masquerading as a POSIX call)
168 errno = EIO;
169 return -1;
170 }
171 return static_cast<ssize_t>(bytes_read);
172}
173#endif
174
175bool ReadFullyAtOffset(int fd, void* data, size_t byte_count, off64_t offset) {
176 uint8_t* p = reinterpret_cast<uint8_t*>(data);
177 while (byte_count > 0) {
178 ssize_t n = TEMP_FAILURE_RETRY(pread(fd, p, byte_count, offset));
179 if (n <= 0) return false;
180 p += n;
181 byte_count -= n;
182 offset += n;
183 }
184 return true;
185}
186
Elliott Hughes20abc872015-04-24 21:57:16 -0700187bool WriteFully(int fd, const void* data, size_t byte_count) {
188 const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
189 size_t remaining = byte_count;
190 while (remaining > 0) {
191 ssize_t n = TEMP_FAILURE_RETRY(write(fd, p, remaining));
192 if (n == -1) return false;
193 p += n;
194 remaining -= n;
195 }
196 return true;
197}
198
Yabin Cui8f6a5a02016-01-29 17:25:54 -0800199bool RemoveFileIfExists(const std::string& path, std::string* err) {
200 struct stat st;
201#if defined(_WIN32)
liwugang78cea682018-07-11 13:24:49 +0800202 // TODO: Windows version can't handle symbolic links correctly.
Yabin Cui8f6a5a02016-01-29 17:25:54 -0800203 int result = stat(path.c_str(), &st);
204 bool file_type_removable = (result == 0 && S_ISREG(st.st_mode));
205#else
206 int result = lstat(path.c_str(), &st);
207 bool file_type_removable = (result == 0 && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)));
208#endif
liwugang78cea682018-07-11 13:24:49 +0800209 if (result == -1) {
210 if (errno == ENOENT || errno == ENOTDIR) return true;
211 if (err != nullptr) *err = strerror(errno);
212 return false;
213 }
214
Yabin Cui8f6a5a02016-01-29 17:25:54 -0800215 if (result == 0) {
216 if (!file_type_removable) {
217 if (err != nullptr) {
liwugang78cea682018-07-11 13:24:49 +0800218 *err = "is not a regular file or symbolic link";
Yabin Cui8f6a5a02016-01-29 17:25:54 -0800219 }
220 return false;
221 }
222 if (unlink(path.c_str()) == -1) {
223 if (err != nullptr) {
224 *err = strerror(errno);
225 }
226 return false;
227 }
228 }
229 return true;
230}
231
Elliott Hughesa634a9a2016-08-23 15:53:45 -0700232#if !defined(_WIN32)
233bool Readlink(const std::string& path, std::string* result) {
234 result->clear();
235
236 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
237 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
238 // waste memory to just start there. We add 1 so that we can recognize
239 // whether it actually fit (rather than being truncated to 4095).
240 std::vector<char> buf(4095 + 1);
241 while (true) {
242 ssize_t size = readlink(path.c_str(), &buf[0], buf.size());
243 // Unrecoverable error?
244 if (size == -1) return false;
245 // It fit! (If size == buf.size(), it may have been truncated.)
246 if (static_cast<size_t>(size) < buf.size()) {
247 result->assign(&buf[0], size);
248 return true;
249 }
250 // Double our buffer and try again.
251 buf.resize(buf.size() * 2);
252 }
253}
254#endif
255
Dimitry Ivanov4edc04f2016-09-09 10:49:21 -0700256#if !defined(_WIN32)
257bool Realpath(const std::string& path, std::string* result) {
258 result->clear();
259
260 char* realpath_buf = realpath(path.c_str(), nullptr);
261 if (realpath_buf == nullptr) {
262 return false;
263 }
264 result->assign(realpath_buf);
265 free(realpath_buf);
266 return true;
267}
268#endif
269
Elliott Hughes48f0eb52016-08-31 15:07:18 -0700270std::string GetExecutablePath() {
271#if defined(__linux__)
272 std::string path;
273 android::base::Readlink("/proc/self/exe", &path);
274 return path;
275#elif defined(__APPLE__)
Elliott Hughes48f0eb52016-08-31 15:07:18 -0700276 char path[PATH_MAX + 1];
Josh Gao58668ac2016-09-01 12:31:42 -0700277 uint32_t path_len = sizeof(path);
278 int rc = _NSGetExecutablePath(path, &path_len);
279 if (rc < 0) {
280 std::unique_ptr<char> path_buf(new char[path_len]);
281 _NSGetExecutablePath(path_buf.get(), &path_len);
282 return path_buf.get();
283 }
Elliott Hughes48f0eb52016-08-31 15:07:18 -0700284 return path;
285#elif defined(_WIN32)
286 char path[PATH_MAX + 1];
287 DWORD result = GetModuleFileName(NULL, path, sizeof(path) - 1);
288 if (result == 0 || result == sizeof(path) - 1) return "";
289 path[PATH_MAX - 1] = 0;
290 return path;
291#else
292#error unknown OS
293#endif
294}
295
Colin Cross2909be02017-02-23 17:41:56 -0800296std::string GetExecutableDirectory() {
297 return Dirname(GetExecutablePath());
298}
Colin Cross2e732e22017-02-23 21:23:05 -0800299
Colin Cross2909be02017-02-23 17:41:56 -0800300std::string Basename(const std::string& path) {
Colin Cross2e732e22017-02-23 21:23:05 -0800301 // Copy path because basename may modify the string passed in.
302 std::string result(path);
303
304#if !defined(__BIONIC__)
305 // Use lock because basename() may write to a process global and return a
306 // pointer to that. Note that this locking strategy only works if all other
307 // callers to basename in the process also grab this same lock, but its
308 // better than nothing. Bionic's basename returns a thread-local buffer.
309 static std::mutex& basename_lock = *new std::mutex();
310 std::lock_guard<std::mutex> lock(basename_lock);
311#endif
312
313 // Note that if std::string uses copy-on-write strings, &str[0] will cause
314 // the copy to be made, so there is no chance of us accidentally writing to
315 // the storage for 'path'.
316 char* name = basename(&result[0]);
317
318 // In case basename returned a pointer to a process global, copy that string
319 // before leaving the lock.
320 result.assign(name);
321
322 return result;
323}
324
325std::string Dirname(const std::string& path) {
326 // Copy path because dirname may modify the string passed in.
327 std::string result(path);
328
329#if !defined(__BIONIC__)
330 // Use lock because dirname() may write to a process global and return a
331 // pointer to that. Note that this locking strategy only works if all other
332 // callers to dirname in the process also grab this same lock, but its
333 // better than nothing. Bionic's dirname returns a thread-local buffer.
334 static std::mutex& dirname_lock = *new std::mutex();
335 std::lock_guard<std::mutex> lock(dirname_lock);
336#endif
337
338 // Note that if std::string uses copy-on-write strings, &str[0] will cause
339 // the copy to be made, so there is no chance of us accidentally writing to
340 // the storage for 'path'.
341 char* parent = dirname(&result[0]);
342
343 // In case dirname returned a pointer to a process global, copy that string
344 // before leaving the lock.
345 result.assign(parent);
346
347 return result;
348}
349
Dan Albertaac6b7c2015-03-16 10:08:46 -0700350} // namespace base
351} // namespace android