Revert "libprocessgroup: Remove cgroup.rc file"

Revert submission 3212512

Reason for revert: Droidmonitor created revert due to b/372273614. Will be verifying through ABTD before submission.

Reverted changes: /q/submissionid:3212512

Change-Id: I37568516e973cb940f1229d52f94b8dc801da2ab
diff --git a/libprocessgroup/setup/Android.bp b/libprocessgroup/setup/Android.bp
index cc6c67c..1a4ad01 100644
--- a/libprocessgroup/setup/Android.bp
+++ b/libprocessgroup/setup/Android.bp
@@ -33,6 +33,7 @@
         "libjsoncpp",
     ],
     static_libs: [
+        "libcgrouprc_format",
         "libprocessgroup_util",
     ],
     header_libs: [
diff --git a/libprocessgroup/setup/cgroup_descriptor.h b/libprocessgroup/setup/cgroup_descriptor.h
index 1afd2ee..06ce186 100644
--- a/libprocessgroup/setup/cgroup_descriptor.h
+++ b/libprocessgroup/setup/cgroup_descriptor.h
@@ -21,7 +21,10 @@
 
 #include <sys/stat.h>
 
-#include <processgroup/cgroup_controller.h>
+#include <processgroup/format/cgroup_controller.h>
+
+namespace android {
+namespace cgrouprc {
 
 // Complete controller description for mounting cgroups
 class CgroupDescriptor {
@@ -30,7 +33,7 @@
                      mode_t mode, const std::string& uid, const std::string& gid, uint32_t flags,
                      uint32_t max_activation_depth);
 
-    const CgroupController* controller() const { return &controller_; }
+    const format::CgroupController* controller() const { return &controller_; }
     mode_t mode() const { return mode_; }
     std::string uid() const { return uid_; }
     std::string gid() const { return gid_; }
@@ -38,8 +41,11 @@
     void set_mounted(bool mounted);
 
   private:
-    CgroupController controller_;
+    format::CgroupController controller_;
     mode_t mode_ = 0;
     std::string uid_;
     std::string gid_;
 };
+
+}  // namespace cgrouprc
+}  // namespace android
diff --git a/libprocessgroup/setup/cgroup_map_write.cpp b/libprocessgroup/setup/cgroup_map_write.cpp
index 8211680..bd41874 100644
--- a/libprocessgroup/setup/cgroup_map_write.cpp
+++ b/libprocessgroup/setup/cgroup_map_write.cpp
@@ -22,28 +22,45 @@
 #include <fcntl.h>
 #include <grp.h>
 #include <pwd.h>
+#include <sys/mman.h>
 #include <sys/mount.h>
 #include <sys/stat.h>
 #include <sys/types.h>
+#include <time.h>
 #include <unistd.h>
 
 #include <optional>
 
 #include <android-base/file.h>
 #include <android-base/logging.h>
-#include <processgroup/cgroup_descriptor.h>
+#include <android-base/properties.h>
+#include <android-base/stringprintf.h>
+#include <android-base/unique_fd.h>
+#include <android/cgrouprc.h>
+#include <json/reader.h>
+#include <json/value.h>
+#include <processgroup/format/cgroup_file.h>
 #include <processgroup/processgroup.h>
 #include <processgroup/setup.h>
 #include <processgroup/util.h>
 
 #include "../build_flags.h"
