Пример #1
0
        public void InitChartFromTrace(TraceRecord trace)
        {
            lock (_lock)
            {
                if (trace != _rootTrace)
                {
                    sbgraph.Clear();
                    layout.VerticesPositions.Clear();
                    _rootTrace = trace;
                    addedNodes.Clear();
                }

                bool needLayout = trace.TimelineItemsCount != timelineItemsOnChartDraw;
                if (needLayout && !_layoutActive)
                {
                    Logging.TIMELINE_EVENT[] entries = trace.GetTimeLineEntries();
                    timelineItemsOnChartDraw = entries.Length;
                    //StopLayout();
                    AddThreadItems(null, trace);

                    /*
                     * KKLayoutParameters layoutParams = new KKLayoutParameters()
                     * {
                     *  Height = chartSize.Y - (2 * padding),
                     *  Width = chartSize.X - (2 * padding),
                     *  LengthFactor = 1,
                     *  DisconnectedMultiplier = 2,
                     *  ExchangeVertices = true
                     * };
                     * layout = new GraphShape.Algorithms.Layout.KKLayoutAlgorithm<ItemNode,
                     *  Edge<ItemNode>, BidirectionalGraph<ItemNode, Edge<ItemNode>>>(sbgraph, parameters: layoutParams);
                     */
                    FitNodesToChart();
                    _computeRequired = true;
                }
            }
        }
