blob: 81b04d74e0223a03fb42cec6e502ccac4a9d861a [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
52 char buf[BUFSIZ];
53 ssize_t n;
54 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], sizeof(buf)))) > 0) {
55 content->append(buf, n);
56 }
57 return (n == 0) ? true : false;
58}
59
Josh Gao8e1f0d82016-09-14 16:11:45 -070060bool ReadFileToString(const std::string& path, std::string* content, bool follow_symlinks) {
Dan Albertaac6b7c2015-03-16 10:08:46 -070061 content->clear();
62
Josh Gao8e1f0d82016-09-14 16:11:45 -070063 int flags = O_RDONLY | O_CLOEXEC | O_BINARY | (follow_symlinks ? 0 : O_NOFOLLOW);
64 int fd = TEMP_FAILURE_RETRY(open(path.c_str(), flags));
Dan Albertaac6b7c2015-03-16 10:08:46 -070065 if (fd == -1) {
66 return false;
67 }
68 bool result = ReadFdToString(fd, content);
Nick Kralevich82921302015-05-20 08:59:21 -070069 close(fd);
Dan Albertaac6b7c2015-03-16 10:08:46 -070070 return result;
71}
72
73bool WriteStringToFd(const std::string& content, int fd) {
74 const char* p = content.data();
75 size_t left = content.size();
76 while (left > 0) {
77 ssize_t n = TEMP_FAILURE_RETRY(write(fd, p, left));
78 if (n == -1) {
79 return false;
80 }
81 p += n;
82 left -= n;
83 }
84 return true;
85}
86
87static bool CleanUpAfterFailedWrite(const std::string& path) {
88 // Something went wrong. Let's not leave a corrupt file lying around.
89 int saved_errno = errno;
90 unlink(path.c_str());
91 errno = saved_errno;
92 return false;
93}
94
95#if !defined(_WIN32)
96bool WriteStringToFile(const std::string& content, const std::string& path,
Josh Gao8e1f0d82016-09-14 16:11:45 -070097 mode_t mode, uid_t owner, gid_t group,
98 bool follow_symlinks) {
99 int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY |
100 (follow_symlinks ? 0 : O_NOFOLLOW);
Elliott Hughesd5f8ae62015-09-01 13:35:44 -0700101 int fd = TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode));
Dan Albertaac6b7c2015-03-16 10:08:46 -0700102 if (fd == -1) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700103 PLOG(ERROR) << "android::WriteStringToFile open failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700104 return false;
105 }
106
107 // We do an explicit fchmod here because we assume that the caller really
108 // meant what they said and doesn't want the umask-influenced mode.
109 if (fchmod(fd, mode) == -1) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700110 PLOG(ERROR) << "android::WriteStringToFile fchmod failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700111 return CleanUpAfterFailedWrite(path);
112 }
113 if (fchown(fd, owner, group) == -1) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700114 PLOG(ERROR) << "android::WriteStringToFile fchown failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700115 return CleanUpAfterFailedWrite(path);
116 }
117 if (!WriteStringToFd(content, fd)) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700118 PLOG(ERROR) << "android::WriteStringToFile write failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700119 return CleanUpAfterFailedWrite(path);
120 }
Nick Kralevich82921302015-05-20 08:59:21 -0700121 close(fd);
Dan Albertaac6b7c2015-03-16 10:08:46 -0700122 return true;
123}
124#endif
125
Josh Gao8e1f0d82016-09-14 16:11:45 -0700126bool WriteStringToFile(const std::string& content, const std::string& path,
127 bool follow_symlinks) {
128 int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY |
129 (follow_symlinks ? 0 : O_NOFOLLOW);
Elliott Hughesd5f8ae62015-09-01 13:35:44 -0700130 int fd = TEMP_FAILURE_RETRY(open(path.c_str(), flags, DEFFILEMODE));
Dan Albertaac6b7c2015-03-16 10:08:46 -0700131 if (fd == -1) {
132 return false;
133 }
134
135 bool result = WriteStringToFd(content, fd);
Nick Kralevich82921302015-05-20 08:59:21 -0700136 close(fd);
Dan Albertaac6b7c2015-03-16 10:08:46 -0700137 return result || CleanUpAfterFailedWrite(path);
138}
139
Elliott Hughes20abc872015-04-24 21:57:16 -0700140bool ReadFully(int fd, void* data, size_t byte_count) {
141 uint8_t* p = reinterpret_cast<uint8_t*>(data);
142 size_t remaining = byte_count;
143 while (remaining > 0) {
144 ssize_t n = TEMP_FAILURE_RETRY(read(fd, p, remaining));
145 if (n <= 0) return false;
146 p += n;
147 remaining -= n;
148 }
149 return true;
150}
151
152bool WriteFully(int fd, const void* data, size_t byte_count) {
153 const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
154 size_t remaining = byte_count;
155 while (remaining > 0) {
156 ssize_t n = TEMP_FAILURE_RETRY(write(fd, p, remaining));
157 if (n == -1) return false;
158 p += n;
159 remaining -= n;
160 }
161 return true;
162}
163
Yabin Cui8f6a5a02016-01-29 17:25:54 -0800164bool RemoveFileIfExists(const std::string& path, std::string* err) {
165 struct stat st;
166#if defined(_WIN32)
167 //TODO: Windows version can't handle symbol link correctly.
168 int result = stat(path.c_str(), &st);
169 bool file_type_removable = (result == 0 && S_ISREG(st.st_mode));
170#else
171 int result = lstat(path.c_str(), &st);
172 bool file_type_removable = (result == 0 && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)));
173#endif
174 if (result == 0) {
175 if (!file_type_removable) {
176 if (err != nullptr) {
177 *err = "is not a regular or symbol link file";
178 }
179 return false;
180 }
181 if (unlink(path.c_str()) == -1) {
182 if (err != nullptr) {
183 *err = strerror(errno);
184 }
185 return false;
186 }
187 }
188 return true;
189}
190
Elliott Hughesa634a9a2016-08-23 15:53:45 -0700191#if !defined(_WIN32)
192bool Readlink(const std::string& path, std::string* result) {
193 result->clear();
194
195 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
196 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
197 // waste memory to just start there. We add 1 so that we can recognize
198 // whether it actually fit (rather than being truncated to 4095).
199 std::vector<char> buf(4095 + 1);
200 while (true) {
201 ssize_t size = readlink(path.c_str(), &buf[0], buf.size());
202 // Unrecoverable error?
203 if (size == -1) return false;
204 // It fit! (If size == buf.size(), it may have been truncated.)
205 if (static_cast<size_t>(size) < buf.size()) {
206 result->assign(&buf[0], size);
207 return true;
208 }
209 // Double our buffer and try again.
210 buf.resize(buf.size() * 2);
211 }
212}
213#endif
214
Elliott Hughes48f0eb52016-08-31 15:07:18 -0700215std::string GetExecutablePath() {
216#if defined(__linux__)
217 std::string path;
218 android::base::Readlink("/proc/self/exe", &path);
219 return path;
220#elif defined(__APPLE__)
Elliott Hughes48f0eb52016-08-31 15:07:18 -0700221 char path[PATH_MAX + 1];
Josh Gao58668ac2016-09-01 12:31:42 -0700222 uint32_t path_len = sizeof(path);
223 int rc = _NSGetExecutablePath(path, &path_len);
224 if (rc < 0) {
225 std::unique_ptr<char> path_buf(new char[path_len]);
226 _NSGetExecutablePath(path_buf.get(), &path_len);
227 return path_buf.get();
228 }
Elliott Hughes48f0eb52016-08-31 15:07:18 -0700229 return path;
230#elif defined(_WIN32)
231 char path[PATH_MAX + 1];
232 DWORD result = GetModuleFileName(NULL, path, sizeof(path) - 1);
233 if (result == 0 || result == sizeof(path) - 1) return "";
234 path[PATH_MAX - 1] = 0;
235 return path;
236#else
237#error unknown OS
238#endif
239}
240
Colin Cross2909be02017-02-23 17:41:56 -0800241std::string GetExecutableDirectory() {
242 return Dirname(GetExecutablePath());
243}
Colin Cross2e732e22017-02-23 21:23:05 -0800244
Colin Cross2909be02017-02-23 17:41:56 -0800245std::string Basename(const std::string& path) {
Colin Cross2e732e22017-02-23 21:23:05 -0800246 // Copy path because basename may modify the string passed in.
247 std::string result(path);
248
249#if !defined(__BIONIC__)
250 // Use lock because basename() may write to a process global and return a
251 // pointer to that. Note that this locking strategy only works if all other
252 // callers to basename in the process also grab this same lock, but its
253 // better than nothing. Bionic's basename returns a thread-local buffer.
254 static std::mutex& basename_lock = *new std::mutex();
255 std::lock_guard<std::mutex> lock(basename_lock);
256#endif
257
258 // Note that if std::string uses copy-on-write strings, &str[0] will cause
259 // the copy to be made, so there is no chance of us accidentally writing to
260 // the storage for 'path'.
261 char* name = basename(&result[0]);
262
263 // In case basename returned a pointer to a process global, copy that string
264 // before leaving the lock.
265 result.assign(name);
266
267 return result;
268}
269
270std::string Dirname(const std::string& path) {
271 // Copy path because dirname may modify the string passed in.
272 std::string result(path);
273
274#if !defined(__BIONIC__)
275 // Use lock because dirname() may write to a process global and return a
276 // pointer to that. Note that this locking strategy only works if all other
277 // callers to dirname in the process also grab this same lock, but its
278 // better than nothing. Bionic's dirname returns a thread-local buffer.
279 static std::mutex& dirname_lock = *new std::mutex();
280 std::lock_guard<std::mutex> lock(dirname_lock);
281#endif
282
283 // Note that if std::string uses copy-on-write strings, &str[0] will cause
284 // the copy to be made, so there is no chance of us accidentally writing to
285 // the storage for 'path'.
286 char* parent = dirname(&result[0]);
287
288 // In case dirname returned a pointer to a process global, copy that string
289 // before leaving the lock.
290 result.assign(parent);
291
292 return result;
293}
294
Dan Albertaac6b7c2015-03-16 10:08:46 -0700295} // namespace base
296} // namespace android