master ohmu/fastfetch-openbsd / src / detection / memory / memory_apple.c
ohmu  ·  2026-10-15
 1#include "memory.h"
 2#include "common/debug.h"
 3
 4#include <errno.h>
 5#include <string.h>
 6#include <mach/mach.h>
 7#include <sys/sysctl.h>
 8#include <unistd.h>
 9
10const char* ffDetectMemory(FFMemoryResult* ram) {
11    size_t length = sizeof(ram->bytesTotal);
12
13#if FF_APPLE_MEMSIZE_USABLE
14    if (sysctlbyname("hw.memsize_usable", &ram->bytesTotal, &length, nullptr, 0) != 0) {
15        FF_DEBUG("sysctlbyname(\"hw.memsize_usable\") failed: %s", strerror(errno));
16        return "Failed to read hw.memsize_usable";
17    }
18#else
19    if (sysctl((int[]) { CTL_HW, HW_MEMSIZE }, 2, &ram->bytesTotal, &length, nullptr, 0) != 0) {
20        FF_DEBUG("sysctl(HW_MEMSIZE) failed: %s", strerror(errno));
21        return "Failed to read hw.memsize";
22    }
23#endif
24
25    mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
26    vm_statistics64_data_t vmstat;
27    if (host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t) (&vmstat), &count) != KERN_SUCCESS) {
28        FF_DEBUG("host_statistics64() failed");
29        return "Failed to read host_statistics64";
30    }
31
32    // https://github.com/st3fan/osx-10.9/blob/34e34a6a539b5a822cda4074e56a7ced9b57da71/system_cmds-597.1.1/vm_stat.tproj/vm_stat.c#L139
33
34    uint64_t pagesFree = vmstat.free_count - vmstat.speculative_count;
35    uint64_t pagesFileBacked = vmstat.external_page_count; // Cached files
36    ram->bytesUsed = ram->bytesTotal - ((pagesFree + pagesFileBacked) << instance.state.platform.sysinfo.pageSizeShift);
37
38    return nullptr;
39}