private void LoadSharedScripts(V8ScriptEngine context, bool precompileOnly) { if (SharedScripts == null) { return; } foreach (var script in SharedScripts) { try { if (precompileOnly) { context.Compile(script.Content, V8CacheKind.Code, out byte[] cache); script.CompiledCache = cache; } else { V8Script v8Script = context.Compile(script.Content, V8CacheKind.Code, script.CompiledCache, out bool accepted); context.Execute(v8Script); } } catch (Exception ex) { logger.ErrorFormat("Script: Shared script failed to run. {0}. {1}", script.Name, ex.Message); throw; } } }
static void ProcessScript(String sFunc, String sHdrFile, String sDtlFile) { String sFileResult = Path.GetFileNameWithoutExtension(sDtlFile) + "-result.js"; String sHdrScript = File.ReadAllText(sHdrFile); String sRScript = File.ReadAllText(sDtlFile); V8ScriptEngine v8 = new V8ScriptEngine(); V8Script myScript = v8.Compile(sHdrScript); v8.Execute(myScript); String sRegex = "(" + sFunc + @"\(\'0[xX][0-9A-Fa-f]+\'\))"; MatchCollection arMatches = Regex.Matches(sRScript, sRegex); int nI; String sMatchVal, sRes; for (nI = 0; nI < arMatches.Count; nI++) { sMatchVal = arMatches[nI].Value; Console.WriteLine("Processing " + sMatchVal + " ..."); sRes = v8.ExecuteCommand(sMatchVal); sRScript = sRScript.Replace(arMatches[nI].Value, "\"" + sRes + "\""); } v8.Dispose(); File.WriteAllText(sFileResult, sRScript); return; }
/// <summary> /// Assumes layout has been already applied /// Note: method mutates graph and graphLayout /// </summary> public void ImproveAppliedLayout(SigmaGraphModel graph, GraphLayout graphLayout, LayoutSettings layoutSettings, TimeSpan duration) { using (var engine = new V8ScriptEngine()) { try { var v8Graph = new V8GraphModel(); v8Graph.LoadSigma(graph); engine.AddHostObject("log", _log); engine.Execute("var graph = " + JsonConvention.SerializeObject(v8Graph) + ";"); engine.Execute("var settings = " + JsonConvention.SerializeObject(layoutSettings) + ";"); engine.Execute("var duration = " + JsonConvention.SerializeObject(duration.TotalMilliseconds) + ";"); var baseDirectory = AppDomain.CurrentDomain.BaseDirectory; var forceAtlas2 = engine.Compile(File.ReadAllText($@"{baseDirectory}\App\Graph\Layout\ForceAtlas2.js")); var serviceScript = engine.Compile(File.ReadAllText($@"{baseDirectory}\App\Graph\Layout\GraphLayoutService.js")); engine.Execute(forceAtlas2); engine.Execute(serviceScript); var nodesJson = engine.Evaluate("JSON.stringify(nodes)").ToString(); var nodes = JsonConvention.DeserializeObject <V8NodeModel[]>(nodesJson); for (int i = 0; i < nodes.Length; i++) { var node = graph.Nodes[i]; node.X = nodes[i].x; node.Y = nodes[i].y; var id = node.Entity; if (id.HasValue) { graphLayout[id.Value] = new GraphLayout.Coords() { X = nodes[i].x, Y = nodes[i].y }; } } } catch (ScriptEngineException e) { _log.Error("V8 exception: " + e.ErrorDetails); throw; } } }
public void BugFix_V8CompiledScriptDispose() { V8Script script1; using (var tempEngine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDebugging)) { script1 = tempEngine.Compile("(function () { return 123; })()"); Assert.AreEqual(123, tempEngine.Evaluate(script1)); V8Script script2 = tempEngine.Compile("(function () { return 456; })()"); using (script2) { Assert.AreEqual(456, tempEngine.Evaluate(script2)); } } using (script1) { } }
public void BugFix_Resurrection_V8Script() { for (var index = 0; index < 256; index++) { // ReSharper disable UnusedVariable var tempEngine = new V8ScriptEngine(); var wrapper = new ResurrectionTestWrapper(tempEngine.Compile("function foo() {}")); GC.Collect(); // ReSharper restore UnusedVariable } }
public void BugFix_V8CompiledScriptWeakBinding() { // This test verifies that V8 compiled scripts no longer prevent their isolates from // being destroyed. Previously it exhausted address space and crashed in 32-bit mode. for (var i = 0; i < 128; i++) { using (var tempEngine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDebugging)) { tempEngine.Compile("(function () {}).valueOf()"); } } }
public static object RunJS_V8() { using (var engine = new V8ScriptEngine()) { var f = "test.js"; var code = File.ReadAllText(f); engine.Compile(code); engine.AddHostType("Console", typeof(Console)); engine.Execute("Console.WriteLine('{0} is an interesting number.', Math.PI)"); engine.AddHostType("Console", typeof(Console)); engine.Evaluate("Console.debug('faasfafa')"); var res = engine.Evaluate("test(fsfs)"); Console.WriteLine(res); } return(null); }
internal void Init() { Dispose(); V8ScriptEngineFlags flags = V8ScriptEngineFlags.None; #if DEBUG flags |= V8ScriptEngineFlags.EnableDebugging; flags |= V8ScriptEngineFlags.EnableRemoteDebugging; #endif scriptEngine = new V8ScriptEngine(flags); loadedScripts = new HashSet <string>(); scriptEngine.AddHostObject("Engine", new GameEngineProxy(this)); LoadScript("src/Init.js"); scriptEngine.Execute("Init()"); executeScript = scriptEngine.Compile("Execute(Engine.Input);"); }
private void compileScript(string src, Dictionary <string, object> hostObjects = null) { Ok = false; engine = new V8ScriptEngine(); code = engine.Compile(src); if (hostObjects != null) { foreach (var kvp in hostObjects) { engine.AddHostObject(kvp.Key, kvp.Value); } } engine.Execute(code); Ok = true; }
public string[] ValidateTemplate(string code) { using var engine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDynamicModuleImports); try { engine.Compile(new DocumentInfo("main") { Category = ModuleCategory.Standard }, code); return(Array.Empty <string>()); } catch (ScriptEngineException e) { return(new[] { e.ErrorDetails }); } }
static void Testing() { Console.WriteLine("Testing Here"); V8ScriptEngine v8 = new V8ScriptEngine(); String sScript = File.ReadAllText("header.js"); String sRScript = File.ReadAllText("detail.js"); String sFunc = "_0xfec0"; //Console.WriteLine(sScript); V8Script myScript = v8.Compile(sScript); v8.Execute(myScript); //find certain pattern in the String sTest = v8.ExecuteCommand("_0xfec0('0x0')"); Console.WriteLine("OK " + sTest); sTest = v8.ExecuteCommand("_0xfec0('0x1')"); Console.WriteLine("OK " + sTest); sTest = v8.ExecuteCommand("_0xfec0('0x2')"); Console.WriteLine("OK " + sTest); v8.Dispose(); }
/// <summary> /// Executes a script in context of a discord reply /// </summary> /// <param name="scriptName">The name of the action that executes this script.</param> /// <param name="script">The script source code</param> /// <param name="c">CommandContext of the issued discord command</param> /// <param name="player">Player object of the user that issues the command</param> /// <param name="m">The message that the bot sent as a reply</param> /// <returns></returns> public static async Task RunDiscordScriptAsync(string scriptName, string script, CommandContext c, Player player, DiscordMessage m) { await Task.Run(() => { using (var engine = new V8ScriptEngine()) { if (engine.Compile(script, V8CacheKind.Parser, out byte[] cacheBytes) == null) { c.RespondAsync($"A exception occured while compiling the {scriptName} action script."); return; } using (var compiled = engine.Compile(script, V8CacheKind.Parser, cacheBytes, out bool cacheAccepted)) { if (cacheAccepted) { Log.Debug("Using script cache for {scriptname}", scriptName); } engine.AddHostObject("Realm", new ScriptContext(player, c, m)); engine.AddHostType(typeof(DiscordMessage)); engine.AddHostType(typeof(CommandContext)); engine.AddHostType(typeof(DiscordEmoji)); engine.AddHostObject("Discord", new HostTypeCollection("DSharpPlus", "DSharpPlus.CommandsNext", "DSharpPlus.Interactivity")); try { engine.Execute(compiled); } catch (ScriptEngineException e) { Log.Error(e, "Scripting Exception"); c.RespondAsync($"A exception occured while running the {scriptName} action script: {e.Message}"); } } }
public override float[][] Do(float[][] buffer) { // TODO: ステレオの両方のチャンネルに対して処理する using (var engine = new V8ScriptEngine()) { int BLOCK_SIZE = 8192; engine.Execute("__mapper = (" + ExpressionCode + ")"); // アルファベットにエンコードすることにより更に約4倍の高速化 var code1 = engine.Compile( "(function(){" + #if EXPRESSION_USE_ENCODING_IN "var __byteArray = new Array(__inputStr.length / 2);\n" + "for(__i = 0; __i < __inputStr.length / 8; __i++) {\n" + " __byteArray[__i * 4 + 3] = (__inputStr.charCodeAt(__i * 8 + 0) - 65) * 16 + (__inputStr.charCodeAt(__i * 8 + 1) - 65);\n" + " __byteArray[__i * 4 + 2] = (__inputStr.charCodeAt(__i * 8 + 2) - 65) * 16 + (__inputStr.charCodeAt(__i * 8 + 3) - 65);\n" + " __byteArray[__i * 4 + 1] = (__inputStr.charCodeAt(__i * 8 + 4) - 65) * 16 + (__inputStr.charCodeAt(__i * 8 + 5) - 65);\n" + " __byteArray[__i * 4 + 0] = (__inputStr.charCodeAt(__i * 8 + 6) - 65) * 16 + (__inputStr.charCodeAt(__i * 8 + 7) - 65);\n" + "}\n" + "var __inputArray = new Float32Array((new Uint8Array(__byteArray)).buffer);\n" + #endif "var __result = new Array(__inputArray.length);\n" + "for(__j=0;__j<__inputArray.length;__j++){__result[__j]=__mapper(__inputArray[__j]);}\n" + #if EXPRESSION_USE_ENCODING_OUT "__byteArray = new Uint8Array((new Float32Array(__result)).buffer);\n" + "var __outputStr = \"\";\n" + "for(__i = 0; __i < __result.length; __i++) {\n" + " __outputStr += String.fromCharCode(((__byteArray[__i * 4 + 3] >> 4) & 0x0F) + 65);\n" + " __outputStr += String.fromCharCode(((__byteArray[__i * 4 + 3] ) & 0x0F) + 65);\n" + " __outputStr += String.fromCharCode(((__byteArray[__i * 4 + 2] >> 4) & 0x0F) + 65);\n" + " __outputStr += String.fromCharCode(((__byteArray[__i * 4 + 2] ) & 0x0F) + 65);\n" + " __outputStr += String.fromCharCode(((__byteArray[__i * 4 + 1] >> 4) & 0x0F) + 65);\n" + " __outputStr += String.fromCharCode(((__byteArray[__i * 4 + 1] ) & 0x0F) + 65);\n" + " __outputStr += String.fromCharCode(((__byteArray[__i * 4 + 0] >> 4) & 0x0F) + 65);\n" + " __outputStr += String.fromCharCode(((__byteArray[__i * 4 + 0] ) & 0x0F) + 65);\n" + "}\n" + "return __outputStr;\n" + #else "return __result.join(',');\n" + #endif "})()" ); List <float[]> ret = new List <float[]>(); foreach (var channelOfBuffer in buffer) { List <float> wholeResult = new List <float>(); for (int blockId = 0; blockId < (channelOfBuffer.Length - 1) / BLOCK_SIZE + 1; blockId++) { int fromInclusive = BLOCK_SIZE * blockId; int toExclusive = Math.Min(BLOCK_SIZE * (blockId + 1), channelOfBuffer.Length); var s = new StringBuilder(); #if EXPRESSION_USE_ENCODING_IN s.Append("__inputStr = \""); var charbuf = new byte[(toExclusive - fromInclusive) * 8]; for (int i = 0, i4 = 0, i8 = 0; i < toExclusive - fromInclusive; i++, i4 += 4, i8 += 8) { var x = channelOfBuffer[i + fromInclusive]; var floatbits = BitConverter.GetBytes(x); charbuf[i8 + 0] = (byte)(((floatbits[3] >> 4) & 0x0F) + 65); charbuf[i8 + 1] = (byte)(((floatbits[3] >> 0) & 0x0F) + 65); charbuf[i8 + 2] = (byte)(((floatbits[2] >> 4) & 0x0F) + 65); charbuf[i8 + 3] = (byte)(((floatbits[2] >> 0) & 0x0F) + 65); charbuf[i8 + 4] = (byte)(((floatbits[1] >> 4) & 0x0F) + 65); charbuf[i8 + 5] = (byte)(((floatbits[1] >> 0) & 0x0F) + 65); charbuf[i8 + 6] = (byte)(((floatbits[0] >> 4) & 0x0F) + 65); charbuf[i8 + 7] = (byte)(((floatbits[0] >> 0) & 0x0F) + 65); } s.Append(Encoding.ASCII.GetString(charbuf)); s.Append("\";"); #else s.Append("__inputArray = ["); // 配列ではなく文字列に変換して渡すことにより大幅に高速化 s.Append(string.Join(",", Enumerable.Range(fromInclusive, toExclusive - fromInclusive).Select(i => { var x = channelOfBuffer[i]; if (float.IsNaN(x)) { return("NaN"); } // ここいる?? else if (float.IsNegativeInfinity(x)) { return("-Infinity"); } else if (float.IsPositiveInfinity(x)) { return("Infinity"); } return(x.ToString()); }))); s.Append("];"); #endif // コンパイルしてもコンパイルしなくてもほとんど同じ時間でした engine.Execute(engine.Compile(s.ToString())); dynamic result = engine.Evaluate(code1); #if EXPRESSION_USE_ENCODING_OUT string result_s = (string)result; float[] result3 = new float[toExclusive - fromInclusive]; for (int i = 0; i < toExclusive - fromInclusive; i++) { result3[i] = BitConverter.ToSingle(new byte[] { (byte)((result_s[i * 8 + 6] - 65) * 16 + (result_s[i * 8 + 7] - 65)), (byte)((result_s[i * 8 + 4] - 65) * 16 + (result_s[i * 8 + 5] - 65)), (byte)((result_s[i * 8 + 2] - 65) * 16 + (result_s[i * 8 + 3] - 65)), (byte)((result_s[i * 8 + 0] - 65) * 16 + (result_s[i * 8 + 1] - 65)), }, 0); } #else float[] result3 = ((string)result).Split(',').Select(x => { if (x == "Infinity") { return(float.PositiveInfinity); } if (x == "-Infinity") { return(float.NegativeInfinity); } if (x == "NaN") { return(float.NaN); } // NaNやInfinityは残さない方が良い気もします・・・ return(float.Parse(x)); }).ToArray(); #endif wholeResult.AddRange(result3); } ret.Add(wholeResult.ToArray()); } return(ret.ToArray()); } }
public void Execute(Script script) { script.SetExecutionEnvironment(this); _engine.AddHostObject("script", script); _engine.AddHostObject("world", ActiveWorld.Active.World); _engine.AddHostObject("sky", ActiveWorld.Active.Sky); _engine.AddHostObject("camera", ActiveWorld.Active.Camera); _engine.Script.print = new Action <Object>(print); _engine.Script.spawn = new Action <Object>(spawn); _engine.Script.delay = new Action <Object, double>(delay); _engine.Script.loop = new Action <Object, double>(loop); _engine.Script.forLoop = new Action <Object, int, double>(forLoop); _engine.Script.onRenderStep = new Action <Object>(onRenderStep); _engine.Script.onStep = new Action <Object>(onStep); _engine.Script.onKeyPress = new Action <int, Object>(onKeyPress); _engine.Script.onKeyDown = new Action <int, Object>(onKeyDown); _engine.Script.onKeyUp = new Action <int, Object>(onKeyUp); _engine.AddHostType(HostItemFlags.DirectAccess, typeof(Math)); _engine.AddHostType(HostItemFlags.DirectAccess, typeof(Noise)); _engine.AddHostType(HostItemFlags.DirectAccess, typeof(Random)); _engine.AddHostType(HostItemFlags.DirectAccess, typeof(Key)); _engine.AddHostType(HostItemFlags.DirectAccess, typeof(Camera)); _engine.AddHostType(HostItemFlags.DirectAccess, typeof(Part)); _engine.AddHostType(HostItemFlags.DirectAccess, typeof(Script)); _engine.AddHostType(HostItemFlags.DirectAccess, typeof(Sky)); _engine.AddHostType(HostItemFlags.DirectAccess, typeof(World)); _engine.AddHostType(HostItemFlags.DirectAccess, typeof(Vector3)); _engine.AddHostType(HostItemFlags.DirectAccess, typeof(Rotation)); //Allow for reflection on Instance types to access higher concrete implementation properties _engine.DisableTypeRestriction = true; _engine.AllowReflection = true; _engine.SuppressExtensionMethodEnumeration = false; _engine.UseReflectionBindFallback = true; _engine.DefaultAccess = ScriptAccess.None; try { V8Script v8Script = _engine.Compile((script.source != null) ? script.source : String.Empty); _engine.Execute(v8Script); } catch (ScriptEngineException e) { String errorDetails = e.ErrorDetails; Match errDetailsMatch = Regex.Match(errorDetails, @"'(?<type>Flex\..*)'"); if (errDetailsMatch.Success) { Match match = Regex.Match(errorDetails, @"'Flex\..*.\.(?<class>.+)'"); if (match.Success) { errorDetails = errorDetails.Replace(errDetailsMatch.Groups["type"].Value, match.Groups["class"].Value); } } _output.AppendLine(errorDetails); } catch (Exception e) { _output.AppendLine("[external error] " + e.Message); } }
public V8Script CompileScript(string codeScript) { V8Script result = m_scriptEngine.Compile(m_currentScriptName, codeScript); return(result); }
// Simple engine functions public V8Script Compile(string file, string code) => _engine.Compile(new DocumentInfo(new Uri(file, UriKind.RelativeOrAbsolute)), code);