blob: d4e58942c1b1fd0a4dfebf8ecb2ce5f9a383a33f [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 Hughesb6351622015-12-04 22:00:26 -080031#include "android-base/macros.h" // For TEMP_FAILURE_RETRY on Darwin.
Elliott Hughes7d9a4792016-07-28 15:15:28 -070032#include "android-base/logging.h"
Elliott Hughesb6351622015-12-04 22:00:26 -080033#include "android-base/utf8.h"
Dan Albert5f770222015-03-26 23:33:28 -070034#include "utils/Compat.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>
41#endif
42
Dan Albertaac6b7c2015-03-16 10:08:46 -070043namespace android {
44namespace base {
45
Elliott Hughes774d7f62015-11-11 18:02:29 +000046// Versions of standard library APIs that support UTF-8 strings.
47using namespace android::base::utf8;
48
Dan Albertaac6b7c2015-03-16 10:08:46 -070049bool ReadFdToString(int fd, std::string* content) {
50 content->clear();
51
Elliott Hughese9ab7ad2017-03-20 19:16:18 -070052 // Although original we had small files in mind, this code gets used for
53 // very large files too, where the std::string growth heuristics might not
54 // be suitable. https://code.google.com/p/android/issues/detail?id=258500.
55 struct stat sb;
56 if (fstat(fd, &sb) != -1 && sb.st_size > 0) {
57 content->reserve(sb.st_size);
58 }
59
Dan Albertaac6b7c2015-03-16 10:08:46 -070060 char buf[BUFSIZ];
61 ssize_t n;
62 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], sizeof(buf)))) > 0) {
63 content->append(buf, n);
64 }
65 return (n == 0) ? true : false;
66}
67
Josh Gao8e1f0d82016-09-14 16:11:45 -070068bool ReadFileToString(const std::string& path, std::string* content, bool follow_symlinks) {
Dan Albertaac6b7c2015-03-16 10:08:46 -070069 content->clear();
70
Josh Gao8e1f0d82016-09-14 16:11:45 -070071 int flags = O_RDONLY | O_CLOEXEC | O_BINARY | (follow_symlinks ? 0 : O_NOFOLLOW);
72 int fd = TEMP_FAILURE_RETRY(open(path.c_str(), flags));
Dan Albertaac6b7c2015-03-16 10:08:46 -070073 if (fd == -1) {
74 return false;
75 }
76 bool result = ReadFdToString(fd, content);
Nick Kralevich82921302015-05-20 08:59:21 -070077 close(fd);
Dan Albertaac6b7c2015-03-16 10:08:46 -070078 return result;
79}
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);
Elliott Hughesd5f8ae62015-09-01 13:35:44 -0700109 int 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 }
Nick Kralevich82921302015-05-20 08:59:21 -0700129 close(fd);
Dan Albertaac6b7c2015-03-16 10:08:46 -0700130 return true;
131}
132#endif
133
Josh Gao8e1f0d82016-09-14 16:11:45 -0700134bool WriteStringToFile(const std::string& content, const std::string& path,
135 bool follow_symlinks) {
136 int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY |
137 (follow_symlinks ? 0 : O_NOFOLLOW);
Elliott Hughesd5f8ae62015-09-01 13:35:44 -0700138 int fd = TEMP_FAILURE_RETRY(open(path.c_str(), flags, DEFFILEMODE));
Dan Albertaac6b7c2015-03-16 10:08:46 -0700139 if (fd == -1) {
140 return false;
141 }
142
143 bool result = WriteStringToFd(content, fd);
Nick Kralevich82921302015-05-20 08:59:21 -0700144 close(fd);
Dan Albertaac6b7c2015-03-16 10:08:46 -0700145 return result || CleanUpAfterFailedWrite(path);
146}
147
Elliott Hughes20abc872015-04-24 21:57:16 -0700148bool ReadFully(int fd, void* data, size_t byte_count) {
149 uint8_t* p = reinterpret_cast<uint8_t*>(data);
150 size_t remaining = byte_count;
151 while (remaining > 0) {
152 ssize_t n = TEMP_FAILURE_RETRY(read(fd, p, remaining));
153 if (n <= 0) return false;
154 p += n;
155 remaining -= n;
156 }
157 return true;
158}
159
160bool WriteFully(int fd, const void* data, size_t byte_count) {
161 const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
162 size_t remaining = byte_count;
163 while (remaining > 0) {
164 ssize_t n = TEMP_FAILURE_RETRY(write(fd, p, remaining));
165 if (n == -1) return false;
166 p += n;
167 remaining -= n;
168 }
169 return true;
170}
171
Yabin Cui8f6a5a02016-01-29 17:25:54 -0800172bool RemoveFileIfExists(const std::string& path, std::string* err) {
173 struct stat st;
174#if defined(_WIN32)
175 //TODO: Windows version can't handle symbol link correctly.
176 int result = stat(path.c_str(), &st);
177 bool file_type_removable = (result == 0 && S_ISREG(st.st_mode));
178#else
179 int result = lstat(path.c_str(), &st);
180 bool file_type_removable = (result == 0 && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)));
181#endif
182 if (result == 0) {
183 if (!file_type_removable) {
184 if (err != nullptr) {
185 *err = "is not a regular or symbol link file";
186 }
187 return false;
188 }
189 if (unlink(path.c_str()) == -1) {
190 if (err != nullptr) {
191 *err = strerror(errno);
192 }
193 return false;
194 }
195 }
196 return true;
197}
198
Elliott Hughesa634a9a2016-08-23 15:53:45 -0700199#if !defined(_WIN32)
200bool Readlink(const std::string& path, std::string* result) {
201 result->clear();
202
203 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
204 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
205 // waste memory to just start there. We add 1 so that we can recognize
206 // whether it actually fit (rather than being truncated to 4095).
207 std::vector<char> buf(4095 + 1);
208 while (true) {
209 ssize_t size = readlink(path.c_str(), &buf[0], buf.size());
210 // Unrecoverable error?
211 if (size == -1) return false;
212 // It fit! (If size == buf.size(), it may have been truncated.)
213 if (static_cast<size_t>(size) < buf.size()) {
214 result->assign(&buf[0], size);
215 return true;
216 }
217 // Double our buffer and try again.
218 buf.resize(buf.size() * 2);
219 }
220}
221#endif
222
Dimitry Ivanov4edc04f2016-09-09 10:49:21 -0700223#if !defined(_WIN32)
224bool Realpath(const std::string& path, std::string* result) {
225 result->clear();
226
227 char* realpath_buf = realpath(path.c_str(), nullptr);
228 if (realpath_buf == nullptr) {
229 return false;
230 }
231 result->assign(realpath_buf);
232 free(realpath_buf);
233 return true;
234}
235#endif
236
Elliott Hughes48f0eb52016-08-31 15:07:18 -0700237std::string GetExecutablePath() {
238#if defined(__linux__)
239 std::string path;
240 android::base::Readlink("/proc/self/exe", &path);
241 return path;
242#elif defined(__APPLE__)
Elliott Hughes48f0eb52016-08-31 15:07:18 -0700243 char path[PATH_MAX + 1];
Josh Gao58668ac2016-09-01 12:31:42 -0700244 uint32_t path_len = sizeof(path);
245 int rc = _NSGetExecutablePath(path, &path_len);
246 if (rc < 0) {
247 std::unique_ptr<char> path_buf(new char[path_len]);
248 _NSGetExecutablePath(path_buf.get(), &path_len);
249 return path_buf.get();
250 }
Elliott Hughes48f0eb52016-08-31 15:07:18 -0700251 return path;
252#elif defined(_WIN32)
253 char path[PATH_MAX + 1];
254 DWORD result = GetModuleFileName(NULL, path, sizeof(path) - 1);
255 if (result == 0 || result == sizeof(path) - 1) return "";
256 path[PATH_MAX - 1] = 0;
257 return path;
258#else
259#error unknown OS
260#endif
261}
262
Colin Cross2909be02017-02-23 17:41:56 -0800263std::string GetExecutableDirectory() {
264 return Dirname(GetExecutablePath());
265}
Colin Cross2e732e22017-02-23 21:23:05 -0800266
Colin Cross2909be02017-02-23 17:41:56 -0800267std::string Basename(const std::string& path) {
Colin Cross2e732e22017-02-23 21:23:05 -0800268 // Copy path because basename may modify the string passed in.
269 std::string result(path);
270
271#if !defined(__BIONIC__)
272 // Use lock because basename() may write to a process global and return a
273 // pointer to that. Note that this locking strategy only works if all other
274 // callers to basename in the process also grab this same lock, but its
275 // better than nothing. Bionic's basename returns a thread-local buffer.
276 static std::mutex& basename_lock = *new std::mutex();
277 std::lock_guard<std::mutex> lock(basename_lock);
278#endif
279
280 // Note that if std::string uses copy-on-write strings, &str[0] will cause
281 // the copy to be made, so there is no chance of us accidentally writing to
282 // the storage for 'path'.
283 char* name = basename(&result[0]);
284
285 // In case basename returned a pointer to a process global, copy that string
286 // before leaving the lock.
287 result.assign(name);
288
289 return result;
290}
291
292std::string Dirname(const std::string& path) {
293 // Copy path because dirname may modify the string passed in.
294 std::string result(path);
295
296#if !defined(__BIONIC__)
297 // Use lock because dirname() may write to a process global and return a
298 // pointer to that. Note that this locking strategy only works if all other
299 // callers to dirname in the process also grab this same lock, but its
300 // better than nothing. Bionic's dirname returns a thread-local buffer.
301 static std::mutex& dirname_lock = *new std::mutex();
302 std::lock_guard<std::mutex> lock(dirname_lock);
303#endif
304
305 // Note that if std::string uses copy-on-write strings, &str[0] will cause
306 // the copy to be made, so there is no chance of us accidentally writing to
307 // the storage for 'path'.
308 char* parent = dirname(&result[0]);
309
310 // In case dirname returned a pointer to a process global, copy that string
311 // before leaving the lock.
312 result.assign(parent);
313
314 return result;
315}
316
Dan Albertaac6b7c2015-03-16 10:08:46 -0700317} // namespace base
318} // namespace android