public override int Execute()
        {
            var hostedScript = new HostedScriptEngine
            {
                CustomConfig = ScriptFileHelper.CustomConfigPath(_path)
            };

            hostedScript.Initialize();
            ScriptFileHelper.OnBeforeScriptRead(hostedScript);
            var source   = hostedScript.Loader.FromFile(_path);
            var compiler = hostedScript.GetCompilerService();

            hostedScript.SetGlobalEnvironment(new DoNothingHost(), source);
            var writer = new ModuleWriter(compiler);

            try
            {
                writer.Write(Console.Out, source);
            }
            catch (ScriptException e)
            {
                Output.WriteLine(e.Message);
                return(1);
            }

            return(0);
        }
示例#2
0
        private void CreateDump(Stream output)
        {
            var offset = (int)output.Length;

            var engine = new HostedScriptEngine
            {
                CustomConfig = ScriptFileHelper.CustomConfigPath(_codePath)
            };

            engine.Initialize();
            ScriptFileHelper.OnBeforeScriptRead(engine);
            var source   = engine.Loader.FromFile(_codePath);
            var compiler = engine.GetCompilerService();

            engine.SetGlobalEnvironment(new DoNothingHost(), source);
            var entry = compiler.Compile(source);

            var embeddedContext = engine.GetUserAddedScripts();
            var templates       = GlobalsManager.GetGlobalContext <TemplateStorage>();

            var dump = new ApplicationDump();

            dump.Scripts = new UserAddedScript[]
            {
                new UserAddedScript()
                {
                    Image  = entry,
                    Symbol = "$entry",
                    Type   = UserAddedScriptType.Module
                }
            }.Concat(embeddedContext)
            .ToArray();
            dump.Resources = templates.GetTemplates()
                             .Select(SerializeTemplate)
                             .ToArray();

            using (var bw = new BinaryWriter(output))
            {
                var serializer = new BinaryFormatter();
                serializer.Serialize(output, dump);

                var signature = new byte[]
                {
                    0x4f,
                    0x53,
                    0x4d,
                    0x44
                };
                output.Write(signature, 0, signature.Length);

                bw.Write(offset);

                OutputToFile(output);
            }
        }
示例#3
0
        private void CreateExe()
        {
            using (var exeStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("oscript.StandaloneRunner.exe"))
                using (var output = new MemoryStream())
                {
                    exeStream?.CopyTo(output);

                    var offset = (int)output.Length;

                    var engine = new HostedScriptEngine
                    {
                        CustomConfig = ScriptFileHelper.CustomConfigPath(_codePath)
                    };
                    engine.Initialize();
                    ScriptFileHelper.OnBeforeScriptRead(engine);
                    var source   = engine.Loader.FromFile(_codePath);
                    var compiler = engine.GetCompilerService();
                    engine.SetGlobalEnvironment(new DoNothingHost(), source);
                    var entry = compiler.CreateModule(source);

                    var embeddedContext = engine.GetUserAddedScripts();

                    using (var bw = new BinaryWriter(output))
                    {
                        var userAddedScripts = embeddedContext as IList <UserAddedScript> ?? embeddedContext.ToList();
                        bw.Write(userAddedScripts.Count + 1);

                        var persistor = new ModulePersistor();
                        persistor.Save(new UserAddedScript
                        {
                            Type   = UserAddedScriptType.Module,
                            Symbol = "$entry",
                            Module = entry
                        }, output);

                        foreach (var item in userAddedScripts)
                        {
                            persistor.Save(item, output);
                        }

                        var signature = new byte[]
                        {
                            0x4f,
                            0x53,
                            0x4d,
                            0x44
                        };
                        output.Write(signature, 0, signature.Length);

                        bw.Write(offset);
                        OutputToFile(output);
                    }
                }
        }
        private void CreateDump(Stream output)
        {
            var offset = (int)output.Length;

            var engine = new HostedScriptEngine
            {
                CustomConfig = ScriptFileHelper.CustomConfigPath(_codePath)
            };

            engine.Initialize();
            ScriptFileHelper.OnBeforeScriptRead(engine);
            var source   = engine.Loader.FromFile(_codePath);
            var compiler = engine.GetCompilerService();

            engine.SetGlobalEnvironment(new DoNothingHost(), source);
            var entry = compiler.Compile(source);

            var embeddedContext = engine.GetUserAddedScripts();

            using (var bw = new BinaryWriter(output))
            {
                var userAddedScripts = embeddedContext as IList <UserAddedScript> ?? embeddedContext.ToList();
                bw.Write(userAddedScripts.Count + 1);

                var persistor = new ModulePersistor();
                persistor.Save(new UserAddedScript
                {
                    Type   = UserAddedScriptType.Module,
                    Symbol = "$entry",
                    Image  = entry
                }, output);

                foreach (var item in userAddedScripts)
                {
                    persistor.Save(item, output);
                }

                var signature = new byte[]
                {
                    0x4f,
                    0x53,
                    0x4d,
                    0x44
                };
                output.Write(signature, 0, signature.Length);

                bw.Write(offset);
                OutputToFile(output);
            }
        }
