-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
InternalManager.cs
869 lines (712 loc) · 22.3 KB
/
InternalManager.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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace CitizenFX.Core
{
class InternalManager : MarshalByRefObject, InternalManagerInterface
{
private static readonly List<BaseScript> ms_definedScripts = new List<BaseScript>();
private static readonly List<Tuple<DateTime, AsyncCallback, string>> ms_delays = new List<Tuple<DateTime, AsyncCallback, string>>();
private static int ms_instanceId;
private static bool ms_useSyncContext;
private string m_resourceName;
public static IScriptHost ScriptHost { get; internal set; }
// actually, domain-global
internal static InternalManager GlobalManager { get; set; }
internal string ResourceName => m_resourceName;
[SecuritySafeCritical]
public InternalManager()
{
//CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
//CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;
GlobalManager = this;
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
InitializeAssemblyResolver();
CitizenTaskScheduler.Create();
}
[SecuritySafeCritical]
public void CreateTaskScheduler()
{
CitizenTaskScheduler.MakeDefault();
#if !IS_FXSERVER
SynchronizationContext.SetSynchronizationContext(new CitizenSynchronizationContext());
#endif
}
[SecuritySafeCritical]
public void Destroy()
{
if (m_retvalBuffer != IntPtr.Zero)
{
Marshal.FreeHGlobal(m_retvalBuffer);
m_retvalBuffer = IntPtr.Zero;
}
}
public void SetResourceName(string resourceName)
{
m_resourceName = resourceName;
}
public void SetConfiguration(bool useSyncContext)
{
ms_useSyncContext = useSyncContext;
}
[SecuritySafeCritical]
public void SetScriptHost(IScriptHost host, int instanceId)
{
ScriptHost = host;
ms_instanceId = instanceId;
}
[SecuritySafeCritical]
public void SetScriptHost(IntPtr hostPtr, int instanceId)
{
ScriptHost = new DirectScriptHost(hostPtr);
ms_instanceId = instanceId;
}
internal static void AddScript(BaseScript script)
{
if (!ms_definedScripts.Contains(script))
{
script.InitializeOnAdd();
ms_definedScripts.Add(script);
}
}
internal static void RemoveScript(BaseScript script)
{
if (ms_definedScripts.Contains(script))
{
ms_definedScripts.Remove(script);
}
}
public void CreateAssembly(string scriptFile, byte[] assemblyData, byte[] symbolData)
{
CreateAssemblyInternal(scriptFile, assemblyData, symbolData);
}
static Dictionary<string, Assembly> ms_loadedAssemblies = new Dictionary<string, Assembly>();
[SecuritySafeCritical]
private static Assembly CreateAssemblyInternal(string assemblyFile, byte[] assemblyData, byte[] symbolData)
{
if (ms_loadedAssemblies.ContainsKey(assemblyFile))
{
#if !IS_FXSERVER
Debug.WriteLine("Returning previously loaded assembly {0}", ms_loadedAssemblies[assemblyFile].FullName);
#endif
return ms_loadedAssemblies[assemblyFile];
}
var assembly = Assembly.Load(assemblyData, symbolData);
#if !IS_FXSERVER
Debug.WriteLine("Loaded {1} into {0}", AppDomain.CurrentDomain.FriendlyName, assembly.FullName);
#endif
ms_loadedAssemblies[assemblyFile] = assembly;
Func<Type, bool> typesPredicate = t =>
t != null && !t.IsAbstract && t.IsSubclassOf(typeof(BaseScript)) && t.GetConstructor(Type.EmptyTypes) != null;
// We have ClientScript and ServerScript defined only in the respective environments.
// Handle type load exceptions and keep going.
// See https://stackoverflow.com/a/11915414
IEnumerable<Type> definedTypes;
try
{
definedTypes = assembly.GetTypes().Where(typesPredicate);
}
catch (ReflectionTypeLoadException e)
{
definedTypes = e.Types.Where(typesPredicate);
}
foreach (var type in definedTypes)
{
try
{
var derivedScript = Activator.CreateInstance(type) as BaseScript;
Debug.WriteLine("Instantiated instance of script {0}.", type.FullName);
AddScript(derivedScript);
}
catch (Exception e)
{
Debug.WriteLine("Failed to instantiate instance of script {0}: {1}", type.FullName, e.ToString());
}
}
return assembly;
}
[SecuritySafeCritical]
void InitializeAssemblyResolver()
{
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Debug.WriteLine("Unhandled exception: {0}", e.ExceptionObject.ToString());
}
private static HashSet<string> ms_assemblySearchPaths = new HashSet<string>();
public void LoadAssembly(string name)
{
LoadAssemblyInternal(name.Replace(".dll", ""));
}
static Assembly LoadAssemblyInternal(string baseName, bool useSearchPaths = false)
{
var attemptPaths = new List<string>();
attemptPaths.Add(baseName);
var exceptions = new StringBuilder();
if (useSearchPaths)
{
foreach (var path in ms_assemblySearchPaths)
{
attemptPaths.Add($"{path.Replace('\\', '/')}/{baseName}");
}
}
foreach (var name in attemptPaths)
{
try
{
byte[] assemblyBytes;
using (var assemblyStream = new BinaryReader(new FxStreamWrapper(ScriptHost.OpenHostFile(name + ".dll"))))
{
assemblyBytes = assemblyStream.ReadBytes((int)assemblyStream.BaseStream.Length);
}
byte[] symbolBytes = null;
try
{
using (var symbolStream = new BinaryReader(new FxStreamWrapper(ScriptHost.OpenHostFile(name + ".dll.mdb"))))
{
symbolBytes = symbolStream.ReadBytes((int)symbolStream.BaseStream.Length);
}
}
catch
{
try
{
using (var symbolStream = new BinaryReader(new FxStreamWrapper(ScriptHost.OpenHostFile(name + ".pdb"))))
{
symbolBytes = symbolStream.ReadBytes((int)symbolStream.BaseStream.Length);
}
}
catch
{
// nothing
}
}
if (assemblyBytes != null)
{
var dirName = Path.GetDirectoryName(name);
if (!string.IsNullOrWhiteSpace(dirName))
{
ms_assemblySearchPaths.Add(dirName);
}
}
return CreateAssemblyInternal(name + ".dll", assemblyBytes, symbolBytes);
}
catch (Exception e)
{
//Switching the FileNotFound to a NotImplemented tells mono to disable I18N support.
//See: https://github.com/mono/mono/blob/8fee89e530eb3636325306c66603ba826319e8c5/mcs/class/corlib/System.Text/EncodingHelper.cs#L131
if (e is FileNotFoundException && string.Equals(name, "I18N", StringComparison.OrdinalIgnoreCase))
throw new NotImplementedException("I18N not found", e);
exceptions.AppendLine($"Exception loading assembly {name}: {e}");
}
}
if (!baseName.Contains(".resources"))
{
Debug.WriteLine($"Could not load assembly {baseName} - loading exceptions: {exceptions}");
}
return null;
}
[SecuritySafeCritical]
public byte[] WalkStack(byte[] boundaryStart, byte[] boundaryEnd)
{
var success = GameInterface.WalkStackBoundary(m_resourceName, boundaryStart, boundaryEnd, out var blob);
return (success) ? blob : null;
}
static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
return LoadAssemblyInternal(args.Name.Split(',')[0], useSearchPaths: true);
}
public static void AddDelay(int delay, AsyncCallback callback, string name = null)
{
lock (ms_delays)
ms_delays.Add(Tuple.Create(DateTime.UtcNow.AddMilliseconds(delay), callback, name));
}
public static void TickGlobal()
{
GlobalManager.Tick();
}
[SecuritySafeCritical]
public void Tick()
{
IsProfiling = ProfilerIsRecording();
if (GameInterface.SnapshotStackBoundary(out var b))
{
ScriptHost.SubmitBoundaryStart(b, b.Length);
}
try
{
using (var scope = new ProfilerScope(() => "c# cleanup"))
{
ScriptContext.GlobalCleanUp();
}
using (var scope = new ProfilerScope(() => "c# deferredDelay"))
{
var now = DateTime.UtcNow;
lock (ms_delays)
{
var count = ms_delays.Count;
for (int delayIdx = 0; delayIdx < count; delayIdx++)
{
var delay = ms_delays[delayIdx];
if (now >= delay.Item1)
{
using (var inScope = new ProfilerScope(() => delay.Item3))
{
try
{
BaseScript.CurrentName = delay.Item3;
delay.Item2(new DummyAsyncResult());
}
finally
{
BaseScript.CurrentName = null;
}
}
ms_delays.RemoveAt(delayIdx);
delayIdx--;
count--;
}
}
}
}
using (var scope = new ProfilerScope(() => "c# schedule"))
{
var flowBlock = CitizenTaskScheduler.SuppressFlow();
foreach (var script in ms_definedScripts.ToArray())
{
script.ScheduleRun();
}
flowBlock?.Undo();
}
using (var scope = new ProfilerScope(() => "c# tasks"))
{
CitizenTaskScheduler.Instance.Tick();
}
using (var scope = new ProfilerScope(() => "c# syncCtx"))
{
CitizenSynchronizationContext.Tick();
}
}
catch (Exception e)
{
PrintError("tick", e);
}
finally
{
ScriptHost.SubmitBoundaryStart(null, 0);
}
}
private class SyncContextScope : IDisposable
{
private static SynchronizationContext citizenContext = new CitizenSynchronizationContext();
private SynchronizationContext oldContext;
public SyncContextScope()
{
if (ms_useSyncContext)
{
oldContext = SynchronizationContext.Current;
SynchronizationContext.SetSynchronizationContext(citizenContext);
}
}
public void Dispose()
{
if (oldContext != null)
{
SynchronizationContext.SetSynchronizationContext(oldContext);
}
}
}
[SecuritySafeCritical]
public void TriggerEvent(string eventName, byte[] argsSerialized, string sourceString)
{
// not using using statements here as old Mono on Linux build doesn't know of these
#if IS_FXSERVER
using (var syncContext = new SyncContextScope())
#endif
{
if (GameInterface.SnapshotStackBoundary(out var bo))
{
ScriptHost.SubmitBoundaryStart(bo, bo.Length);
}
try
{
#if IS_FXSERVER
var netSource = (sourceString.StartsWith("net") || sourceString.StartsWith("internal-net")) ? sourceString : null;
#else
var netSource = sourceString.StartsWith("net") ? sourceString : null;
#endif
var obj = MsgPackDeserializer.Deserialize(argsSerialized, netSource) as List<object> ?? (IEnumerable<object>)new object[0];
var scripts = ms_definedScripts.ToArray();
var objArray = obj.ToArray();
NetworkFunctionManager.HandleEventTrigger(eventName, objArray, sourceString);
foreach (var script in scripts)
{
Task.Factory.StartNew(() =>
{
BaseScript.CurrentName = $"eventHandler {script.GetType().Name} -> {eventName}";
var t = script.EventHandlers.Invoke(eventName, sourceString, objArray);
BaseScript.CurrentName = null;
return t;
}, CancellationToken.None, TaskCreationOptions.None, CitizenTaskScheduler.Instance).Unwrap().ContinueWith(a =>
{
if (a.IsFaulted)
{
Debug.WriteLine($"Error invoking event handlers for {eventName}: {a.Exception?.InnerExceptions.Aggregate("", (b, s) => s + b.ToString() + "\n")}");
}
});
}
ExportDictionary.Invoke(eventName, objArray);
// invoke a single task tick
CitizenTaskScheduler.Instance.Tick();
}
catch (Exception e)
{
PrintError($"event ({eventName})", e);
}
finally
{
ScriptHost.SubmitBoundaryStart(null, 0);
}
}
}
[SecuritySafeCritical]
public static string CanonicalizeRef(int refId)
{
var re = ScriptHost.CanonicalizeRef(refId, ms_instanceId);
var str = Marshal.PtrToStringAnsi(re);
GameInterface.fwFree(re);
return str;
}
private IntPtr m_retvalBuffer;
private int m_retvalBufferSize;
[SecuritySafeCritical]
public void CallRef(int refIndex, byte[] argsSerialized, out IntPtr retvalSerialized, out int retvalSize)
{
// not using using statements here as old Mono on Linux build doesn't know of these
#if IS_FXSERVER
using (var syncContext = new SyncContextScope())
#endif
{
if (GameInterface.SnapshotStackBoundary(out var b))
{
ScriptHost.SubmitBoundaryStart(b, b.Length);
}
try
{
var retvalData = FunctionReference.Invoke(refIndex, argsSerialized);
if (retvalData != null)
{
if (m_retvalBuffer == IntPtr.Zero)
{
m_retvalBuffer = Marshal.AllocHGlobal(32768);
m_retvalBufferSize = 32768;
}
if (m_retvalBufferSize < retvalData.Length)
{
m_retvalBuffer = Marshal.ReAllocHGlobal(m_retvalBuffer, new IntPtr(retvalData.Length));
m_retvalBufferSize = retvalData.Length;
}
Marshal.Copy(retvalData, 0, m_retvalBuffer, retvalData.Length);
retvalSerialized = m_retvalBuffer;
retvalSize = retvalData.Length;
}
else
{
retvalSerialized = IntPtr.Zero;
retvalSize = 0;
}
}
catch (Exception e)
{
retvalSerialized = IntPtr.Zero;
retvalSize = 0;
PrintError($"reference call", e.InnerException ?? e);
}
}
}
public int DuplicateRef(int refIndex)
{
return FunctionReference.Duplicate(refIndex);
}
public void RemoveRef(int refIndex)
{
FunctionReference.Remove(refIndex);
}
[SecuritySafeCritical]
public ulong GetMemoryUsage()
{
return GameInterface.GetMemoryUsage();
}
[SecuritySafeCritical]
public static T CreateInstance<T>(Guid clsid)
{
var hr = GameInterface.CreateObjectInstance(clsid, typeof(T).GUID, out IntPtr ptr);
if (hr < 0)
{
Marshal.ThrowExceptionForHR(hr);
}
var obj = (T)Marshal.GetObjectForIUnknown(ptr);
Marshal.Release(ptr);
return obj;
}
[SecurityCritical]
public override object InitializeLifetimeService()
{
return null;
}
internal static void PrintErrorInternal(string where, Exception what)
{
GlobalManager?.PrintError(where, what);
}
[SecuritySafeCritical]
private void PrintError(string where, Exception what)
{
ScriptHost.SubmitBoundaryEnd(null, 0);
var stackTrace = new StackTrace(what, true);
#if IS_FXSERVER
var stackFrames = stackTrace.GetFrames();
#else
IEnumerable<StackFrame> stackFrames;
// HACK: workaround to iterate inner traces ourselves.
var fieldCapturedTraces = typeof(StackTrace).GetField("captured_traces", BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldCapturedTraces != null)
{
var captured_traces = (StackTrace[])fieldCapturedTraces.GetValue(stackTrace);
// client's mscorlib is missing this piece of code, copied from https://github.com/mono/mono/blob/ef848cfa83ea16b8afbd5b933968b1838df19505/mcs/class/corlib/System.Diagnostics/StackTrace.cs#L181
var accum = new List<StackFrame>();
foreach (var t in captured_traces)
{
for (int i = 0; i < t.FrameCount; i++)
accum.Add(t.GetFrame(i));
}
accum.AddRange(stackTrace.GetFrames());
stackFrames = accum;
}
else
stackFrames = stackTrace.GetFrames();
#endif
var frames = stackFrames
.Select(a => new
{
Frame = a,
Method = a.GetMethod(),
Type = a.GetMethod()?.DeclaringType
})
.Where(a => a.Method != null && (!a.Type.Assembly.GetName().Name.Contains("mscorlib") && !a.Type.Assembly.GetName().Name.Contains("CitizenFX.Core") && !a.Type.Assembly.GetName().Name.StartsWith("System")))
.Select(a => new
{
name = EnhancedStackTrace.GetMethodDisplayString(a.Method).ToString(),
sourcefile = a.Frame.GetFileName() ?? "",
line = a.Frame.GetFileLineNumber(),
file = $"@{m_resourceName}/{a.Type?.Assembly.GetName().Name ?? "UNK"}.dll"
});
var serializedFrames = MsgPackSerializer.Serialize(frames);
var formattedStackTrace = FormatStackTrace(serializedFrames);
if (formattedStackTrace != null)
{
Debug.WriteLine($"^1SCRIPT ERROR in {where}: {what.GetType().FullName}: {what.Message}^7");
Debug.WriteLine("{0}", formattedStackTrace);
}
}
[SecurityCritical]
private unsafe string FormatStackTrace(byte[] serializedFrames)
{
fixed (byte* ptr = serializedFrames)
{
return Native.Function.Call<string>((Native.Hash)0xd70c3bca, ptr, serializedFrames.Length);
}
}
private class DirectScriptHost : IScriptHost
{
private IntPtr hostPtr;
private FastMethod<Func<IntPtr, IntPtr, int>> invokeNativeMethod;
private FastMethod<Func<IntPtr, IntPtr, IntPtr, int>> openSystemFileMethod;
private FastMethod<Func<IntPtr, IntPtr, IntPtr, int>> openHostFileMethod;
private FastMethod<Func<IntPtr, int, int, IntPtr, int>> canonicalizeRefMethod;
private FastMethod<Action<IntPtr, IntPtr>> scriptTraceMethod;
private FastMethod<Action<IntPtr, IntPtr, int>> submitBoundaryStartMethod;
private FastMethod<Action<IntPtr, IntPtr, int>> submitBoundaryEndMethod;
private FastMethod<Func<IntPtr, IntPtr, int>> getLastErrorTextMethod;
[SecuritySafeCritical]
public DirectScriptHost(IntPtr hostPtr)
{
this.hostPtr = hostPtr;
invokeNativeMethod = new FastMethod<Func<IntPtr, IntPtr, int>>(nameof(invokeNativeMethod), hostPtr, 0);
openSystemFileMethod = new FastMethod<Func<IntPtr, IntPtr, IntPtr, int>>(nameof(openSystemFileMethod), hostPtr, 1);
openHostFileMethod = new FastMethod<Func<IntPtr, IntPtr, IntPtr, int>>(nameof(openHostFileMethod), hostPtr, 2);
canonicalizeRefMethod = new FastMethod<Func<IntPtr, int, int, IntPtr, int>>(nameof(canonicalizeRefMethod), hostPtr, 3);
scriptTraceMethod = new FastMethod<Action<IntPtr, IntPtr>>(nameof(scriptTraceMethod), hostPtr, 4);
submitBoundaryStartMethod = new FastMethod<Action<IntPtr, IntPtr, int>>(nameof(submitBoundaryStartMethod), hostPtr, 5);
submitBoundaryEndMethod = new FastMethod<Action<IntPtr, IntPtr, int>>(nameof(submitBoundaryEndMethod), hostPtr, 6);
getLastErrorTextMethod = new FastMethod<Func<IntPtr, IntPtr, int>>(nameof(getLastErrorTextMethod), hostPtr, 7);
}
[SecuritySafeCritical]
public void InvokeNative([MarshalAs(UnmanagedType.Struct)] IntPtr context)
{
var hr = invokeNativeMethod.method(hostPtr, context);
Marshal.ThrowExceptionForHR(hr);
}
[SecuritySafeCritical]
public fxIStream OpenSystemFile(string fileName)
{
return OpenSystemFileInternal(fileName);
}
[SecurityCritical]
private unsafe fxIStream OpenSystemFileInternal(string fileName)
{
IntPtr retVal = IntPtr.Zero;
IntPtr stringRef = Marshal.StringToHGlobalAnsi(fileName);
try
{
IntPtr* retValRef = &retVal;
Marshal.ThrowExceptionForHR(openSystemFileMethod.method(hostPtr, stringRef, new IntPtr(retValRef)));
}
finally
{
Marshal.FreeHGlobal(stringRef);
}
var s = (fxIStream)Marshal.GetObjectForIUnknown(retVal);
Marshal.Release(retVal);
return s;
}
[SecuritySafeCritical]
public fxIStream OpenHostFile(string fileName)
{
return OpenHostFileInternal(fileName);
}
[SecurityCritical]
private unsafe fxIStream OpenHostFileInternal(string fileName)
{
IntPtr retVal = IntPtr.Zero;
IntPtr stringRef = Marshal.StringToHGlobalAnsi(fileName);
try
{
IntPtr* retValRef = &retVal;
Marshal.ThrowExceptionForHR(openHostFileMethod.method(hostPtr, stringRef, new IntPtr(retValRef)));
}
finally
{
Marshal.FreeHGlobal(stringRef);
}
var s = (fxIStream)Marshal.GetObjectForIUnknown(retVal);
Marshal.Release(retVal);
return s;
}
[SecuritySafeCritical]
public IntPtr CanonicalizeRef(int localRef, int instanceId)
{
return CanonicalizeRefInternal(localRef, instanceId);
}
[SecurityCritical]
private unsafe IntPtr CanonicalizeRefInternal(int localRef, int instanceId)
{
IntPtr retVal = IntPtr.Zero;
try
{
IntPtr* retValRef = &retVal;
Marshal.ThrowExceptionForHR(canonicalizeRefMethod.method(hostPtr, localRef, instanceId, new IntPtr(retValRef)));
}
finally
{
}
return retVal;
}
[SecuritySafeCritical]
public void ScriptTrace([MarshalAs(UnmanagedType.LPStr)] string message)
{
ScriptTraceInternal(message);
}
[SecurityCritical]
private unsafe void ScriptTraceInternal(string message)
{
var bytes = Encoding.UTF8.GetBytes(message);
fixed (byte* p = bytes)
{
scriptTraceMethod.method(hostPtr, new IntPtr(p));
}
}
[SecuritySafeCritical]
public void SubmitBoundaryStart(byte[] boundaryData, int boundarySize)
{
SubmitBoundaryInternal(submitBoundaryStartMethod, boundaryData, boundarySize);
}
[SecuritySafeCritical]
public void SubmitBoundaryEnd(byte[] boundaryData, int boundarySize)
{
SubmitBoundaryInternal(submitBoundaryEndMethod, boundaryData, boundarySize);
}
[SecurityCritical]
private unsafe void SubmitBoundaryInternal(FastMethod<Action<IntPtr, IntPtr, int>> method, byte[] boundaryData, int boundarySize)
{
fixed (byte* p = boundaryData)
{
method.method(hostPtr, new IntPtr(p), boundarySize);
}
}
[SecuritySafeCritical]
public IntPtr GetLastErrorText()
{
return GetLastErrorTextInternal();
}
[SecurityCritical]
private unsafe IntPtr GetLastErrorTextInternal()
{
IntPtr retVal = IntPtr.Zero;
try
{
IntPtr* retValRef = &retVal;
Marshal.ThrowExceptionForHR(getLastErrorTextMethod.method(hostPtr, new IntPtr(retValRef)));
}
finally
{
}
return retVal;
}
}
internal static bool ProfilerIsRecording()
{
return Native.API.ProfilerIsRecording();
}
internal static void ProfilerEnterScope(string scopeName)
{
Native.API.ProfilerEnterScope(scopeName);
}
internal static void ProfilerExitScope()
{
Native.API.ProfilerExitScope();
}
internal static bool IsProfiling { get; private set; }
}
internal class ProfilerScope : IDisposable
{
public ProfilerScope(Func<string> name)
{
if (!InternalManager.IsProfiling)
{
return;
}
InternalManager.ProfilerEnterScope(name() ?? "c# scope");
}
public void Dispose()
{
if (!InternalManager.IsProfiling)
{
return;
}
InternalManager.ProfilerExitScope();
}
}
}