public void Create(IScriptHost host)
        {
            try
            {
                m_scriptHost = host;

                m_appDomain = AppDomain.CreateDomain($"ScriptDomain_{m_instanceId}");
                m_appDomain.SetupInformation.ConfigurationFile = "dummy.config";

                m_intManager = (InternalManager)m_appDomain.CreateInstanceAndUnwrap(typeof(InternalManager).Assembly.FullName, typeof(InternalManager).FullName);

                // TODO: figure out a cleaner solution to Mono JIT corruption so server doesn't have to be slower
#if IS_FXSERVER
                m_intManager.SetScriptHost(new WrapScriptHost(host), m_instanceId);
#else
                m_intManager.SetScriptHost(Marshal.GetIUnknownForObject(host), m_instanceId);
#endif
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());

                if (e.InnerException != null)
                {
                    Debug.WriteLine(e.InnerException.ToString());
                }

                throw;
            }
        }
        public void Create(IScriptHost host)
        {
            try
            {
                m_scriptHost = host;

                ((IScriptHostWithResourceData)host).GetResourceName(out var nameString);
                string resourceName = Marshal.PtrToStringAnsi(nameString);

                bool useTaskScheduler = true;

#if IS_FXSERVER
                string basePath = "";

                {
                    // we can't invoke natives if not doing this
                    InternalManager.ScriptHost = host;

                    basePath         = Native.API.GetResourcePath(resourceName);
                    useTaskScheduler = Native.API.GetNumResourceMetadata(resourceName, "clr_disable_task_scheduler") == 0;
                }
#endif

                m_appDomain = AppDomain.CreateDomain($"ScriptDomain_{m_instanceId}", AppDomain.CurrentDomain.Evidence, new AppDomainSetup()
                {
#if IS_FXSERVER
                    ApplicationBase = basePath
#endif
                });

                m_appDomain.SetupInformation.ConfigurationFile = "dummy.config";

                m_intManager = (InternalManager)m_appDomain.CreateInstanceAndUnwrap(typeof(InternalManager).Assembly.FullName, typeof(InternalManager).FullName);

                if (useTaskScheduler)
                {
                    m_intManager.CreateTaskScheduler();
                }

                m_intManager.SetResourceName(resourceName);

                // TODO: figure out a cleaner solution to Mono JIT corruption so server doesn't have to be slower
#if IS_FXSERVER
                m_intManager.SetScriptHost(new WrapScriptHost(host), m_instanceId);
#else
                m_intManager.SetScriptHost(Marshal.GetIUnknownForObject(host), m_instanceId);
#endif
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());

                if (e.InnerException != null)
                {
                    Debug.WriteLine(e.InnerException.ToString());
                }

                throw;
            }
        }
Example #3
0
        public IScriptSession CreateSession(IScriptHost host, IDictionary <string, string> arguments)
        {
            if (arguments == null)
            {
                throw new ArgumentNullException("arguments");
            }

            // Are we using the experimental bits?
            var experimental = arguments.ContainsKey("experimental");

            if (!experimental)
            {
                // Are we running Windows 10, build 10041?
                var operativeSystemVersion = Environment.OSVersion.Version;
                if (operativeSystemVersion.Major == 10 && operativeSystemVersion.Build >= 10041)
                {
                    // Since .NET 4.6.1 is default here and since Roslyn
                    // isn't compatible with that framework version,
                    // we default to the experimental bits.
                    experimental = true;
                }
            }

            // Create the script session.
            _log.Debug("Creating script session...");
            if (experimental)
            {
                // Use the nightly build.
                _log.Information("Using nightly build of Roslyn.");
                return(_nightlyFactory.CreateSession(host));
            }

            // Use the stable build.
            return(_stableFactory.CreateSession(host));
        }
Example #4
0
 private unsafe static void InvokeInternal(ulong nativeIdentifier, IScriptHost scriptHost)
 {
     fixed(ContextType *cxt = &m_extContext)
     {
         InvokeInternal(cxt, nativeIdentifier, scriptHost);
     }
 }
