Пример #1
0
        static int Main(string[] args)
        {
            try
            {
                // Disable fatal error message popups by SetErrorMode(SEM_FAILCRITICALERRORS)
                try
                {
                    SetErrorMode(1);
                }
                catch (System.EntryPointNotFoundException)
                {
                }

                AppDomainLoader.progress("Main: Starting");
                AppDomain.CurrentDomain.UnhandledException += (a, b) => { AppDomainLoader.progress("Main: !!!" + b.IsTerminating); };
                int exitCode = AppDomainLoader.Loader(args) ?? MainWithoutContext(args);
                AppDomainLoader.progress("Main: Exiting with exit code " + exitCode);
                return(exitCode);
            }
            catch (System.Security.SecurityException)
            {
                Console.Error.WriteLine("Code security exception. Please copy XSharper to a local hard drive and try again.");
                return(-3);
            }
        }
Пример #2
0
        static public int MainWithoutContext(string[] args)
        {
            AppDomainLoader.progress("MainWithoutContext: Entering");
            ScriptContext context = new ScriptContext(AppDomainLoader.ResourceAssembly);

            return(MainWithContext(context, args));
        }
Пример #3
0
        private static int restartAsAdmin(ScriptContext context, string[] args, bool hidden)
        {
            context.WriteLine(OutputType.Info, "** Administrative privileges are required to run this script.\n** Please confirm to continue.");
            if (context.IsSet(xs.testElevation))
            {
                List <string> f = new List <string>();
                foreach (string s in args)
                {
                    if (string.Compare(s, xs.testElevation.Replace("xs.", "//"), StringComparison.OrdinalIgnoreCase) != 0)
                    {
                        f.Add(s);
                    }
                }
                args = f.ToArray();
            }

            AppDomainLoader.progress("MainWithContext: About to restart with CmdLine=" + string.Join(" ", args));


            int n = AppDomainLoader.RunWithElevatedContext(
                delegate(ScriptContext ctx)
            {
                ScriptContextScope.DefaultContext = ctx;
                try
                {
                    if (!ctx.IsAdministrator)
                    {
                        throw new ScriptRuntimeException("Administrator privileges are required");
                    }
                    return(MainWithContext(ctx, args));
                }
                finally
                {
                    ScriptContextScope.DefaultContext = null;
                }
            }, hidden);

            if (n == -1)
            {
                throw new ScriptRuntimeException("An error occured while granting administrative privileges.");
            }
            if (n != 0)
            {
                throw new ScriptRuntimeException("An error occured during script execution.");
            }

            return(0);
        }
Пример #4
0
        private static Script execGenerator(ScriptContext context, string c, string prefix, string suffix)
        {
            Script script = createEmptyScript(context, "generated");

            if (context.Compiler.DefaultNETVersion >= new Version(3, 5))
            {
                // Yeah, I know it's deprecated, and it's best to use full assembly names, but
                // but I don't really want to scan GAC myself
#pragma warning disable 618
                context.AddAssembly(Assembly.LoadWithPartialName("System.Xml.Linq"), false);
                context.AddAssembly(Assembly.LoadWithPartialName("System.Core"), false);
#pragma warning restore 618
            }
            script.Add(new Rem {
                Text = "----- Generated from command line -------" + Environment.NewLine + "\t" + c + Environment.NewLine + "\t ------------"
            });
            script.Parameters.Add(new CommandLineParameter("arg", CommandLineValueCount.Multiple)
            {
                Last = true, Default = "", Required = false
            });
            script.UnknownSwitches = true;

            c = c.Trim();
            if (c.StartsWith("\"", StringComparison.Ordinal) && c.EndsWith("\"", StringComparison.Ordinal))
            {
                c = c.Substring(1, c.Length - 2);
            }
            if (c == "-")
            {
                c = Console.In.ReadToEnd();
            }
            if (c.StartsWith("="))
            {
                prefix = "=" + prefix;
                c      = "${=" + c.Substring(1) + "}";
            }
            if (prefix != null || suffix != null)
            {
                c = prefix + Environment.NewLine + c + Environment.NewLine + suffix;
            }
            c = c.Replace("`", "\"");

            AppDomainLoader.progress("Read script begin");
            using (new ScriptContextScope(context))
                script.Load(c);
            AppDomainLoader.progress("Read script end");
            return(script);
        }
