public override void TryParse(TFunction caller, bool forFlag) { ReturnBubble = null; ReturnFlag = false; if (caller != null) { BlindExecute = caller.BlindExecute; Tracer = caller.Tracer; Caller = caller; Extensions = caller.Extensions; } if (caller != null && caller.Arguments != null && ExpectedArgs != null && ExpectedArgs.Length > 0) { ProvidedArgs = new TokenStack(); var args = caller.ReturnArgsArray(); if (args.Length > 0) { if (args.Length > ExpectedArgs.Length) { Compiler.ExceptionListener.Throw($"The arguments supplied do not match the arguments expected!"); return; } for (var i = 0; i < args.Length; i++) { var exp = ExpectedArgs[i].Replace("var ", "").Replace(" ", ""); ProvidedArgs.Add(new Token(exp, args[i], caller.Line)); } } } Parse(); }
// Helper to send items to the listener, and return what they collected private object[] Run <TFunction>(params FakeQueueData[] items) where TFunction : FunctionsBase, new() { var activator = new FakeActivator(); var func1 = new TFunction(); activator.Add(func1); JobHostConfiguration config = new JobHostConfiguration() { TypeLocator = new FakeTypeLocator(typeof(TFunction)), JobActivator = activator }; FakeQueueClient client = new FakeQueueClient(); IExtensionRegistry extensions = config.GetService <IExtensionRegistry>(); extensions.RegisterExtension <IExtensionConfigProvider>(client); JobHost host = new JobHost(config); foreach (var item in items) { client.AddAsync(item).Wait(); } host.Start(); TestHelpers.WaitOne(func1._stopEvent); host.Stop(); return(func1._collected.ToArray()); }
// Helper to send items to the listener, and return what they collected private object[] Run <TFunction>(params FakeQueueData[] items) where TFunction : FunctionsBase, new() { var activator = new FakeActivator(); var func1 = new TFunction(); activator.Add(func1); FakeQueueClient client = new FakeQueueClient(); var host = TestHelpers.NewJobHost <TFunction>(client, activator); foreach (var item in items) { client.AddAsync(item).Wait(); } host.Start(); TestHelpers.WaitOne(func1._stopEvent); host.Stop(); // Add any items sent using [FakeQueue(Prefix=...)] foreach (var kv in client._prefixedItems) { func1._collected.AddRange(kv.Value); } return(func1._collected.ToArray()); }
public static void RunRegexParser(string pattern, params string[] tests) { var regex = new RegularExpression(pattern); if (!regex.IsValid) { Console.WriteLine($"{pattern} Is invalid."); } else { Console.WriteLine($"Pattern ({pattern}): {regex}"); Console.WriteLine("\nNFA:"); Console.WriteLine(regex.NFA); Console.WriteLine("\nDFA:"); var dm = new TFunction(regex.NFA).ConstructDFA(); dm.Rename(); Console.WriteLine(dm); Console.WriteLine("\nMinimized DFA:"); var diff = dm.GetDistinguishableElements(); var minimized = dm.Minimize(diff); minimized.Rename(); Console.WriteLine(minimized); Console.WriteLine("\nInput Tests:"); foreach (var test in tests) { minimized.Run(test); } } }
public static void DemoNFA(string file, params string[] tests) { Console.WriteLine(file); Console.WriteLine("NFA:"); var m = MachineUtilities.ParseFileToNFA(file); Console.WriteLine(m); Console.WriteLine("\nλ-Closure & t-Table:"); var tTrans = new TFunction(m); Console.WriteLine(tTrans); Console.WriteLine("\nDFA:"); var mDFA = tTrans.ConstructDFA(); Console.WriteLine(mDFA); Console.WriteLine("\nRenamed:"); mDFA.Rename(); Console.WriteLine(mDFA); Console.WriteLine("\nMinimized:"); var diff = mDFA.GetDistinguishableElements(); var minimized = mDFA.Minimize(diff); Console.WriteLine(minimized); Console.WriteLine("\nInput Tests:"); foreach (var test in tests) { minimized.Run(test); } }
/// <summary> /// Override this method if you do not want to include it as a function. /// Overriding this must contain {TryParse(args,true)} or you won't get anywhere! /// </summary> /// <param name="args"></param> /// <param name="findFor"></param> protected virtual void ForExtension(TFunction caller, ExtensionFor findFor) { this.IsLoop = true; string[] forNumber = findFor.Extend(); int forNumberAsNumber = int.Parse(forNumber[0]); var tracer = new LoopTracer(); Compiler.LoopTracerStack.Add(tracer); if (forNumberAsNumber <= 0) { forNumberAsNumber = int.MaxValue; } for (var x = 0; x < forNumberAsNumber; x++) { if (!TokenParser.Stop) { if (tracer.Break) { break; } if (tracer.Continue) { tracer.SetContinue(false);//reset continue } caller.SetTracer(tracer); TryParse(caller, true); } else { break; } } Compiler.LoopTracerStack.Remove(tracer); tracer = null; }
public static void Sleep(double ms, TFunction caller) { var sleep = FunctionStack.First("Sleep"); var func = new TFunction(sleep, new List <EDefinition>(), ms.ToString(), caller.CallingFunction); sleep.TryParse(func); //Utilities.Sleep((int)ms); }
/// <inheritdoc /> protected IReverseWrapper <TFunction> CreateReverseWrapper(TFunction function) { if (_is64Bit) { return(new X64.ReverseWrapper <TFunction>(function)); } return(new X86.ReverseWrapper <TFunction>(function)); }
public static void AnalyzeScreen(string success, IBaseFunction successAction, IBaseFunction failureAction, string[] prop, TFunction caller = null) { var tfunc = new TFunction(caller.Function, new List <EDefinition>(), string.Join(",", caller.Function.GetInvokeProperties()), caller.CallingFunction); try { bool finished = false; bool func = false; Thread th = new Thread(() => { AnalyzeScreen ascreen = new AnalyzeScreen(); ascreen.Analyze(success.UnCleanString(), () => { finished = true; func = true; }, () => { finished = true; }, prop ); }); th.Start(); Stopwatch watch = new Stopwatch(); watch.Start(); while (finished == false) { if (TokenParser.Stop) { break; } Thread.Sleep(1000); //sleep for 1 second before checking again //if 30 seconds go by, then break and kill the thread if (watch.Elapsed.TotalMilliseconds >= 45000) { Compiler.ExceptionListener.ThrowSilent(new ExceptionHandler(ExceptionType.SystemException, $"CheckScreen() timed out.")); //smash the thread and move on. we dont care about that data anyway try { th.Abort(); } catch (Exception e) { if (!(e is ThreadAbortException)) { throw; } } break; } } watch.Stop(); if (func) { successAction.TryParse(tfunc); } else { failureAction.TryParse(tfunc); } } catch { Compiler.ExceptionListener.ThrowSilent(new ExceptionHandler("[63]Image check failed to execute. Continuing with failure function")); failureAction.TryParse(tfunc); } }
FunctionAdapter(MethodInfo function, TFunction funtionType, TValue returnType, TValue maxParamType, int paramCountMin, int paramCountMax) { mFunction = function; mFunctionType = funtionType; mReturnType = returnType; mMaxParamType = maxParamType; mParamCountMin = paramCountMin; mParamCountMax = paramCountMax; mParamList = new object[1]; }
/// <inheritdoc /> public TFunction GetWrapper() { if (!_wrapperCreated) { _wrapper = Hooks.CreateWrapper <TFunction>(Address, out var wrapperAddress); _wrapperAddress = wrapperAddress.ToUnsigned(); _wrapperCreated = true; } return(_wrapper); }
/// <summary> /// Gets the sequence of assembly instructions required to assemble an absolute call to a C# function address. /// </summary> /// <param name="function">The C# function to create a jump to.</param> /// <param name="reverseWrapper"> /// The native reverse wrapper used to call your function. /// Please keep a reference to this class as long as you are using the generated code. /// i.e. make it a class/struct member on heap. /// </param> public static string GetAbsoluteCallMnemonics < #if NET5_0_OR_GREATER [DynamicallyAccessedMembers(Trimming.ReloadedAttributeTypes)] #endif TFunction>(TFunction function, out IReverseWrapper <TFunction> reverseWrapper) where TFunction : Delegate { var hooks = ReloadedHooks.Instance; reverseWrapper = hooks.CreateReverseWrapper <TFunction>(function); return(GetAbsoluteCallMnemonics(reverseWrapper.WrapperPointer.ToUnsigned(), IntPtr.Size == 8)); }
public static IEnumerator genericT(TFunction tfunc, float dur) { float startTime = Time.time; while (Time.time < startTime + dur) { float t = Mathf.Clamp01((Time.time - startTime) / dur); tfunc(t); yield return(0); } //force call with 1 tfunc(1); }
public unsafe IReverseWrapper <TFunction> CreateReverseWrapper < #if NET5_0_OR_GREATER [DynamicallyAccessedMembers(Trimming.ReloadedAttributeTypes)] #endif TFunction>(TFunction function) { if (sizeof(IntPtr) == 4) { return(new X86.ReverseWrapper <TFunction>(function)); } return(new X64.ReverseWrapper <TFunction>(function)); }
/// <summary> /// Hooks an individual vtable function pointer from a already hooked vtable pointer. /// </summary> /// <param name="vTableHook">The already hooked virtual function table</param> /// <param name="originalVirtualFunctionTableAddress">The address of the original virtual function pointer /// This will be read to store the original function pointer</param> /// <param name="index">The index of the virtual function pointer in the virtual function table</param> /// <param name="function">The hook function</param> internal unsafe VTableEntryHook(HookedObjectVirtualFunctionTable vTableHook, nuint originalVirtualFunctionTableAddress, int index, TFunction function) { CurrentProcess.SafeRead(originalVirtualFunctionTableAddress + (nuint)(index * sizeof(nuint)), out nuint originalFunctionAddress); _vTableHook = vTableHook; _index = index; _is64Bit = sizeof(IntPtr) == 8; ReverseWrapper = CreateReverseWrapper(function); OriginalFunction = CreateWrapper(originalFunctionAddress, out nuint originalFunctionWrapperAddress); OriginalFunctionAddress = originalFunctionAddress.ToSigned(); OriginalFunctionWrapperAddress = originalFunctionWrapperAddress.ToSigned(); IsHookActivated = false; }
public virtual void TryParse(TFunction caller) { ReturnBubble = null; ReturnFlag = false; if (caller != null) { BlindExecute = caller.BlindExecute; Tracer = caller.Tracer; Caller = caller; } var findFor = Extensions.FirstOrDefault(f => f.Name == "For") as ExtensionFor; if (findFor != null) { //if for extension exists, reroutes this tryparse method to the loop version without the for check ForExtension(caller, findFor); return; } //combine expected args and given args and add them to variabel pool if (caller != null && caller.Arguments != null && ExpectedArgs != null && ExpectedArgs.Length > 0) { ProvidedArgs = new TokenStack(); var args = caller.ReturnArgsArray(); if (ExpectedArgs.Length > 0) { for (var i = 0; i < ExpectedArgs.Length; i++) { var exp = ExpectedArgs[i].Replace("var ", "").Replace(" ", ""); if (args.ElementAtOrDefault(i) == null) { ProvidedArgs.Add(new Token(exp, "null", caller.Line)); } else { ProvidedArgs.Add(new Token(exp, args[i], caller.Line)); } } } } var guts = Value.Split('{')[1].Split('}'); var lines = guts[0].Split(';'); foreach (var l in lines) { new Line(l, this); } //clear local var stack after use LocalVariables = new TokenStack(); }
FunctionAdapter(MethodInfo function, TValue returnType, List <TValue> paramList) { mFunction = function; mFunctionType = TFunction.Fixed; mReturnType = returnType; mParamTypes = paramList; if (ParamCount > 0) { mParamList = new object[ParamCount]; } else { paramList = null; } }
public static IEnumerator genericT(TFunction tfunc, float dur) { float timer = 0; while (timer < dur) { float t = Mathf.Clamp01(timer / dur); tfunc(t); yield return(new WaitForEndOfFrame()); timer += Time.deltaTime; } //force call with 1 tfunc(1); }
private Token Parse(TFunction t) { if (!_reference.ReturnFlag) { if (!TokenParser.Stop) { if (_reference.Tracer == null || (!_reference.Tracer.Continue && !_reference.Tracer.Break)) { return(TryParseMember(t)); } } else if (TokenParser.Stop && _reference.BlindExecute) { return(TryParseMember(t)); } } return(null); }
/// <summary> /// Creates a wrapper function with a custom calling convention which calls the supplied function. /// </summary> /// <remarks> /// Please keep a reference to this class as long as you are using it (if <typeparamref name="TFunction"/> is a delegate type). /// Otherwise Garbage Collection will break the native function pointer to your C# function /// resulting in a spectacular crash if it is still used anywhere. /// </remarks> /// <param name="function">The function to create a pointer to.</param> public ReverseWrapper(TFunction function) { CSharpFunction = function; if (typeof(TFunction).IsValueType && !typeof(TFunction).IsPrimitive) { NativeFunctionPtr = Unsafe.As <TFunction, IntPtr>(ref function); } else { NativeFunctionPtr = Marshal.GetFunctionPointerForDelegate(function); } WrapperPointer = NativeFunctionPtr; // Call above may or may not replace WrapperPointer. Create(this, NativeFunctionPtr.ToUnsigned()); }
public static IEnumerator genericT(TFunction tfunc, float dur, float delay) { yield return(new WaitForSeconds(delay)); //float startTime = Time.time; float counter = 0; while (counter < dur) { float t = Mathf.Clamp01(counter / dur); tfunc(t); yield return(new WaitForEndOfFrame()); counter += Time.deltaTime; } //force call with 1 tfunc(1); }
private Token TryParseMember(TFunction t) { if (t == null) { return(null); } if (_reference.BlindExecute) { t.BlindExecute = true; } if (t.Name == "Base") { var b = _reference.Base; b.Extensions = new List <EDefinition>(); if (t.Extensions != null) { b.Extensions = t.Extensions; } if (t.Function.BlindExecute) { b.BlindExecute = true; } b.TryParse(t); return(b.ReturnBubble); } //change this plz if (t.Name == _reference.Name) { Compiler.ExceptionListener.Throw("Cannot call function from itself. Please use `Base()` if this is an override." , ExceptionType.SystemException); return(null); } var z = t.Function; if (t.Extensions != null) { z.Extensions = t.Extensions; } z.TryParse(t); return(z.ReturnBubble); }
//this overload is when the function is called with the for extension public virtual void TryParse(TFunction caller, bool forFlag) { ReturnBubble = null; ReturnFlag = false; if (caller != null) { BlindExecute = caller.BlindExecute; Tracer = caller.Tracer; Caller = caller; } //combine expected args and given args and add them to variabel pool if (caller != null && caller.Arguments != null && ExpectedArgs != null && ExpectedArgs.Length > 0) { ProvidedArgs = new TokenStack(); var args = caller.ReturnArgsArray(); if (ExpectedArgs.Length > 0) { for (var i = 0; i < ExpectedArgs.Length; i++) { var exp = ExpectedArgs[i].Replace("var ", "").Replace(" ", ""); if (args.ElementAtOrDefault(i) == null) { ProvidedArgs.Add(new Token(exp, "null", caller.Line)); } else { ProvidedArgs.Add(new Token(exp, args[i], caller.Line)); } } } } var guts = Value.Split('{')[1].Split('}'); var lines = guts[0].Split(';'); foreach (var l in lines) { new Line(l, this); } //clear local var stack after use LocalVariables = new TokenStack(); }
public override void TryParse(TFunction caller) { ReturnBubble = null; ReturnFlag = false; if (caller != null) { BlindExecute = caller.BlindExecute; Tracer = caller.Tracer; Caller = caller; Extensions = caller.Extensions; } var findFor = Extensions.FirstOrDefault(f => f.Name == "For") as ExtensionFor; if (findFor != null) { //if for extension exists, reroutes this tryparse method to the loop version without the for check ForExtension(caller, findFor); return; } if (caller != null && caller.Arguments != null && ExpectedArgs != null && ExpectedArgs.Length > 0) { ProvidedArgs = new TokenStack(); var args = caller.ReturnArgsArray(); if (args.Length > 0) { if (args.Length > ExpectedArgs.Length) { Compiler.ExceptionListener.Throw($"The arguments supplied do not match the arguments expected!"); return; } for (var i = 0; i < args.Length; i++) { var exp = ExpectedArgs[i].Replace("var ", "").Replace(" ", ""); ProvidedArgs.Add(new Token(exp, args[i], caller.Line)); } } } Parse(); }
public static IEnumerator genericT(TFunction tfunc1, float dur1, TFunction tfunc2, float dur2) { float startTime = Time.time; while (Time.time < startTime + dur1) { float t = Mathf.Clamp01((Time.time - startTime) / dur1); tfunc1(t); yield return(new WaitForEndOfFrame()); } //force call with 1 tfunc1(1); startTime = Time.time; while (Time.time < startTime + dur2) { float t = Mathf.Clamp01((Time.time - startTime) / dur2); tfunc2(t); yield return(new WaitForEndOfFrame()); } //force call with 1 tfunc2(1); }
public static void Test() { //var file = "./demos/NFA/HW5_40"; //var file = "./demos/NFA/Exam4"; //var file = "./demos/NFA/HW5_36"; /*var m = MachineUtilities.ParseFileToNFA(file); * var m2 = NFA.KleeneStar(m); * * Console.WriteLine("\n" + m); * Console.WriteLine("\n" + m2);*/ var alph = "abcde".ToCharArray(); var m = NFA.GenerateFromSet("abc", alph); var m2 = NFA.GenerateFromString("abc", alph); Console.WriteLine(m + "\n"); Console.WriteLine(m2 + "\n"); var m3 = NFA.Plus(m); Console.WriteLine(m3 + "\n"); var m4 = NFA.Plus(m2); Console.WriteLine(m4 + "\n"); var dm1 = new TFunction(m3).ConstructDFA(); Console.WriteLine(dm1 + "\n"); var dm1m = dm1.Minimize(dm1.GetDistinguishableElements()); dm1m.Rename(); Console.WriteLine(dm1m + "\n"); }
private void TryParseMember(TFunction t) { //this was moved to Line.cs }
protected override void ForExtension(TFunction caller, ExtensionFor findFor) { Compiler.ExceptionListener.Throw(new ExceptionHandler(ExceptionType.CompilerException, $"Cannot call 'For' on {this.Name}.", LineValue)); }
/// <inheritdoc /> public IHook <TFunction> Hook(TFunction function) => Hook(function, -1);
/// <inheritdoc /> public IHook <TFunction> Hook(TFunction function, int minHookLength) => Hooks.CreateHook(function, Address, minHookLength);