-#include "../internal.h"
+#include "cgroup_descriptor.h"
+
+using android::base::GetUintProperty;
+using android::base::StringPrintf;
+using android::base::unique_fd;
+
+namespace android {
+namespace cgrouprc {
 
 static constexpr const char* CGROUPS_DESC_FILE = "/etc/cgroups.json";
 static constexpr const char* CGROUPS_DESC_VENDOR_FILE = "/vendor/etc/cgroups.json";
 
 static constexpr const char* TEMPLATE_CGROUPS_DESC_API_FILE = "/etc/task_profiles/cgroups_%u.json";
 
+static const std::string CGROUP_V2_ROOT_DEFAULT = "/sys/fs/cgroup";
+
 static bool ChangeDirModeAndOwner(const std::string& path, mode_t mode, const std::string& uid,
                                   const std::string& gid, bool permissive_mode = false) {
     uid_t pw_uid = -1;
@@ -131,15 +148,149 @@
     return true;
 }
 
+static void MergeCgroupToDescriptors(std::map<std::string, CgroupDescriptor>* descriptors,
+                                     const Json::Value& cgroup, const std::string& name,
+                                     const std::string& root_path, int cgroups_version) {
+    const std::string cgroup_path = cgroup["Path"].asString();
+    std::string path;
+
+    if (!root_path.empty()) {
+        path = root_path;
+        if (cgroup_path != ".") {
+            path += "/";
+            path += cgroup_path;
+        }
+    } else {
+        path = cgroup_path;
+    }
+
+    uint32_t controller_flags = 0;
+
+    if (cgroup["NeedsActivation"].isBool() && cgroup["NeedsActivation"].asBool()) {
+        controller_flags |= CGROUPRC_CONTROLLER_FLAG_NEEDS_ACTIVATION;
+    }
+
+    if (cgroup["Optional"].isBool() && cgroup["Optional"].asBool()) {
+        controller_flags |= CGROUPRC_CONTROLLER_FLAG_OPTIONAL;
+    }
+
+    uint32_t max_activation_depth = UINT32_MAX;
+    if (cgroup.isMember("MaxActivationDepth")) {
+        max_activation_depth = cgroup["MaxActivationDepth"].asUInt();
+    }
+
+    CgroupDescriptor descriptor(
+            cgroups_version, name, path, std::strtoul(cgroup["Mode"].asString().c_str(), 0, 8),
+            cgroup["UID"].asString(), cgroup["GID"].asString(), controller_flags,
+            max_activation_depth);
+
+    auto iter = descriptors->find(name);
+    if (iter == descriptors->end()) {
+        descriptors->emplace(name, descriptor);
+    } else {
+        iter->second = descriptor;
+    }
+}
+
+static const bool force_memcg_v2 = android::libprocessgroup_flags::force_memcg_v2();
+
+static bool ReadDescriptorsFromFile(const std::string& file_name,
+                                    std::map<std::string, CgroupDescriptor>* descriptors) {
+    std::vector<CgroupDescriptor> result;
+    std::string json_doc;
+
+    if (!android::base::ReadFileToString(file_name, &json_doc)) {
+        PLOG(ERROR) << "Failed to read task profiles from " << file_name;
+        return false;
+    }
+
+    Json::CharReaderBuilder builder;
+    std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
+    Json::Value root;
+    std::string errorMessage;
+    if (!reader->parse(&*json_doc.begin(), &*json_doc.end(), &root, &errorMessage)) {
+        LOG(ERROR) << "Failed to parse cgroups description: " << errorMessage;
+        return false;
+    }
+
+    if (root.isMember("Cgroups")) {
+        const Json::Value& cgroups = root["Cgroups"];
+        for (Json::Value::ArrayIndex i = 0; i < cgroups.size(); ++i) {
+            std::string name = cgroups[i]["Controller"].asString();
+
+            if (force_memcg_v2 && name == "memory") continue;
+
+            MergeCgroupToDescriptors(descriptors, cgroups[i], name, "", 1);
+        }
+    }
+
+    bool memcgv2_present = false;
+    std::string root_path;
+    if (root.isMember("Cgroups2")) {
+        const Json::Value& cgroups2 = root["Cgroups2"];
+        root_path = cgroups2["Path"].asString();
+        MergeCgroupToDescriptors(descriptors, cgroups2, CGROUPV2_HIERARCHY_NAME, "", 2);
+
+        const Json::Value& childGroups = cgroups2["Controllers"];
+        for (Json::Value::ArrayIndex i = 0; i < childGroups.size(); ++i) {
+            std::string name = childGroups[i]["Controller"].asString();
+
+            if (force_memcg_v2 && name == "memory") memcgv2_present = true;
+
+            MergeCgroupToDescriptors(descriptors, childGroups[i], name, root_path, 2);
+        }
+    }
+
+    if (force_memcg_v2 && !memcgv2_present) {
+        LOG(INFO) << "Forcing memcg to v2 hierarchy";
+        Json::Value memcgv2;
+        memcgv2["Controller"] = "memory";
+        memcgv2["NeedsActivation"] = true;
+        memcgv2["Path"] = ".";
+        memcgv2["Optional"] = true;  // In case of cgroup_disabled=memory, so we can still boot
+        MergeCgroupToDescriptors(descriptors, memcgv2, "memory",
+                                 root_path.empty() ? CGROUP_V2_ROOT_DEFAULT : root_path, 2);
+    }
+
+    return true;
+}
+
+static bool ReadDescriptors(std::map<std::string, CgroupDescriptor>* descriptors) {
+    // load system cgroup descriptors
+    if (!ReadDescriptorsFromFile(CGROUPS_DESC_FILE, descriptors)) {
+        return false;
+    }
+
+    // load API-level specific system cgroups descriptors if available
+    unsigned int api_level = GetUintProperty<unsigned int>("ro.product.first_api_level", 0);
+    if (api_level > 0) {
+        std::string api_cgroups_path =
+                android::base::StringPrintf(TEMPLATE_CGROUPS_DESC_API_FILE, api_level);
+        if (!access(api_cgroups_path.c_str(), F_OK) || errno != ENOENT) {
+            if (!ReadDescriptorsFromFile(api_cgroups_path, descriptors)) {
+                return false;
+            }
+        }
+    }
+
+    // load vendor cgroup descriptors if the file exists
+    if (!access(CGROUPS_DESC_VENDOR_FILE, F_OK) &&
+        !ReadDescriptorsFromFile(CGROUPS_DESC_VENDOR_FILE, descriptors)) {
+        return false;
+    }
+
+    return true;
+}
+
 // To avoid issues in sdk_mac build
 #if defined(__ANDROID__)
 
-static bool IsOptionalController(const CgroupController* controller) {
+static bool IsOptionalController(const format::CgroupController* controller) {
     return controller->flags() & CGROUPRC_CONTROLLER_FLAG_OPTIONAL;
 }
 
 static bool MountV2CgroupController(const CgroupDescriptor& descriptor) {
-    const CgroupController* controller = descriptor.controller();
+    const format::CgroupController* controller = descriptor.controller();
 
     // /sys/fs/cgroup is created by cgroup2 with specific selinux permissions,
     // try to create again in case the mount point is changed
@@ -173,7 +324,7 @@
 }
 
 static bool ActivateV2CgroupController(const CgroupDescriptor& descriptor) {
-    const CgroupController* controller = descriptor.controller();
+    const format::CgroupController* controller = descriptor.controller();
 
     if (!Mkdir(controller->path(), descriptor.mode(), descriptor.uid(), descriptor.gid())) {
         LOG(ERROR) << "Failed to create directory for " << controller->name() << " cgroup";
@@ -187,7 +338,7 @@
         std::string path = controller->path();
         path += "/cgroup.subtree_control";
 
-        if (!android::base::WriteStringToFile(str, path)) {
+        if (!base::WriteStringToFile(str, path)) {
             if (IsOptionalController(controller)) {
                 PLOG(INFO) << "Failed to activate optional controller " << controller->name()
                            << " at " << path;
@@ -202,7 +353,7 @@
 }
 
 static bool MountV1CgroupController(const CgroupDescriptor& descriptor) {
-    const CgroupController* controller = descriptor.controller();
+    const format::CgroupController* controller = descriptor.controller();
 
     // mkdir <path> [mode] [owner] [group]
     if (!Mkdir(controller->path(), descriptor.mode(), descriptor.uid(), descriptor.gid())) {
@@ -237,7 +388,7 @@
 }
 
 static bool SetupCgroup(const CgroupDescriptor& descriptor) {
-    const CgroupController* controller = descriptor.controller();
+    const format::CgroupController* controller = descriptor.controller();
 
     if (controller->version() == 2) {
         if (!strcmp(controller->name(), CGROUPV2_HIERARCHY_NAME)) {
@@ -259,6 +410,35 @@
 
 #endif
 
+static bool WriteRcFile(const std::map<std::string, CgroupDescriptor>& descriptors) {
+    unique_fd fd(TEMP_FAILURE_RETRY(open(CGROUPS_RC_PATH, O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC,
+                                         S_IRUSR | S_IRGRP | S_IROTH)));
+    if (fd < 0) {
+        PLOG(ERROR) << "open() failed for " << CGROUPS_RC_PATH;
+        return false;
+    }
+
+    format::CgroupFile fl;
+    fl.version_ = format::CgroupFile::FILE_CURR_VERSION;
+    fl.controller_count_ = descriptors.size();
+    int ret = TEMP_FAILURE_RETRY(write(fd, &fl, sizeof(fl)));
+    if (ret < 0) {
+        PLOG(ERROR) << "write() failed for " << CGROUPS_RC_PATH;
+        return false;
+    }
+
+    for (const auto& [name, descriptor] : descriptors) {
+        ret = TEMP_FAILURE_RETRY(
+                write(fd, descriptor.controller(), sizeof(format::CgroupController)));
+        if (ret < 0) {
+            PLOG(ERROR) << "write() failed for " << CGROUPS_RC_PATH;
+            return false;
+        }
+    }
+
+    return true;
+}
+
 CgroupDescriptor::CgroupDescriptor(uint32_t version, const std::string& name,
                                    const std::string& path, mode_t mode, const std::string& uid,
                                    const std::string& gid, uint32_t flags,
@@ -278,6 +458,9 @@
     controller_.set_flags(flags);
 }
 
+}  // namespace cgrouprc
+}  // namespace android
+
 static std::optional<bool> MGLRUDisabled() {
     const std::string file_name = "/sys/kernel/mm/lru_gen/enabled";
     std::string content;
@@ -289,8 +472,9 @@
     return content == "0x0000";
 }
 
-static std::optional<bool> MEMCGDisabled(const CgroupDescriptorMap& descriptors) {
-    std::string cgroup_v2_root = CGROUP_V2_ROOT_DEFAULT;
+static std::optional<bool> MEMCGDisabled(
+        const std::map<std::string, android::cgrouprc::CgroupDescriptor>& descriptors) {
+    std::string cgroup_v2_root = android::cgrouprc::CGROUP_V2_ROOT_DEFAULT;
     const auto it = descriptors.find(CGROUPV2_HIERARCHY_NAME);
     if (it == descriptors.end()) {
         LOG(WARNING) << "No Cgroups2 path found in cgroups.json. Vendor has modified Android, and "
@@ -311,10 +495,14 @@
     return content.find("memory") == std::string::npos;
 }
 
-static bool CreateV2SubHierarchy(const std::string& path, const CgroupDescriptorMap& descriptors) {
+static bool CreateV2SubHierarchy(
+        const std::string& path,
+        const std::map<std::string, android::cgrouprc::CgroupDescriptor>& descriptors) {
+    using namespace android::cgrouprc;
+
     const auto cgv2_iter = descriptors.find(CGROUPV2_HIERARCHY_NAME);
     if (cgv2_iter == descriptors.end()) return false;
-    const CgroupDescriptor cgv2_descriptor = cgv2_iter->second;
+    const android::cgrouprc::CgroupDescriptor cgv2_descriptor = cgv2_iter->second;
 
     if (!Mkdir(path, cgv2_descriptor.mode(), cgv2_descriptor.uid(), cgv2_descriptor.gid())) {
         PLOG(ERROR) << "Failed to create directory for " << path;
@@ -324,10 +512,10 @@
     // Activate all v2 controllers in path so they can be activated in
     // children as they are created.
     for (const auto& [name, descriptor] : descriptors) {
-        const CgroupController* controller = descriptor.controller();
+        const format::CgroupController* controller = descriptor.controller();
         std::uint32_t flags = controller->flags();
         std::uint32_t max_activation_depth = controller->max_activation_depth();
-        const int depth = GetCgroupDepth(controller->path(), path);
+        const int depth = util::GetCgroupDepth(controller->path(), path);
 
         if (controller->version() == 2 && name != CGROUPV2_HIERARCHY_NAME &&
             flags & CGROUPRC_CONTROLLER_FLAG_NEEDS_ACTIVATION && depth < max_activation_depth) {
@@ -347,13 +535,22 @@
 }
 
 bool CgroupSetup() {
-    CgroupDescriptorMap descriptors;
+    using namespace android::cgrouprc;
+
+    std::map<std::string, CgroupDescriptor> descriptors;
 
     if (getpid() != 1) {
         LOG(ERROR) << "Cgroup setup can be done only by init process";
         return false;
     }
 
+    // Make sure we do this only one time. No need for std::call_once because
+    // init is a single-threaded process
+    if (access(CGROUPS_RC_PATH, F_OK) == 0) {
+        LOG(WARNING) << "Attempt to call CgroupSetup() more than once";
+        return true;
+    }
+
     // load cgroups.json file
     if (!ReadDescriptors(&descriptors)) {
         LOG(ERROR) << "Failed to load cgroup description file";
@@ -362,18 +559,15 @@
 
     // setup cgroups
     for (auto& [name, descriptor] : descriptors) {
-        if (descriptor.controller()->flags() & CGROUPRC_CONTROLLER_FLAG_MOUNTED) {
-            LOG(WARNING) << "Attempt to call CgroupSetup() more than once";
-            return true;
-        }
-
-        if (!SetupCgroup(descriptor)) {
+        if (SetupCgroup(descriptor)) {
+            descriptor.set_mounted(true);
+        } else {
             // issue a warning and proceed with the next cgroup
             LOG(WARNING) << "Failed to setup " << name << " cgroup";
         }
     }
 
-    if (android::libprocessgroup_flags::force_memcg_v2()) {
+    if (force_memcg_v2) {
         if (MGLRUDisabled().value_or(false)) {
             LOG(WARNING) << "Memcg forced to v2 hierarchy with MGLRU disabled! "
                          << "Global reclaim performance will suffer.";
@@ -399,5 +593,26 @@
         }
     }
 
+    // mkdir <CGROUPS_RC_DIR> 0711 system system
+    if (!Mkdir(android::base::Dirname(CGROUPS_RC_PATH), 0711, "system", "system")) {
+        LOG(ERROR) << "Failed to create directory for " << CGROUPS_RC_PATH << " file";
+        return false;
+    }
+
+    // Generate <CGROUPS_RC_FILE> file which can be directly mmapped into
+    // process memory. This optimizes performance, memory usage
+    // and limits infrormation shared with unprivileged processes
+    // to the minimum subset of information from cgroups.json
+    if (!WriteRcFile(descriptors)) {
+        LOG(ERROR) << "Failed to write " << CGROUPS_RC_PATH << " file";
+        return false;
+    }
+
+    // chmod 0644 <CGROUPS_RC_PATH>
+    if (fchmodat(AT_FDCWD, CGROUPS_RC_PATH, 0644, AT_SYMLINK_NOFOLLOW) < 0) {
+        PLOG(ERROR) << "fchmodat() failed";
+        return false;
+    }
+
     return true;
 }