ohmu
·
2026-10-15
1#include "detection/cpuusage/cpuusage.h"
2#include "common/debug.h"
3#include "common/mallocHelper.h"
4
5#include <sys/types.h>
6#include <sys/sysctl.h>
7#include <sys/resource.h>
8#include <stdlib.h>
9#include <errno.h>
10#include <string.h>
11
12#if __OpenBSD__ || __NetBSD__
13 #include <sys/sched.h>
14#endif
15
16const char* ffGetCpuUsageInfo(FFlist* cpuTimes) {
17 size_t neededLength = 0;
18#if __OpenBSD__ || __NetBSD__
19 #ifdef KERN_CPTIME
20 int ctls[] = { CTL_KERN, KERN_CPTIME };
21 #else
22 int ctls[] = { CTL_KERN, KERN_CP_TIME };
23 #endif
24 if (sysctl(ctls, 2, nullptr, &neededLength, nullptr, 0) != 0) {
25 FF_DEBUG("sysctl({CTL_KERN, KERN_CPTIME}, 2, nullptr) failed: %s", strerror(errno));
26 return "sysctl({CTL_KERN, KERN_CPTIME}, 2, nullptr) failed";
27 }
28#else
29 if (sysctlbyname("kern.cp_times", nullptr, &neededLength, nullptr, 0) != 0) {
30 FF_DEBUG("sysctlbyname(kern.cp_times, nullptr) failed: %s", strerror(errno));
31 return "sysctlbyname(kern.cp_times, nullptr) failed";
32 }
33#endif
34
35 uint32_t coreCount = (uint32_t) (neededLength / (CPUSTATES * sizeof(uint64_t)));
36 assert(coreCount > 0);
37
38 FF_AUTO_FREE uint64_t (*cpTimes)[CPUSTATES] = malloc(neededLength);
39
40#if __OpenBSD__ || __NetBSD__
41 if (sysctl(ctls, 2, cpTimes, &neededLength, nullptr, 0) != 0) {
42 FF_DEBUG("sysctl({CTL_KERN, KERN_CPTIME}, 2, cpTimes) failed: %s", strerror(errno));
43 return "sysctl({CTL_KERN, KERN_CPTIME}, 2, nullptr) failed";
44 }
45#else
46 if (sysctlbyname("kern.cp_times", cpTimes, &neededLength, nullptr, 0) != 0) {
47 FF_DEBUG("sysctlbyname(kern.cp_times, cpTimes) failed: %s", strerror(errno));
48 return "sysctlbyname(kern.cp_times, cpTime) failed";
49 }
50#endif
51
52 for (uint32_t i = 0; i < coreCount; ++i) {
53 uint64_t* cpTime = cpTimes[i];
54 uint64_t inUse = cpTime[CP_USER] + cpTime[CP_NICE] + cpTime[CP_SYS] + cpTime[CP_INTR];
55 uint64_t total = inUse + cpTime[CP_IDLE];
56
57 FFCpuUsageInfo* info = FF_LIST_ADD(FFCpuUsageInfo, *cpuTimes);
58 *info = (FFCpuUsageInfo) {
59 .inUseAll = inUse,
60 .totalAll = total,
61 };
62 }
63
64 return nullptr;
65}