예제 #1
0
        public static List<IXRule> compileXRules(O2Thread.FuncVoidT1<string> currentTask, O2Thread.FuncVoidT1<int> numberOfStepsToPerform, O2Thread.FuncVoid onStepEvent)
        {
            var compiledXRulesFiles = getCompiledXRulesAssemblies(currentTask,numberOfStepsToPerform, onStepEvent);

            currentTask("Moving XRules and its dependencies");

            numberOfStepsToPerform(compiledXRulesFiles.Count * 2);

            //var pathToAppDomainWithXRulesAssemblies = populateDirectoryWithAllDependencies(compiledXRulesFiles, onStepEvent);
            // dont add the dependencies since they are creating a prob with the cmd line tool
            Files.deleteAllFilesFromDir(XRules_Config.PathTo_XRulesCompiledDlls);
            foreach (var file in compiledXRulesFiles)
                Files.Copy(file, XRules_Config.PathTo_XRulesCompiledDlls);

            var pathToAppDomainWithXRulesAssemblies = XRules_Config.PathTo_XRulesCompiledDlls;

            // special case where we don't need the O2_XRules_Database.dll file in the )CompiledDlls folder
              //  var xRulesDatabaseOriginalDll = System.IO.Path.Combine(pathToAppDomainWithXRulesAssemblies, "O2_XRules_Database.dll");
              //  if (System.IO.File.Exists(xRulesDatabaseOriginalDll))
              //      System.IO.File.Delete(xRulesDatabaseOriginalDll);

            var xRulesAssemblies = new List<string>();
            foreach (var originalDll in compiledXRulesFiles)
            {
                var dllInXRulesCompiledDllFolder = originalDll.Replace(System.IO.Path.GetDirectoryName(originalDll),
                                                                       pathToAppDomainWithXRulesAssemblies);
                xRulesAssemblies.Add(dllInXRulesCompiledDllFolder);
            }
            return loadXRules(xRulesAssemblies, currentTask, numberOfStepsToPerform, onStepEvent);
        }
예제 #2
0
 public static void compileXRules(O2Thread.FuncVoidT1<List<IXRule>> onCompilation, O2Thread.FuncVoidT1<string> currentTask, O2Thread.FuncVoidT1<int> numberOfStepsToPerform, O2Thread.FuncVoid onStepEvent)
 {
     O2Thread.mtaThread(
         () =>
             {
                 var xRules = compileXRules(currentTask,numberOfStepsToPerform, onStepEvent);
                 onCompilation(xRules);
             });
 }
 private void saveCurrentFilter(string typeOfRule, string signatureFilter, O2Thread.FuncVoid onComplete)
 {
     O2Thread.mtaThread(
         () =>
             {                        
                 var o2RulePack = new O2RulePack("All loaded rules", rulesToShow);
                 var savedFile = O2RulePackUtils.saveRulePack(typeOfRule, signatureFilter, o2RulePack);
                 DI.log.showMessageBox("Current filtered rules saved to: " + savedFile);
                 onComplete();
             });
 }
 private void executeO2DebugAction(O2Thread.FuncThread actionToExecute)
 {
     var threadForAction = actionToExecute();
     // since we cant touch the current thread, lets start a new one that can wait for threadForAction
     O2Thread.mtaThread(() =>
                            {
                                if (threadForAction != null && threadForAction.IsAlive)
                                     threadForAction.Join();
                                // once the threadForAction is complete we can update the controls
                                updateGuiProjectStartOrAttachControls();
                            });
     
 }
예제 #5
0
 public static void backupGac(string zipFileToSaveGacContents)
 {
     O2Thread.mtaThread(
         () =>
     {
         PublicDI.log.info("Started unzip process of Gac Folder");
         var timer = new O2Timer("Gac Backup").start();
         new zipUtils().zipFolder(DI.PathToGac, zipFileToSaveGacContents);
         var logMessage = String.Format("Contents of \n\n\t{0}\n\n saved to \n\n\t{1}\n\n ", DI.PathToGac, zipFileToSaveGacContents);
         timer.stop();
         PublicDI.log.info(logMessage);
         PublicDI.log.showMessageBox(logMessage);
     });
 }
예제 #6
0
파일: O2MDbg.cs 프로젝트: pusp/o2platform
 public void startMDbg(O2Thread.FuncVoid onShellStart)
 {
     if (shell == null)
         O2Thread.mtaThread(() =>
         {
             setMDbgEventsMessagesCallbacks();
             shell = new MDbgShell();                    
             shell.Start(new string[0]);
             setO2MDbgShellCallbacks();
             o2MdbgIsReady.Set();
             if (onShellStart != null)
                 onShellStart();
         });
 }
