blob: 7fbebc5385ef5eede72eede7c7d22fb17262e0f7 [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 Albert5f770222015-03-26 23:33:28 -070035#include "utils/Compat.h"
Dan Albertaac6b7c2015-03-16 10:08:46 -070036
Elliott Hughes48f0eb52016-08-31 15:07:18 -070037#if defined(__APPLE__)
Josh Gao58668ac2016-09-01 12:31:42 -070038#include <mach-o/dyld.h>
Elliott Hughes48f0eb52016-08-31 15:07:18 -070039#endif
40#if defined(_WIN32)
41#include <windows.h>
42#endif
43
Dan Albertaac6b7c2015-03-16 10:08:46 -070044namespace android {
45namespace base {
46
Elliott Hughes774d7f62015-11-11 18:02:29 +000047// Versions of standard library APIs that support UTF-8 strings.
48using namespace android::base::utf8;
49
Dan Albertaac6b7c2015-03-16 10:08:46 -070050bool ReadFdToString(int fd, std::string* content) {
51 content->clear();
52
Elliott Hughese9ab7ad2017-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
Dan Albertaac6b7c2015-03-16 10:08:46 -070061 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 Gao8e1f0d82016-09-14 16:11:45 -070069bool ReadFileToString(const std::string& path, std::string* content, bool follow_symlinks) {
Dan Albertaac6b7c2015-03-16 10:08:46 -070070 content->clear();
71
Josh Gao8e1f0d82016-09-14 16:11:45 -070072 int flags = O_RDONLY | O_CLOEXEC | O_BINARY | (follow_symlinks ? 0 : O_NOFOLLOW);
Christopher Ferrisbf0929f2017-04-05 12:09:17 -070073 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags)));
Dan Albertaac6b7c2015-03-16 10:08:46 -070074 if (fd == -1) {
75 return false;
76 }
Christopher Ferrisbf0929f2017-04-05 12:09:17 -070077 return ReadFdToString(fd, content);
Dan Albertaac6b7c2015-03-16 10:08:46 -070078}
79
80bool WriteStringToFd(const std::string& content, int fd) {
81 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) {
86 return false;
87 }
88 p += n;
89 left -= n;
90 }
91 return true;
92}
93
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
102#if !defined(_WIN32)
103bool WriteStringToFile(const std::string& content, const std::string& path,
Josh Gao8e1f0d82016-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 Ferrisbf0929f2017-04-05 12:09:17 -0700108 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode)));
Dan Albertaac6b7c2015-03-16 10:08:46 -0700109 if (fd == -1) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700110 PLOG(ERROR) << "android::WriteStringToFile open failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700111 return false;
112 }
113
114 // 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.
116 if (fchmod(fd, mode) == -1) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700117 PLOG(ERROR) << "android::WriteStringToFile fchmod failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700118 return CleanUpAfterFailedWrite(path);
119 }
120 if (fchown(fd, owner, group) == -1) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700121 PLOG(ERROR) << "android::WriteStringToFile fchown failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700122 return CleanUpAfterFailedWrite(path);
123 }
124 if (!WriteStringToFd(content, fd)) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700125 PLOG(ERROR) << "android::WriteStringToFile write failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700126 return CleanUpAfterFailedWrite(path);
127 }
Dan Albertaac6b7c2015-03-16 10:08:46 -0700128 return true;
129}
130#endif
131
Josh Gao8e1f0d82016-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 Ferrisbf0929f2017-04-05 12:09:17 -0700136 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, DEFFILEMODE)));
Dan Albertaac6b7c2015-03-16 10:08:46 -0700137 if (fd == -1) {
138 return false;
139 }
Christopher Ferrisbf0929f2017-04-05 12:09:17 -0700140 return WriteStringToFd(content, fd) || CleanUpAfterFailedWrite(path);
Dan Albertaac6b7c2015-03-16 10:08:46 -0700141}
142
Elliott Hughes20abc872015-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 Cui8f6a5a02016-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 Hughesa634a9a2016-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 Ivanov4edc04f2016-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 Hughes48f0eb52016-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 Hughes48f0eb52016-08-31 15:07:18 -0700238 char path[PATH_MAX + 1];
Josh Gao58668ac2016-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 Hughes48f0eb52016-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 Cross2909be02017-02-23 17:41:56 -0800258std::string GetExecutableDirectory() {
259 return Dirname(GetExecutablePath());
260}
Colin Cross2e732e22017-02-23 21:23:05 -0800261
Colin Cross2909be02017-02-23 17:41:56 -0800262std::string Basename(const std::string& path) {
Colin Cross2e732e22017-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 Albertaac6b7c2015-03-16 10:08:46 -0700312} // namespace base
313} // namespace android