unsafe protected override void ShutdownLibrary() { if (thread != null) { needAbortThread = true; Thread.Sleep(50); thread.Abort(); } if (realChannels != null) { realChannels.Clear(); realChannels = null; } if (directSound != null) { IDirectSound8.Release(directSound); directSound = null; } if (criticalSection != null) { criticalSection.Dispose(); criticalSection = null; } instance = null; }
public static void Run(string hostName, Action action) { GlobalLockToken token = new GlobalLockToken("MACH_SHUT_3E94", TimeSpan.FromDays(1), TimeSpan.FromMinutes(10)); CriticalSection criticalSection = new CriticalSection(new DistributedLockManager(GlobalSettings.WcfHosts["Lock"])); criticalSection.RunConcurrent(token, action, _batchSize); }
/// <summary> /// Background thread used to notify the changes in the system /// </summary> private void NotifyChanges() { while (Notify) { // Release the mutex asap CriticalSection.WaitOne(); Dictionary <IModelElement, HashSet <ChangeKind> > changes = Changes; Changes = new Dictionary <IModelElement, HashSet <ChangeKind> >(); CriticalSection.ReleaseMutex(); // Notify of changes if (ValueChange != null) { foreach (KeyValuePair <IModelElement, HashSet <ChangeKind> > pair in changes) { foreach (ChangeKind kind in pair.Value) { ValueChange(pair.Key, kind); } } } Thread.Sleep(250); } }
public void ExecuteCriticalSection(CriticalSection criticalSection) { lock (this.stats) { if (!this.stats.ContainsKey(Thread.CurrentThread)) { this.stats.Add(Thread.CurrentThread, new Stats(0, 0, 0)); } } Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); if (!Monitor.TryEnter(this.LockObject)) { lock (this.stats) this.stats [Thread.CurrentThread].WaitCount++; //Console.WriteLine ("Logging Mutex {0} is waiting for lock on thread {1}", this.Name, Thread.CurrentThread.Name); Monitor.Enter(this.LockObject); //Console.WriteLine ("Logging Mutex {0} is got lock on thread {1} after {2}ms", this.Name, Thread.CurrentThread.Name, stopWatch.ElapsedMilliseconds); stopWatch.Restart(); } lock (this.stats) this.stats [Thread.CurrentThread].LockCount++; try { criticalSection.Invoke(); } catch (Exception ex) { BooruApp.BooruApplication.Log.Log(BooruLog.Category.Application, ex, string.Format("Logging Mutex {0} caught an exception during critical section", this.Name)); } Monitor.Exit(this.LockObject); lock (this.stats) this.stats [Thread.CurrentThread].totalWaitMS = this.stats [Thread.CurrentThread].totalWaitMS + stopWatch.ElapsedMilliseconds; //Console.WriteLine ("Logging Mutex {0} is released lock on thread {1} after {2}ms", this.Name, Thread.CurrentThread.Name, stopWatch.ElapsedMilliseconds); }
public async Task <IDisposable> EnterAsync(CancellationToken cancellationToken = default) { var criticalSection = new CriticalSection(SemaphoreMachine, cancellationToken); await criticalSection.EnterAsync(); return(criticalSection); }
public ThreadSimulation(CurrentSimulation currentSimulation, int threadId) { CancellationTokenSource = new CancellationTokenSource(); Thread = new Thread(delegate() { CriticalSection.UseCriticalSection(currentSimulation, threadId, CancellationTokenSource.Token); }); }
/// <summary> /// Simulate the current configuration /// </summary> /// <param name="currentSimulation"></param> /// <param name="dataPath"></param> /// <param name="rampUpPeriod"></param> public static void SimulateConfiguration(CurrentSimulation currentSimulation, string dataPath, int rampUpPeriod = 100) { ThreadGenerator.StopThreads(); CriticalSection.InitCriticalSection(currentSimulation.CriticalSectionDimension, dataPath); ThreadGenerator.InitThreads(currentSimulation); ThreadGenerator.StartThreads(rampUpPeriod); }
/// <summary> /// ReSyncs the VM Inventory. /// </summary> /// <param name="credential">The VSphere credentials to use during synchronization.</param> public static void SyncInventory(UserCredential credential) { UserManager.CurrentUser = credential; TraceFactory.Logger.Debug("Acquiring Lock."); var token = new GlobalLockToken("VirtualMachineInventorySynchronization", TimeSpan.FromMinutes(3), TimeSpan.FromMinutes(5)); // Create an explicit CriticalSection here because this call is coming from the UI where ExecutionServices is not initialized. CriticalSection criticalSection = new CriticalSection(new DistributedLockManager(GlobalSettings.WcfHosts["Lock"])); criticalSection.Run(token, UpdateInventory); }
public Cache(TimeSpan expireSpan = default, CacheType type = DefaultCacheType) { if (expireSpan == default) { expireSpan = DefaultExpireSpan; } this.ExpireSpan = expireSpan; this.Type = type; list = new Dictionary <TKey, Entry>(); LockObj = new CriticalSection(); }
public void SingleWriterFollowedByMultipleReaders() { var locker = new AsyncReaderWriterLock(); var cs = new CriticalSection(); var write1 = locker.WithWriteLockAsync(() => cs.WriteAsync(500)); var read1 = locker.WithReadLockAsync(() => cs.ReadAsync(5)); var read2 = locker.WithReadLockAsync(() => cs.ReadAsync(5)); Assert.Equal(1, cs.WriterCount); Assert.Equal(0, cs.ReaderCount); Task.WhenAll(read1, read2, write1).Wait(); }
// This method accepts a code pointer and allows the NativeDelegateRecord // associated with it to be collected. In order to call this method // safely it must be certain that no references to the code ptr exist // in native code. private static unsafe void ReleaseCodePtr(IntPtr codePtr) { byte * codeBuffer = (byte *)codePtr.ToPointer(); int idx = *(int *)(codeBuffer + 7); Delegate del = IdxToDelegate(idx); del.CodePtr = IntPtr.Zero; CriticalSection.AcquireMutex(); try { FreeNativeDelegateRecord(idx); } finally { CriticalSection.ReleaseMutex(); } FixedFree(codePtr); }
protected override void ShutdownLibrary() { if (thread != null) { needAbortThread = true; Thread.Sleep(50); thread.Abort(); } if (realChannels != null) { foreach (OpenALRealChannel realChannel in realChannels) { if (realChannel.alSource != 0) { Al.alDeleteSources(1, ref realChannel.alSource); realChannel.alSource = 0; } } } try { Alc.alcMakeContextCurrent(IntPtr.Zero); Alc.alcDestroyContext(alContext); Alc.alcCloseDevice(alDevice); } catch { } if (realChannels != null) { realChannels.Clear(); realChannels = null; } if (criticalSection != null) { criticalSection.Dispose(); criticalSection = null; } instance = null; }
public void MultipleReadersMultipleWriters() { var locker = new AsyncReaderWriterLock(); var cs = new CriticalSection(); var readersWriters = new[] { false, true, false, false, true, false, false, false, true, true, false, false, false, true, false, true, true, false, false, true }; var readerWriterTasks = new Task[readersWriters.Length]; Parallel.For(0, readersWriters.Length, index => { readerWriterTasks[index] = readersWriters[index] ? locker.WithWriteLockAsync(() => cs.WriteAsync(10)) : locker.WithReadLockAsync(() => cs.ReadAsync(10)); }); Task.WhenAll(readerWriterTasks).Wait(); }
private static IntPtr GetCodePtr(Delegate d, IntPtr callBackStub) { IntPtr codePtr = d.CodePtr; if (codePtr == IntPtr.Zero) { CriticalSection.AcquireMutex(); try { codePtr = d.CodePtr; if (codePtr == IntPtr.Zero) { int idx = AllocateNativeDelegateRecord(d); codePtr = CreateCodePtr(idx, callBackStub); d.CodePtr = codePtr; } } finally { CriticalSection.ReleaseMutex(); } } return(codePtr); }
/// <summary> /// Handles a change of the value of a model element /// </summary> /// <param name="value"></param> /// <param name="changeKind">Indicates the reason why the change occured</param> protected virtual void OnValueChange(IModelElement value, ChangeKind changeKind) { if (ValueChange != null) { if (value != null) { CriticalSection.WaitOne(); HashSet <ChangeKind> changeKinds; if (!Changes.TryGetValue(value, out changeKinds)) { changeKinds = new HashSet <ChangeKind>(); Changes.Add(value, changeKinds); } changeKinds.Add(changeKind); CriticalSection.ReleaseMutex(); } else { // ReSharper disable once ExpressionIsAlwaysNull ValueChange(value, changeKind); } } }
/// <summary> /// Initializes the Exchange version and the URL so we don't have to use autodiscover for all the subscribers. /// </summary> /// <param name="credential"></param> private static void Initialize(NetworkCredential credential) { ExchangeConnectionSettings settings = new ExchangeConnectionSettings(_exchangeServerSettings); if (settings.AutodiscoverEnabled) { Action action = new Action(() => { TraceFactory.Logger.Debug("Autodiscover lock acquired. Autodiscovering the Exchange Server."); MailAddress autodiscoverAddress = ExchangeEmailController.GetLdapEmailAddress(credential); _exchangeUrl = ExchangeEmailController.AutodiscoverExchangeUrl(autodiscoverAddress); }); TraceFactory.Logger.Debug("Attempting to autodiscover against Exchange"); CriticalSection criticalSection = new CriticalSection(new DistributedLockManager(GlobalSettings.WcfHosts["Lock"])); criticalSection.Run(new LocalLockToken("ExchangeAutodiscover", new TimeSpan(0, 5, 0), new TimeSpan(0, 5, 0)), action); } else { TraceFactory.Logger.Debug("Configuring exchange service using Exchange Web Services URL."); _exchangeUrl = settings.EwsUrl; } }
public static extern void InitializeCriticalSection(out CriticalSection lpCriticalSection);
private static void InstallBootstrapPatch() { var cAsmName = Assembly.GetExecutingAssembly().GetName(); var managedPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var dataDir = new DirectoryInfo(managedPath).Parent.Name; var gameName = dataDir.Substring(0, dataDir.Length - 5); loader.Debug("Finding backup"); var backupPath = Path.Combine(Environment.CurrentDirectory, "IPA", "Backups", gameName); var bkp = BackupManager.FindLatestBackup(backupPath); if (bkp == null) { loader.Warn("No backup found! Was BSIPA installed using the installer?"); } loader.Debug("Ensuring patch on UnityEngine.CoreModule exists"); #region Insert patch into UnityEngine.CoreModule.dll { var unityPath = Path.Combine(managedPath, "UnityEngine.CoreModule.dll"); // this is a critical section because if you exit in here, CoreModule can die CriticalSection.EnterExecuteSection(); var unityAsmDef = AssemblyDefinition.ReadAssembly(unityPath, new ReaderParameters { ReadWrite = false, InMemory = true, ReadingMode = ReadingMode.Immediate }); var unityModDef = unityAsmDef.MainModule; bool modified = false; foreach (var asmref in unityModDef.AssemblyReferences) { if (asmref.Name == cAsmName.Name) { if (asmref.Version != cAsmName.Version) { asmref.Version = cAsmName.Version; modified = true; } } } var application = unityModDef.GetType("UnityEngine", "Application"); MethodDefinition cctor = null; foreach (var m in application.Methods) { if (m.IsRuntimeSpecialName && m.Name == ".cctor") { cctor = m; } } var cbs = unityModDef.ImportReference(((Action)CreateBootstrapper).Method); if (cctor == null) { cctor = new MethodDefinition(".cctor", MethodAttributes.RTSpecialName | MethodAttributes.Static | MethodAttributes.SpecialName, unityModDef.TypeSystem.Void); application.Methods.Add(cctor); modified = true; var ilp = cctor.Body.GetILProcessor(); ilp.Emit(OpCodes.Call, cbs); ilp.Emit(OpCodes.Ret); } else { var ilp = cctor.Body.GetILProcessor(); for (var i = 0; i < Math.Min(2, cctor.Body.Instructions.Count); i++) { var ins = cctor.Body.Instructions[i]; switch (i) { case 0 when ins.OpCode != OpCodes.Call: ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs)); modified = true; break; case 0: { var methodRef = ins.Operand as MethodReference; if (methodRef?.FullName != cbs.FullName) { ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs)); modified = true; } break; } case 1 when ins.OpCode != OpCodes.Ret: ilp.Replace(ins, ilp.Create(OpCodes.Ret)); modified = true; break; } } } if (modified) { bkp?.Add(unityPath); unityAsmDef.Write(unityPath); } CriticalSection.ExitExecuteSection(); } #endregion Insert patch into UnityEngine.CoreModule.dll loader.Debug("Ensuring Assembly-CSharp is virtualized"); { var ascPath = Path.Combine(managedPath, "MainAssembly.dll"); // TODO: change to config option for other games #region Virtualize Assembly-CSharp.dll { CriticalSection.EnterExecuteSection(); try { var ascModule = VirtualizedModule.Load(ascPath); ascModule.Virtualize(cAsmName, () => bkp?.Add(ascPath)); } catch (Exception e) { loader.Error($"Could not virtualize {ascPath}"); loader.Error(e); } CriticalSection.ExitExecuteSection(); } #endregion Virtualize Assembly-CSharp.dll #region Anti-Yeet CriticalSection.EnterExecuteSection(); try { loader.Debug("Applying anti-yeet patch"); var ascAsmDef = AssemblyDefinition.ReadAssembly(ascPath, new ReaderParameters { ReadWrite = false, InMemory = true, ReadingMode = ReadingMode.Immediate }); var ascModDef = ascAsmDef.MainModule; var deleter = ascModDef.GetType("IPAPluginsDirDeleter"); deleter.Methods.Clear(); // delete all methods ascAsmDef.Write(ascPath); } catch (Exception) { // ignore } CriticalSection.ExitExecuteSection(); #endregion } }
//private static string otherNewtonsoftJson = null; // ReSharper disable once UnusedParameter.Global internal static void Main(string[] args) { // entry point for doorstop // At this point, literally nothing but mscorlib is loaded, // and since this class doesn't have any static fields that // aren't defined in mscorlib, we can control exactly what // gets loaded. try { if (Environment.GetCommandLineArgs().Contains("--verbose")) { WinConsole.Initialize(); } SetupLibraryLoading(); /*var otherNewtonsoft = Path.Combine( * Directory.EnumerateDirectories(Environment.CurrentDirectory, "*_Data").First(), * "Managed", * "Newtonsoft.Json.dll"); * if (File.Exists(otherNewtonsoft)) * { // this game ships its own Newtonsoft; force load ours and flag loading theirs * LibLoader.LoadLibrary(new AssemblyName("Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed")); * otherNewtonsoftJson = otherNewtonsoft; * }*/ EnsureDirectories(); // this is weird, but it prevents Mono from having issues loading the type. // IMPORTANT: NO CALLS TO ANY LOGGER CAN HAPPEN BEFORE THIS var unused = StandardLogger.PrintFilter; #region // Above hack explaination /* * Due to an unknown bug in the version of Mono that Unity uses, if the first access to StandardLogger * is a call to a constructor, then Mono fails to load the type correctly. However, if the first access is to * the above static property (or maybe any, but I don't really know) it behaves as expected and works fine. */ #endregion log.Debug("Initializing logger"); SelfConfig.ReadCommandLine(Environment.GetCommandLineArgs()); SelfConfig.Load(); DisabledConfig.Load(); /* Removing this crap just in case. * if (AntiPiracy.IsInvalid(Environment.CurrentDirectory)) * { * loader.Error("Invalid installation; please buy the game to run BSIPA."); * * return; * } */ CriticalSection.Configure(); loader.Debug("Prepping bootstrapper"); // updates backup InstallBootstrapPatch(); LibLoader.SetupAssemblyFilenames(true); GameVersionEarly.Load(); Updates.InstallPendingUpdates(); //HarmonyProtector.Protect(); pluginAsyncLoadTask = PluginLoader.LoadTask(); permissionFixTask = PermissionFix.FixPermissions(new DirectoryInfo(Environment.CurrentDirectory)); } catch (Exception e) { Console.WriteLine(e); } }
public static extern void EnterCriticalSection(ref CriticalSection lpCriticalSection);
protected override bool InitLibrary(IntPtr mainWindowHandle, int maxReal2DChannels, int maxReal3DChannels) { //NativeLibraryManager.PreLoadLibrary( "libogg" ); //NativeLibraryManager.PreLoadLibrary( "libvorbis" ); //NativeLibraryManager.PreLoadLibrary( "libvorbisfile" ); //preload dlls { var fileNames = new List <string>(); if (SystemSettings.CurrentPlatform == SystemSettings.Platform.Windows) { fileNames.Add("OpenAL32.dll"); } else if (SystemSettings.CurrentPlatform == SystemSettings.Platform.UWP) { fileNames.Add("SDL2.dll"); fileNames.Add("OpenAL32.dll"); } else if (SystemSettings.CurrentPlatform == SystemSettings.Platform.MacOS) { fileNames.Add("OpenAL32.dylib"); } else if (SystemSettings.CurrentPlatform == SystemSettings.Platform.Android) { //fileNames.Add( "libOpenAL.so" ); } else { Log.Fatal("OpenALSoundWorld: InitLibrary: Unknown platform."); return(false); } foreach (var fileName in fileNames) { var path = Path.Combine(VirtualFileSystem.Directories.PlatformSpecific, fileName); if (File.Exists(path)) { NativeLibraryManager.PreLoadLibrary(fileName); } } } criticalSection = CriticalSection.Create(); //if( PlatformInfo.Platform == PlatformInfo.Platforms.Android ) //{ // Alc.alcSetJNIEnvironmentAndJavaVM( // EngineApp.Instance._CallCustomPlatformSpecificMethod( "GetJNIEnvironment", IntPtr.Zero ), // EngineApp.Instance._CallCustomPlatformSpecificMethod( "GetJavaVM", IntPtr.Zero ) ); //} //string[] devices = Alc.alcGetStringv( IntPtr.Zero, Alc.ALC_DEVICE_SPECIFIER ); try { alDevice = Alc.alcOpenDevice(null); } catch (DllNotFoundException) { Log.InvisibleInfo("OpenALSoundSystem: OpenAL not found."); return(false); } catch (Exception e) { Log.InvisibleInfo("OpenALSoundSystem: Open device failed. " + e.Message); return(false); } if (alDevice == IntPtr.Zero) { Log.InvisibleInfo("OpenALSoundSystem: No sound driver."); return(false); } alContext = Alc.alcCreateContext(alDevice, IntPtr.Zero); if (alContext == IntPtr.Zero) { Log.Error("OpenALSoundSystem: Create context failed."); return(false); } try { Alc.alcMakeContextCurrent(alContext); } catch (Exception e) { Log.InvisibleInfo("OpenALSoundSystem: alcMakeContextCurrent failed. " + e.Message); return(false); } if (CheckError()) { return(false); } //get captureDeviceName try { captureDeviceName = Alc.alcGetString(alDevice, Alc.ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER); } catch { } //Channels realChannels = new List <OpenALRealChannel>(); for (int n = 0; n < maxReal2DChannels; n++) { OpenALRealChannel realChannel = new OpenALRealChannel(); AddRealChannel(realChannel, false); realChannels.Add(realChannel); } for (int n = 0; n < maxReal3DChannels; n++) { OpenALRealChannel realChannel = new OpenALRealChannel(); AddRealChannel(realChannel, true); realChannels.Add(realChannel); } fileStreamRealChannels = new List <OpenALRealChannel>(); thread = new Thread(new ThreadStart(ThreadFunction)); try { if (SystemSettings.CurrentPlatform != SystemSettings.Platform.UWP) { thread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); } } catch { } thread.IsBackground = true; thread.Start(); hWnd = mainWindowHandle; Al.alDistanceModel(Al.AL_NONE); return(true); }
protected override bool InitLibrary( IntPtr mainWindowHandle, int maxReal2DChannels, int maxReal3DChannels ) { instance = this; NativeLibraryManager.PreLoadLibrary( "libogg" ); NativeLibraryManager.PreLoadLibrary( "libvorbis" ); NativeLibraryManager.PreLoadLibrary( "libvorbisfile" ); //preload OpenAL32 { string fileName; if( PlatformInfo.Platform == PlatformInfo.Platforms.Windows ) fileName = "OpenAL32.dll"; else if( PlatformInfo.Platform == PlatformInfo.Platforms.MacOSX ) fileName = "OpenAL32.dylib"; else if( PlatformInfo.Platform == PlatformInfo.Platforms.Android ) fileName = "libOpenAL32.so"; else { Log.Fatal( "OpenALSoundWorld: InitLibrary: Unknown platform." ); return false; } string path = Path.Combine( NativeLibraryManager.GetNativeLibrariesDirectory(), fileName ); if( File.Exists( path ) ) NativeLibraryManager.PreLoadLibrary( "OpenAL32" ); } criticalSection = CriticalSection.Create(); if( PlatformInfo.Platform == PlatformInfo.Platforms.Android ) { Alc.alcSetJNIEnvironmentAndJavaVM( EngineApp.Instance._CallCustomPlatformSpecificMethod( "GetJNIEnvironment", IntPtr.Zero ), EngineApp.Instance._CallCustomPlatformSpecificMethod( "GetJavaVM", IntPtr.Zero ) ); } //string[] devices = Alc.alcGetStringv( IntPtr.Zero, Alc.ALC_DEVICE_SPECIFIER ); try { alDevice = Alc.alcOpenDevice( null ); } catch( DllNotFoundException ) { Log.InvisibleInfo( "OpenALSoundSystem: OpenAL not found." ); return false; } if( alDevice == IntPtr.Zero ) { Log.InvisibleInfo( "OpenALSoundSystem: No sound driver." ); return false; } alContext = Alc.alcCreateContext( alDevice, IntPtr.Zero ); if( alContext == IntPtr.Zero ) { Log.Error( "OpenALSoundSystem: Create context failed." ); return false; } Alc.alcMakeContextCurrent( alContext ); if( CheckError() ) return false; //get captureDeviceName try { captureDeviceName = Alc.alcGetString( alDevice, Alc.ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER ); } catch { } //Channels realChannels = new List<OpenALRealChannel>(); for( int n = 0; n < maxReal2DChannels; n++ ) { OpenALRealChannel realChannel = new OpenALRealChannel(); AddRealChannel( realChannel, false ); realChannels.Add( realChannel ); } for( int n = 0; n < maxReal3DChannels; n++ ) { OpenALRealChannel realChannel = new OpenALRealChannel(); AddRealChannel( realChannel, true ); realChannels.Add( realChannel ); } fileStreamRealChannels = new List<OpenALRealChannel>(); thread = new Thread( new ThreadStart( ThreadFunction ) ); thread.CurrentCulture = new System.Globalization.CultureInfo( "en-US" ); thread.IsBackground = true; thread.Start(); hWnd = mainWindowHandle; Al.alDistanceModel( Al.AL_NONE ); return true; }
public static extern void LeaveCriticalSection(ref CriticalSection lpCriticalSection);
private bool IsCriticalSectionActive() { return((this.CSMask & CriticalSection.GetActive()) != (CriticalSections)0); }
public static LazyResult <T> New <T>(Func <T> valueFactory, LazyThreadSafetyMode lazyThreadSafetyMode, CriticalSection sync) => new LazyResult <T, int>(x => valueFactory(), 0, lazyThreadSafetyMode, sync);
private static void InstallBootstrapPatch() { var sw = Stopwatch.StartNew(); var cAsmName = Assembly.GetExecutingAssembly().GetName(); var managedPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var dataDir = new DirectoryInfo(managedPath).Parent.Name; var gameName = dataDir.Substring(0, dataDir.Length - 5); injector.Debug("Finding backup"); var backupPath = Path.Combine(Environment.CurrentDirectory, "IPA", "Backups", gameName); var bkp = BackupManager.FindLatestBackup(backupPath); if (bkp == null) { injector.Warn("No backup found! Was BSIPA installed using the installer?"); } injector.Debug("Ensuring patch on UnityEngine.CoreModule exists"); #region Insert patch into UnityEngine.CoreModule.dll { var unityPath = Path.Combine(managedPath, "UnityEngine.CoreModule.dll"); // this is a critical section because if you exit in here, CoreModule can die using var critSec = CriticalSection.ExecuteSection(); using var unityAsmDef = AssemblyDefinition.ReadAssembly(unityPath, new ReaderParameters { ReadWrite = false, InMemory = true, ReadingMode = ReadingMode.Immediate }); var unityModDef = unityAsmDef.MainModule; bool modified = false; foreach (var asmref in unityModDef.AssemblyReferences) { if (asmref.Name == cAsmName.Name) { if (asmref.Version != cAsmName.Version) { asmref.Version = cAsmName.Version; modified = true; } } } var application = unityModDef.GetType("UnityEngine", "Camera"); if (application == null) { injector.Critical("UnityEngine.CoreModule doesn't have a definition for UnityEngine.Camera!" + "Nothing to patch to get ourselves into the Unity run cycle!"); goto endPatchCoreModule; } MethodDefinition?cctor = null; foreach (var m in application.Methods) { if (m.IsRuntimeSpecialName && m.Name == ".cctor") { cctor = m; } } var cbs = unityModDef.ImportReference(((Action)CreateBootstrapper).Method); if (cctor == null) { cctor = new MethodDefinition(".cctor", MethodAttributes.RTSpecialName | MethodAttributes.Static | MethodAttributes.SpecialName, unityModDef.TypeSystem.Void); application.Methods.Add(cctor); modified = true; var ilp = cctor.Body.GetILProcessor(); ilp.Emit(OpCodes.Call, cbs); ilp.Emit(OpCodes.Ret); } else { var ilp = cctor.Body.GetILProcessor(); for (var i = 0; i < Math.Min(2, cctor.Body.Instructions.Count); i++) { var ins = cctor.Body.Instructions[i]; switch (i) { case 0 when ins.OpCode != OpCodes.Call: ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs)); modified = true; break; case 0: { var methodRef = ins.Operand as MethodReference; if (methodRef?.FullName != cbs.FullName) { ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs)); modified = true; } break; } case 1 when ins.OpCode != OpCodes.Ret: ilp.Replace(ins, ilp.Create(OpCodes.Ret)); modified = true; break; } } } if (modified) { bkp?.Add(unityPath); unityAsmDef.Write(unityPath); } } endPatchCoreModule: #endregion Insert patch into UnityEngine.CoreModule.dll injector.Debug("Ensuring game assemblies are virtualized"); #region Virtualize game assemblies bool isFirst = true; foreach (var name in SelfConfig.GameAssemblies_) { var ascPath = Path.Combine(managedPath, name); using var execSec = CriticalSection.ExecuteSection(); try { injector.Debug($"Virtualizing {name}"); using var ascModule = VirtualizedModule.Load(ascPath); ascModule.Virtualize(cAsmName, () => bkp?.Add(ascPath)); } catch (Exception e) { injector.Error($"Could not virtualize {ascPath}"); if (SelfConfig.Debug_.ShowHandledErrorStackTraces_) { injector.Error(e); } } #if BeatSaber if (isFirst) { try { injector.Debug("Applying anti-yeet patch"); using var ascAsmDef = AssemblyDefinition.ReadAssembly(ascPath, new ReaderParameters { ReadWrite = false, InMemory = true, ReadingMode = ReadingMode.Immediate }); var ascModDef = ascAsmDef.MainModule; var deleter = ascModDef.GetType("IPAPluginsDirDeleter"); deleter.Methods.Clear(); // delete all methods ascAsmDef.Write(ascPath); isFirst = false; } catch (Exception e) { injector.Warn($"Could not apply anti-yeet patch to {ascPath}"); if (SelfConfig.Debug_.ShowHandledErrorStackTraces_) { injector.Warn(e); } } } #endif } #endregion sw.Stop(); injector.Info($"Installing bootstrapper took {sw.Elapsed}"); }
internal static void Main(string[] args) { // entry point for doorstop // At this point, literally nothing but mscorlib is loaded, // and since this class doesn't have any static fields that // aren't defined in mscorlib, we can control exactly what // gets loaded. _ = args; try { if (Environment.GetCommandLineArgs().Contains("--verbose")) { WinConsole.Initialize(); } SetupLibraryLoading(); EnsureDirectories(); // this is weird, but it prevents Mono from having issues loading the type. // IMPORTANT: NO CALLS TO ANY LOGGER CAN HAPPEN BEFORE THIS var unused = StandardLogger.PrintFilter; #region // Above hack explaination /* * Due to an unknown bug in the version of Mono that Unity uses, if the first access to StandardLogger * is a call to a constructor, then Mono fails to load the type correctly. However, if the first access is to * the above static property (or maybe any, but I don't really know) it behaves as expected and works fine. */ #endregion log.Debug("Initializing logger"); SelfConfig.ReadCommandLine(Environment.GetCommandLineArgs()); SelfConfig.Load(); DisabledConfig.Load(); if (AntiPiracy.IsInvalid(Environment.CurrentDirectory)) { log.Error("Invalid installation; please buy the game to run BSIPA."); return; } CriticalSection.Configure(); injector.Debug("Prepping bootstrapper"); // updates backup InstallBootstrapPatch(); GameVersionEarly.Load(); AntiMalwareEngine.Initialize(); Updates.InstallPendingUpdates(); LibLoader.SetupAssemblyFilenames(true); pluginAsyncLoadTask = PluginLoader.LoadTask(); permissionFixTask = PermissionFix.FixPermissions(new DirectoryInfo(Environment.CurrentDirectory)); } catch (Exception e) { Console.WriteLine(e); } }
public Producer(IProductFactory <T> factory) { m_CriticalSection = new CriticalSection <T>(factory); m_Timer = new Timer(x => m_CriticalSection.GenerateChar(), null, 0, 200); }
public static extern void DeleteCriticalSection(ref CriticalSection lpCriticalSection);
unsafe protected override bool InitLibrary( IntPtr mainWindowHandle, int maxReal2DChannels, int maxReal3DChannels ) { NativeLibraryManager.PreLoadLibrary( "libogg" ); NativeLibraryManager.PreLoadLibrary( "libvorbis" ); NativeLibraryManager.PreLoadLibrary( "libvorbisfile" ); NativeLibraryManager.PreLoadLibrary( "DirectSoundNativeWrapper" ); { DSoundStructureSizes sizes = new DSoundStructureSizes(); sizes.Init(); DSoundStructureSizes originalSizes; DSound.GetStructureSizes( out originalSizes ); FieldInfo[] fields = sizes.GetType().GetFields( BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public ); foreach( FieldInfo field in fields ) { int originalSize = (int)field.GetValue( originalSizes ); int size = (int)field.GetValue( sizes ); if( originalSize != size ) { Log.Fatal( "DirectXSoundSystem: Invalid unmanaged bridge. " + "Invalid \"{0}\". Native size = \"{1}\". Managed size = \"{2}\".", field.Name, originalSize, size ); return false; } } } instance = this; criticalSection = CriticalSection.Create(); DSound.CoInitialize( null ); int hr; //create IDirectSound using the primary sound device void*/*IDirectSound8*/ directSoundTemp; hr = DSound.DirectSoundCreate8( null, out directSoundTemp, null ); if( Wrapper.FAILED( hr ) ) { if( hr == DSound.Get_DSERR_NODRIVER() ) { Log.InvisibleInfo( "DirectXSoundSystem: No sound driver." ); return false; } Error( "DirectSoundCreate8", hr ); return false; } directSound = (IDirectSound8*)directSoundTemp; //set DirectSound cooperative level hWnd = mainWindowHandle; hr = IDirectSound8.SetCooperativeLevel( directSound, hWnd, DSound.DSSCL_PRIORITY ); if( Wrapper.FAILED( hr ) ) { Error( "SetCooperativeLevel", hr ); return false; } //set primary buffer format { hr = SetPrimaryBufferFormat( 2, 44100, 16, false ); if( Wrapper.FAILED( hr ) ) hr = SetPrimaryBufferFormat( 2, 22050, 16, true ); if( Wrapper.FAILED( hr ) ) return false; } //get listener { void*/*IDirectSoundBuffer*/ primaryBuffer = null; // Obtain primary buffer, asking it for 3D control DSBUFFERDESC bufferDesc = new DSBUFFERDESC(); //ZeroMemory( &bufferDesc, sizeof( DSBUFFERDESC ) ); bufferDesc.dwSize = (uint)sizeof( DSBUFFERDESC ); bufferDesc.dwFlags = DSound.DSBCAPS_CTRL3D | DSound.DSBCAPS_PRIMARYBUFFER; hr = IDirectSound8.CreateSoundBuffer( directSound, ref bufferDesc, out primaryBuffer, null ); if( Wrapper.FAILED( hr ) ) { Error( "CreateSoundBuffer", hr ); return false; } void*/*IDirectSound3DListener*/ listenerTemp = null; GUID guid = DSound.IID_IDirectSound3DListener; if( Wrapper.FAILED( hr = IDirectSoundBuffer.QueryInterface( primaryBuffer, ref guid, &listenerTemp ) ) ) { IDirectSoundBuffer.Release( primaryBuffer ); Error( "QueryInterface", hr ); return false; } listener = (IDirectSound3DListener*)listenerTemp; IDirectSoundBuffer.Release( primaryBuffer ); } //update general parameters { DS3DLISTENER parameters = new DS3DLISTENER(); parameters.dwSize = (uint)sizeof( DS3DLISTENER ); IDirectSound3DListener.GetAllParameters( listener, ref parameters ); parameters.flDistanceFactor = 1; parameters.flRolloffFactor = 0; parameters.flDopplerFactor = DopplerScale; hr = IDirectSound3DListener.SetAllParameters( listener, ref parameters, DSound.DS3D_IMMEDIATE ); if( Wrapper.FAILED( hr ) ) Warning( "IDirectSound3DListener.SetAllParameters", hr ); } GenerateRecordDriverList(); //Channels realChannels = new List<DirectSoundRealChannel>(); for( int n = 0; n < maxReal2DChannels; n++ ) { DirectSoundRealChannel realChannel = new DirectSoundRealChannel(); AddRealChannel( realChannel, false ); realChannels.Add( realChannel ); } for( int n = 0; n < maxReal3DChannels; n++ ) { DirectSoundRealChannel realChannel = new DirectSoundRealChannel(); AddRealChannel( realChannel, true ); realChannels.Add( realChannel ); } fileStreamRealChannels = new List<DirectSoundRealChannel>(); thread = new Thread( new ThreadStart( ThreadFunction ) ); thread.CurrentCulture = new System.Globalization.CultureInfo( "en-US" ); thread.IsBackground = true; thread.Start(); return true; }
public LazyResult(Func <TArg, T> valueFactory, TArg arg, LazyThreadSafetyMode lazyThreadSafetyMode, CriticalSection sync) : base(sync) { Validate.IsNotNull <Func <TArg, T> >(valueFactory, "valueFactory"); if (lazyThreadSafetyMode == LazyThreadSafetyMode.PublicationOnly) { throw new ArgumentException("LazyThreadSafetyMode.PublicationOnly is not supported", "lazyThreadSafetyMode"); } if ((lazyThreadSafetyMode != LazyThreadSafetyMode.None) && (lazyThreadSafetyMode != LazyThreadSafetyMode.ExecutionAndPublication)) { ExceptionUtil.ThrowInvalidEnumArgumentException <LazyThreadSafetyMode>(lazyThreadSafetyMode, "lazyThreadSafetyMode"); } base.valueFactory = valueFactory; this.arg = arg; base.lazyThreadSafetyMode = lazyThreadSafetyMode; this.value = default(T); this.errorData = null; }
unsafe protected override bool InitLibrary(IntPtr mainWindowHandle, int maxReal2DChannels, int maxReal3DChannels) { NativeLibraryManager.PreLoadLibrary("libogg"); NativeLibraryManager.PreLoadLibrary("libvorbis"); NativeLibraryManager.PreLoadLibrary("libvorbisfile"); NativeLibraryManager.PreLoadLibrary("DirectSoundNativeWrapper"); { DSoundStructureSizes sizes = new DSoundStructureSizes(); sizes.Init(); DSoundStructureSizes originalSizes; DSound.GetStructureSizes(out originalSizes); FieldInfo[] fields = sizes.GetType().GetFields( BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); foreach (FieldInfo field in fields) { int originalSize = (int)field.GetValue(originalSizes); int size = (int)field.GetValue(sizes); if (originalSize != size) { Log.Fatal("DirectXSoundSystem: Invalid unmanaged bridge. " + "Invalid \"{0}\". Native size = \"{1}\". Managed size = \"{2}\".", field.Name, originalSize, size); return(false); } } } instance = this; criticalSection = CriticalSection.Create(); DSound.CoInitialize(null); int hr; //create IDirectSound using the primary sound device void */*IDirectSound8*/ directSoundTemp; hr = DSound.DirectSoundCreate8(null, out directSoundTemp, null); if (Wrapper.FAILED(hr)) { if (hr == DSound.Get_DSERR_NODRIVER()) { Log.InvisibleInfo("DirectXSoundSystem: No sound driver."); return(false); } Error("DirectSoundCreate8", hr); return(false); } directSound = (IDirectSound8 *)directSoundTemp; //set DirectSound cooperative level hWnd = mainWindowHandle; hr = IDirectSound8.SetCooperativeLevel(directSound, hWnd, DSound.DSSCL_PRIORITY); if (Wrapper.FAILED(hr)) { Error("SetCooperativeLevel", hr); return(false); } //set primary buffer format { hr = SetPrimaryBufferFormat(2, 44100, 16, false); if (Wrapper.FAILED(hr)) { hr = SetPrimaryBufferFormat(2, 22050, 16, true); } if (Wrapper.FAILED(hr)) { return(false); } } //get listener { void */*IDirectSoundBuffer*/ primaryBuffer = null; // Obtain primary buffer, asking it for 3D control DSBUFFERDESC bufferDesc = new DSBUFFERDESC(); //ZeroMemory( &bufferDesc, sizeof( DSBUFFERDESC ) ); bufferDesc.dwSize = (uint)sizeof(DSBUFFERDESC); bufferDesc.dwFlags = DSound.DSBCAPS_CTRL3D | DSound.DSBCAPS_PRIMARYBUFFER; hr = IDirectSound8.CreateSoundBuffer(directSound, ref bufferDesc, out primaryBuffer, null); if (Wrapper.FAILED(hr)) { Error("CreateSoundBuffer", hr); return(false); } void */*IDirectSound3DListener*/ listenerTemp = null; GUID guid = DSound.IID_IDirectSound3DListener; if (Wrapper.FAILED(hr = IDirectSoundBuffer.QueryInterface(primaryBuffer, ref guid, &listenerTemp))) { IDirectSoundBuffer.Release(primaryBuffer); Error("QueryInterface", hr); return(false); } listener = (IDirectSound3DListener *)listenerTemp; IDirectSoundBuffer.Release(primaryBuffer); } //update general parameters { DS3DLISTENER parameters = new DS3DLISTENER(); parameters.dwSize = (uint)sizeof(DS3DLISTENER); IDirectSound3DListener.GetAllParameters(listener, ref parameters); parameters.flDistanceFactor = 1; parameters.flRolloffFactor = 0; parameters.flDopplerFactor = DopplerScale; hr = IDirectSound3DListener.SetAllParameters(listener, ref parameters, DSound.DS3D_IMMEDIATE); if (Wrapper.FAILED(hr)) { Warning("IDirectSound3DListener.SetAllParameters", hr); } } GenerateRecordDriverList(); //Channels realChannels = new List <DirectSoundRealChannel>(); for (int n = 0; n < maxReal2DChannels; n++) { DirectSoundRealChannel realChannel = new DirectSoundRealChannel(); AddRealChannel(realChannel, false); realChannels.Add(realChannel); } for (int n = 0; n < maxReal3DChannels; n++) { DirectSoundRealChannel realChannel = new DirectSoundRealChannel(); AddRealChannel(realChannel, true); realChannels.Add(realChannel); } fileStreamRealChannels = new List <DirectSoundRealChannel>(); thread = new Thread(new ThreadStart(ThreadFunction)); thread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); thread.IsBackground = true; thread.Start(); return(true); }
protected override void ShutdownLibrary() { if( thread != null ) { needAbortThread = true; Thread.Sleep( 50 ); thread.Abort(); } if( realChannels != null ) { foreach( OpenALRealChannel realChannel in realChannels ) { if( realChannel.alSource != 0 ) { Al.alDeleteSources( 1, ref realChannel.alSource ); realChannel.alSource = 0; } } } try { Alc.alcMakeContextCurrent( IntPtr.Zero ); Alc.alcDestroyContext( alContext ); Alc.alcCloseDevice( alDevice ); } catch { } if( realChannels != null ) { realChannels.Clear(); realChannels = null; } if( criticalSection != null ) { criticalSection.Dispose(); criticalSection = null; } instance = null; }
unsafe protected override void ShutdownLibrary() { if( thread != null ) { needAbortThread = true; Thread.Sleep( 50 ); thread.Abort(); } if( realChannels != null ) { realChannels.Clear(); realChannels = null; } if( directSound != null ) { IDirectSound8.Release( directSound ); directSound = null; } if( criticalSection != null ) { criticalSection.Dispose(); criticalSection = null; } instance = null; }