예제 #7
0
        /// <summary>
        /// ASync execution of code on the the Control thread unless we are on the correct thread
        /// and the execution will be sync
        /// </summary>
        public static void invokeOnThread(this Control control, O2Thread.FuncVoid codeToInvoke)
        {
            try
            {
                if (control.InvokeRequired)
                    control.Invoke(new EventHandler((sender, e) => codeToInvoke()));     
                else                                   
                    codeToInvoke();
            }

            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);                
            }
        }
예제 #8
0
 public static void nTimesWithDelay(int count, int delay, bool runInMtaThread, MethodInvoker methodInvoker)
 {
     if (runInMtaThread)
     {
         O2Thread.mtaThread(() => nTimesWithDelay(count, delay, false, methodInvoker));
     }
     else
     {
         for (int i = 0; i < count; i++)
         {
             methodInvoker();
             Processes.Sleep(delay);
         }
     }
 }
 public void editRule(IO2Rule ruleToEdit, O2Thread.FuncVoidT1<IO2Rule> _onSave)
 {
     this.invokeOnThread(
         () =>
             {
                 laDataSaved.Visible = false;
                 btSaveRuleChanges.Enabled = true;
                 btSaveChangesToAllRules.Enabled = false;
                 laUnsavedChanges.Visible = false;
                 laNumberOfRulesLoaded.Text = "1 rule loaded";
                 onSave = _onSave;
                 o2LoadedRule = ruleToEdit;
                 loadRuleIntoEditor(o2LoadedRule);
                 o2LoadedRules.Clear();
                 o2LoadedRules.Add(o2LoadedRule);       
             });
 }
예제 #10
0
 public static List<String> compileAllFilesIndividually(List<String> filesToCompile, O2Thread.FuncVoidT1<string> currentTask, O2Thread.FuncVoidT1<int> numberOfStepsToPerform, O2Thread.FuncVoid onStepEvent)
 {
     currentTask("Compiling all rules individualy (one file at the time)");
     numberOfStepsToPerform(filesToCompile.Count);
     var compileEngine = new CompileEngine();
     PublicDI.log.info("Compiling All XRules source code files ONE at the time");
     var results = new List<String>();
     foreach (var fileToCompile in filesToCompile)
     {
         var assembly = compileEngine.compileSourceFile(fileToCompile);
         if (assembly != null)
             results.Add(assembly.Location);
         else
             PublicDI.log.error("In XRules_Execution.compileAllFilesIndividually, could not compile file: {0}", fileToCompile);
         onStepEvent();
     }
     return results;
 }
예제 #11
0
파일: O2MDbg.cs 프로젝트: pusp/o2platform
        public O2MDbg(O2Thread.FuncVoid onShellStart)            
        {
            if (DI.o2MDbg != null)
                DI.log.error("DI.o2MDbg != null, and we should only have one instance of the O2MDbg per AppDomain, so this will override that one (and some data might be lost)");
            DI.o2MDbg = this;                              
            
            sessionData = new O2MDbgSessionData(this);
            BreakPoints = new O2MDbgBreakPoint(this);
            LogInternalMDbgMessage = false;
            LogCommandExecutionMessage = true;
            AnimateOnStepEvent = false;
            AutoContinueOnBreakPointEvent = false;
            LogBreakpointEvent = true;
            debugggerActive = false;
            debugggerRunning = false;

            startMDbg(onShellStart);   
        }
        public Thread executeFilter(AvailableFilters filterToApply, bool addFindingsWithNoMatches, O2Thread.FuncVoidT1<List<IO2Finding>> onCompletion)
        {
	        var o2TargetO2Findings = findingsViewerSourceFindings.currentO2Findings;
	        var o2RulesToUse = rulePackViewer.currentO2RulePack.o2Rules;
            return O2Thread.mtaThread(
                () =>
                    {
                        List<IO2Finding> mappedFidings = null ;
                        List<IO2Rule> o2Rules = o2RulesToUse.Cast<IO2Rule>().ToList();
                        switch (filterToApply)
                        {
                            case AvailableFilters.BasicSinksMapping:
                                DI.log.info("Executing filter: BasicSinksMapping");
                                mappedFidings = Filter_BasicSinksMapping.applyFilter(o2TargetO2Findings, o2Rules);
                                break;
                            case AvailableFilters.CreateAllPartialTraces:
                                DI.log.info("Executing filter: CreateAllPartialTraces");
                                mappedFidings = Filter_CreateAllPartialTraces.applyFilter(o2TargetO2Findings, o2Rules);
                                break;
                            case AvailableFilters.MapSinksToAllTraces:
                                DI.log.info("Executing filter: MapSinksToAllTraces");
                                mappedFidings = Filter_MapSinksToAllTraces.applyFilter(o2TargetO2Findings, o2Rules, addFindingsWithNoMatches);
                                break;
                            case AvailableFilters.MapSourcesToAllTraces:
                                DI.log.info("Executing filter: MapSourcesToAllTraces");
                                mappedFidings = Filter_MapSourcesToAllTraces.applyFilter(o2TargetO2Findings, o2Rules);
                                break;       
                            case AvailableFilters.MapFirstSourcesThenSinksToAllTraces:
                                DI.log.info("Executing filter: MapFirstSourcesThenSinksToAllTraces which has two steps");
                                DI.log.info("Step 1): MapFirstSourcesThenSinksToAllTraces->MapSourcesToAllTraces");
                                var sourceMappings = Filter_MapSourcesToAllTraces.applyFilter(o2TargetO2Findings, o2Rules);
                                DI.log.info("Step 2): MapFirstSourcesThenSinksToAllTraces->MapSinksToAllTraces");
                                mappedFidings = Filter_MapSinksToAllTraces.applyFilter(sourceMappings, o2Rules, addFindingsWithNoMatches);
                                break;                                          
                        }
                        if (onCompletion != null)
                            onCompletion(mappedFidings);
                    });
        }
