Exemplo n.º 1
0
        public static string CurrentWorkingDirectoryOrDefault(IProgramContext context, string defaultDirectory = "C:\\Windows\\System32")
        {
            if (context.CurrentProcess.ProcessName != "explorer")
            {
                return(defaultDirectory);
            }

            SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();
            int    handle = context.WindowHandle.ToInt32();
            string path   = null;

            foreach (SHDocVw.InternetExplorer exp in shellWindows)
            {
                if (handle == exp.HWND)
                {
                    path = System.Web.HttpUtility.UrlDecode(exp.LocationURL);
                    if (path.StartsWith("file:///") == true)
                    {
                        path = path.Substring(8);
                    }
                    if (path.Length > 0)
                    {
                        return(path);
                    }
                    else
                    {
                        return(defaultDirectory);
                    }
                }
            }
            path = Path.Combine(Environment.GetEnvironmentVariable("HOMEDRIVE") + "\\", Environment.GetEnvironmentVariable("HOMEPATH").Substring(1), "desktop");
            return(path);
        }
Exemplo n.º 2
0
        public void ShowWindow(IProgramContext context)
        {
            if (IsVisible == true)
            {
                return;
            }
            RECT   position      = context.WindowPosition;
            double ttop          = position.Top + 50;
            double halfwidthdiff = ((position.Right - position.Left) - Width) / 2;
            double tleft         = position.Left + halfwidthdiff;

            if (tleft < 0 && tleft + Width > 0)
            {
                tleft = -(Width + 50);
            }

            if (ttop < 50)
            {
                ttop = 50;
            }
            Left = tleft;
            Top  = ttop;
            Show();
            Activate();
            textbox_input.Focus();
            SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, 3);
        }
Exemplo n.º 3
0
 public override void ThreadInitialize(SafeSharedObjects shared)
 {
     if (compileMode != CompileMode.FILE)
     {
         programContext = shared.Cpu.SwitchToProgramContext(); // only switch the context if executing
     }
     codeParts = new List <CodePart>();
 }
Exemplo n.º 4
0
        public bool IsWaitingForCommand()
        {
            IProgramContext context = ((CPU)Shared.Cpu).GetInterpreterContext();

            // If running from a boot script, there will be no interpreter instructions,
            // only a single OpcodeEOF.  So we check to see if the interpreter is locked,
            // which is a sign that a sub-program is running.
            return(!locked && context.Program[context.InstructionPointer] is OpcodeEOF);
        }
Exemplo n.º 5
0
 /// <summary>
 /// Make a new trigger for insertion into the trigger list, which is a callback from C# code.
 /// </summary>
 /// <param name="context">The ProgramContext under which this Trigger is meant to run.</param>
 /// <param name="entryPoint">Address within the program context where the routine starts that
 /// needs to be called when the trigger needs to be invoked.</param>
 /// <param name="closure">If not-null, this is the closure the trigger should be called with.
 /// If null, the trigger will only reliably be able to see global variables.</param>
 /// <param name="args">list of the arguments to pass in to the function.  Note, the existence of
 /// arguments mandates that this is a callback trigger.</param>
 public TriggerInfo(IProgramContext context, int entryPoint, List <VariableScope> closure, List <Structure> args)
 {
     EntryPoint       = entryPoint;
     IsCSharpCallback = true;
     ReturnValue      = new ScalarIntValue(0);
     CallbackFinished = false;
     Args             = args;
     ContextId        = context.ContextId;
     Closure          = closure;
 }
Exemplo n.º 6
0
 /// <summary>
 /// Make a new UserDelegate given the current state of the CPU and its stack, and
 /// the entry point location of the function to call.
 /// </summary>
 /// <param name="cpu">the CPU on which this program is running.</param>
 /// <param name="context">The IProgramContext in which the entryPoint is stored.  Entry point 27 in the interpreter is not the same as entrypoint 27 in program context.</param>
 /// <param name="entryPoint">instruction address where OpcodeCall should jump to to call the function.</param>
 /// <param name="useClosure">If true, then a snapshot of the current scoping stack, and thus a persistent ref to its variables,
 ///   will be kept in the delegate so it can be called later as a callback with closure.  Set to false if the
 ///   function is only getting called instantly using whatever the scope is at the time of the call.</param>
 public UserDelegate(ICpu cpu, IProgramContext context, int entryPoint, bool useClosure)
 {
     this.cpu = cpu;
     ProgContext = context;
     EntryPoint = entryPoint;
     if (useClosure)
         CaptureClosure();
     else
         Closure = new List<VariableScope>(); // make sure it exists as an empty list so we don't have to have 'if null' checks everwywhere.
 }