Example #5
0
        public IScriptSession CreateSession(IScriptHost host)
        {
            // Is Roslyn installed?
            if (!IsInstalled())
            {
                // Find out which is the latest Roslyn version.
                _log.Information("Checking what the latest version of Roslyn is...");
                var version = GetLatestVersion();
                if (version == null)
                {
                    throw new CakeException("Could not resolve latest version of Roslyn.");
                }

                _log.Information("The latest Roslyn version is {0}.", version);
                _log.Information("Downloading and installing Roslyn...");
                Install(version);
            }

            // Load Roslyn assemblies dynamically.
            foreach (var filePath in _paths)
            {
                Assembly.LoadFrom(_environment
                                  .GetApplicationRoot()
                                  .CombineWithFilePath(filePath.GetFilename())
                                  .FullPath);
            }

            // Create the session.
            return(new RoslynNightlyScriptSession(host, _log));
        }
 public void OnLoad(IScriptHost host)
 {
     this.host = host;
     //
     // TODO: Add initialization code.
     //
 }
Example #7
0
        public MonoScriptSession(IScriptHost host, ICakeLog log)
        {
            if (host == null)
            {
                throw new ArgumentNullException("host");
            }
            if (log == null)
            {
                throw new ArgumentNullException("log");
            }

            _log = log;

            // Create the evaluator.
            var compilerSettings = new CompilerSettings();
            var reportPrinter    = new MonoConsoleReportPrinter(_log);
            var compilerContext  = new CompilerContext(compilerSettings, reportPrinter);

            _evaluator = new Evaluator(compilerContext);

            // Set our instance of the script host to this static member
            MonoScriptHostProxy.ScriptHost = host;

            // This will be our 'base' type from which the evaluator grants access
            // to static members to the script being run
            _evaluator.InteractiveBaseClass = typeof(MonoScriptHostProxy);
        }
Example #8
0
        public IScriptSession CreateSession(IScriptHost host)
        {
            _log.Debug("Creating script session...");
            var roslynScriptEngine = new ScriptEngine();
            var session            = roslynScriptEngine.CreateSession(host, typeof(IScriptHost));

            return(new RoslynScriptSession(session, _log));
        }
Example #9
0
 public IScriptSession CreateSession(IScriptHost host, IDictionary <string, string> arguments)
 {
     if (_options.PerformDebug)
     {
         return(new DebugXPlatScriptSession(host, _loader, _log));
     }
     return(new DefaultXPlatScriptSession(host, _loader, _log));
 }
Example #10
0
        public RoslynNightlyScriptSession(IScriptHost host, ICakeLog log)
        {
            _host = host;
            _log  = log;

            _referencePaths = new HashSet <FilePath>(PathComparer.Default);
            _references     = new HashSet <Assembly>();
            _namespaces     = new HashSet <string>(StringComparer.Ordinal);
        }
Example #11
0
        public DefaultRoslynScriptSession(IScriptHost host, ICakeLog log) : base(host, log)
        {
            if (log == null)
            {
                throw new ArgumentNullException("log");
            }

            _log = log;
        }
Example #12
0
        public void Create(IScriptHost host)
        {
            try
            {
                m_scriptHost = host;

#if IS_FXSERVER
                string resourceName = "";
                string basePath     = "";

                {
                    ((IScriptHostWithResourceData)host).GetResourceName(out var nameString);

                    resourceName = Marshal.PtrToStringAnsi(nameString);

                    // we can't invoke natives if not doing this
                    InternalManager.ScriptHost = host;

                    basePath = Native.API.GetResourcePath(resourceName);
                }

                // Load required assemblies by resource
                ms_appDomain.AssemblyResolve += (sender, args) =>
                {
                    var assemblyPath = Path.Combine(basePath, new AssemblyName(args.Name).Name + ".dll");
                    if (!File.Exists(assemblyPath))
                    {
                        return(null);
                    }

                    return(Assembly.LoadFile(assemblyPath));
                };
#endif

                m_intManager = (InternalManager)ms_appDomain.CreateInstanceAndUnwrap(
                    typeof(InternalManager).Assembly.FullName, typeof(InternalManager).FullName);

                // TODO: figure out a cleaner solution to Mono JIT corruption so server doesn't have to be slower
#if IS_FXSERVER
                m_intManager.SetScriptHost(new WrapScriptHost(host), m_instanceId);
#else
                m_intManager.SetScriptHost(Marshal.GetIUnknownForObject(host), m_instanceId);
#endif
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());

                if (e.InnerException != null)
                {
                    Debug.WriteLine(e.InnerException.ToString());
                }

                throw;
            }
        }
Example #13
0
        /// <summary>
        /// Initializes environment according to the setup information.
        /// </summary>
        private ScriptDomainManager()
        {
            // create local environment for the host:
            _environment = new ScriptEnvironment(this);
            _host        = new ScriptHost(_environment);

            // initialize snippets:
            _snippets = new Snippets();
            _pal      = null;
        }
