Path: blob/main/contrib/llvm-project/libcxx/src/filesystem/operations.cpp
35231 views
//===----------------------------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include <__assert>9#include <__config>10#include <__utility/unreachable.h>11#include <array>12#include <climits>13#include <cstdlib>14#include <filesystem>15#include <iterator>16#include <string_view>17#include <type_traits>18#include <vector>1920#include "error.h"21#include "file_descriptor.h"22#include "path_parser.h"23#include "posix_compat.h"24#include "time_utils.h"2526#if defined(_LIBCPP_WIN32API)27# define WIN32_LEAN_AND_MEAN28# define NOMINMAX29# include <windows.h>30#else31# include <dirent.h>32# include <sys/stat.h>33# include <sys/statvfs.h>34# include <unistd.h>35#endif36#include <fcntl.h> /* values for fchmodat */37#include <time.h>3839#if __has_include(<sys/sendfile.h>)40# include <sys/sendfile.h>41# define _LIBCPP_FILESYSTEM_USE_SENDFILE42#elif defined(__APPLE__) || __has_include(<copyfile.h>)43# include <copyfile.h>44# define _LIBCPP_FILESYSTEM_USE_COPYFILE45#else46# include <fstream>47# define _LIBCPP_FILESYSTEM_USE_FSTREAM48#endif4950#if defined(__ELF__) && defined(_LIBCPP_LINK_RT_LIB)51# pragma comment(lib, "rt")52#endif5354_LIBCPP_BEGIN_NAMESPACE_FILESYSTEM5556using detail::capture_errno;57using detail::ErrorHandler;58using detail::StatT;59using detail::TimeSpec;60using parser::createView;61using parser::PathParser;62using parser::string_view_t;6364static path __do_absolute(const path& p, path* cwd, error_code* ec) {65if (ec)66ec->clear();67if (p.is_absolute())68return p;69*cwd = __current_path(ec);70if (ec && *ec)71return {};72return (*cwd) / p;73}7475path __absolute(const path& p, error_code* ec) {76path cwd;77return __do_absolute(p, &cwd, ec);78}7980path __canonical(path const& orig_p, error_code* ec) {81path cwd;82ErrorHandler<path> err("canonical", ec, &orig_p, &cwd);8384path p = __do_absolute(orig_p, &cwd, ec);85#if (defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112) || defined(_LIBCPP_WIN32API)86std::unique_ptr<path::value_type, decltype(&::free)> hold(detail::realpath(p.c_str(), nullptr), &::free);87if (hold.get() == nullptr)88return err.report(capture_errno());89return {hold.get()};90#else91# if defined(__MVS__) && !defined(PATH_MAX)92path::value_type buff[_XOPEN_PATH_MAX + 1];93# else94path::value_type buff[PATH_MAX + 1];95# endif96path::value_type* ret;97if ((ret = detail::realpath(p.c_str(), buff)) == nullptr)98return err.report(capture_errno());99return {ret};100#endif101}102103void __copy(const path& from, const path& to, copy_options options, error_code* ec) {104ErrorHandler<void> err("copy", ec, &from, &to);105106const bool sym_status = bool(options & (copy_options::create_symlinks | copy_options::skip_symlinks));107108const bool sym_status2 = bool(options & copy_options::copy_symlinks);109110error_code m_ec1;111StatT f_st;112const file_status f =113sym_status || sym_status2 ? detail::posix_lstat(from, f_st, &m_ec1) : detail::posix_stat(from, f_st, &m_ec1);114if (m_ec1)115return err.report(m_ec1);116117StatT t_st;118const file_status t = sym_status ? detail::posix_lstat(to, t_st, &m_ec1) : detail::posix_stat(to, t_st, &m_ec1);119120if (not status_known(t))121return err.report(m_ec1);122123if (!exists(f) || is_other(f) || is_other(t) || (is_directory(f) && is_regular_file(t)) ||124(exists(t) && detail::stat_equivalent(f_st, t_st))) {125return err.report(errc::function_not_supported);126}127128if (is_symlink(f)) {129if (bool(copy_options::skip_symlinks & options)) {130// do nothing131} else if (not exists(t)) {132__copy_symlink(from, to, ec);133} else {134return err.report(errc::file_exists);135}136return;137} else if (is_regular_file(f)) {138if (bool(copy_options::directories_only & options)) {139// do nothing140} else if (bool(copy_options::create_symlinks & options)) {141__create_symlink(from, to, ec);142} else if (bool(copy_options::create_hard_links & options)) {143__create_hard_link(from, to, ec);144} else if (is_directory(t)) {145__copy_file(from, to / from.filename(), options, ec);146} else {147__copy_file(from, to, options, ec);148}149return;150} else if (is_directory(f) && bool(copy_options::create_symlinks & options)) {151return err.report(errc::is_a_directory);152} else if (is_directory(f) && (bool(copy_options::recursive & options) || copy_options::none == options)) {153if (!exists(t)) {154// create directory to with attributes from 'from'.155__create_directory(to, from, ec);156if (ec && *ec) {157return;158}159}160directory_iterator it = ec ? directory_iterator(from, *ec) : directory_iterator(from);161if (ec && *ec) {162return;163}164error_code m_ec2;165for (; !m_ec2 && it != directory_iterator(); it.increment(m_ec2)) {166__copy(it->path(), to / it->path().filename(), options | copy_options::__in_recursive_copy, ec);167if (ec && *ec) {168return;169}170}171if (m_ec2) {172return err.report(m_ec2);173}174}175}176177namespace detail {178namespace {179180#if defined(_LIBCPP_FILESYSTEM_USE_SENDFILE)181bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {182size_t count = read_fd.get_stat().st_size;183do {184ssize_t res;185if ((res = ::sendfile(write_fd.fd, read_fd.fd, nullptr, count)) == -1) {186ec = capture_errno();187return false;188}189count -= res;190} while (count > 0);191192ec.clear();193194return true;195}196#elif defined(_LIBCPP_FILESYSTEM_USE_COPYFILE)197bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {198struct CopyFileState {199copyfile_state_t state;200CopyFileState() { state = copyfile_state_alloc(); }201~CopyFileState() { copyfile_state_free(state); }202203private:204CopyFileState(CopyFileState const&) = delete;205CopyFileState& operator=(CopyFileState const&) = delete;206};207208CopyFileState cfs;209if (fcopyfile(read_fd.fd, write_fd.fd, cfs.state, COPYFILE_DATA) < 0) {210ec = capture_errno();211return false;212}213214ec.clear();215return true;216}217#elif defined(_LIBCPP_FILESYSTEM_USE_FSTREAM)218bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {219ifstream in;220in.__open(read_fd.fd, ios::binary);221if (!in.is_open()) {222// This assumes that __open didn't reset the error code.223ec = capture_errno();224return false;225}226read_fd.fd = -1;227ofstream out;228out.__open(write_fd.fd, ios::binary);229if (!out.is_open()) {230ec = capture_errno();231return false;232}233write_fd.fd = -1;234235if (in.good() && out.good()) {236using InIt = istreambuf_iterator<char>;237using OutIt = ostreambuf_iterator<char>;238InIt bin(in);239InIt ein;240OutIt bout(out);241copy(bin, ein, bout);242}243if (out.fail() || in.fail()) {244ec = make_error_code(errc::io_error);245return false;246}247248ec.clear();249return true;250}251#else252# error "Unknown implementation for copy_file_impl"253#endif // copy_file_impl implementation254255} // end anonymous namespace256} // end namespace detail257258bool __copy_file(const path& from, const path& to, copy_options options, error_code* ec) {259using detail::FileDescriptor;260ErrorHandler<bool> err("copy_file", ec, &to, &from);261262error_code m_ec;263FileDescriptor from_fd = FileDescriptor::create_with_status(&from, m_ec, O_RDONLY | O_NONBLOCK | O_BINARY);264if (m_ec)265return err.report(m_ec);266267auto from_st = from_fd.get_status();268StatT const& from_stat = from_fd.get_stat();269if (!is_regular_file(from_st)) {270if (not m_ec)271m_ec = make_error_code(errc::not_supported);272return err.report(m_ec);273}274275const bool skip_existing = bool(copy_options::skip_existing & options);276const bool update_existing = bool(copy_options::update_existing & options);277const bool overwrite_existing = bool(copy_options::overwrite_existing & options);278279StatT to_stat_path;280file_status to_st = detail::posix_stat(to, to_stat_path, &m_ec);281if (!status_known(to_st))282return err.report(m_ec);283284const bool to_exists = exists(to_st);285if (to_exists && !is_regular_file(to_st))286return err.report(errc::not_supported);287288if (to_exists && detail::stat_equivalent(from_stat, to_stat_path))289return err.report(errc::file_exists);290291if (to_exists && skip_existing)292return false;293294bool ShouldCopy = [&]() {295if (to_exists && update_existing) {296auto from_time = detail::extract_mtime(from_stat);297auto to_time = detail::extract_mtime(to_stat_path);298if (from_time.tv_sec < to_time.tv_sec)299return false;300if (from_time.tv_sec == to_time.tv_sec && from_time.tv_nsec <= to_time.tv_nsec)301return false;302return true;303}304if (!to_exists || overwrite_existing)305return true;306return err.report(errc::file_exists);307}();308if (!ShouldCopy)309return false;310311// Don't truncate right away. We may not be opening the file we originally312// looked at; we'll check this later.313int to_open_flags = O_WRONLY | O_BINARY;314if (!to_exists)315to_open_flags |= O_CREAT;316FileDescriptor to_fd = FileDescriptor::create_with_status(&to, m_ec, to_open_flags, from_stat.st_mode);317if (m_ec)318return err.report(m_ec);319320if (to_exists) {321// Check that the file we initially stat'ed is equivalent to the one322// we opened.323// FIXME: report this better.324if (!detail::stat_equivalent(to_stat_path, to_fd.get_stat()))325return err.report(errc::bad_file_descriptor);326327// Set the permissions and truncate the file we opened.328if (detail::posix_fchmod(to_fd, from_stat, m_ec))329return err.report(m_ec);330if (detail::posix_ftruncate(to_fd, 0, m_ec))331return err.report(m_ec);332}333334if (!detail::copy_file_impl(from_fd, to_fd, m_ec)) {335// FIXME: Remove the dest file if we failed, and it didn't exist previously.336return err.report(m_ec);337}338339return true;340}341342void __copy_symlink(const path& existing_symlink, const path& new_symlink, error_code* ec) {343const path real_path(__read_symlink(existing_symlink, ec));344if (ec && *ec) {345return;346}347#if defined(_LIBCPP_WIN32API)348error_code local_ec;349if (is_directory(real_path, local_ec))350__create_directory_symlink(real_path, new_symlink, ec);351else352#endif353__create_symlink(real_path, new_symlink, ec);354}355356bool __create_directories(const path& p, error_code* ec) {357ErrorHandler<bool> err("create_directories", ec, &p);358359error_code m_ec;360auto const st = detail::posix_stat(p, &m_ec);361if (!status_known(st))362return err.report(m_ec);363else if (is_directory(st))364return false;365else if (exists(st))366return err.report(errc::file_exists);367368const path parent = p.parent_path();369if (!parent.empty()) {370const file_status parent_st = status(parent, m_ec);371if (not status_known(parent_st))372return err.report(m_ec);373if (not exists(parent_st)) {374if (parent == p)375return err.report(errc::invalid_argument);376__create_directories(parent, ec);377if (ec && *ec) {378return false;379}380} else if (not is_directory(parent_st))381return err.report(errc::not_a_directory);382}383bool ret = __create_directory(p, &m_ec);384if (m_ec)385return err.report(m_ec);386return ret;387}388389bool __create_directory(const path& p, error_code* ec) {390ErrorHandler<bool> err("create_directory", ec, &p);391392if (detail::mkdir(p.c_str(), static_cast<int>(perms::all)) == 0)393return true;394395if (errno != EEXIST)396return err.report(capture_errno());397error_code mec = capture_errno();398error_code ignored_ec;399const file_status st = status(p, ignored_ec);400if (!is_directory(st))401return err.report(mec);402return false;403}404405bool __create_directory(path const& p, path const& attributes, error_code* ec) {406ErrorHandler<bool> err("create_directory", ec, &p, &attributes);407408StatT attr_stat;409error_code mec;410file_status st = detail::posix_stat(attributes, attr_stat, &mec);411if (!status_known(st))412return err.report(mec);413if (!is_directory(st))414return err.report(errc::not_a_directory, "the specified attribute path is invalid");415416if (detail::mkdir(p.c_str(), attr_stat.st_mode) == 0)417return true;418419if (errno != EEXIST)420return err.report(capture_errno());421422mec = capture_errno();423error_code ignored_ec;424st = status(p, ignored_ec);425if (!is_directory(st))426return err.report(mec);427return false;428}429430void __create_directory_symlink(path const& from, path const& to, error_code* ec) {431ErrorHandler<void> err("create_directory_symlink", ec, &from, &to);432if (detail::symlink_dir(from.c_str(), to.c_str()) == -1)433return err.report(capture_errno());434}435436void __create_hard_link(const path& from, const path& to, error_code* ec) {437ErrorHandler<void> err("create_hard_link", ec, &from, &to);438if (detail::link(from.c_str(), to.c_str()) == -1)439return err.report(capture_errno());440}441442void __create_symlink(path const& from, path const& to, error_code* ec) {443ErrorHandler<void> err("create_symlink", ec, &from, &to);444if (detail::symlink_file(from.c_str(), to.c_str()) == -1)445return err.report(capture_errno());446}447448path __current_path(error_code* ec) {449ErrorHandler<path> err("current_path", ec);450451#if defined(_LIBCPP_WIN32API) || defined(__GLIBC__) || defined(__APPLE__)452// Common extension outside of POSIX getcwd() spec, without needing to453// preallocate a buffer. Also supported by a number of other POSIX libcs.454int size = 0;455path::value_type* ptr = nullptr;456typedef decltype(&::free) Deleter;457Deleter deleter = &::free;458#else459errno = 0; // Note: POSIX mandates that modifying `errno` is thread-safe.460auto size = ::pathconf(".", _PC_PATH_MAX);461if (size == -1) {462if (errno != 0) {463return err.report(capture_errno(), "call to pathconf failed");464465// `pathconf` returns `-1` without an error to indicate no limit.466} else {467# if defined(__MVS__) && !defined(PATH_MAX)468size = _XOPEN_PATH_MAX + 1;469# else470size = PATH_MAX + 1;471# endif472}473}474475auto buff = unique_ptr<path::value_type[]>(new path::value_type[size + 1]);476path::value_type* ptr = buff.get();477478// Preallocated buffer, don't free the buffer in the second unique_ptr479// below.480struct Deleter {481void operator()(void*) const {}482};483Deleter deleter;484#endif485486unique_ptr<path::value_type, Deleter> hold(detail::getcwd(ptr, size), deleter);487if (hold.get() == nullptr)488return err.report(capture_errno(), "call to getcwd failed");489490return {hold.get()};491}492493void __current_path(const path& p, error_code* ec) {494ErrorHandler<void> err("current_path", ec, &p);495if (detail::chdir(p.c_str()) == -1)496err.report(capture_errno());497}498499bool __equivalent(const path& p1, const path& p2, error_code* ec) {500ErrorHandler<bool> err("equivalent", ec, &p1, &p2);501502error_code ec1, ec2;503StatT st1 = {}, st2 = {};504auto s1 = detail::posix_stat(p1.native(), st1, &ec1);505if (!exists(s1))506return err.report(errc::not_supported);507auto s2 = detail::posix_stat(p2.native(), st2, &ec2);508if (!exists(s2))509return err.report(errc::not_supported);510511return detail::stat_equivalent(st1, st2);512}513514uintmax_t __file_size(const path& p, error_code* ec) {515ErrorHandler<uintmax_t> err("file_size", ec, &p);516517error_code m_ec;518StatT st;519file_status fst = detail::posix_stat(p, st, &m_ec);520if (!exists(fst) || !is_regular_file(fst)) {521errc error_kind = is_directory(fst) ? errc::is_a_directory : errc::not_supported;522if (!m_ec)523m_ec = make_error_code(error_kind);524return err.report(m_ec);525}526// is_regular_file(p) == true527return static_cast<uintmax_t>(st.st_size);528}529530uintmax_t __hard_link_count(const path& p, error_code* ec) {531ErrorHandler<uintmax_t> err("hard_link_count", ec, &p);532533error_code m_ec;534StatT st;535detail::posix_stat(p, st, &m_ec);536if (m_ec)537return err.report(m_ec);538return static_cast<uintmax_t>(st.st_nlink);539}540541bool __fs_is_empty(const path& p, error_code* ec) {542ErrorHandler<bool> err("is_empty", ec, &p);543544error_code m_ec;545StatT pst;546auto st = detail::posix_stat(p, pst, &m_ec);547if (m_ec)548return err.report(m_ec);549else if (!is_directory(st) && !is_regular_file(st))550return err.report(errc::not_supported);551else if (is_directory(st)) {552auto it = ec ? directory_iterator(p, *ec) : directory_iterator(p);553if (ec && *ec)554return false;555return it == directory_iterator{};556} else if (is_regular_file(st))557return static_cast<uintmax_t>(pst.st_size) == 0;558559__libcpp_unreachable();560}561562file_time_type __last_write_time(const path& p, error_code* ec) {563using namespace chrono;564ErrorHandler<file_time_type> err("last_write_time", ec, &p);565566error_code m_ec;567StatT st;568detail::posix_stat(p, st, &m_ec);569if (m_ec)570return err.report(m_ec);571return detail::__extract_last_write_time(p, st, ec);572}573574void __last_write_time(const path& p, file_time_type new_time, error_code* ec) {575using detail::fs_time;576ErrorHandler<void> err("last_write_time", ec, &p);577578#if defined(_LIBCPP_WIN32API)579TimeSpec ts;580if (!fs_time::convert_to_timespec(ts, new_time))581return err.report(errc::value_too_large);582detail::WinHandle h(p.c_str(), FILE_WRITE_ATTRIBUTES, 0);583if (!h)584return err.report(detail::make_windows_error(GetLastError()));585FILETIME last_write = timespec_to_filetime(ts);586if (!SetFileTime(h, nullptr, nullptr, &last_write))587return err.report(detail::make_windows_error(GetLastError()));588#else589error_code m_ec;590array<TimeSpec, 2> tbuf;591# if !defined(_LIBCPP_USE_UTIMENSAT)592// This implementation has a race condition between determining the593// last access time and attempting to set it to the same value using594// ::utimes595StatT st;596file_status fst = detail::posix_stat(p, st, &m_ec);597if (m_ec)598return err.report(m_ec);599tbuf[0] = detail::extract_atime(st);600# else601tbuf[0].tv_sec = 0;602tbuf[0].tv_nsec = UTIME_OMIT;603# endif604if (!fs_time::convert_to_timespec(tbuf[1], new_time))605return err.report(errc::value_too_large);606607detail::set_file_times(p, tbuf, m_ec);608if (m_ec)609return err.report(m_ec);610#endif611}612613void __permissions(const path& p, perms prms, perm_options opts, error_code* ec) {614ErrorHandler<void> err("permissions", ec, &p);615616auto has_opt = [&](perm_options o) { return bool(o & opts); };617const bool resolve_symlinks = !has_opt(perm_options::nofollow);618const bool add_perms = has_opt(perm_options::add);619const bool remove_perms = has_opt(perm_options::remove);620_LIBCPP_ASSERT_ARGUMENT_WITHIN_DOMAIN(621(add_perms + remove_perms + has_opt(perm_options::replace)) == 1,622"One and only one of the perm_options constants 'replace', 'add', or 'remove' must be present in opts");623624bool set_sym_perms = false;625prms &= perms::mask;626if (!resolve_symlinks || (add_perms || remove_perms)) {627error_code m_ec;628file_status st = resolve_symlinks ? detail::posix_stat(p, &m_ec) : detail::posix_lstat(p, &m_ec);629set_sym_perms = is_symlink(st);630if (m_ec)631return err.report(m_ec);632// TODO(hardening): double-check this assertion -- it might be a valid (if rare) case when the permissions are633// unknown.634_LIBCPP_ASSERT_VALID_EXTERNAL_API_CALL(st.permissions() != perms::unknown, "Permissions unexpectedly unknown");635if (add_perms)636prms |= st.permissions();637else if (remove_perms)638prms = st.permissions() & ~prms;639}640const auto real_perms = static_cast<detail::ModeT>(prms & perms::mask);641642#if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD)643const int flags = set_sym_perms ? AT_SYMLINK_NOFOLLOW : 0;644if (detail::fchmodat(AT_FDCWD, p.c_str(), real_perms, flags) == -1) {645return err.report(capture_errno());646}647#else648if (set_sym_perms)649return err.report(errc::operation_not_supported);650if (::chmod(p.c_str(), real_perms) == -1) {651return err.report(capture_errno());652}653#endif654}655656path __read_symlink(const path& p, error_code* ec) {657ErrorHandler<path> err("read_symlink", ec, &p);658659#if defined(PATH_MAX) || defined(MAX_SYMLINK_SIZE)660struct NullDeleter {661void operator()(void*) const {}662};663# ifdef MAX_SYMLINK_SIZE664const size_t size = MAX_SYMLINK_SIZE + 1;665# else666const size_t size = PATH_MAX + 1;667# endif668path::value_type stack_buff[size];669auto buff = std::unique_ptr<path::value_type[], NullDeleter>(stack_buff);670#else671StatT sb;672if (detail::lstat(p.c_str(), &sb) == -1) {673return err.report(capture_errno());674}675const size_t size = sb.st_size + 1;676auto buff = unique_ptr<path::value_type[]>(new path::value_type[size]);677#endif678detail::SSizeT ret;679if ((ret = detail::readlink(p.c_str(), buff.get(), size)) == -1)680return err.report(capture_errno());681// Note that `ret` returning `0` would work, resulting in a valid empty string being returned.682if (static_cast<size_t>(ret) >= size)683return err.report(errc::value_too_large);684buff[ret] = 0;685return {buff.get()};686}687688bool __remove(const path& p, error_code* ec) {689ErrorHandler<bool> err("remove", ec, &p);690if (detail::remove(p.c_str()) == -1) {691if (errno != ENOENT)692err.report(capture_errno());693return false;694}695return true;696}697698// We currently have two implementations of `__remove_all`. The first one is general and699// used on platforms where we don't have access to the `openat()` family of POSIX functions.700// That implementation uses `directory_iterator`, however it is vulnerable to some race701// conditions, see https://reviews.llvm.org/D118134 for details.702//703// The second implementation is used on platforms where `openat()` & friends are available,704// and it threads file descriptors through recursive calls to avoid such race conditions.705#if defined(_LIBCPP_WIN32API) || defined(__MVS__)706# define REMOVE_ALL_USE_DIRECTORY_ITERATOR707#endif708709#if defined(REMOVE_ALL_USE_DIRECTORY_ITERATOR)710711namespace {712713uintmax_t remove_all_impl(path const& p, error_code& ec) {714const auto npos = static_cast<uintmax_t>(-1);715const file_status st = __symlink_status(p, &ec);716if (ec)717return npos;718uintmax_t count = 1;719if (is_directory(st)) {720for (directory_iterator it(p, ec); !ec && it != directory_iterator(); it.increment(ec)) {721auto other_count = remove_all_impl(it->path(), ec);722if (ec)723return npos;724count += other_count;725}726if (ec)727return npos;728}729if (!__remove(p, &ec))730return npos;731return count;732}733734} // end namespace735736uintmax_t __remove_all(const path& p, error_code* ec) {737ErrorHandler<uintmax_t> err("remove_all", ec, &p);738739error_code mec;740auto count = remove_all_impl(p, mec);741if (mec) {742if (mec == errc::no_such_file_or_directory)743return 0;744return err.report(mec);745}746return count;747}748749#else // !REMOVE_ALL_USE_DIRECTORY_ITERATOR750751namespace {752753template <class Cleanup>754struct scope_exit {755explicit scope_exit(Cleanup const& cleanup) : cleanup_(cleanup) {}756757~scope_exit() { cleanup_(); }758759private:760Cleanup cleanup_;761};762_LIBCPP_CTAD_SUPPORTED_FOR_TYPE(scope_exit);763764uintmax_t remove_all_impl(int parent_directory, const path& p, error_code& ec) {765// First, try to open the path as a directory.766const int options = O_CLOEXEC | O_RDONLY | O_DIRECTORY | O_NOFOLLOW;767int fd = ::openat(parent_directory, p.c_str(), options);768if (fd != -1) {769// If that worked, iterate over the contents of the directory and770// remove everything in it, recursively.771DIR* stream = ::fdopendir(fd);772if (stream == nullptr) {773::close(fd);774ec = detail::capture_errno();775return 0;776}777// Note: `::closedir` will also close the associated file descriptor, so778// there should be no call to `close(fd)`.779scope_exit close_stream([=] { ::closedir(stream); });780781uintmax_t count = 0;782while (true) {783auto [str, type] = detail::posix_readdir(stream, ec);784static_assert(std::is_same_v<decltype(str), std::string_view>);785if (str == "." || str == "..") {786continue;787} else if (ec || str.empty()) {788break; // we're done iterating through the directory789} else {790count += remove_all_impl(fd, str, ec);791}792}793794// Then, remove the now-empty directory itself.795if (::unlinkat(parent_directory, p.c_str(), AT_REMOVEDIR) == -1) {796ec = detail::capture_errno();797return count;798}799800return count + 1; // the contents of the directory + the directory itself801}802803ec = detail::capture_errno();804805// If we failed to open `p` because it didn't exist, it's not an806// error -- it might have moved or have been deleted already.807if (ec == errc::no_such_file_or_directory) {808ec.clear();809return 0;810}811812// If opening `p` failed because it wasn't a directory, remove it as813// a normal file instead. Note that `openat()` can return either ENOTDIR814// or ELOOP depending on the exact reason of the failure. On FreeBSD it815// may return EMLINK instead of ELOOP, contradicting POSIX.816if (ec == errc::not_a_directory || ec == errc::too_many_symbolic_link_levels || ec == errc::too_many_links) {817ec.clear();818if (::unlinkat(parent_directory, p.c_str(), /* flags = */ 0) == -1) {819ec = detail::capture_errno();820return 0;821}822return 1;823}824825// Otherwise, it's a real error -- we don't remove anything.826return 0;827}828829} // end namespace830831uintmax_t __remove_all(const path& p, error_code* ec) {832ErrorHandler<uintmax_t> err("remove_all", ec, &p);833error_code mec;834uintmax_t count = remove_all_impl(AT_FDCWD, p, mec);835if (mec)836return err.report(mec);837return count;838}839840#endif // REMOVE_ALL_USE_DIRECTORY_ITERATOR841842void __rename(const path& from, const path& to, error_code* ec) {843ErrorHandler<void> err("rename", ec, &from, &to);844if (detail::rename(from.c_str(), to.c_str()) == -1)845err.report(capture_errno());846}847848void __resize_file(const path& p, uintmax_t size, error_code* ec) {849ErrorHandler<void> err("resize_file", ec, &p);850if (detail::truncate(p.c_str(), static_cast< ::off_t>(size)) == -1)851return err.report(capture_errno());852}853854space_info __space(const path& p, error_code* ec) {855ErrorHandler<void> err("space", ec, &p);856space_info si;857detail::StatVFS m_svfs = {};858if (detail::statvfs(p.c_str(), &m_svfs) == -1) {859err.report(capture_errno());860si.capacity = si.free = si.available = static_cast<uintmax_t>(-1);861return si;862}863// Multiply with overflow checking.864auto do_mult = [&](uintmax_t& out, uintmax_t other) {865out = other * m_svfs.f_frsize;866if (other == 0 || out / other != m_svfs.f_frsize)867out = static_cast<uintmax_t>(-1);868};869do_mult(si.capacity, m_svfs.f_blocks);870do_mult(si.free, m_svfs.f_bfree);871do_mult(si.available, m_svfs.f_bavail);872return si;873}874875file_status __status(const path& p, error_code* ec) { return detail::posix_stat(p, ec); }876877file_status __symlink_status(const path& p, error_code* ec) { return detail::posix_lstat(p, ec); }878879path __temp_directory_path(error_code* ec) {880ErrorHandler<path> err("temp_directory_path", ec);881882#if defined(_LIBCPP_WIN32API)883wchar_t buf[MAX_PATH];884DWORD retval = GetTempPathW(MAX_PATH, buf);885if (!retval)886return err.report(detail::make_windows_error(GetLastError()));887if (retval > MAX_PATH)888return err.report(errc::filename_too_long);889// GetTempPathW returns a path with a trailing slash, which we890// shouldn't include for consistency.891if (buf[retval - 1] == L'\\')892buf[retval - 1] = L'\0';893path p(buf);894#else895const char* env_paths[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};896const char* ret = nullptr;897898for (auto& ep : env_paths)899if ((ret = getenv(ep)))900break;901if (ret == nullptr) {902# if defined(__ANDROID__)903ret = "/data/local/tmp";904# else905ret = "/tmp";906# endif907}908909path p(ret);910#endif911error_code m_ec;912file_status st = detail::posix_stat(p, &m_ec);913if (!status_known(st))914return err.report(m_ec, "cannot access path " PATH_CSTR_FMT, p.c_str());915916if (!exists(st) || !is_directory(st))917return err.report(errc::not_a_directory, "path " PATH_CSTR_FMT " is not a directory", p.c_str());918919return p;920}921922path __weakly_canonical(const path& p, error_code* ec) {923ErrorHandler<path> err("weakly_canonical", ec, &p);924925if (p.empty())926return __canonical("", ec);927928path result;929path tmp;930tmp.__reserve(p.native().size());931auto PP = PathParser::CreateEnd(p.native());932--PP;933vector<string_view_t> DNEParts;934935error_code m_ec;936while (PP.State_ != PathParser::PS_BeforeBegin) {937tmp.assign(createView(p.native().data(), &PP.RawEntry.back()));938file_status st = __status(tmp, &m_ec);939if (!status_known(st)) {940return err.report(m_ec);941} else if (exists(st)) {942result = __canonical(tmp, &m_ec);943if (m_ec) {944return err.report(m_ec);945}946break;947}948DNEParts.push_back(*PP);949--PP;950}951if (PP.State_ == PathParser::PS_BeforeBegin) {952result = __canonical("", &m_ec);953if (m_ec) {954return err.report(m_ec);955}956}957if (DNEParts.empty())958return result;959for (auto It = DNEParts.rbegin(); It != DNEParts.rend(); ++It)960result /= *It;961return result.lexically_normal();962}963964_LIBCPP_END_NAMESPACE_FILESYSTEM965966967