From 71728247abd2aa5ee1dbb63681d18a76253e0c08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E9=80=9A=E6=B4=B2?= Date: Tue, 25 Aug 2026 23:24:31 +0800 Subject: [PATCH] Common (Sysctl): handle varying data lengths in integer retrieval functions --- src/common/impl/sysctl.c | 56 ++++++++++++++++++++++++++++++++++------ 1 file changed, 48 insertions(+), 8 deletions(-) diff --git a/src/common/impl/sysctl.c b/src/common/impl/sysctl.c index e17b5c348..122a79091 100644 --- a/src/common/impl/sysctl.c +++ b/src/common/impl/sysctl.c @@ -22,21 +22,41 @@ const char* ffSysctlGetString(int mib1, int mib2, FFstrbuf* result) { } int ffSysctlGetInt(int mib1, int mib2, int defaultValue) { - int result; + alignas(int) uint8_t result[sizeof(int)]; size_t neededLength = sizeof(result); if (sysctl((int[]) { mib1, mib2 }, 2, &result, &neededLength, nullptr, 0) != 0) { return defaultValue; } - return result; + switch (neededLength) { + case sizeof(int32_t): + return *(int32_t*)result; + case sizeof(int16_t): + return *(int16_t*)result; + case sizeof(int8_t): + return *(int8_t*)result; + default: + return defaultValue; + } } int64_t ffSysctlGetInt64(int mib1, int mib2, int64_t defaultValue) { - int64_t result; + alignas(int64_t) uint8_t result[sizeof(int64_t)]; size_t neededLength = sizeof(result); if (sysctl((int[]) { mib1, mib2 }, 2, &result, &neededLength, nullptr, 0) != 0) { return defaultValue; } - return result; + switch (neededLength) { + case sizeof(int64_t): + return *(int64_t*)result; + case sizeof(int32_t): + return *(int32_t*)result; + case sizeof(int16_t): + return *(int16_t*)result; + case sizeof(int8_t): + return *(int8_t*)result; + default: + return defaultValue; + } } #else const char* ffSysctlGetString(const char* propName, FFstrbuf* result) { @@ -59,21 +79,41 @@ const char* ffSysctlGetString(const char* propName, FFstrbuf* result) { } int ffSysctlGetInt(const char* propName, int defaultValue) { - int result; + alignas(int) uint8_t result[sizeof(int)]; size_t neededLength = sizeof(result); if (sysctlbyname(propName, &result, &neededLength, nullptr, 0) != 0) { return defaultValue; } - return result; + switch (neededLength) { + case sizeof(int32_t): + return *(int32_t*)result; + case sizeof(int16_t): + return *(int16_t*)result; + case sizeof(int8_t): + return *(int8_t*)result; + default: + return defaultValue; + } } int64_t ffSysctlGetInt64(const char* propName, int64_t defaultValue) { - int64_t result; + alignas(int64_t) uint8_t result[sizeof(int64_t)]; size_t neededLength = sizeof(result); if (sysctlbyname(propName, &result, &neededLength, nullptr, 0) != 0) { return defaultValue; } - return result; + switch (neededLength) { + case sizeof(int64_t): + return *(int64_t*)result; + case sizeof(int32_t): + return *(int32_t*)result; + case sizeof(int16_t): + return *(int16_t*)result; + case sizeof(int8_t): + return *(int8_t*)result; + default: + return defaultValue; + } } #endif // OpenBSD