Example #14
0
        public void Destroy()
        {
            m_intManager?.Destroy();

            AppDomain.Unload(m_appDomain);

            m_appDomain  = null;
            m_intManager = null;
            m_scriptHost = null;
        }
 public StateMachineManagerDataService(
     ISessionIdProvider sessionIdProvider,
     ILocaleManager localeManager,
     IAssetsManager assetsManager,
     IScriptHost scriptHost)
 {
     this.sessionIdProvider = sessionIdProvider;
     this.localeManager     = localeManager;
     this.assetsManager     = assetsManager;
     this.scriptHost        = scriptHost;
 }
Example #16
0
        public RoslynScriptSession(IScriptHost host, IAssemblyLoader loader, ICakeLog log, CakeOptions options)
        {
            _host    = host;
            _loader  = loader;
            _log     = log;
            _options = options;

            ReferencePaths = new HashSet <FilePath>(PathComparer.Default);
            References     = new HashSet <Assembly>();
            Namespaces     = new HashSet <string>(StringComparer.Ordinal);
        }
Example #17
0
        private unsafe static void InvokeInternal(ulong nativeIdentifier, IScriptHost scriptHost)
        {
            var context = m_extContext;

            m_extContext = new ContextType();

            ContextType *cxt = &context;

            InvokeInternal(cxt, nativeIdentifier, scriptHost);

            m_extContext = context;
        }
Example #18
0
        private void InvokeInternal(ulong nativeIdentifier, IScriptHost scriptHost)
        {
            m_context.nativeIdentifier = nativeIdentifier;

            unsafe
            {
                fixed(fxScriptContext *cxt = &m_context)
                {
                    scriptHost.InvokeNative(new IntPtr(cxt));
                }
            }
        }
Example #19
0
        public DebugRoslynNightlyScriptSession(IScriptHost host, ICakeLog log) : base(log)
        {
            if (host == null)
            {
                throw new ArgumentNullException("host");
            }
            if (log == null)
            {
                throw new ArgumentNullException("log");
            }

            _host = host;
            _log  = log;
        }
Example #20
0
        public IScriptSession CreateSession(IScriptHost host, IDictionary <string, string> arguments)
        {
            if (host == null)
            {
                throw new ArgumentNullException("host");
            }
            if (arguments == null)
            {
                throw new ArgumentNullException("arguments");
            }

            // Create the script session.
            _log.Debug("Creating script session...");
            return(new MonoScriptSession(host, _log));
        }
Example #21
0
        public RoslynScriptSession(
            IScriptHost host,
            IAssemblyLoader loader,
            ICakeConfiguration configuration,
            ICakeLog log,
            IScriptHostSettings settings)
        {
            _host          = host;
            _loader        = loader;
            _log           = log;
            _configuration = configuration;
            _settings      = settings;

            ReferencePaths = new HashSet <FilePath>(PathComparer.Default);
            References     = new HashSet <Assembly>();
            Namespaces     = new HashSet <string>(StringComparer.Ordinal);
        }
Example #22
0
        protected RoslynScriptSession(IScriptHost host, ICakeLog log)
        {
            if (host == null)
            {
                throw new ArgumentNullException("host");
            }
            if (log == null)
            {
                throw new ArgumentNullException("log");
            }

            var roslynScriptEngine = new global::Roslyn.Scripting.CSharp.ScriptEngine();

            _roslynSession = roslynScriptEngine.CreateSession(host, typeof(IScriptHost));

            _log = log;
            _importedNamespaces = new HashSet <string>();
        }
Example #23
0
        /// <summary>
        /// Initializes environment according to the setup information.
        /// </summary>
        private ScriptDomainManager(ScriptEnvironmentSetup setup)
        {
            Debug.Assert(setup != null);

            // create local environment for the host:
            _environment = new ScriptEnvironment(this);

            // create PAL (default always available):
            _pal = setup.CreatePAL();

            // let setup register providers listed on it:
            setup.RegisterProviders(this);

            // initialize snippets:
            _snippets = new Snippets();

            // create a local host unless a remote one has already been created:
            _host = setup.CreateScriptHost(_environment);
        }
        public IScriptSession CreateSession(IScriptHost host)
        {
            // Is Roslyn installed?
            if (!IsInstalled())
            {
                _log.Information("Downloading and installing Roslyn (experimental)...");
                Install(new SemanticVersion(1, 0, 0, "rc2"));
            }

            // Load Roslyn assemblies dynamically.
            foreach (var filePath in _paths)
            {
                Assembly.LoadFrom(_environment.ApplicationRoot
                                  .CombineWithFilePath(filePath.GetFilename())
                                  .FullPath);
            }

            // Create the session.
            return(CreateSession(host, _log));
        }