예제 #13
0
        public void loadFiles(List<String> lFilesToLoad, O2Thread.FuncVoidT1<int> onPartialLoad)
        {
            int iFilesProcessed = 0;
            foreach (String sFileToLoad in lFilesToLoad)
            {
                loadFile(sFileToLoad);
                if (iFilesProcessed++ % 100 == 0)
                {
                    DI.log.info("Processed files: {0} /{1}", iFilesProcessed, lFilesToLoad.Count);
                    if (onPartialLoad != null)
                        onPartialLoad(iFilesProcessed);
                }
            }

            // some file stats

            DI.log.debug("Number of Files Currently Loaded: {0}", dLoadedFilesCache.Keys.Count);
            int iLinesOfCode = 0;
            //int iChars = 0;
            foreach (var lsLines in dLoadedFilesCache.Values)
                iLinesOfCode += lsLines.Count;
            DI.log.debug("Number of Lines of Code Currently Loaded: {0}", iLinesOfCode);
        }
예제 #14
0
 public static void addControlToMenu(string menuItemName, O2Thread.FuncVoid onMenuItemClick)
 {
     DI.o2GuiWithDockPanel.addToLoadedO2ModulesMenu(menuItemName, onMenuItemClick);
 }
예제 #15
0
        public static List<IXRule> loadXRules(List<string>xRulesAssemblies, O2Thread.FuncVoidT1<string> currentTask, O2Thread.FuncVoidT1<int> numberOfStepsToPerform, O2Thread.FuncVoid onStepEvent)
        {
            if (currentTask != null)
                currentTask("Loading XRules");

            var xRules = new List<IXRule>();
            foreach(var xRuleAssembly in xRulesAssemblies)
            {
                var assembly = PublicDI.reflection.getAssembly(xRuleAssembly);
                if (assembly != null)
                    xRules.AddRange(createXRulesFromAssembly(assembly));
                if (onStepEvent != null)
                    onStepEvent();
            }
            if (currentTask != null)
            currentTask("XRules Loading Complete");
            return xRules;
        }
예제 #16
0
        public static void createAssessessmentFileWithJoinnedTraces(
            string textFilter, Dictionary<string, O2TraceBlock_OunceV6> _dRawData, ICirData _cdCirData,
            Dictionary<string, O2TraceBlock_OunceV6> _dO2TraceBlock, bool bOnlyProcessTracesWithNoCallers,
            string targetFolder, string fileNamePrefix, bool bCreateFileWithAllTraces,
            bool bCreateFileWithUniqueTraces, bool bDropDuplicateSmartTraces, bool bIgnoreRootCallInvocation,
            O2Thread.FuncVoidT1<List<TreeNode>> viewNormalizedTraces, Func<string, string> onCompletion)
        {
            O2Thread.mtaThread(
                () =>
                    {
                        DI.log.debug("\n\n\ncreateAssessessmentFileWithJoinnedTraces: step 1 - createListOfNormalizedTraces\n\n\n");
                        var ltnNormalizedTraces = createListOfNormalizedTraces(textFilter, _dRawData, _cdCirData, _dO2TraceBlock,bOnlyProcessTracesWithNoCallers);

                        if (ltnNormalizedTraces.Count ==0)
                        {
                            DI.log.error("There were no normalized traces, aborting");
                            onCompletion("");
                            return;
                        }

                        if (viewNormalizedTraces != null)
                            viewNormalizedTraces(ltnNormalizedTraces);

                        DI.log.debug("\n\n\ncreateAssessessmentFileWithJoinnedTraces: step 2 - createSavedAssessmentSearchObjectFromNormalizedTraces\n\n\n");

                        var sasSavedAssessmentSearch = createSavedAssessmentSearchObjectFromNormalizedTraces(ltnNormalizedTraces);

                        DI.log.debug("\n\n\ncreateAssessessmentFileWithJoinnedTraces: step 3 - createAssessmentFileFromSavedAssessmentSearchObject\n\n\n");

                        var sAssessmentFile = createAssessmentFileFromSavedAssessmentSearchObject(
                            sasSavedAssessmentSearch, targetFolder, fileNamePrefix, bCreateFileWithAllTraces,
                            bCreateFileWithUniqueTraces, bDropDuplicateSmartTraces, bIgnoreRootCallInvocation);

                        DI.log.debug("\n\n\ncreateAssessessmentFileWithJoinnedTraces: completed\n\n\n");
                        onCompletion(sAssessmentFile);
                    });
        }
