-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathSafeReference.cs
490 lines (429 loc) · 14.2 KB
/
SafeReference.cs
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
/* Date: 13.6.2015, Time: 13:34 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using IllidanS4.SharpUtils.Accessing;
using IllidanS4.SharpUtils.Interop;
using IllidanS4.SharpUtils.Metadata;
using IllidanS4.SharpUtils.Unsafe;
namespace IllidanS4.SharpUtils
{
/// <summary>
/// Contains a disposable reference to a variable.
/// </summary>
public sealed class SafeReference : IDisposable, ITypedReference, IReadWriteAccessor, IEquatable<SafeReference>
{
private TypedRef? m_ref{get; set;}
/// <summary>
/// Checks whether this is 'out' (write-only) reference. If this has been written to with <see cref="Value"/> or <see cref="SetValue"/>, returns true.
/// </summary>
public bool IsOut{get; private set;}
/// <summary>
/// Checks whether this reference is valid and not disposed.
/// </summary>
public bool IsValid{
get{
return m_ref != null;
}
}
private unsafe SafeReference(TypedReference tr, bool isOut)
{
m_ref = *(TypedRef*)(&tr);
IsOut = isOut;
}
/// <summary>
/// Creates a new <see cref="SafeReference"/> from a "ref" reference.
/// </summary>
/// <param name="obj">The reference to a variable.</param>
/// <param name="act">The action to receive the <see cref="SafeReference"/>.</param>
public static void Create<T>(ref T obj, Action<SafeReference> act)
{
Reference.Pin(
ref obj,
(ref T o) => {using(var r = new SafeReference(__makeref(o), false))act(r);}
);
}
/// <summary>
/// Creates a new <see cref="SafeReference"/> from an "out" reference.
/// </summary>
/// <param name="obj">The reference to a variable.</param>
/// <param name="act">The action to receive the <see cref="SafeReference"/>.</param>
public static void CreateOut<T>(out T obj, Action<SafeReference> act)
{
Reference.Pin(
out obj,
Reference.RefToOutAction(
(ref T o) => {using(var r = new SafeReference(__makeref(o), true))act(r);}
)
);
}
/// <summary>
/// Creates a new <see cref="SafeReference"/> from a "ref" reference.
/// </summary>
/// <param name="obj">The reference to a variable.</param>
/// <param name="func">The function to receive the <see cref="SafeReference"/>.</param>
/// <returns>The value returned by <paramref name="func"/></returns>
public static TRet Create<T, TRet>(ref T obj, Func<SafeReference, TRet> func)
{
return Reference.Pin(
ref obj,
(ref T o) => {using(var r = new SafeReference(__makeref(o), true))return func(r);}
);
}
/// <summary>
/// Creates a new <see cref="SafeReference"/> from an "out" reference.
/// </summary>
/// <param name="obj">The reference to a variable.</param>
/// <param name="func">The function to receive the <see cref="SafeReference"/>.</param>
/// <returns>The value returned by <paramref name="func"/></returns>
public static TRet CreateOut<T, TRet>(out T obj, Func<SafeReference, TRet> func)
{
return Reference.Pin(
out obj,
Reference.RefToOutFunc(
(ref T o) => {using(var r = new SafeReference(__makeref(o), true))return func(r);}
)
);
}
/// <summary>
/// Creates a new <see cref="SafeReference"/> from a <see cref="TypedReference"/>.
/// </summary>
/// <param name="tr">The typed reference.</param>
/// <param name="act">The action to receive the <see cref="SafeReference"/>.</param>
[CLSCompliant(false)]
public static void Create(TypedReference tr, Action<SafeReference> act)
{
tr.Pin(
tr2 => {using(var r = new SafeReference(tr2, false))act(r);}
);
}
/// <summary>
/// Creates a new <see cref="SafeReference"/> from a <see cref="TypedReference"/>.
/// </summary>
/// <param name="tr">The typed reference.</param>
/// <param name="func">The function to receive the <see cref="SafeReference"/>.</param>
/// <returns>The value returned by <paramref name="func"/></returns>
[CLSCompliant(false)]
public static TRet Create<TRet>(TypedReference tr, Func<SafeReference, TRet> func)
{
return tr.Pin(
tr2 => {using(var r = new SafeReference(tr2, false))return func(r);}
);
}
/// <summary>
/// Obtains an array of <see cref="SafeReference"/> from a variable number of typed references.
/// </summary>
/// <param name="act">The action to receive the array of <see cref="SafeReference"/>.</param>
/// <param name="__arglist">A variable number of typed references.</param>
[CLSCompliant(false)]
public static void Create(Action<SafeReference[]> act, __arglist)
{
Create(act, new ArgIterator(__arglist));
}
/// <summary>
/// Obtains an array of <see cref="SafeReference"/> from a variable number of typed references.
/// </summary>
/// <param name="act">The action to receive the array of <see cref="SafeReference"/>.</param>
/// <param name="refs">A variable number of typed references.</param>
public static void Create(Action<SafeReference[]> act, ArgIterator refs)
{
Create<Unit>(r=>{act(r);return 0;}, refs);
}
/// <summary>
/// Obtains an array of <see cref="SafeReference"/> from a variable number of typed references.
/// </summary>
/// <param name="func">The function to receive the array of <see cref="SafeReference"/>.</param>
/// <param name="refs">A variable number of typed references.</param>
/// <returns>The value returned by <paramref name="func"/></returns>
public static TRet Create<TRet>(Func<SafeReference[], TRet> func, ArgIterator refs)
{
var arr = new SafeReference[refs.GetRemainingCount()];
if(arr.Length > 0)
{
return PinHelper<TRet>.PinRecursive(refs.GetNextArg(), refs, arr, func);
}else{
return func(arr);
}
}
/// <summary>
/// The type of the <see cref="SafeReference"/>.
/// </summary>
public unsafe Type Type{
get{
var tr = m_ref.Value;
return __reftype(*(TypedReference*)(&tr));
}
}
/// <summary>
/// The value of the <see cref="SafeReference"/>.
/// </summary>
public unsafe object Value{
get{
if(IsOut) throw new InvalidOperationException("This is a write-only reference.");
var tr = m_ref.Value;
return (*(TypedReference*)(&tr)).GetValue();
}
set{
var tr = m_ref.Value;
(*(TypedReference*)(&tr)).SetValue(value);
IsOut = false;
}
}
/// <summary>
/// Sets the value of the <see cref="SafeReference"/>.
/// </summary>
public unsafe void SetValue<T>(T value)
{
var tr = m_ref.Value;
__refvalue(*(TypedReference*)(&tr), T) = value;
IsOut = false;
}
/// <summary>
/// Returns the value of the <see cref="SafeReference"/>.
/// </summary>
/// <returns>The value of the <see cref="SafeReference"/>.</returns>
public unsafe T GetValue<T>()
{
if(IsOut) throw new InvalidOperationException("This is a write-only reference.");
var tr = m_ref.Value;
return __refvalue(*(TypedReference*)(&tr), T);
}
/// <summary>
/// Obtains a <see cref="TypedReference"/> from this object.
/// </summary>
/// <param name="act">The action to receive the typed reference.</param>
[CLSCompliant(false)]
public unsafe void GetReference(TypedReferenceTools.TypedRefAction act)
{
if(IsOut) throw new InvalidOperationException("This is a write-only reference.");
var tr = m_ref.Value;
act(*(TypedReference*)(&tr));
}
/// <summary>
/// Obtains a <see cref="TypedReference"/> from this object.
/// </summary>
/// <param name="func">The function to receive the typed reference.</param>
/// <returns>The value returned by <paramref name="func"/></returns>
[CLSCompliant(false)]
public unsafe TRet GetReference<TRet>(TypedReferenceTools.TypedRefFunc<TRet> func)
{
if(IsOut) throw new InvalidOperationException("This is a write-only reference.");
var tr = m_ref.Value;
return func(*(TypedReference*)(&tr));
}
TRet ITypedReference.GetReference<TRet>(Func<SafeReference,TRet> func)
{
return func(this);
}
object IReadWriteAccessor.Item{
get{
return Value;
}
set{
Value = value;
}
}
object IWriteAccessor.Item{
set{
Value = value;
}
}
object IReadAccessor.Item{
get{
return Value;
}
}
/// <summary>
/// Disposes the reference and clears all pointers stored in it.
/// </summary>
public void Dispose()
{
m_ref = null;
GC.SuppressFinalize(this);
}
/// <summary>
/// Permors finalization on the reference.
/// </summary>
~SafeReference()
{
Dispose();
}
/// <summary>
/// True if this is a null reference.
/// </summary>
public bool IsNull{
get{
return m_ref.Value.Value == IntPtr.Zero;
}
}
/// <summary>
/// True if this is an empty reference (null and no type).
/// </summary>
public bool IsEmpty{
get{
return m_ref.Value == default(TypedRef);
}
}
/// <summary>
/// True if this reference is equal to another one.
/// </summary>
public bool Equals(SafeReference other)
{
return m_ref == other.m_ref;
}
/// <summary>
/// True if this reference is equal to another one.
/// </summary>
public override bool Equals(object obj)
{
SafeReference other = obj as SafeReference;
if(other == null)
return false;
return Equals(other);
}
/// <summary>
/// Returns the hash code of this reference.
/// </summary>
public override int GetHashCode()
{
int hashCode = 0;
unchecked {
if (m_ref != null)
hashCode += 1000000007 * m_ref.GetHashCode();
}
return hashCode;
}
/// <summary>
/// Creates a safe reference from a field in an object.
/// </summary>
public static void MakeReference(object target, FieldInfo[] fields, Action<SafeReference> act)
{
TypedReferenceTools.MakeTypedReference(target, fields, tr => Create(tr, act));
}
/// <summary>
/// Creates a safe reference from a field in an object.
/// </summary>
public static TRet MakeReference<TRet>(object target, FieldInfo[] fields, Func<SafeReference, TRet> func)
{
return TypedReferenceTools.MakeTypedReference(target, fields, tr => Create(tr, func));
}
/// <summary>
/// Creates a safe reference from a field in an object.
/// </summary>
public static void MakeReference(object target, Action<SafeReference> act, params FieldInfo[] fields)
{
MakeReference(target, fields, act);
}
/// <summary>
/// Creates a safe reference from a field in an object.
/// </summary>
public static TRet MakeReference<TRet>(object target, Func<SafeReference, TRet> func, params FieldInfo[] fields)
{
return MakeReference(target, fields, func);
}
/// <summary>
/// Creates a safe reference from a boxed value type.
/// </summary>
public static void GetBoxedReference(ValueType target, Action<SafeReference> act)
{
MakeReference(target, act);
}
/// <summary>
/// Creates a safe reference from a boxed value type.
/// </summary>
public static TRet GetBoxedReference<TRet>(ValueType target, Func<SafeReference,TRet> func)
{
return MakeReference(target, func);
}
internal void ChangeType(Type newType)
{
var tr = m_ref.Value;
tr.Type = newType.TypeHandle.Value;
m_ref = tr;
}
internal IntPtr GetAddress()
{
return m_ref.Value.Value;
}
internal void ChangeAddress(IntPtr addr)
{
var tr = m_ref.Value;
tr.Value = addr;
m_ref = tr;
}
/// <summary>
/// Sets the value of a variable specified by the safe reference.
/// </summary>
public unsafe void SetValue(SafeReference value)
{
var tr1 = m_ref.Value;
var tr2 = value.m_ref.Value;
(*(TypedReference*)(&tr1)).SetValue(*(TypedReference*)(&tr2));
}
private static class PinHelper<TRet>
{
public delegate TRet Del(TypedReference first, ArgIterator refs, SafeReference[] sr, Func<SafeReference[],TRet> func);
public static readonly Del PinRecursive = MakePinRecursive();
static Del MakePinRecursive()
{
var tai = typeof(ArgIterator);
var tsr = typeof(SafeReference);
var tvr = typeof(Func<SafeReference[],TRet>);
var trt = typeof(TRet);
var dyn = new DynamicMethod("PinRecursive", trt, new[]{typeof(TypedReference), tai, typeof(SafeReference[]), tvr}, typeof(PinHelper<TRet>));
var ctor = tsr.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance).Single();
var il = dyn.GetILGenerator();
var next = il.DefineLabel();
var end = il.DefineLabel();
il.DeclareLocal(typeof(void).MakeByRefType(), true); //void&
il.DeclareLocal(tsr); //SafeReference
il.DeclareLocal(trt); //TRet
il.Emit(OpCodes.Ldarga_S, 0); //loc_0 = ref *(void**)(&arg_0);
il.Emit(OpCodes.Ldind_I);
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Ldarg_0); //loc_1 = new SafeReference(arg_0, false);
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Newobj, ctor);
il.Emit(OpCodes.Stloc_1);
il.BeginExceptionBlock(); //try{
il.Emit(OpCodes.Ldarg_2); //arg_2[arg_2.Length-arg_1.GetRemainingCount()-1] = loc_1;
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Ldlen);
il.Emit(OpCodes.Ldarga_S, 1);
il.Emit(OpCodes.Call, tai.GetMethod("GetRemainingCount"));
il.Emit(OpCodes.Sub);
il.Emit(OpCodes.Ldc_I4_1);
il.Emit(OpCodes.Sub);
il.Emit(OpCodes.Ldloc_1);
il.Emit(OpCodes.Stelem_Ref);
il.Emit(OpCodes.Ldarga_S, 1); //if(arg_1.GetRemainincCount() > 0) goto next;
il.Emit(OpCodes.Call, tai.GetMethod("GetRemainingCount"));
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Bgt_S, next);
il.Emit(OpCodes.Ldarg_3); //loc_2 = arg_3(arg_2);
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Callvirt, tvr.GetMethod("Invoke"));
il.Emit(OpCodes.Stloc_2);
il.Emit(OpCodes.Br_S, end); //goto end;
il.MarkLabel(next); //next:
il.Emit(OpCodes.Ldarga_S, 1); //loc_2 = PinRecursive(arg_1.GetNextArg(), arg_1, arg_2, arg_3);
il.Emit(OpCodes.Call, tai.GetMethod("GetNextArg", Type.EmptyTypes));
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Ldarg_3);
il.Emit(OpCodes.Call, dyn);
il.Emit(OpCodes.Stloc_2);
il.MarkLabel(end); //end:
il.BeginFinallyBlock(); //}finally{
il.Emit(OpCodes.Ldloc_1); //loc_1.Dispose();
il.Emit(OpCodes.Callvirt, tsr.GetMethod("Dispose"));
il.EndExceptionBlock(); //}
il.Emit(OpCodes.Ldloc_2); //return loc_2;
il.Emit(OpCodes.Ret);
return (Del)dyn.CreateDelegate(typeof(Del));
}
}
}
}