diff options
| author | sumuel <samuel@yakubos.org> | 2026-08-17 20:44:55 +0000 |
|---|---|---|
| committer | sumuel <samuel@yakubos.org> | 2026-08-17 20:44:55 +0000 |
| commit | 76424950e373d3b04ac3dd13019151bfba3e8423 (patch) | |
| tree | 4c3cfdbda039e592b9186be3e28f8d7cfd439e8a /src/detection/cpuusage/cpuusage_bsd.c | |
Add the files
Diffstat (limited to 'src/detection/cpuusage/cpuusage_bsd.c')
| -rw-r--r-- | src/detection/cpuusage/cpuusage_bsd.c | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/src/detection/cpuusage/cpuusage_bsd.c b/src/detection/cpuusage/cpuusage_bsd.c new file mode 100644 index 0000000..f690d15 --- /dev/null +++ b/src/detection/cpuusage/cpuusage_bsd.c @@ -0,0 +1,58 @@ +#include "detection/cpuusage/cpuusage.h" +#include "common/mallocHelper.h" + +#include <sys/types.h> +#include <sys/sysctl.h> +#include <sys/resource.h> +#include <stdlib.h> + +#if __OpenBSD__ || __NetBSD__ + #include <sys/sched.h> +#endif + +const char* ffGetCpuUsageInfo(FFlist* cpuTimes) { + size_t neededLength = 0; +#if __OpenBSD__ || __NetBSD__ + #ifdef KERN_CPTIME + int ctls[] = { CTL_KERN, KERN_CPTIME }; + #else + int ctls[] = { CTL_KERN, KERN_CP_TIME }; + #endif + if (sysctl(ctls, 2, NULL, &neededLength, NULL, 0) != 0) { + return "sysctl({CTL_KERN, KERN_CPTIME}, 2, NULL) failed"; + } +#else + if (sysctlbyname("kern.cp_times", NULL, &neededLength, NULL, 0) != 0) { + return "sysctlbyname(kern.cp_times, NULL) failed"; + } +#endif + + uint32_t coreCount = (uint32_t) (neededLength / (CPUSTATES * sizeof(uint64_t))); + assert(coreCount > 0); + + FF_AUTO_FREE uint64_t (*cpTimes)[CPUSTATES] = malloc(neededLength); + +#if __OpenBSD__ || __NetBSD__ + if (sysctl(ctls, 2, cpTimes, &neededLength, NULL, 0) != 0) { + return "sysctl({CTL_KERN, KERN_CPTIME}, 2, NULL) failed"; + } +#else + if (sysctlbyname("kern.cp_times", cpTimes, &neededLength, NULL, 0) != 0) { + return "sysctlbyname(kern.cp_times, cpTime) failed"; + } +#endif + + for (uint32_t i = 0; i < coreCount; ++i) { + uint64_t* cpTime = cpTimes[i]; + uint64_t inUse = cpTime[CP_USER] + cpTime[CP_NICE] + cpTime[CP_SYS] + cpTime[CP_INTR]; + uint64_t total = inUse + cpTime[CP_IDLE]; + + FFCpuUsageInfo* info = FF_LIST_ADD(FFCpuUsageInfo, *cpuTimes); + *info = (FFCpuUsageInfo) { + .inUseAll = inUse, + .totalAll = total, + }; + } + + return NULL; +} |