Android-cuttlefish cvd tool
proc_file_utils_sysctl.h
Go to the documentation of this file.
1/*
2 * Copyright (C) 2026 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#pragma once
18
19#include <errno.h>
20#include <sys/sysctl.h>
21#include <sys/types.h>
22
23#include <cstddef>
24#include <span>
25#include <vector>
26
29
30namespace cuttlefish {
31
32// Reads the sysctl at mib into a vector of T, trimmed to what the kernel
33// wrote. With max_size == 0 the kernel is asked for the size first.
34template <typename T>
35Result<std::vector<T>> ReadSysctl(std::span<const int> mib,
36 size_t max_size = 0) {
37#ifdef __APPLE__
38 // macOS declares the name parameter as non-const.
39 int* name = const_cast<int*>(mib.data());
40#else
41 const int* name = mib.data();
42#endif
43 u_int namelen = mib.size();
44 size_t size = max_size;
45 if (size == 0) {
46 CF_EXPECTF(sysctl(name, namelen, nullptr, &size, nullptr, 0) == 0,
47 "sysctl failed: {}", StrError(errno));
48 }
49
50 std::vector<T> out(size / sizeof(T));
51 if (out.empty()) {
52 return out;
53 }
54
55 size = out.size() * sizeof(T);
56 CF_EXPECTF(sysctl(name, namelen, out.data(), &size, nullptr, 0) == 0,
57 "sysctl failed: {}", StrError(errno));
58 out.resize(size / sizeof(T));
59 return out;
60}
61
62} // namespace cuttlefish
#define CF_EXPECTF(RESULT, MSG,...)
Definition: expect.h:187
uint32_t size
Definition: io.h:2
Definition: alloc_driver.h:21
std::string StrError()
Definition: strerror.cc:26
Result< std::vector< T > > ReadSysctl(std::span< const int > mib, size_t max_size=0)
Definition: proc_file_utils_sysctl.h:35
tl::expected< T, StackTraceError< E > > Result
Definition: result_type.h:30