예제 #17
0
 public static void addMenuItemWithOnClickEvent(string menuItemName, O2Thread.FuncVoid onMenuItemClick)
 {
     
 }
예제 #18
0
 public void EditRules(List<IO2Rule> o2RulesToEdit, O2Thread.FuncVoidT1<IO2Rule> _onSave)
 {
     this.invokeOnThread(
         () =>
             {
                 onSave = _onSave;
                 newRule();
                 laDataSaved.Visible = false;
                 btSaveRuleChanges.Enabled = false;
                 btSaveChangesToAllRules.Enabled = true;
                 laNumberOfRulesLoaded.Text = o2RulesToEdit.Count +  " rule loaded";
                 o2LoadedRules = o2RulesToEdit;
                 o2LoadedRule = null;
             });
 }
예제 #19
0
파일: Files.cs 프로젝트: pusp/o2platform
 public static List<String> getListOfAllFilesFromDirectory(String sStartDirectory, bool bSearchRecursively, O2Thread.FuncVoidT1<List<String>> onComplete)
 {
     var lsFiles = new List<string>();
     O2Thread.mtaThread(
         () =>
             {
                 getListOfAllFilesFromDirectory(lsFiles, sStartDirectory, bSearchRecursively, "*.*", false);
                 onComplete(lsFiles);
             });
     return lsFiles;
 }
예제 #20
0
        public static void WhereCmd(string arguments, O2Thread.FuncVoidT1<string> o2Callback)
        {
            const int default_depth = 100; // default number of frames to print

            const string countOpt = "c";
            const string verboseOpt = "v";

            var ap = new ArgParser(arguments, countOpt + ":1;" + verboseOpt);
            int depth = default_depth;
            if (ap.OptionPassed(countOpt))
            {
                ArgToken countArg = ap.GetOption(countOpt);
                if (countArg.AsString == "all")
                {
                    depth = 0; // 0 means print entire stack0
                }
                else
                {
                    depth = countArg.AsInt;
                    if (depth <= 0)
                    {
                        throw new MDbgShellException("Depth must be positive number or string \"all\"");
                    }
                }
            }
            if (ap.Count != 0 && ap.Count != 1)
            {
                throw new MDbgShellException("Wrong # of arguments.");
            }

            if (ap.Count == 0)
            {
                // print current thread only
                InternalWhereCommand(CommandBase.Debugger.Processes.Active.Threads.Active, depth, ap.OptionPassed(verboseOpt));
            }
            else if (ap.AsString(0).Equals("all"))
            {
                foreach (MDbgThread t in CommandBase.Debugger.Processes.Active.Threads)
                    InternalWhereCommand(t, depth, ap.OptionPassed(verboseOpt));
            }
            else
            {
                MDbgThread t = CommandBase.Debugger.Processes.Active.Threads[ap.AsInt(0)];
                if (t == null)
                {
                    throw new MDbgShellException("Wrong thread number");
                }
                else
                {
                    InternalWhereCommand(t, depth, ap.OptionPassed(verboseOpt));
                }
            }
        }
