Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions core/libs/prx/libkernel_sys/Export.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,56 @@ bool IsSymbolicLink(const std::filesystem::path& native) {
#endif
}

bool ReadSymbolicLinkTarget(const std::filesystem::path& native, std::filesystem::path& target) {
#ifdef _WIN32
const DWORD attributes = GetFileAttributesW(native.c_str());
if (attributes == INVALID_FILE_ATTRIBUTES || (attributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0) return false;
std::string text;
if (!File::WindowsSymbolicLink::Read(native, text, "link")) return false;
target = std::filesystem::path(reinterpret_cast<const char8_t*>(text.c_str()));
return true;
#else
std::error_code error;
if (!std::filesystem::is_symlink(std::filesystem::symlink_status(native, error))) return false;
target = std::filesystem::read_symlink(native, error);
if (error) throw std::system_error(error, "link: read_symlink");
return true;
#endif
}

int SymbolicLinkLimitError(const std::filesystem::path& native, bool followLast) {
constexpr int MaxSymbolicLinks = 32;
std::vector<std::filesystem::path> pending;
const auto push = [&pending](const std::filesystem::path& path) {
const std::vector<std::filesystem::path> parts(path.begin(), path.end());
pending.insert(pending.end(), parts.rbegin(), parts.rend());
};
push(native.relative_path());
std::filesystem::path current = native.root_path();
int links = 0;
while (!pending.empty()) {
const auto part = pending.back();
pending.pop_back();
if (part.empty() || part == ".") continue;
if (part == "..") {
std::error_code error;
if (!std::filesystem::is_directory(current, error)) return 0;
current = current.parent_path();
continue;
}
const auto next = current / part;
std::filesystem::path target;
if ((followLast || !pending.empty()) && ReadSymbolicLinkTarget(next, target)) {
if (++links > MaxSymbolicLinks) return GuestEloop;
if (target.has_root_path()) current = target.root_path();
push(target.relative_path());
continue;
}
current = next;
}
return 0;
}

std::int64_t ReadNativeLink(const std::filesystem::path& native, char* buffer, std::size_t size) {
#ifdef _WIN32
const DWORD attributes = GetFileAttributesW(native.wstring().c_str());
Expand Down Expand Up @@ -697,9 +747,11 @@ int APS5_VABI link_nid_postfix(const char* existing, const char* created) {
if (const int error = CopyPath(existing, existingCopy)) return static_cast<int>(Fail(error));
std::filesystem::path source, destination;
if (const int error = ResolvePathError_nid_no_patch(existing, source)) return static_cast<int>(Fail(error));
if (const int error = SymbolicLinkLimitError(source, true)) return static_cast<int>(Fail(error));
if (const int error = LinkSourceError(source)) return static_cast<int>(Fail(error));
if (const int error = CopyPath(created, createdCopy)) return static_cast<int>(Fail(error));
if (const int error = ResolvePathError_nid_no_patch(created, destination)) return static_cast<int>(Fail(error));
if (const int error = SymbolicLinkLimitError(destination, false)) return static_cast<int>(Fail(error));
return LinkNative(source, destination);
}

Expand All @@ -719,11 +771,13 @@ int APS5_VABI linkat_nid_postfix(int fd1, const char* path1, int fd2, const char
if (const int error = CopyPath(path1, copy1)) return static_cast<int>(Fail(error));
std::filesystem::path source, destination;
if (const int error = ResolveAtPath(fd1, path1, source)) return static_cast<int>(Fail(error));
if (const int error = SymbolicLinkLimitError(source, flag != 0)) return static_cast<int>(Fail(error));
const bool linkItself = flag == 0 && IsSymbolicLink(source);
if (!linkItself)
if (const int error = LinkSourceError(source)) return static_cast<int>(Fail(error));
if (const int error = CopyPath(path2, copy2)) return static_cast<int>(Fail(error));
if (const int error = ResolveAtPath(fd2, path2, destination)) return static_cast<int>(Fail(error));
if (const int error = SymbolicLinkLimitError(destination, false)) return static_cast<int>(Fail(error));
if (linkItself) return LinkSymbolicLinkItself(source, destination);
return LinkNative(source, destination);
}
Expand Down
58 changes: 58 additions & 0 deletions core/libs/tests/GuestKernelSys.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,63 @@ void CheckSymlinkTargetRestrictions(const std::filesystem::path& root) {
}
}

void CheckLinkSymbolicLinkLimit(const std::filesystem::path& root) {
const auto chain = root / "link-chain";
const auto folder = chain / "folder";
Require(std::filesystem::create_directories(folder));
std::ofstream((chain / "file.txt").string()).put('x');
std::ofstream((folder / "file.txt").string()).put('x');
const auto at = [&](const std::string& name) { return (chain / name).string(); };
const auto fileLink = [](int index) { return "file" + std::to_string(index); };
const auto folderLink = [](int index) { return "folder" + std::to_string(index); };
const int first = symlink_nid_postfix("file.txt", at(fileLink(1)).c_str());
if (first != 0) {
Require(first == -1 && Error() == 1);
std::fprintf(stderr, "symbolic links unavailable: the link chain limit not tested\n");
Require(std::filesystem::remove(folder / "file.txt") && std::filesystem::remove(folder));
Require(std::filesystem::remove(chain / "file.txt") && std::filesystem::remove(chain));
return;
}
Require(symlink_nid_postfix("folder", at(folderLink(1)).c_str()) == 0);
for (int index = 2; index <= 33; ++index) {
Require(symlink_nid_postfix(fileLink(index - 1).c_str(), at(fileLink(index)).c_str()) == 0);
Require(symlink_nid_postfix(folderLink(index - 1).c_str(), at(folderLink(index)).c_str()) == 0);
}
const auto copy = at("copy.txt");
const auto linksTo = [&](const std::string& source, const std::string& created, const std::filesystem::path& file) {
const bool linked = link_nid_postfix(source.c_str(), created.c_str()) == 0 && std::filesystem::hard_link_count(file) == 2;
return linked && std::filesystem::remove(created);
};
const auto refused = [](int result) { return result == -1 && Error() == 62; };
Require(linksTo(at(fileLink(32)), copy, chain / "file.txt"));
Require(refused(link_nid_postfix(at(fileLink(33)).c_str(), copy.c_str())));
Require(refused(linkat_nid_postfix(-100, at(fileLink(33)).c_str(), -100, copy.c_str(), 0x400)));
Require(linkat_nid_postfix(-100, at(fileLink(33)).c_str(), -100, copy.c_str(), 0) == 0 && RemoveSymlink(copy));
Require(linksTo(at(folderLink(32) + "/file.txt"), copy, folder / "file.txt"));
Require(refused(link_nid_postfix(at(folderLink(33) + "/file.txt").c_str(), copy.c_str())));
Require(refused(linkat_nid_postfix(-100, at(folderLink(33) + "/file.txt").c_str(), -100, copy.c_str(), 0)));
Require(symlink_nid_postfix("file.txt", (folder / "inner").string().c_str()) == 0);
Require(linksTo(at(folderLink(31) + "/inner"), copy, folder / "file.txt"));
Require(refused(link_nid_postfix(at(folderLink(32) + "/inner").c_str(), copy.c_str())));
Require(RemoveSymlink((folder / "inner").string()));
Require(linksTo(at("file.txt"), at(folderLink(32) + "/created.txt"), chain / "file.txt"));
Require(refused(link_nid_postfix(at("file.txt").c_str(), at(folderLink(33) + "/created.txt").c_str())));
Require(refused(linkat_nid_postfix(-100, at("file.txt").c_str(), -100, at(folderLink(33) + "/created.txt").c_str(), 0x400)));
#ifndef _WIN32
const int chainDirectory = sceKernelOpen(chain.string().c_str(), SCE_KERNEL_O_RDONLY | SCE_KERNEL_O_DIRECTORY, 0);
Require(chainDirectory >= 0);
const auto belowMissing = "missing/../" + fileLink(33);
Require(linkat_nid_postfix(chainDirectory, belowMissing.c_str(), -100, copy.c_str(), 0x400) == -1 && Error() == 2);
const auto belowFile = "file.txt/../" + fileLink(33);
Require(linkat_nid_postfix(chainDirectory, belowFile.c_str(), -100, copy.c_str(), 0x400) == -1 && Error() == 20);
Require(sceKernelClose(chainDirectory) == 0);
#endif
Require(!std::filesystem::exists(copy) && !std::filesystem::exists(folder / "created.txt"));
for (int index = 1; index <= 33; ++index) Require(RemoveSymlink(at(fileLink(index))) && RemoveSymlink(at(folderLink(index))));
Require(std::filesystem::remove(folder / "file.txt") && std::filesystem::remove(folder));
Require(std::filesystem::remove(chain / "file.txt") && std::filesystem::remove(chain));
}

UserUcontext sigreturnContext{};
UserUcontext sigreturnResume{};
volatile int sigreturnPasses = 0;
Expand Down Expand Up @@ -1164,6 +1221,7 @@ int main() {
Require(std::filesystem::create_directory(root));
DirectoryRenameTests(root);
OwnershipAndLinkTests(root);
CheckLinkSymbolicLinkLimit(root);
const auto file = (root / "file.txt").string();
std::ofstream(file).put('x');
CheckPathconf(root, file);
Expand Down
2 changes: 1 addition & 1 deletion docs/dev/debt/libkernel_sys.md
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,7 @@
- [readlink](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) on Windows reads a symbolic link's target from its reparse data and returns it with `/` separators, only when the target is relative, as `symlink` creates them. A symbolic link with an absolute target returns its print name, or its substitute name when the print name is empty, without a `\??\` or `\\?\` prefix. A directory junction returns the same kind of name when it is a drive path (`X:\...`), using the print name when that is a drive path and the substitute name otherwise. A mounted volume (`\??\Volume{GUID}\`), any other name surrogate and every reparse point without the name surrogate bit (WOF compression, deduplication, cloud files) return `EINVAL`, as FreeBSD does for a file that is not a link and as CPython's `os.readlink`, which reads only symbolic links and junctions, does
- [aio_read, aio_write, aio_fsync, aio_error, aio_return, aio_suspend, aio_waitcomplete, aio_cancel](../../../core/libs/prx/libkernel_sys/Aio.cpp) (libkernel_sys) - a request with `SIGEV_SIGNAL`, `SIGEV_THREAD_ID` or `SIGEV_KEVENT` completion, or on a socket, throws, because delivering a guest signal or kevent and socket aio are not modelled. One worker thread runs the process's requests one at a time in submission order, so a request is cancellable only until that thread takes it. A queued request keeps the descriptor number, not the open file: closing or reusing the descriptor before it runs changes what it reaches. Pipes fail with `EOPNOTSUPP`, as FreeBSD 11 does with `vfs.aio.enable_unsafe` 0; the console's setting is unverified. Waits are not interrupted by signals (`EINTR`), and timeouts under 1 ms round up to 1 ms (hz 1000). Otherwise the rules follow FreeBSD 11 `vfs_aio.c`
- [readlinkat](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) passes `AT_FDCWD` (-100) and absolute paths to `readlink`. Any other relative path is joined to the descriptor's host directory, found the same way as for `fchdir`, so guest path aliases and case-insensitive name matching do not apply to it, and a `..` component is not kept inside the guest root. It returns `EBADF` for a descriptor that is not open and `ENOTDIR` for one that is not a directory. Console behaviour is unverified
- [link](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) on Windows resolves a symbolic link source through the host, which follows longer chains than FreeBSD: a chain of 40 links is linked, where FreeBSD 11.4 returns `ELOOP` after 32 (`MAXSYMLINKS`). A loop returns `ELOOP` as on FreeBSD
- [link](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) and `linkat` count the symbolic links met while resolving the source and the new name, and return `ELOOP` at the 33rd, as FreeBSD 11.4's [`namei`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/kern/vfs_lookup.c#L484-L487) does with `MAXSYMLINKS` (32), where the hosts allow longer chains (Linux 40). The count walks the host path from its root, so symbolic links in the host directories a guest path maps to count too; only Windows symbolic links count there, not junctions. A guest path, and on Windows a descriptor-relative one, reaches the count with its `..` components already dropped lexically, so a link a dropped component would have followed is not counted
- [pthread_attr_setcreatesuspend_np, pthread_resume_np, pthread_resume_all_np, pthread_multi_np, scePthreadAttrSetcreatesuspend, scePthreadResume, scePthreadResumeAll and scePthreadMulti](../../../core/libs/prx/libkernel_sys/Export.Discovery.cpp) (libkernel_sys) - when a thread created suspended stops relative to its signal mask is unmeasured on a console. Return values and errors follow FreeBSD 11.4 libthr ([`thr_attr.c`](https://github.com/freebsd/freebsd-src/blob/8c639945/lib/libthr/thread/thr_attr.c#L369-L381), [`thr_resume_np.c`](https://github.com/freebsd/freebsd-src/blob/8c639945/lib/libthr/thread/thr_resume_np.c#L47-L97), [`thr_multi_np.c`](https://github.com/freebsd/freebsd-src/blob/8c639945/lib/libthr/thread/thr_multi_np.c#L40-L51)) and the code of firmware 13.42's `libkernel_sys.sprx` ([#9573](https://github.com/boykopovar/AnyPS5/pull/9573#issuecomment-6393877843)), where the sce forms add `0x80020000` to a non-zero errno
- [pthread_attr_setstackaddr and pthread_attr_getsolosched_np](../../../core/libs/prx/libkernel_sys/Export.Discovery.cpp) (libkernel_sys) - firmware 13.60 `libkernel_sys.sprx` (SHA-256 `60921322b155ba649cfa29ea5e6d358ca0229424b4f73fd5c30ae7f7ce7c304c`) places `pthread_attr_setstackaddr` (NID `suCrEbr0xIQ`) at function address `0x4ed0`: it returns `EINVAL` for a null attribute pointer, null attribute handle or null stack address, and stores a valid address at attribute offset `0x18`. `pthread_attr_getsolosched_np` (NID `ApMLfJ527Ag`) is at `0x51b0`: it returns `EINVAL` for a null attribute pointer, null handle or null output, otherwise writes the attribute field at `+0x10` masked with `0x10`. These details are from local firmware disassembly; console runtime behavior is not independently tested
- [sceKernelGetCpumodeGame and sceKernelSetCpumodeGame](../../../core/libs/prx/libkernel_sys/Export.cpp) (libkernel_sys) - the setter takes the mode as its only argument and the getter writes it through an `int*`, as [ProsperoEden (PPSA99008) declares and calls them](https://github.com/mihawk-99/PS5_ProsperoEden/blob/a0b65fe50dd48d4064e2f58fa9c8d44665478878/headless/performance.cpp#L1030-L1062); its getter faulted when called without one, which throws here. The mode starts at 1, 0 and 1 are accepted, and 2 to 7 return `EINVAL` (0x80020016), as it [measured](https://github.com/mihawk-99/PS5_ProsperoEden/blob/a0b65fe50dd48d4064e2f58fa9c8d44665478878/docs/PERFORMANCE_FINDINGS.md#L113-L114) on a PS5; other modes were not tried and throw. That the getter reports the last accepted mode is inferred from the probe. The mode changes nothing else here: on the console 0 gave system CPU mode 1 and 1 mode 5, while `sceKernelGetCpumode` still returns 0.
Expand Down
Loading