示例#5
0
        private static void CreateWorld()
        {
            _world = new HostedScriptEngine();
            var thisAsm = System.Reflection.Assembly.GetExecutingAssembly();
            var asmDir  = Path.GetDirectoryName(thisAsm.Location);
            var libDir  = Path.Combine(asmDir, "lib");

            if (Directory.Exists(libDir))
            {
                _world.InitExternalLibraries(libDir, new string[0]);
            }

            _world.SetGlobalEnvironment(new ConsoleHost(), null);
            _world.AttachAssembly(thisAsm);
            _world.Initialize();
        }
示例#6
0
        public override int Execute()
        {
            var engine = new HostedScriptEngine
            {
                CustomConfig = ScriptFileHelper.CustomConfigPath(_path)
            };

            engine.Initialize();
            ScriptFileHelper.OnBeforeScriptRead(engine);
            var source   = engine.Loader.FromFile(_path);
            var compiler = engine.GetCompilerService();

            engine.SetGlobalEnvironment(new DoNothingHost(), source);
            var entry           = compiler.Compile(source);
            var embeddedContext = engine.GetExternalLibraries();

            var serializer = new JsonSerializer();
            var sb         = new StringBuilder();

            using (var textWriter = new StringWriter(sb))
            {
                var writer = new JsonTextWriter(textWriter);
                writer.WriteStartArray();

                WriteImage(new UserAddedScript
                {
                    Type   = UserAddedScriptType.Module,
                    Symbol = "$entry",
                    Image  = entry
                }, writer, serializer);

                foreach (var item in embeddedContext)
                {
                    item.Classes.ForEach(x => WriteImage(x, writer, serializer));
                    item.Modules.ForEach(x => WriteImage(x, writer, serializer));
                }

                writer.WriteEndArray();
            }

            string result = sb.ToString();

            Output.WriteLine(result);

            return(0);
        }
        public int Run()
        {
            var engine = new HostedScriptEngine();
            var src    = new BinaryCodeSource();

            engine.SetGlobalEnvironment(this, src);

            try
            {
                ScriptModuleHandle module;
                engine.Initialize();

                using (var codeStream = LocateCode())
                    using (var binReader = new BinaryReader(codeStream))
                    {
                        var modulesCount = binReader.ReadInt32();

                        var reader = new ModulePersistor();

                        var entry = reader.Read(codeStream);
                        --modulesCount;

                        while (modulesCount-- > 0)
                        {
                            var userScript = reader.Read(codeStream);
                            engine.LoadUserScript(userScript);
                        }

                        module = entry.Module;
                    }

                var process = engine.CreateProcess(this, module, src);

                return(process.Start());
            }
            catch (ScriptInterruptionException e)
            {
                return(e.ExitCode);
            }
            catch (Exception e)
            {
                ShowExceptionInfo(e);
                return(1);
            }
        }
