blob: f71773bb398032e5c5393caf7bc04c370c45645a [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>
Florian Mayerc08f3d42018-10-23 15:56:28 +010025#include <string.h>
Elliott Hughes3e6e4422022-05-26 16:37:25 -070026#include <sys/param.h>
Dan Albertaac6b7c2015-03-16 10:08:46 -070027#include <sys/stat.h>
28#include <sys/types.h>
Elliott Hughesa634a9a2016-08-23 15:53:45 -070029#include <unistd.h>
Dan Albertaac6b7c2015-03-16 10:08:46 -070030
Josh Gao58668ac2016-09-01 12:31:42 -070031#include <memory>
Colin Cross2e732e22017-02-23 21:23:05 -080032#include <mutex>
Dan Albertaac6b7c2015-03-16 10:08:46 -070033#include <string>
Elliott Hughesa634a9a2016-08-23 15:53:45 -070034#include <vector>
Dan Albertaac6b7c2015-03-16 10:08:46 -070035
Elliott Hughes48f0eb52016-08-31 15:07:18 -070036#if defined(__APPLE__)
Josh Gao58668ac2016-09-01 12:31:42 -070037#include <mach-o/dyld.h>
Elliott Hughes48f0eb52016-08-31 15:07:18 -070038#endif
39#if defined(_WIN32)
Mark Salyzyn40a4cb42018-11-12 12:29:14 -080040#include <direct.h>
Elliott Hughes48f0eb52016-08-31 15:07:18 -070041#include <windows.h>
Elliott Hughes62ecbaa2017-05-15 17:31:15 -070042#define O_NOFOLLOW 0
Mark Salyzyn40a4cb42018-11-12 12:29:14 -080043#define OS_PATH_SEPARATOR '\\'
44#else
45#define OS_PATH_SEPARATOR '/'
Elliott Hughes48f0eb52016-08-31 15:07:18 -070046#endif
47
Mark Salyzynf2e76152018-11-13 13:38:33 -080048#include "android-base/logging.h" // and must be after windows.h for ERROR
49#include "android-base/macros.h" // For TEMP_FAILURE_RETRY on Darwin.
50#include "android-base/unique_fd.h"
51#include "android-base/utf8.h"
52
Alex Buynytskyyab0407f2019-09-27 11:11:24 -070053namespace {
54
Mark Salyzyn40a4cb42018-11-12 12:29:14 -080055#ifdef _WIN32
Alex Buynytskyyab0407f2019-09-27 11:11:24 -070056static int mkstemp(char* name_template, size_t size_in_chars) {
Alex Buynytskyy19ba0882019-10-02 16:27:22 -070057 std::wstring path;
58 CHECK(android::base::UTF8ToWide(name_template, &path))
59 << "path can't be converted to wchar: " << name_template;
60 if (_wmktemp_s(path.data(), path.size() + 1) != 0) {
Mark Salyzyn40a4cb42018-11-12 12:29:14 -080061 return -1;
62 }
Alex Buynytskyyab0407f2019-09-27 11:11:24 -070063
Mark Salyzyn40a4cb42018-11-12 12:29:14 -080064 // Use open() to match the close() that TemporaryFile's destructor does.
65 // Use O_BINARY to match base file APIs.
Alex Buynytskyy19ba0882019-10-02 16:27:22 -070066 int fd = _wopen(path.c_str(), O_CREAT | O_EXCL | O_RDWR | O_BINARY, S_IRUSR | S_IWUSR);
67 if (fd < 0) {
68 return -1;
69 }
70
71 std::string path_utf8;
72 CHECK(android::base::WideToUTF8(path, &path_utf8)) << "path can't be converted to utf8";
73 CHECK(strcpy_s(name_template, size_in_chars, path_utf8.c_str()) == 0)
74 << "utf8 path can't be assigned back to name_template";
75
76 return fd;
Mark Salyzyn40a4cb42018-11-12 12:29:14 -080077}
78
Alex Buynytskyyab0407f2019-09-27 11:11:24 -070079static char* mkdtemp(char* name_template, size_t size_in_chars) {
Alex Buynytskyy19ba0882019-10-02 16:27:22 -070080 std::wstring path;
81 CHECK(android::base::UTF8ToWide(name_template, &path))
82 << "path can't be converted to wchar: " << name_template;
83
84 if (_wmktemp_s(path.data(), path.size() + 1) != 0) {
Mark Salyzyn40a4cb42018-11-12 12:29:14 -080085 return nullptr;
86 }
Alex Buynytskyyab0407f2019-09-27 11:11:24 -070087
Alex Buynytskyy19ba0882019-10-02 16:27:22 -070088 if (_wmkdir(path.c_str()) != 0) {
Mark Salyzyn40a4cb42018-11-12 12:29:14 -080089 return nullptr;
90 }
Alex Buynytskyy19ba0882019-10-02 16:27:22 -070091
92 std::string path_utf8;
93 CHECK(android::base::WideToUTF8(path, &path_utf8)) << "path can't be converted to utf8";
94 CHECK(strcpy_s(name_template, size_in_chars, path_utf8.c_str()) == 0)
95 << "utf8 path can't be assigned back to name_template";
96
97 return name_template;
Mark Salyzyn40a4cb42018-11-12 12:29:14 -080098}
99#endif
100
Mark Salyzyn40a4cb42018-11-12 12:29:14 -0800101std::string GetSystemTempDir() {
102#if defined(__ANDROID__)
Mark Salyzyn00a68032018-11-13 15:34:38 -0800103 const auto* tmpdir = getenv("TMPDIR");
104 if (tmpdir == nullptr) tmpdir = "/data/local/tmp";
Mark Salyzyn40a4cb42018-11-12 12:29:14 -0800105 if (access(tmpdir, R_OK | W_OK | X_OK) == 0) {
106 return tmpdir;
107 }
108 // Tests running in app context can't access /data/local/tmp,
109 // so try current directory if /data/local/tmp is not accessible.
110 return ".";
111#elif defined(_WIN32)
Alex Buynytskyyab0407f2019-09-27 11:11:24 -0700112 wchar_t tmp_dir_w[MAX_PATH];
113 DWORD result = GetTempPathW(std::size(tmp_dir_w), tmp_dir_w); // checks TMP env
114 CHECK_NE(result, 0ul) << "GetTempPathW failed, error: " << GetLastError();
115 CHECK_LT(result, std::size(tmp_dir_w)) << "path truncated to: " << result;
Mark Salyzyn40a4cb42018-11-12 12:29:14 -0800116
117 // GetTempPath() returns a path with a trailing slash, but init()
118 // does not expect that, so remove it.
Alex Buynytskyyab0407f2019-09-27 11:11:24 -0700119 if (tmp_dir_w[result - 1] == L'\\') {
120 tmp_dir_w[result - 1] = L'\0';
121 }
122
123 std::string tmp_dir;
124 CHECK(android::base::WideToUTF8(tmp_dir_w, &tmp_dir)) << "path can't be converted to utf8";
125
Mark Salyzyn40a4cb42018-11-12 12:29:14 -0800126 return tmp_dir;
127#else
Mark Salyzyn00a68032018-11-13 15:34:38 -0800128 const auto* tmpdir = getenv("TMPDIR");
129 if (tmpdir == nullptr) tmpdir = "/tmp";
130 return tmpdir;
Mark Salyzyn40a4cb42018-11-12 12:29:14 -0800131#endif
132}
133
134} // namespace
135
136TemporaryFile::TemporaryFile() {
137 init(GetSystemTempDir());
138}
139
140TemporaryFile::TemporaryFile(const std::string& tmp_dir) {
141 init(tmp_dir);
142}
143
144TemporaryFile::~TemporaryFile() {
145 if (fd != -1) {
146 close(fd);
147 }
148 if (remove_file_) {
149 unlink(path);
150 }
151}
152
153int TemporaryFile::release() {
154 int result = fd;
155 fd = -1;
156 return result;
157}
158
159void TemporaryFile::init(const std::string& tmp_dir) {
160 snprintf(path, sizeof(path), "%s%cTemporaryFile-XXXXXX", tmp_dir.c_str(), OS_PATH_SEPARATOR);
Alex Buynytskyyab0407f2019-09-27 11:11:24 -0700161#if defined(_WIN32)
162 fd = mkstemp(path, sizeof(path));
163#else
Mark Salyzyn40a4cb42018-11-12 12:29:14 -0800164 fd = mkstemp(path);
Alex Buynytskyyab0407f2019-09-27 11:11:24 -0700165#endif
Mark Salyzyn40a4cb42018-11-12 12:29:14 -0800166}
167
168TemporaryDir::TemporaryDir() {
169 init(GetSystemTempDir());
170}
171
172TemporaryDir::~TemporaryDir() {
Mark Salyzynb6f6a202018-11-13 13:38:33 -0800173 if (!remove_dir_and_contents_) return;
174
Mark Salyzynf2e76152018-11-13 13:38:33 -0800175 auto callback = [](const char* child, const struct stat*, int file_type, struct FTW*) -> int {
176 switch (file_type) {
177 case FTW_D:
178 case FTW_DP:
179 case FTW_DNR:
180 if (rmdir(child) == -1) {
181 PLOG(ERROR) << "rmdir " << child;
182 }
183 break;
184 case FTW_NS:
185 default:
186 if (rmdir(child) != -1) break;
187 // FALLTHRU (for gcc, lint, pcc, etc; and following for clang)
188 FALLTHROUGH_INTENDED;
189 case FTW_F:
190 case FTW_SL:
191 case FTW_SLN:
192 if (unlink(child) == -1) {
193 PLOG(ERROR) << "unlink " << child;
194 }
195 break;
196 }
197 return 0;
198 };
199
200 nftw(path, callback, 128, FTW_DEPTH | FTW_MOUNT | FTW_PHYS);
Mark Salyzyn40a4cb42018-11-12 12:29:14 -0800201}
202
203bool TemporaryDir::init(const std::string& tmp_dir) {
204 snprintf(path, sizeof(path), "%s%cTemporaryDir-XXXXXX", tmp_dir.c_str(), OS_PATH_SEPARATOR);
Alex Buynytskyyab0407f2019-09-27 11:11:24 -0700205#if defined(_WIN32)
206 return (mkdtemp(path, sizeof(path)) != nullptr);
207#else
Mark Salyzyn40a4cb42018-11-12 12:29:14 -0800208 return (mkdtemp(path) != nullptr);
Alex Buynytskyyab0407f2019-09-27 11:11:24 -0700209#endif
Mark Salyzyn40a4cb42018-11-12 12:29:14 -0800210}
211
Dan Albertaac6b7c2015-03-16 10:08:46 -0700212namespace android {
213namespace base {
214
Elliott Hughes774d7f62015-11-11 18:02:29 +0000215// Versions of standard library APIs that support UTF-8 strings.
216using namespace android::base::utf8;
217
Josh Gaoe4401992019-04-25 14:04:57 -0700218bool ReadFdToString(borrowed_fd fd, std::string* content) {
Dan Albertaac6b7c2015-03-16 10:08:46 -0700219 content->clear();
220
Elliott Hughese9ab7ad2017-03-20 19:16:18 -0700221 // Although original we had small files in mind, this code gets used for
222 // very large files too, where the std::string growth heuristics might not
223 // be suitable. https://code.google.com/p/android/issues/detail?id=258500.
224 struct stat sb;
Josh Gaoe4401992019-04-25 14:04:57 -0700225 if (fstat(fd.get(), &sb) != -1 && sb.st_size > 0) {
Elliott Hughese9ab7ad2017-03-20 19:16:18 -0700226 content->reserve(sb.st_size);
227 }
228
Frederick Mayleafb16602023-01-06 15:38:21 -0800229 char buf[4096] __attribute__((__uninitialized__));
Dan Albertaac6b7c2015-03-16 10:08:46 -0700230 ssize_t n;
Josh Gaoe4401992019-04-25 14:04:57 -0700231 while ((n = TEMP_FAILURE_RETRY(read(fd.get(), &buf[0], sizeof(buf)))) > 0) {
Dan Albertaac6b7c2015-03-16 10:08:46 -0700232 content->append(buf, n);
233 }
234 return (n == 0) ? true : false;
235}
236
Josh Gao8e1f0d82016-09-14 16:11:45 -0700237bool ReadFileToString(const std::string& path, std::string* content, bool follow_symlinks) {
Dan Albertaac6b7c2015-03-16 10:08:46 -0700238 content->clear();
239
Josh Gao8e1f0d82016-09-14 16:11:45 -0700240 int flags = O_RDONLY | O_CLOEXEC | O_BINARY | (follow_symlinks ? 0 : O_NOFOLLOW);
Christopher Ferrisbf0929f2017-04-05 12:09:17 -0700241 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags)));
Dan Albertaac6b7c2015-03-16 10:08:46 -0700242 if (fd == -1) {
243 return false;
244 }
Christopher Ferrisbf0929f2017-04-05 12:09:17 -0700245 return ReadFdToString(fd, content);
Dan Albertaac6b7c2015-03-16 10:08:46 -0700246}
247
Chris Weirfc25fae2022-11-15 16:15:14 -0800248bool WriteStringToFd(std::string_view content, borrowed_fd fd) {
Dan Albertaac6b7c2015-03-16 10:08:46 -0700249 const char* p = content.data();
250 size_t left = content.size();
251 while (left > 0) {
Josh Gaoe4401992019-04-25 14:04:57 -0700252 ssize_t n = TEMP_FAILURE_RETRY(write(fd.get(), p, left));
Dan Albertaac6b7c2015-03-16 10:08:46 -0700253 if (n == -1) {
254 return false;
255 }
256 p += n;
257 left -= n;
258 }
259 return true;
260}
261
262static bool CleanUpAfterFailedWrite(const std::string& path) {
263 // Something went wrong. Let's not leave a corrupt file lying around.
264 int saved_errno = errno;
265 unlink(path.c_str());
266 errno = saved_errno;
267 return false;
268}
269
270#if !defined(_WIN32)
271bool WriteStringToFile(const std::string& content, const std::string& path,
Josh Gao8e1f0d82016-09-14 16:11:45 -0700272 mode_t mode, uid_t owner, gid_t group,
273 bool follow_symlinks) {
274 int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY |
275 (follow_symlinks ? 0 : O_NOFOLLOW);
Christopher Ferrisbf0929f2017-04-05 12:09:17 -0700276 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode)));
Dan Albertaac6b7c2015-03-16 10:08:46 -0700277 if (fd == -1) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700278 PLOG(ERROR) << "android::WriteStringToFile open failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700279 return false;
280 }
281
282 // We do an explicit fchmod here because we assume that the caller really
283 // meant what they said and doesn't want the umask-influenced mode.
284 if (fchmod(fd, mode) == -1) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700285 PLOG(ERROR) << "android::WriteStringToFile fchmod failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700286 return CleanUpAfterFailedWrite(path);
287 }
288 if (fchown(fd, owner, group) == -1) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700289 PLOG(ERROR) << "android::WriteStringToFile fchown failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700290 return CleanUpAfterFailedWrite(path);
291 }
292 if (!WriteStringToFd(content, fd)) {
Elliott Hughes7d9a4792016-07-28 15:15:28 -0700293 PLOG(ERROR) << "android::WriteStringToFile write failed";
Dan Albertaac6b7c2015-03-16 10:08:46 -0700294 return CleanUpAfterFailedWrite(path);
295 }
Dan Albertaac6b7c2015-03-16 10:08:46 -0700296 return true;
297}
298#endif
299
Josh Gao8e1f0d82016-09-14 16:11:45 -0700300bool WriteStringToFile(const std::string& content, const std::string& path,
301 bool follow_symlinks) {
302 int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY |
303 (follow_symlinks ? 0 : O_NOFOLLOW);
Elliott Hughes62ecbaa2017-05-15 17:31:15 -0700304 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, 0666)));
Dan Albertaac6b7c2015-03-16 10:08:46 -0700305 if (fd == -1) {
306 return false;
307 }
Christopher Ferrisbf0929f2017-04-05 12:09:17 -0700308 return WriteStringToFd(content, fd) || CleanUpAfterFailedWrite(path);
Dan Albertaac6b7c2015-03-16 10:08:46 -0700309}
310
Josh Gaoe4401992019-04-25 14:04:57 -0700311bool ReadFully(borrowed_fd fd, void* data, size_t byte_count) {
Elliott Hughes20abc872015-04-24 21:57:16 -0700312 uint8_t* p = reinterpret_cast<uint8_t*>(data);
313 size_t remaining = byte_count;
314 while (remaining > 0) {
Josh Gaoe4401992019-04-25 14:04:57 -0700315 ssize_t n = TEMP_FAILURE_RETRY(read(fd.get(), p, remaining));
Tomasz Wasilczyk4b992a82023-11-13 13:40:32 -0800316 if (n == 0) { // EOF
317 errno = ENODATA;
318 return false;
319 }
320 if (n == -1) return false;
Elliott Hughes20abc872015-04-24 21:57:16 -0700321 p += n;
322 remaining -= n;
323 }
324 return true;
325}
326
Adam Lesinski6d6f9b32017-06-19 10:27:38 -0700327#if defined(_WIN32)
328// Windows implementation of pread. Note that this DOES move the file descriptors read position,
329// but it does so atomically.
Josh Gaoe4401992019-04-25 14:04:57 -0700330static ssize_t pread(borrowed_fd fd, void* data, size_t byte_count, off64_t offset) {
Adam Lesinski6d6f9b32017-06-19 10:27:38 -0700331 DWORD bytes_read;
332 OVERLAPPED overlapped;
333 memset(&overlapped, 0, sizeof(OVERLAPPED));
334 overlapped.Offset = static_cast<DWORD>(offset);
335 overlapped.OffsetHigh = static_cast<DWORD>(offset >> 32);
Josh Gaoe4401992019-04-25 14:04:57 -0700336 if (!ReadFile(reinterpret_cast<HANDLE>(_get_osfhandle(fd.get())), data,
337 static_cast<DWORD>(byte_count), &bytes_read, &overlapped)) {
Adam Lesinski6d6f9b32017-06-19 10:27:38 -0700338 // In case someone tries to read errno (since this is masquerading as a POSIX call)
339 errno = EIO;
340 return -1;
341 }
342 return static_cast<ssize_t>(bytes_read);
343}
Kelvin Zhanga095db02022-11-02 09:51:21 -0700344
345static ssize_t pwrite(borrowed_fd fd, const void* data, size_t byte_count, off64_t offset) {
346 DWORD bytes_written;
347 OVERLAPPED overlapped;
348 memset(&overlapped, 0, sizeof(OVERLAPPED));
349 overlapped.Offset = static_cast<DWORD>(offset);
350 overlapped.OffsetHigh = static_cast<DWORD>(offset >> 32);
351 if (!WriteFile(reinterpret_cast<HANDLE>(_get_osfhandle(fd.get())), data,
352 static_cast<DWORD>(byte_count), &bytes_written, &overlapped)) {
353 // In case someone tries to read errno (since this is masquerading as a POSIX call)
354 errno = EIO;
355 return -1;
356 }
357 return static_cast<ssize_t>(bytes_written);
358}
Adam Lesinski6d6f9b32017-06-19 10:27:38 -0700359#endif
360
Josh Gaoe4401992019-04-25 14:04:57 -0700361bool ReadFullyAtOffset(borrowed_fd fd, void* data, size_t byte_count, off64_t offset) {
Adam Lesinski6d6f9b32017-06-19 10:27:38 -0700362 uint8_t* p = reinterpret_cast<uint8_t*>(data);
363 while (byte_count > 0) {
Josh Gaoe4401992019-04-25 14:04:57 -0700364 ssize_t n = TEMP_FAILURE_RETRY(pread(fd.get(), p, byte_count, offset));
Tomasz Wasilczyk4b992a82023-11-13 13:40:32 -0800365 if (n == 0) { // EOF
366 errno = ENODATA;
367 return false;
368 }
369 if (n == -1) return false;
Adam Lesinski6d6f9b32017-06-19 10:27:38 -0700370 p += n;
371 byte_count -= n;
372 offset += n;
373 }
374 return true;
375}
376
Kelvin Zhanga095db02022-11-02 09:51:21 -0700377bool WriteFullyAtOffset(borrowed_fd fd, const void* data, size_t byte_count, off64_t offset) {
378 const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
379 size_t remaining = byte_count;
380 while (remaining > 0) {
381 ssize_t n = TEMP_FAILURE_RETRY(pwrite(fd.get(), p, remaining, offset));
382 if (n == -1) return false;
383 p += n;
384 remaining -= n;
385 offset += n;
386 }
387 return true;
388}
389
Josh Gaoe4401992019-04-25 14:04:57 -0700390bool WriteFully(borrowed_fd fd, const void* data, size_t byte_count) {
Elliott Hughes20abc872015-04-24 21:57:16 -0700391 const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
392 size_t remaining = byte_count;
393 while (remaining > 0) {
Josh Gaoe4401992019-04-25 14:04:57 -0700394 ssize_t n = TEMP_FAILURE_RETRY(write(fd.get(), p, remaining));
Elliott Hughes20abc872015-04-24 21:57:16 -0700395 if (n == -1) return false;
396 p += n;
397 remaining -= n;
398 }
399 return true;
400}
401
Yabin Cui8f6a5a02016-01-29 17:25:54 -0800402bool RemoveFileIfExists(const std::string& path, std::string* err) {
403 struct stat st;
404#if defined(_WIN32)
liwugang78cea682018-07-11 13:24:49 +0800405 // TODO: Windows version can't handle symbolic links correctly.
Yabin Cui8f6a5a02016-01-29 17:25:54 -0800406 int result = stat(path.c_str(), &st);
407 bool file_type_removable = (result == 0 && S_ISREG(st.st_mode));
408#else
409 int result = lstat(path.c_str(), &st);
410 bool file_type_removable = (result == 0 && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)));
411#endif
liwugang78cea682018-07-11 13:24:49 +0800412 if (result == -1) {
413 if (errno == ENOENT || errno == ENOTDIR) return true;
414 if (err != nullptr) *err = strerror(errno);
415 return false;
416 }
417
Yabin Cui8f6a5a02016-01-29 17:25:54 -0800418 if (result == 0) {
419 if (!file_type_removable) {
420 if (err != nullptr) {
liwugang78cea682018-07-11 13:24:49 +0800421 *err = "is not a regular file or symbolic link";
Yabin Cui8f6a5a02016-01-29 17:25:54 -0800422 }
423 return false;
424 }
425 if (unlink(path.c_str()) == -1) {
426 if (err != nullptr) {
427 *err = strerror(errno);
428 }
429 return false;
430 }
431 }
432 return true;
433}
434
Elliott Hughesa634a9a2016-08-23 15:53:45 -0700435#if !defined(_WIN32)
436bool Readlink(const std::string& path, std::string* result) {
437 result->clear();
438
439 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
440 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
441 // waste memory to just start there. We add 1 so that we can recognize
442 // whether it actually fit (rather than being truncated to 4095).
443 std::vector<char> buf(4095 + 1);
444 while (true) {
445 ssize_t size = readlink(path.c_str(), &buf[0], buf.size());
446 // Unrecoverable error?
447 if (size == -1) return false;
448 // It fit! (If size == buf.size(), it may have been truncated.)
449 if (static_cast<size_t>(size) < buf.size()) {
450 result->assign(&buf[0], size);
451 return true;
452 }
453 // Double our buffer and try again.
454 buf.resize(buf.size() * 2);
455 }
456}
457#endif
458
Dimitry Ivanov4edc04f2016-09-09 10:49:21 -0700459#if !defined(_WIN32)
460bool Realpath(const std::string& path, std::string* result) {
461 result->clear();
462
Yifan Hong26fd2342019-03-21 15:20:53 -0700463 // realpath may exit with EINTR. Retry if so.
464 char* realpath_buf = nullptr;
465 do {
466 realpath_buf = realpath(path.c_str(), nullptr);
467 } while (realpath_buf == nullptr && errno == EINTR);
468
Dimitry Ivanov4edc04f2016-09-09 10:49:21 -0700469 if (realpath_buf == nullptr) {
470 return false;
471 }
472 result->assign(realpath_buf);
473 free(realpath_buf);
474 return true;
475}
476#endif
477
Elliott Hughes48f0eb52016-08-31 15:07:18 -0700478std::string GetExecutablePath() {
479#if defined(__linux__)
480 std::string path;
481 android::base::Readlink("/proc/self/exe", &path);
482 return path;
483#elif defined(__APPLE__)
Elliott Hughes48f0eb52016-08-31 15:07:18 -0700484 char path[PATH_MAX + 1];
Josh Gao58668ac2016-09-01 12:31:42 -0700485 uint32_t path_len = sizeof(path);
486 int rc = _NSGetExecutablePath(path, &path_len);
487 if (rc < 0) {
488 std::unique_ptr<char> path_buf(new char[path_len]);
489 _NSGetExecutablePath(path_buf.get(), &path_len);
490 return path_buf.get();
491 }
Elliott Hughes48f0eb52016-08-31 15:07:18 -0700492 return path;
493#elif defined(_WIN32)
494 char path[PATH_MAX + 1];
495 DWORD result = GetModuleFileName(NULL, path, sizeof(path) - 1);
496 if (result == 0 || result == sizeof(path) - 1) return "";
497 path[PATH_MAX - 1] = 0;
498 return path;
Mitchell Willsa7c91d72023-05-08 13:30:24 -0700499#elif defined(__EMSCRIPTEN__)
500 abort();
Elliott Hughes48f0eb52016-08-31 15:07:18 -0700501#else
502#error unknown OS
503#endif
504}
505
Colin Cross2909be02017-02-23 17:41:56 -0800506std::string GetExecutableDirectory() {
507 return Dirname(GetExecutablePath());
508}
Colin Cross2e732e22017-02-23 21:23:05 -0800509
Elliott Hughes91a10d92022-05-24 17:44:36 -0700510#if defined(_WIN32)
Yurii Zubrytskyi2902e102022-11-08 23:32:50 -0800511std::string Basename(std::string_view path) {
Elliott Hughes91a10d92022-05-24 17:44:36 -0700512 // TODO: how much of this is actually necessary for mingw?
513
Colin Cross2e732e22017-02-23 21:23:05 -0800514 // Copy path because basename may modify the string passed in.
515 std::string result(path);
516
Colin Cross2e732e22017-02-23 21:23:05 -0800517 // Use lock because basename() may write to a process global and return a
518 // pointer to that. Note that this locking strategy only works if all other
519 // callers to basename in the process also grab this same lock, but its
520 // better than nothing. Bionic's basename returns a thread-local buffer.
521 static std::mutex& basename_lock = *new std::mutex();
522 std::lock_guard<std::mutex> lock(basename_lock);
Colin Cross2e732e22017-02-23 21:23:05 -0800523
524 // Note that if std::string uses copy-on-write strings, &str[0] will cause
525 // the copy to be made, so there is no chance of us accidentally writing to
526 // the storage for 'path'.
527 char* name = basename(&result[0]);
528
529 // In case basename returned a pointer to a process global, copy that string
530 // before leaving the lock.
531 result.assign(name);
532
533 return result;
534}
Elliott Hughes91a10d92022-05-24 17:44:36 -0700535#else
536// Copied from bionic so that Basename() below can be portable and thread-safe.
Yurii Zubrytskyi2902e102022-11-08 23:32:50 -0800537static int _basename_r(const char* path, size_t path_size, char* buffer, size_t buffer_size) {
Elliott Hughes91a10d92022-05-24 17:44:36 -0700538 const char* startp = nullptr;
539 const char* endp = nullptr;
540 int len;
541 int result;
542
543 // Empty or NULL string gets treated as ".".
Yurii Zubrytskyi2902e102022-11-08 23:32:50 -0800544 if (path == nullptr || path_size == 0) {
Elliott Hughes91a10d92022-05-24 17:44:36 -0700545 startp = ".";
546 len = 1;
547 goto Exit;
548 }
549
550 // Strip trailing slashes.
Yurii Zubrytskyi2902e102022-11-08 23:32:50 -0800551 endp = path + path_size - 1;
Elliott Hughes91a10d92022-05-24 17:44:36 -0700552 while (endp > path && *endp == '/') {
553 endp--;
554 }
555
556 // All slashes becomes "/".
557 if (endp == path && *endp == '/') {
558 startp = "/";
559 len = 1;
560 goto Exit;
561 }
562
563 // Find the start of the base.
564 startp = endp;
565 while (startp > path && *(startp - 1) != '/') {
566 startp--;
567 }
568
569 len = endp - startp +1;
570
571 Exit:
572 result = len;
573 if (buffer == nullptr) {
574 return result;
575 }
576 if (len > static_cast<int>(buffer_size) - 1) {
577 len = buffer_size - 1;
578 result = -1;
579 errno = ERANGE;
580 }
581
582 if (len >= 0) {
583 memcpy(buffer, startp, len);
584 buffer[len] = 0;
585 }
586 return result;
587}
Yurii Zubrytskyi2902e102022-11-08 23:32:50 -0800588std::string Basename(std::string_view path) {
589 char buf[PATH_MAX] __attribute__((__uninitialized__));
590 const auto size = _basename_r(path.data(), path.size(), buf, sizeof(buf));
591 return size > 0 ? std::string(buf, size) : std::string();
Elliott Hughes91a10d92022-05-24 17:44:36 -0700592}
593#endif
Colin Cross2e732e22017-02-23 21:23:05 -0800594
Elliott Hughes3e6e4422022-05-26 16:37:25 -0700595#if defined(_WIN32)
Yurii Zubrytskyi2902e102022-11-08 23:32:50 -0800596std::string Dirname(std::string_view path) {
Elliott Hughes3e6e4422022-05-26 16:37:25 -0700597 // TODO: how much of this is actually necessary for mingw?
598
Colin Cross2e732e22017-02-23 21:23:05 -0800599 // Copy path because dirname may modify the string passed in.
600 std::string result(path);
601
Colin Cross2e732e22017-02-23 21:23:05 -0800602 // Use lock because dirname() may write to a process global and return a
603 // pointer to that. Note that this locking strategy only works if all other
604 // callers to dirname in the process also grab this same lock, but its
605 // better than nothing. Bionic's dirname returns a thread-local buffer.
606 static std::mutex& dirname_lock = *new std::mutex();
607 std::lock_guard<std::mutex> lock(dirname_lock);
Colin Cross2e732e22017-02-23 21:23:05 -0800608
609 // Note that if std::string uses copy-on-write strings, &str[0] will cause
610 // the copy to be made, so there is no chance of us accidentally writing to
611 // the storage for 'path'.
612 char* parent = dirname(&result[0]);
613
614 // In case dirname returned a pointer to a process global, copy that string
615 // before leaving the lock.
616 result.assign(parent);
617
618 return result;
619}
Elliott Hughes3e6e4422022-05-26 16:37:25 -0700620#else
621// Copied from bionic so that Dirname() below can be portable and thread-safe.
Yurii Zubrytskyi2902e102022-11-08 23:32:50 -0800622static int _dirname_r(const char* path, size_t path_size, char* buffer, size_t buffer_size) {
Elliott Hughes3e6e4422022-05-26 16:37:25 -0700623 const char* endp = nullptr;
624 int len;
625 int result;
626
627 // Empty or NULL string gets treated as ".".
Yurii Zubrytskyi2902e102022-11-08 23:32:50 -0800628 if (path == nullptr || path_size == 0) {
Elliott Hughes3e6e4422022-05-26 16:37:25 -0700629 path = ".";
630 len = 1;
631 goto Exit;
632 }
633
634 // Strip trailing slashes.
Yurii Zubrytskyi2902e102022-11-08 23:32:50 -0800635 endp = path + path_size - 1;
Elliott Hughes3e6e4422022-05-26 16:37:25 -0700636 while (endp > path && *endp == '/') {
637 endp--;
638 }
639
640 // Find the start of the dir.
641 while (endp > path && *endp != '/') {
642 endp--;
643 }
644
645 // Either the dir is "/" or there are no slashes.
646 if (endp == path) {
647 path = (*endp == '/') ? "/" : ".";
648 len = 1;
649 goto Exit;
650 }
651
652 do {
653 endp--;
654 } while (endp > path && *endp == '/');
655
656 len = endp - path + 1;
657
658 Exit:
659 result = len;
660 if (len + 1 > MAXPATHLEN) {
661 errno = ENAMETOOLONG;
662 return -1;
663 }
664 if (buffer == nullptr) {
665 return result;
666 }
667
668 if (len > static_cast<int>(buffer_size) - 1) {
669 len = buffer_size - 1;
670 result = -1;
671 errno = ERANGE;
672 }
673
674 if (len >= 0) {
675 memcpy(buffer, path, len);
676 buffer[len] = 0;
677 }
678 return result;
679}
Yurii Zubrytskyi2902e102022-11-08 23:32:50 -0800680std::string Dirname(std::string_view path) {
681 char buf[PATH_MAX] __attribute__((__uninitialized__));
682 const auto size = _dirname_r(path.data(), path.size(), buf, sizeof(buf));
683 return size > 0 ? std::string(buf, size) : std::string();
Elliott Hughes3e6e4422022-05-26 16:37:25 -0700684}
685#endif
Colin Cross2e732e22017-02-23 21:23:05 -0800686
Dan Albertaac6b7c2015-03-16 10:08:46 -0700687} // namespace base
688} // namespace android