Exemplo n.º 7
0
 /// <summary>
 /// Make a new trigger for insertion into the trigger list, which is a callback from C# code.
 /// </summary>
 /// <param name="context">The ProgramContext under which this Trigger is meant to run.</param>
 /// <param name="entryPoint">Address within the program context where the routine starts that
 /// needs to be called when the trigger needs to be invoked.</param>
 /// <param name="instanceCount">If you want it to be allowed to make more than one instance of
 /// a trigger at this EntryPoint, then pass in a call to TriggerInfo.NextInstance here, else
 /// pass in zero to mean that multiple instances from the same entry point aren't allowed.</param>
 /// <param name="closure">If not-null, this is the closure the trigger should be called with.
 /// If null, the trigger will only reliably be able to see global variables.</param>
 /// <param name="args">list of the arguments to pass in to the function.  Note, the existence of
 /// arguments mandates that this is a callback trigger.</param>
 public TriggerInfo(IProgramContext context, int entryPoint, InterruptPriority priority, int instanceCount, List <VariableScope> closure, List <Structure> args)
 {
     EntryPoint       = entryPoint;
     Priority         = priority;
     InstanceCount    = instanceCount;
     IsCSharpCallback = true;
     ReturnValue      = new ScalarIntValue(0);
     CallbackFinished = false;
     Args             = args ?? new List <Structure>();
     ContextId        = context.ContextId;
     Closure          = closure;
 }
Exemplo n.º 8
0
        private void OnHotKeyPressed(IHotKey sender, int hotkeyid)
        {
            if (window.IsVisible)
            {
                window.HideWindow();
                return;
            }
            pool.EnterScope();
            IProgramContext context = services.GetService <IProgramContext>();

            window.ClearInput();
            window.ShowWindow(context);
        }
Exemplo n.º 9
0
 /// <summary>
 /// Make a new UserDelegate given the current state of the CPU and its stack, and
 /// the entry point location of the function to call.
 /// </summary>
 /// <param name="cpu">the CPU on which this program is running.</param>
 /// <param name="context">The IProgramContext in which the entryPoint is stored.  Entry point 27 in the interpreter is not the same as entrypoint 27 in program context.</param>
 /// <param name="entryPoint">instruction address where OpcodeCall should jump to to call the function.</param>
 /// <param name="useClosure">If true, then a snapshot of the current scoping stack, and thus a persistent ref to its variables,
 ///   will be kept in the delegate so it can be called later as a callback with closure.  Set to false if the
 ///   function is only getting called instantly using whatever the scope is at the time of the call.</param>
 public UserDelegate(ICpu cpu, IProgramContext context, int entryPoint, bool useClosure) :
     base(cpu)
 {
     ProgContext = context;
     EntryPoint  = entryPoint;
     if (useClosure)
     {
         CaptureClosure();
     }
     if (Cpu != null)
     {
         Cpu.AddPopContextNotifyee(this);
     }
 }
Exemplo n.º 10
0
 /// <summary>
 /// Make a new UserDelegate given the current state of the CPU and its stack, and
 /// the entry point location of the function to call.
 /// </summary>
 /// <param name="cpu">the CPU on which this program is running.</param>
 /// <param name="context">The IProgramContext in which the entryPoint is stored.  Entry point 27 in the interpreter is not the same as entrypoint 27 in program context.</param>
 /// <param name="entryPoint">instruction address where OpcodeCall should jump to to call the function.</param>
 /// <param name="useClosure">If true, then a snapshot of the current scoping stack, and thus a persistent ref to its variables,
 ///   will be kept in the delegate so it can be called later as a callback with closure.  Set to false if the
 ///   function is only getting called instantly using whatever the scope is at the time of the call.</param>
 public UserDelegate(ICpu cpu, IProgramContext context, int entryPoint, bool useClosure)
 {
     this.cpu    = cpu;
     ProgContext = context;
     EntryPoint  = entryPoint;
     if (useClosure)
     {
         CaptureClosure();
     }
     else
     {
         Closure = new List <VariableScope>(); // make sure it exists as an empty list so we don't have to have 'if null' checks everwywhere.
     }
 }