示例#8
0
        public override int Execute()
        {
            var hostedScript = new HostedScriptEngine
            {
                CustomConfig = ScriptFileHelper.CustomConfigPath(_path)
            };

            hostedScript.Initialize();

            if (_isCgi)
            {
                var request = ValueFactory.Create();
                hostedScript.InjectGlobalProperty("ВебЗапрос", request, true);
                hostedScript.InjectGlobalProperty("WebRequest", request, true);
            }

            ScriptFileHelper.OnBeforeScriptRead(hostedScript);
            var source = hostedScript.Loader.FromFile(_path);

            hostedScript.SetGlobalEnvironment(new DoNothingHost(), source);

            try
            {
                if (_envFile != null)
                {
                    var envCompiler = hostedScript.GetCompilerService();
                    var envSrc      = hostedScript.Loader.FromFile(_envFile);
                    envCompiler.Compile(envSrc);
                }
                var compiler = hostedScript.GetCompilerService();
                compiler.Compile(source);
            }
            catch (ScriptException e)
            {
                Output.WriteLine(e.Message);
                return(1);
            }

            Output.WriteLine("No errors.");

            return(0);
        }
        public Process CreateProcess(Stream sourceStream, IHostApplication host)
        {
            var appDump         = DeserializeAppDump(sourceStream);
            var engine          = new HostedScriptEngine();
            var src             = new BinaryCodeSource();
            var templateStorage = new TemplateStorage(new StandaloneTemplateFactory());

            engine.SetGlobalEnvironment(host, src);
            engine.InitializationCallback = (e, env) =>
            {
                e.Environment.InjectObject(templateStorage);
                GlobalsManager.RegisterInstance(templateStorage);
            };
            engine.Initialize();

            LoadResources(templateStorage, appDump.Resources);
            LoadScripts(engine, appDump.Scripts);

            var process = engine.CreateProcess(host, appDump.Scripts[0].Image, src);

            return(process);
        }
示例#10
0
        public int Run()
        {
            if (_sourceStream == null && CommandLineArguments != null && CommandLineArguments.Length > 1)
            {
                var firstArg = CommandLineArguments[0];
                if (firstArg == "-loadDump")
                {
                    var path = CommandLineArguments[1];
                    CommandLineArguments = CommandLineArguments.Skip(2).ToArray();
                    using (var dumpStream = new FileStream(path, FileMode.Open))
                    {
                        _sourceStream = GetCodeStream(dumpStream);
                    }

                    return(Run()); //ну да, говнокод и лапша, время жмет
                }
            }

            if (_sourceStream == null)
            {
                _sourceStream = LocateCode();
            }

            var engine = new HostedScriptEngine();
            var src    = new BinaryCodeSource();

            engine.SetGlobalEnvironment(this, src);

            try
            {
                var templateStorage = new TemplateStorage(new StandaloneTemplateFactory());
                engine.InitializationCallback = (e, env) =>
                {
                    e.Environment.InjectObject(templateStorage);
                    GlobalsManager.RegisterInstance(templateStorage);
                };

                engine.Initialize();

                var serializer = new BinaryFormatter();
                var appDump    = (ApplicationDump)serializer.Deserialize(_sourceStream);
                foreach (var resource in appDump.Resources)
                {
                    templateStorage.RegisterTemplate(resource.ResourceName, DeserializeTemplate(resource.Data));
                }
                var module = appDump.Scripts[0].Image;
                for (int i = 1; i < appDump.Scripts.Length; i++)
                {
                    engine.LoadUserScript(appDump.Scripts[i]);
                }

                var process = engine.CreateProcess(this, module, src);

                return(process.Start());
            }
            catch (ScriptInterruptionException e)
            {
                return(e.ExitCode);
            }
            catch (Exception e)
            {
                ShowExceptionInfo(e);
                return(1);
            }
        }