예제 #21
0
        public static void FuncEvalCmd(string arguments, IMDbgShell Shell, O2Thread.FuncVoidT1<string> execOnEval)
        {
            try
            {

                var activeProcess = DI.o2MDbg.ActiveProcess; //Debugger.Processes.Active
                const string appDomainOption = "ad";
                var ap = new ArgParser(arguments, appDomainOption + ":1");
                if (!(ap.Count >= 1))
                {
                    throw new MDbgShellException("Not Enough arguments");
                }


                // Currently debugger picks first function -- we have not implementing resolving overloaded functions.
                // Good example is Console.WriteLine -- there is 18 different types:
                // 1) [06000575] Void WriteLine()
                // 2) [06000576] Void WriteLine(Boolean)
                // 3) [06000577] Void WriteLine(Char)
                // 4) [06000578] Void WriteLine(Char[])
                // 5) [06000579] Void WriteLine(Char[], Int32, Int32)
                // 6) [0600057a] Void WriteLine(Decimal)
                // 7) [0600057b] Void WriteLine(Double)
                // 8) [0600057c] Void WriteLine(Single)
                // 9) [0600057d] Void WriteLine(Int32)
                // 10) [0600057e] Void WriteLine(UInt32)
                // 11) [0600057f] Void WriteLine(Int64)
                // 12) [06000580] Void WriteLine(UInt64)
                // 13) [06000581] Void WriteLine(Object)
                // 14) [06000582] Void WriteLine(String)
                // 15) [06000583] Void WriteLine(String, Object)
                // 16) [06000584] Void WriteLine(String, Object, Object)
                // 17) [06000585] Void WriteLine(String, Object, Object, Object)
                // 18) [06000586] Void WriteLine(String, Object, Object, Object, Object, ...)
                // 19) [06000587] Void WriteLine(String, Object[])
                //
                CorAppDomain appDomain;
                if (ap.OptionPassed(appDomainOption))
                {
                    MDbgAppDomain ad = activeProcess.AppDomains[ap.GetOption(appDomainOption).AsInt];
                    if (ad == null)
                    {
                        throw new ArgumentException("Invalid Appdomain Number");
                    }
                    appDomain = ad.CorAppDomain;
                }
                else
                {
                    appDomain = activeProcess.Threads.Active.CorThread.AppDomain;
                }

                MDbgFunction func = activeProcess.ResolveFunctionNameFromScope(ap.AsString(0), appDomain);
                if (null == func)
                {
                    throw new MDbgShellException(String.Format(CultureInfo.InvariantCulture, "Could not resolve {0}",
                                                               new Object[] {ap.AsString(0)}));
                }

                CorEval eval = activeProcess.Threads.Active.CorThread.CreateEval();

                // Get Variables
                var vars = new ArrayList();
                String arg;
                for (int i = 1; i < ap.Count; i++)
                {
                    arg = ap.AsString(i);

                    CorValue v = Shell.ExpressionParser.ParseExpression2(arg, activeProcess,
                                                                         activeProcess.Threads.Active.
                                                                             CurrentFrame);

                    if (v == null)
                    {
                        throw new MDbgShellException("Cannot resolve expression or variable " + ap.AsString(i));
                    }

                    if (v is CorGenericValue)
                    {
                        vars.Add(v);
                    }

                    else
                    {
                        CorHeapValue hv = v.CastToHeapValue();
                        if (hv != null)
                        {
                            // we cannot pass directly heap values, we need to pass reference to heap valus
                            CorReferenceValue myref =
                                eval.CreateValue(CorElementType.ELEMENT_TYPE_CLASS, null).CastToReferenceValue();
                            myref.Value = hv.Address;
                            vars.Add(myref);
                        }
                        else
                        {
                            vars.Add(v);
                        }
                    }
                }

                eval.CallFunction(func.CorFunction, (CorValue[]) vars.ToArray(typeof (CorValue)));
                activeProcess.Go().WaitOne();

                // now display result of the funceval
                if (!(activeProcess.StopReason is EvalCompleteStopReason))
                {
                    // we could have received also EvalExceptionStopReason but it's derived from EvalCompleteStopReason
                    Shell.IO.WriteOutput(MDbgOutputConstants.StdOutput,
                                         "Func-eval not fully completed and debuggee has stopped");
                    Shell.IO.WriteOutput(MDbgOutputConstants.StdOutput,
                                         "Result of funceval won't be printed when finished.");
                }
                else
                {
                    eval = (activeProcess.StopReason as EvalCompleteStopReason).Eval;
                    Debug.Assert(eval != null);

                    CorValue cv = eval.Result;
                    if (cv != null)
                    {
                        var mv = new MDbgValue(activeProcess, cv);
                        if (execOnEval != null) // if this callback is set then execute 
                        {
                            execOnEval(mv.GetStringValue(1));                         
                            return;
                        }
                        Shell.IO.WriteOutput(MDbgOutputConstants.StdOutput, "result = " + mv.GetStringValue(1));
                        if (cv.CastToReferenceValue() != null)
                            if (activeProcess.DebuggerVars.SetEvalResult(cv))
                                Shell.IO.WriteOutput(MDbgOutputConstants.StdOutput, "results saved to $result");

                    }
                }               
            }
            catch (Exception ex)
            {
                DI.log.ex(ex, "in FuncEvalCmd");
            }
            if (execOnEval != null)                         // need to call this here so that the sync AutoResetEvent is set
                execOnEval(null);
        }
 public Thread saveAllLoadedRules(O2Thread.FuncVoid onComplete)
 {
     return O2Thread.mtaThread(
         () =>
             {
                 var savedFile = O2RulePackUtils.saveRulePack(currentO2RulePack);
                 DI.log.showMessageBox("All loaded rules rules saved to: " + savedFile);
                 if (onComplete != null)
                     onComplete();
             });
 }
