blob: d5bb7fe24e480a917ce9cb863275fe39acde4b18 [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>
Mark Salyzynf2e76152018-11-13 13:38:33 -080021#include <ftw.h>
Colin Cross2e732e22017-02-23 21:23:05 -080022#include <libgen.h>
Mark Salyzyn40a4cb42018-11-12 12:29:14 -080023#include <stdio.h>
24#include <stdlib.h>
Dan Albertaac6b7c2015-03-16 10:08:46 -070025#include <sys/stat.h>
26#include <sys/types.h>
Elliott Hughesa634a9a2016-08-23 15:53:45 -070027#include <unistd.h>
Dan Albertaac6b7c2015-03-16 10:08:46 -070028
Josh Gao58668ac2016-09-01 12:31:42 -070029#include <memory>
Colin Cross2e732e22017-02-23 21:23:05 -080030#include <mutex>
Dan Albertaac6b7c2015-03-16 10:08:46 -070031#include <string>
Elliott Hughesa634a9a2016-08-23 15:53:45 -070032#include <vector>
Dan Albertaac6b7c2015-03-16 10:08:46 -070033
Elliott Hughes48f0eb52016-08-31 15:07:18 -070034#if defined(__APPLE__)
Josh Gao58668ac2016-09-01 12:31:42 -070035#include <mach-o/dyld.h>
Elliott Hughes48f0eb52016-08-31 15:07:18 -070036#endif
37#if defined(_WIN32)
Mark Salyzyn40a4cb42018-11-12 12:29:14 -080038#include <direct.h>
Elliott Hughes48f0eb52016-08-31 15:07:18 -070039#include <windows.h>
Elliott Hughes62ecbaa2017-05-15 17:31:15 -070040#define O_NOFOLLOW 0
Mark Salyzyn40a4cb42018-11-12 12:29:14 -080041#define OS_PATH_SEPARATOR '\\'
42#else
43#define OS_PATH_SEPARATOR '/'
Elliott Hughes48f0eb52016-08-31 15:07:18 -070044#endif
45
Mark Salyzynf2e76152018-11-13 13:38:33 -080046#include "android-base/logging.h" // and must be after windows.h for ERROR
47#include "android-base/macros.h" // For TEMP_FAILURE_RETRY on Darwin.
48#include "android-base/unique_fd.h"
49#include "android-base/utf8.h"
50
Mark Salyzyn40a4cb42018-11-12 12:29:14 -080051#ifdef _WIN32
52int mkstemp(char* template_name) {
53 if (_mktemp(template_name) == nullptr) {
54 return -1;
55 }
56 // Use open() to match the close() that TemporaryFile's destructor does.
57 // Use O_BINARY to match base file APIs.
58 return open(template_name, O_CREAT | O_EXCL | O_RDWR | O_BINARY, S_IRUSR | S_IWUSR);
59}
60
61char* mkdtemp(char* template_name) {
62 if (_mktemp(template_name) == nullptr) {
63 return nullptr;
64 }
65 if (_mkdir(template_name) == -1) {
66 return nullptr;
67 }
68 return template_name;
69}
70#endif
71
72namespace {
73
74std::string GetSystemTempDir() {
75#if defined(__ANDROID__)
Mark Salyzyn00a68032018-11-13 15:34:38 -080076 const auto* tmpdir = getenv("TMPDIR");
77 if (tmpdir == nullptr) tmpdir = "/data/local/tmp";
Mark Salyzyn40a4cb42018-11-12 12:29:14 -080078 if (access(tmpdir, R_OK | W_OK | X_OK) == 0) {
79 return tmpdir;
80 }
81 // Tests running in app context can't access /data/local/tmp,
82 // so try current directory if /data/local/tmp is not accessible.
83 return ".";
84#elif defined(_WIN32)
85 char tmp_dir[MAX_PATH];
Mark Salyzyn00a68032018-11-13 15:34:38 -080086 DWORD result = GetTempPathA(sizeof(tmp_dir), tmp_dir); // checks TMP env
Mark Salyzyn40a4cb42018-11-12 12:29:14 -080087 CHECK_NE(result, 0ul) << "GetTempPathA failed, error: " << GetLastError();
88 CHECK_LT(result, sizeof(tmp_dir)) << "path truncated to: " << result;
89
90 // GetTempPath() returns a path with a trailing slash, but init()
91 // does not expect that, so remove it.
92 CHECK_EQ(tmp_dir[result - 1], '\\');
93 tmp_dir[result - 1] = '\0';
94 return tmp_dir;
95#else
Mark Salyzyn00a68032018-11-13 15:34:38 -080096 const auto* tmpdir = getenv("TMPDIR");
97 if (tmpdir == nullptr) tmpdir = "/tmp";
98 return tmpdir;
Mark Salyzyn40a4cb42018-11-12 12:29:14 -080099#endif
100}
101
102} // namespace
103
104TemporaryFile::TemporaryFile() {
105 init(GetSystemTempDir());
106}
107
108TemporaryFile::TemporaryFile(const std::string& tmp_dir) {
109 init(tmp_dir);
110}
111
112TemporaryFile::~TemporaryFile() {
113 if (fd != -1) {
114 close(fd);
115 }
116 if (remove_file_) {
117 unlink(path);
118 }
119}
120
121int TemporaryFile::release() {
122 int result = fd;
123 fd = -1;
124 return result;
125}
126
127void TemporaryFile::init(const std::string& tmp_dir) {
128 snprintf(path, sizeof(path), "%s%cTemporaryFile-XXXXXX", tmp_dir.c_str(), OS_PATH_SEPARATOR);
129 fd = mkstemp(path);
130}
131
132TemporaryDir::TemporaryDir() {
133 init(GetSystemTempDir());
134}
135
136TemporaryDir::~TemporaryDir() {
Mark Salyzynb6f6a202018-11-13 13:38:33 -0800137 if (!remove_dir_and_contents_) return;
138
Mark Salyzynf2e76152018-11-13 13:38:33 -0800139 auto callback = [](const char* child, const struct stat*, int file_type, struct FTW*) -> int {
140 switch (file_type) {
141 case FTW_D:
142 case FTW_DP:
143 case FTW_DNR:
144 if (rmdir(child) == -1) {
145 PLOG(ERROR) << "rmdir " << child;
146 }
147 break;
148 case FTW_NS:
149 default:
150 if (rmdir(child) != -1) break;
151 // FALLTHRU (for gcc, lint, pcc, etc; and following for clang)
152 FALLTHROUGH_INTENDED;
153 case FTW_F:
154 case FTW_SL:
155 case FTW_SLN:
156 if (unlink(child) == -1) {
157 PLOG(ERROR) << "unlink " << child;
158 }
159 break;
160 }
161 return 0;
162 };
163
164 nftw(path, callback, 128, FTW_DEPTH | FTW_MOUNT | FTW_PHYS);
Mark Salyzyn40a4cb42018-11-12 12:29:14 -0800165}
166
167bool TemporaryDir::init(const std::string& tmp_dir) {
168 snprintf(path, sizeof(path), "%s%cTemporaryDir-XXXXXX", tmp_dir.c_str(), OS_PATH_SEPARATOR);
169 return (mkdtemp(path) != nullptr);
170}
171
Dan Albertaac6b7c2015-03-16 10:08:46 -0700172namespace android {
173namespace base {
174
Elliott Hughes774d7f62015-11-11 18:02:29 +0000175// Versions of standard library APIs that support UTF-8 strings.
176using namespace android::base::utf8;
177
Dan Albertaac6b7c2015-03-16 10:08:46 -0700178bool ReadFdToString(int fd, std::string* content) {
179 content->clear();
180
Elliott Hughese9ab7ad2017-03-20 19:16:18 -0700181 // Although original we had small files in mind, this code gets used for
182 // very large files too, where the std::string growth heuristics might not
183 // be suitable. https://code.google.com/p/android/issues/detail?id=258500.
184 struct stat sb;
185 if (fstat(fd, &sb) != -1 && sb.st_size > 0) {
186 content->reserve(sb.st_size);
187 }
188
Dan Albertaac6b7c2015-03-16 10:08:46 -0700189 char buf[BUFSIZ];
190 ssize_t n;
191 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], sizeof(buf)))) > 0) {
192 content->append(buf, n);
193 }
194 return (n == 0) ? true : false;
195}
196
Josh Gao8e1f0d82016-09-14 16:11:45 -0700197bool ReadFileToString(const std::string& path, std::string* content, bool follow_symlinks) {
Dan Albertaac6b7c2015-03-16 10:08:46 -0700198 content->clear();
199
Josh Gao8e1f0d82016-09-14 16:11:45 -0700200 int flags = O_RDONLY | O_CLOEXEC | O_BINARY | (follow_symlinks ? 0 : O_NOFOLLOW);
Christopher Ferrisbf0929f2017-04-05 12:09:17 -0700201 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags)));
Dan Albertaac6b7c2015-03-16 10:08:46 -0700202 if (fd == -1) {
203 return false;
204 }
Christopher Ferrisbf0929f2017-04-05 12:09:17 -0700205 return ReadFdToString(fd, content);
Dan Albertaac6b7c2015-03-16 10:08:46 -0700206}
207
208bool WriteStringToFd(const std::string& content, int fd) {
209 const char* p = content.data();
210 size_t left = content.size();
211 while (left > 0) {
212 ssize_t n = TEMP_FAILURE_RETRY(write(fd, p, left));
213 if (n == -1) {
214 return false;
215 }
216 p += n;
217 left -= n;
218 }
219 return true;
220}
221
222static bool CleanUpAfterFailedWrite(const std::string& path) {
223 // Something went wrong. Let's not leave a corrupt file lying around.
224 int saved_errno = errno;
225 unlink(path.c_str());
226 errno = saved_errno;
227 return false;
228}
229
230#if !defined(_WIN32)
231bool WriteStringToFile(const std::string& content, const std::string& path,
Josh Gao8e1f0d82016-09-14 16:11:45 -0700232 mode_t mode, uid_t owner, gid_t group,
233 bool follow_symlinks) {
234 int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY |
235 (follow_symlinks ? 0 : O_NOFOLLOW);
Christopher Ferrisbf0929f2017-04-05 12:09:17 -0700236 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode)));
Dan Albertaac6b7c2015-03-16 10:08:46 -0700237 if (fd == -1) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700238 PLOG(ERROR) << "android::WriteStringToFile open failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700239 return false;
240 }
241
242 // We do an explicit fchmod here because we assume that the caller really
243 // meant what they said and doesn't want the umask-influenced mode.
244 if (fchmod(fd, mode) == -1) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700245 PLOG(ERROR) << "android::WriteStringToFile fchmod failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700246 return CleanUpAfterFailedWrite(path);
247 }
248 if (fchown(fd, owner, group) == -1) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700249 PLOG(ERROR) << "android::WriteStringToFile fchown failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700250 return CleanUpAfterFailedWrite(path);
251 }
252 if (!WriteStringToFd(content, fd)) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700253 PLOG(ERROR) << "android::WriteStringToFile write failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700254 return CleanUpAfterFailedWrite(path);
255 }
Dan Albertaac6b7c2015-03-16 10:08:46 -0700256 return true;
257}
258#endif
259
Josh Gao8e1f0d82016-09-14 16:11:45 -0700260bool WriteStringToFile(const std::string& content, const std::string& path,
261 bool follow_symlinks) {
262 int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY |
263 (follow_symlinks ? 0 : O_NOFOLLOW);
Elliott Hughes62ecbaa2017-05-15 17:31:15 -0700264 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, 0666)));
Dan Albertaac6b7c2015-03-16 10:08:46 -0700265 if (fd == -1) {
266 return false;
267 }
Christopher Ferrisbf0929f2017-04-05 12:09:17 -0700268 return WriteStringToFd(content, fd) || CleanUpAfterFailedWrite(path);
Dan Albertaac6b7c2015-03-16 10:08:46 -0700269}
270
Elliott Hughes20abc872015-04-24 21:57:16 -0700271bool ReadFully(int fd, void* data, size_t byte_count) {
272 uint8_t* p = reinterpret_cast<uint8_t*>(data);
273 size_t remaining = byte_count;
274 while (remaining > 0) {
275 ssize_t n = TEMP_FAILURE_RETRY(read(fd, p, remaining));
276 if (n <= 0) return false;
277 p += n;
278 remaining -= n;
279 }
280 return true;
281}
282
Adam Lesinski6d6f9b32017-06-19 10:27:38 -0700283#if defined(_WIN32)
284// Windows implementation of pread. Note that this DOES move the file descriptors read position,
285// but it does so atomically.
286static ssize_t pread(int fd, void* data, size_t byte_count, off64_t offset) {
287 DWORD bytes_read;
288 OVERLAPPED overlapped;
289 memset(&overlapped, 0, sizeof(OVERLAPPED));
290 overlapped.Offset = static_cast<DWORD>(offset);
291 overlapped.OffsetHigh = static_cast<DWORD>(offset >> 32);
292 if (!ReadFile(reinterpret_cast<HANDLE>(_get_osfhandle(fd)), data, static_cast<DWORD>(byte_count),
293 &bytes_read, &overlapped)) {
294 // In case someone tries to read errno (since this is masquerading as a POSIX call)
295 errno = EIO;
296 return -1;
297 }
298 return static_cast<ssize_t>(bytes_read);
299}
300#endif
301
302bool ReadFullyAtOffset(int fd, void* data, size_t byte_count, off64_t offset) {
303 uint8_t* p = reinterpret_cast<uint8_t*>(data);
304 while (byte_count > 0) {
305 ssize_t n = TEMP_FAILURE_RETRY(pread(fd, p, byte_count, offset));
306 if (n <= 0) return false;
307 p += n;
308 byte_count -= n;
309 offset += n;
310 }
311 return true;
312}
313
Elliott Hughes20abc872015-04-24 21:57:16 -0700314bool WriteFully(int fd, const void* data, size_t byte_count) {
315 const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
316 size_t remaining = byte_count;
317 while (remaining > 0) {
318 ssize_t n = TEMP_FAILURE_RETRY(write(fd, p, remaining));
319 if (n == -1) return false;
320 p += n;
321 remaining -= n;
322 }
323 return true;
324}
325
Yabin Cui8f6a5a02016-01-29 17:25:54 -0800326bool RemoveFileIfExists(const std::string& path, std::string* err) {
327 struct stat st;
328#if defined(_WIN32)
liwugang78cea682018-07-11 13:24:49 +0800329 // TODO: Windows version can't handle symbolic links correctly.
Yabin Cui8f6a5a02016-01-29 17:25:54 -0800330 int result = stat(path.c_str(), &st);
331 bool file_type_removable = (result == 0 && S_ISREG(st.st_mode));
332#else
333 int result = lstat(path.c_str(), &st);
334 bool file_type_removable = (result == 0 && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)));
335#endif
liwugang78cea682018-07-11 13:24:49 +0800336 if (result == -1) {
337 if (errno == ENOENT || errno == ENOTDIR) return true;
338 if (err != nullptr) *err = strerror(errno);
339 return false;
340 }
341
Yabin Cui8f6a5a02016-01-29 17:25:54 -0800342 if (result == 0) {
343 if (!file_type_removable) {
344 if (err != nullptr) {
liwugang78cea682018-07-11 13:24:49 +0800345 *err = "is not a regular file or symbolic link";
Yabin Cui8f6a5a02016-01-29 17:25:54 -0800346 }
347 return false;
348 }
349 if (unlink(path.c_str()) == -1) {
350 if (err != nullptr) {
351 *err = strerror(errno);
352 }
353 return false;
354 }
355 }
356 return true;
357}
358
Elliott Hughesa634a9a2016-08-23 15:53:45 -0700359#if !defined(_WIN32)
360bool Readlink(const std::string& path, std::string* result) {
361 result->clear();
362
363 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
364 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
365 // waste memory to just start there. We add 1 so that we can recognize
366 // whether it actually fit (rather than being truncated to 4095).
367 std::vector<char> buf(4095 + 1);
368 while (true) {
369 ssize_t size = readlink(path.c_str(), &buf[0], buf.size());
370 // Unrecoverable error?
371 if (size == -1) return false;
372 // It fit! (If size == buf.size(), it may have been truncated.)
373 if (static_cast<size_t>(size) < buf.size()) {
374 result->assign(&buf[0], size);
375 return true;
376 }
377 // Double our buffer and try again.
378 buf.resize(buf.size() * 2);
379 }
380}
381#endif
382
Dimitry Ivanov4edc04f2016-09-09 10:49:21 -0700383#if !defined(_WIN32)
384bool Realpath(const std::string& path, std::string* result) {
385 result->clear();
386
387 char* realpath_buf = realpath(path.c_str(), nullptr);
388 if (realpath_buf == nullptr) {
389 return false;
390 }
391 result->assign(realpath_buf);
392 free(realpath_buf);
393 return true;
394}
395#endif
396
Elliott Hughes48f0eb52016-08-31 15:07:18 -0700397std::string GetExecutablePath() {
398#if defined(__linux__)
399 std::string path;
400 android::base::Readlink("/proc/self/exe", &path);
401 return path;
402#elif defined(__APPLE__)
Elliott Hughes48f0eb52016-08-31 15:07:18 -0700403 char path[PATH_MAX + 1];
Josh Gao58668ac2016-09-01 12:31:42 -0700404 uint32_t path_len = sizeof(path);
405 int rc = _NSGetExecutablePath(path, &path_len);
406 if (rc < 0) {
407 std::unique_ptr<char> path_buf(new char[path_len]);
408 _NSGetExecutablePath(path_buf.get(), &path_len);
409 return path_buf.get();
410 }
Elliott Hughes48f0eb52016-08-31 15:07:18 -0700411 return path;
412#elif defined(_WIN32)
413 char path[PATH_MAX + 1];
414 DWORD result = GetModuleFileName(NULL, path, sizeof(path) - 1);
415 if (result == 0 || result == sizeof(path) - 1) return "";
416 path[PATH_MAX - 1] = 0;
417 return path;
418#else
419#error unknown OS
420#endif
421}
422
Colin Cross2909be02017-02-23 17:41:56 -0800423std::string GetExecutableDirectory() {
424 return Dirname(GetExecutablePath());
425}
Colin Cross2e732e22017-02-23 21:23:05 -0800426
Colin Cross2909be02017-02-23 17:41:56 -0800427std::string Basename(const std::string& path) {
Colin Cross2e732e22017-02-23 21:23:05 -0800428 // Copy path because basename may modify the string passed in.
429 std::string result(path);
430
431#if !defined(__BIONIC__)
432 // Use lock because basename() may write to a process global and return a
433 // pointer to that. Note that this locking strategy only works if all other
434 // callers to basename in the process also grab this same lock, but its
435 // better than nothing. Bionic's basename returns a thread-local buffer.
436 static std::mutex& basename_lock = *new std::mutex();
437 std::lock_guard<std::mutex> lock(basename_lock);
438#endif
439
440 // Note that if std::string uses copy-on-write strings, &str[0] will cause
441 // the copy to be made, so there is no chance of us accidentally writing to
442 // the storage for 'path'.
443 char* name = basename(&result[0]);
444
445 // In case basename returned a pointer to a process global, copy that string
446 // before leaving the lock.
447 result.assign(name);
448
449 return result;
450}
451
452std::string Dirname(const std::string& path) {
453 // Copy path because dirname may modify the string passed in.
454 std::string result(path);
455
456#if !defined(__BIONIC__)
457 // Use lock because dirname() may write to a process global and return a
458 // pointer to that. Note that this locking strategy only works if all other
459 // callers to dirname in the process also grab this same lock, but its
460 // better than nothing. Bionic's dirname returns a thread-local buffer.
461 static std::mutex& dirname_lock = *new std::mutex();
462 std::lock_guard<std::mutex> lock(dirname_lock);
463#endif
464
465 // Note that if std::string uses copy-on-write strings, &str[0] will cause
466 // the copy to be made, so there is no chance of us accidentally writing to
467 // the storage for 'path'.
468 char* parent = dirname(&result[0]);
469
470 // In case dirname returned a pointer to a process global, copy that string
471 // before leaving the lock.
472 result.assign(parent);
473
474 return result;
475}
476
Dan Albertaac6b7c2015-03-16 10:08:46 -0700477} // namespace base
478} // namespace android