示例#11
0
        public ASPNETHandler()
        {
            System.Collections.Specialized.NameValueCollection appSettings = System.Web.Configuration.WebConfigurationManager.AppSettings;

            // Инициализируем логгирование, если надо
            TextWriter logWriter = OpenLog(appSettings);

            WriteToLog(logWriter, "Start loading.");

            try
            {
                _hostedScript = new HostedScriptEngine();
                // метод настраивает внутренние переменные у SystemGlobalContext
                if (appSettings["enableEcho"] == "true")
                {
                    _hostedScript.SetGlobalEnvironment(new ASPNetApplicationHost(), new AspEntryScriptSrc(appSettings["startupScript"] ?? HttpContext.Current.Server.MapPath("~/web.config")));
                }
                else
                {
                    _hostedScript.SetGlobalEnvironment(new AspNetNullApplicationHost(), new AspNetNullEntryScriptSrc());
                }

                _hostedScript.Initialize();


                // Размещаем oscript.cfg вместе с web.config. Так наверное привычнее
                _hostedScript.CustomConfig = appSettings["configFilePath"] ?? HttpContext.Current.Server.MapPath("~/oscript.cfg");
                _hostedScript.AttachAssembly(System.Reflection.Assembly.GetExecutingAssembly());
                // Аттачим доп сборки. По идее должны лежать в Bin
                foreach (System.Reflection.Assembly assembly in _assembliesForAttaching)
                {
                    try
                    {
                        _hostedScript.AttachAssembly(assembly);
                    }
                    catch (Exception ex)
                    {
                        // Возникла проблема при аттаче сборки
                        WriteToLog(logWriter, "Assembly attaching error: " + ex.Message);
                        if (appSettings["handlerLoadingPolicy"] == "strict")
                        {
                            throw;
                        }
                    }
                }

                //Загружаем библиотечные скрипты aka общие модули
                string libPath = appSettings["commonModulesPath"];

                if (libPath != null)
                {
                    libPath = HttpContext.Current.Server.MapPath(libPath);

                    string[] files = System.IO.Directory.GetFiles(libPath, "*.os");


                    foreach (string filePathName in files)
                    {
                        _hostedScript.InjectGlobalProperty(System.IO.Path.GetFileNameWithoutExtension(filePathName), ValueFactory.Create(), true);
                    }

                    foreach (string filePathName in files)
                    {
                        try
                        {
                            ICodeSource src = _hostedScript.Loader.FromFile(filePathName);

                            var compilerService = _hostedScript.GetCompilerService();
                            var module          = compilerService.Compile(src);
                            var loaded          = _hostedScript.EngineInstance.LoadModuleImage(module);
                            var instance        = (IValue)_hostedScript.EngineInstance.NewObject(loaded);
                            _hostedScript.EngineInstance.Environment.SetGlobalProperty(System.IO.Path.GetFileNameWithoutExtension(filePathName), instance);
                        }
                        catch (Exception ex)
                        {
                            // Возникла проблема при загрузке файла os, логгируем, если логгирование включено
                            WriteToLog(logWriter, "Error loading " + System.IO.Path.GetFileNameWithoutExtension(filePathName) + " : " + ex.Message);
                            if (appSettings["handlerLoadingPolicy"] == "strict")
                            {
                                throw;
                            }
                        }
                    }
                }

                _hostedScript.EngineInstance.Environment.LoadMemory(MachineInstance.Current);
            }
            catch (Exception ex)
            {
                // Возникла проблема при инициализации хэндлера
                WriteToLog(logWriter, ex.Message);

                if (appSettings["handlerLoadingPolicy"] == "strict")
                {
                    throw; // Must fail!
                }
            }
            finally
            {
                WriteToLog(logWriter, "End loading.");
                CloseLog(logWriter);
            }
        }