Exemplo n.º 11
0
        public void Invoke(IProgramContext progContext, ILogger runnerLogger, bool admin = false)
        {
            ProcessStartInfo psi = new ProcessStartInfo(exeCommand, exeArgs);

            psi.WorkingDirectory = Helper.CurrentWorkingDirectoryOrDefault(progContext);
            if (admin)
            {
                psi.Verb = "runas";
            }
            try
            {
                Process.Start(psi);
            }
            catch (Exception ex)
            {
                runnerLogger.LogExceptionAsync(ex);
            }
        }
Exemplo n.º 12
0
 /// <summary>
 /// Cleans up the references I hold (to allow GC to  happen on them) because I
 /// know I can never be called again at this point.
 /// (Note, this is called because of Cpu.AddPopContextNotifyee()).
 /// </summary>
 public bool OnPopContext(IProgramContext context)
 {
     // Just in case we ever add more contexts later than just interpreter
     // and program, we want to be sure we don't invoke the cleanup code
     // unless it's *our* program context (the one this UserDelegate is from)
     // that's being removed.  That's the reason for these checks here:
     if (weakProgContext.IsAlive)
     {
         if (weakProgContext.Target == context)
         {
             DeadCleanup();
             return(false);
         }
         return(true); // act like this never fired off.  It's not for our program context.
     }
     // If we already orphaned our program context for some other reason (I don't
     // know what that would be), then at least clean up what's still left:
     DeadCleanup();
     return(false);
 }
Exemplo n.º 13
0
        public IProgramContext CreateProgramContext(ContextFeatures contextFeatures, IProgram program, IExecutor executor)
        {
            if (contextFeatures == null)
            {
                throw new ArgumentNullException("contextFeatures");
            }
            if (executor == null)
            {
                throw new ArgumentNullException("executor");
            }

            IProgramContext context = (IProgramContext)_CreateContext(ContextTargetType.Program, contextFeatures);

            if (context != null)
            {
                context.Executor = executor;
                context.Program  = program;
                _AddContext(context);
            }
            return(context);
        }
        public Task Invoke(IQuickContext context, IProgramContext program, Func <Task> next)
        {
            if (!Config.EnableSearch)
            {
                return(next());
            }

            bool isChrome = program.CurrentProcess.ProcessName == "chrome";

            if (isChrome)
            {
                string search = context.Command.Raw.Trim().ToLower();
                if (search.Length <= 0)
                {
                    return(next());
                }

                Regex searchReg = null;
                try
                {
                    searchReg = new Regex(search);
                }
                catch
                {
                    SearchPatternErrorAction.Update("搜索模式错误", search);
                    context.AddAction(SearchPatternErrorAction);
                }
                if (searchReg != null)
                {
                    List <Bookmark> bookmarks = new List <Bookmark>();
                    SearchFolder(Bookmarks.BookmarkBar, searchReg, bookmarks);
                    SearchFolder(Bookmarks.Others, searchReg, bookmarks);
                    foreach (Bookmark bookmark in bookmarks)
                    {
                        context.AddAction(new BookmarkAction(bookmark.Name, bookmark.Url));
                    }
                }
            }
            return(next());
        }
Exemplo n.º 15
0
        public void ShowWindow(IProgramContext context)
        {
            if (IsVisible == true)
            {
                return;
            }
            System.Windows.Forms.Screen[] screens = System.Windows.Forms.Screen.AllScreens;
            List <uint> dpis        = ScreenHelpers.GetScreenDpis(screens);
            RECT        position    = context.WindowPosition;
            double      ttop        = position.Top + 50;
            double      windowWidth = ActualWidth;

            if (windowWidth <= 0)
            {
                windowWidth = Width;
            }
            uint scale = dpis[0] / 96;

            windowWidth *= scale;
            double halfwidthdiff = ((position.Right - position.Left) - windowWidth) / 2;
            double tleft         = position.Left + halfwidthdiff;

            if (tleft < 0 && tleft + windowWidth > 0)
            {
                tleft = -(windowWidth + 50);
            }

            if (ttop < 50)
            {
                ttop = 50;
            }
            Left = tleft / scale;
            Top  = ttop / scale;
            Show();
            Activate();
            textbox_input.Focus();
            SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, 3);
        }