예제 #23
0
        public static void ShowCmd(string arguments, O2Thread.FuncVoidT1<string> o2Callback)
        {

            MDbgSourcePosition pos = CommandBase.Debugger.Processes.Active.Threads.Active.CurrentSourcePosition;
            
            if (pos == null)
            {
                throw new MDbgShellException("No source location");
            }

            string fileLoc = CommandBase.Shell.FileLocator.GetFileLocation(pos.Path);
            if (fileLoc == null)
            {
                throw new MDbgShellException(String.Format(CultureInfo.InvariantCulture,
                                                           "Source file '{0}' not available.", pos.Path));
            }

            IMDbgSourceFile file = CommandBase.Shell.SourceFileMgr.GetSourceFile(fileLoc);

            var ap = new ArgParser(arguments);
            if (ap.Count > 1)
            {
                throw new MDbgShellException("Wrong # of arguments.");
            }

            int around;
            if (ap.Exists(0))
            {
                around = ap.AsInt(0);
            }
            else
            {
                around = 3;
            }

            int lo, hi;
            lo = pos.Line - around;
            if (lo < 1)
            {
                lo = 1;
            }
            hi = pos.Line + around;
            if (hi > file.Count)
            {
                hi = file.Count;
            }

            for (int i = lo; i < hi; i++)
            {
                CommandBase.WriteOutput(String.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", i, i == pos.Line ? ":*" : "  ",
                                          file[i]));
            }
        }
 public Thread importFromLocalMySqlDatabase(
     bool addSources, bool addSinks, bool addCallbacks, bool addPropagateTaint, bool addDontPropagateTaint, bool addAnyHigh, bool addAnyMedium, bool addAnyLow,
     O2Thread.FuncVoid onComplete)
 {
     return O2Thread.mtaThread(
         () =>
             {
                 try
                 {
                     var timer = new O2Timer("Loaded rules from DB").start();
                     var o2Rules =
                         new MySqlRules_OunceV6().createO2RulesForAllLddbEntriesForLanguage(
                             currentLanguage,
                             addSources, addSinks, addCallbacks, addPropagateTaint, addDontPropagateTaint, addAnyHigh, addAnyMedium, addAnyLow
                             );
                     setRulesAsLoadedFromDb(o2Rules);
                     setCurrentRulePack(new O2RulePack("MySql_Dump", o2Rules));
                     timer.stop();
                 }
                 catch (Exception ex)
                 {
                     DI.log.error("in importFromLocalMySqlDatabase:{0}", ex.Message);
                 }
                 if (onComplete != null)
                     onComplete();
             });
 }
예제 #25
0
        public static void DeleteCmd(string arguments, O2Thread.FuncVoidT1<string> o2Callback)

        {
            var ap = new ArgParser(arguments);
            if (ap.Count != 1)
            {
                CommandBase.WriteOutput("Please choose some breakpoint to delete");
                MdbgCommands.BreakCmd("");
                return;
            }

            MDbgBreakpoint breakpoint = CommandBase.Debugger.Processes.Active.Breakpoints[ap.AsInt(0)];
            if (breakpoint == null)
            {
                throw new MDbgShellException("Could not find breakpint #:" + ap.AsInt(0));
            }
            else
            {
                breakpoint.Delete();
            }
        }
예제 #26
0
        // O2.Debugger.Mdbg.OriginalMdbgCode.mdbg.mdbgCommandsCustomizedForO2
        // , O2Thread.FuncVoid<string> o2Callback)
        public static bool AttachCmd(string arguments, O2Thread.FuncVoidT1<string> o2Callback)
        {
            try
            {
                var ap = new ArgParser(arguments);
                if (ap.Count > 1)
                {
                    DI.log.error("in AttachCmd: Wrong # of arguments.");
                    return false;
                }

                if (!ap.Exists(0))
                {
                    DI.log.error("in AttachCmd: Please choose some process to attach");
                    MdbgCommands.ProcessEnumCmd("");
                    return false;
                }
                int pid = ap.AsInt(0);

                if (Process.GetCurrentProcess().Id == pid)
                {
                    DI.log.error("in AttachCmd: Cannot attach to myself!");
                    return false;
                }

                MDbgProcess p = CommandBase.Debugger.Attach(pid);
                p.Go().WaitOne();
                return true;
            }
            catch (Exception ex)
            {
                DI.log.ex(ex, "in AttachCmd");
                return false;
            }                        
        }
