blob: 7a147115e4115672aab75fc75a6233f17dbc8b95 [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 Salyzynf2e76152018-11-13 13:38:33 -0800137 auto callback = [](const char* child, const struct stat*, int file_type, struct FTW*) -> int {
138 switch (file_type) {
139 case FTW_D:
140 case FTW_DP:
141 case FTW_DNR:
142 if (rmdir(child) == -1) {
143 PLOG(ERROR) << "rmdir " << child;
144 }
145 break;
146 case FTW_NS:
147 default:
148 if (rmdir(child) != -1) break;
149 // FALLTHRU (for gcc, lint, pcc, etc; and following for clang)
150 FALLTHROUGH_INTENDED;
151 case FTW_F:
152 case FTW_SL:
153 case FTW_SLN:
154 if (unlink(child) == -1) {
155 PLOG(ERROR) << "unlink " << child;
156 }
157 break;
158 }
159 return 0;
160 };
161
162 nftw(path, callback, 128, FTW_DEPTH | FTW_MOUNT | FTW_PHYS);
Mark Salyzyn40a4cb42018-11-12 12:29:14 -0800163}
164
165bool TemporaryDir::init(const std::string& tmp_dir) {
166 snprintf(path, sizeof(path), "%s%cTemporaryDir-XXXXXX", tmp_dir.c_str(), OS_PATH_SEPARATOR);
167 return (mkdtemp(path) != nullptr);
168}
169
Dan Albertaac6b7c2015-03-16 10:08:46 -0700170namespace android {
171namespace base {
172
Elliott Hughes774d7f62015-11-11 18:02:29 +0000173// Versions of standard library APIs that support UTF-8 strings.
174using namespace android::base::utf8;
175
Dan Albertaac6b7c2015-03-16 10:08:46 -0700176bool ReadFdToString(int fd, std::string* content) {
177 content->clear();
178
Elliott Hughese9ab7ad2017-03-20 19:16:18 -0700179 // Although original we had small files in mind, this code gets used for
180 // very large files too, where the std::string growth heuristics might not
181 // be suitable. https://code.google.com/p/android/issues/detail?id=258500.
182 struct stat sb;
183 if (fstat(fd, &sb) != -1 && sb.st_size > 0) {
184 content->reserve(sb.st_size);
185 }
186
Dan Albertaac6b7c2015-03-16 10:08:46 -0700187 char buf[BUFSIZ];
188 ssize_t n;
189 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], sizeof(buf)))) > 0) {
190 content->append(buf, n);
191 }
192 return (n == 0) ? true : false;
193}
194
Josh Gao8e1f0d82016-09-14 16:11:45 -0700195bool ReadFileToString(const std::string& path, std::string* content, bool follow_symlinks) {
Dan Albertaac6b7c2015-03-16 10:08:46 -0700196 content->clear();
197
Josh Gao8e1f0d82016-09-14 16:11:45 -0700198 int flags = O_RDONLY | O_CLOEXEC | O_BINARY | (follow_symlinks ? 0 : O_NOFOLLOW);
Christopher Ferrisbf0929f2017-04-05 12:09:17 -0700199 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags)));
Dan Albertaac6b7c2015-03-16 10:08:46 -0700200 if (fd == -1) {
201 return false;
202 }
Christopher Ferrisbf0929f2017-04-05 12:09:17 -0700203 return ReadFdToString(fd, content);
Dan Albertaac6b7c2015-03-16 10:08:46 -0700204}
205
206bool WriteStringToFd(const std::string& content, int fd) {
207 const char* p = content.data();
208 size_t left = content.size();
209 while (left > 0) {
210 ssize_t n = TEMP_FAILURE_RETRY(write(fd, p, left));
211 if (n == -1) {
212 return false;
213 }
214 p += n;
215 left -= n;
216 }
217 return true;
218}
219
220static bool CleanUpAfterFailedWrite(const std::string& path) {
221 // Something went wrong. Let's not leave a corrupt file lying around.
222 int saved_errno = errno;
223 unlink(path.c_str());
224 errno = saved_errno;
225 return false;
226}
227
228#if !defined(_WIN32)
229bool WriteStringToFile(const std::string& content, const std::string& path,
Josh Gao8e1f0d82016-09-14 16:11:45 -0700230 mode_t mode, uid_t owner, gid_t group,
231 bool follow_symlinks) {
232 int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY |
233 (follow_symlinks ? 0 : O_NOFOLLOW);
Christopher Ferrisbf0929f2017-04-05 12:09:17 -0700234 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode)));
Dan Albertaac6b7c2015-03-16 10:08:46 -0700235 if (fd == -1) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700236 PLOG(ERROR) << "android::WriteStringToFile open failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700237 return false;
238 }
239
240 // We do an explicit fchmod here because we assume that the caller really
241 // meant what they said and doesn't want the umask-influenced mode.
242 if (fchmod(fd, mode) == -1) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700243 PLOG(ERROR) << "android::WriteStringToFile fchmod failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700244 return CleanUpAfterFailedWrite(path);
245 }
246 if (fchown(fd, owner, group) == -1) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700247 PLOG(ERROR) << "android::WriteStringToFile fchown failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700248 return CleanUpAfterFailedWrite(path);
249 }
250 if (!WriteStringToFd(content, fd)) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700251 PLOG(ERROR) << "android::WriteStringToFile write failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700252 return CleanUpAfterFailedWrite(path);
253 }
Dan Albertaac6b7c2015-03-16 10:08:46 -0700254 return true;
255}
256#endif
257
Josh Gao8e1f0d82016-09-14 16:11:45 -0700258bool WriteStringToFile(const std::string& content, const std::string& path,
259 bool follow_symlinks) {
260 int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY |
261 (follow_symlinks ? 0 : O_NOFOLLOW);
Elliott Hughes62ecbaa2017-05-15 17:31:15 -0700262 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, 0666)));
Dan Albertaac6b7c2015-03-16 10:08:46 -0700263 if (fd == -1) {
264 return false;
265 }
Christopher Ferrisbf0929f2017-04-05 12:09:17 -0700266 return WriteStringToFd(content, fd) || CleanUpAfterFailedWrite(path);
Dan Albertaac6b7c2015-03-16 10:08:46 -0700267}
268
Elliott Hughes20abc872015-04-24 21:57:16 -0700269bool ReadFully(int fd, void* data, size_t byte_count) {
270 uint8_t* p = reinterpret_cast<uint8_t*>(data);
271 size_t remaining = byte_count;
272 while (remaining > 0) {
273 ssize_t n = TEMP_FAILURE_RETRY(read(fd, p, remaining));
274 if (n <= 0) return false;
275 p += n;
276 remaining -= n;
277 }
278 return true;
279}
280
Adam Lesinski6d6f9b32017-06-19 10:27:38 -0700281#if defined(_WIN32)
282// Windows implementation of pread. Note that this DOES move the file descriptors read position,
283// but it does so atomically.
284static ssize_t pread(int fd, void* data, size_t byte_count, off64_t offset) {
285 DWORD bytes_read;
286 OVERLAPPED overlapped;
287 memset(&overlapped, 0, sizeof(OVERLAPPED));
288 overlapped.Offset = static_cast<DWORD>(offset);
289 overlapped.OffsetHigh = static_cast<DWORD>(offset >> 32);
290 if (!ReadFile(reinterpret_cast<HANDLE>(_get_osfhandle(fd)), data, static_cast<DWORD>(byte_count),
291 &bytes_read, &overlapped)) {
292 // In case someone tries to read errno (since this is masquerading as a POSIX call)
293 errno = EIO;
294 return -1;
295 }
296 return static_cast<ssize_t>(bytes_read);
297}
298#endif
299
300bool ReadFullyAtOffset(int fd, void* data, size_t byte_count, off64_t offset) {
301 uint8_t* p = reinterpret_cast<uint8_t*>(data);
302 while (byte_count > 0) {
303 ssize_t n = TEMP_FAILURE_RETRY(pread(fd, p, byte_count, offset));
304 if (n <= 0) return false;
305 p += n;
306 byte_count -= n;
307 offset += n;
308 }
309 return true;
310}
311
Elliott Hughes20abc872015-04-24 21:57:16 -0700312bool WriteFully(int fd, const void* data, size_t byte_count) {
313 const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
314 size_t remaining = byte_count;
315 while (remaining > 0) {
316 ssize_t n = TEMP_FAILURE_RETRY(write(fd, p, remaining));
317 if (n == -1) return false;
318 p += n;
319 remaining -= n;
320 }
321 return true;
322}
323
Yabin Cui8f6a5a02016-01-29 17:25:54 -0800324bool RemoveFileIfExists(const std::string& path, std::string* err) {
325 struct stat st;
326#if defined(_WIN32)
liwugang78cea682018-07-11 13:24:49 +0800327 // TODO: Windows version can't handle symbolic links correctly.
Yabin Cui8f6a5a02016-01-29 17:25:54 -0800328 int result = stat(path.c_str(), &st);
329 bool file_type_removable = (result == 0 && S_ISREG(st.st_mode));
330#else
331 int result = lstat(path.c_str(), &st);
332 bool file_type_removable = (result == 0 && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)));
333#endif
liwugang78cea682018-07-11 13:24:49 +0800334 if (result == -1) {
335 if (errno == ENOENT || errno == ENOTDIR) return true;
336 if (err != nullptr) *err = strerror(errno);
337 return false;
338 }
339
Yabin Cui8f6a5a02016-01-29 17:25:54 -0800340 if (result == 0) {
341 if (!file_type_removable) {
342 if (err != nullptr) {
liwugang78cea682018-07-11 13:24:49 +0800343 *err = "is not a regular file or symbolic link";
Yabin Cui8f6a5a02016-01-29 17:25:54 -0800344 }
345 return false;
346 }
347 if (unlink(path.c_str()) == -1) {
348 if (err != nullptr) {
349 *err = strerror(errno);
350 }
351 return false;
352 }
353 }
354 return true;
355}
356
Elliott Hughesa634a9a2016-08-23 15:53:45 -0700357#if !defined(_WIN32)
358bool Readlink(const std::string& path, std::string* result) {
359 result->clear();
360
361 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
362 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
363 // waste memory to just start there. We add 1 so that we can recognize
364 // whether it actually fit (rather than being truncated to 4095).
365 std::vector<char> buf(4095 + 1);
366 while (true) {
367 ssize_t size = readlink(path.c_str(), &buf[0], buf.size());
368 // Unrecoverable error?
369 if (size == -1) return false;
370 // It fit! (If size == buf.size(), it may have been truncated.)
371 if (static_cast<size_t>(size) < buf.size()) {
372 result->assign(&buf[0], size);
373 return true;
374 }
375 // Double our buffer and try again.
376 buf.resize(buf.size() * 2);
377 }
378}
379#endif
380
Dimitry Ivanov4edc04f2016-09-09 10:49:21 -0700381#if !defined(_WIN32)
382bool Realpath(const std::string& path, std::string* result) {
383 result->clear();
384
385 char* realpath_buf = realpath(path.c_str(), nullptr);
386 if (realpath_buf == nullptr) {
387 return false;
388 }
389 result->assign(realpath_buf);
390 free(realpath_buf);
391 return true;
392}
393#endif
394
Elliott Hughes48f0eb52016-08-31 15:07:18 -0700395std::string GetExecutablePath() {
396#if defined(__linux__)
397 std::string path;
398 android::base::Readlink("/proc/self/exe", &path);
399 return path;
400#elif defined(__APPLE__)
Elliott Hughes48f0eb52016-08-31 15:07:18 -0700401 char path[PATH_MAX + 1];
Josh Gao58668ac2016-09-01 12:31:42 -0700402 uint32_t path_len = sizeof(path);
403 int rc = _NSGetExecutablePath(path, &path_len);
404 if (rc < 0) {
405 std::unique_ptr<char> path_buf(new char[path_len]);
406 _NSGetExecutablePath(path_buf.get(), &path_len);
407 return path_buf.get();
408 }
Elliott Hughes48f0eb52016-08-31 15:07:18 -0700409 return path;
410#elif defined(_WIN32)
411 char path[PATH_MAX + 1];
412 DWORD result = GetModuleFileName(NULL, path, sizeof(path) - 1);
413 if (result == 0 || result == sizeof(path) - 1) return "";
414 path[PATH_MAX - 1] = 0;
415 return path;
416#else
417#error unknown OS
418#endif
419}
420
Colin Cross2909be02017-02-23 17:41:56 -0800421std::string GetExecutableDirectory() {
422 return Dirname(GetExecutablePath());
423}
Colin Cross2e732e22017-02-23 21:23:05 -0800424
Colin Cross2909be02017-02-23 17:41:56 -0800425std::string Basename(const std::string& path) {
Colin Cross2e732e22017-02-23 21:23:05 -0800426 // Copy path because basename may modify the string passed in.
427 std::string result(path);
428
429#if !defined(__BIONIC__)
430 // Use lock because basename() may write to a process global and return a
431 // pointer to that. Note that this locking strategy only works if all other
432 // callers to basename in the process also grab this same lock, but its
433 // better than nothing. Bionic's basename returns a thread-local buffer.
434 static std::mutex& basename_lock = *new std::mutex();
435 std::lock_guard<std::mutex> lock(basename_lock);
436#endif
437
438 // Note that if std::string uses copy-on-write strings, &str[0] will cause
439 // the copy to be made, so there is no chance of us accidentally writing to
440 // the storage for 'path'.
441 char* name = basename(&result[0]);
442
443 // In case basename returned a pointer to a process global, copy that string
444 // before leaving the lock.
445 result.assign(name);
446
447 return result;
448}
449
450std::string Dirname(const std::string& path) {
451 // Copy path because dirname may modify the string passed in.
452 std::string result(path);
453
454#if !defined(__BIONIC__)
455 // Use lock because dirname() may write to a process global and return a
456 // pointer to that. Note that this locking strategy only works if all other
457 // callers to dirname in the process also grab this same lock, but its
458 // better than nothing. Bionic's dirname returns a thread-local buffer.
459 static std::mutex& dirname_lock = *new std::mutex();
460 std::lock_guard<std::mutex> lock(dirname_lock);
461#endif
462
463 // Note that if std::string uses copy-on-write strings, &str[0] will cause
464 // the copy to be made, so there is no chance of us accidentally writing to
465 // the storage for 'path'.
466 char* parent = dirname(&result[0]);
467
468 // In case dirname returned a pointer to a process global, copy that string
469 // before leaving the lock.
470 result.assign(parent);
471
472 return result;
473}
474
Dan Albertaac6b7c2015-03-16 10:08:46 -0700475} // namespace base
476} // namespace android