1 /*
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
17 #include "android-base/file.h"
18
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <ftw.h>
22 #include <libgen.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/param.h>
27 #include <sys/stat.h>
28 #include <sys/types.h>
29 #include <unistd.h>
30
31 #include <memory>
32 #include <mutex>
33 #include <string>
34 #include <vector>
35
36 #if defined(__APPLE__)
37 #include <mach-o/dyld.h>
38 #endif
39 #if defined(_WIN32)
40 #include <direct.h>
41 #include <windows.h>
42 #define O_NOFOLLOW 0
43 #define OS_PATH_SEPARATOR '\\'
44 #else
45 #define OS_PATH_SEPARATOR '/'
46 #endif
47
48 #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
53 namespace {
54
55 #ifdef _WIN32
mkstemp(char * name_template,size_t size_in_chars)56 static int mkstemp(char* name_template, size_t size_in_chars) {
57 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) {
61 return -1;
62 }
63
64 // Use open() to match the close() that TemporaryFile's destructor does.
65 // Use O_BINARY to match base file APIs.
66 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;
77 }
78
mkdtemp(char * name_template,size_t size_in_chars)79 static char* mkdtemp(char* name_template, size_t size_in_chars) {
80 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) {
85 return nullptr;
86 }
87
88 if (_wmkdir(path.c_str()) != 0) {
89 return nullptr;
90 }
91
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;
98 }
99 #endif
100
GetSystemTempDir()101 std::string GetSystemTempDir() {
102 #if defined(__ANDROID__)
103 const auto* tmpdir = getenv("TMPDIR");
104 if (tmpdir == nullptr) tmpdir = "/data/local/tmp";
105 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)
112 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;
116
117 // GetTempPath() returns a path with a trailing slash, but init()
118 // does not expect that, so remove it.
119 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
126 return tmp_dir;
127 #else
128 const auto* tmpdir = getenv("TMPDIR");
129 if (tmpdir == nullptr) tmpdir = "/tmp";
130 return tmpdir;
131 #endif
132 }
133
134 } // namespace
135
TemporaryFile()136 TemporaryFile::TemporaryFile() {
137 init(GetSystemTempDir());
138 }
139
TemporaryFile(const std::string & tmp_dir)140 TemporaryFile::TemporaryFile(const std::string& tmp_dir) {
141 init(tmp_dir);
142 }
143
~TemporaryFile()144 TemporaryFile::~TemporaryFile() {
145 if (fd != -1) {
146 close(fd);
147 }
148 if (remove_file_) {
149 unlink(path);
150 }
151 }
152
release()153 int TemporaryFile::release() {
154 int result = fd;
155 fd = -1;
156 return result;
157 }
158
init(const std::string & tmp_dir)159 void TemporaryFile::init(const std::string& tmp_dir) {
160 snprintf(path, sizeof(path), "%s%cTemporaryFile-XXXXXX", tmp_dir.c_str(), OS_PATH_SEPARATOR);
161 #if defined(_WIN32)
162 fd = mkstemp(path, sizeof(path));
163 #else
164 fd = mkstemp(path);
165 #endif
166 }
167
TemporaryDir()168 TemporaryDir::TemporaryDir() {
169 init(GetSystemTempDir());
170 }
171
~TemporaryDir()172 TemporaryDir::~TemporaryDir() {
173 if (!remove_dir_and_contents_) return;
174
175 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);
201 }
202
init(const std::string & tmp_dir)203 bool TemporaryDir::init(const std::string& tmp_dir) {
204 snprintf(path, sizeof(path), "%s%cTemporaryDir-XXXXXX", tmp_dir.c_str(), OS_PATH_SEPARATOR);
205 #if defined(_WIN32)
206 return (mkdtemp(path, sizeof(path)) != nullptr);
207 #else
208 return (mkdtemp(path) != nullptr);
209 #endif
210 }
211
212 namespace android {
213 namespace base {
214
215 // Versions of standard library APIs that support UTF-8 strings.
216 using namespace android::base::utf8;
217
ReadFdToString(borrowed_fd fd,std::string * content)218 bool ReadFdToString(borrowed_fd fd, std::string* content) {
219 content->clear();
220
221 // 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;
225 if (fstat(fd.get(), &sb) != -1 && sb.st_size > 0 && sb.st_size <= SSIZE_MAX) {
226 // Shrink the string capacity to fit the file, but if the capacity is only
227 // slightly larger than needed, avoid reallocating. std::string::reserve no
228 // longer lowers capacity after P0966R1, but it does round the request up a
229 // small amount (e.g. 8 or 16 bytes).
230 size_t fd_size = sb.st_size;
231 if (fd_size > content->capacity()) {
232 content->reserve(fd_size);
233 } else if (fd_size < content->capacity() && content->capacity() - fd_size >= 64) {
234 content->shrink_to_fit();
235 content->reserve(fd_size);
236 }
237 }
238
239 char buf[4096] __attribute__((__uninitialized__));
240 ssize_t n;
241 while ((n = TEMP_FAILURE_RETRY(read(fd.get(), &buf[0], sizeof(buf)))) > 0) {
242 content->append(buf, n);
243 }
244 return (n == 0) ? true : false;
245 }
246
ReadFileToString(const std::string & path,std::string * content,bool follow_symlinks)247 bool ReadFileToString(const std::string& path, std::string* content, bool follow_symlinks) {
248 content->clear();
249
250 int flags = O_RDONLY | O_CLOEXEC | O_BINARY | (follow_symlinks ? 0 : O_NOFOLLOW);
251 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags)));
252 if (fd == -1) {
253 return false;
254 }
255 return ReadFdToString(fd, content);
256 }
257
WriteStringToFd(std::string_view content,borrowed_fd fd)258 bool WriteStringToFd(std::string_view content, borrowed_fd fd) {
259 const char* p = content.data();
260 size_t left = content.size();
261 while (left > 0) {
262 ssize_t n = TEMP_FAILURE_RETRY(write(fd.get(), p, left));
263 if (n == -1) {
264 return false;
265 }
266 p += n;
267 left -= n;
268 }
269 return true;
270 }
271
CleanUpAfterFailedWrite(const std::string & path)272 static bool CleanUpAfterFailedWrite(const std::string& path) {
273 // Something went wrong. Let's not leave a corrupt file lying around.
274 int saved_errno = errno;
275 unlink(path.c_str());
276 errno = saved_errno;
277 return false;
278 }
279
280 #if !defined(_WIN32)
WriteStringToFile(const std::string & content,const std::string & path,mode_t mode,uid_t owner,gid_t group,bool follow_symlinks)281 bool WriteStringToFile(const std::string& content, const std::string& path,
282 mode_t mode, uid_t owner, gid_t group,
283 bool follow_symlinks) {
284 int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY |
285 (follow_symlinks ? 0 : O_NOFOLLOW);
286 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode)));
287 if (fd == -1) {
288 PLOG(ERROR) << "android::WriteStringToFile open failed";
289 return false;
290 }
291
292 // We do an explicit fchmod here because we assume that the caller really
293 // meant what they said and doesn't want the umask-influenced mode.
294 if (fchmod(fd, mode) == -1) {
295 PLOG(ERROR) << "android::WriteStringToFile fchmod failed";
296 return CleanUpAfterFailedWrite(path);
297 }
298 if (fchown(fd, owner, group) == -1) {
299 PLOG(ERROR) << "android::WriteStringToFile fchown failed";
300 return CleanUpAfterFailedWrite(path);
301 }
302 if (!WriteStringToFd(content, fd)) {
303 PLOG(ERROR) << "android::WriteStringToFile write failed";
304 return CleanUpAfterFailedWrite(path);
305 }
306 return true;
307 }
308 #endif
309
WriteStringToFile(const std::string & content,const std::string & path,bool follow_symlinks)310 bool WriteStringToFile(const std::string& content, const std::string& path,
311 bool follow_symlinks) {
312 int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY |
313 (follow_symlinks ? 0 : O_NOFOLLOW);
314 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, 0666)));
315 if (fd == -1) {
316 return false;
317 }
318 return WriteStringToFd(content, fd) || CleanUpAfterFailedWrite(path);
319 }
320
ReadFully(borrowed_fd fd,void * data,size_t byte_count)321 bool ReadFully(borrowed_fd fd, void* data, size_t byte_count) {
322 uint8_t* p = reinterpret_cast<uint8_t*>(data);
323 size_t remaining = byte_count;
324 while (remaining > 0) {
325 ssize_t n = TEMP_FAILURE_RETRY(read(fd.get(), p, remaining));
326 if (n == 0) { // EOF
327 errno = ENODATA;
328 return false;
329 }
330 if (n == -1) return false;
331 p += n;
332 remaining -= n;
333 }
334 return true;
335 }
336
337 #if defined(_WIN32)
338 // Windows implementation of pread. Note that this DOES move the file descriptors read position,
339 // but it does so atomically.
pread(borrowed_fd fd,void * data,size_t byte_count,off64_t offset)340 static ssize_t pread(borrowed_fd fd, void* data, size_t byte_count, off64_t offset) {
341 DWORD bytes_read;
342 OVERLAPPED overlapped;
343 memset(&overlapped, 0, sizeof(OVERLAPPED));
344 overlapped.Offset = static_cast<DWORD>(offset);
345 overlapped.OffsetHigh = static_cast<DWORD>(offset >> 32);
346 if (!ReadFile(reinterpret_cast<HANDLE>(_get_osfhandle(fd.get())), data,
347 static_cast<DWORD>(byte_count), &bytes_read, &overlapped)) {
348 // In case someone tries to read errno (since this is masquerading as a POSIX call)
349 errno = EIO;
350 return -1;
351 }
352 return static_cast<ssize_t>(bytes_read);
353 }
354
pwrite(borrowed_fd fd,const void * data,size_t byte_count,off64_t offset)355 static ssize_t pwrite(borrowed_fd fd, const void* data, size_t byte_count, off64_t offset) {
356 DWORD bytes_written;
357 OVERLAPPED overlapped;
358 memset(&overlapped, 0, sizeof(OVERLAPPED));
359 overlapped.Offset = static_cast<DWORD>(offset);
360 overlapped.OffsetHigh = static_cast<DWORD>(offset >> 32);
361 if (!WriteFile(reinterpret_cast<HANDLE>(_get_osfhandle(fd.get())), data,
362 static_cast<DWORD>(byte_count), &bytes_written, &overlapped)) {
363 // In case someone tries to read errno (since this is masquerading as a POSIX call)
364 errno = EIO;
365 return -1;
366 }
367 return static_cast<ssize_t>(bytes_written);
368 }
369 #endif
370
ReadFullyAtOffset(borrowed_fd fd,void * data,size_t byte_count,off64_t offset)371 bool ReadFullyAtOffset(borrowed_fd fd, void* data, size_t byte_count, off64_t offset) {
372 uint8_t* p = reinterpret_cast<uint8_t*>(data);
373 while (byte_count > 0) {
374 ssize_t n = TEMP_FAILURE_RETRY(pread(fd.get(), p, byte_count, offset));
375 if (n == 0) { // EOF
376 errno = ENODATA;
377 return false;
378 }
379 if (n == -1) return false;
380 p += n;
381 byte_count -= n;
382 offset += n;
383 }
384 return true;
385 }
386
WriteFullyAtOffset(borrowed_fd fd,const void * data,size_t byte_count,off64_t offset)387 bool WriteFullyAtOffset(borrowed_fd fd, const void* data, size_t byte_count, off64_t offset) {
388 const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
389 size_t remaining = byte_count;
390 while (remaining > 0) {
391 ssize_t n = TEMP_FAILURE_RETRY(pwrite(fd.get(), p, remaining, offset));
392 if (n == -1) return false;
393 p += n;
394 remaining -= n;
395 offset += n;
396 }
397 return true;
398 }
399
WriteFully(borrowed_fd fd,const void * data,size_t byte_count)400 bool WriteFully(borrowed_fd fd, const void* data, size_t byte_count) {
401 const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
402 size_t remaining = byte_count;
403 while (remaining > 0) {
404 ssize_t n = TEMP_FAILURE_RETRY(write(fd.get(), p, remaining));
405 if (n == -1) return false;
406 p += n;
407 remaining -= n;
408 }
409 return true;
410 }
411
RemoveFileIfExists(const std::string & path,std::string * err)412 bool RemoveFileIfExists(const std::string& path, std::string* err) {
413 struct stat st;
414 #if defined(_WIN32)
415 // TODO: Windows version can't handle symbolic links correctly.
416 int result = stat(path.c_str(), &st);
417 bool file_type_removable = (result == 0 && S_ISREG(st.st_mode));
418 #else
419 int result = lstat(path.c_str(), &st);
420 bool file_type_removable = (result == 0 && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)));
421 #endif
422 if (result == -1) {
423 if (errno == ENOENT || errno == ENOTDIR) return true;
424 if (err != nullptr) *err = strerror(errno);
425 return false;
426 }
427
428 if (result == 0) {
429 if (!file_type_removable) {
430 if (err != nullptr) {
431 *err = "is not a regular file or symbolic link";
432 }
433 return false;
434 }
435 if (unlink(path.c_str()) == -1) {
436 if (err != nullptr) {
437 *err = strerror(errno);
438 }
439 return false;
440 }
441 }
442 return true;
443 }
444
445 #if !defined(_WIN32)
Readlink(const std::string & path,std::string * result)446 bool Readlink(const std::string& path, std::string* result) {
447 result->clear();
448
449 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
450 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
451 // waste memory to just start there. We add 1 so that we can recognize
452 // whether it actually fit (rather than being truncated to 4095).
453 std::vector<char> buf(4095 + 1);
454 while (true) {
455 ssize_t size = readlink(path.c_str(), &buf[0], buf.size());
456 // Unrecoverable error?
457 if (size == -1) return false;
458 // It fit! (If size == buf.size(), it may have been truncated.)
459 if (static_cast<size_t>(size) < buf.size()) {
460 result->assign(&buf[0], size);
461 return true;
462 }
463 // Double our buffer and try again.
464 buf.resize(buf.size() * 2);
465 }
466 }
467 #endif
468
469 #if !defined(_WIN32)
Realpath(const std::string & path,std::string * result)470 bool Realpath(const std::string& path, std::string* result) {
471 result->clear();
472
473 // realpath may exit with EINTR. Retry if so.
474 char* realpath_buf = nullptr;
475 do {
476 realpath_buf = realpath(path.c_str(), nullptr);
477 } while (realpath_buf == nullptr && errno == EINTR);
478
479 if (realpath_buf == nullptr) {
480 return false;
481 }
482 result->assign(realpath_buf);
483 free(realpath_buf);
484 return true;
485 }
486 #endif
487
GetExecutablePath()488 std::string GetExecutablePath() {
489 #if defined(__linux__)
490 std::string path;
491 android::base::Readlink("/proc/self/exe", &path);
492 return path;
493 #elif defined(__APPLE__)
494 char path[PATH_MAX + 1];
495 uint32_t path_len = sizeof(path);
496 int rc = _NSGetExecutablePath(path, &path_len);
497 if (rc < 0) {
498 std::unique_ptr<char> path_buf(new char[path_len]);
499 _NSGetExecutablePath(path_buf.get(), &path_len);
500 return path_buf.get();
501 }
502 return path;
503 #elif defined(_WIN32)
504 char path[PATH_MAX + 1];
505 DWORD result = GetModuleFileName(NULL, path, sizeof(path) - 1);
506 if (result == 0 || result == sizeof(path) - 1) return "";
507 path[PATH_MAX - 1] = 0;
508 return path;
509 #elif defined(__EMSCRIPTEN__)
510 abort();
511 #else
512 #error unknown OS
513 #endif
514 }
515
GetExecutableDirectory()516 std::string GetExecutableDirectory() {
517 return Dirname(GetExecutablePath());
518 }
519
520 #if defined(_WIN32)
Basename(std::string_view path)521 std::string Basename(std::string_view path) {
522 // TODO: how much of this is actually necessary for mingw?
523
524 // Copy path because basename may modify the string passed in.
525 std::string result(path);
526
527 // Use lock because basename() may write to a process global and return a
528 // pointer to that. Note that this locking strategy only works if all other
529 // callers to basename in the process also grab this same lock, but its
530 // better than nothing. Bionic's basename returns a thread-local buffer.
531 static std::mutex& basename_lock = *new std::mutex();
532 std::lock_guard<std::mutex> lock(basename_lock);
533
534 // Note that if std::string uses copy-on-write strings, &str[0] will cause
535 // the copy to be made, so there is no chance of us accidentally writing to
536 // the storage for 'path'.
537 char* name = basename(&result[0]);
538
539 // In case basename returned a pointer to a process global, copy that string
540 // before leaving the lock.
541 result.assign(name);
542
543 return result;
544 }
545 #else
546 // Copied from bionic so that Basename() below can be portable and thread-safe.
_basename_r(const char * path,size_t path_size,char * buffer,size_t buffer_size)547 static int _basename_r(const char* path, size_t path_size, char* buffer, size_t buffer_size) {
548 const char* startp = nullptr;
549 const char* endp = nullptr;
550 int len;
551 int result;
552
553 // Empty or NULL string gets treated as ".".
554 if (path == nullptr || path_size == 0) {
555 startp = ".";
556 len = 1;
557 goto Exit;
558 }
559
560 // Strip trailing slashes.
561 endp = path + path_size - 1;
562 while (endp > path && *endp == '/') {
563 endp--;
564 }
565
566 // All slashes becomes "/".
567 if (endp == path && *endp == '/') {
568 startp = "/";
569 len = 1;
570 goto Exit;
571 }
572
573 // Find the start of the base.
574 startp = endp;
575 while (startp > path && *(startp - 1) != '/') {
576 startp--;
577 }
578
579 len = endp - startp +1;
580
581 Exit:
582 result = len;
583 if (buffer == nullptr) {
584 return result;
585 }
586 if (len > static_cast<int>(buffer_size) - 1) {
587 len = buffer_size - 1;
588 result = -1;
589 errno = ERANGE;
590 }
591
592 if (len >= 0) {
593 memcpy(buffer, startp, len);
594 buffer[len] = 0;
595 }
596 return result;
597 }
Basename(std::string_view path)598 std::string Basename(std::string_view path) {
599 char buf[PATH_MAX] __attribute__((__uninitialized__));
600 const auto size = _basename_r(path.data(), path.size(), buf, sizeof(buf));
601 return size > 0 ? std::string(buf, size) : std::string();
602 }
603 #endif
604
605 #if defined(_WIN32)
Dirname(std::string_view path)606 std::string Dirname(std::string_view path) {
607 // TODO: how much of this is actually necessary for mingw?
608
609 // Copy path because dirname may modify the string passed in.
610 std::string result(path);
611
612 // Use lock because dirname() may write to a process global and return a
613 // pointer to that. Note that this locking strategy only works if all other
614 // callers to dirname in the process also grab this same lock, but its
615 // better than nothing. Bionic's dirname returns a thread-local buffer.
616 static std::mutex& dirname_lock = *new std::mutex();
617 std::lock_guard<std::mutex> lock(dirname_lock);
618
619 // Note that if std::string uses copy-on-write strings, &str[0] will cause
620 // the copy to be made, so there is no chance of us accidentally writing to
621 // the storage for 'path'.
622 char* parent = dirname(&result[0]);
623
624 // In case dirname returned a pointer to a process global, copy that string
625 // before leaving the lock.
626 result.assign(parent);
627
628 return result;
629 }
630 #else
631 // Copied from bionic so that Dirname() below can be portable and thread-safe.
_dirname_r(const char * path,size_t path_size,char * buffer,size_t buffer_size)632 static int _dirname_r(const char* path, size_t path_size, char* buffer, size_t buffer_size) {
633 const char* endp = nullptr;
634 int len;
635 int result;
636
637 // Empty or NULL string gets treated as ".".
638 if (path == nullptr || path_size == 0) {
639 path = ".";
640 len = 1;
641 goto Exit;
642 }
643
644 // Strip trailing slashes.
645 endp = path + path_size - 1;
646 while (endp > path && *endp == '/') {
647 endp--;
648 }
649
650 // Find the start of the dir.
651 while (endp > path && *endp != '/') {
652 endp--;
653 }
654
655 // Either the dir is "/" or there are no slashes.
656 if (endp == path) {
657 path = (*endp == '/') ? "/" : ".";
658 len = 1;
659 goto Exit;
660 }
661
662 do {
663 endp--;
664 } while (endp > path && *endp == '/');
665
666 len = endp - path + 1;
667
668 Exit:
669 result = len;
670 if (len + 1 > MAXPATHLEN) {
671 errno = ENAMETOOLONG;
672 return -1;
673 }
674 if (buffer == nullptr) {
675 return result;
676 }
677
678 if (len > static_cast<int>(buffer_size) - 1) {
679 len = buffer_size - 1;
680 result = -1;
681 errno = ERANGE;
682 }
683
684 if (len >= 0) {
685 memcpy(buffer, path, len);
686 buffer[len] = 0;
687 }
688 return result;
689 }
Dirname(std::string_view path)690 std::string Dirname(std::string_view path) {
691 char buf[PATH_MAX] __attribute__((__uninitialized__));
692 const auto size = _dirname_r(path.data(), path.size(), buf, sizeof(buf));
693 return size > 0 ? std::string(buf, size) : std::string();
694 }
695 #endif
696
697 } // namespace base
698 } // namespace android
699