1 ///////////////////////////////////////////////////////////////////////////////
4 /// \brief Get the amount of physical memory
6 // This code has been put into the public domain.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12 ///////////////////////////////////////////////////////////////////////////////
17 #if defined(HAVE_PHYSMEM_SYSCTL) || defined(HAVE_NCPU_SYSCTL)
18 # ifdef HAVE_SYS_PARAM_H
19 # include <sys/param.h>
21 # ifdef HAVE_SYS_SYSCTL_H
22 # include <sys/sysctl.h>
26 #if defined(HAVE_PHYSMEM_SYSCONF) || defined(HAVE_NCPU_SYSCONF)
31 /// \brief Get the amount of physical memory in bytes
33 /// \return Amount of physical memory in bytes. On error, zero is
35 static inline uint64_t
40 #if defined(HAVE_PHYSMEM_SYSCONF)
41 const long pagesize = sysconf(_SC_PAGESIZE);
42 const long pages = sysconf(_SC_PHYS_PAGES);
43 if (pagesize != -1 || pages != -1)
44 // According to docs, pagesize * pages can overflow.
45 // Simple case is 32-bit box with 4 GiB or more RAM,
46 // which may report exactly 4 GiB of RAM, and "long"
47 // being 32-bit will overflow. Casting to uint64_t
48 // hopefully avoids overflows in the near future.
49 ret = (uint64_t)(pagesize) * (uint64_t)(pages);
51 #elif defined(HAVE_PHYSMEM_SYSCTL)
52 int name[2] = { CTL_HW, HW_PHYSMEM };
54 size_t mem_ptr_size = sizeof(mem);
55 if (!sysctl(name, 2, &mem, &mem_ptr_size, NULL, NULL)) {
56 // Some systems use unsigned int as the "return value".
57 // This makes a difference on 64-bit boxes.
58 if (mem_ptr_size != sizeof(mem)) {
59 if (mem_ptr_size == sizeof(unsigned int))
60 ret = *(unsigned int *)(&mem);