blob: e4407d073e2350d832255dfa06ed133db166cb4a [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>
Colin Cross2e732e22017-02-23 21:23:05 -080021#include <libgen.h>
Mark Salyzyn40a4cb42018-11-12 12:29:14 -080022#include <stdio.h>
23#include <stdlib.h>
Dan Albertaac6b7c2015-03-16 10:08:46 -070024#include <sys/stat.h>
25#include <sys/types.h>
Elliott Hughesa634a9a2016-08-23 15:53:45 -070026#include <unistd.h>
Dan Albertaac6b7c2015-03-16 10:08:46 -070027
Josh Gao58668ac2016-09-01 12:31:42 -070028#include <memory>
Colin Cross2e732e22017-02-23 21:23:05 -080029#include <mutex>
Dan Albertaac6b7c2015-03-16 10:08:46 -070030#include <string>
Elliott Hughesa634a9a2016-08-23 15:53:45 -070031#include <vector>
Dan Albertaac6b7c2015-03-16 10:08:46 -070032
Elliott Hughes7d9a4792016-07-28 15:15:28 -070033#include "android-base/logging.h"
Christopher Ferrisbf0929f2017-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 Hughesb6351622015-12-04 22:00:26 -080036#include "android-base/utf8.h"
Dan Albertaac6b7c2015-03-16 10:08:46 -070037
Elliott Hughes48f0eb52016-08-31 15:07:18 -070038#if defined(__APPLE__)
Josh Gao58668ac2016-09-01 12:31:42 -070039#include <mach-o/dyld.h>
Elliott Hughes48f0eb52016-08-31 15:07:18 -070040#endif
41#if defined(_WIN32)
Mark Salyzyn40a4cb42018-11-12 12:29:14 -080042#include <direct.h>
Elliott Hughes48f0eb52016-08-31 15:07:18 -070043#include <windows.h>
Elliott Hughes62ecbaa2017-05-15 17:31:15 -070044#define O_NOFOLLOW 0
Mark Salyzyn40a4cb42018-11-12 12:29:14 -080045#define OS_PATH_SEPARATOR '\\'
46#else
47#define OS_PATH_SEPARATOR '/'
Elliott Hughes48f0eb52016-08-31 15:07:18 -070048#endif
49
Mark Salyzyn40a4cb42018-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__)
75 const char* tmpdir = "/data/local/tmp";
76 if (access(tmpdir, R_OK | W_OK | X_OK) == 0) {
77 return tmpdir;
78 }
79 // Tests running in app context can't access /data/local/tmp,
80 // so try current directory if /data/local/tmp is not accessible.
81 return ".";
82#elif defined(_WIN32)
83 char tmp_dir[MAX_PATH];
84 DWORD result = GetTempPathA(sizeof(tmp_dir), tmp_dir);
85 CHECK_NE(result, 0ul) << "GetTempPathA failed, error: " << GetLastError();
86 CHECK_LT(result, sizeof(tmp_dir)) << "path truncated to: " << result;
87
88 // GetTempPath() returns a path with a trailing slash, but init()
89 // does not expect that, so remove it.
90 CHECK_EQ(tmp_dir[result - 1], '\\');
91 tmp_dir[result - 1] = '\0';
92 return tmp_dir;
93#else
94 return "/tmp";
95#endif
96}
97
98} // namespace
99
100TemporaryFile::TemporaryFile() {
101 init(GetSystemTempDir());
102}
103
104TemporaryFile::TemporaryFile(const std::string& tmp_dir) {
105 init(tmp_dir);
106}
107
108TemporaryFile::~TemporaryFile() {
109 if (fd != -1) {
110 close(fd);
111 }
112 if (remove_file_) {
113 unlink(path);
114 }
115}
116
117int TemporaryFile::release() {
118 int result = fd;
119 fd = -1;
120 return result;
121}
122
123void TemporaryFile::init(const std::string& tmp_dir) {
124 snprintf(path, sizeof(path), "%s%cTemporaryFile-XXXXXX", tmp_dir.c_str(), OS_PATH_SEPARATOR);
125 fd = mkstemp(path);
126}
127
128TemporaryDir::TemporaryDir() {
129 init(GetSystemTempDir());
130}
131
132TemporaryDir::~TemporaryDir() {
133 rmdir(path);
134}
135
136bool TemporaryDir::init(const std::string& tmp_dir) {
137 snprintf(path, sizeof(path), "%s%cTemporaryDir-XXXXXX", tmp_dir.c_str(), OS_PATH_SEPARATOR);
138 return (mkdtemp(path) != nullptr);
139}
140
Dan Albertaac6b7c2015-03-16 10:08:46 -0700141namespace android {
142namespace base {
143
Elliott Hughes774d7f62015-11-11 18:02:29 +0000144// Versions of standard library APIs that support UTF-8 strings.
145using namespace android::base::utf8;
146
Dan Albertaac6b7c2015-03-16 10:08:46 -0700147bool ReadFdToString(int fd, std::string* content) {
148 content->clear();
149
Elliott Hughese9ab7ad2017-03-20 19:16:18 -0700150 // Although original we had small files in mind, this code gets used for
151 // very large files too, where the std::string growth heuristics might not
152 // be suitable. https://code.google.com/p/android/issues/detail?id=258500.
153 struct stat sb;
154 if (fstat(fd, &sb) != -1 && sb.st_size > 0) {
155 content->reserve(sb.st_size);
156 }
157
Dan Albertaac6b7c2015-03-16 10:08:46 -0700158 char buf[BUFSIZ];
159 ssize_t n;
160 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], sizeof(buf)))) > 0) {
161 content->append(buf, n);
162 }
163 return (n == 0) ? true : false;
164}
165
Josh Gao8e1f0d82016-09-14 16:11:45 -0700166bool ReadFileToString(const std::string& path, std::string* content, bool follow_symlinks) {
Dan Albertaac6b7c2015-03-16 10:08:46 -0700167 content->clear();
168
Josh Gao8e1f0d82016-09-14 16:11:45 -0700169 int flags = O_RDONLY | O_CLOEXEC | O_BINARY | (follow_symlinks ? 0 : O_NOFOLLOW);
Christopher Ferrisbf0929f2017-04-05 12:09:17 -0700170 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags)));
Dan Albertaac6b7c2015-03-16 10:08:46 -0700171 if (fd == -1) {
172 return false;
173 }
Christopher Ferrisbf0929f2017-04-05 12:09:17 -0700174 return ReadFdToString(fd, content);
Dan Albertaac6b7c2015-03-16 10:08:46 -0700175}
176
177bool WriteStringToFd(const std::string& content, int fd) {
178 const char* p = content.data();
179 size_t left = content.size();
180 while (left > 0) {
181 ssize_t n = TEMP_FAILURE_RETRY(write(fd, p, left));
182 if (n == -1) {
183 return false;
184 }
185 p += n;
186 left -= n;
187 }
188 return true;
189}
190
191static bool CleanUpAfterFailedWrite(const std::string& path) {
192 // Something went wrong. Let's not leave a corrupt file lying around.
193 int saved_errno = errno;
194 unlink(path.c_str());
195 errno = saved_errno;
196 return false;
197}
198
199#if !defined(_WIN32)
200bool WriteStringToFile(const std::string& content, const std::string& path,
Josh Gao8e1f0d82016-09-14 16:11:45 -0700201 mode_t mode, uid_t owner, gid_t group,
202 bool follow_symlinks) {
203 int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY |
204 (follow_symlinks ? 0 : O_NOFOLLOW);
Christopher Ferrisbf0929f2017-04-05 12:09:17 -0700205 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode)));
Dan Albertaac6b7c2015-03-16 10:08:46 -0700206 if (fd == -1) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700207 PLOG(ERROR) << "android::WriteStringToFile open failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700208 return false;
209 }
210
211 // We do an explicit fchmod here because we assume that the caller really
212 // meant what they said and doesn't want the umask-influenced mode.
213 if (fchmod(fd, mode) == -1) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700214 PLOG(ERROR) << "android::WriteStringToFile fchmod failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700215 return CleanUpAfterFailedWrite(path);
216 }
217 if (fchown(fd, owner, group) == -1) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700218 PLOG(ERROR) << "android::WriteStringToFile fchown failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700219 return CleanUpAfterFailedWrite(path);
220 }
221 if (!WriteStringToFd(content, fd)) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700222 PLOG(ERROR) << "android::WriteStringToFile write failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700223 return CleanUpAfterFailedWrite(path);
224 }
Dan Albertaac6b7c2015-03-16 10:08:46 -0700225 return true;
226}
227#endif
228
Josh Gao8e1f0d82016-09-14 16:11:45 -0700229bool WriteStringToFile(const std::string& content, const std::string& path,
230 bool follow_symlinks) {
231 int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY |
232 (follow_symlinks ? 0 : O_NOFOLLOW);
Elliott Hughes62ecbaa2017-05-15 17:31:15 -0700233 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, 0666)));
Dan Albertaac6b7c2015-03-16 10:08:46 -0700234 if (fd == -1) {
235 return false;
236 }
Christopher Ferrisbf0929f2017-04-05 12:09:17 -0700237 return WriteStringToFd(content, fd) || CleanUpAfterFailedWrite(path);
Dan Albertaac6b7c2015-03-16 10:08:46 -0700238}
239
Elliott Hughes20abc872015-04-24 21:57:16 -0700240bool ReadFully(int fd, void* data, size_t byte_count) {
241 uint8_t* p = reinterpret_cast<uint8_t*>(data);
242 size_t remaining = byte_count;
243 while (remaining > 0) {
244 ssize_t n = TEMP_FAILURE_RETRY(read(fd, p, remaining));
245 if (n <= 0) return false;
246 p += n;
247 remaining -= n;
248 }
249 return true;
250}
251
Adam Lesinski6d6f9b32017-06-19 10:27:38 -0700252#if defined(_WIN32)
253// Windows implementation of pread. Note that this DOES move the file descriptors read position,
254// but it does so atomically.
255static ssize_t pread(int fd, void* data, size_t byte_count, off64_t offset) {
256 DWORD bytes_read;
257 OVERLAPPED overlapped;
258 memset(&overlapped, 0, sizeof(OVERLAPPED));
259 overlapped.Offset = static_cast<DWORD>(offset);
260 overlapped.OffsetHigh = static_cast<DWORD>(offset >> 32);
261 if (!ReadFile(reinterpret_cast<HANDLE>(_get_osfhandle(fd)), data, static_cast<DWORD>(byte_count),
262 &bytes_read, &overlapped)) {
263 // In case someone tries to read errno (since this is masquerading as a POSIX call)
264 errno = EIO;
265 return -1;
266 }
267 return static_cast<ssize_t>(bytes_read);
268}
269#endif
270
271bool ReadFullyAtOffset(int fd, void* data, size_t byte_count, off64_t offset) {
272 uint8_t* p = reinterpret_cast<uint8_t*>(data);
273 while (byte_count > 0) {
274 ssize_t n = TEMP_FAILURE_RETRY(pread(fd, p, byte_count, offset));
275 if (n <= 0) return false;
276 p += n;
277 byte_count -= n;
278 offset += n;
279 }
280 return true;
281}
282
Elliott Hughes20abc872015-04-24 21:57:16 -0700283bool WriteFully(int fd, const void* data, size_t byte_count) {
284 const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
285 size_t remaining = byte_count;
286 while (remaining > 0) {
287 ssize_t n = TEMP_FAILURE_RETRY(write(fd, p, remaining));
288 if (n == -1) return false;
289 p += n;
290 remaining -= n;
291 }
292 return true;
293}
294
Yabin Cui8f6a5a02016-01-29 17:25:54 -0800295bool RemoveFileIfExists(const std::string& path, std::string* err) {
296 struct stat st;
297#if defined(_WIN32)
liwugang78cea682018-07-11 13:24:49 +0800298 // TODO: Windows version can't handle symbolic links correctly.
Yabin Cui8f6a5a02016-01-29 17:25:54 -0800299 int result = stat(path.c_str(), &st);
300 bool file_type_removable = (result == 0 && S_ISREG(st.st_mode));
301#else
302 int result = lstat(path.c_str(), &st);
303 bool file_type_removable = (result == 0 && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)));
304#endif
liwugang78cea682018-07-11 13:24:49 +0800305 if (result == -1) {
306 if (errno == ENOENT || errno == ENOTDIR) return true;
307 if (err != nullptr) *err = strerror(errno);
308 return false;
309 }
310
Yabin Cui8f6a5a02016-01-29 17:25:54 -0800311 if (result == 0) {
312 if (!file_type_removable) {
313 if (err != nullptr) {
liwugang78cea682018-07-11 13:24:49 +0800314 *err = "is not a regular file or symbolic link";
Yabin Cui8f6a5a02016-01-29 17:25:54 -0800315 }
316 return false;
317 }
318 if (unlink(path.c_str()) == -1) {
319 if (err != nullptr) {
320 *err = strerror(errno);
321 }
322 return false;
323 }
324 }
325 return true;
326}
327
Elliott Hughesa634a9a2016-08-23 15:53:45 -0700328#if !defined(_WIN32)
329bool Readlink(const std::string& path, std::string* result) {
330 result->clear();
331
332 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
333 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
334 // waste memory to just start there. We add 1 so that we can recognize
335 // whether it actually fit (rather than being truncated to 4095).
336 std::vector<char> buf(4095 + 1);
337 while (true) {
338 ssize_t size = readlink(path.c_str(), &buf[0], buf.size());
339 // Unrecoverable error?
340 if (size == -1) return false;
341 // It fit! (If size == buf.size(), it may have been truncated.)
342 if (static_cast<size_t>(size) < buf.size()) {
343 result->assign(&buf[0], size);
344 return true;
345 }
346 // Double our buffer and try again.
347 buf.resize(buf.size() * 2);
348 }
349}
350#endif
351
Dimitry Ivanov4edc04f2016-09-09 10:49:21 -0700352#if !defined(_WIN32)
353bool Realpath(const std::string& path, std::string* result) {
354 result->clear();
355
356 char* realpath_buf = realpath(path.c_str(), nullptr);
357 if (realpath_buf == nullptr) {
358 return false;
359 }
360 result->assign(realpath_buf);
361 free(realpath_buf);
362 return true;
363}
364#endif
365
Elliott Hughes48f0eb52016-08-31 15:07:18 -0700366std::string GetExecutablePath() {
367#if defined(__linux__)
368 std::string path;
369 android::base::Readlink("/proc/self/exe", &path);
370 return path;
371#elif defined(__APPLE__)
Elliott Hughes48f0eb52016-08-31 15:07:18 -0700372 char path[PATH_MAX + 1];
Josh Gao58668ac2016-09-01 12:31:42 -0700373 uint32_t path_len = sizeof(path);
374 int rc = _NSGetExecutablePath(path, &path_len);
375 if (rc < 0) {
376 std::unique_ptr<char> path_buf(new char[path_len]);
377 _NSGetExecutablePath(path_buf.get(), &path_len);
378 return path_buf.get();
379 }
Elliott Hughes48f0eb52016-08-31 15:07:18 -0700380 return path;
381#elif defined(_WIN32)
382 char path[PATH_MAX + 1];
383 DWORD result = GetModuleFileName(NULL, path, sizeof(path) - 1);
384 if (result == 0 || result == sizeof(path) - 1) return "";
385 path[PATH_MAX - 1] = 0;
386 return path;
387#else
388#error unknown OS
389#endif
390}
391
Colin Cross2909be02017-02-23 17:41:56 -0800392std::string GetExecutableDirectory() {
393 return Dirname(GetExecutablePath());
394}
Colin Cross2e732e22017-02-23 21:23:05 -0800395
Colin Cross2909be02017-02-23 17:41:56 -0800396std::string Basename(const std::string& path) {
Colin Cross2e732e22017-02-23 21:23:05 -0800397 // Copy path because basename may modify the string passed in.
398 std::string result(path);
399
400#if !defined(__BIONIC__)
401 // Use lock because basename() may write to a process global and return a
402 // pointer to that. Note that this locking strategy only works if all other
403 // callers to basename in the process also grab this same lock, but its
404 // better than nothing. Bionic's basename returns a thread-local buffer.
405 static std::mutex& basename_lock = *new std::mutex();
406 std::lock_guard<std::mutex> lock(basename_lock);
407#endif
408
409 // Note that if std::string uses copy-on-write strings, &str[0] will cause
410 // the copy to be made, so there is no chance of us accidentally writing to
411 // the storage for 'path'.
412 char* name = basename(&result[0]);
413
414 // In case basename returned a pointer to a process global, copy that string
415 // before leaving the lock.
416 result.assign(name);
417
418 return result;
419}
420
421std::string Dirname(const std::string& path) {
422 // Copy path because dirname may modify the string passed in.
423 std::string result(path);
424
425#if !defined(__BIONIC__)
426 // Use lock because dirname() may write to a process global and return a
427 // pointer to that. Note that this locking strategy only works if all other
428 // callers to dirname in the process also grab this same lock, but its
429 // better than nothing. Bionic's dirname returns a thread-local buffer.
430 static std::mutex& dirname_lock = *new std::mutex();
431 std::lock_guard<std::mutex> lock(dirname_lock);
432#endif
433
434 // Note that if std::string uses copy-on-write strings, &str[0] will cause
435 // the copy to be made, so there is no chance of us accidentally writing to
436 // the storage for 'path'.
437 char* parent = dirname(&result[0]);
438
439 // In case dirname returned a pointer to a process global, copy that string
440 // before leaving the lock.
441 result.assign(parent);
442
443 return result;
444}
445
Dan Albertaac6b7c2015-03-16 10:08:46 -0700446} // namespace base
447} // namespace android