T.J. Mercier | ae0b290 | 2024-08-05 18:18:35 +0000 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright (C) 2024 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #include <processgroup/util.h> |
| 18 | |
| 19 | #include <algorithm> |
| 20 | #include <iterator> |
| 21 | |
| 22 | namespace { |
| 23 | |
| 24 | const char SEP = '/'; |
| 25 | |
| 26 | std::string DeduplicateAndTrimSeparators(const std::string& path) { |
| 27 | bool lastWasSep = false; |
| 28 | std::string ret; |
| 29 | |
| 30 | std::copy_if(path.begin(), path.end(), std::back_inserter(ret), [&lastWasSep](char c) { |
| 31 | if (lastWasSep) { |
| 32 | if (c == SEP) return false; |
| 33 | lastWasSep = false; |
| 34 | } else if (c == SEP) { |
| 35 | lastWasSep = true; |
| 36 | } |
| 37 | return true; |
| 38 | }); |
| 39 | |
| 40 | if (ret.length() > 1 && ret.back() == SEP) ret.pop_back(); |
| 41 | |
| 42 | return ret; |
| 43 | } |
| 44 | |
| 45 | } // anonymous namespace |
| 46 | |
| 47 | namespace util { |
| 48 | |
| 49 | unsigned int GetCgroupDepth(const std::string& controller_root, const std::string& cgroup_path) { |
| 50 | const std::string deduped_root = DeduplicateAndTrimSeparators(controller_root); |
| 51 | const std::string deduped_path = DeduplicateAndTrimSeparators(cgroup_path); |
| 52 | |
| 53 | if (deduped_root.empty() || deduped_path.empty() || !deduped_path.starts_with(deduped_root)) |
| 54 | return 0; |
| 55 | |
| 56 | return std::count(deduped_path.begin() + deduped_root.size(), deduped_path.end(), SEP); |
| 57 | } |
| 58 | |
| 59 | } // namespace util |