예제 #27
0
 public static void ListBreakpoints(O2Thread.FuncVoidT1<string> o2Callback)
 {
     if (CommandBase.Debugger.Processes.HaveActive)
     {
         MDbgBreakpointCollection breakpoints = CommandBase.Debugger.Processes.Active.Breakpoints;
         if (o2Callback != null)
             CommandBase.WriteOutput("Current breakpoints:");
         bool haveBps = false;
         foreach (MDbgBreakpoint b in breakpoints)
         {
             if (o2Callback != null)
                 o2Callback(b.ToString());
             else
                 CommandBase.WriteOutput(b.ToString());
             haveBps = true;
         }
         if (!haveBps)
         {
             if (o2Callback != null)
                 DI.log.debug("There are no breakpoints set in the current active process");
             else
                 CommandBase.WriteOutput("No breakpoints!");
         }
     }
 }
        public Thread loadAssesmblyDataIntoTreeView(Assembly aAssemblyToLoad, TreeView tvTargetTreeView,
                                                    Label lbLastMethodExecuted, bool bOnlyShowStaticMethods)
        {
            tvTargetTreeView.Visible = false;
            tvTargetTreeView.Nodes.Clear();
            tvTargetTreeView.Sorted = true;
            int iTypesAdded = 0;

            return(O2Thread.mtaThread(() =>
            {
                try
                {
                    var treeNodesToAdd = new List <TreeNode>();
                    foreach (Type tType in aAssemblyToLoad.GetTypes())
                    {
                        if ((iTypesAdded++) % 500 == 0)
                        {
                            PublicDI.log.info("{0} types processed", iTypesAdded);
                        }
                        //vars.set_(tType.Name, tType); // set global variable of compiled code
                        //Callbacks.raiseEvent_ScriptCompiledSuccessfully(tType.Name);
                        TreeNode tnType = O2Forms.newTreeNode(tType.Name, tType.Name, 1, tType);
                        foreach (
                            MethodInfo mMethod in
                            tType.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly |
                                             ((bOnlyShowStaticMethods) ? BindingFlags.Static : BindingFlags.Static | BindingFlags.Instance)))
                        {
                            if (mMethod.Name == lbLastMethodExecuted.Text)
                            {
                                lbLastMethodExecuted.Tag = mMethod;
                            }
                            //TreeNode tnMethod = O2Forms.newTreeNode(mMethod.Name, mMethod.Name, 2, mMethod);
                            TreeNode tnMethod =
                                O2Forms.newTreeNode(
                                    new FilteredSignature(mMethod).getReflectorView(),
                                    mMethod.Name, 2, mMethod);
                            tnType.Nodes.Add(tnMethod);
                        }
                        if (tnType.Nodes.Count > 0)
                        {
                            treeNodesToAdd.Add(tnType);
                        }
                        //O2Forms.addNodeToTreeNodeCollection(tvTargetTreeView, tvTargetTreeView.Nodes, tnType);      // thread safe way to add nodes
                    }
                    PublicDI.log.info("{0} types processed , now loading them into treeView", iTypesAdded);
                    tvTargetTreeView.invokeOnThread(() =>
                    {
                        foreach (var treeNode in treeNodesToAdd)
                        {
                            tvTargetTreeView.Nodes.Add(treeNode);
                        }
                        PublicDI.log.info("All nodes loaded");
                        if (tvTargetTreeView.Nodes.Count > 0)
                        {
                            tvTargetTreeView.Nodes[0].Expand();
                        }
                        tvTargetTreeView.Visible = true;
                    });
                }
                catch (Exception ex)
                {
                    PublicDI.log.ex(ex, "in loadAssesmblyDataIntoTreeView");
                }
            }));


            //if (tvTargetTreeView.GetNodeCount(true) < 20)
            //    tvTargetTreeView.ExpandAll();
            //tvTargetTreeView.Visible = true;
        }
예제 #29
0
        public static void ProcessEnumCmd(string arguments, O2Thread.FuncVoidT1<CorPublishProcess> handleManagedProcess) // extended with Lambda method
        {
            var cp = new CorPublish();

            CommandBase.WriteOutput("Active processes on current machine:");
            foreach (CorPublishProcess cpp in cp.EnumProcesses())
            {
                if (Process.GetCurrentProcess().Id == cpp.ProcessId) // let's hide our process
                {
                    continue;
                }

                // Try and get the list of AppDomains, but watch for the process terminating
                IEnumerable appDomainEnum;
                try
                {
                    appDomainEnum = cpp.EnumAppDomains();
                }
                catch (COMException e)
                {
                    if ((uint) e.ErrorCode == 0x80131301) //CORDBG_E_PROCESS_TERMINATED
                    {
                        continue; // process was terminated, ignore it
                    }
                    throw; // let error propogate up
                }
                if (handleManagedProcess != null)
                    handleManagedProcess(cpp);
                else
                {
                    CommandBase.WriteOutput("(PID: " + cpp.ProcessId + ") " + cpp.DisplayName);
                    foreach (CorPublishAppDomain cpad in appDomainEnum)
                        CommandBase.WriteOutput("\t(ID: " + cpad.Id + ") " + cpad.Name);
                }
            }
        }
예제 #30
0
        public static List<String> getCompiledXRulesAssemblies(O2Thread.FuncVoidT1<string> currentTask, O2Thread.FuncVoidT1<int> numberOfStepsToPerform, O2Thread.FuncVoid onStepEvent)
        {
            currentTask("Compiling all rules together");
            numberOfStepsToPerform(1);
            // first try to scan all together
            var filesToCompile = Files.getFilesFromDir_returnFullPath(XRules_Config.PathTo_XRulesDatabase_fromO2, "*.cs", true); 			// recursive search
            foreach(var xRuleFile in Files.getFilesFromDir_returnFullPath(XRules_Config.PathTo_XRulesDatabase_fromLocalDisk, "*.cs", true)) // recursive search
                if (false == filesToCompile.Contains(xRuleFile))
                    filesToCompile.Add(xRuleFile);
            PublicDI.log.info("There are {0} XRules to Compile", filesToCompile.Count);

            var compiledXRulesAssembly = compileAllFilesTogether(filesToCompile);
            onStepEvent();
            if (compiledXRulesAssembly != null)
                return new List<String> {compiledXRulesAssembly.Location};

            // if we couldn't compile all at once, then compile each file individually
            PublicDI.log.error("It was not possible to compile all XRules together, going to try to compile each XRule file individually");
            //return compileAllFilesIndividually(filesToCompile,currentTask,numberOfStepsToPerform,onStepEvent);
            return null;
        }