Example #25
0
        public async Task Apply(IScriptHost context)
        {
            foreach (var script in Scripts)
            {
                switch (script.Type)
                {
                case ScriptType.CSharp:
                    await context.ExecuteCSharp(script.Value).ConfigureAwait(false);

                    break;

                case ScriptType.Lua:
                    context.ExecuteLua(script.Value);
                    break;

                default:
                    throw new InvalidOperationException("Unsupported script type: " + script.Type.ToString("f"));
                }
            }
        }
Example #26
0
        public IScriptSession CreateSession(IScriptHost host, IDictionary <string, string> arguments)
        {
            if (arguments == null)
            {
                throw new ArgumentNullException("arguments");
            }

            // Create the script session.
            _log.Debug("Creating script session...");

            // Are we using the experimental bits?
            if (_options.Experimental)
            {
                // Use the nightly build.
                _log.Debug("Using prerelease build of Roslyn.");
                return(_nightlyFactory.CreateSession(host));
            }

            // Use the stable build.
            return(_stableFactory.CreateSession(host));
        }
Example #27
0
        public IScriptSession CreateSession(IScriptHost host)
        {
            var root = _environment.ApplicationRoot;

            // Is Roslyn installed?
            if (!IsInstalled(root))
            {
                _log.Information("Downloading and installing Roslyn...");
                Install(root);
            }

            // Load Roslyn assemblies dynamically.
            foreach (var filePath in _paths)
            {
                Assembly.LoadFrom(_environment.ApplicationRoot
                                  .CombineWithFilePath(filePath.GetFilename())
                                  .FullPath);
            }

            // Create a new session.
            return(CreateSession(host, _log));
        }
Example #28
0
        public void Create(IScriptHost host)
        {
            try
            {
                m_scriptHost = host;

                m_appDomain = AppDomain.CreateDomain($"ScriptDomain_{m_instanceId}");

                m_intManager = (InternalManager)m_appDomain.CreateInstanceAndUnwrap(typeof(InternalManager).Assembly.FullName, typeof(InternalManager).FullName);
                m_intManager.SetScriptHost(Marshal.GetIUnknownForObject(host), m_instanceId);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());

                if (e.InnerException != null)
                {
                    Debug.WriteLine(e.InnerException.ToString());
                }

                throw;
            }
        }
Example #29
0
 public ScriptRunner(IFileSystem fileSystem, ICakeEnvironment environment, CakeArguments arguments,
                     IScriptSessionFactory sessionFactory, IScriptAliasGenerator aliasGenerator,
                     IScriptProcessor processor, IScriptHost host)
 {
     if (fileSystem == null)
     {
         throw new ArgumentNullException("fileSystem");
     }
     if (environment == null)
     {
         throw new ArgumentNullException("environment");
     }
     if (arguments == null)
     {
         throw new ArgumentNullException("arguments");
     }
     if (sessionFactory == null)
     {
         throw new ArgumentNullException("sessionFactory");
     }
     if (aliasGenerator == null)
     {
         throw new ArgumentNullException("aliasGenerator");
     }
     if (host == null)
     {
         throw new ArgumentNullException("host");
     }
     _fileSystem     = fileSystem;
     _environment    = environment;
     _arguments      = arguments;
     _sessionFactory = sessionFactory;
     _aliasGenerator = aliasGenerator;
     _processor      = processor;
     _host           = host;
 }
Example #30
0
        public RoslynScriptSession(
            IScriptHost host,
            IAssemblyLoader loader,
            ICakeConfiguration configuration,
            ICakeLog log,
            IScriptHostSettings settings)
        {
            _host          = host;
            _fileSystem    = host.Context.FileSystem;
            _loader        = loader;
            _log           = log;
            _configuration = configuration;
            _settings      = settings;

            ReferencePaths = new HashSet <FilePath>(PathComparer.Default);
            References     = new HashSet <Assembly>();
            Namespaces     = new HashSet <string>(StringComparer.Ordinal);

            var cacheEnabled = configuration.GetValue(Constants.Settings.EnableScriptCache) ?? bool.FalseString;

            _scriptCacheEnabled = cacheEnabled.Equals(bool.TrueString, StringComparison.OrdinalIgnoreCase);
            _regenerateCache    = host.Context.Arguments.HasArgument(Constants.Cache.InvalidateScriptCache);
            _scriptCachePath    = configuration.GetScriptCachePath(settings.Script.GetDirectory(), host.Context.Environment);
        }
