blob: a2f28878e83ee674176bbc109f2359b96519dd2e [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 Albertc007bc32015-03-16 10:08:46 -070035
Elliott Hughes82ff3152016-08-31 15:07:18 -070036#if defined(__APPLE__)
Josh Gao7307f092016-09-01 12:31:42 -070037#include <mach-o/dyld.h>
Elliott Hughes82ff3152016-08-31 15:07:18 -070038#endif
39#if defined(_WIN32)
40#include <windows.h>
Elliott Hughes282ec452017-05-15 17:31:15 -070041#define O_CLOEXEC O_NOINHERIT
42#define O_NOFOLLOW 0
Elliott Hughes82ff3152016-08-31 15:07:18 -070043#endif
44
Dan Albertc007bc32015-03-16 10:08:46 -070045namespace android {
46namespace base {
47
Elliott Hughesc1fd4922015-11-11 18:02:29 +000048// Versions of standard library APIs that support UTF-8 strings.
49using namespace android::base::utf8;
50
Dan Albertc007bc32015-03-16 10:08:46 -070051bool ReadFdToString(int fd, std::string* content) {
Elliott Hughesf682b472015-02-06 12:19:48 -080052 content->clear();
53
Elliott Hughes9bb79712017-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
Elliott Hughesf682b472015-02-06 12:19:48 -080062 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 Gaoffabc962016-09-14 16:11:45 -070070bool ReadFileToString(const std::string& path, std::string* content, bool follow_symlinks) {
Elliott Hughesdec12b22015-02-02 17:31:27 -080071 content->clear();
72
Josh Gaoffabc962016-09-14 16:11:45 -070073 int flags = O_RDONLY | O_CLOEXEC | O_BINARY | (follow_symlinks ? 0 : O_NOFOLLOW);
Christopher Ferris48d08c22017-04-05 12:09:17 -070074 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags)));
Elliott Hughesdec12b22015-02-02 17:31:27 -080075 if (fd == -1) {
76 return false;
77 }
Christopher Ferris48d08c22017-04-05 12:09:17 -070078 return ReadFdToString(fd, content);
Elliott Hughesdec12b22015-02-02 17:31:27 -080079}
80
Dan Albertc007bc32015-03-16 10:08:46 -070081bool WriteStringToFd(const std::string& content, int fd) {
Elliott Hughesdec12b22015-02-02 17:31:27 -080082 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) {
Elliott Hughesdec12b22015-02-02 17:31:27 -080087 return false;
88 }
89 p += n;
90 left -= n;
91 }
Elliott Hughesdec12b22015-02-02 17:31:27 -080092 return true;
93}
Elliott Hughes202f0242015-02-04 13:19:13 -080094
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
Elliott Hughes31fa09c2015-02-04 19:38:28 -0800103#if !defined(_WIN32)
Dan Albertc007bc32015-03-16 10:08:46 -0700104bool WriteStringToFile(const std::string& content, const std::string& path,
Josh Gaoffabc962016-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 Ferris48d08c22017-04-05 12:09:17 -0700109 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode)));
Elliott Hughes202f0242015-02-04 13:19:13 -0800110 if (fd == -1) {
Elliott Hughese5dd71a2016-07-28 15:15:28 -0700111 PLOG(ERROR) << "android::WriteStringToFile open failed";
Elliott Hughes202f0242015-02-04 13:19:13 -0800112 return false;
113 }
Elliott Hughesf682b472015-02-06 12:19:48 -0800114
Dan Albertc007bc32015-03-16 10:08:46 -0700115 // 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.
Elliott Hughes9d1f5152015-02-17 10:16:04 -0800117 if (fchmod(fd, mode) == -1) {
Elliott Hughese5dd71a2016-07-28 15:15:28 -0700118 PLOG(ERROR) << "android::WriteStringToFile fchmod failed";
Elliott Hughes9d1f5152015-02-17 10:16:04 -0800119 return CleanUpAfterFailedWrite(path);
120 }
121 if (fchown(fd, owner, group) == -1) {
Elliott Hughese5dd71a2016-07-28 15:15:28 -0700122 PLOG(ERROR) << "android::WriteStringToFile fchown failed";
Elliott Hughes9d1f5152015-02-17 10:16:04 -0800123 return CleanUpAfterFailedWrite(path);
124 }
125 if (!WriteStringToFd(content, fd)) {
Elliott Hughese5dd71a2016-07-28 15:15:28 -0700126 PLOG(ERROR) << "android::WriteStringToFile write failed";
Elliott Hughes9d1f5152015-02-17 10:16:04 -0800127 return CleanUpAfterFailedWrite(path);
128 }
Elliott Hughes9d1f5152015-02-17 10:16:04 -0800129 return true;
Elliott Hughes202f0242015-02-04 13:19:13 -0800130}
Elliott Hughes31fa09c2015-02-04 19:38:28 -0800131#endif
Elliott Hughes202f0242015-02-04 13:19:13 -0800132
Josh Gaoffabc962016-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 Hughes282ec452017-05-15 17:31:15 -0700137 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, 0666)));
Elliott Hughes202f0242015-02-04 13:19:13 -0800138 if (fd == -1) {
139 return false;
140 }
Christopher Ferris48d08c22017-04-05 12:09:17 -0700141 return WriteStringToFd(content, fd) || CleanUpAfterFailedWrite(path);
Elliott Hughes202f0242015-02-04 13:19:13 -0800142}
Dan Albertc007bc32015-03-16 10:08:46 -0700143
Elliott Hughes56085ed2015-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
156bool WriteFully(int fd, const void* data, size_t byte_count) {
157 const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
158 size_t remaining = byte_count;
159 while (remaining > 0) {
160 ssize_t n = TEMP_FAILURE_RETRY(write(fd, p, remaining));
161 if (n == -1) return false;
162 p += n;
163 remaining -= n;
164 }
165 return true;
166}
167
Yabin Cuib6e314a2016-01-29 17:25:54 -0800168bool RemoveFileIfExists(const std::string& path, std::string* err) {
169 struct stat st;
170#if defined(_WIN32)
171 //TODO: Windows version can't handle symbol link correctly.
172 int result = stat(path.c_str(), &st);
173 bool file_type_removable = (result == 0 && S_ISREG(st.st_mode));
174#else
175 int result = lstat(path.c_str(), &st);
176 bool file_type_removable = (result == 0 && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)));
177#endif
178 if (result == 0) {
179 if (!file_type_removable) {
180 if (err != nullptr) {
181 *err = "is not a regular or symbol link file";
182 }
183 return false;
184 }
185 if (unlink(path.c_str()) == -1) {
186 if (err != nullptr) {
187 *err = strerror(errno);
188 }
189 return false;
190 }
191 }
192 return true;
193}
194
Elliott Hughesd3ff6e52016-08-23 15:53:45 -0700195#if !defined(_WIN32)
196bool Readlink(const std::string& path, std::string* result) {
197 result->clear();
198
199 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
200 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
201 // waste memory to just start there. We add 1 so that we can recognize
202 // whether it actually fit (rather than being truncated to 4095).
203 std::vector<char> buf(4095 + 1);
204 while (true) {
205 ssize_t size = readlink(path.c_str(), &buf[0], buf.size());
206 // Unrecoverable error?
207 if (size == -1) return false;
208 // It fit! (If size == buf.size(), it may have been truncated.)
209 if (static_cast<size_t>(size) < buf.size()) {
210 result->assign(&buf[0], size);
211 return true;
212 }
213 // Double our buffer and try again.
214 buf.resize(buf.size() * 2);
215 }
216}
217#endif
218
Dimitry Ivanov840b6012016-09-09 10:49:21 -0700219#if !defined(_WIN32)
220bool Realpath(const std::string& path, std::string* result) {
221 result->clear();
222
223 char* realpath_buf = realpath(path.c_str(), nullptr);
224 if (realpath_buf == nullptr) {
225 return false;
226 }
227 result->assign(realpath_buf);
228 free(realpath_buf);
229 return true;
230}
231#endif
232
Elliott Hughes82ff3152016-08-31 15:07:18 -0700233std::string GetExecutablePath() {
234#if defined(__linux__)
235 std::string path;
236 android::base::Readlink("/proc/self/exe", &path);
237 return path;
238#elif defined(__APPLE__)
Elliott Hughes82ff3152016-08-31 15:07:18 -0700239 char path[PATH_MAX + 1];
Josh Gao7307f092016-09-01 12:31:42 -0700240 uint32_t path_len = sizeof(path);
241 int rc = _NSGetExecutablePath(path, &path_len);
242 if (rc < 0) {
243 std::unique_ptr<char> path_buf(new char[path_len]);
244 _NSGetExecutablePath(path_buf.get(), &path_len);
245 return path_buf.get();
246 }
Elliott Hughes82ff3152016-08-31 15:07:18 -0700247 return path;
248#elif defined(_WIN32)
249 char path[PATH_MAX + 1];
250 DWORD result = GetModuleFileName(NULL, path, sizeof(path) - 1);
251 if (result == 0 || result == sizeof(path) - 1) return "";
252 path[PATH_MAX - 1] = 0;
253 return path;
254#else
255#error unknown OS
256#endif
257}
258
Colin Crossbb3a5152017-02-23 17:41:56 -0800259std::string GetExecutableDirectory() {
260 return Dirname(GetExecutablePath());
261}
Colin Cross58021d12017-02-23 21:23:05 -0800262
Colin Crossbb3a5152017-02-23 17:41:56 -0800263std::string Basename(const std::string& path) {
Colin Cross58021d12017-02-23 21:23:05 -0800264 // Copy path because basename may modify the string passed in.
265 std::string result(path);
266
267#if !defined(__BIONIC__)
268 // Use lock because basename() may write to a process global and return a
269 // pointer to that. Note that this locking strategy only works if all other
270 // callers to basename in the process also grab this same lock, but its
271 // better than nothing. Bionic's basename returns a thread-local buffer.
272 static std::mutex& basename_lock = *new std::mutex();
273 std::lock_guard<std::mutex> lock(basename_lock);
274#endif
275
276 // Note that if std::string uses copy-on-write strings, &str[0] will cause
277 // the copy to be made, so there is no chance of us accidentally writing to
278 // the storage for 'path'.
279 char* name = basename(&result[0]);
280
281 // In case basename returned a pointer to a process global, copy that string
282 // before leaving the lock.
283 result.assign(name);
284
285 return result;
286}
287
288std::string Dirname(const std::string& path) {
289 // Copy path because dirname may modify the string passed in.
290 std::string result(path);
291
292#if !defined(__BIONIC__)
293 // Use lock because dirname() may write to a process global and return a
294 // pointer to that. Note that this locking strategy only works if all other
295 // callers to dirname in the process also grab this same lock, but its
296 // better than nothing. Bionic's dirname returns a thread-local buffer.
297 static std::mutex& dirname_lock = *new std::mutex();
298 std::lock_guard<std::mutex> lock(dirname_lock);
299#endif
300
301 // Note that if std::string uses copy-on-write strings, &str[0] will cause
302 // the copy to be made, so there is no chance of us accidentally writing to
303 // the storage for 'path'.
304 char* parent = dirname(&result[0]);
305
306 // In case dirname returned a pointer to a process global, copy that string
307 // before leaving the lock.
308 result.assign(parent);
309
310 return result;
311}
312
Dan Albertc007bc32015-03-16 10:08:46 -0700313} // namespace base
314} // namespace android