예제 #31
0
 private static string populateDirectoryWithAllDependencies(List<String> compiledXRulesFiles, O2Thread.FuncVoid onStepEvent)
 {
     var targetDirectory = XRules_Config.PathTo_XRulesCompiledDlls;
     Files.deleteFilesFromDirThatMatchPattern(targetDirectory,"*.dll");
     foreach (var compiledFile in compiledXRulesFiles)
     {
         CecilAssemblyDependencies.populateDirectoryWithAllDependenciesOfAssembly(targetDirectory, compiledFile,
                                                                                  null);
         onStepEvent();
     }
     return targetDirectory;
 }
예제 #32
0
        public static void BreakCmd(string arguments, O2Thread.FuncVoidT1<string> o2Callback)
        {
            if (arguments.Length == 0)
            {
                ListBreakpoints(o2Callback);
                return;
            }

            // We're adding a breakpoint. Parse the argument string.
            MDbgBreakpointCollection breakpoints = CommandBase.Debugger.Processes.Active.Breakpoints;
            ISequencePointResolver bploc = CommandBase.Shell.BreakpointParser.ParseFunctionBreakpoint(arguments);            
            if (bploc == null)
            {
                throw new MDbgShellException("Invalid breakpoint syntax.");
            }

            MDbgBreakpoint bpnew = CommandBase.Debugger.Processes.Active.Breakpoints.CreateBreakpoint(bploc);
            CommandBase.WriteOutput(bpnew.ToString());
        }
예제 #33
0
        public static void PrintCmd(string arguments, O2Thread.FuncVoidT1<string> o2Callback)
        {
            const string debuggerVarsOpt = "d";
            const string noFuncevalOpt = "nf";
            const string expandDepthOpt = "r";

            var ap = new ArgParser(arguments, debuggerVarsOpt + ";" + noFuncevalOpt + ";" + expandDepthOpt + ":1");
            bool canDoFunceval = ! ap.OptionPassed(noFuncevalOpt);

            int? expandDepth = null; // we use optional here because
            // different codes bellow has different
            // default values.
            if (ap.OptionPassed(expandDepthOpt))
            {
                expandDepth = ap.GetOption(expandDepthOpt).AsInt;
                if (expandDepth < 0)
                    throw new MDbgShellException("Depth cannot be negative.");
            }

            MDbgFrame frame = CommandBase.Debugger.Processes.Active.Threads.Active.CurrentFrame;
            if (ap.OptionPassed(debuggerVarsOpt))
            {
                // let's print all debugger variables
                MDbgProcess p = CommandBase.Debugger.Processes.Active;
                foreach (MDbgDebuggerVar dv in p.DebuggerVars)
                {
                    var v = new MDbgValue(p, dv.CorValue);
                    CommandBase.WriteOutput(dv.Name + "=" + v.GetStringValue(expandDepth == null ? 0 : (int) expandDepth,
                                                                 canDoFunceval));
                }
            }
            else
            {
                if (ap.Count == 0)
                {
                    // get all active variables
                    MDbgFunction f = frame.Function;

                    var vars = new ArrayList();
                    MDbgValue[] vals = f.GetActiveLocalVars(frame);
                    if (vals != null)
                    {
                        vars.AddRange(vals);
                    }

                    vals = f.GetArguments(frame);
                    if (vals != null)
                    {
                        vars.AddRange(vals);
                    }
                    foreach (MDbgValue v in vars)
                    {
                        CommandBase.WriteOutput(v.Name + "=" + v.GetStringValue(expandDepth == null ? 0 : (int) expandDepth,
                                                                    canDoFunceval));
                    }
                }
                else
                {
                    // user requested printing of specific variables
                    for (int j = 0; j < ap.Count; ++j)
                    {
                        MDbgValue var = CommandBase.Debugger.Processes.Active.ResolveVariable(ap.AsString(j), frame);
                        if (var != null)
                        {
                            CommandBase.WriteOutput(ap.AsString(j) + "=" + var.GetStringValue(expandDepth == null
                                                                                      ? 1
                                                                                      : (int) expandDepth, canDoFunceval));
                        }
                        else
                        {
                            throw new MDbgShellException("Variable not found");
                        }
                    }
                }
            }
        }