aboutsummaryrefslogtreecommitdiff
path: root/Ryujinx.Memory/MemoryManagementWindows.cs
blob: 48616ec30057f2f872b6c67159161c1dced4c43b (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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
using Ryujinx.Memory.WindowsShared;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;

namespace Ryujinx.Memory
{
    [SupportedOSPlatform("windows")]
    static class MemoryManagementWindows
    {
        private static readonly IntPtr InvalidHandleValue = new IntPtr(-1);
        private static bool UseWin10Placeholders;

        private static object _emulatedHandleLock = new object();
        private static EmulatedSharedMemoryWindows[] _emulatedShared = new EmulatedSharedMemoryWindows[64];
        private static List<EmulatedSharedMemoryWindows> _emulatedSharedList = new List<EmulatedSharedMemoryWindows>();

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern IntPtr VirtualAlloc(
            IntPtr lpAddress,
            IntPtr dwSize,
            AllocationType flAllocationType,
            MemoryProtection flProtect);

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool VirtualProtect(
            IntPtr lpAddress,
            IntPtr dwSize,
            MemoryProtection flNewProtect,
            out MemoryProtection lpflOldProtect);

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool VirtualFree(IntPtr lpAddress, IntPtr dwSize, AllocationType dwFreeType);

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern IntPtr CreateFileMapping(
            IntPtr hFile,
            IntPtr lpFileMappingAttributes,
            FileMapProtection flProtect,
            uint dwMaximumSizeHigh,
            uint dwMaximumSizeLow,
            [MarshalAs(UnmanagedType.LPWStr)] string lpName);

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool CloseHandle(IntPtr hObject);

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern IntPtr MapViewOfFile(
            IntPtr hFileMappingObject,
            uint dwDesiredAccess,
            uint dwFileOffsetHigh,
            uint dwFileOffsetLow,
            IntPtr dwNumberOfBytesToMap);

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool UnmapViewOfFile(IntPtr lpBaseAddress);

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern uint GetLastError();

        static MemoryManagementWindows()
        {
            UseWin10Placeholders = OperatingSystem.IsWindowsVersionAtLeast(10, 0, 17134);
        }

        public static IntPtr Allocate(IntPtr size)
        {
            return AllocateInternal(size, AllocationType.Reserve | AllocationType.Commit);
        }

        public static IntPtr Reserve(IntPtr size)
        {
            return AllocateInternal(size, AllocationType.Reserve);
        }

        private static IntPtr AllocateInternal(IntPtr size, AllocationType flags = 0)
        {
            IntPtr ptr = VirtualAlloc(IntPtr.Zero, size, flags, MemoryProtection.ReadWrite);

            if (ptr == IntPtr.Zero)
            {
                throw new OutOfMemoryException();
            }

            return ptr;
        }

        public static bool Commit(IntPtr location, IntPtr size)
        {
            if (UseWin10Placeholders)
            {
                lock (_emulatedSharedList)
                {
                    foreach (var shared in _emulatedSharedList)
                    {
                        if (shared.CommitMap(location, size))
                        {
                            return true;
                        }
                    }
                }
            }

            return VirtualAlloc(location, size, AllocationType.Commit, MemoryProtection.ReadWrite) != IntPtr.Zero;
        }

        public static bool Decommit(IntPtr location, IntPtr size)
        {
            if (UseWin10Placeholders)
            {
                lock (_emulatedSharedList)
                {
                    foreach (var shared in _emulatedSharedList)
                    {
                        if (shared.DecommitMap(location, size))
                        {
                            return true;
                        }
                    }
                }
            }

            return VirtualFree(location, size, AllocationType.Decommit);
        }

        public static bool Reprotect(IntPtr address, IntPtr size, MemoryPermission permission)
        {
            if (UseWin10Placeholders)
            {
                ulong uaddress = (ulong)address;
                ulong usize = (ulong)size;
                while (usize > 0)
                {
                    ulong nextGranular = (uaddress & ~EmulatedSharedMemoryWindows.MappingMask) + EmulatedSharedMemoryWindows.MappingGranularity;
                    ulong mapSize = Math.Min(usize, nextGranular - uaddress);

                    if (!VirtualProtect((IntPtr)uaddress, (IntPtr)mapSize, GetProtection(permission), out _))
                    {
                        return false;
                    }

                    uaddress = nextGranular;
                    usize -= mapSize;
                }

                return true;
            }
            else
            {
                return VirtualProtect(address, size, GetProtection(permission), out _);
            }
        }

        private static MemoryProtection GetProtection(MemoryPermission permission)
        {
            return permission switch
            {
                MemoryPermission.None => MemoryProtection.NoAccess,
                MemoryPermission.Read => MemoryProtection.ReadOnly,
                MemoryPermission.ReadAndWrite => MemoryProtection.ReadWrite,
                MemoryPermission.ReadAndExecute => MemoryProtection.ExecuteRead,
                MemoryPermission.ReadWriteExecute => MemoryProtection.ExecuteReadWrite,
                MemoryPermission.Execute => MemoryProtection.Execute,
                _ => throw new MemoryProtectionException(permission)
            };
        }

        public static bool Free(IntPtr address)
        {
            return VirtualFree(address, IntPtr.Zero, AllocationType.Release);
        }

        private static int GetEmulatedHandle()
        {
            // Assumes we have the handle lock.

            for (int i = 0; i < _emulatedShared.Length; i++)
            {
                if (_emulatedShared[i] == null)
                {
                    return i + 1;
                }
            }

            throw new InvalidProgramException("Too many shared memory handles were created.");
        }

        public static bool EmulatedHandleValid(ref int handle)
        {
            handle--;
            return handle >= 0 && handle < _emulatedShared.Length && _emulatedShared[handle] != null;
        }

        public static IntPtr CreateSharedMemory(IntPtr size, bool reserve)
        {
            if (UseWin10Placeholders && reserve)
            {
                lock (_emulatedHandleLock)
                {
                    int handle = GetEmulatedHandle();
                    _emulatedShared[handle - 1] = new EmulatedSharedMemoryWindows((ulong)size);
                    _emulatedSharedList.Add(_emulatedShared[handle - 1]);

                    return (IntPtr)handle;
                }
            }
            else
            {
                var prot = reserve ? FileMapProtection.SectionReserve : FileMapProtection.SectionCommit;

                IntPtr handle = CreateFileMapping(
                    InvalidHandleValue,
                    IntPtr.Zero,
                    FileMapProtection.PageReadWrite | prot,
                    (uint)(size.ToInt64() >> 32),
                    (uint)size.ToInt64(),
                    null);

                if (handle == IntPtr.Zero)
                {
                    throw new OutOfMemoryException();
                }

                return handle;
            }
        }

        public static void DestroySharedMemory(IntPtr handle)
        {
            if (UseWin10Placeholders)
            {
                lock (_emulatedHandleLock)
                {
                    int iHandle = (int)(ulong)handle;

                    if (EmulatedHandleValid(ref iHandle))
                    {
                        _emulatedSharedList.Remove(_emulatedShared[iHandle]);
                        _emulatedShared[iHandle].Dispose();
                        _emulatedShared[iHandle] = null;

                        return;
                    }
                }
            }

            if (!CloseHandle(handle))
            {
                throw new ArgumentException("Invalid handle.", nameof(handle));
            }
        }

        public static IntPtr MapSharedMemory(IntPtr handle)
        {
            if (UseWin10Placeholders)
            {
                lock (_emulatedHandleLock)
                {
                    int iHandle = (int)(ulong)handle;

                    if (EmulatedHandleValid(ref iHandle))
                    {
                        return _emulatedShared[iHandle].Map();
                    }
                }
            }

            IntPtr ptr = MapViewOfFile(handle, 4 | 2, 0, 0, IntPtr.Zero);

            if (ptr == IntPtr.Zero)
            {
                throw new OutOfMemoryException();
            }

            return ptr;
        }

        public static void UnmapSharedMemory(IntPtr address)
        {
            if (UseWin10Placeholders)
            {
                lock (_emulatedHandleLock)
                {
                    foreach (EmulatedSharedMemoryWindows shared in _emulatedSharedList)
                    {
                        if (shared.Unmap((ulong)address))
                        {
                            return;
                        }
                    }
                }
            }

            if (!UnmapViewOfFile(address))
            {
                throw new ArgumentException("Invalid address.", nameof(address));
            }
        }
    }
}