blob: f362f941c3a407d35c28cb994a1525bf605a8692 [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>
Mark Salyzyn0790b242018-11-12 12:29:14 -080022#include <stdio.h>
23#include <stdlib.h>
Elliott Hughesdec12b22015-02-02 17:31:27 -080024#include <sys/stat.h>
25#include <sys/types.h>
Elliott Hughesd3ff6e52016-08-23 15:53:45 -070026#include <unistd.h>
Elliott Hughesdec12b22015-02-02 17:31:27 -080027
Josh Gao7307f092016-09-01 12:31:42 -070028#include <memory>
Colin Cross58021d12017-02-23 21:23:05 -080029#include <mutex>
Dan Albertc007bc32015-03-16 10:08:46 -070030#include <string>
Elliott Hughesd3ff6e52016-08-23 15:53:45 -070031#include <vector>
Elliott Hughesaf4885a2015-02-03 13:02:57 -080032
Elliott Hughese5dd71a2016-07-28 15:15:28 -070033#include "android-base/logging.h"
Christopher Ferris48d08c22017-04-05 12:09:17 -070034#include "android-base/macros.h" // For TEMP_FAILURE_RETRY on Darwin.
35#include "android-base/unique_fd.h"
Elliott Hughes4f713192015-12-04 22:00:26 -080036#include "android-base/utf8.h"
Dan Albertc007bc32015-03-16 10:08:46 -070037
Elliott Hughes82ff3152016-08-31 15:07:18 -070038#if defined(__APPLE__)
Josh Gao7307f092016-09-01 12:31:42 -070039#include <mach-o/dyld.h>
Elliott Hughes82ff3152016-08-31 15:07:18 -070040#endif
41#if defined(_WIN32)
Mark Salyzyn0790b242018-11-12 12:29:14 -080042#include <direct.h>
Elliott Hughes82ff3152016-08-31 15:07:18 -070043#include <windows.h>
Elliott Hughes282ec452017-05-15 17:31:15 -070044#define O_NOFOLLOW 0
Mark Salyzyn0790b242018-11-12 12:29:14 -080045#define OS_PATH_SEPARATOR '\\'
46#else
47#define OS_PATH_SEPARATOR '/'
Elliott Hughes82ff3152016-08-31 15:07:18 -070048#endif
49
Mark Salyzyn0790b242018-11-12 12:29:14 -080050#ifdef _WIN32
51int mkstemp(char* template_name) {
52 if (_mktemp(template_name) == nullptr) {
53 return -1;
54 }
55 // Use open() to match the close() that TemporaryFile's destructor does.
56 // Use O_BINARY to match base file APIs.
57 return open(template_name, O_CREAT | O_EXCL | O_RDWR | O_BINARY, S_IRUSR | S_IWUSR);
58}
59
60char* mkdtemp(char* template_name) {
61 if (_mktemp(template_name) == nullptr) {
62 return nullptr;
63 }
64 if (_mkdir(template_name) == -1) {
65 return nullptr;
66 }
67 return template_name;
68}
69#endif
70
71namespace {
72
73std::string GetSystemTempDir() {
74#if defined(__ANDROID__)
Mark Salyzyn6009a2d2018-11-13 15:34:38 -080075 const auto* tmpdir = getenv("TMPDIR");
76 if (tmpdir == nullptr) tmpdir = "/data/local/tmp";
Mark Salyzyn0790b242018-11-12 12:29:14 -080077 if (access(tmpdir, R_OK | W_OK | X_OK) == 0) {
78 return tmpdir;
79 }
80 // Tests running in app context can't access /data/local/tmp,
81 // so try current directory if /data/local/tmp is not accessible.
82 return ".";
83#elif defined(_WIN32)
84 char tmp_dir[MAX_PATH];
Mark Salyzyn6009a2d2018-11-13 15:34:38 -080085 DWORD result = GetTempPathA(sizeof(tmp_dir), tmp_dir); // checks TMP env
Mark Salyzyn0790b242018-11-12 12:29:14 -080086 CHECK_NE(result, 0ul) << "GetTempPathA failed, error: " << GetLastError();
87 CHECK_LT(result, sizeof(tmp_dir)) << "path truncated to: " << result;
88
89 // GetTempPath() returns a path with a trailing slash, but init()
90 // does not expect that, so remove it.
91 CHECK_EQ(tmp_dir[result - 1], '\\');
92 tmp_dir[result - 1] = '\0';
93 return tmp_dir;
94#else
Mark Salyzyn6009a2d2018-11-13 15:34:38 -080095 const auto* tmpdir = getenv("TMPDIR");
96 if (tmpdir == nullptr) tmpdir = "/tmp";
97 return tmpdir;
Mark Salyzyn0790b242018-11-12 12:29:14 -080098#endif
99}
100
101} // namespace
102
103TemporaryFile::TemporaryFile() {
104 init(GetSystemTempDir());
105}
106
107TemporaryFile::TemporaryFile(const std::string& tmp_dir) {
108 init(tmp_dir);
109}
110
111TemporaryFile::~TemporaryFile() {
112 if (fd != -1) {
113 close(fd);
114 }
115 if (remove_file_) {
116 unlink(path);
117 }
118}
119
120int TemporaryFile::release() {
121 int result = fd;
122 fd = -1;
123 return result;
124}
125
126void TemporaryFile::init(const std::string& tmp_dir) {
127 snprintf(path, sizeof(path), "%s%cTemporaryFile-XXXXXX", tmp_dir.c_str(), OS_PATH_SEPARATOR);
128 fd = mkstemp(path);
129}
130
131TemporaryDir::TemporaryDir() {
132 init(GetSystemTempDir());
133}
134
135TemporaryDir::~TemporaryDir() {
136 rmdir(path);
137}
138
139bool TemporaryDir::init(const std::string& tmp_dir) {
140 snprintf(path, sizeof(path), "%s%cTemporaryDir-XXXXXX", tmp_dir.c_str(), OS_PATH_SEPARATOR);
141 return (mkdtemp(path) != nullptr);
142}
143
Dan Albertc007bc32015-03-16 10:08:46 -0700144namespace android {
145namespace base {
146
Elliott Hughesc1fd4922015-11-11 18:02:29 +0000147// Versions of standard library APIs that support UTF-8 strings.
148using namespace android::base::utf8;
149
Dan Albertc007bc32015-03-16 10:08:46 -0700150bool ReadFdToString(int fd, std::string* content) {
Elliott Hughesf682b472015-02-06 12:19:48 -0800151 content->clear();
152
Elliott Hughes9bb79712017-03-20 19:16:18 -0700153 // Although original we had small files in mind, this code gets used for
154 // very large files too, where the std::string growth heuristics might not
155 // be suitable. https://code.google.com/p/android/issues/detail?id=258500.
156 struct stat sb;
157 if (fstat(fd, &sb) != -1 && sb.st_size > 0) {
158 content->reserve(sb.st_size);
159 }
160
Elliott Hughesf682b472015-02-06 12:19:48 -0800161 char buf[BUFSIZ];
162 ssize_t n;
163 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], sizeof(buf)))) > 0) {
164 content->append(buf, n);
165 }
166 return (n == 0) ? true : false;
167}
168
Josh Gaoffabc962016-09-14 16:11:45 -0700169bool ReadFileToString(const std::string& path, std::string* content, bool follow_symlinks) {
Elliott Hughesdec12b22015-02-02 17:31:27 -0800170 content->clear();
171
Josh Gaoffabc962016-09-14 16:11:45 -0700172 int flags = O_RDONLY | O_CLOEXEC | O_BINARY | (follow_symlinks ? 0 : O_NOFOLLOW);
Christopher Ferris48d08c22017-04-05 12:09:17 -0700173 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags)));
Elliott Hughesdec12b22015-02-02 17:31:27 -0800174 if (fd == -1) {
175 return false;
176 }
Christopher Ferris48d08c22017-04-05 12:09:17 -0700177 return ReadFdToString(fd, content);
Elliott Hughesdec12b22015-02-02 17:31:27 -0800178}
179
Dan Albertc007bc32015-03-16 10:08:46 -0700180bool WriteStringToFd(const std::string& content, int fd) {
Elliott Hughesdec12b22015-02-02 17:31:27 -0800181 const char* p = content.data();
182 size_t left = content.size();
183 while (left > 0) {
184 ssize_t n = TEMP_FAILURE_RETRY(write(fd, p, left));
185 if (n == -1) {
Elliott Hughesdec12b22015-02-02 17:31:27 -0800186 return false;
187 }
188 p += n;
189 left -= n;
190 }
Elliott Hughesdec12b22015-02-02 17:31:27 -0800191 return true;
192}
Elliott Hughes202f0242015-02-04 13:19:13 -0800193
194static bool CleanUpAfterFailedWrite(const std::string& path) {
195 // Something went wrong. Let's not leave a corrupt file lying around.
196 int saved_errno = errno;
197 unlink(path.c_str());
198 errno = saved_errno;
199 return false;
200}
201
Elliott Hughes31fa09c2015-02-04 19:38:28 -0800202#if !defined(_WIN32)
Dan Albertc007bc32015-03-16 10:08:46 -0700203bool WriteStringToFile(const std::string& content, const std::string& path,
Josh Gaoffabc962016-09-14 16:11:45 -0700204 mode_t mode, uid_t owner, gid_t group,
205 bool follow_symlinks) {
206 int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY |
207 (follow_symlinks ? 0 : O_NOFOLLOW);
Christopher Ferris48d08c22017-04-05 12:09:17 -0700208 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode)));
Elliott Hughes202f0242015-02-04 13:19:13 -0800209 if (fd == -1) {
Elliott Hughese5dd71a2016-07-28 15:15:28 -0700210 PLOG(ERROR) << "android::WriteStringToFile open failed";
Elliott Hughes202f0242015-02-04 13:19:13 -0800211 return false;
212 }
Elliott Hughesf682b472015-02-06 12:19:48 -0800213
Dan Albertc007bc32015-03-16 10:08:46 -0700214 // We do an explicit fchmod here because we assume that the caller really
215 // meant what they said and doesn't want the umask-influenced mode.
Elliott Hughes9d1f5152015-02-17 10:16:04 -0800216 if (fchmod(fd, mode) == -1) {
Elliott Hughese5dd71a2016-07-28 15:15:28 -0700217 PLOG(ERROR) << "android::WriteStringToFile fchmod failed";
Elliott Hughes9d1f5152015-02-17 10:16:04 -0800218 return CleanUpAfterFailedWrite(path);
219 }
220 if (fchown(fd, owner, group) == -1) {
Elliott Hughese5dd71a2016-07-28 15:15:28 -0700221 PLOG(ERROR) << "android::WriteStringToFile fchown failed";
Elliott Hughes9d1f5152015-02-17 10:16:04 -0800222 return CleanUpAfterFailedWrite(path);
223 }
224 if (!WriteStringToFd(content, fd)) {
Elliott Hughese5dd71a2016-07-28 15:15:28 -0700225 PLOG(ERROR) << "android::WriteStringToFile write failed";
Elliott Hughes9d1f5152015-02-17 10:16:04 -0800226 return CleanUpAfterFailedWrite(path);
227 }
Elliott Hughes9d1f5152015-02-17 10:16:04 -0800228 return true;
Elliott Hughes202f0242015-02-04 13:19:13 -0800229}
Elliott Hughes31fa09c2015-02-04 19:38:28 -0800230#endif
Elliott Hughes202f0242015-02-04 13:19:13 -0800231
Josh Gaoffabc962016-09-14 16:11:45 -0700232bool WriteStringToFile(const std::string& content, const std::string& path,
233 bool follow_symlinks) {
234 int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY |
235 (follow_symlinks ? 0 : O_NOFOLLOW);
Elliott Hughes282ec452017-05-15 17:31:15 -0700236 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, 0666)));
Elliott Hughes202f0242015-02-04 13:19:13 -0800237 if (fd == -1) {
238 return false;
239 }
Christopher Ferris48d08c22017-04-05 12:09:17 -0700240 return WriteStringToFd(content, fd) || CleanUpAfterFailedWrite(path);
Elliott Hughes202f0242015-02-04 13:19:13 -0800241}
Dan Albertc007bc32015-03-16 10:08:46 -0700242
Elliott Hughes56085ed2015-04-24 21:57:16 -0700243bool ReadFully(int fd, void* data, size_t byte_count) {
244 uint8_t* p = reinterpret_cast<uint8_t*>(data);
245 size_t remaining = byte_count;
246 while (remaining > 0) {
247 ssize_t n = TEMP_FAILURE_RETRY(read(fd, p, remaining));
248 if (n <= 0) return false;
249 p += n;
250 remaining -= n;
251 }
252 return true;
253}
254
Adam Lesinskide117e42017-06-19 10:27:38 -0700255#if defined(_WIN32)
256// Windows implementation of pread. Note that this DOES move the file descriptors read position,
257// but it does so atomically.
258static ssize_t pread(int fd, void* data, size_t byte_count, off64_t offset) {
259 DWORD bytes_read;
260 OVERLAPPED overlapped;
261 memset(&overlapped, 0, sizeof(OVERLAPPED));
262 overlapped.Offset = static_cast<DWORD>(offset);
263 overlapped.OffsetHigh = static_cast<DWORD>(offset >> 32);
264 if (!ReadFile(reinterpret_cast<HANDLE>(_get_osfhandle(fd)), data, static_cast<DWORD>(byte_count),
265 &bytes_read, &overlapped)) {
266 // In case someone tries to read errno (since this is masquerading as a POSIX call)
267 errno = EIO;
268 return -1;
269 }
270 return static_cast<ssize_t>(bytes_read);
271}
272#endif
273
274bool ReadFullyAtOffset(int fd, void* data, size_t byte_count, off64_t offset) {
275 uint8_t* p = reinterpret_cast<uint8_t*>(data);
276 while (byte_count > 0) {
277 ssize_t n = TEMP_FAILURE_RETRY(pread(fd, p, byte_count, offset));
278 if (n <= 0) return false;
279 p += n;
280 byte_count -= n;
281 offset += n;
282 }
283 return true;
284}
285
Elliott Hughes56085ed2015-04-24 21:57:16 -0700286bool WriteFully(int fd, const void* data, size_t byte_count) {
287 const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
288 size_t remaining = byte_count;
289 while (remaining > 0) {
290 ssize_t n = TEMP_FAILURE_RETRY(write(fd, p, remaining));
291 if (n == -1) return false;
292 p += n;
293 remaining -= n;
294 }
295 return true;
296}
297
Yabin Cuib6e314a2016-01-29 17:25:54 -0800298bool RemoveFileIfExists(const std::string& path, std::string* err) {
299 struct stat st;
300#if defined(_WIN32)
liwugangc63cb072018-07-11 13:24:49 +0800301 // TODO: Windows version can't handle symbolic links correctly.
Yabin Cuib6e314a2016-01-29 17:25:54 -0800302 int result = stat(path.c_str(), &st);
303 bool file_type_removable = (result == 0 && S_ISREG(st.st_mode));
304#else
305 int result = lstat(path.c_str(), &st);
306 bool file_type_removable = (result == 0 && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)));
307#endif
liwugangc63cb072018-07-11 13:24:49 +0800308 if (result == -1) {
309 if (errno == ENOENT || errno == ENOTDIR) return true;
310 if (err != nullptr) *err = strerror(errno);
311 return false;
312 }
313
Yabin Cuib6e314a2016-01-29 17:25:54 -0800314 if (result == 0) {
315 if (!file_type_removable) {
316 if (err != nullptr) {
liwugangc63cb072018-07-11 13:24:49 +0800317 *err = "is not a regular file or symbolic link";
Yabin Cuib6e314a2016-01-29 17:25:54 -0800318 }
319 return false;
320 }
321 if (unlink(path.c_str()) == -1) {
322 if (err != nullptr) {
323 *err = strerror(errno);
324 }
325 return false;
326 }
327 }
328 return true;
329}
330
Elliott Hughesd3ff6e52016-08-23 15:53:45 -0700331#if !defined(_WIN32)
332bool Readlink(const std::string& path, std::string* result) {
333 result->clear();
334
335 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
336 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
337 // waste memory to just start there. We add 1 so that we can recognize
338 // whether it actually fit (rather than being truncated to 4095).
339 std::vector<char> buf(4095 + 1);
340 while (true) {
341 ssize_t size = readlink(path.c_str(), &buf[0], buf.size());
342 // Unrecoverable error?
343 if (size == -1) return false;
344 // It fit! (If size == buf.size(), it may have been truncated.)
345 if (static_cast<size_t>(size) < buf.size()) {
346 result->assign(&buf[0], size);
347 return true;
348 }
349 // Double our buffer and try again.
350 buf.resize(buf.size() * 2);
351 }
352}
353#endif
354
Dimitry Ivanov840b6012016-09-09 10:49:21 -0700355#if !defined(_WIN32)
356bool Realpath(const std::string& path, std::string* result) {
357 result->clear();
358
359 char* realpath_buf = realpath(path.c_str(), nullptr);
360 if (realpath_buf == nullptr) {
361 return false;
362 }
363 result->assign(realpath_buf);
364 free(realpath_buf);
365 return true;
366}
367#endif
368
Elliott Hughes82ff3152016-08-31 15:07:18 -0700369std::string GetExecutablePath() {
370#if defined(__linux__)
371 std::string path;
372 android::base::Readlink("/proc/self/exe", &path);
373 return path;
374#elif defined(__APPLE__)
Elliott Hughes82ff3152016-08-31 15:07:18 -0700375 char path[PATH_MAX + 1];
Josh Gao7307f092016-09-01 12:31:42 -0700376 uint32_t path_len = sizeof(path);
377 int rc = _NSGetExecutablePath(path, &path_len);
378 if (rc < 0) {
379 std::unique_ptr<char> path_buf(new char[path_len]);
380 _NSGetExecutablePath(path_buf.get(), &path_len);
381 return path_buf.get();
382 }
Elliott Hughes82ff3152016-08-31 15:07:18 -0700383 return path;
384#elif defined(_WIN32)
385 char path[PATH_MAX + 1];
386 DWORD result = GetModuleFileName(NULL, path, sizeof(path) - 1);
387 if (result == 0 || result == sizeof(path) - 1) return "";
388 path[PATH_MAX - 1] = 0;
389 return path;
390#else
391#error unknown OS
392#endif
393}
394
Colin Crossbb3a5152017-02-23 17:41:56 -0800395std::string GetExecutableDirectory() {
396 return Dirname(GetExecutablePath());
397}
Colin Cross58021d12017-02-23 21:23:05 -0800398
Colin Crossbb3a5152017-02-23 17:41:56 -0800399std::string Basename(const std::string& path) {
Colin Cross58021d12017-02-23 21:23:05 -0800400 // Copy path because basename may modify the string passed in.
401 std::string result(path);
402
403#if !defined(__BIONIC__)
404 // Use lock because basename() may write to a process global and return a
405 // pointer to that. Note that this locking strategy only works if all other
406 // callers to basename in the process also grab this same lock, but its
407 // better than nothing. Bionic's basename returns a thread-local buffer.
408 static std::mutex& basename_lock = *new std::mutex();
409 std::lock_guard<std::mutex> lock(basename_lock);
410#endif
411
412 // Note that if std::string uses copy-on-write strings, &str[0] will cause
413 // the copy to be made, so there is no chance of us accidentally writing to
414 // the storage for 'path'.
415 char* name = basename(&result[0]);
416
417 // In case basename returned a pointer to a process global, copy that string
418 // before leaving the lock.
419 result.assign(name);
420
421 return result;
422}
423
424std::string Dirname(const std::string& path) {
425 // Copy path because dirname may modify the string passed in.
426 std::string result(path);
427
428#if !defined(__BIONIC__)
429 // Use lock because dirname() may write to a process global and return a
430 // pointer to that. Note that this locking strategy only works if all other
431 // callers to dirname in the process also grab this same lock, but its
432 // better than nothing. Bionic's dirname returns a thread-local buffer.
433 static std::mutex& dirname_lock = *new std::mutex();
434 std::lock_guard<std::mutex> lock(dirname_lock);
435#endif
436
437 // Note that if std::string uses copy-on-write strings, &str[0] will cause
438 // the copy to be made, so there is no chance of us accidentally writing to
439 // the storage for 'path'.
440 char* parent = dirname(&result[0]);
441
442 // In case dirname returned a pointer to a process global, copy that string
443 // before leaving the lock.
444 result.assign(parent);
445
446 return result;
447}
448
Dan Albertc007bc32015-03-16 10:08:46 -0700449} // namespace base
450} // namespace android