Пример #2
0
        private void DrawEventListTable(TraceRecord trace, SandboxChart.ItemNode?selectedNode)
        {
            if (chart is null)
            {
                return;
            }

            ImGui.PushStyleColor(ImGuiCol.Header, Themes.GetThemeColourUINT(Themes.eThemeColour.Emphasis2, 40));
            TIMELINE_EVENT[] events = trace.GetTimeLineEntries();
            if (ImGui.BeginTable("#TaTTFullList", 4, ImGuiTableFlags.Borders | ImGuiTableFlags.ScrollY |
                                 ImGuiTableFlags.Resizable | ImGuiTableFlags.RowBg))
            {
                ImGui.TableSetupScrollFreeze(0, 1);
                ImGui.TableSetupColumn("#", ImGuiTableColumnFlags.WidthFixed, 50);
                ImGui.TableSetupColumn("Type", ImGuiTableColumnFlags.WidthFixed, 70);
                ImGui.TableSetupColumn("Module", ImGuiTableColumnFlags.WidthFixed, 70);
                ImGui.TableSetupColumn("Details", ImGuiTableColumnFlags.None);
                ImGui.TableHeadersRow();

                var SelectedEntity   = chart.SelectedEntity;
                var SelectedAPIEvent = chart.SelectedAPIEvent;

                bool ThreadNodeSelected  = selectedNode is not null && Equals(selectedNode.reference.GetType(), typeof(ProtoGraph));
                bool ProcessNodeSelected = selectedNode is not null && Equals(selectedNode.reference.GetType(), typeof(TraceRecord));


                int i = 0;
                foreach (TIMELINE_EVENT TLevent in events)
                {
                    i += 1;

                    ImGui.TableNextRow();
                    if (TLevent.MetaError != null)
                    {
                        ImGui.TableSetBgColor(ImGuiTableBgTarget.RowBg0, Themes.GetThemeColourUINT(Themes.eThemeColour.BadStateColour));
                        ImGui.TableSetBgColor(ImGuiTableBgTarget.RowBg1, Themes.GetThemeColourUINT(Themes.eThemeColour.BadStateColour));
                    }

                    bool   selected  = false;
                    string eventType = "";
                    string module    = "";
                    if (ImGui.TableNextColumn())
                    {
                        switch (TLevent.TimelineEventType)
                        {
                        case eTimelineEvent.ProcessStart:
                        case eTimelineEvent.ProcessEnd:
                            eventType = "Process";

                            if (selectedNode != null)
                            {
                                selected = (ProcessNodeSelected && TLevent.ID == ((TraceRecord)selectedNode.reference).PID);
                            }

                            break;

                        case eTimelineEvent.ThreadStart:
                        case eTimelineEvent.ThreadEnd:
                            eventType = "Thread";
                            if (selectedNode != null)
                            {
                                ProtoGraph currentEntryGraph = (ProtoGraph)TLevent.Item;
                                selected = (ThreadNodeSelected && currentEntryGraph.ThreadID == ((ProtoGraph)selectedNode.reference).ThreadID);
                                selected = selected || (ProcessNodeSelected && currentEntryGraph.TraceData.PID == ((TraceRecord)(selectedNode.reference)).PID);
                            }
                            break;

                        case eTimelineEvent.APICall:
                        {
                            Logging.APICALL call = (Logging.APICALL)(TLevent.Item);
                            selected = TLevent == SelectedAPIEvent;

                            if (call.Node !.IsExternal)
                            {
                                eventType = "API - " + call.APIType();
                                module    = Path.GetFileNameWithoutExtension(trace.DisassemblyData.GetModulePath(call.Node.GlobalModuleID));

                                //api call is selected if it is either directly activated, or interacts with a reference to the active entity
                                //eg: if the file.txt node is selected, writefile to the relevant handle will also be selected
                                selected = selected || (SelectedEntity != null && SelectedEntity == chart.GetInteractedEntity(TLevent));
                                if (!selected && selectedNode != null)
                                {
                                    //select all apis called by selected thread node
                                    selected = selected || (ThreadNodeSelected && call.Graph !.ThreadID == ((ProtoGraph)selectedNode.reference).ThreadID);
                                    //select all apis called by selected process node
                                    selected = selected || (ProcessNodeSelected && call.Graph !.TraceData.PID == ((TraceRecord)selectedNode.reference).PID);
                                }
                                //WinAPIDetails.API_ENTRY = call.APIEntry;
                            }
                            else
                            {
                                eventType = "Internal";
                            }
                        }
                        break;
                        }

                        if (ImGui.Selectable(i.ToString(), selected, ImGuiSelectableFlags.SpanAllColumns) && !selected)
                        {
                            chart.SelectAPIEvent(TLevent);
                        }
                    }
Пример #3
0
        private void AddThreadItems(ItemNode?parentProcess, TraceRecord trace)
        {
            string   nodeName     = $"PROCNODE_{trace.PID}_{trace.LaunchedTime}";
            ItemNode?startProcess = null;

            lock (_lock)
            {
                if (!addedNodes.TryGetValue(nodeName, out startProcess))
                {
                    startProcess = new ItemNode(nodeName, Logging.eTimelineEvent.ProcessStart, trace);
                    sbgraph.AddVertex(startProcess);
                    addedNodes[nodeName] = startProcess;
                    if (parentProcess != null)
                    {
                        sbgraph.AddEdge(new Edge <ItemNode>(parentProcess, startProcess));
                    }
                }


                var threads = trace.ProtoGraphs;
                foreach (var thread in threads)
                {
                    string threadName = $"THREADNODE_{thread.TraceData.randID}_{thread.ThreadID}";
                    if (!addedNodes.ContainsKey(threadName))
                    {
                        ItemNode threadNode = new ItemNode(threadName, Logging.eTimelineEvent.ThreadStart, thread);
                        sbgraph.AddVertex(threadNode);
                        sbgraph.AddEdge(new Edge <ItemNode>(startProcess, threadNode));
                        addedNodes[threadName] = threadNode;
                    }
                }

                var timelineEntries = trace.GetTimeLineEntries();
                foreach (Logging.TIMELINE_EVENT timelineEvent in timelineEntries)
                {
                    if (timelineEvent.TimelineEventType == Logging.eTimelineEvent.APICall)
                    {
                        var call = (Logging.APICALL)(timelineEvent.Item);
                        if (call.APIDetails != null)
                        {
                            APIDetailsWin.API_ENTRY apiinfo = call.APIDetails.Value;
                            if (apiinfo.Effects != null)
                            {
                                ProtoGraph?caller = call.Graph;
                                if (caller is null || call.Node is null || call.Index >= call.Node.callRecordsIndexs.Count)
                                {
                                    Logging.RecordLogEvent($"Warning: Call {call.APIDetails.Value.ModuleName}:{call.APIDetails.Value.Symbol} tried to place call {call.Index} on timeline, but only {call.Node?.callRecordsIndexs.Count} recorded");
                                    continue;
                                }
                                int recordsIndex = (int)call.Node.callRecordsIndexs[call.Index];
                                if (recordsIndex >= caller.SymbolCallRecords.Count)
                                {
                                    Logging.RecordLogEvent($"Warning: Call {call.APIDetails.Value.ModuleName}:{call.APIDetails.Value.Symbol} tried to place record {recordsIndex} on timeline, but caller has only {caller.SymbolCallRecords} recorded");
                                    continue;
                                }
                                APICALLDATA APICallRecord = caller.SymbolCallRecords[recordsIndex];
                                string      threadName    = $"THREADNODE_{caller.TraceData.randID}_{caller.ThreadID}";
                                ItemNode    threadNode    = addedNodes[threadName];

                                foreach (APIDetailsWin.InteractionEffect effectBase in apiinfo.Effects)
                                {
                                    switch (effectBase)
                                    {
                                    case APIDetailsWin.LinkReferenceEffect linkEffect:
                                    {
                                        APIDetailsWin.API_PARAM_ENTRY entityParamRecord    = apiinfo.LoggedParams[linkEffect.EntityIndex];
                                        APIDetailsWin.API_PARAM_ENTRY referenceParamRecord = apiinfo.LoggedParams[linkEffect.ReferenceIndex];

                                        int entityParamLoggedIndex    = APICallRecord.argList.FindIndex(x => x.Item1 == entityParamRecord.Index);
                                        int referenceParamLoggedIndex = APICallRecord.argList.FindIndex(x => x.Item1 == referenceParamRecord.Index);

                                        if (entityParamLoggedIndex == -1 || referenceParamLoggedIndex == -1)
                                        {
                                            string error = $"API call record for {apiinfo.ModuleName}:{apiinfo.Symbol} [LinkReference] didn't have correct parameters. The instrumentation library or apidata file may not match.";
                                            timelineEvent.MetaError = error;
                                            Logging.RecordLogEvent(error, Logging.LogFilterType.Debug);
                                            break;
                                        }

                                        if (!_interactionEntities.TryGetValue(entityParamRecord.EntityType, out Dictionary <string, ItemNode>?entityDict))
                                        {
                                            entityDict = new Dictionary <string, ItemNode>();
                                            _interactionEntities.Add(entityParamRecord.EntityType, entityDict);
                                        }
                                        string entityString = APICallRecord.argList[entityParamLoggedIndex].Item2;

                                        ItemNode entityNode;
                                        if (!entityDict.ContainsKey(entityString))
                                        {
                                            entityNode = new ItemNode(entityString, Logging.eTimelineEvent.APICall, timelineEvent);
                                            entityDict.Add(entityString, entityNode);
                                            sbgraph.AddVertex(entityNode);
                                            addedNodes[entityString] = entityNode;
                                        }
                                        else
                                        {
                                            entityNode = addedNodes[entityString];
                                        }
                                        AddAPIEdge(threadNode, entityNode, apiinfo.Label);

                                        if (!_timelineEventEntities.TryGetValue(timelineEvent, out ItemNode? existingEntity))
                                        {
                                            _timelineEventEntities.Add(timelineEvent, entityNode);
                                        }
                                        Debug.Assert(existingEntity == null || existingEntity == entityNode);


                                        //link this entity to the reference the api all created (eg associate a file path with the file handle that 'CreateFile' created)
                                        string referenceString = APICallRecord.argList[referenceParamLoggedIndex].Item2;
                                        if (referenceParamRecord.NoCase)
                                        {
                                            referenceString = referenceString.ToLower();
                                        }

                                        if (!_interactionEntityReferences.ContainsKey(referenceParamRecord.RawType))
                                        {
                                            _interactionEntityReferences.Add(referenceParamRecord.RawType, new Dictionary <string, ItemNode>());
                                        }
                                        if (!_interactionEntityReferences[referenceParamRecord.RawType].ContainsKey(referenceString))
                                        {
                                            _interactionEntityReferences[referenceParamRecord.RawType].Add(referenceString, entityNode);
                                        }

                                        break;
                                    }

                                    // this api performs some action on a refererence to an entity
                                    // record this as a label on the edge and link this event to the entity
                                    case APIDetailsWin.UseReferenceEffect useEffect:
                                    {
                                        APIDetailsWin.API_PARAM_ENTRY referenceParamRecord = apiinfo.LoggedParams[useEffect.ReferenceIndex];
                                        int referenceParamLoggedIndex = APICallRecord.argList.FindIndex(x => x.Item1 == referenceParamRecord.Index);
                                        if (referenceParamLoggedIndex == -1)
                                        {
                                            timelineEvent.MetaError = $"API call record for {apiinfo.ModuleName}:{apiinfo.Symbol} [UseReference] didn't have correct parameters";
                                            Logging.RecordLogEvent(timelineEvent.MetaError, Logging.LogFilterType.Debug);
                                            break;
                                        }

                                        string referenceString = APICallRecord.argList[referenceParamLoggedIndex].Item2;
                                        if (referenceParamRecord.NoCase)
                                        {
                                            referenceString = referenceString.ToLower();
                                        }

                                        bool resolvedReference = false;
                                        if (_interactionEntityReferences.TryGetValue(referenceParamRecord.RawType, out Dictionary <string, ItemNode>?typeEntityList))
                                        {
                                            if (typeEntityList.TryGetValue(referenceString, out ItemNode? entityNode))
                                            {
                                                resolvedReference = true;
                                                if (!_timelineEventEntities.ContainsKey(timelineEvent))
                                                {
                                                    _timelineEventEntities.Add(timelineEvent, entityNode);
                                                }

                                                AddAPIEdge(threadNode, entityNode, apiinfo.Label);
                                            }
                                        }
                                        if (!resolvedReference)
                                        {
                                            timelineEvent.MetaError = $"API call record for {apiinfo.ModuleName}:{apiinfo.Symbol} [UseReference] reference was not linked to an entity ({referenceString})";
                                            Logging.RecordLogEvent(timelineEvent.MetaError, Logging.LogFilterType.Debug);
                                        }
                                        break;
                                    }

                                    // this api invalidates a reference
                                    // remove the link between the reference and the entity it references
                                    case APIDetailsWin.DestroyReferenceEffect destroyEffect:
                                    {
                                        APIDetailsWin.API_PARAM_ENTRY referenceParamRecord = apiinfo.LoggedParams[destroyEffect.ReferenceIndex];
                                        int referenceParamLoggedIndex = APICallRecord.argList.FindIndex(x => x.Item1 == referenceParamRecord.Index);
                                        if (referenceParamLoggedIndex == -1)
                                        {
                                            timelineEvent.MetaError = $"API call record for {apiinfo.ModuleName}:{apiinfo.Symbol} [DestroyReference] didn't have correct parameters";
                                            Logging.RecordLogEvent(timelineEvent.MetaError, Logging.LogFilterType.Debug);
                                            break;
                                        }

                                        string referenceString = APICallRecord.argList[referenceParamLoggedIndex].Item2;
                                        if (referenceParamRecord.NoCase)
                                        {
                                            referenceString = referenceString.ToLower();
                                        }

                                        bool resolvedReference = false;
                                        if (_interactionEntityReferences.TryGetValue(referenceParamRecord.RawType, out Dictionary <string, ItemNode>?typeEntityList))
                                        {
                                            if (typeEntityList.TryGetValue(referenceString, out ItemNode? entityNode))
                                            {
                                                resolvedReference = true;
                                                if (!_timelineEventEntities.ContainsKey(timelineEvent))
                                                {
                                                    _timelineEventEntities.Add(timelineEvent, entityNode);
                                                }

                                                AddAPIEdge(threadNode, entityNode, apiinfo.Label);
                                                typeEntityList.Remove(referenceString);
                                            }
                                        }
                                        if (!resolvedReference)
                                        {
                                            timelineEvent.MetaError = $"API call record for {apiinfo.ModuleName}:{apiinfo.Symbol} [DestroyReference] reference was not linked to an entity ({referenceString})";
                                            Logging.RecordLogEvent(timelineEvent.MetaError, Logging.LogFilterType.Debug);
                                        }

                                        break;
                                    }

                                    default:
                                        timelineEvent.MetaError = $"API call record for {apiinfo.ModuleName}:{apiinfo.Symbol}: had invalid effect {effectBase}";
                                        Logging.RecordLogEvent(timelineEvent.MetaError, Logging.LogFilterType.Debug);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }

                if (startProcess is not null)
                {
                    foreach (var child in trace.GetChildren())
                    {
                        string childName = $"PROCNODE_{child.PID}_{child.LaunchedTime}";
                        if (!addedNodes.TryGetValue(childName, out ItemNode? childProcess) || childProcess is null)
                        {
                            childProcess = new ItemNode(childName, Logging.eTimelineEvent.ProcessStart, child);
                            sbgraph.AddVertex(childProcess);
                            addedNodes[childName] = childProcess;

                            sbgraph.AddEdge(new Edge <ItemNode>(startProcess, childProcess));
                        }
                        AddThreadItems(parentProcess, child);
                    }
                }
            }
        }