File size: 67,973 Bytes
07a3434
1
2
{"repo_name": "NoHello", "file_name": "/NoHello/module/src/main/cpp/MountRuleParser.cpp", "inference_info": {"prefix_code": "#include <fstream>\n#include <sstream>\n#include <vector>\n#include <unordered_set>\n#include <algorithm>\n#include <string>\n#include \"log.h\"\n\nclass MountRuleParser {\npublic:\n\tstruct MountRule {\n\t\tstd::vector<std::string> rootSubstrs;\n\t\tstd::vector<std::string> mountPointSubstrs;\n\t\tstd::unordered_set<std::string> fsTypes;\n\t\tstd::vector<std::string> sources; // changed from unordered_set to vector for wildcard matching\n\n\t\texplicit operator bool() const {\n\t\t\treturn !(rootSubstrs.empty() && mountPointSubstrs.empty() && fsTypes.empty() && sources.empty());\n\t\t}\n\n\t\tbool matches(const std::string& root, const std::string& mountPoint,\n\t\t\t\t\t const std::string& fsType, const std::string& source) const {\n\t\t\treturn matchList(rootSubstrs, root) &&\n\t\t\t\t   matchList(mountPointSubstrs, mountPoint) &&\n\t\t\t\t   (fsTypes.empty() || fsTypes.count(fsType) > 0) &&\n\t\t\t\t   matchSourceList(sources, source);\n\t\t}\n\n\t\tbool matches(const std::vector<std::string>& roots, const std::string& mountPoint,\n\t\t\t\t\t const std::string& fsType, const std::string& source) const {\n\t\t\tif (!matchList(mountPointSubstrs, mountPoint) ||\n\t\t\t\t(!fsTypes.empty() && fsTypes.count(fsType) == 0) ||\n\t\t\t\t!matchSourceList(sources, source)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tfor (const auto& root : roots) {\n\t\t\t\tif (matchList(rootSubstrs, root)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\n\tprivate:\n\t\tstatic bool match_with_wildcard(const std::string& value, const std::string& rawPattern) {\n\t\t\tstd::string pattern;\n\t\t\tstd::vector<bool> isEscaped;\n\n\t\t\tfor (size_t i = 0; i < rawPattern.size(); ++i) {\n\t\t\t\tif (rawPattern[i] == '\\\\' && i + 1 < rawPattern.size()) {\n\t\t\t\t\t++i;\n\t\t\t\t\tpattern += rawPattern[i];\n\t\t\t\t\tisEscaped.push_back(true);\n\t\t\t\t} else {\n\t\t\t\t\tpattern += rawPattern[i];\n\t\t\t\t\tisEscaped.push_back(false);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbool startsWithWildcard = !pattern.empty() && pattern.front() == '*' && !isEscaped[0];\n\t\t\tbool endsWithWildcard = !pattern.empty() &&\n\t\t\t\t\t\t\t\t\tpattern.back() == '*' &&\n\t\t\t\t\t\t\t\t\t!isEscaped[pattern.size() - 1];\n\n\t\t\tif (startsWithWildcard && endsWithWildcard && pattern.size() > 2) {\n\t\t\t\treturn value.find(pattern.substr(1, pattern.size() - 2)) != std::string::npos;\n\t\t\t} else if (startsWithWildcard) {\n\t\t\t\tstd::string suffix = pattern.substr(1);\n\t\t\t\treturn value.size() >= suffix.size() &&\n\t\t\t\t\t   value.compare(value.size() - suffix.size(), suffix.size(), suffix) == 0;\n\t\t\t} else if (endsWithWildcard) {\n\t\t\t\tstd::string prefix = pattern.substr(0, pattern.size() - 1);\n\t\t\t\treturn value.compare(0, prefix.size(), prefix) == 0;\n\t\t\t} else {\n\t\t\t\treturn value == pattern;\n\t\t\t}\n\t\t}\n\n\t\tstatic bool match_source_pattern(const std::string& value, const std::string& rawPattern) {\n\t\t\tstd::string pattern;\n\t\t\tstd::vector<bool> isEscaped;\n\n\t\t\tfor (size_t i = 0; i < rawPattern.size(); ++i) {\n\t\t\t\tif (rawPattern[i] == '\\\\' && i + 1 < rawPattern.size()) {\n\t\t\t\t\t++i;\n\t\t\t\t\tpattern += rawPattern[i];\n\t\t\t\t\tisEscaped.push_back(true);\n\t\t\t\t} else {\n\t\t\t\t\tpattern += rawPattern[i];\n\t\t\t\t\tisEscaped.push_back(false);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbool startsWithWildcard = !pattern.empty() && pattern.front() == '*' && !isEscaped[0];\n\t\t\tbool endsWithWildcard = !pattern.empty() &&\n\t\t\t\t\t\t\t\t\tpattern.back() == '*' &&\n\t\t\t\t\t\t\t\t\t!isEscaped[pattern.size() - 1];\n\n\t\t\tif (startsWithWildcard && endsWithWildcard && pattern.size() > 2) {\n\t\t\t\treturn value.find(pattern.substr(1, pattern.size() - 2)) != std::string::npos;\n\t\t\t} else if (startsWithWildcard) {\n\t\t\t\tstd::string suffix = pattern.substr(1);\n\t\t\t\treturn value.size() >= suffix.size() &&\n\t\t\t\t\t   value.compare(value.size() - suffix.size(), suffix.size(), suffix) == 0;\n\t\t\t} else if (endsWithWildcard) {\n\t\t\t\tstd::string prefix = pattern.substr(0, pattern.size() - 1);\n\t\t\t\treturn value.compare(0, prefix.size(), prefix) == 0;\n\t\t\t} else {\n\t\t\t\treturn value == pattern;\n\t\t\t}\n\t\t}\n\n\t\tstatic bool matchList(const std::vector<std::string>& patterns, const std::string& value) {\n\t\t\tif (patterns.empty()) return true;\n\t\t\treturn std::any_of(patterns.begin(), patterns.end(),\n\t\t\t\t\t\t\t   [&](const std::string& p) { return match_with_wildcard(value, p); });\n\t\t}\n\n\t\tstatic bool matchSourceList(const std::vector<std::string>& patterns, const std::string& value) {\n\t\t\tif (patterns.empty()) return true;\n\t\t\treturn std::any_of(patterns.begin(), patterns.end(),\n\t\t\t\t\t\t\t   [&](const std::string& p) { return match_source_pattern(value, p); });\n\t\t}\n\t};\n\n\t// Not necessary anymore\n\tstruct MountEntry {\n\t\tstd::string root;\n\t\tstd::string mountPoint;\n\t\tstd::string fsType;\n\t\tstd::string mountSource;\n\t};\n\n\t// Used previously for testing its effectiveness\n\tstatic MountEntry parseMountinfo(const std::string& line) {\n\t\tstd::istringstream iss(line);\n\t\tstd::vector<std::string> tokens;\n\t\tstd::string token;\n\n\t\twhile (iss >> token) tokens.push_back(token);\n\n\t\tauto sep = std::find(tokens.begin(), tokens.end(), \"-\");\n\t\tif (sep == tokens.end() || std::distance(tokens.begin(), sep) < 6) {\n\t\t\tLOGE(\"[MountRuleParser::parseMultipleRules]: Malformed mountinfo line\");\n\t\t\treturn {};\n\t\t}\n\n\t\tMountEntry entry;\n\t\tentry.root = tokens[3];\n\t\tentry.mountPoint = tokens[4];\n\t\tentry.fsType = *(sep + 1);\n\t\tentry.mountSource = *(sep + 2);\n\t\treturn entry;\n\t}\n\n\tstatic MountRule parseRuleString(const std::string& ruleText) {\n\t\tif (!validateSyntax(ruleText)) {\n\t\t\treturn {};\n\t\t}\n\n\t\tMountRule rule;\n\t\tauto tokens = tokenizePreserveQuotes(ruleText);\n\n\t\tenum Section { NONE, ROOT, POINT, FILESYSTEM, SOURCE } current = NONE;\n\t\tenum State { WRITING, IDLE } state = IDLE;\n\n\t\tfor (std::string& word : tokens) {\n\t\t\t", "suffix_code": "\n\t\t}\n\n\t\treturn rule;\n\t}\n\n\tstatic std::vector<MountRule> parseMultipleRules(const std::vector<std::string>& ruleTexts) {\n\t\tstd::vector<MountRule> rules;\n\t\tfor (const auto& text : ruleTexts) {\n\t\t\tMountRule rule = parseRuleString(text);\n\t\t\tif (rule) {\n\t\t\t\trules.push_back(rule);\n\t\t\t} else {\n\t\t\t\tLOGE(\"[MountRuleParser::parseMultipleRules]: Failed to parse rule: `%s`\", text.c_str());\n\t\t\t}\n\t\t}\n\t\treturn rules;\n\t}\n\nprivate:\n\tstatic bool validateSyntax(const std::string& text) {\n\t\tint braceCount = 0;\n\t\tbool inDoubleQuotes = false, inSingleQuotes = false;\n\n\t\tfor (size_t i = 0; i < text.size(); ++i) {\n\t\t\tchar ch = text[i];\n\t\t\tif (ch == '\"' && !inSingleQuotes && (i == 0 || text[i - 1] != '\\\\'))\n\t\t\t\tinDoubleQuotes = !inDoubleQuotes;\n\t\t\telse if (ch == '\\'' && !inDoubleQuotes && (i == 0 || text[i - 1] != '\\\\'))\n\t\t\t\tinSingleQuotes = !inSingleQuotes;\n\n\t\t\tif (!inDoubleQuotes && !inSingleQuotes) {\n\t\t\t\tif (ch == '{') ++braceCount;\n\t\t\t\telse if (ch == '}') {\n\t\t\t\t\t--braceCount;\n\t\t\t\t\tif (braceCount < 0) return false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn braceCount == 0 && !inDoubleQuotes && !inSingleQuotes;\n\t}\n\n\tstatic std::vector<std::string> tokenizePreserveQuotes(const std::string& text) {\n\t\tstd::vector<std::string> tokens;\n\t\tstd::string current;\n\t\tbool inQuotes = false;\n\t\tchar quoteChar = '\\0';\n\n\t\tfor (size_t i = 0; i < text.length(); ++i) {\n\t\t\tchar c = text[i];\n\n\t\t\tif ((c == '\"' || c == '\\'') && (i == 0 || text[i - 1] != '\\\\')) {\n\t\t\t\tif (!inQuotes) {\n\t\t\t\t\tinQuotes = true;\n\t\t\t\t\tquoteChar = c;\n\t\t\t\t\tcurrent += c;\n\t\t\t\t} else if (c == quoteChar) {\n\t\t\t\t\tinQuotes = false;\n\t\t\t\t\tcurrent += c;\n\t\t\t\t\ttokens.push_back(current);\n\t\t\t\t\tcurrent.clear();\n\t\t\t\t} else {\n\t\t\t\t\tcurrent += c;\n\t\t\t\t}\n\t\t\t} else if (std::isspace(c) && !inQuotes) {\n\t\t\t\tif (!current.empty()) {\n\t\t\t\t\ttokens.push_back(current);\n\t\t\t\t\tcurrent.clear();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcurrent += c;\n\t\t\t}\n\t\t}\n\n\t\tif (!current.empty()) tokens.push_back(current);\n\t\treturn tokens;\n\t}\n};\n", "middle_code": "if (state == IDLE) {\n\t\t\t\tif (current == NONE) {\n\t\t\t\t\tif (word == \"root\") current = ROOT;\n\t\t\t\t\telse if (word == \"point\") current = POINT;\n\t\t\t\t\telse if (word == \"fs\") current = FILESYSTEM;\n\t\t\t\t\telse if (word == \"source\") current = SOURCE;\n\t\t\t\t} else if (word == \"{\") {\n\t\t\t\t\tstate = WRITING;\n\t\t\t\t}\n\t\t\t} else if (state == WRITING && word == \"}\") {\n\t\t\t\tcurrent = NONE;\n\t\t\t\tstate = IDLE;\n\t\t\t} else {\n\t\t\t\tif ((word.front() == '\"' && word.back() == '\"') ||\n\t\t\t\t\t(word.front() == '\\'' && word.back() == '\\'')) {\n\t\t\t\t\tword = word.substr(1, word.size() - 2);\n\t\t\t\t}\n\t\t\t\tswitch (current) {\n\t\t\t\t\tcase ROOT:\n\t\t\t\t\t\trule.rootSubstrs.push_back(word);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase POINT:\n\t\t\t\t\t\trule.mountPointSubstrs.push_back(word);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase FILESYSTEM:\n\t\t\t\t\t\trule.fsTypes.insert(word);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase SOURCE:\n\t\t\t\t\t\trule.sources.push_back(word); \n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}", "code_description": null, "fill_type": "BLOCK_TYPE", "language_type": "cpp", "sub_task_type": "if_statement"}, "context_code": [["/NoHello/module/src/main/cpp/nohello.cpp", "/* Copyright 2022-2023 John \"topjohnwu\" Wu\n * Copyright 2024 The NoHello Contributors\n *\n * Permission to use, copy, modify, and/or distribute this software for any\n * purpose with or without fee is hereby granted.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\n * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\n * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n * PERFORMANCE OF THIS SOFTWARE.\n */\n\n#include <cstdlib>\n#include <unistd.h>\n#include <fcntl.h>\n#include <android/log.h>\n#include <filesystem>\n#include <ranges>\n#include <vector>\n#include <utility> // For std::pair, std::move\n\n#include \"zygisk.hpp\"\n#include \"external/android_filesystem_config.h\"\n#include \"mountsinfo.cpp\"\n#include \"utils.cpp\"\n#include \"external/fdutils/fd_utils.cpp\"\n#include <sys/mount.h>\n#include <sys/ptrace.h>\n#include <endian.h>\n#include <thread>\n#include \"log.h\"\n#include \"PropertyManager.cpp\"\n#include \"MountRuleParser.cpp\"\n#include \"external/emoji.h\"\n\nusing zygisk::Api;\nusing zygisk::AppSpecializeArgs;\nusing zygisk::ServerSpecializeArgs;\n\nnamespace fs = std::filesystem;\n\nstatic constexpr off_t EXT_SUPERBLOCK_OFFSET = 0x400;\nstatic constexpr off_t EXT_MAGIC_OFFSET = 0x38;\nstatic constexpr off_t EXT_ERRORS_OFFSET = 0x3C;\nstatic constexpr uint16_t EXT_MAGIC = 0xEF53;\nstatic const std::vector<std::string> defaultRules = {\n\t\tR\"(source { \"KSU\", \"APatch\", \"magisk\", \"worker\" } fs { \"tmpfs\" \"overlay\" })\"\n};\n\nenum Advice {\n\tNORMAL = 0,\n\tMODULE_CONFLICT = 2,\n};\n\nenum State {\n\tSUCCESS = 0,\n\tFAILURE = 1\n};\n\nstatic const std::set<std::string> toumount_sources = {\"KSU\", \"APatch\", \"magisk\", \"worker\"};\nstatic const std::string adbPathPrefix = \"/data/adb\";\n\nstatic bool anomaly(MountRootResolver mrs, const MountInfo &mount) {\n\tconst std::string resolved_root = mrs.resolveRoot(mount);\n\tif (resolved_root.starts_with(adbPathPrefix) || mount.getMountPoint().starts_with(adbPathPrefix)) {\n\t\treturn true;\n\t}\n\tconst auto& fs_type = mount.getFsType();\n\tconst auto& mnt_src = mount.getMountSource();\n\tif (toumount_sources.count(mnt_src)) {\n\t\treturn true;\n\t}\n\tif (fs_type == \"overlay\") {\n\t\tif (toumount_sources.count(mnt_src)) {\n\t\t\treturn true;\n\t\t}\n\t\tconst auto& fm = mount.getMountOptions().flagmap;\n\t\tif (fm.count(\"lowerdir\") && fm.at(\"lowerdir\").starts_with(adbPathPrefix)) {\n\t\t\treturn true;\n\t\t}\n\t\tif (fm.count(\"upperdir\") && fm.at(\"upperdir\").starts_with(adbPathPrefix)) {\n\t\t\treturn true;\n\t\t}\n\t\tif (fm.count(\"workdir\") && fm.at(\"workdir\").starts_with(adbPathPrefix)) {\n\t\t\treturn true;\n\t\t}\n\t} else if (fs_type == \"tmpfs\") {\n\t\tif (toumount_sources.count(mnt_src)) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nstatic bool anomaly(const MountRuleParser::MountRule& rule, MountRootResolver mrs, const MountInfo &mount) {\n\tconst std::string resolvedRoot = mrs.resolveRoot(mount);\n\tconst auto& fsType = mount.getFsType();\n\tif (fsType != \"overlay\") {\n\t\treturn rule.matches(resolvedRoot, mount.getMountPoint(), fsType, mount.getMountSource());\n\t} else {\n\t\tconst auto& fm = mount.getMountOptions().flagmap;\n\t\tstd::vector<std::string> roots = {resolvedRoot};\n\t\tfor (const auto* key : {\"lowerdir\", \"upperdir\", \"workdir\"}) {\n\t\t\tauto it = fm.find(key);\n\t\t\tif (it != fm.end()) {\n\t\t\t\troots.push_back(it->second);\n\t\t\t}\n\t\t}\n\t\treturn rule.matches(roots, mount.getMountPoint(), fsType, mount.getMountSource());\n\t}\n\treturn false;\n}\n\nstatic bool anomaly(const std::vector<MountRuleParser::MountRule>& rules, MountRootResolver mrs, const MountInfo &mount) {\n\tconst std::string resolvedRoot = mrs.resolveRoot(mount);\n\tconst auto& fsType = mount.getFsType();\n\tconst auto& fm = mount.getMountOptions().flagmap;\n\tfor (const auto& rule : rules) {\n\t\tif (fsType != \"overlay\") {\n\t\t\tif (rule.matches(resolvedRoot, mount.getMountPoint(), fsType, mount.getMountSource()))\n\t\t\t\treturn true;\n\t\t} else {\n\t\t\tstd::vector<std::string> roots = {resolvedRoot};\n\t\t\tfor (const auto* key : {\"lowerdir\", \"upperdir\", \"workdir\"}) {\n\t\t\t\tauto it = fm.find(key);\n\t\t\t\tif (it != fm.end()) {\n\t\t\t\t\troots.push_back(it->second);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (rule.matches(roots, mount.getMountPoint(), fsType, mount.getMountSource()))\n\t\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nstatic std::pair<bool, bool> anomaly(const std::unique_ptr<FileDescriptorInfo> fdi) {\n\tif (fdi->is_sock) {\n\t\tstd::string socket_name;\n\t\tif (fdi->GetSocketName(&socket_name)) {\n\t\t\tif (socket_name.find(\"magisk\") != std::string::npos ||\n\t\t\t\tsocket_name.find(\"kernelsu\") != std::string::npos || // For KernelSU daemon, common pattern\n\t\t\t\tsocket_name.find(\"ksud\") != std::string::npos || // KernelSU daemon\n\t\t\t\tsocket_name.find(\"apatchd\") != std::string::npos || // For APatch daemon, common pattern\n\t\t\t\tsocket_name.find(\"apd\") != std::string::npos      // APatch daemon\n\t\t\t\t\t) {\n\t\t\t\tLOGD(\"Marking sensitive socket FD %d (%s) for sanitization.\", fdi->fd, socket_name.c_str());\n\t\t\t\treturn {true, true};\n\t\t\t}\n\t\t}\n\t} else { // Not a socket\n\t\tif (!fdi->file_path.starts_with(\"/memfd:\") &&\n\t\t\t!fdi->file_path.starts_with(\"/dev/ashmem\") && // Common, usually not root related\n\t\t\t!fdi->file_path.starts_with(\"[anon_inode:\") && // e.g., [anon_inode:sync_fence]\n\t\t\t!fdi->file_path.empty() // Ensure path is not empty\n\t\t\t\t) {\n\t\t\tif (fdi->file_path.starts_with(adbPathPrefix) ||\n\t\t\t\tfdi->file_path.find(\"magisk\") != std::string::npos ||\n\t\t\t\tfdi->file_path.find(\"kernelsu\") != std::string::npos ||\n\t\t\t\tfdi->file_path.find(\"apatch\") != std::string::npos) {\n\t\t\t\tLOGD(\"Marking sensitive file FD %d (%s) for sanitization.\", fdi->fd, fdi->file_path.c_str());\n\t\t\t\treturn {true, true};\n\t\t\t}\n\t\t}\n\t}\n\treturn {false, false};\n}\n\n\nstatic std::unique_ptr<std::string> getExternalErrorBehaviour(const MountInfo& mount) {\n\tconst auto& fs = mount.getFsType();\n\tif (fs != \"ext2\" && fs != \"ext3\" && fs != \"ext4\")\n\t\treturn nullptr;\n\tstd::ifstream mntsrc(mount.getMountSource(), std::ios::binary);\n\tif (!mntsrc || !mntsrc.is_open())\n\t\treturn nullptr;\n\tuint16_t magic;\n\tmntsrc.seekg(EXT_SUPERBLOCK_OFFSET + EXT_MAGIC_OFFSET, std::ios::beg);\n\tmntsrc.read(reinterpret_cast<char *>(&magic), sizeof(magic));\n\tif (!mntsrc || mntsrc.gcount() != sizeof(magic))\n\t\treturn nullptr;\n\tmagic = le16toh(magic);\n\tif (magic != EXT_MAGIC)\n\t\treturn nullptr;\n\tuint16_t errors;\n\tmntsrc.seekg(EXT_SUPERBLOCK_OFFSET + EXT_ERRORS_OFFSET, std::ios::beg);\n\tmntsrc.read(reinterpret_cast<char *>(&errors), sizeof(errors));\n\tif (!mntsrc || mntsrc.gcount() != sizeof(errors))\n\t\treturn nullptr;\n\terrors = le16toh(errors);\n\tswitch (errors)\n\t{\n\t\tcase 1:\n\t\t\treturn std::make_unique<std::string>(\"continue\");\n\t\tcase 2:\n\t\t\treturn std::make_unique<std::string>(\"remount-ro\");\n\t\tcase 3:\n\t\t\treturn std::make_unique<std::string>(\"panic\");\n\t\tdefault:\n\t\t\treturn nullptr;\n\t}\n\treturn nullptr;\n}\n\nstatic void doumount(const std::string& mntPnt);\n\nstatic void unmount(const std::vector<MountInfo>& mounts) {\n\tMountRootResolver mrs(mounts);\n\tfor (const auto& mount : std::ranges::reverse_view(mounts)) {\n\t\tif (anomaly(mrs, mount))\n\t\t\tdoumount(mount.getMountPoint());\n\t}\n}\n\nstatic void unmount(const std::vector<MountRuleParser::MountRule>& rules, const std::vector<MountInfo>& mounts) {\n\tMountRootResolver mrs(mounts);\n\tfor (const auto& mount : std::ranges::reverse_view(mounts)) {\n\t\tif (anomaly(rules, mrs, mount))\n\t\t\tdoumount(mount.getMountPoint());\n\t}\n}\n\nstatic void unmount(const MountRuleParser::MountRule& rule, const std::vector<MountInfo>& mounts) {\n\tMountRootResolver mrs(mounts);\n\tfor (const auto& mount : std::ranges::reverse_view(mounts)) {\n\t\tif (anomaly(rule, mrs, mount))\n\t\t\tdoumount(mount.getMountPoint());\n\t}\n}\n\nstatic void doumount(const std::string& mntPnt) {\n\terrno = 0;\n\tint res;\n\tconst char *mntpnt = mntPnt.c_str();\n\tif ((res = umount2(mntpnt, MNT_DETACH)) == 0)\n\t\tLOGD(\"umount2(\\\"%s\\\", MNT_DETACH): returned (0): 0 (Success)\", mntpnt);\n\telse\n\t\tLOGE(\"umount2(\\\"%s\\\", MNT_DETACH): returned %d: %d (%s)\", mntpnt, res, errno, strerror(errno));\n}\n\nstatic void remount(const std::vector<MountInfo>& mounts) {\n\tfor (const auto& mount : mounts) {\n\t\tif (mount.getMountPoint() == \"/data\") {\n\t\t\tconst auto& mntopts = mount.getMountOptions();\n\t\t\tconst auto& fm = mntopts.flagmap;\n\t\t\tif (!fm.count(\"errors\"))\n\t\t\t\tbreak;\n\t\t\tauto errors = getExternalErrorBehaviour(mount);\n\t\t\tif (!errors || fm.at(\"errors\") == *errors)\n\t\t\t\tbreak;\n\t\t\tauto mntflags = mount.getFlags();\n\t\t\tunsigned int flags = MS_REMOUNT;\n\t\t\tif (mntflags & MountFlags::NOSUID) {\n\t\t\t\tflags |= MS_NOSUID;\n\t\t\t}\n\t\t\tif (mntflags & MountFlags::NODEV) {\n\t\t\t\tflags |= MS_NODEV;\n\t\t\t}\n\t\t\tif (mntflags & MountFlags::NOEXEC) {\n\t\t\t\tflags |= MS_NOEXEC;\n\t\t\t}\n\t\t\tif (mntflags & MountFlags::NOATIME) {\n\t\t\t\tflags |= MS_NOATIME;\n\t\t\t}\n\t\t\tif (mntflags & MountFlags::NODIRATIME) {\n\t\t\t\tflags |= MS_NODIRATIME;\n\t\t\t}\n\t\t\tif (mntflags & MountFlags::RELATIME) {\n\t\t\t\tflags |= MS_RELATIME;\n\t\t\t}\n\t\t\tif (mntflags & MountFlags::NOSYMFOLLOW) {\n\t\t\t\tflags |= MS_NOSYMFOLLOW;\n\t\t\t}\n\t\t\tint res;\n\t\t\tif ((res = ::mount(nullptr, \"/data\", nullptr, flags, (std::string(\"errors=\") + *errors).c_str())) == 0)\n\t\t\t\tLOGD(\"mount(nullptr, \\\"/data\\\", nullptr, 0x%x, \\\"errors=%s\\\"): returned 0: 0 (Success)\", flags, errors->c_str());\n\t\t\telse\n\t\t\t\tLOGW(\"mount(NULL, \\\"/data\\\", NULL, 0x%x, \\\"errors=%s\\\"): returned %d: %d (%s)\", flags, errors->c_str(), res, errno, strerror(errno));\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nint (*ar_unshare)(int) = nullptr;\n\nstatic int reshare(int flags) {\n    errno = 0;\n    return ar_unshare(flags & ~(CLONE_NEWNS | CLONE_NEWCGROUP));\n}\n\nclass NoHello : public zygisk::ModuleBase {\npublic:\n    void onLoad(Api *_api, JNIEnv *_env) override {\n        this->api = _api;\n        this->env = _env;\n    }\n\n    void preAppSpecialize(AppSpecializeArgs *args) override {\n        preSpecialize(args);\n    }\n\n\tvoid postAppSpecialize(const AppSpecializeArgs *args) override {\n\t\tconst char *process = env->GetStringUTFChars(args->nice_name, nullptr);\n\t\tpostSpecialize(process);\n\t\tenv->ReleaseStringUTFChars(args->nice_name, process);\n\t}\n\n    void preServerSpecialize(ServerSpecializeArgs *args) override {\n        //preSpecialize(\"system_server\"); // System server usually doesn't need this level of hiding\n\t\tapi->setOption(zygisk::Option::DLCLOSE_MODULE_LIBRARY);\n    }\n\nprivate:\n    Api *api{};\n    JNIEnv *env{};\n\tint cfd{};\n\tdev_t rundev{};\n\tino_t runinode{};\n\tdev_t cdev{};\n\tino_t cinode{};\n\n\n    void preSpecialize(AppSpecializeArgs *args) {\n\t\tunsigned int flags = api->getFlags();\n\t\tconst bool whitelist = access(\"/data/adb/nohello/whitelist\", F_OK) == 0;\n\t\tconst bool nodirtyro = access(\"/data/adb/nohello/no_dirtyro_ar\", F_OK) == 0;\n\t\tif (flags & zygisk::StateFlag::PROCESS_GRANTED_ROOT) {\n\t\t\tapi->setOption(zygisk::Option::DLCLOSE_MODULE_LIBRARY);\n\t\t\treturn;\n\t\t}\n\t\tauto fn = [this](const std::string& lib) {\n\t\t\tauto di = devinoby(lib.c_str());\n\t\t\tif (di) {\n\t\t\t\treturn *di;\n\t\t\t} else {\n\t\t\t\tLOGW(\"#[zygisk::?] devino[dl_iterate_phdr]: Failed to get device & inode for %s\", lib.c_str());\n\t\t\t\tLOGI(\"#[zygisk::?] Fallback to use `/proc/self/maps`\");\n\t\t\t\treturn devinobymap(lib);\n\t\t\t}\n\t\t};\n\t\tif ((whitelist && isuserapp(args->uid)) || flags & zygisk::StateFlag::PROCESS_ON_DENYLIST) {\n\t\t\tpid_t pid = getpid(), ppid = getppid();\n\t\t\tcfd = api->connectCompanion(); // Companion FD\n\t\t\tapi->exemptFd(cfd);\n\t\t\tif (write(cfd, &ppid, sizeof(ppid)) != sizeof(ppid)) {\n\t\t\t\tLOGE(\"#[zygisk::preSpecialize] write: [-> ppid]: %s\", strerror(errno));\n\t\t\t\tclose(cfd);\n\t\t\t\tapi->setOption(zygisk::Option::DLCLOSE_MODULE_LIBRARY);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tint advice;\n\t\t\tif (read(cfd, &advice, sizeof(advice)) != sizeof(advice)) {\n\t\t\t\tLOGE(\"#[zygisk::preSpecialize] read: [<- status]: %s\", strerror(errno));\n\t\t\t\tclose(cfd);\n\t\t\t\tapi->setOption(zygisk::Option::DLCLOSE_MODULE_LIBRARY);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (advice == MODULE_CONFLICT) {\n\t\t\t\tclose(cfd);\n\t\t\t\tapi->setOption(zygisk::Option::DLCLOSE_MODULE_LIBRARY);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tstd::tie(cdev, cinode) = fn(\"libc.so\");\n\t\t\tif (!cdev && !cinode) {\n\t\t\t\tLOGE(\"#[zygisk::preSpecialize] Failed to get device & inode for libc.so\");\n\t\t\t\tclose(cfd);\n\t\t\t\tapi->setOption(zygisk::Option::DLCLOSE_MODULE_LIBRARY);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tstd::tie(rundev, runinode) = fn(\"libandroid_runtime.so\");\n\t\t\tif (!rundev && !runinode) {\n\t\t\t\tLOGE(\"#[zygisk::preSpecialize] Failed to get device & inode for libandroid_runtime.so\");\n\t\t\t\tclose(cfd);\n\t\t\t\tapi->setOption(zygisk::Option::DLCLOSE_MODULE_LIBRARY);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tapi->pltHookRegister(rundev, runinode, \"unshare\", (void*) reshare, (void**) &ar_unshare);\n\t\t\tapi->pltHookCommit();\n\t\t\tif (!nodirtyro) {\n\t\t\t\tif (auto res = robaseby(rundev, runinode)) {\n\t\t\t\t\t/*\n\t\t\t\t\t * Temporary workaround to fix detection in apps that checks Shared_Clean\n\t\t\t\t\t * if >= 512kb\n\t\t\t\t\t */\n\t\t\t\t\tauto [base, size] = *res;\n\t\t\t\t\tlong pagesz = sysconf(_SC_PAGESIZE);\n\t\t\t\t\tsize_t alignedSize = (size + pagesz - 1) & ~(pagesz - 1);\n\t\t\t\t\tmprotect(base, alignedSize, PROT_READ | PROT_WRITE);\n\t\t\t\t\tfor (uintptr_t addr = (uintptr_t) base; addr < (uintptr_t) base + size; addr += pagesz) {\n\t\t\t\t\t\tvoid* page = reinterpret_cast<void*>(addr);\n\t\t\t\t\t\tuint8_t orig = *(volatile uint8_t*) page;\n\t\t\t\t\t\t*(volatile uint8_t*) page = orig;\n\t\t\t\t\t}\n\t\t\t\t\tmprotect(base, alignedSize, PROT_READ);\n\t\t\t\t\tmadvise(base, alignedSize, MADV_REMOVE);\n\t\t\t\t} else {\n\t\t\t\t\tLOGW(\"#[zygisk::preSpecialize] Failed to get ro block for libandroid_runtime.so\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::vector<std::pair<std::unique_ptr<FileDescriptorInfo>, bool>> fdSanitizeList; // bool is shouldDetach\n\t\t\tauto fds = GetOpenFds([](const std::string &error){\n\t\t\t\tLOGE(\"#[zygisk::preSpecialize] GetOpenFds: %s\", error.c_str());\n\t\t\t});\n\t\t\tif (fds) {\n\t\t\t\tfor (auto &fd : *fds) {\n\t\t\t\t\tif (fd == cfd) continue; // Skip companion FD itself\n\t\t\t\t\tauto fdi = FileDescriptorInfo::CreateFromFd(fd, [fd](const std::string &error){\n\t\t\t\t\t\tLOGE(\"#[zygisk::preSpecialize] CreateFromFd(%d): %s\", fd, error.c_str());\n\t\t\t\t\t});\n\t\t\t\t\tif (!fdi)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tauto [canSanitize, shouldDetach] = anomaly(std::move(fdi));\n\t\t\t\t\tif (canSanitize) {\n\t\t\t\t\t\tfdSanitizeList.emplace_back(std::move(fdi), shouldDetach);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint res = unshare(CLONE_NEWNS | CLONE_NEWCGROUP);\n\t\t\tif (res != 0) {\n\t\t\t\tLOGE(\"#[zygisk::preSpecialize] unshare: %s\", strerror(errno));\n\t\t\t\t// There's nothing we can do except returning\n\t\t\t\tclose(cfd);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tres = mount(\"rootfs\", \"/\", nullptr, MS_SLAVE | MS_REC, nullptr);\n\t\t\tif (res != 0) {\n\t\t\t\tLOGE(\"#[zygisk::preSpecialize] mount(rootfs, \\\"/\\\", nullptr, MS_SLAVE | MS_REC, nullptr): returned %d: %d (%s)\", res, errno, strerror(errno));\n\t\t\t\t// There's nothing we can do except returning\n\t\t\t\tclose(cfd);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tstatic std::vector<MountRuleParser::MountRule> mountRules;\n\n\t\t\tif (write(cfd, &pid, sizeof(pid)) != sizeof(pid)) {\n\t\t\t\tLOGE(\"#[zygisk::preSpecialize] write: [-> pid]: %s\", strerror(errno));\n\t\t\t\tres = FAILURE; // Fallback to unmount from zygote\n\t\t\t} else if (read(cfd, &res, sizeof(res)) != sizeof(res)) {\n\t\t\t\tLOGE(\"#[zygisk::preSpecialize] read: [<- status]: %s\", strerror(errno));\n\t\t\t\tres = FAILURE; // Fallback to unmount from zygote\n\t\t\t} else if (res == FAILURE) {\n\t\t\t\tLOGW(\"#[zygisk::preSpecialize]: Companion failed, fallback to unmount in zygote process\");\n\t\t\t\tmountRules = MountRuleParser::parseMultipleRules([this]() {\n\t\t\t\t\tauto sizeOfRulesPtr = xread<std::size_t>(cfd);\n\t\t\t\t\tif (!sizeOfRulesPtr) {\n\t\t\t\t\t\tLOGE(\"#[zygisk::preSpecialize] read: [sizeOfRules]: %s\", strerror(errno));\n\t\t\t\t\t\treturn defaultRules;\n\t\t\t\t\t}\n\t\t\t\t\tauto sizeOfRules = *sizeOfRulesPtr;\n\t\t\t\t\tstd::vector<std::string> rules(sizeOfRules, \"\");\n\t\t\t\t\tfor (int i = 0; i < sizeOfRules; ++i) {\n\t\t\t\t\t\tauto rule = xread<std::string>(cfd);\n\t\t\t\t\t\tif (!rule) {\n\t\t\t\t\t\t\tLOGE(\"#[zygisk::preSpecialize] read: [rule (at index %d)]: %s\", i, strerror(errno));\n\t\t\t\t\t\t\treturn defaultRules;\n\t\t\t\t\t\t}\n\t\t\t\t\t\trules[i] = std::move(*rule);\n\t\t\t\t\t}\n\t\t\t\t\treturn rules;\n\t\t\t\t}());\n\t\t\t}\n\n\t\t\tclose(cfd);\n\n\t\t\tif (res == FAILURE) {\n\t\t\t\tLOGW(\"#[zygisk::preSpecialize]: Companion failed, fallback to unmount in zygote process\");\n\t\t\t\tunmount(mountRules, getMountInfo()); // Unmount in current (zygote) namespace as fallback\n\t\t\t}\n\n\t\t\t// Sanitize FDs after companion communication and potential mount changes\n\t\t\tfor (auto &[fdi, shouldDetach] : fdSanitizeList) {\n\t\t\t\tLOGD(\"#[zygisk::preSpecialize]: Sanitizing FD %d (path: %s, socket: %d), detach: %d\",\n\t\t\t\t\t fdi->fd, fdi->file_path.c_str(), fdi->is_sock, shouldDetach);\n\t\t\t\tfdi->ReopenOrDetach([\n\t\t\t\t\t\t\t\t\t\t\tfd = fdi->fd,\n\t\t\t\t\t\t\t\t\t\t\tpath = fdi->file_path // Capture path by value for lambda\n\t\t\t\t\t\t\t\t\t](const std::string &error){\n\t\t\t\t\tLOGE(\"#[zygisk::preSpecialize]: Sanitize FD %d (%s): %s\", fd, path.c_str(), error.c_str());\n\t\t\t\t}, shouldDetach);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n        api->setOption(zygisk::Option::DLCLOSE_MODULE_LIBRARY);\n    }\n\n\tvoid postSpecialize(const char *process) {\n        // Unhook PLT hooks\n\t\tif (ar_unshare) {\n\t\t\tapi->pltHookRegister(rundev, runinode, \"unshare\", (void*) ar_unshare, nullptr);\n            ar_unshare = nullptr; // Clear pointer\n        }\n\t\tapi->pltHookCommit();\n\t\t//close(cfd);\n\t\tapi->setOption(zygisk::Option::DLCLOSE_MODULE_LIBRARY);\n\t}\n\n};\n\nstatic void NoRoot(int fd) {\n\tpid_t pid = -1, ppid = -1;\n\tstatic unsigned int successRate = 0;\n\tstatic const std::string description = [] {\n\t\tstd::ifstream f(\"/data/adb/modules/zygisk_nohello/description\");\n\t\t// This file exists only after installing/updating the module\n\t\t// It should have the default description\n\t\t// Since this is static const it's only evaluated once per boot since companion won't exit\n\t\treturn f ? ([](std::ifstream& s){ std::string l; std::getline(s, l); return l; })(f) : \"A Zygisk module to hide root.\";\n\t}();\n\tstatic PropertyManager pm(\"/data/adb/modules/zygisk_nohello/module.prop\");\n\n\tstatic const int compatbility = [] {\n\t\tif (fs::exists(\"/data/adb/modules/zygisk_shamiko\") && !fs::exists(\"/data/adb/modules/zygisk_shamiko/disable\"))\n\t\t\treturn MODULE_CONFLICT;\n\t\tif (fs::exists(\"/data/adb/modules/zygisk-assistant\") && !fs::exists(\"/data/adb/modules/zygisk-assistant/disable\"))\n\t\t\treturn MODULE_CONFLICT;\n\t\tif (fs::exists(\"/data/adb/modules/treat_wheel\") && !fs::exists(\"/data/adb/modules/treat_wheel/disable\"))\n\t\t\treturn MODULE_CONFLICT;\n\t\tif (fs::exists(\"/data/adb/modules/susfs4ksu\") && !fs::exists(\"/data/adb/modules/susfs4ksu/disable\"))\n\t\t\treturn MODULE_CONFLICT;\n\t\treturn NORMAL;\n\t}();\n\n\tstatic const bool doesUmountPersists = []() {\n\t\treturn fs::exists(\"/data/adb/nohello/umount_persist\") || fs::exists(\"/data/adb/nohello/umount_persists\");\n\t}();\n\n\tstatic std::vector<std::string> stringRules;\n\tstatic std::vector<MountRuleParser::MountRule> mountRules;\n\tstatic bool evaluateOnlyOnce = false;\n\n\tif (!evaluateOnlyOnce) {\n\t\tstringRules = []() {\n\t\t\tstd::vector<std::string> rules;\n\t\t\tstd::ifstream f(\"/data/adb/nohello/umount\");\n\t\t\tif (f && f.is_open()) {\n\t\t\t\tstd::string line;\n\t\t\t\twhile (std::getline(f, line)) {\n\t\t\t\t\tif (!line.empty() && line[0] != '#')\n\t\t\t\t\t\trules.push_back(line);\n\t\t\t\t}\n\t\t\t\tf.close();\n\t\t\t} else {\n\t\t\t\trules = defaultRules;\n\t\t\t\tstd::ofstream redef(\"/data/adb/nohello/umount\");\n\t\t\t\tif (redef && redef.is_open()) {\n\t\t\t\t\tfor (const auto &rule: rules)\n\t\t\t\t\t\tredef << rule << std::endl;\n\t\t\t\t\tf.close();\n\t\t\t\t} else\n\t\t\t\t\tLOGE(\"Unable to create `/data/adb/nohello/umount`\");\n\t\t\t}\n\t\t\treturn rules;\n\t\t}();\n\t\tmountRules = MountRuleParser::parseMultipleRules(stringRules);\n\t\tif (doesUmountPersists)\n\t\t\tevaluateOnlyOnce = true;\n\t}\n\n\tif (read(fd, &ppid, sizeof(ppid)) != sizeof(ppid)) {\n\t\tLOGE(\"#[ps::Companion] Failed to read PPID: %s\", strerror(errno));\n\t\tclose(fd);\n\t\treturn;\n\t}\n\n\tstatic const pid_t clrMsgZygote = [ppid]() -> pid_t {\n\t\tif (fs::exists(\"/data/adb/nohello/no_clr_ptracemsg\"))\n\t\t\t// Apply the fix only by user's choice\n\t\t\treturn ppid;\n\t\tif (getKernelVersion() >= KERNEL_VERSION(6, 1, 0))\n\t\t\t// The issue was fixed in 6.1+\n\t\t\t// https://marc.info/?l=linux-arch&m=164124554311501&w=2\n\t\t\treturn ppid;\n\t\t// Re-work this to avoid issues with bootloops\n\t\t// https://github.com/PerformanC/ReZygisk/issues/171\n\t\tif (ptrace(PTRACE_ATTACH, ppid, nullptr, nullptr) == -1) {\n\t\t\tLOGE(\"#[ps::Companion] ptrace(PTRACE_ATTACH, %d, nullptr, nullptr): %s\", ppid,\n\t\t\t\t strerror(errno));\n\t\t\treturn -1;\n\t\t}\n\t\twaitpid(ppid, nullptr, 0);\n\t\tif (ptrace(PTRACE_SYSCALL, ppid, nullptr, nullptr) == -1) {\n\t\t\tLOGE(\"#[ps::Companion] ptrace(PTRACE_SYSCALL, %d, nullptr, nullptr): %s\", ppid, strerror(errno));\n\t\t\tptrace(PTRACE_DETACH, ppid, nullptr, nullptr);\n\t\t\treturn -1;\n\t\t}\n\t\twaitpid(ppid, nullptr, 0);\n\t\tptrace(PTRACE_DETACH, ppid, nullptr, nullptr);\n\t\tLOGD(\"#[ps::Companion] Cleared ptrace_message for zygote(%d)\", ppid);\n\t\treturn ppid;\n\t}();\n\n\tint result = compatbility;\n\tif (result == MODULE_CONFLICT) {\n\t\tpm.setProp(\"description\", \"[\" + emoji::emojize(\":warning: \") + \"Conflicting modules] \" + description);\n\t\tif (write(fd, &result, sizeof(result)) != sizeof(result)) {\n\t\t\tLOGE(\"#[ps::Companion] Failed to write result: %s\", strerror(errno));\n\t\t}\n\t\tclose(fd);\n\t\treturn;\n\t} else {\n\t\tif (write(fd, &result, sizeof(result)) != sizeof(result)) {\n\t\t\tLOGE(\"#[ps::Companion] Failed to write result: %s\", strerror(errno));\n\t\t\tclose(fd);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tif (read(fd, &pid, sizeof(pid)) != sizeof(pid)) {\n        LOGE(\"#[ps::Companion] Failed to read PID: %s\", strerror(errno));\n\t\tclose(fd);\n\t\treturn;\n\t}\n\n\tresult = forkcall(\n\t\t[pid]()\n\t\t{\n\t\t\tint res = nscg2(pid);\n\t\t\tif (!res) { // switchnsto returns true on success (0 from setns)\n\t\t\t\tLOGE(\"#[ps::Companion] Switch namespaces failed for PID %d: %s\", pid, strerror(errno));\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\t\t\tauto mounts = getMountInfo();\n\t\t\tunmount(mountRules, mounts);\n\t\t\tremount(mounts);\n\t\t\treturn SUCCESS;\n\t\t}\n\t);\n\n\tif (result == SUCCESS) {\n\t\tsuccessRate++;\n\t\tpm.setProp(\"description\", \"[\" + emoji::emojize(\":yum: \") + \"Nohello unmounted \" +\n\t\t\t\t\t\t\t\t  std::to_string(successRate) + \" time(s)] \" + description);\n\t} else if (result == FAILURE) {\n\t\tif (write(fd, &result, sizeof(result)) != sizeof(result)) {\n\t\t\tLOGE(\"#[ps::Companion] Failed to write result: %s\", strerror(errno));\n\t\t\tclose(fd);\n\t\t\treturn;\n\t\t}\n\t\tif (xwrite(fd, stringRules.size())) {\n\t\t\tfor (int i = 0; i < stringRules.size(); ++i) {\n\t\t\t\tif (!xwrite(fd, stringRules[i])) {\n\t\t\t\t\tLOGE(\"#[ps::Companion] write: [rule (at index %d)]: %s\", i, strerror(errno));\n\t\t\t\t\tclose(fd);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tLOGE(\"#[ps::Companion] write: [stringRules.size()]: %s\", strerror(errno));\n\t\t\tclose(fd);\n\t\t\treturn;\n\t\t}\n\t\tclose(fd);\n\t\treturn;\n\t}\n\tif (write(fd, &result, sizeof(result)) != sizeof(result)) {\n\t\tLOGE(\"#[ps::Companion] Failed to write result: %s\", strerror(errno));\n\t\tclose(fd);\n\t\treturn;\n\t}\n\tclose(fd);\n}\n\n// Register our module class and the companion handler function\nREGISTER_ZYGISK_MODULE(NoHello)\nREGISTER_ZYGISK_COMPANION(NoRoot)\n"], ["/NoHello/module/src/main/cpp/mountsinfo.cpp", "#pragma once\n\n#include <string>\n#include <unordered_map>\n#include <sstream>\n#include <fstream>\n#include <vector>\n#include <cstdint>\n#include <type_traits>\n#include <algorithm>\n#include <sys/types.h>\n#include <sys/sysmacros.h>\n\nenum class MountFlags : uint64_t {\n\tRO         = 1ull << 0,\n\tRW         = 1ull << 1,\n\tNOEXEC     = 1ull << 2,\n\tEXEC       = 1ull << 3,\n\tNOSUID     = 1ull << 4,\n\tSUID       = 1ull << 5,\n\tNODEV      = 1ull << 6,\n\tDEV        = 1ull << 7,\n\tRELATIME   = 1ull << 8,\n\tNORELATIME = 1ull << 9,\n\tSTRICTATIME= 1ull << 10,\n\tNOATIME    = 1ull << 11,\n\tATIME      = 1ull << 12,\n\tDIRSYNC    = 1ull << 13,\n\tSYNC       = 1ull << 14,\n\tMANDLOCK   = 1ull << 15,\n\tNODIRATIME = 1ull << 16,\n\tLAZYTIME   = 1ull << 17,\n\tSECLABEL   = 1ull << 18,\n\tINDEX      = 1ull << 19,\n\tNOINDEX    = 1ull << 20,\n\tMETACOPY   = 1ull << 21,\n\tNOMETACOPY = 1ull << 22,\n\tBIND       = 1ull << 23,\n\tRPRIVATE   = 1ull << 24,\n\tRSHARED    = 1ull << 25,\n\tRSLAVE     = 1ull << 26,\n\tPRIVATE    = 1ull << 27,\n\tSHARED     = 1ull << 28,\n\tSLAVE      = 1ull << 29,\n\tREC        = 1ull << 30,\n\tREMOUNT    = 1ull << 31,\n\tNOSYMFOLLOW= 1ull << 32\n};\n\n\ninline MountFlags operator|(MountFlags a, MountFlags b) {\n\treturn static_cast<MountFlags>(\n\t\t\tstatic_cast<std::underlying_type_t<MountFlags>>(a) |\n\t\t\tstatic_cast<std::underlying_type_t<MountFlags>>(b)\n\t);\n}\n\ninline MountFlags& operator|=(MountFlags& a, MountFlags b) {\n\ta = a | b;\n\treturn a;\n}\n\ninline bool operator&(MountFlags a, MountFlags b) {\n\treturn\n\t\t\tstatic_cast<std::underlying_type_t<MountFlags>>(a) &\n\t\t\tstatic_cast<std::underlying_type_t<MountFlags>>(b);\n}\n\nenum class PropagationType {\n\tPRIVATE,\n\tSHARED,\n\tSLAVE,\n\tUNBINDABLE,\n\tUNKNOWN\n};\n\nstruct MountPropagation {\n\tPropagationType type = PropagationType::UNKNOWN;\n\tint id = -1;\n};\n\nstatic const std::unordered_map<std::string, MountFlags> mountFlags = {\n\t\t{\"ro\", MountFlags::RO}, {\"rw\", MountFlags::RW}, {\"noexec\", MountFlags::NOEXEC},\n\t\t{\"exec\", MountFlags::EXEC}, {\"nosuid\", MountFlags::NOSUID}, {\"suid\", MountFlags::SUID},\n\t\t{\"nodev\", MountFlags::NODEV}, {\"dev\", MountFlags::DEV}, {\"relatime\", MountFlags::RELATIME},\n\t\t{\"norelatime\", MountFlags::NORELATIME}, {\"strictatime\", MountFlags::STRICTATIME},\n\t\t{\"noatime\", MountFlags::NOATIME}, {\"atime\", MountFlags::ATIME}, {\"dirsync\", MountFlags::DIRSYNC},\n\t\t{\"sync\", MountFlags::SYNC}, {\"mand\", MountFlags::MANDLOCK}, {\"nodiratime\", MountFlags::NODIRATIME},\n\t\t{\"lazytime\", MountFlags::LAZYTIME}, {\"seclabel\", MountFlags::SECLABEL}, {\"index\", MountFlags::INDEX},\n\t\t{\"noindex\", MountFlags::NOINDEX}, {\"metacopy\", MountFlags::METACOPY},\n\t\t{\"nometacopy\", MountFlags::NOMETACOPY}, {\"bind\", MountFlags::BIND},\n\t\t{\"rprivate\", MountFlags::RPRIVATE}, {\"rshared\", MountFlags::RSHARED},\n\t\t{\"rslave\", MountFlags::RSLAVE}, {\"private\", MountFlags::PRIVATE},\n\t\t{\"shared\", MountFlags::SHARED}, {\"slave\", MountFlags::SLAVE},\n\t\t{\"rec\", MountFlags::REC}, {\"remount\", MountFlags::REMOUNT},\n\t\t{\"nosymfollow\", MountFlags::NOSYMFOLLOW}\n};\n\nstruct MountOptions {\n\tMountFlags flags = MountFlags(0);\n\tstd::unordered_map<std::string, std::string> flagmap;\n\n\tvoid parse(const std::string& str) {\n\t\tstd::istringstream s(str);\n\t\tstd::string opt;\n\t\twhile (std::getline(s, opt, ',')) {\n\t\t\tauto it = mountFlags.find(opt);\n\t\t\tif (it != mountFlags.end()) {\n\t\t\t\tflags |= it->second;\n\t\t\t} else {\n\t\t\t\tsize_t eq = opt.find('=');\n\t\t\t\tif (eq != std::string::npos) {\n\t\t\t\t\tflagmap[opt.substr(0, eq)] = opt.substr(eq + 1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n};\n\nclass MountInfo {\npublic:\n\texplicit MountInfo(const std::string& line) {\n\t\tstd::istringstream ss(line);\n\t\tstd::vector<std::string> parts;\n\t\tstd::string token;\n\t\twhile (ss >> token)\n\t\t\tparts.push_back(token);\n\t\tauto it = std::find(parts.begin(), parts.end(), std::string(\"-\"));\n\t\tif (it == parts.end() || std::distance(parts.begin(), it) < 6)\n\t\t\treturn;\n\t\tsize_t sep_idx = std::distance(parts.begin(), it);\n\t\tmnt_id = std::stoi(parts[0]);\n\t\tmnt_parent_id = std::stoi(parts[1]);\n\t\tparseMajorMinor(parts[2]);\n\t\troot = parts[3];\n\t\tmnt_pnt = parts[4];\n\t\tparseFlags(parts[5]);\n\t\tfor (size_t i = 6; i < sep_idx; ++i)\n\t\t\tparsePropagation(parts[i]);\n\t\tfs_type = parts[sep_idx + 1];\n\t\tmnt_src = parts[sep_idx + 2];\n\t\tparseOptions(parts[sep_idx + 3]);\n\t}\n\n\t~MountInfo() = default;\n\n\t[[nodiscard]] int getMountId() const { return mnt_id; }\n\t[[nodiscard]] int getParentId() const { return mnt_parent_id; }\n\t[[nodiscard]] dev_t getDev() const { return dev; }\n\t[[nodiscard]] const std::string& getRoot() const { return root; }\n\t[[nodiscard]] const std::string& getMountPoint() const { return mnt_pnt; }\n\t[[nodiscard]] MountFlags getFlags() const { return mnt_flags; }\n\t[[nodiscard]] const MountPropagation& getPropagation() const { return propagation; }\n\t[[nodiscard]] const std::string& getFsType() const { return fs_type; }\n\t[[nodiscard]] const std::string& getMountSource() const { return mnt_src; }\n\t[[nodiscard]] const MountOptions& getMountOptions() const { return mnt_opts; }\n\nprivate:\n\tint mnt_id;\n\tint mnt_parent_id;\n\tdev_t dev = 0;\n\tstd::string root;\n\tstd::string mnt_pnt;\n\tMountFlags mnt_flags = MountFlags(0);\n\tMountPropagation propagation;\n\tstd::string fs_type;\n\tstd::string mnt_src;\n\tMountOptions mnt_opts;\n\n\tvoid parseFlags(const std::string& str) {\n\t\tstd::istringstream s(str);\n\t\tstd::string opt;\n\t\twhile (std::getline(s, opt, ',')) {\n\t\t\tauto it = mountFlags.find(opt);\n\t\t\tif (it != mountFlags.end())\n\t\t\t\tmnt_flags |= it->second;\n\t\t}\n\t}\n\n\tvoid parsePropagation(const std::string& pg) {\n\t\tif (pg.find(\"master:\") == 0) {\n\t\t\tpropagation.type = PropagationType::SLAVE;\n\t\t\tpropagation.id = std::stoi(pg.substr(7));\n\t\t} else if (pg.find(\"shared:\") == 0) {\n\t\t\tpropagation.type = PropagationType::SHARED;\n\t\t\tpropagation.id = std::stoi(pg.substr(7));\n\t\t} else if (pg == \"unbindable\") {\n\t\t\tpropagation.type = PropagationType::UNBINDABLE;\n\t\t} else if (pg == \"private\") {\n\t\t\tpropagation.type = PropagationType::PRIVATE;\n\t\t}\n\t}\n\n\tvoid parseOptions(const std::string& opt) {\n\t\tmnt_opts.parse(opt);\n\t}\n\n\tvoid parseMajorMinor(const std::string& mmstr) {\n\t\tsize_t sep = mmstr.find(':');\n\t\tif (sep != std::string::npos) {\n\t\t\tint major = std::stoi(mmstr.substr(0, sep));\n\t\t\tint minor = std::stoi(mmstr.substr(sep + 1));\n\t\t\tdev = makedev(major, minor);\n\t\t} else {\n\t\t\tdev = 0;\n\t\t}\n\t}\n};\n\nclass MountRootResolver {\nprivate:\n\tstd::unordered_map<dev_t, std::string> dmm;\n\npublic:\n\texplicit MountRootResolver(const std::vector<MountInfo>& mounts) {\n\t\tfor (const auto& mount : mounts) {\n\t\t\tif (mount.getRoot() == \"/\") {\n\t\t\t\tdmm[mount.getDev()] = mount.getMountPoint();\n\t\t\t}\n\t\t}\n\t}\n\n\t~MountRootResolver() = default;\n\n\tstd::string resolveRoot(const MountInfo& mount) {\n\t\tauto dev = mount.getDev();\n\t\tauto it = dmm.find(dev);\n\t\tif (it != dmm.end()) {\n\t\t\tif (it->second != \"/\")\n\t\t\t\treturn it->second + mount.getRoot();\n\t\t}\n\t\treturn mount.getRoot();\n\t}\n};\n\nstd::vector<MountInfo> getMountInfo(const std::string& path = \"/proc/self/mountinfo\") {\n\tstd::ifstream mi(path);\n\tstd::vector<MountInfo> mounts;\n\tstd::string line;\n\tif (!mi.is_open())\n\t\treturn mounts;\n\twhile (std::getline(mi, line)) {\n\t\tMountInfo mountInfo(line);\n\t\tmounts.emplace_back(std::move(mountInfo));\n\t}\n\tmi.close();\n\treturn mounts;\n}"], ["/NoHello/module/src/main/cpp/utils.cpp", "#include <fstream>\n#include <sstream>\n#include <string>\n#include <utility>\n#include <iostream>\n#include <iomanip>\n#include <sys/sysmacros.h>\n#include <sys/types.h>\n#include <sys/wait.h>\n#include <sys/syscall.h>\n#include <sys/socket.h>\n#include <vector>\n#include <tuple>\n#include <cstdint>\n#include <sys/mman.h>\n#include <link.h>\n#include <sys/stat.h>\n#include <sys/utsname.h>\n#include <linux/version.h>\n#include <dirent.h>\n#include \"log.h\"\n\nstd::pair<dev_t, ino_t> devinobymap(const std::string& lib, bool useFind = false, unsigned int *ln = nullptr) {\n\tstd::ifstream maps(\"/proc/self/maps\");\n\tunsigned int index = 0;\n\tstd::string line;\n\tstd::string needle = \"/\" + lib;\n\twhile (std::getline(maps, line)) {\n\t\tif (ln && index < *ln) {\n\t\t\tindex++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (line.size() >= needle.size() && ((useFind && line.find(needle) != std::string::npos) ||\n\t\t\tline.compare(line.size() - needle.size(), needle.size(), needle) == 0)) {\n\t\t\tstd::istringstream iss(line);\n\t\t\tstd::string addr, perms, offset, dev, inode_str;\n\t\t\tiss >> addr >> perms >> offset >> dev >> inode_str;\n\t\t\tstd::istringstream devsplit(dev);\n\t\t\tstd::string major_hex, minor_hex;\n\t\t\tif (std::getline(devsplit, major_hex, ':') &&\n\t\t\t\tstd::getline(devsplit, minor_hex)) {\n\t\t\t\tint major = std::stoi(major_hex, nullptr, 16);\n\t\t\t\tint minor = std::stoi(minor_hex, nullptr, 16);\n\t\t\t\tdev_t devnum = makedev(major, minor);\n\t\t\t\tino_t inode = std::stoul(inode_str);\n\t\t\t\tif (ln)\n\t\t\t\t\t*ln = index;\n\t\t\t\treturn {devnum, inode};\n\t\t\t}\n\t\t}\n\t\tindex++;\n\t}\n\tif (ln)\n\t\t*ln = -1;\n\treturn {dev_t(0), ino_t(0)};\n}\n\nstd::optional<std::pair<dev_t, ino_t>> devinoby(const char* lib) {\n\tstruct State {\n\t\tconst char* needle;\n\t\tstd::optional<std::pair<dev_t, ino_t>> result;\n\t} state = { lib };\n\n\tdl_iterate_phdr([](struct dl_phdr_info* info, size_t, void* data) -> int {\n\t\tauto* s = static_cast<State*>(data);\n\t\tif (info->dlpi_name && strstr(info->dlpi_name, s->needle)) {\n\t\t\tstruct stat st{};\n\t\t\tif (stat(info->dlpi_name, &st) == 0) {\n\t\t\t\ts->result = std::make_pair(st.st_dev, st.st_ino);\n\t\t\t\treturn 1; // Stop iteration\n\t\t\t}\n\t\t}\n\t\treturn 0; // Continue\n\t}, &state);\n\n\treturn state.result;\n}\n\nstd::optional<std::pair<void*, size_t>> robaseby(dev_t dev, ino_t ino) {\n\tstruct State {\n\t\tdev_t dev;\n\t\tino_t ino;\n\t\tstd::optional<std::pair<void*, size_t>> result;\n\t} state = { dev, ino };\n\n\tdl_iterate_phdr([](struct dl_phdr_info* info, size_t, void* data) -> int {\n\t\tauto* s = static_cast<State*>(data);\n\n\t\tstruct stat st{};\n\t\tif (stat(info->dlpi_name, &st) != 0)\n\t\t\treturn 0;\n\n\t\tif (st.st_dev != s->dev || st.st_ino != s->ino)\n\t\t\treturn 0;\n\n\t\tfor (int i = 0; i < info->dlpi_phnum; ++i) {\n\t\t\tconst auto& phdr = info->dlpi_phdr[i];\n\t\t\tif (phdr.p_type == PT_LOAD &&\n\t\t\t\t(phdr.p_flags & PF_R) &&\n\t\t\t\t!(phdr.p_flags & PF_X)) // r--p only\n\t\t\t{\n\t\t\t\tuintptr_t base = info->dlpi_addr + phdr.p_vaddr;\n\t\t\t\tsize_t size = phdr.p_memsz;\n\t\t\t\ts->result = std::make_pair(reinterpret_cast<void*>(base), size);\n\t\t\t\treturn 1; // Stop searching\n\t\t\t}\n\t\t}\n\n\t\treturn 0;\n\t}, &state);\n\n\treturn state.result;\n}\n\nint forkcall(const std::function<int()> &lambda)\n{\n\tpid_t pid = fork();\n\tif (pid == -1)\n\t\treturn -1;\n\tif (pid == 0) {\n\t\texit(lambda());\n\t} else {\n\t\tint status = -1;\n\t\twaitpid(pid, &status, 0);\n\t\tif (WIFEXITED(status)) {\n\t\t\treturn WEXITSTATUS(status);\n\t\t}\n\t}\n\treturn -1;\n}\n\nstatic inline int seccomp(int op, int fd, void *arg) {\n\treturn syscall(SYS_seccomp, op, fd, arg);\n}\n\nstatic int pidfd_open(pid_t pid, unsigned int flags)\n{\n\treturn syscall(SYS_pidfd_open, pid, flags);\n}\n\nstatic ssize_t process_vm_readv(pid_t pid,\n\t\t\t\t\t\t\t\t const struct iovec *local_iov,\n\t\t\t\t\t\t\t\t unsigned long liovcnt,\n\t\t\t\t\t\t\t\t const struct iovec *remote_iov,\n\t\t\t\t\t\t\t\t unsigned long riovcnt,\n\t\t\t\t\t\t\t\t unsigned long flags)\n{\n\treturn syscall(SYS_process_vm_readv, pid, local_iov, liovcnt, remote_iov, riovcnt, flags);\n}\n\nstatic ssize_t process_vm_writev(pid_t pid,\n\t\t\t\t\t\t\t\t const struct iovec *local_iov,\n\t\t\t\t\t\t\t\t unsigned long liovcnt,\n\t\t\t\t\t\t\t\t const struct iovec *remote_iov,\n\t\t\t\t\t\t\t\t unsigned long riovcnt,\n\t\t\t\t\t\t\t\t unsigned long flags)\n{\n\treturn syscall(SYS_process_vm_writev, pid, local_iov, liovcnt, remote_iov, riovcnt, flags);\n}\n\nbool nscg2(pid_t pid) {\n    int pidfd = pidfd_open(pid, 0);\n    if (pidfd != -1) {\n    \t// https://man7.org/linux/man-pages/man2/setns.2.html\n        int res = setns(pidfd, CLONE_NEWNS | CLONE_NEWCGROUP);\n        close(pidfd);\n        if (res) {\n            LOGE(\"setns(pidfd_open(%d, 0) -> %d (closed), 0): %s\", pid, pidfd, strerror(errno));\n            goto fallback;\n        }\n        return true;\n    } else {\n        LOGE(\"pidfd_open(%d): %s\", pid, strerror(errno));\n    }\nfallback:\n    {\n        std::string mntPath = \"/proc/\" + std::to_string(pid) + \"/ns/mnt\";\n        int mntfd_fallback = open(mntPath.c_str(), O_RDONLY);\n        if (mntfd_fallback != -1) {\n            int res = setns(mntfd_fallback, CLONE_NEWNS);\n            if (res) {\n                LOGE(\"setns(open(\\\"%s\\\") -> %d, CLONE_NEWNS): %s\", mntPath.c_str(), mntfd_fallback, strerror(errno));\n                close(mntfd_fallback);\n                return false;\n            }\n            close(mntfd_fallback);\n        } else {\n            LOGE(\"open(\\\"%s\\\"): %s\", mntPath.c_str(), strerror(errno));\n            return false;\n        }\n    }\n    {\n        std::string cgPath = \"/proc/\" + std::to_string(pid) + \"/ns/cgroup\";\n        int cgfd_fallback = open(cgPath.c_str(), O_RDONLY);\n        if (cgfd_fallback != -1) {\n            int res = setns(cgfd_fallback, CLONE_NEWCGROUP);\n            if (res) {\n                LOGE(\"setns(open(\\\"%s\\\") -> %d, CLONE_NEWCGROUP): %s\", cgPath.c_str(), cgfd_fallback, strerror(errno));\n                close(cgfd_fallback);\n                return false;\n            }\n            close(cgfd_fallback);\n        } else {\n            LOGE(\"open(\\\"%s\\\"): %s\", cgPath.c_str(), strerror(errno));\n            return false;\n        }\n    }\n    return true;\n}\n\n\nbool isuserapp(int uid) {\n\tint appid = uid % AID_USER_OFFSET;\n\tif (appid >= AID_APP_START && appid <= AID_APP_END)\n\t\treturn true;\n\tif (appid >= AID_ISOLATED_START && appid <= AID_ISOLATED_END)\n\t\treturn true;\n\treturn false;\n}\n\nstatic int sendfd(int sockfd, int fd) {\n\tint data;\n\tstruct iovec iov{};\n\tstruct msghdr msgh{};\n\tstruct cmsghdr *cmsgp;\n\n\t/* Allocate a char array of suitable size to hold the ancillary data.\n\t   However, since this buffer is in reality a 'struct cmsghdr', use a\n\t   union to ensure that it is suitably aligned. */\n\tunion {\n\t\tchar buf[CMSG_SPACE(sizeof(int))];\n\t\t/* Space large enough to hold an 'int' */\n\t\tstruct cmsghdr align;\n\t} controlMsg{};\n\n\t/* The 'msg_name' field can be used to specify the address of the\n\t   destination socket when sending a datagram. However, we do not\n\t   need to use this field because 'sockfd' is a connected socket. */\n\n\tmsgh.msg_name = nullptr;\n\tmsgh.msg_namelen = 0;\n\n\t/* On Linux, we must transmit at least one byte of real data in\n\t   order to send ancillary data. We transmit an arbitrary integer\n\t   whose value is ignored by recvfd(). */\n\n\tmsgh.msg_iov = &iov;\n\tmsgh.msg_iovlen = 1;\n\tiov.iov_base = &data;\n\tiov.iov_len = sizeof(int);\n\tdata = 12345;\n\n\t/* Set 'msghdr' fields that describe ancillary data */\n\n\tmsgh.msg_control = controlMsg.buf;\n\tmsgh.msg_controllen = sizeof(controlMsg.buf);\n\n\t/* Set up ancillary data describing file descriptor to send */\n\n\tcmsgp = reinterpret_cast<cmsghdr *>(msgh.msg_control);\n\tcmsgp->cmsg_level = SOL_SOCKET;\n\tcmsgp->cmsg_type = SCM_RIGHTS;\n\tcmsgp->cmsg_len = CMSG_LEN(sizeof(int));\n\tmemcpy(CMSG_DATA(cmsgp), &fd, sizeof(int));\n\n\t/* Send real plus ancillary data */\n\n\tif (sendmsg(sockfd, &msgh, 0) == -1) return -1;\n\n\treturn 0;\n}\n\nstatic int recvfd(int sockfd) {\n\tint data, fd;\n\tssize_t nr;\n\tstruct iovec iov{};\n\tstruct msghdr msgh{};\n\n\t/* Allocate a char buffer for the ancillary data. See the comments\n\t   in sendfd() */\n\tunion {\n\t\tchar buf[CMSG_SPACE(sizeof(int))];\n\t\tstruct cmsghdr align;\n\t} controlMsg{};\n\tstruct cmsghdr *cmsgp;\n\n\t/* The 'msg_name' field can be used to obtain the address of the\n\t   sending socket. However, we do not need this information. */\n\n\tmsgh.msg_name = nullptr;\n\tmsgh.msg_namelen = 0;\n\n\t/* Specify buffer for receiving real data */\n\n\tmsgh.msg_iov = &iov;\n\tmsgh.msg_iovlen = 1;\n\tiov.iov_base = &data; /* Real data is an 'int' */\n\tiov.iov_len = sizeof(int);\n\n\t/* Set 'msghdr' fields that describe ancillary data */\n\n\tmsgh.msg_control = controlMsg.buf;\n\tmsgh.msg_controllen = sizeof(controlMsg.buf);\n\n\t/* Receive real plus ancillary data; real data is ignored */\n\n\tnr = recvmsg(sockfd, &msgh, 0);\n\tif (nr == -1) return -1;\n\n\tcmsgp = CMSG_FIRSTHDR(&msgh);\n\n\t/* Check the validity of the 'cmsghdr' */\n\n\tif (cmsgp == nullptr || cmsgp->cmsg_len != CMSG_LEN(sizeof(int)) ||\n\t\tcmsgp->cmsg_level != SOL_SOCKET || cmsgp->cmsg_type != SCM_RIGHTS) {\n\t\terrno = EINVAL;\n\t\treturn -1;\n\t}\n\n\t/* Return the received file descriptor to our caller */\n\n\tmemcpy(&fd, CMSG_DATA(cmsgp), sizeof(int));\n\treturn fd;\n}\n\nstatic int getKernelVersion() {\n\tstruct utsname un{};\n\tif (uname(&un) != 0) {\n\t\treturn 0;\n\t}\n\tint kmaj = 0, kmin = 0, kpatch = 0;\n\tsscanf(un.release, \"%d.%d.%d\", &kmaj, &kmin, &kpatch);\n\treturn KERNEL_VERSION(kmaj, kmin, kpatch);\n}\n\ntemplate <typename T>\nbool xwrite(int fd, const T& data) {\n\tuint64_t size = sizeof(T);\n\tif (write(fd, &size, sizeof(size)) != sizeof(size)) {\n\t\treturn false;\n\t}\n\tif (write(fd, data.data(), size) != static_cast<ssize_t>(size)) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\ntemplate<>\nbool xwrite<std::string>(int fd, const std::string& data) {\n\tuint64_t size = data.size();\n\tif (write(fd, &size, sizeof(size)) != sizeof(size)) {\n\t\treturn false;\n\t}\n\tif (write(fd, data.data(), size) != static_cast<ssize_t>(size)) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nbool xwrite(int fd, const char* data) {\n\tif (!data) return false;\n\treturn xwrite(fd, std::string(data));\n}\n\ntemplate <>\nbool xwrite<bool>(int fd, const bool& data) {\n\tuint64_t size = sizeof(bool);\n\tif (write(fd, &size, sizeof(size)) != sizeof(size)) {\n\t\treturn false;\n\t}\n\tuint8_t byteData = data ? 1 : 0;\n\tif (write(fd, &byteData, sizeof(byteData)) != sizeof(byteData)) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\ntemplate <>\nbool xwrite<uintptr_t>(int fd, const uintptr_t& data) {\n\tuint64_t size = sizeof(uintptr_t);\n\tif (write(fd, &size, sizeof(size)) != sizeof(size)) {\n\t\treturn false;\n\t}\n\tif (write(fd, &data, size) != size) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\ntemplate <typename T>\nstd::unique_ptr<T> xread(int fd) {\n\tuint64_t size = 0;\n\tif (read(fd, &size, sizeof(size)) != sizeof(size)) {\n\t\treturn nullptr;\n\t}\n\tif (size != sizeof(T)) {\n\t\treturn nullptr;\n\t}\n\tauto data = std::make_unique<T>();\n\tif (read(fd, data.get(), size) != static_cast<ssize_t>(size)) {\n\t\treturn nullptr;\n\t}\n\treturn data;\n}\n\ntemplate<>\nstd::unique_ptr<std::string> xread<std::string>(int fd) {\n\tuint64_t size = 0;\n\tif (read(fd, &size, sizeof(size)) != sizeof(size)) {\n\t\treturn nullptr;\n\t}\n\tauto data = std::make_unique<std::string>(size, '\\0');\n\tif (read(fd, data->data(), size) != static_cast<ssize_t>(size)) {\n\t\treturn nullptr;\n\t}\n\treturn data;\n}\n\ntemplate <>\nstd::unique_ptr<bool> xread<bool>(int fd) {\n\tuint64_t size = 0;\n\tif (read(fd, &size, sizeof(size)) != sizeof(size)) {\n\t\treturn nullptr;\n\t}\n\tif (size != sizeof(bool)) {\n\t\treturn nullptr;\n\t}\n\tuint8_t byteData = 0;\n\tif (read(fd, &byteData, sizeof(byteData)) != sizeof(byteData)) {\n\t\treturn nullptr;\n\t}\n\treturn std::make_unique<bool>(byteData != 0);\n}\n\ntemplate <>\nstd::unique_ptr<uintptr_t> xread<uintptr_t>(int fd) {\n\tuint64_t size = 0;\n\tif (read(fd, &size, sizeof(size)) != sizeof(size)) {\n\t\treturn nullptr;\n\t}\n\tif (size != sizeof(uintptr_t)) {\n\t\treturn nullptr;\n\t}\n\tuintptr_t data = 0;\n\tif (read(fd, &data, size) != size) {\n\t\treturn nullptr;\n\t}\n\treturn std::make_unique<uintptr_t>(data);\n}\n"], ["/NoHello/module/src/main/cpp/PropertyManager.h", "class PropertyManager {\n  public:\n    explicit PropertyManager(std::string  path) {\n\tloadFromFile();\n}\n    std::string getProp(const std::string& key, const std::string& defaultValue = \"\") {\n\tauto it = keyIndex.find(key);\n\treturn it != keyIndex.end() ? orderedProps[it->second].second : defaultValue;\n}\n    void setProp(const std::string& key, const std::string& value) {\n\tauto it = keyIndex.find(key);\n\tif (it != keyIndex.end()) {\n\t\t// Update existing\n\t\torderedProps[it->second].second = value;\n\t} else {\n\t\t// Append new\n\t\tsize_t idx = orderedProps.size();\n\t\torderedProps.emplace_back(key, value);\n\t\tkeyIndex[key] = idx;\n\t}\n\n\tsaveToFile();\n}\n  private:\n    std::string filePath;\n    std::vector<std::pair<std::string, std::string>> orderedProps;\n    std::unordered_map<std::string, size_t> keyIndex;\n    bool loadFromFile() {\n\torderedProps.clear();\n\tkeyIndex.clear();\n\n\tstd::ifstream file(filePath);\n\tif (!file.is_open()) {\n\t\tLOGW(\"PropertyManager: Could not open %s for loading.\", filePath.c_str());\n\t\treturn false;\n\t}\n\n\tstd::string line;\n\twhile (std::getline(file, line)) {\n\t\tif (line.empty() || line[0] == '#')\n\t\t\tcontinue;\n\n\t\tauto pos = line.find('=');\n\t\tif (pos == std::string::npos)\n\t\t\tcontinue;\n\n\t\tstd::string key = line.substr(0, pos);\n\t\tstd::string val = line.substr(pos + 1);\n\n\t\tsize_t idx = orderedProps.size();\n\t\torderedProps.emplace_back(key, val);\n\t\tkeyIndex[key] = idx;\n\t}\n\n\tfile.close();\n\treturn true;\n}\n    bool saveToFile() {\n\tstd::ofstream file(filePath, std::ios::trunc);\n\tif (!file.is_open()) {\n\t\tLOGE(\"PropertyManager: Could not open %s for saving.\", filePath.c_str());\n\t\treturn false;\n\t}\n\n\tfor (const auto& [key, value] : orderedProps) {\n\t\tfile << key << \"=\" << value << '\\n';\n\t}\n\n\tfile.close();\n\treturn true;\n}\n};"], ["/NoHello/module/src/main/cpp/log.h", "\n#pragma once\n\n#ifndef NOHELLO_LOG_H\n#define NOHELLO_LOG_H\n\n#ifdef DEBUG_BUILD\n#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, \"NoHello\", __VA_ARGS__)\n#else\n#define LOGD(...) ((void) 0)\n#endif\n\n#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, \"NoHello\", __VA_ARGS__)\n#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, \"NoHello\", __VA_ARGS__)\n#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, \"NoHello\", __VA_ARGS__)\n#define LOGF(...) __android_log_print(ANDROID_LOG_FATAL, \"NoHello\", __VA_ARGS__)\n\n#endif //NOHELLO_LOG_H\n"]], "task_instance_info": {"created_time": "2025-08-20 20:11:12", "created_task_model": "DeepSeek-R1", "code_description": "This code segment functions to: Process structured configuration directives by identifying section headers, managing state transitions between declaration blocks, and populating pattern storage containers with appropriately sanitized input values."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```cpp\n[TASK_BEGIN]\n            if (state == IDLE) {\n                if (word.rfind(\"root{\", 0) == 0) {\n                    current = ROOT;\n                    state = WRITING;\n                    std::string content = word.substr(5);\n                    size_t endBrace = content.find('}');\n                    if (endBrace != std::string::npos) {\n                        if (!content.substr(0, endBrace).empty())\n                            rule.rootSubstrs.push_back(content.substr(0, endBrace));\n                        current = NONE;\n                        state = IDLE;\n                    } else if (!content.empty()) {\n                        rule.rootSubstrs.push_back(content);\n                    }\n                }\n                else if (word.rfind(\"point{\", 0) == 0) {\n                    current = POINT;\n                    state = WRITING;\n                    std::string content = word.substr(6);\n                    size_t endBrace = content.find('}');\n                    if (endBrace != std::string::npos) {\n                        if (!content.substr(0, endBrace).empty())\n                            rule.mountPointSubstrs.push_back(content.substr(0, endBrace));\n                        current = NONE;\n                        state = IDLE;\n                    } else if (!content.empty()) {\n                        rule.mountPointSubstrs.push_back(content);\n                    }\n                }\n                else if (word.rfind(\"filesystem{\", 0) == 0) {\n                    current = FILESYSTEM;\n                    state = WRITING;\n                    std::string content = word.substr(11);\n                    size_t endBrace = content.find('}');\n                    if (endBrace != std::string::npos) {\n                        if (!content.substr(0, endBrace).empty())\n                            rule.fsTypes.insert(content.substr(0, endBrace));\n                        current = NONE;\n                        state = IDLE;\n                    } else if (!content.empty()) {\n                        rule.fsTypes.insert(content);\n                    }\n                }\n                else if (word.rfind(\"source{\", 0) == 0) {\n                    current = SOURCE;\n                    state = WRITING;\n                    std::string content = word.substr(7);\n                    size_t endBrace = content.find('}');\n                    if (endBrace != std::string::npos) {\n                        if (!content.substr(0, endBrace).empty())\n                            rule.sources.push_back(content.substr(0, endBrace));\n                        current = NONE;\n                        state = IDLE;\n                    } else if (!content.empty()) {\n                        rule.sources.push_back(content);\n                    }\n                }\n            }\n            else if (state == WRITING) {\n                size_t endBrace = word.find('}');\n                if (endBrace != std::string::npos) {\n                    std::string elem = word.substr(0, endBrace);\n                    if (!elem.empty()) {\n                        switch (current) {\n                            case ROOT: rule.rootSubstrs.push_back(elem); break;\n                            case POINT: rule.mountPointSubstrs.push_back(elem); break;\n                            case FILESYSTEM: rule.fsTypes.insert(elem); break;\n                            case SOURCE: rule.sources.push_back(elem); break;\n                            default: break;\n                        }\n                    }\n                    current = NONE;\n                    state = IDLE;\n                } else {\n                    switch (current) {\n                        case ROOT: rule.rootSubstrs.push_back(word); break;\n                        case POINT: rule.mountPointSubstrs.push_back(word); break;\n                        case FILESYSTEM: rule.fsTypes.insert(word); break;\n                        case SOURCE: rule.sources.push_back(word); break;\n                        default: break;\n                    }\n                }\n            }\n[TASK_END]\n```", "inference_time": "2025-08-20 20-13-07"}, "editdistance_info": {"edit_distance": 12.6005, "calculate_time": "2025-08-20 20:13:07", "true_code_clean": "if (state == IDLE) {\n\t\t\t\tif (current == NONE) {\n\t\t\t\t\tif (word == \"root\") current = ROOT;\n\t\t\t\t\telse if (word == \"point\") current = POINT;\n\t\t\t\t\telse if (word == \"fs\") current = FILESYSTEM;\n\t\t\t\t\telse if (word == \"source\") current = SOURCE;\n\t\t\t\t} else if (word == \"{\") {\n\t\t\t\t\tstate = WRITING;\n\t\t\t\t}\n\t\t\t} else if (state == WRITING && word == \"}\") {\n\t\t\t\tcurrent = NONE;\n\t\t\t\tstate = IDLE;\n\t\t\t} else {\n\t\t\t\tif ((word.front() == '\"' && word.back() == '\"') ||\n\t\t\t\t\t(word.front() == '\\'' && word.back() == '\\'')) {\n\t\t\t\t\tword = word.substr(1, word.size() - 2);\n\t\t\t\t}\n\t\t\t\tswitch (current) {\n\t\t\t\t\tcase ROOT:\n\t\t\t\t\t\trule.rootSubstrs.push_back(word);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase POINT:\n\t\t\t\t\t\trule.mountPointSubstrs.push_back(word);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase FILESYSTEM:\n\t\t\t\t\t\trule.fsTypes.insert(word);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase SOURCE:\n\t\t\t\t\t\trule.sources.push_back(word); \n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}", "predict_code_clean": "if (state == IDLE) {\n                if (word.rfind(\"root{\", 0) == 0) {\n                    current = ROOT;\n                    state = WRITING;\n                    std::string content = word.substr(5);\n                    size_t endBrace = content.find('}');\n                    if (endBrace != std::string::npos) {\n                        if (!content.substr(0, endBrace).empty())\n                            rule.rootSubstrs.push_back(content.substr(0, endBrace));\n                        current = NONE;\n                        state = IDLE;\n                    } else if (!content.empty()) {\n                        rule.rootSubstrs.push_back(content);\n                    }\n                }\n                else if (word.rfind(\"point{\", 0) == 0) {\n                    current = POINT;\n                    state = WRITING;\n                    std::string content = word.substr(6);\n                    size_t endBrace = content.find('}');\n                    if (endBrace != std::string::npos) {\n                        if (!content.substr(0, endBrace).empty())\n                            rule.mountPointSubstrs.push_back(content.substr(0, endBrace));\n                        current = NONE;\n                        state = IDLE;\n                    } else if (!content.empty()) {\n                        rule.mountPointSubstrs.push_back(content);\n                    }\n                }\n                else if (word.rfind(\"filesystem{\", 0) == 0) {\n                    current = FILESYSTEM;\n                    state = WRITING;\n                    std::string content = word.substr(11);\n                    size_t endBrace = content.find('}');\n                    if (endBrace != std::string::npos) {\n                        if (!content.substr(0, endBrace).empty())\n                            rule.fsTypes.insert(content.substr(0, endBrace));\n                        current = NONE;\n                        state = IDLE;\n                    } else if (!content.empty()) {\n                        rule.fsTypes.insert(content);\n                    }\n                }\n                else if (word.rfind(\"source{\", 0) == 0) {\n                    current = SOURCE;\n                    state = WRITING;\n                    std::string content = word.substr(7);\n                    size_t endBrace = content.find('}');\n                    if (endBrace != std::string::npos) {\n                        if (!content.substr(0, endBrace).empty())\n                            rule.sources.push_back(content.substr(0, endBrace));\n                        current = NONE;\n                        state = IDLE;\n                    } else if (!content.empty()) {\n                        rule.sources.push_back(content);\n                    }\n                }\n            }\n            else if (state == WRITING) {\n                size_t endBrace = word.find('}');\n                if (endBrace != std::string::npos) {\n                    std::string elem = word.substr(0, endBrace);\n                    if (!elem.empty()) {\n                        switch (current) {\n                            case ROOT: rule.rootSubstrs.push_back(elem); break;\n                            case POINT: rule.mountPointSubstrs.push_back(elem); break;\n                            case FILESYSTEM: rule.fsTypes.insert(elem); break;\n                            case SOURCE: rule.sources.push_back(elem); break;\n                            default: break;\n                        }\n                    }\n                    current = NONE;\n                    state = IDLE;\n                } else {\n                    switch (current) {\n                        case ROOT: rule.rootSubstrs.push_back(word); break;\n                        case POINT: rule.mountPointSubstrs.push_back(word); break;\n                        case FILESYSTEM: rule.fsTypes.insert(word); break;\n                        case SOURCE: rule.sources.push_back(word); break;\n                        default: break;\n                    }\n                }\n            }"}}