示例#12
0
        public int Run()
        {
            if (_sourceStream == null && CommandLineArguments != null && CommandLineArguments.Length > 1)
            {
                var firstArg = CommandLineArguments[0];
                if (firstArg == "-loadDump")
                {
                    var path = CommandLineArguments[1];
                    CommandLineArguments = CommandLineArguments.Skip(2).ToArray();
                    using (var dumpStream = new FileStream(path, FileMode.Open))
                    {
                        _sourceStream = GetCodeStream(dumpStream);
                    }

                    Run(); //ну да, говнокод и лапша, время жмет
                }
            }

            if (_sourceStream == null)
            {
                _sourceStream = LocateCode();
            }

            var engine = new HostedScriptEngine();
            var src    = new BinaryCodeSource();

            engine.SetGlobalEnvironment(this, src);

            try
            {
                ModuleImage module;
                engine.Initialize();

                using (var binReader = new BinaryReader(_sourceStream))
                {
                    var modulesCount = binReader.ReadInt32();

                    var reader = new ModulePersistor();

                    var entry = reader.Read(_sourceStream);
                    --modulesCount;

                    while (modulesCount-- > 0)
                    {
                        var userScript = reader.Read(_sourceStream);
                        engine.LoadUserScript(userScript);
                    }

                    module = entry.Image;
                }

                var process = engine.CreateProcess(this, module, src);

                return(process.Start());
            }
            catch (ScriptInterruptionException e)
            {
                return(e.ExitCode);
            }
            catch (Exception e)
            {
                ShowExceptionInfo(e);
                return(1);
            }
        }
        public AspNetHostEngine(
            List <System.Reflection.Assembly> assembliesForAttaching,
            List <PropertiesInjectorInfo> propertiesInjectorsInfo,
            System.Collections.Hashtable commonModulesForLoading
            )
        {
            System.Collections.Specialized.NameValueCollection appSettings = System.Web.Configuration.WebConfigurationManager.AppSettings;

            _hostedScript = new HostedScriptEngine();

            // метод настраивает внутренние переменные у SystemGlobalContext
            if (appSettings["enableEcho"] == "true")
            {
                _hostedScript.SetGlobalEnvironment(new ASPNetApplicationHost(), new AspEntryScriptSrc(appSettings["startupScript"] ?? HttpContext.Current.Server.MapPath("~/web.config")));
            }
            else
            {
                _hostedScript.SetGlobalEnvironment(new AspNetNullApplicationHost(), new AspNetNullEntryScriptSrc());
            }

            _hostedScript.Initialize();

            // Размещаем oscript.cfg вместе с web.config. Так наверное привычнее
            _hostedScript.CustomConfig = appSettings["configFilePath"] ?? System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "oscript.cfg");

            // Аттачим доп сборки. По идее должны лежать в Bin
            foreach (System.Reflection.Assembly assembly in assembliesForAttaching)
            {
                _hostedScript.AttachAssembly(assembly);
            }

            // Добавляем свойства для общих модулей
            foreach (System.Collections.DictionaryEntry cm in commonModulesForLoading)
            {
                _hostedScript.InjectGlobalProperty((string)cm.Key, ValueFactory.Create(), true);
            }

            // Загружаем классы инжекторов свойств
            List <PropertiesInjector> propertiesInjectors = new List <PropertiesInjector>();

            foreach (PropertiesInjectorInfo ci in propertiesInjectorsInfo)
            {
                ILibraryAsPropertiesLoader instance = (ILibraryAsPropertiesLoader)(Activator.CreateInstance(ci.AssemblyName, ci.ClassName).Unwrap());
                propertiesInjectors.Add(new PropertiesInjector(instance, ci.Info));
            }

            // Получаем и вставляем списки свойств. Класс инжектора должен иметь метод GetPropertyNamesForInjecting
            foreach (PropertiesInjector injector in propertiesInjectors)
            {
                List <string> propertiesNames = injector.Loader.GetPropertiesNamesForInjecting(injector.Info);
                foreach (string cp in propertiesNames)
                {
                    _hostedScript.InjectGlobalProperty(cp, ValueFactory.Create(), true);
                }
            }

            // Подключаем общие модули
            foreach (System.Collections.DictionaryEntry cm in commonModulesForLoading)
            {
                ICodeSource src = _hostedScript.Loader.FromString((string)cm.Value);

                var compilerService = _hostedScript.GetCompilerService();
                var module          = compilerService.CreateModule(src);
                var loaded          = _hostedScript.EngineInstance.LoadModuleImage(module);
                var instance        = (IValue)_hostedScript.EngineInstance.NewObject(loaded);
                _hostedScript.EngineInstance.Environment.SetGlobalProperty((string)cm.Key, instance);
            }

            // Присваиваем значения свойств
            foreach (PropertiesInjector injector in propertiesInjectors)
            {
                injector.Loader.AssignPropertiesValues(_hostedScript);
            }

            _hostedScript.EngineInstance.Environment.LoadMemory(MachineInstance.Current);
        }