Example #31
0
        /// <summary>
        /// Runs the script using the specified script host.
        /// </summary>
        /// <param name="host">The script host.</param>
        /// <param name="scriptPath">The script.</param>
        /// <param name="arguments">The arguments.</param>
        public void Run(IScriptHost host, FilePath scriptPath, IDictionary <string, string> arguments)
        {
            if (host == null)
            {
                throw new ArgumentNullException(nameof(host));
            }
            if (scriptPath == null)
            {
                throw new ArgumentNullException(nameof(scriptPath));
            }
            if (arguments == null)
            {
                throw new ArgumentNullException(nameof(arguments));
            }

            // Make the script path absolute.
            scriptPath = scriptPath.MakeAbsolute(_environment);

            // Prepare the environment.
            _environment.WorkingDirectory = scriptPath.GetDirectory();

            // Analyze the script file.
            _log.Verbose("Analyzing build script...");
            var result = _analyzer.Analyze(scriptPath.GetFilename());

            // Log all errors and throw
            if (!result.Succeeded)
            {
                foreach (var error in result.Errors)
                {
                    var format = $"{error.File.MakeAbsolute(_environment).FullPath}:{error.Line}: {{0}}";
                    _log.Error(format, error.Message);
                }
                throw new CakeException("Errors occurred while analyzing script.");
            }

            // Install tools.
            _log.Verbose("Processing build script...");
            var toolsPath = GetToolPath(scriptPath.GetDirectory());

            _processor.InstallTools(result.Tools, toolsPath);

            // Install addins.
            var addinRoot       = GetAddinPath(scriptPath.GetDirectory());
            var addinReferences = _processor.InstallAddins(result.Addins, addinRoot);

            foreach (var addinReference in addinReferences)
            {
                result.References.Add(addinReference.FullPath);
            }

            // Create and prepare the session.
            var session = _engine.CreateSession(host);

            // Load all references.
            var applicationRoot = _environment.ApplicationRoot;
            var assemblies      = new HashSet <Assembly>();

            assemblies.AddRange(_conventions.GetDefaultAssemblies(applicationRoot));

            foreach (var reference in result.References)
            {
                var referencePath = new FilePath(reference);
                if (host.Context.FileSystem.Exist(referencePath))
                {
                    var assembly = _assemblyLoader.Load(referencePath, true);
                    assemblies.Add(assembly);
                }
                else
                {
                    // Add a reference to the session.
                    session.AddReference(referencePath);
                }
            }

            var aliases = new List <ScriptAlias>();

            // Got any assemblies?
            if (assemblies.Count > 0)
            {
                // Find all script aliases.
                var foundAliases = _aliasFinder.FindAliases(assemblies);
                if (foundAliases.Count > 0)
                {
                    aliases.AddRange(foundAliases);
                }

                // Add assembly references to the session.
                foreach (var assembly in assemblies)
                {
                    session.AddReference(assembly);
                }
            }

            // Import all namespaces.
            var namespaces = new HashSet <string>(result.Namespaces, StringComparer.Ordinal);

            namespaces.AddRange(_conventions.GetDefaultNamespaces());
            namespaces.AddRange(aliases.SelectMany(alias => alias.Namespaces));
            foreach (var @namespace in namespaces.OrderBy(ns => ns))
            {
                session.ImportNamespace(@namespace);
            }

            // Execute the script.
            var script = new Script(result.Namespaces, result.Lines, aliases, result.UsingAliases, result.UsingStaticDirectives, result.Defines);

            session.Execute(script);
        }
        /// <summary>
        /// Initializes environment according to the setup information.
        /// </summary>
        private ScriptDomainManager()
        {
            // create local environment for the host:
            _environment = new ScriptEnvironment(this);
            _host = new ScriptHost(_environment);

            // initialize snippets:
            _snippets = new Snippets();
            _pal = null;
        }
 internal void SetLocalHost(IScriptHost host) {
     Contract.Requires(host is ILocalObject, "host", "Host must be a local object.");
     _host = host;
 }
 public RemoteScriptHost(IScriptHost host) {
     Contract.Requires(host is ILocalObject, "host", "Host must be a local object.");
     _host = host;
 }
 internal RemoteScriptHost() {
     // to be provided later:
     _host = null;
 }
Example #36
0
 /// <summary>
 /// Initializes a new host.
 /// </summary>
 protected CodeCakeHost()
 {
     Debug.Assert( _injectedActualHost != null );
     _host = _injectedActualHost;
 }