Ejemplo n.º 1
0
        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;
        }
        public V8Script Compile(string scriptId, string code, bool addToCache = true, int?cacheExpirationSeconds = null)
        {
            CachedV8Script cachedScript;

            if (TryGetCached(scriptId, out cachedScript))
            {
                return(cachedScript.Script);
            }

            V8Script compiledScript = _v8Runtime.Compile(scriptId, code);

            if (addToCache)
            {
                if (!cacheExpirationSeconds.HasValue)
                {
                    cacheExpirationSeconds = _settings.ScriptCacheExpirationSeconds;
                }
                if (cacheExpirationSeconds > 0)
                {
                    var cacheEntry = new CachedV8Script(compiledScript, cacheExpirationSeconds.Value);
                    _scriptCache.AddOrUpdate(scriptId, cacheEntry, (key, original) => cacheEntry);
                }
            }

            return(compiledScript);
        }
Ejemplo n.º 3
0
        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;
                }
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 执行js V8方法
        /// </summary>
        /// <param name="reString">Js代码</param>
        /// <param name="para">参数字符串(使用逗号分隔)</param>
        /// <param name="MethodName">方法名称</param>
        public static string V8Method(string reString, string para, string MethodName)
        {
            V8Engine engine = V8Engine.Create();        //创建V8对象
            V8Script script = engine.Compile(reString); //编译

            try
            {
                engine.Execute(script);                                                              //将编译的脚本加载到V8引擎中
                string res = engine.Execute(string.Format("{0}({1})", MethodName, para)).ToString(); //执行结果
                return(res);
            }
            catch (Exception ex)
            {
                return(ex.Message);//异常信息
            }
        }
Ejemplo n.º 5
0
        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);");
        }
Ejemplo n.º 6
0
        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;
        }
Ejemplo n.º 7
0
        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)
            {
            }
        }
Ejemplo n.º 8
0
        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();
        }
Ejemplo n.º 9
0
        public async Task <V8ScriptEngine> ExecuteAsync(IEnumerable <IncludeScript> scripts, Action <V8ScriptEngine> configAction, ExecutionOptions options = null)
        {
            var scriptList = PrecheckScripts(scripts);

            if (scriptList == null)
            {
                return(null);
            }

            if (options == null)
            {
                options = new ExecutionOptions();
            }

            IEnumerable <V8Script> compiledScripts = scriptList.Select(x => _scriptCompiler.Compile(x, options.AddToCache, options.CacheExpirationSeconds));

            GetEngine();

            if (AddConsoleReference)
            {
                _scriptEngine.AddHostType("Console", typeof(Console));
            }

            RequireManager.BuildRequirer(_scriptCompiler, _scriptEngine);

            if (configAction != null)
            {
                configAction(_scriptEngine);
            }

            if (options.Scripts != null)
            {
                foreach (var script in options.Scripts)
                {
                    var compiledInclude = _scriptCompiler.Compile(script, options.AddToCache);
                    if (compiledInclude != null)
                    {
                        _scriptEngine.Execute(compiledInclude);
                    }
                }
            }

            foreach (var compiledScript in compiledScripts)
            {
                //Only create a wrapping task if the script has a timeout.
                CancellationToken cancellationToken;
                if (TryCreateCancellationToken(out cancellationToken))
                {
                    using (cancellationToken.Register(_scriptEngine.Interrupt))
                    {
                        try
                        {
                            V8Script script = compiledScript;
                            await Task.Run(() => _scriptEngine.Execute(script), cancellationToken).ConfigureAwait(false);
                        }
                        catch (ScriptInterruptedException ex)
                        {
                            var newEx = new ScriptInterruptedException(
                                "Script interruption occurred, this often indicates a script timeout.  Examine the data and inner exception for more information.", ex);
                            newEx.Data.Add("Timeout", _settings.ScriptTimeoutMilliSeconds);
                            newEx.Data.Add("ScriptId", compiledScript.Name);

                            throw newEx;
                        }
                    }
                }
                else
                {
                    _scriptEngine.Execute(compiledScript);
                }
            }

            return(_scriptEngine);
        }
Ejemplo n.º 10
0
        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);
            }
        }
Ejemplo n.º 11
0
 public CachedV8Script(V8Script script, int expirationSeconds = ManagerSettings.DefaultScriptTimeoutMilliSeconds)
 {
     CreatedOn = DateTime.UtcNow;
     ExpiresOn = CreatedOn.AddSeconds(expirationSeconds);
     Script    = script;
 }
Ejemplo n.º 12
0
 public dynamic Evaluate(V8Script script) => _engine.Evaluate(script);
        public V8Script CompileScript(string codeScript)
        {
            V8Script result = m_scriptEngine.Compile(m_currentScriptName, codeScript);

            return(result);
        }