blob: 2f4a517589e75c21b6d13974ef867ece3d400a45 [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>
Mark Salyzyn46c2df52018-11-13 13:38:33 -080021#include <ftw.h>
Colin Cross58021d12017-02-23 21:23:05 -080022#include <libgen.h>
Mark Salyzyn0790b242018-11-12 12:29:14 -080023#include <stdio.h>
24#include <stdlib.h>
Florian Mayer3f1f2e02018-10-23 15:56:28 +010025#include <string.h>
Elliott Hughesdec12b22015-02-02 17:31:27 -080026#include <sys/stat.h>
27#include <sys/types.h>
Elliott Hughesd3ff6e52016-08-23 15:53:45 -070028#include <unistd.h>
Elliott Hughesdec12b22015-02-02 17:31:27 -080029
Josh Gao7307f092016-09-01 12:31:42 -070030#include <memory>
Colin Cross58021d12017-02-23 21:23:05 -080031#include <mutex>
Dan Albertc007bc32015-03-16 10:08:46 -070032#include <string>
Elliott Hughesd3ff6e52016-08-23 15:53:45 -070033#include <vector>
Elliott Hughesaf4885a2015-02-03 13:02:57 -080034
Elliott Hughes82ff3152016-08-31 15:07:18 -070035#if defined(__APPLE__)
Josh Gao7307f092016-09-01 12:31:42 -070036#include <mach-o/dyld.h>
Elliott Hughes82ff3152016-08-31 15:07:18 -070037#endif
38#if defined(_WIN32)
Mark Salyzyn0790b242018-11-12 12:29:14 -080039#include <direct.h>
Elliott Hughes82ff3152016-08-31 15:07:18 -070040#include <windows.h>
Elliott Hughes282ec452017-05-15 17:31:15 -070041#define O_NOFOLLOW 0
Mark Salyzyn0790b242018-11-12 12:29:14 -080042#define OS_PATH_SEPARATOR '\\'
43#else
44#define OS_PATH_SEPARATOR '/'
Elliott Hughes82ff3152016-08-31 15:07:18 -070045#endif
46
Mark Salyzyn46c2df52018-11-13 13:38:33 -080047#include "android-base/logging.h" // and must be after windows.h for ERROR
48#include "android-base/macros.h" // For TEMP_FAILURE_RETRY on Darwin.
49#include "android-base/unique_fd.h"
50#include "android-base/utf8.h"
51
Mark Salyzyn0790b242018-11-12 12:29:14 -080052#ifdef _WIN32
53int mkstemp(char* template_name) {
54 if (_mktemp(template_name) == nullptr) {
55 return -1;
56 }
57 // Use open() to match the close() that TemporaryFile's destructor does.
58 // Use O_BINARY to match base file APIs.
59 return open(template_name, O_CREAT | O_EXCL | O_RDWR | O_BINARY, S_IRUSR | S_IWUSR);
60}
61
62char* mkdtemp(char* template_name) {
63 if (_mktemp(template_name) == nullptr) {
64 return nullptr;
65 }
66 if (_mkdir(template_name) == -1) {
67 return nullptr;
68 }
69 return template_name;
70}
71#endif
72
73namespace {
74
75std::string GetSystemTempDir() {
76#if defined(__ANDROID__)
Mark Salyzyn6009a2d2018-11-13 15:34:38 -080077 const auto* tmpdir = getenv("TMPDIR");
78 if (tmpdir == nullptr) tmpdir = "/data/local/tmp";
Mark Salyzyn0790b242018-11-12 12:29:14 -080079 if (access(tmpdir, R_OK | W_OK | X_OK) == 0) {
80 return tmpdir;
81 }
82 // Tests running in app context can't access /data/local/tmp,
83 // so try current directory if /data/local/tmp is not accessible.
84 return ".";
85#elif defined(_WIN32)
86 char tmp_dir[MAX_PATH];
Mark Salyzyn6009a2d2018-11-13 15:34:38 -080087 DWORD result = GetTempPathA(sizeof(tmp_dir), tmp_dir); // checks TMP env
Mark Salyzyn0790b242018-11-12 12:29:14 -080088 CHECK_NE(result, 0ul) << "GetTempPathA failed, error: " << GetLastError();
89 CHECK_LT(result, sizeof(tmp_dir)) << "path truncated to: " << result;
90
91 // GetTempPath() returns a path with a trailing slash, but init()
92 // does not expect that, so remove it.
93 CHECK_EQ(tmp_dir[result - 1], '\\');
94 tmp_dir[result - 1] = '\0';
95 return tmp_dir;
96#else
Mark Salyzyn6009a2d2018-11-13 15:34:38 -080097 const auto* tmpdir = getenv("TMPDIR");
98 if (tmpdir == nullptr) tmpdir = "/tmp";
99 return tmpdir;
Mark Salyzyn0790b242018-11-12 12:29:14 -0800100#endif
101}
102
103} // namespace
104
105TemporaryFile::TemporaryFile() {
106 init(GetSystemTempDir());
107}
108
109TemporaryFile::TemporaryFile(const std::string& tmp_dir) {
110 init(tmp_dir);
111}
112
113TemporaryFile::~TemporaryFile() {
114 if (fd != -1) {
115 close(fd);
116 }
117 if (remove_file_) {
118 unlink(path);
119 }
120}
121
122int TemporaryFile::release() {
123 int result = fd;
124 fd = -1;
125 return result;
126}
127
128void TemporaryFile::init(const std::string& tmp_dir) {
129 snprintf(path, sizeof(path), "%s%cTemporaryFile-XXXXXX", tmp_dir.c_str(), OS_PATH_SEPARATOR);
130 fd = mkstemp(path);
131}
132
133TemporaryDir::TemporaryDir() {
134 init(GetSystemTempDir());
135}
136
137TemporaryDir::~TemporaryDir() {
Mark Salyzynd2f58882018-11-13 13:38:33 -0800138 if (!remove_dir_and_contents_) return;
139
Mark Salyzyn46c2df52018-11-13 13:38:33 -0800140 auto callback = [](const char* child, const struct stat*, int file_type, struct FTW*) -> int {
141 switch (file_type) {
142 case FTW_D:
143 case FTW_DP:
144 case FTW_DNR:
145 if (rmdir(child) == -1) {
146 PLOG(ERROR) << "rmdir " << child;
147 }
148 break;
149 case FTW_NS:
150 default:
151 if (rmdir(child) != -1) break;
152 // FALLTHRU (for gcc, lint, pcc, etc; and following for clang)
153 FALLTHROUGH_INTENDED;
154 case FTW_F:
155 case FTW_SL:
156 case FTW_SLN:
157 if (unlink(child) == -1) {
158 PLOG(ERROR) << "unlink " << child;
159 }
160 break;
161 }
162 return 0;
163 };
164
165 nftw(path, callback, 128, FTW_DEPTH | FTW_MOUNT | FTW_PHYS);
Mark Salyzyn0790b242018-11-12 12:29:14 -0800166}
167
168bool TemporaryDir::init(const std::string& tmp_dir) {
169 snprintf(path, sizeof(path), "%s%cTemporaryDir-XXXXXX", tmp_dir.c_str(), OS_PATH_SEPARATOR);
170 return (mkdtemp(path) != nullptr);
171}
172
Dan Albertc007bc32015-03-16 10:08:46 -0700173namespace android {
174namespace base {
175
Elliott Hughesc1fd4922015-11-11 18:02:29 +0000176// Versions of standard library APIs that support UTF-8 strings.
177using namespace android::base::utf8;
178
Dan Albertc007bc32015-03-16 10:08:46 -0700179bool ReadFdToString(int fd, std::string* content) {
Elliott Hughesf682b472015-02-06 12:19:48 -0800180 content->clear();
181
Elliott Hughes9bb79712017-03-20 19:16:18 -0700182 // Although original we had small files in mind, this code gets used for
183 // very large files too, where the std::string growth heuristics might not
184 // be suitable. https://code.google.com/p/android/issues/detail?id=258500.
185 struct stat sb;
186 if (fstat(fd, &sb) != -1 && sb.st_size > 0) {
187 content->reserve(sb.st_size);
188 }
189
Elliott Hughesf682b472015-02-06 12:19:48 -0800190 char buf[BUFSIZ];
191 ssize_t n;
192 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], sizeof(buf)))) > 0) {
193 content->append(buf, n);
194 }
195 return (n == 0) ? true : false;
196}
197
Josh Gaoffabc962016-09-14 16:11:45 -0700198bool ReadFileToString(const std::string& path, std::string* content, bool follow_symlinks) {
Elliott Hughesdec12b22015-02-02 17:31:27 -0800199 content->clear();
200
Josh Gaoffabc962016-09-14 16:11:45 -0700201 int flags = O_RDONLY | O_CLOEXEC | O_BINARY | (follow_symlinks ? 0 : O_NOFOLLOW);
Christopher Ferris48d08c22017-04-05 12:09:17 -0700202 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags)));
Elliott Hughesdec12b22015-02-02 17:31:27 -0800203 if (fd == -1) {
204 return false;
205 }
Christopher Ferris48d08c22017-04-05 12:09:17 -0700206 return ReadFdToString(fd, content);
Elliott Hughesdec12b22015-02-02 17:31:27 -0800207}
208
Dan Albertc007bc32015-03-16 10:08:46 -0700209bool WriteStringToFd(const std::string& content, int fd) {
Elliott Hughesdec12b22015-02-02 17:31:27 -0800210 const char* p = content.data();
211 size_t left = content.size();
212 while (left > 0) {
213 ssize_t n = TEMP_FAILURE_RETRY(write(fd, p, left));
214 if (n == -1) {
Elliott Hughesdec12b22015-02-02 17:31:27 -0800215 return false;
216 }
217 p += n;
218 left -= n;
219 }
Elliott Hughesdec12b22015-02-02 17:31:27 -0800220 return true;
221}
Elliott Hughes202f0242015-02-04 13:19:13 -0800222
223static bool CleanUpAfterFailedWrite(const std::string& path) {
224 // Something went wrong. Let's not leave a corrupt file lying around.
225 int saved_errno = errno;
226 unlink(path.c_str());
227 errno = saved_errno;
228 return false;
229}
230
Elliott Hughes31fa09c2015-02-04 19:38:28 -0800231#if !defined(_WIN32)
Dan Albertc007bc32015-03-16 10:08:46 -0700232bool WriteStringToFile(const std::string& content, const std::string& path,
Josh Gaoffabc962016-09-14 16:11:45 -0700233 mode_t mode, uid_t owner, gid_t group,
234 bool follow_symlinks) {
235 int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY |
236 (follow_symlinks ? 0 : O_NOFOLLOW);
Christopher Ferris48d08c22017-04-05 12:09:17 -0700237 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode)));
Elliott Hughes202f0242015-02-04 13:19:13 -0800238 if (fd == -1) {
Elliott Hughese5dd71a2016-07-28 15:15:28 -0700239 PLOG(ERROR) << "android::WriteStringToFile open failed";
Elliott Hughes202f0242015-02-04 13:19:13 -0800240 return false;
241 }
Elliott Hughesf682b472015-02-06 12:19:48 -0800242
Dan Albertc007bc32015-03-16 10:08:46 -0700243 // We do an explicit fchmod here because we assume that the caller really
244 // meant what they said and doesn't want the umask-influenced mode.
Elliott Hughes9d1f5152015-02-17 10:16:04 -0800245 if (fchmod(fd, mode) == -1) {
Elliott Hughese5dd71a2016-07-28 15:15:28 -0700246 PLOG(ERROR) << "android::WriteStringToFile fchmod failed";
Elliott Hughes9d1f5152015-02-17 10:16:04 -0800247 return CleanUpAfterFailedWrite(path);
248 }
249 if (fchown(fd, owner, group) == -1) {
Elliott Hughese5dd71a2016-07-28 15:15:28 -0700250 PLOG(ERROR) << "android::WriteStringToFile fchown failed";
Elliott Hughes9d1f5152015-02-17 10:16:04 -0800251 return CleanUpAfterFailedWrite(path);
252 }
253 if (!WriteStringToFd(content, fd)) {
Elliott Hughese5dd71a2016-07-28 15:15:28 -0700254 PLOG(ERROR) << "android::WriteStringToFile write failed";
Elliott Hughes9d1f5152015-02-17 10:16:04 -0800255 return CleanUpAfterFailedWrite(path);
256 }
Elliott Hughes9d1f5152015-02-17 10:16:04 -0800257 return true;
Elliott Hughes202f0242015-02-04 13:19:13 -0800258}
Elliott Hughes31fa09c2015-02-04 19:38:28 -0800259#endif
Elliott Hughes202f0242015-02-04 13:19:13 -0800260
Josh Gaoffabc962016-09-14 16:11:45 -0700261bool WriteStringToFile(const std::string& content, const std::string& path,
262 bool follow_symlinks) {
263 int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY |
264 (follow_symlinks ? 0 : O_NOFOLLOW);
Elliott Hughes282ec452017-05-15 17:31:15 -0700265 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, 0666)));
Elliott Hughes202f0242015-02-04 13:19:13 -0800266 if (fd == -1) {
267 return false;
268 }
Christopher Ferris48d08c22017-04-05 12:09:17 -0700269 return WriteStringToFd(content, fd) || CleanUpAfterFailedWrite(path);
Elliott Hughes202f0242015-02-04 13:19:13 -0800270}
Dan Albertc007bc32015-03-16 10:08:46 -0700271
Elliott Hughes56085ed2015-04-24 21:57:16 -0700272bool ReadFully(int fd, void* data, size_t byte_count) {
273 uint8_t* p = reinterpret_cast<uint8_t*>(data);
274 size_t remaining = byte_count;
275 while (remaining > 0) {
276 ssize_t n = TEMP_FAILURE_RETRY(read(fd, p, remaining));
277 if (n <= 0) return false;
278 p += n;
279 remaining -= n;
280 }
281 return true;
282}
283
Adam Lesinskide117e42017-06-19 10:27:38 -0700284#if defined(_WIN32)
285// Windows implementation of pread. Note that this DOES move the file descriptors read position,
286// but it does so atomically.
287static ssize_t pread(int fd, void* data, size_t byte_count, off64_t offset) {
288 DWORD bytes_read;
289 OVERLAPPED overlapped;
290 memset(&overlapped, 0, sizeof(OVERLAPPED));
291 overlapped.Offset = static_cast<DWORD>(offset);
292 overlapped.OffsetHigh = static_cast<DWORD>(offset >> 32);
293 if (!ReadFile(reinterpret_cast<HANDLE>(_get_osfhandle(fd)), data, static_cast<DWORD>(byte_count),
294 &bytes_read, &overlapped)) {
295 // In case someone tries to read errno (since this is masquerading as a POSIX call)
296 errno = EIO;
297 return -1;
298 }
299 return static_cast<ssize_t>(bytes_read);
300}
301#endif
302
303bool ReadFullyAtOffset(int fd, void* data, size_t byte_count, off64_t offset) {
304 uint8_t* p = reinterpret_cast<uint8_t*>(data);
305 while (byte_count > 0) {
306 ssize_t n = TEMP_FAILURE_RETRY(pread(fd, p, byte_count, offset));
307 if (n <= 0) return false;
308 p += n;
309 byte_count -= n;
310 offset += n;
311 }
312 return true;
313}
314
Elliott Hughes56085ed2015-04-24 21:57:16 -0700315bool WriteFully(int fd, const void* data, size_t byte_count) {
316 const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
317 size_t remaining = byte_count;
318 while (remaining > 0) {
319 ssize_t n = TEMP_FAILURE_RETRY(write(fd, p, remaining));
320 if (n == -1) return false;
321 p += n;
322 remaining -= n;
323 }
324 return true;
325}
326
Yabin Cuib6e314a2016-01-29 17:25:54 -0800327bool RemoveFileIfExists(const std::string& path, std::string* err) {
328 struct stat st;
329#if defined(_WIN32)
liwugangc63cb072018-07-11 13:24:49 +0800330 // TODO: Windows version can't handle symbolic links correctly.
Yabin Cuib6e314a2016-01-29 17:25:54 -0800331 int result = stat(path.c_str(), &st);
332 bool file_type_removable = (result == 0 && S_ISREG(st.st_mode));
333#else
334 int result = lstat(path.c_str(), &st);
335 bool file_type_removable = (result == 0 && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)));
336#endif
liwugangc63cb072018-07-11 13:24:49 +0800337 if (result == -1) {
338 if (errno == ENOENT || errno == ENOTDIR) return true;
339 if (err != nullptr) *err = strerror(errno);
340 return false;
341 }
342
Yabin Cuib6e314a2016-01-29 17:25:54 -0800343 if (result == 0) {
344 if (!file_type_removable) {
345 if (err != nullptr) {
liwugangc63cb072018-07-11 13:24:49 +0800346 *err = "is not a regular file or symbolic link";
Yabin Cuib6e314a2016-01-29 17:25:54 -0800347 }
348 return false;
349 }
350 if (unlink(path.c_str()) == -1) {
351 if (err != nullptr) {
352 *err = strerror(errno);
353 }
354 return false;
355 }
356 }
357 return true;
358}
359
Elliott Hughesd3ff6e52016-08-23 15:53:45 -0700360#if !defined(_WIN32)
361bool Readlink(const std::string& path, std::string* result) {
362 result->clear();
363
364 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
365 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
366 // waste memory to just start there. We add 1 so that we can recognize
367 // whether it actually fit (rather than being truncated to 4095).
368 std::vector<char> buf(4095 + 1);
369 while (true) {
370 ssize_t size = readlink(path.c_str(), &buf[0], buf.size());
371 // Unrecoverable error?
372 if (size == -1) return false;
373 // It fit! (If size == buf.size(), it may have been truncated.)
374 if (static_cast<size_t>(size) < buf.size()) {
375 result->assign(&buf[0], size);
376 return true;
377 }
378 // Double our buffer and try again.
379 buf.resize(buf.size() * 2);
380 }
381}
382#endif
383
Dimitry Ivanov840b6012016-09-09 10:49:21 -0700384#if !defined(_WIN32)
385bool Realpath(const std::string& path, std::string* result) {
386 result->clear();
387
388 char* realpath_buf = realpath(path.c_str(), nullptr);
389 if (realpath_buf == nullptr) {
390 return false;
391 }
392 result->assign(realpath_buf);
393 free(realpath_buf);
394 return true;
395}
396#endif
397
Elliott Hughes82ff3152016-08-31 15:07:18 -0700398std::string GetExecutablePath() {
399#if defined(__linux__)
400 std::string path;
401 android::base::Readlink("/proc/self/exe", &path);
402 return path;
403#elif defined(__APPLE__)
Elliott Hughes82ff3152016-08-31 15:07:18 -0700404 char path[PATH_MAX + 1];
Josh Gao7307f092016-09-01 12:31:42 -0700405 uint32_t path_len = sizeof(path);
406 int rc = _NSGetExecutablePath(path, &path_len);
407 if (rc < 0) {
408 std::unique_ptr<char> path_buf(new char[path_len]);
409 _NSGetExecutablePath(path_buf.get(), &path_len);
410 return path_buf.get();
411 }
Elliott Hughes82ff3152016-08-31 15:07:18 -0700412 return path;
413#elif defined(_WIN32)
414 char path[PATH_MAX + 1];
415 DWORD result = GetModuleFileName(NULL, path, sizeof(path) - 1);
416 if (result == 0 || result == sizeof(path) - 1) return "";
417 path[PATH_MAX - 1] = 0;
418 return path;
419#else
420#error unknown OS
421#endif
422}
423
Colin Crossbb3a5152017-02-23 17:41:56 -0800424std::string GetExecutableDirectory() {
425 return Dirname(GetExecutablePath());
426}
Colin Cross58021d12017-02-23 21:23:05 -0800427
Colin Crossbb3a5152017-02-23 17:41:56 -0800428std::string Basename(const std::string& path) {
Colin Cross58021d12017-02-23 21:23:05 -0800429 // Copy path because basename may modify the string passed in.
430 std::string result(path);
431
432#if !defined(__BIONIC__)
433 // Use lock because basename() may write to a process global and return a
434 // pointer to that. Note that this locking strategy only works if all other
435 // callers to basename in the process also grab this same lock, but its
436 // better than nothing. Bionic's basename returns a thread-local buffer.
437 static std::mutex& basename_lock = *new std::mutex();
438 std::lock_guard<std::mutex> lock(basename_lock);
439#endif
440
441 // Note that if std::string uses copy-on-write strings, &str[0] will cause
442 // the copy to be made, so there is no chance of us accidentally writing to
443 // the storage for 'path'.
444 char* name = basename(&result[0]);
445
446 // In case basename returned a pointer to a process global, copy that string
447 // before leaving the lock.
448 result.assign(name);
449
450 return result;
451}
452
453std::string Dirname(const std::string& path) {
454 // Copy path because dirname may modify the string passed in.
455 std::string result(path);
456
457#if !defined(__BIONIC__)
458 // Use lock because dirname() may write to a process global and return a
459 // pointer to that. Note that this locking strategy only works if all other
460 // callers to dirname in the process also grab this same lock, but its
461 // better than nothing. Bionic's dirname returns a thread-local buffer.
462 static std::mutex& dirname_lock = *new std::mutex();
463 std::lock_guard<std::mutex> lock(dirname_lock);
464#endif
465
466 // Note that if std::string uses copy-on-write strings, &str[0] will cause
467 // the copy to be made, so there is no chance of us accidentally writing to
468 // the storage for 'path'.
469 char* parent = dirname(&result[0]);
470
471 // In case dirname returned a pointer to a process global, copy that string
472 // before leaving the lock.
473 result.assign(parent);
474
475 return result;
476}
477
Dan Albertc007bc32015-03-16 10:08:46 -0700478} // namespace base
479} // namespace android