8cb642b308f928e26698f36f8fd1001fc7e7770b
[deliverable/tracecompass.git] / analysis / org.eclipse.tracecompass.analysis.os.linux.ui / src / org / eclipse / tracecompass / internal / analysis / os / linux / ui / views / controlflow / ControlFlowView.java
1 /*******************************************************************************
2 * Copyright (c) 2012, 2016 Ericsson, École Polytechnique de Montréal and others.
3 *
4 * All rights reserved. This program and the accompanying materials are
5 * made available under the terms of the Eclipse Public License v1.0 which
6 * accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
8 *
9 * Contributors:
10 * Patrick Tasse - Initial API and implementation
11 * Geneviève Bastien - Move code to provide base classes for time graph view
12 * Christian Mansky - Add check active / uncheck inactive buttons
13 * Mahdi Zolnouri & Samuel Gagnon - Add flat / hierarchical button
14 *******************************************************************************/
15
16 package org.eclipse.tracecompass.internal.analysis.os.linux.ui.views.controlflow;
17
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.Collections;
21 import java.util.Comparator;
22 import java.util.HashMap;
23 import java.util.HashSet;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Set;
27 import java.util.function.Function;
28 import java.util.function.Predicate;
29 import java.util.stream.Collectors;
30 import java.util.stream.Stream;
31
32 import org.eclipse.core.runtime.IProgressMonitor;
33 import org.eclipse.core.runtime.IStatus;
34 import org.eclipse.core.runtime.Status;
35 import org.eclipse.core.runtime.jobs.ISchedulingRule;
36 import org.eclipse.core.runtime.jobs.Job;
37 import org.eclipse.jdt.annotation.NonNull;
38 import org.eclipse.jdt.annotation.Nullable;
39 import org.eclipse.jface.action.Action;
40 import org.eclipse.jface.action.IAction;
41 import org.eclipse.jface.action.IMenuManager;
42 import org.eclipse.jface.action.IToolBarManager;
43 import org.eclipse.jface.action.MenuManager;
44 import org.eclipse.jface.action.Separator;
45 import org.eclipse.jface.dialogs.IDialogSettings;
46 import org.eclipse.jface.viewers.ISelection;
47 import org.eclipse.jface.viewers.StructuredSelection;
48 import org.eclipse.swt.widgets.Composite;
49 import org.eclipse.swt.widgets.Event;
50 import org.eclipse.tracecompass.analysis.os.linux.core.kernel.KernelAnalysisModule;
51 import org.eclipse.tracecompass.analysis.os.linux.core.kernel.KernelTidAspect;
52 import org.eclipse.tracecompass.common.core.StreamUtils.StreamFlattener;
53 import org.eclipse.tracecompass.internal.analysis.os.linux.core.kernel.Attributes;
54 import org.eclipse.tracecompass.internal.analysis.os.linux.ui.Activator;
55 import org.eclipse.tracecompass.internal.analysis.os.linux.ui.Messages;
56 import org.eclipse.tracecompass.internal.analysis.os.linux.ui.actions.FollowThreadAction;
57 import org.eclipse.tracecompass.statesystem.core.ITmfStateSystem;
58 import org.eclipse.tracecompass.statesystem.core.exceptions.AttributeNotFoundException;
59 import org.eclipse.tracecompass.statesystem.core.exceptions.StateSystemDisposedException;
60 import org.eclipse.tracecompass.statesystem.core.exceptions.StateValueTypeException;
61 import org.eclipse.tracecompass.statesystem.core.exceptions.TimeRangeException;
62 import org.eclipse.tracecompass.statesystem.core.interval.ITmfStateInterval;
63 import org.eclipse.tracecompass.statesystem.core.statevalue.ITmfStateValue;
64 import org.eclipse.tracecompass.tmf.core.event.ITmfEvent;
65 import org.eclipse.tracecompass.tmf.core.signal.TmfSelectionRangeUpdatedSignal;
66 import org.eclipse.tracecompass.tmf.core.signal.TmfSignalHandler;
67 import org.eclipse.tracecompass.tmf.core.signal.TmfSignalManager;
68 import org.eclipse.tracecompass.tmf.core.signal.TmfTraceSelectedSignal;
69 import org.eclipse.tracecompass.tmf.core.statesystem.TmfStateSystemAnalysisModule;
70 import org.eclipse.tracecompass.tmf.core.timestamp.TmfTimestamp;
71 import org.eclipse.tracecompass.tmf.core.trace.ITmfContext;
72 import org.eclipse.tracecompass.tmf.core.trace.ITmfTrace;
73 import org.eclipse.tracecompass.tmf.core.trace.TmfTraceManager;
74 import org.eclipse.tracecompass.tmf.core.trace.TmfTraceUtils;
75 import org.eclipse.tracecompass.tmf.core.util.Pair;
76 import org.eclipse.tracecompass.tmf.ui.views.timegraph.AbstractStateSystemTimeGraphView;
77 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.model.ILinkEvent;
78 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.model.ITimeEvent;
79 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.model.ITimeGraphEntry;
80 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.model.NullTimeEvent;
81 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.model.TimeEvent;
82 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.model.TimeGraphEntry;
83 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.model.TimeLinkEvent;
84 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.widgets.TimeGraphControl;
85 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.widgets.Utils;
86 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.widgets.Utils.Resolution;
87 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.widgets.Utils.TimeFormat;
88
89 import com.google.common.collect.ImmutableList;
90
91 /**
92 * The Control Flow view main object
93 *
94 */
95 public class ControlFlowView extends AbstractStateSystemTimeGraphView {
96
97 // ------------------------------------------------------------------------
98 // Constants
99 // ------------------------------------------------------------------------
100 /**
101 * View ID.
102 */
103 public static final @NonNull String ID = "org.eclipse.tracecompass.analysis.os.linux.views.controlflow"; //$NON-NLS-1$
104
105 private static final String ICONS_PATH = "icons/"; //$NON-NLS-1$
106 private static final String OPTIMIZE_ICON = ICONS_PATH + "elcl16/Optimization.png"; //$NON-NLS-1$
107
108 private static final String PROCESS_COLUMN = Messages.ControlFlowView_processColumn;
109 private static final String TID_COLUMN = Messages.ControlFlowView_tidColumn;
110 private static final String PTID_COLUMN = Messages.ControlFlowView_ptidColumn;
111 private static final String BIRTH_TIME_COLUMN = Messages.ControlFlowView_birthTimeColumn;
112 private static final String INVISIBLE_COLUMN = Messages.ControlFlowView_invisibleColumn;
113 private Action fOptimizationAction;
114
115 private static final String NEXT_EVENT_ICON_PATH = "icons/elcl16/shift_r_edit.gif"; //$NON-NLS-1$
116 private static final String PREV_EVENT_ICON_PATH = "icons/elcl16/shift_l_edit.gif"; //$NON-NLS-1$
117
118 private static final String[] COLUMN_NAMES = new String[] {
119 PROCESS_COLUMN,
120 TID_COLUMN,
121 PTID_COLUMN,
122 BIRTH_TIME_COLUMN
123 };
124
125 private static final String[] FILTER_COLUMN_NAMES = new String[] {
126 PROCESS_COLUMN,
127 TID_COLUMN
128 };
129
130 // Timeout between updates in the build thread in ms
131 private static final long BUILD_UPDATE_TIMEOUT = 500;
132
133 private static final Comparator<ITimeGraphEntry>[] COLUMN_COMPARATORS;
134
135 private final Function<Collection<ILinkEvent>, Map<Integer, Long>> UPDATE_SCHEDULING_COLUMN_ALGO = new NaiveOptimizationAlgorithm();
136
137 private static final int INITIAL_SORT_COLUMN_INDEX = 3;
138
139 static {
140 ImmutableList.Builder<Comparator<ITimeGraphEntry>> builder = ImmutableList.builder();
141 builder.add(ControlFlowColumnComparators.PROCESS_NAME_COLUMN_COMPARATOR)
142 .add(ControlFlowColumnComparators.TID_COLUMN_COMPARATOR)
143 .add(ControlFlowColumnComparators.PTID_COLUMN_COMPARATOR)
144 .add(ControlFlowColumnComparators.BIRTH_TIME_COLUMN_COMPARATOR);
145 List<Comparator<ITimeGraphEntry>> l = builder.build();
146 COLUMN_COMPARATORS = l.toArray(new Comparator[l.size()]);
147 }
148
149 /**
150 * Mutex rule for search action jobs, making sure they execute sequentially
151 */
152 private final ISchedulingRule fSearchActionMutexRule = new ISchedulingRule() {
153 @Override
154 public boolean isConflicting(ISchedulingRule rule) {
155 return (rule == this);
156 }
157
158 @Override
159 public boolean contains(ISchedulingRule rule) {
160 return (rule == this);
161 }
162 };
163
164 private final Set<ITmfTrace> fFlatTraces = new HashSet<>();
165
166 private MenuManager fThreadPresentationMenu;
167 private IAction fFlatAction;
168
169 private IAction fHierarchicalAction;
170 private IAction fPreviousEventAction;
171 private IAction fNextEventAction;
172
173 // ------------------------------------------------------------------------
174 // Constructors
175 // ------------------------------------------------------------------------
176
177 /**
178 * Constructor
179 */
180 public ControlFlowView() {
181 super(ID, new ControlFlowPresentationProvider());
182 setTreeColumns(COLUMN_NAMES, COLUMN_COMPARATORS, INITIAL_SORT_COLUMN_INDEX);
183 setTreeLabelProvider(new ControlFlowTreeLabelProvider());
184 setFilterColumns(FILTER_COLUMN_NAMES);
185 setFilterLabelProvider(new ControlFlowFilterLabelProvider());
186 setEntryComparator(ControlFlowColumnComparators.BIRTH_TIME_COLUMN_COMPARATOR);
187 }
188
189 @Override
190 public void createPartControl(Composite parent) {
191 super.createPartControl(parent);
192 // add "Check active" Button to TimeGraphFilterDialog
193 super.getTimeGraphCombo().addTimeGraphFilterCheckActiveButton(
194 new ControlFlowCheckActiveProvider(Messages.ControlFlowView_checkActiveLabel, Messages.ControlFlowView_checkActiveToolTip));
195 // add "Uncheck inactive" Button to TimeGraphFilterDialog
196 super.getTimeGraphCombo().addTimeGraphFilterUncheckInactiveButton(
197 new ControlFlowCheckActiveProvider(Messages.ControlFlowView_uncheckInactiveLabel, Messages.ControlFlowView_uncheckInactiveToolTip));
198 }
199
200 /**
201 * @since 2.0
202 */
203 @Override
204 protected void fillTimeGraphEntryContextMenu(@NonNull IMenuManager menuManager) {
205 ISelection selection = getSite().getSelectionProvider().getSelection();
206 if (selection instanceof StructuredSelection) {
207 StructuredSelection sSel = (StructuredSelection) selection;
208 if (sSel.getFirstElement() instanceof ControlFlowEntry) {
209 ControlFlowEntry entry = (ControlFlowEntry) sSel.getFirstElement();
210 menuManager.add(new FollowThreadAction(ControlFlowView.this, entry.getName(), entry.getThreadId(), entry.getTrace()));
211 }
212 }
213 }
214
215 @Override
216 protected void fillLocalToolBar(IToolBarManager manager) {
217 // add "Optimization" Button to local tool bar of Controlflow
218 IAction optimizationAction = getOptimizationAction();
219 manager.add(optimizationAction);
220
221 // add a separator to local tool bar
222 manager.add(new Separator());
223
224 super.fillLocalToolBar(manager);
225 IDialogSettings settings = Activator.getDefault().getDialogSettings();
226 IDialogSettings section = settings.getSection(getClass().getName());
227 if (section == null) {
228 section = settings.addNewSection(getClass().getName());
229 }
230
231 IAction hideArrowsAction = getTimeGraphCombo().getTimeGraphViewer().getHideArrowsAction(section);
232 manager.add(hideArrowsAction);
233
234 IAction followArrowBwdAction = getTimeGraphCombo().getTimeGraphViewer().getFollowArrowBwdAction();
235 followArrowBwdAction.setText(Messages.ControlFlowView_followCPUBwdText);
236 followArrowBwdAction.setToolTipText(Messages.ControlFlowView_followCPUBwdText);
237 manager.add(followArrowBwdAction);
238
239 IAction followArrowFwdAction = getTimeGraphCombo().getTimeGraphViewer().getFollowArrowFwdAction();
240 followArrowFwdAction.setText(Messages.ControlFlowView_followCPUFwdText);
241 followArrowFwdAction.setToolTipText(Messages.ControlFlowView_followCPUFwdText);
242 manager.add(followArrowFwdAction);
243
244 fPreviousEventAction = new SearchEventAction(false, PackageMessages.ControlFlowView_PreviousEventJobName);
245 fPreviousEventAction.setText(PackageMessages.ControlFlowView_PreviousEventActionName);
246 fPreviousEventAction.setToolTipText(PackageMessages.ControlFlowView_PreviousEventActionTooltip);
247 fPreviousEventAction.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(PREV_EVENT_ICON_PATH));
248 manager.add(fPreviousEventAction);
249
250 fNextEventAction = new SearchEventAction(true, PackageMessages.ControlFlowView_NextEventJobName);
251 fNextEventAction.setText(PackageMessages.ControlFlowView_NextEventActionName);
252 fNextEventAction.setToolTipText(PackageMessages.ControlFlowView_NextEventActionTooltip);
253 fNextEventAction.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(NEXT_EVENT_ICON_PATH));
254 manager.add(fNextEventAction);
255 }
256
257 private IAction getOptimizationAction() {
258 if (fOptimizationAction == null) {
259 fOptimizationAction = new OptimizationAction();
260 fOptimizationAction.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(OPTIMIZE_ICON));
261 fOptimizationAction.setText(Messages.ControlFlowView_optimizeLabel);
262 fOptimizationAction.setToolTipText(Messages.ControlFlowView_optimizeToolTip);
263 }
264 return fOptimizationAction;
265 }
266
267 @Override
268 protected void fillLocalMenu(IMenuManager manager) {
269 super.fillLocalMenu(manager);
270 fThreadPresentationMenu = new MenuManager(Messages.ControlFlowView_threadPresentation);
271 fFlatAction = createFlatAction();
272 fThreadPresentationMenu.add(fFlatAction);
273
274 fHierarchicalAction = createHierarchicalAction();
275 fThreadPresentationMenu.add(fHierarchicalAction);
276 manager.add(fThreadPresentationMenu);
277
278 }
279
280 /**
281 * Base Action for the "Go to Next/Previous Event for thread" actions
282 */
283 private class SearchEventAction extends Action {
284
285 private final boolean ifDirection;
286 private final String ifJobName;
287
288 /**
289 * Constructor
290 *
291 * @param direction
292 * The direction of the search, "true" for forwards and
293 * "false" for backwards.
294 * @param jobName
295 * The name of the job that will be spawned
296 */
297 public SearchEventAction(boolean direction, String jobName) {
298 ifDirection = direction;
299 ifJobName = jobName;
300 }
301
302 @Override
303 public void run() {
304 Job job = new Job(ifJobName) {
305 @Override
306 protected IStatus run(IProgressMonitor monitor) {
307 TimeGraphControl ctrl = getTimeGraphViewer().getTimeGraphControl();
308 ITimeGraphEntry traceEntry = ctrl.getSelectedTrace();
309
310 long ts = getTimeGraphViewer().getSelectionBegin();
311 ITimeEvent selectedState = Utils.findEvent(traceEntry, ts, 0);
312
313 if (selectedState == null) {
314 /* No selection currently in the view, do nothing */
315 return Status.OK_STATUS;
316 }
317 ITimeGraphEntry entry = selectedState.getEntry();
318 if (!(entry instanceof ControlFlowEntry)) {
319 return Status.OK_STATUS;
320 }
321 ControlFlowEntry cfEntry = (ControlFlowEntry) entry;
322 int tid = cfEntry.getThreadId();
323
324 ITmfTrace trace = cfEntry.getTrace();
325 ITmfContext ctx = trace.seekEvent(TmfTimestamp.fromNanos(ts));
326 long rank = ctx.getRank();
327 ctx.dispose();
328
329 Predicate<@NonNull ITmfEvent> predicate = event -> {
330 /*
331 * TODO Specific to the Control Flow View and kernel
332 * traces for now. Could be eventually generalized to
333 * anything represented by the time graph row.
334 */
335 Integer eventTid = KernelTidAspect.INSTANCE.resolve(event);
336 return (eventTid != null && eventTid.intValue() == tid);
337 };
338
339 ITmfEvent event = (ifDirection ?
340 TmfTraceUtils.getNextEventMatching(cfEntry.getTrace(), rank, predicate, monitor) :
341 TmfTraceUtils.getPreviousEventMatching(cfEntry.getTrace(), rank, predicate, monitor));
342 if (event != null) {
343 TmfSignalManager.dispatchSignal(new TmfSelectionRangeUpdatedSignal(this, event.getTimestamp()));
344 }
345 return Status.OK_STATUS;
346
347 }
348 };
349 /*
350 * Make subsequent jobs not run concurrently, but wait after one
351 * another.
352 */
353 job.setRule(fSearchActionMutexRule);
354 job.schedule();
355 }
356 }
357
358 private IAction createHierarchicalAction() {
359 IAction action = new Action(Messages.ControlFlowView_hierarchicalViewLabel, IAction.AS_RADIO_BUTTON) {
360 @Override
361 public void run() {
362 ITmfTrace parentTrace = getTrace();
363 synchronized (fFlatTraces) {
364 fFlatTraces.remove(parentTrace);
365 for (ITmfTrace trace : TmfTraceManager.getTraceSet(parentTrace)) {
366 final ITmfStateSystem ss = TmfStateSystemAnalysisModule.getStateSystem(trace, KernelAnalysisModule.ID);
367 for (TimeGraphEntry traceEntry : getEntryList(ss)) {
368 List<ControlFlowEntry> currentRootList = traceEntry.getChildren().stream()
369 .filter(e -> e instanceof ControlFlowEntry)
370 .map(e -> (ControlFlowEntry) e)
371 .collect(Collectors.toList());
372 addEntriesToHierarchicalTree(currentRootList, traceEntry);
373 }
374 }
375 }
376 refresh();
377 }
378 };
379 action.setChecked(true);
380 action.setToolTipText(Messages.ControlFlowView_hierarchicalViewToolTip);
381 return action;
382 }
383
384 private IAction createFlatAction() {
385 IAction action = new Action(Messages.ControlFlowView_flatViewLabel, IAction.AS_RADIO_BUTTON) {
386 @Override
387 public void run() {
388 ITmfTrace parentTrace = getTrace();
389 synchronized (fFlatTraces) {
390 fFlatTraces.add(parentTrace);
391 for (ITmfTrace trace : TmfTraceManager.getTraceSet(parentTrace)) {
392 final ITmfStateSystem ss = TmfStateSystemAnalysisModule.getStateSystem(trace, KernelAnalysisModule.ID);
393 List<@NonNull TimeGraphEntry> entryList = getEntryList(ss);
394 if (entryList != null) {
395 for (TimeGraphEntry traceEntry : entryList) {
396 hierarchicalToFlatTree(traceEntry);
397 }
398 }
399 }
400 }
401 refresh();
402 }
403 };
404 action.setToolTipText(Messages.ControlFlowView_flatViewToolTip);
405 return action;
406 }
407
408 @Override
409 protected String getNextText() {
410 return Messages.ControlFlowView_nextProcessActionNameText;
411 }
412
413 @Override
414 protected String getNextTooltip() {
415 return Messages.ControlFlowView_nextProcessActionToolTipText;
416 }
417
418 @Override
419 protected String getPrevText() {
420 return Messages.ControlFlowView_previousProcessActionNameText;
421 }
422
423 @Override
424 protected String getPrevTooltip() {
425 return Messages.ControlFlowView_previousProcessActionToolTipText;
426 }
427
428 /**
429 * Get the optimization function for the scheduling column. In the base
430 * implementation, this optimizes by Line arrows, but can be overidden.
431 * <p>
432 * It takes a collection of link events, looking at the entries being
433 * linked, and returns a list of the proposed order. The list of indexes
434 * should be in ascending order. There can be duplicates, but the values and
435 * order should always be the same for the same input.
436 *
437 * @return the returned column order, where the integer is the tid of the
438 * entry, and the return value is the position, there can be
439 * duplicates.
440 */
441 public Function<Collection<ILinkEvent>, Map<Integer, Long>> getUpdatedSchedulingColumn() {
442 return UPDATE_SCHEDULING_COLUMN_ALGO;
443 }
444
445 /**
446 * This is an optimization action used to find cliques of entries due to
447 * links and put them closer together
448 *
449 * @author Samuel Gagnon
450 */
451 private final class OptimizationAction extends Action {
452
453 @Override
454 public void runWithEvent(Event event) {
455 ITmfTrace trace = getTrace();
456 if (trace == null) {
457 return;
458 }
459
460 createFlatAction().run();
461
462 /*
463 * This method only returns the arrows in the current time interval
464 * [a,b] of ControlFlowView. Thus, we only optimize for that time
465 * interval
466 */
467 List<ILinkEvent> arrows = getTimeGraphViewer().getTimeGraphControl().getArrows();
468 final ITmfStateSystem ss = TmfStateSystemAnalysisModule.getStateSystem(trace, KernelAnalysisModule.ID);
469 List<TimeGraphEntry> currentList = getEntryList(ss);
470
471 Map<Integer, Long> orderedTidMap = getUpdatedSchedulingColumn().apply(arrows);
472
473 /*
474 * Now that we have our list of ordered tid, it's time to assign a
475 * position for each threads in the view. For this, we assign a
476 * value to an invisible column and sort according to the values in
477 * this column.
478 */
479 for (TimeGraphEntry entry : currentList) {
480 if (entry instanceof TraceEntry) {
481 for (TimeGraphEntry child : ((TraceEntry) entry).getChildren()) {
482 if (child instanceof ControlFlowEntry) {
483 ControlFlowEntry cEntry = (ControlFlowEntry) child;
484 /*
485 * If the thread is in our list, we give it a
486 * position. Otherwise, it means there's no activity
487 * in the current interval for that thread. We set
488 * its position to Long.MAX_VALUE so it goes to the
489 * bottom.
490 */
491 cEntry.setSchedulingPosition(orderedTidMap.getOrDefault(cEntry.getThreadId(), Long.MAX_VALUE));
492 }
493 }
494 }
495 }
496
497 setEntryComparator(ControlFlowColumnComparators.SCHEDULING_COLUMN_COMPARATOR);
498 refresh();
499 }
500
501 }
502
503 /**
504 * @author gbastien
505 *
506 */
507 protected static class ControlFlowTreeLabelProvider extends TreeLabelProvider {
508
509 @Override
510 public String getColumnText(Object element, int columnIndex) {
511 if (element instanceof TraceEntry) {
512 if (columnIndex == 0) {
513 return ((TraceEntry) element).getName();
514 }
515 return ""; //$NON-NLS-1$
516 }
517 ControlFlowEntry entry = (ControlFlowEntry) element;
518
519 if (COLUMN_NAMES[columnIndex].equals(Messages.ControlFlowView_processColumn)) {
520 return entry.getName();
521 } else if (COLUMN_NAMES[columnIndex].equals(Messages.ControlFlowView_tidColumn)) {
522 return Integer.toString(entry.getThreadId());
523 } else if (COLUMN_NAMES[columnIndex].equals(Messages.ControlFlowView_ptidColumn)) {
524 if (entry.getParentThreadId() > 0) {
525 return Integer.toString(entry.getParentThreadId());
526 }
527 } else if (COLUMN_NAMES[columnIndex].equals(Messages.ControlFlowView_birthTimeColumn)) {
528 return Utils.formatTime(entry.getStartTime(), TimeFormat.CALENDAR, Resolution.NANOSEC);
529 } else if (COLUMN_NAMES[columnIndex].equals(Messages.ControlFlowView_traceColumn)) {
530 return entry.getTrace().getName();
531 } else if (COLUMN_NAMES[columnIndex].equals(INVISIBLE_COLUMN)) {
532 return Long.toString(entry.getSchedulingPosition());
533 }
534 return ""; //$NON-NLS-1$
535 }
536
537 }
538
539 private static class ControlFlowFilterLabelProvider extends TreeLabelProvider {
540
541 @Override
542 public String getColumnText(Object element, int columnIndex) {
543 if (element instanceof TraceEntry) {
544 if (columnIndex == 0) {
545 return ((TraceEntry) element).getName();
546 }
547 return ""; //$NON-NLS-1$
548 }
549 ControlFlowEntry entry = (ControlFlowEntry) element;
550
551 if (columnIndex == 0) {
552 return entry.getName();
553 } else if (columnIndex == 1) {
554 return Integer.toString(entry.getThreadId());
555 }
556 return ""; //$NON-NLS-1$
557 }
558
559 }
560
561 private static class TraceEntry extends TimeGraphEntry {
562
563 public TraceEntry(String name, long startTime, long endTime) {
564 super(name, startTime, endTime);
565 }
566
567 @Override
568 public boolean hasTimeEvents() {
569 return false;
570 }
571 }
572
573 @TmfSignalHandler
574 @Override
575 public void traceClosed(org.eclipse.tracecompass.tmf.core.signal.TmfTraceClosedSignal signal) {
576 super.traceClosed(signal);
577 synchronized (fFlatTraces) {
578 fFlatTraces.remove(signal.getTrace());
579 }
580 }
581
582 @TmfSignalHandler
583 @Override
584 public void traceSelected(TmfTraceSelectedSignal signal) {
585 super.traceSelected(signal);
586 synchronized (fFlatTraces) {
587 if (fFlatTraces.contains(signal.getTrace())) {
588 fHierarchicalAction.setChecked(false);
589 fFlatAction.setChecked(true);
590 } else {
591 fFlatAction.setChecked(false);
592 fHierarchicalAction.setChecked(true);
593 }
594 }
595 }
596
597 // ------------------------------------------------------------------------
598 // Internal
599 // ------------------------------------------------------------------------
600
601 @Override
602 protected void buildEntryList(final ITmfTrace trace, final ITmfTrace parentTrace, final IProgressMonitor monitor) {
603 final ITmfStateSystem ssq = TmfStateSystemAnalysisModule.getStateSystem(trace, KernelAnalysisModule.ID);
604 if (ssq == null) {
605 return;
606 }
607
608 final List<ControlFlowEntry> entryList = new ArrayList<>();
609 /** Map of trace entries */
610 Map<ITmfTrace, TraceEntry> traceEntryMap = new HashMap<>();
611 /** Map of control flow entries, key is a pair [threadId, cpuId] */
612 final Map<Pair<Integer, Integer>, ControlFlowEntry> entryMap = new HashMap<>();
613
614 long start = ssq.getStartTime();
615 setStartTime(Math.min(getStartTime(), start));
616
617 boolean complete = false;
618 while (!complete) {
619 if (monitor.isCanceled()) {
620 return;
621 }
622 complete = ssq.waitUntilBuilt(BUILD_UPDATE_TIMEOUT);
623 if (ssq.isCancelled()) {
624 return;
625 }
626 long end = ssq.getCurrentEndTime();
627 if (start == end && !complete) { // when complete execute one last time regardless of end time
628 continue;
629 }
630
631 TraceEntry aTraceEntry = traceEntryMap.get(trace);
632 if (aTraceEntry == null) {
633 aTraceEntry = new TraceEntry(trace.getName(), start, end + 1);
634 traceEntryMap.put(trace, aTraceEntry);
635 addToEntryList(parentTrace, ssq, Collections.singletonList(aTraceEntry));
636 } else {
637 aTraceEntry.updateEndTime(end + 1);
638 }
639 final TraceEntry traceEntry = aTraceEntry;
640
641 final long resolution = Math.max(1, (end - ssq.getStartTime()) / getDisplayWidth());
642 setEndTime(Math.max(getEndTime(), end + 1));
643 final List<Integer> threadQuarks = ssq.getQuarks(Attributes.THREADS, "*"); //$NON-NLS-1$
644 queryFullStates(ssq, start, end, resolution, monitor, new IQueryHandler() {
645 @Override
646 public void handle(List<List<ITmfStateInterval>> fullStates, List<ITmfStateInterval> prevFullState) {
647 for (int threadQuark : threadQuarks) {
648 String threadAttributeName = ssq.getAttributeName(threadQuark);
649
650 Pair<Integer, Integer> entryKey = Attributes.parseThreadAttributeName(threadAttributeName);
651 int threadId = entryKey.getFirst();
652
653 if (threadId < 0) { // ignore the 'unknown' (-1) thread
654 continue;
655 }
656
657 int execNameQuark = ssq.optQuarkRelative(threadQuark, Attributes.EXEC_NAME);
658 int ppidQuark = ssq.optQuarkRelative(threadQuark, Attributes.PPID);
659 if (execNameQuark == ITmfStateSystem.INVALID_ATTRIBUTE) {
660 /* No information on this thread (yet?), skip it for now */
661 continue;
662 }
663 ITmfStateInterval lastExecNameInterval = prevFullState == null || execNameQuark >= prevFullState.size() ? null : prevFullState.get(execNameQuark);
664 long lastExecNameStartTime = lastExecNameInterval == null ? -1 : lastExecNameInterval.getStartTime();
665 long lastExecNameEndTime = lastExecNameInterval == null ? -1 : lastExecNameInterval.getEndTime() + 1;
666 long lastPpidStartTime = prevFullState == null || ppidQuark >= prevFullState.size() || ppidQuark == ITmfStateSystem.INVALID_ATTRIBUTE ? -1 : prevFullState.get(ppidQuark).getStartTime();
667 for (List<ITmfStateInterval> fullState : fullStates) {
668 if (monitor.isCanceled()) {
669 return;
670 }
671 if (execNameQuark >= fullState.size() || ppidQuark >= fullState.size()) {
672 /* No information on this thread (yet?), skip it for now */
673 continue;
674 }
675 ITmfStateInterval execNameInterval = fullState.get(execNameQuark);
676 ITmfStateInterval ppidInterval = ppidQuark == ITmfStateSystem.INVALID_ATTRIBUTE ? null : fullState.get(ppidQuark);
677 long startTime = execNameInterval.getStartTime();
678 long endTime = execNameInterval.getEndTime() + 1;
679 if (startTime == lastExecNameStartTime && ppidInterval != null && ppidInterval.getStartTime() == lastPpidStartTime) {
680 continue;
681 }
682 boolean isNull = execNameInterval.getStateValue().isNull();
683 if (isNull && lastExecNameEndTime < startTime && lastExecNameEndTime != -1) {
684 /*
685 * There was a non-null interval in between the
686 * full states, try to use it.
687 */
688 try {
689 execNameInterval = ssq.querySingleState(startTime - 1, execNameQuark);
690 ppidInterval = ppidQuark == ITmfStateSystem.INVALID_ATTRIBUTE ? null : ssq.querySingleState(startTime - 1, ppidQuark);
691 startTime = execNameInterval.getStartTime();
692 endTime = execNameInterval.getEndTime() + 1;
693 } catch (StateSystemDisposedException e) {
694 /* ignored */
695 }
696 }
697 if (!execNameInterval.getStateValue().isNull() &&
698 execNameInterval.getStateValue().getType() == ITmfStateValue.Type.STRING) {
699 String execName = execNameInterval.getStateValue().unboxStr();
700 int ppid = ppidInterval == null ? -1 : ppidInterval.getStateValue().unboxInt();
701 ControlFlowEntry entry = entryMap.get(entryKey);
702 if (entry == null) {
703 entry = new ControlFlowEntry(threadQuark, trace, execName, threadId, ppid, startTime, endTime);
704 entryList.add(entry);
705 entryMap.put(entryKey, entry);
706 } else {
707 /*
708 * Update the name of the entry to the
709 * latest execName and the parent thread id
710 * to the latest ppid.
711 */
712 entry.setName(execName);
713 entry.setParentThreadId(ppid);
714 entry.updateEndTime(endTime);
715 }
716 }
717 if (isNull) {
718 entryMap.remove(entryKey);
719 }
720 lastExecNameStartTime = startTime;
721 lastExecNameEndTime = endTime;
722 lastPpidStartTime = ppidInterval == null ? -1 : ppidInterval.getStartTime();
723 }
724 }
725 synchronized (fFlatTraces) {
726 if (fFlatTraces.contains(parentTrace)) {
727 addEntriesToFlatTree(entryList, traceEntry);
728 } else {
729 addEntriesToHierarchicalTree(entryList, traceEntry);
730 }
731 }
732 }
733 });
734
735 queryFullStates(ssq, ssq.getStartTime(), end, resolution, monitor, new IQueryHandler() {
736 @Override
737 public void handle(@NonNull List<List<ITmfStateInterval>> fullStates, @Nullable List<ITmfStateInterval> prevFullState) {
738 for (final TimeGraphEntry entry : traceEntry.getChildren()) {
739 if (monitor.isCanceled()) {
740 return;
741 }
742 buildStatusEvents(trace, parentTrace, ssq, fullStates, prevFullState, (ControlFlowEntry) entry, monitor, ssq.getStartTime(), end);
743 }
744 }
745 });
746
747 if (parentTrace.equals(getTrace())) {
748 refresh();
749 }
750
751 start = end;
752 }
753 }
754
755 /**
756 * Add entries to the traces's child list in a flat fashion (no hierarchy).
757 * If one entry has children, we do a depth first search to add each child
758 * to the trace's child list and update the parent and child relations.
759 */
760 private static void hierarchicalToFlatTree(TimeGraphEntry traceEntry) {
761 List<@NonNull TimeGraphEntry> rootList = traceEntry.getChildren();
762 // We visit the children of every entry to add
763 StreamFlattener<TimeGraphEntry> sf = new StreamFlattener<>(entry -> entry.getChildren().stream());
764 Stream<TimeGraphEntry> allEntries = rootList.stream().flatMap(entry -> sf.flatten(entry));
765
766 // We add every entry that is missing from the trace's entry list
767 List<@NonNull TimeGraphEntry> rootListToAdd = allEntries
768 .filter(entry -> !rootList.contains(entry))
769 .collect(Collectors.toList());
770 rootList.forEach(entry -> {
771 entry.clearChildren();
772 });
773 rootListToAdd.forEach(entry -> {
774 traceEntry.addChild(entry);
775 entry.clearChildren();
776 });
777 }
778
779 /**
780 * Add entries to the traces's child list in a flat fashion (no hierarchy).
781 */
782 private static void addEntriesToFlatTree(List<@NonNull ControlFlowEntry> entryList, TimeGraphEntry traceEntry) {
783 List<TimeGraphEntry> rootList = traceEntry.getChildren();
784 for (ControlFlowEntry entry : entryList) {
785 if (!rootList.contains(entry)) {
786 traceEntry.addChild(entry);
787 }
788 }
789 }
790
791 /**
792 * Add entries to the trace's child list in a hierarchical fashion.
793 */
794 private static void addEntriesToHierarchicalTree(List<ControlFlowEntry> entryList, TimeGraphEntry traceEntry) {
795 List<TimeGraphEntry> rootList = traceEntry.getChildren();
796
797 for (ControlFlowEntry entry : entryList) {
798 boolean root = (entry.getParent() == null || entry.getParent() == traceEntry);
799 if (root && entry.getParentThreadId() > 0) {
800 for (ControlFlowEntry parent : entryList) {
801 /*
802 * Associate the parent entry only if their time overlap. A
803 * child entry may start before its parent, for example at
804 * the beginning of the trace if a parent has not yet
805 * appeared in the state system. We just want to make sure
806 * that the entry didn't start after the parent ended or
807 * ended before the parent started.
808 */
809 if (parent.getThreadId() == entry.getParentThreadId() &&
810 !(entry.getStartTime() > parent.getEndTime() ||
811 entry.getEndTime() < parent.getStartTime())) {
812 root = false;
813 if (rootList.contains(entry)) {
814 traceEntry.removeChild(entry);
815 }
816 parent.addChild(entry);
817 break;
818 }
819 }
820 }
821 if (root && (!rootList.contains(entry))) {
822 traceEntry.addChild(entry);
823 }
824 }
825 }
826
827 private void buildStatusEvents(ITmfTrace trace, ITmfTrace parentTrace, ITmfStateSystem ss, @NonNull List<List<ITmfStateInterval>> fullStates,
828 @Nullable List<ITmfStateInterval> prevFullState, ControlFlowEntry entry, @NonNull IProgressMonitor monitor, long start, long end) {
829 if (start < entry.getEndTime() && end > entry.getStartTime()) {
830 List<ITimeEvent> eventList = getEventList(entry, ss, fullStates, prevFullState, monitor);
831 if (eventList == null) {
832 return;
833 }
834 /* Start a new event list on first iteration, then append to it */
835 if (prevFullState == null) {
836 entry.setEventList(eventList);
837 } else {
838 for (ITimeEvent event : eventList) {
839 entry.addEvent(event);
840 }
841 }
842 if (parentTrace.equals(getTrace())) {
843 redraw();
844 }
845 }
846 for (ITimeGraphEntry child : entry.getChildren()) {
847 if (monitor.isCanceled()) {
848 return;
849 }
850 buildStatusEvents(trace, parentTrace, ss, fullStates, prevFullState, (ControlFlowEntry) child, monitor, start, end);
851 }
852 }
853
854 @Override
855 protected @Nullable List<ITimeEvent> getEventList(@NonNull TimeGraphEntry tgentry, ITmfStateSystem ss,
856 @NonNull List<List<ITmfStateInterval>> fullStates, @Nullable List<ITmfStateInterval> prevFullState, @NonNull IProgressMonitor monitor) {
857 List<ITimeEvent> eventList = null;
858 if (!(tgentry instanceof ControlFlowEntry)) {
859 return eventList;
860 }
861 ControlFlowEntry entry = (ControlFlowEntry) tgentry;
862 try {
863 int statusQuark = entry.getThreadQuark();
864 eventList = new ArrayList<>(fullStates.size());
865 ITmfStateInterval lastInterval = prevFullState == null || statusQuark >= prevFullState.size() ? null : prevFullState.get(statusQuark);
866 long lastStartTime = lastInterval == null ? -1 : lastInterval.getStartTime();
867 long lastEndTime = lastInterval == null ? -1 : lastInterval.getEndTime() + 1;
868 for (List<ITmfStateInterval> fullState : fullStates) {
869 if (monitor.isCanceled()) {
870 return null;
871 }
872 if (statusQuark >= fullState.size()) {
873 /* No information on this thread (yet?), skip it for now */
874 continue;
875 }
876 ITmfStateInterval statusInterval = fullState.get(statusQuark);
877 long time = statusInterval.getStartTime();
878 if (time == lastStartTime) {
879 continue;
880 }
881 long duration = statusInterval.getEndTime() - time + 1;
882 int status = -1;
883 try {
884 status = statusInterval.getStateValue().unboxInt();
885 } catch (StateValueTypeException e) {
886 Activator.getDefault().logError(e.getMessage());
887 }
888 if (lastEndTime != time && lastEndTime != -1) {
889 eventList.add(new TimeEvent(entry, lastEndTime, time - lastEndTime));
890 }
891 if (!statusInterval.getStateValue().isNull()) {
892 eventList.add(new TimeEvent(entry, time, duration, status));
893 } else {
894 eventList.add(new NullTimeEvent(entry, time, duration));
895 }
896 lastStartTime = time;
897 lastEndTime = time + duration;
898 }
899 } catch (TimeRangeException e) {
900 Activator.getDefault().logError(e.getMessage());
901 }
902 return eventList;
903 }
904
905 /**
906 * Returns a value corresponding to the selected entry.
907 *
908 * Used in conjunction with synchingToTime to change the selected entry. If
909 * one of these methods is overridden in child class, then both should be.
910 *
911 * @param time
912 * The currently selected time
913 * @return a value identifying the entry
914 */
915 private int getSelectionValue(long time) {
916 int thread = -1;
917 for (ITmfTrace trace : TmfTraceManager.getTraceSet(getTrace())) {
918 if (thread > 0) {
919 break;
920 }
921 ITmfStateSystem ssq = TmfStateSystemAnalysisModule.getStateSystem(trace, KernelAnalysisModule.ID);
922 if (ssq == null) {
923 continue;
924 }
925 if (time >= ssq.getStartTime() && time <= ssq.getCurrentEndTime()) {
926 List<Integer> currentThreadQuarks = ssq.getQuarks(Attributes.CPUS, "*", Attributes.CURRENT_THREAD); //$NON-NLS-1$
927 for (int currentThreadQuark : currentThreadQuarks) {
928 try {
929 ITmfStateInterval currentThreadInterval = ssq.querySingleState(time, currentThreadQuark);
930 int currentThread = currentThreadInterval.getStateValue().unboxInt();
931 if (currentThread > 0) {
932 int statusQuark = ssq.getQuarkAbsolute(Attributes.THREADS, Integer.toString(currentThread));
933 ITmfStateInterval statusInterval = ssq.querySingleState(time, statusQuark);
934 if (statusInterval.getStartTime() == time) {
935 thread = currentThread;
936 break;
937 }
938 }
939 } catch (AttributeNotFoundException | TimeRangeException | StateValueTypeException e) {
940 Activator.getDefault().logError(e.getMessage());
941 } catch (StateSystemDisposedException e) {
942 /* Ignored */
943 }
944 }
945 }
946 }
947 return thread;
948 }
949
950 @Override
951 protected void synchingToTime(long time) {
952 int selected = getSelectionValue(time);
953 if (selected > 0) {
954 for (Object element : getTimeGraphViewer().getExpandedElements()) {
955 if (element instanceof ControlFlowEntry) {
956 ControlFlowEntry entry = (ControlFlowEntry) element;
957 if (entry.getThreadId() == selected) {
958 getTimeGraphCombo().setSelection(entry);
959 break;
960 }
961 }
962 }
963 }
964 }
965
966 @Override
967 protected @NonNull List<ILinkEvent> getLinkList(ITmfStateSystem ss,
968 @NonNull List<List<ITmfStateInterval>> fullStates, @Nullable List<ITmfStateInterval> prevFullState, @NonNull IProgressMonitor monitor) {
969 List<ILinkEvent> list = new ArrayList<>();
970 List<TimeGraphEntry> entryList = getEntryList(ss);
971 if (entryList == null) {
972 return list;
973 }
974 for (ITmfTrace trace : TmfTraceManager.getTraceSet(getTrace())) {
975 List<Integer> currentThreadQuarks = ss.getQuarks(Attributes.CPUS, "*", Attributes.CURRENT_THREAD); //$NON-NLS-1$
976 for (int currentThreadQuark : currentThreadQuarks) {
977 if (currentThreadQuark >= fullStates.get(0).size()) {
978 /* No information on this cpu (yet?), skip it for now */
979 continue;
980 }
981 List<ITmfStateInterval> currentThreadIntervals = new ArrayList<>(fullStates.size() + 2);
982 try {
983 /*
984 * Add the previous interval if it is the first query
985 * iteration and the first interval has currentThread=0. Add
986 * the following interval if the last interval has
987 * currentThread=0. These are diagonal arrows crossing the
988 * query iteration range.
989 */
990 if (prevFullState == null) {
991 ITmfStateInterval currentThreadInterval = fullStates.get(0).get(currentThreadQuark);
992 if (currentThreadInterval.getStateValue().unboxInt() == 0) {
993 long start = Math.max(currentThreadInterval.getStartTime() - 1, ss.getStartTime());
994 currentThreadIntervals.add(ss.querySingleState(start, currentThreadQuark));
995 }
996 }
997 for (List<ITmfStateInterval> fullState : fullStates) {
998 currentThreadIntervals.add(fullState.get(currentThreadQuark));
999 }
1000 ITmfStateInterval currentThreadInterval = fullStates.get(fullStates.size() - 1).get(currentThreadQuark);
1001 if (currentThreadInterval.getStateValue().unboxInt() == 0) {
1002 long end = Math.min(currentThreadInterval.getEndTime() + 1, ss.getCurrentEndTime());
1003 currentThreadIntervals.add(ss.querySingleState(end, currentThreadQuark));
1004 }
1005 } catch (StateSystemDisposedException e) {
1006 /* Ignored */
1007 return list;
1008 }
1009 int prevThread = 0;
1010 long prevEnd = 0;
1011 long lastEnd = 0;
1012 for (ITmfStateInterval currentThreadInterval : currentThreadIntervals) {
1013 if (monitor.isCanceled()) {
1014 return list;
1015 }
1016 if (currentThreadInterval.getEndTime() + 1 == lastEnd) {
1017 continue;
1018 }
1019 long time = currentThreadInterval.getStartTime();
1020 if (time != lastEnd) {
1021 // don't create links where there are gaps in intervals due to the resolution
1022 prevThread = 0;
1023 prevEnd = 0;
1024 }
1025 int thread = currentThreadInterval.getStateValue().unboxInt();
1026 if (thread > 0 && prevThread > 0) {
1027 ITimeGraphEntry prevEntry = findEntry(entryList, trace, prevThread);
1028 ITimeGraphEntry nextEntry = findEntry(entryList, trace, thread);
1029 list.add(new TimeLinkEvent(prevEntry, nextEntry, prevEnd, time - prevEnd, 0));
1030 }
1031 lastEnd = currentThreadInterval.getEndTime() + 1;
1032 if (thread != 0) {
1033 prevThread = thread;
1034 prevEnd = lastEnd;
1035 }
1036 }
1037 }
1038 }
1039 return list;
1040 }
1041
1042 private ControlFlowEntry findEntry(List<TimeGraphEntry> entryList, ITmfTrace trace, int threadId) {
1043 for (TimeGraphEntry entry : entryList) {
1044 if (entry instanceof ControlFlowEntry) {
1045 ControlFlowEntry controlFlowEntry = (ControlFlowEntry) entry;
1046 if (controlFlowEntry.getThreadId() == threadId && controlFlowEntry.getTrace() == trace) {
1047 return controlFlowEntry;
1048 }
1049 }
1050 if (entry.hasChildren()) {
1051 ControlFlowEntry controlFlowEntry = findEntry(entry.getChildren(), trace, threadId);
1052 if (controlFlowEntry != null) {
1053 return controlFlowEntry;
1054 }
1055 }
1056 }
1057 return null;
1058 }
1059
1060 @Override
1061 protected boolean canBePinned() {
1062 //TODO: actionPin is not defined
1063 return false;
1064 }
1065
1066 }
This page took 0.073103 seconds and 4 git commands to generate.