1/*
2 * Copyright (C) 2012-2019 Apple Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23 * THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26#include "config.h"
27#include <wtf/RAMSize.h>
28
29#include <mutex>
30#include <wtf/StdLibExtras.h>
31
32#if OS(WINDOWS)
33#include <windows.h>
34#elif defined(USE_SYSTEM_MALLOC) && USE_SYSTEM_MALLOC
35#if OS(LINUX)
36#include <sys/sysinfo.h>
37#endif // OS(LINUX)
38#else
39#include <bmalloc/bmalloc.h>
40#endif
41
42namespace WTF {
43
44#if OS(WINDOWS)
45static constexpr size_t ramSizeGuess = 512 * MB;
46#endif
47
48static size_t computeRAMSize()
49{
50#if OS(WINDOWS)
51 MEMORYSTATUSEX status;
52 status.dwLength = sizeof(status);
53 bool result = GlobalMemoryStatusEx(&status);
54 if (!result)
55 return ramSizeGuess;
56 return status.ullTotalPhys;
57#elif defined(USE_SYSTEM_MALLOC) && USE_SYSTEM_MALLOC
58#if OS(LINUX)
59 struct sysinfo si;
60 sysinfo(&si);
61 return si.totalram * si.mem_unit;
62#else
63#error "Missing a platform specific way of determining the available RAM"
64#endif // OS(LINUX)
65#else
66 return bmalloc::api::availableMemory();
67#endif
68}
69
70size_t ramSize()
71{
72 static size_t ramSize;
73 static std::once_flag onceFlag;
74 std::call_once(onceFlag, [] {
75 ramSize = computeRAMSize();
76 });
77 return ramSize;
78}
79
80} // namespace WTF
81