blob: 7fbebc5385ef5eede72eede7c7d22fb17262e0f7 [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 Albert94d13602015-03-26 23:33:28 -070035#include "utils/Compat.h"
Dan Albertc007bc32015-03-16 10:08:46 -070036
Elliott Hughes82ff3152016-08-31 15:07:18 -070037#if defined(__APPLE__)
Josh Gao7307f092016-09-01 12:31:42 -070038#include <mach-o/dyld.h>
Elliott Hughes82ff3152016-08-31 15:07:18 -070039#endif
40#if defined(_WIN32)
41#include <windows.h>
42#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);
Christopher Ferris48d08c22017-04-05 12:09:17 -0700136 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, DEFFILEMODE)));
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
155bool WriteFully(int fd, const void* data, size_t byte_count) {
156 const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
157 size_t remaining = byte_count;
158 while (remaining > 0) {
159 ssize_t n = TEMP_FAILURE_RETRY(write(fd, p, remaining));
160 if (n == -1) return false;
161 p += n;
162 remaining -= n;
163 }
164 return true;
165}
166
Yabin Cuib6e314a2016-01-29 17:25:54 -0800167bool RemoveFileIfExists(const std::string& path, std::string* err) {
168 struct stat st;
169#if defined(_WIN32)
170 //TODO: Windows version can't handle symbol link correctly.
171 int result = stat(path.c_str(), &st);
172 bool file_type_removable = (result == 0 && S_ISREG(st.st_mode));
173#else
174 int result = lstat(path.c_str(), &st);
175 bool file_type_removable = (result == 0 && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)));
176#endif
177 if (result == 0) {
178 if (!file_type_removable) {
179 if (err != nullptr) {
180 *err = "is not a regular or symbol link file";
181 }
182 return false;
183 }
184 if (unlink(path.c_str()) == -1) {
185 if (err != nullptr) {
186 *err = strerror(errno);
187 }
188 return false;
189 }
190 }
191 return true;
192}
193
Elliott Hughesd3ff6e52016-08-23 15:53:45 -0700194#if !defined(_WIN32)
195bool Readlink(const std::string& path, std::string* result) {
196 result->clear();
197
198 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
199 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
200 // waste memory to just start there. We add 1 so that we can recognize
201 // whether it actually fit (rather than being truncated to 4095).
202 std::vector<char> buf(4095 + 1);
203 while (true) {
204 ssize_t size = readlink(path.c_str(), &buf[0], buf.size());
205 // Unrecoverable error?
206 if (size == -1) return false;
207 // It fit! (If size == buf.size(), it may have been truncated.)
208 if (static_cast<size_t>(size) < buf.size()) {
209 result->assign(&buf[0], size);
210 return true;
211 }
212 // Double our buffer and try again.
213 buf.resize(buf.size() * 2);
214 }
215}
216#endif
217
Dimitry Ivanov840b6012016-09-09 10:49:21 -0700218#if !defined(_WIN32)
219bool Realpath(const std::string& path, std::string* result) {
220 result->clear();
221
222 char* realpath_buf = realpath(path.c_str(), nullptr);
223 if (realpath_buf == nullptr) {
224 return false;
225 }
226 result->assign(realpath_buf);
227 free(realpath_buf);
228 return true;
229}
230#endif
231
Elliott Hughes82ff3152016-08-31 15:07:18 -0700232std::string GetExecutablePath() {
233#if defined(__linux__)
234 std::string path;
235 android::base::Readlink("/proc/self/exe", &path);
236 return path;
237#elif defined(__APPLE__)
Elliott Hughes82ff3152016-08-31 15:07:18 -0700238 char path[PATH_MAX + 1];
Josh Gao7307f092016-09-01 12:31:42 -0700239 uint32_t path_len = sizeof(path);
240 int rc = _NSGetExecutablePath(path, &path_len);
241 if (rc < 0) {
242 std::unique_ptr<char> path_buf(new char[path_len]);
243 _NSGetExecutablePath(path_buf.get(), &path_len);
244 return path_buf.get();
245 }
Elliott Hughes82ff3152016-08-31 15:07:18 -0700246 return path;
247#elif defined(_WIN32)
248 char path[PATH_MAX + 1];
249 DWORD result = GetModuleFileName(NULL, path, sizeof(path) - 1);
250 if (result == 0 || result == sizeof(path) - 1) return "";
251 path[PATH_MAX - 1] = 0;
252 return path;
253#else
254#error unknown OS
255#endif
256}
257
Colin Crossbb3a5152017-02-23 17:41:56 -0800258std::string GetExecutableDirectory() {
259 return Dirname(GetExecutablePath());
260}
Colin Cross58021d12017-02-23 21:23:05 -0800261
Colin Crossbb3a5152017-02-23 17:41:56 -0800262std::string Basename(const std::string& path) {
Colin Cross58021d12017-02-23 21:23:05 -0800263 // Copy path because basename may modify the string passed in.
264 std::string result(path);
265
266#if !defined(__BIONIC__)
267 // Use lock because basename() may write to a process global and return a
268 // pointer to that. Note that this locking strategy only works if all other
269 // callers to basename in the process also grab this same lock, but its
270 // better than nothing. Bionic's basename returns a thread-local buffer.
271 static std::mutex& basename_lock = *new std::mutex();
272 std::lock_guard<std::mutex> lock(basename_lock);
273#endif
274
275 // Note that if std::string uses copy-on-write strings, &str[0] will cause
276 // the copy to be made, so there is no chance of us accidentally writing to
277 // the storage for 'path'.
278 char* name = basename(&result[0]);
279
280 // In case basename returned a pointer to a process global, copy that string
281 // before leaving the lock.
282 result.assign(name);
283
284 return result;
285}
286
287std::string Dirname(const std::string& path) {
288 // Copy path because dirname may modify the string passed in.
289 std::string result(path);
290
291#if !defined(__BIONIC__)
292 // Use lock because dirname() may write to a process global and return a
293 // pointer to that. Note that this locking strategy only works if all other
294 // callers to dirname in the process also grab this same lock, but its
295 // better than nothing. Bionic's dirname returns a thread-local buffer.
296 static std::mutex& dirname_lock = *new std::mutex();
297 std::lock_guard<std::mutex> lock(dirname_lock);
298#endif
299
300 // Note that if std::string uses copy-on-write strings, &str[0] will cause
301 // the copy to be made, so there is no chance of us accidentally writing to
302 // the storage for 'path'.
303 char* parent = dirname(&result[0]);
304
305 // In case dirname returned a pointer to a process global, copy that string
306 // before leaving the lock.
307 result.assign(parent);
308
309 return result;
310}
311
Dan Albertc007bc32015-03-16 10:08:46 -0700312} // namespace base
313} // namespace android