Пример #5
0
 private static Script loadScript(string location, ScriptContext context)
 {
     AppDomainLoader.progress("MainWithContext: Parsing XML");
     try
     {
         byte[] data;
         bool   validate = context.GetBool(xs.validate, false);
         if (location == ".")
         {
             location = loadFromConfig(out data);
             return(context.LoadScript(new MemoryStream(data), location, validate));
         }
         else
         {
             return(context.LoadScript(location, validate));
         }
     }
     finally
     {
         AppDomainLoader.progress("MainWithContext: Parsing completed");
     }
 }
Пример #6
0
        static int MainWithContext(ScriptContext context, string[] args)
        {
            CommandLineParameters xsParams = getXsParams();
            int exitCode = 0;

            ConsoleRedirector redir = null;

            AppDomainLoader.progress("MainWithContext: Entering --------------------");
            bool utf8 = false;

            foreach (string arg in args)
            {
                if (arg.Equals(xs.utf8.Replace("xs.", "//"), StringComparison.OrdinalIgnoreCase))
                {
                    utf8 = true;
                }
            }
            using (ConsoleWithColors cout = new ConsoleWithColors(Environment.GetEnvironmentVariable("XSH_COLORS"), utf8))
                using (CtrlCInterceptor ctrl = new CtrlCInterceptor())
                {
                    context.Output += cout.OnOutput;
                    ctrl.Output     = context.Error;
                    ctrl.Abort     += delegate { context.Abort(); };

                    Stopwatch w = Stopwatch.StartNew();
                    try
                    {
                        // Parse arguments
                        var usage = new UsageGenerator()
                        {
                            Options = UsageOptions.None
                        };
                        xsParams.Parse(context, args, false);
                        setOutputOptions(context, cout);

                        if (context.IsSet(xs.path))
                        {
                            context.ScriptPath = context.GetString(xs.path);
                        }

                        // Load references
                        List <IScriptAction> preScript = getCommandlineReferences(context);

                        // Print help
                        if (args.Length == 0 || context.IsSet(xs.help))
                        {
                            loadReferences(context, preScript);
                            exitCode = HelpHelper.Help(context, usage, xsParams);
                            goto end;
                        }

                        // Handle upgrade
                        if (context.GetBool(xs.upgrade, false))
                        {
                            return(upgrade(context));
                        }
                        if (context.IsSet(xs.updateStage))
                        {
                            return(updateStage(context, context.GetStringArray(xs.updateStage)));
                        }

                        AppDomainLoader.progress("MainWithContext: Processing options");
                        // Process the remaining options
                        context.Compiler.AddRequireAdmin(Utils.To <RequireAdminMode>(context.GetStr(xs.requireAdmin, RequireAdminMode.User.ToString())));

                        if (context.IsSet(xs.codeout))
                        {
                            context.CodeOutputDirectory = Path.GetFullPath(context.GetString(xs.codeout));
                        }
                        if (context.IsSet(xs.genconfig) || context.IsSet(xs.gensample))
                        {
                            genDemoConfig(cout, context);
                        }
                        if (context.IsSet(xs.forcenet20))
                        {
                            context.Compiler.DefaultNETVersion = new Version(2, 0);
                        }

                        AppDomainLoader.progress("MainWithContext: Processing options, continuing");

                        List <string> filteredArgs = new List <string>();
                        if (context.IsSet(xs.scriptargs))
                        {
                            filteredArgs.AddRange(context.GetStringArray(xs.scriptargs));
                        }


                        // Run utilities, like //download etc
                        Script script     = getInlineScript(context, filteredArgs);
                        string scriptName = context.GetString(xs.script, null);
                        if (script == null)
                        {
                            // Load the script
                            if (scriptName == "/?" || scriptName == "-?")
                            {
                                for (int i = 0; i < args.Length; ++i)
                                {
                                    if (args[i] == "/?" || args[i] == "-?")
                                    {
                                        if (i != args.Length - 1)
                                        {
                                            context[xs.help] = args[i + 1];
                                        }
                                        break;
                                    }
                                }
                                loadReferences(context, preScript);
                                return(HelpHelper.Help(context, usage, xsParams));
                            }
                            if (scriptName != null)
                            {
                                AppDomainLoader.progress("MainWithContext: Loading script " + scriptName);
                                script = loadScript(scriptName, context);
                                AppDomainLoader.progress("MainWithContext: Loading completed");
                            }
                        }

                        AppDomainLoader.progress("MainWithContext: About to initialize");
                        // Attach script
                        if (script != null)
                        {
                            // Insert pre-script before the script body
                            int n = 0;
                            foreach (var list in preScript)
                            {
                                script.Items.Insert(n++, list);
                            }

                            AppDomainLoader.BaseDirectory = script.DirectoryName;

                            RequireAdminMode mode = context.Compiler.RequireAdmin;
                            if ((!context.IsAdministrator || context.GetBool(xs.testElevation, false)) && !isCodeGeneration(context) && mode != RequireAdminMode.User)
                            {
                                return(restartAsAdmin(context, args, mode == RequireAdminMode.Hidden && !(context.GetBool(xs.testElevation, false))));
                            }

                            AppDomainLoader.progress("MainWithContext: Before script initialization");
                            if (isCodeGeneration(context))
                            {
                                if (!context.EnableCodePrecompilation && (context.IsSet(xs.genexe) ||
                                                                          context.IsSet(xs.genwinexe) ||
                                                                          context.IsSet(xs.genlibrary) ||
                                                                          context.IsSet(xs.gencs)))
                                {
                                    throw new ParsingException("One of the loaded scripts has precompilation disabled. Executable cannot be generated from this script.");
                                }
                                context.EnableCodePrecompilation = false;
                            }
                            ctrl.IgnoreCtrlC = script.IgnoreCtrlC;
                            ctrl.AbortDelay  = Utils.ToTimeSpan(script.AbortDelay) ?? ctrl.AbortDelay;
                            ctrl.ExitDelay   = Utils.ToTimeSpan(script.ExitDelay) ?? ctrl.ExitDelay;
                            context.Initialize(script);

                            AppDomainLoader.progress("MainWithContext: Script initialization completed");
                        }

                        // After precompilation we're ready to write .exe, if requested
                        if (isCodeGeneration(context))
                        {
                            doCodeGeneration(context, script);
                        }
                        else if (script != null)
                        {
                            // Run the script
                            AppDomainLoader.progress("MainWithContext: Before script execution");
                            redir = new ConsoleRedirector(context);
                            try
                            {
                                object r = context.ExecuteScript(script, filteredArgs.ToArray(), CallIsolation.High);
                                if (r != null)
                                {
                                    int.TryParse(r.ToString(), out exitCode);
                                }
                            }
                            finally
                            {
                                ctrl.KillAbortTimer();
                                redir.Dispose();
                                redir = null;
                            }

                            AppDomainLoader.progress("MainWithContext: Script execution completed");
                        }
                    }
                    catch (ThreadAbortException ae)
                    {
                        AppDomainLoader.progress("MainWithContext: ThreadAbortException is being aborted");
                        resetAbort(context);
                        context.WriteException(ae);
                        exitCode = -1;
                    }
                    catch (ScriptTerminateException te)
                    {
                        exitCode = te.ExitCode;
                        resetAbort(context);
                        if (te.InnerException != null)
                        {
                            context.WriteException(te.InnerException);
                            AppDomainLoader.progress("MainWithContext: " + te.InnerException);
                        }
                        AppDomainLoader.progress("MainWithContext: Terminating with exit code " + exitCode);
                    }
                    catch (Exception e)
                    {
                        exitCode = -1;
                        resetAbort(context);
                        context.WriteException(e);
                        AppDomainLoader.progress("MainWithContext: " + e);
                    }
                    finally
                    {
                        resetAbort(context);
                        AppDomainLoader.BaseDirectory = null;
                    }
end:
                    // Display how long did it take
                    w.Stop();
                    if (context.GetBool(xs.wait, false))
                    {
                        cout.WriteLine(OutputType.Info, string.Format("Completed in {0} with exit code={1}. Press Enter to close...", w.Elapsed, exitCode));
                        Console.ReadLine();
                    }
                }
            AppDomainLoader.progress("MainWithContext: Exiting with code " + exitCode);
            return(exitCode);
        }