示例#14
0
        public AspNetHostEngine()
        {
            System.Collections.Specialized.NameValueCollection appSettings = System.Web.Configuration.WebConfigurationManager.AppSettings;

            // Инициализируем логгирование, если надо
            TextWriter logWriter = AspNetLog.Open(appSettings);

            AspNetLog.Write(logWriter, "Start loading. " + DateTime.Now.Ticks.ToString());

            if (appSettings == null)
            {
                AspNetLog.Write(logWriter, "appSettings is null");
            }

            try
            {
                _hostedScript = new HostedScriptEngine();
                // метод настраивает внутренние переменные у SystemGlobalContext
                _hostedScript.SetGlobalEnvironment(new NullApplicationHost(), new NullEntryScriptSrc());
                _hostedScript.Initialize();
                // Размещаем oscript.cfg вместе с web.config. Так наверное привычнее
                _hostedScript.CustomConfig = appSettings["configFilePath"] ?? System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "oscript.cfg");
                //_hostedScript.AttachAssembly(System.Reflection.Assembly.GetExecutingAssembly());
                // Аттачим доп сборки. По идее должны лежать в Bin
                foreach (System.Reflection.Assembly assembly in _assembliesForAttaching)
                {
                    try
                    {
                        _hostedScript.AttachAssembly(assembly);
                    }
                    catch (Exception ex)
                    {
                        // Возникла проблема при аттаче сборки
                        AspNetLog.Write(logWriter, "Assembly attaching error: " + ex.Message);
                        if (appSettings["handlerLoadingPolicy"] == "strict")
                        {
                            throw;
                        }
                    }
                }

                //Загружаем библиотечные скрипты aka общие модули
                string libPath = ConvertRelativePathToPhysical(appSettings["commonModulesPath"]);
                if (libPath != null)
                {
                    string[] files = System.IO.Directory.GetFiles(libPath, "*.os");
                    foreach (string filePathName in files)
                    {
                        _hostedScript.InjectGlobalProperty(System.IO.Path.GetFileNameWithoutExtension(filePathName), ValueFactory.Create(), true);
                    }

                    foreach (string filePathName in files)
                    {
                        try
                        {
                            ICodeSource src = _hostedScript.Loader.FromFile(filePathName);

                            var compilerService = _hostedScript.GetCompilerService();
                            var module          = compilerService.CreateModule(src);
                            var loaded          = _hostedScript.EngineInstance.LoadModuleImage(module);
                            var instance        = (IValue)_hostedScript.EngineInstance.NewObject(loaded);
                            _hostedScript.EngineInstance.Environment.SetGlobalProperty(System.IO.Path.GetFileNameWithoutExtension(filePathName), instance);
                        }
                        catch (Exception ex)
                        {
                            // Возникла проблема при загрузке файла os, логгируем, если логгирование включено
                            AspNetLog.Write(logWriter, "Error loading " + System.IO.Path.GetFileNameWithoutExtension(filePathName) + " : " + ex.Message);
                            if (appSettings["handlerLoadingPolicy"] == "strict")
                            {
                                throw;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // Возникла проблема при инициализации
                AspNetLog.Write(logWriter, ex.ToString());

                if (appSettings["handlerLoadingPolicy"] == "strict")
                {
                    throw; // Must fail!
                }
            }
            finally
            {
                AspNetLog.Write(logWriter, "End loading.");
                AspNetLog.Close(logWriter);
            }
        }