aboutsummaryrefslogtreecommitdiff
path: root/Ryujinx.Common/SystemInfo/MacOSSystemInfo.cs
blob: 5259760de43451036c08c516368bccda8306c901 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using Ryujinx.Common.Logging;

namespace Ryujinx.Common.SystemInfo
{
    [SupportedOSPlatform("macos")]
    class MacOSSystemInfo : SystemInfo
    {
        internal MacOSSystemInfo()
        {
            string cpuName = GetCpuidCpuName();

            if (cpuName == null && sysctlbyname("machdep.cpu.brand_string", out cpuName) != 0)
            {
                cpuName = "Unknown";
            }

            ulong totalRAM = 0;

            if (sysctlbyname("hw.memsize", ref totalRAM) != 0)  // Bytes
            {
                totalRAM = 0;
            }

            CpuName = $"{cpuName} ; {LogicalCoreCount} logical";
            RamTotal = totalRAM;
        }

        [DllImport("libSystem.dylib", CharSet = CharSet.Ansi, SetLastError = true)]
        private static extern int sysctlbyname(string name, IntPtr oldValue, ref ulong oldSize, IntPtr newValue, ulong newValueSize);

        private static int sysctlbyname(string name, IntPtr oldValue, ref ulong oldSize)
        {
            if (sysctlbyname(name, oldValue, ref oldSize, IntPtr.Zero, 0) == -1)
            {
                int err = Marshal.GetLastWin32Error();

                Logger.Error?.Print(LogClass.Application, $"Cannot retrieve '{name}'. Error Code {err}");

                return err;
            }

            return 0;
        }

        private static int sysctlbyname<T>(string name, ref T oldValue)
        {
            unsafe
            {
                ulong oldValueSize = (ulong)Unsafe.SizeOf<T>();

                return sysctlbyname(name, (IntPtr)Unsafe.AsPointer(ref oldValue), ref oldValueSize);
            }
        }

        private static int sysctlbyname(string name, out string oldValue)
        {
            oldValue = default;

            ulong strSize = 0;

            int res = sysctlbyname(name, IntPtr.Zero, ref strSize);

            if (res == 0)
            {
                byte[] rawData = new byte[strSize];

                unsafe
                {
                    fixed (byte* rawDataPtr = rawData)
                    {
                        res = sysctlbyname(name, (IntPtr)rawDataPtr, ref strSize);
                    }

                    if (res == 0)
                    {
                        oldValue = Encoding.ASCII.GetString(rawData);
                    }
                }
            }

            return res;
        }
    }
}