Exemplo n.º 16
0
        public void Invoke(IProgramContext progContext, ILogger runnerLogger, ICommand command, bool admin = false, bool a = false)
        {
            admin = admin || a || defaultAsAdmin;
            string procname = RunCommand;

            if (commandPath.Length > 0)
            {
                procname = commandPath;
            }
            ProcessStartInfo psi = new ProcessStartInfo(procname);

            if (arguments != null)
            {
                psi.Arguments = arguments;
            }

            if (admin)
            {
                psi.Verb = "runas";
            }
            if (workingDirectory == null)
            {
                psi.WorkingDirectory = Helper.CurrentWorkingDirectoryOrDefault(progContext);
            }
            else
            {
                psi.WorkingDirectory = workingDirectory;
            }
            try
            {
                Process.Start(psi);
            }
            catch (Exception ex)
            {
                runnerLogger.LogExceptionAsync(ex);
            }
        }
Exemplo n.º 17
0
 public ProgramContextEventArgs(IProgramContext programContext)
 {
     ProgramContext = programContext;
 }
Exemplo n.º 18
0
 public ProgramContextEventArgs(IProgramContext programContext)
 {
     ProgramContext = programContext;
 }
Exemplo n.º 19
0
        private bool ExecuteInstruction(IProgramContext context)
        {
            const bool DEBUG_EACH_OPCODE = false;

            Opcode opcode = context.Program[context.InstructionPointer];

            if (DEBUG_EACH_OPCODE)
            {
                executeLog.Append(String.Format("Executing Opcode {0:0000}/{1:0000} {2} {3}\n",
                                                context.InstructionPointer, context.Program.Count, opcode.Label, opcode.ToString()));
            }
            try
            {
                opcode.AbortContext = false;
                opcode.AbortProgram = false;
                opcode.Execute(this);
                if (opcode.AbortProgram)
                {
                    BreakExecution(false);
                    SafeHouse.Logger.Log("Execution Broken");
                    return false;
                }
                else if (opcode.AbortContext)
                {
                    return false;
                }
                else
                {
                    int prevPointer = context.InstructionPointer;
                    context.InstructionPointer += opcode.DeltaInstructionPointer;
                    if (context.InstructionPointer < 0 || context.InstructionPointer >= context.Program.Count())
                    {
                        throw new KOSBadJumpException(
                            context.InstructionPointer, String.Format("after executing {0:0000} {1} {2}", prevPointer, opcode.Label, opcode));
                    }
                    return true;
                }
            }
            catch (Exception)
            {
                // exception will skip the normal printing of the log buffer,
                // so print what we have so far before throwing up the exception:
                if (executeLog.Length > 0)
                    SafeHouse.Logger.Log(executeLog.ToString());
                throw;
            }
        }
Exemplo n.º 20
0
Arquivo: CPU.cs Projeto: CalebJ2/KOS
        private bool ExecuteInstruction(IProgramContext context, bool doProfiling)
        {
            Opcode opcode = context.Program[context.InstructionPointer];

            if (SafeHouse.Config.DebugEachOpcode)
            {
                executeLog.Append(string.Format("Executing Opcode {0:0000}/{1:0000} {2} {3}\n", context.InstructionPointer, context.Program.Count, opcode.Label, opcode));
                executeLog.Append(string.Format("Prior to exeucting, stack looks like this:\n{0}\n", DumpStack()));
            }
            try
            {
                opcode.AbortContext = false;
                opcode.AbortProgram = false;

                opcode.Execute(this);

                if (doProfiling)
                {
                    // This will count *all* the time between the end of the prev instruction and now:
                    instructionWatch.Stop();
                    opcode.ProfileTicksElapsed += instructionWatch.ElapsedTicks;
                    opcode.ProfileExecutionCount++;

                    // start the *next* instruction's timer right after this instruction ended
                    instructionWatch.Reset();
                    instructionWatch.Start();
                }

                if (opcode.AbortProgram)
                {
                    BreakExecution(false);
                    SafeHouse.Logger.Log("Execution Broken");
                    return false;
                }

                if (opcode.AbortContext)
                {
                    return false;
                }

                int prevPointer = context.InstructionPointer;
                context.InstructionPointer += opcode.DeltaInstructionPointer;
                if (context.InstructionPointer < 0 || context.InstructionPointer >= context.Program.Count)
                {
                    throw new KOSBadJumpException(
                        context.InstructionPointer, string.Format("after executing {0:0000} {1} {2}", prevPointer, opcode.Label, opcode));
                }
                return true;
            }
            catch (Exception)
            {
                // exception will skip the normal printing of the log buffer,
                // so print what we have so far before throwing up the exception:
                if (executeLog.Length > 0)
                    SafeHouse.Logger.Log(executeLog.ToString());
                throw;
            }
        }
Exemplo n.º 21
0
 public IProgramContext RebuildContext()
 {
     context = services.CreateInstance <ProgramContext>();
     return(context);
 }