@RunWith(Suite.class)
@Suite.SuiteClasses({
org.eclipse.linuxtools.btf.core.tests.AllTests.class,
- org.eclipse.linuxtools.ctf.core.tests.AllCtfCoreTests.class,
- org.eclipse.linuxtools.ctf.parser.tests.AllCtfParserTests.class,
+ org.eclipse.tracecompass.ctf.core.tests.AllCtfCoreTests.class,
+ org.eclipse.tracecompass.ctf.parser.tests.AllCtfParserTests.class,
org.eclipse.tracecompass.gdbtrace.core.tests.AllGdbTraceCoreTests.class,
org.eclipse.tracecompass.lttng2.control.core.tests.AllTests.class,
org.eclipse.tracecompass.lttng2.kernel.core.tests.AllTests.class,
*/
@RunWith(Suite.class)
@Suite.SuiteClasses({
- org.eclipse.linuxtools.ctf.core.tests.perf.AllPerfTests.class,
+ org.eclipse.tracecompass.ctf.core.tests.perf.AllPerfTests.class,
org.eclipse.tracecompass.lttng2.kernel.core.tests.perf.AllPerfTests.class,
org.eclipse.tracecompass.pcap.core.tests.perf.AllPerfTests.class,
org.eclipse.tracecompass.tmf.core.tests.perf.AllPerfTests.class,
Bundle-Version: 3.1.0.qualifier
Bundle-Localization: plugin
Bundle-SymbolicName: org.eclipse.tracecompass.ctf.core.tests;singleton:=true
-Bundle-Activator: org.eclipse.linuxtools.ctf.core.tests.CtfCoreTestPlugin
+Bundle-Activator: org.eclipse.tracecompass.ctf.core.tests.CtfCoreTestPlugin
Bundle-ActivationPolicy: lazy
Bundle-RequiredExecutionEnvironment: JavaSE-1.7
Require-Bundle: org.junit;bundle-version="4.0.0",
org.eclipse.core.runtime;bundle-version="3.8.0",
org.eclipse.tracecompass.ctf.core;bundle-version="3.1.0"
-Export-Package: org.eclipse.linuxtools.ctf.core.tests;x-friends:="org.eclipse.tracecompass.alltests",
- org.eclipse.linuxtools.ctf.core.tests.ctftestsuite;x-internal:=true,
- org.eclipse.linuxtools.ctf.core.tests.event;x-internal:=true,
- org.eclipse.linuxtools.ctf.core.tests.io;x-internal:=true,
- org.eclipse.linuxtools.ctf.core.tests.perf,
- org.eclipse.linuxtools.ctf.core.tests.perf.trace;x-internal:=true,
- org.eclipse.linuxtools.ctf.core.tests.scope,
- org.eclipse.linuxtools.ctf.core.tests.shared,
- org.eclipse.linuxtools.ctf.core.tests.synthetictraces;x-internal:=true,
- org.eclipse.linuxtools.ctf.core.tests.trace;x-internal:=true,
- org.eclipse.linuxtools.ctf.core.tests.types;x-internal:=true
+Export-Package: org.eclipse.tracecompass.ctf.core.tests;x-friends:="org.eclipse.tracecompass.alltests",
+ org.eclipse.tracecompass.ctf.core.tests.ctftestsuite;x-internal:=true,
+ org.eclipse.tracecompass.ctf.core.tests.event;x-internal:=true,
+ org.eclipse.tracecompass.ctf.core.tests.io;x-internal:=true,
+ org.eclipse.tracecompass.ctf.core.tests.perf,
+ org.eclipse.tracecompass.ctf.core.tests.perf.trace;x-internal:=true,
+ org.eclipse.tracecompass.ctf.core.tests.scope,
+ org.eclipse.tracecompass.ctf.core.tests.shared,
+ org.eclipse.tracecompass.ctf.core.tests.synthetictraces;x-internal:=true,
+ org.eclipse.tracecompass.ctf.core.tests.trace;x-internal:=true,
+ org.eclipse.tracecompass.ctf.core.tests.types;x-internal:=true
Import-Package: com.google.common.collect,
org.antlr.runtime;version="3.2.0",
org.eclipse.test.performance
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are
- * made available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Alexandre Montplaisir - Initial implementation and API
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.perf;
-
-import org.junit.runner.RunWith;
-import org.junit.runners.Suite;
-
-/**
- * Run all performance test suites.
- *
- * @author Alexandre Montplaisir
- */
-@RunWith(Suite.class)
-@Suite.SuiteClasses({
- org.eclipse.linuxtools.ctf.core.tests.perf.trace.AllPerfTests.class
-})
-public class AllPerfTests {
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are
- * made available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Alexandre Montplaisir - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.perf.trace;
-
-import org.junit.runner.RunWith;
-import org.junit.runners.Suite;
-
-/**
- * Test suite
- */
-@RunWith(Suite.class)
-@Suite.SuiteClasses({
- TraceReadBenchmark.class,
- TraceSeekBenchmark.class
-})
-public class AllPerfTests {
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2012, 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are
- * made available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- * Alexandre Montplaisir - Convert to a org.eclipse.test.performance test
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.perf.trace;
-
-import static org.junit.Assert.fail;
-import static org.junit.Assume.assumeTrue;
-
-import org.eclipse.linuxtools.ctf.core.event.EventDefinition;
-import org.eclipse.linuxtools.ctf.core.tests.shared.CtfTestTrace;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTrace;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTraceReader;
-import org.eclipse.test.performance.Dimension;
-import org.eclipse.test.performance.Performance;
-import org.eclipse.test.performance.PerformanceMeter;
-import org.junit.Test;
-
-/**
- * Benchmark of the CTF parser for reading a trace
- *
- * @author Matthew Khouzam
- * @author Alexandre Montplaisir
- */
-public class TraceReadBenchmark {
-
- private static final String TEST_SUITE_NAME = "CTF Read Benchmark";
- private static final String TEST_ID = "org.eclipse.linuxtools#" + TEST_SUITE_NAME;
- private static final int LOOP_COUNT = 100;
-
- /**
- * Benchmark reading the trace "kernel"
- */
- @Test
- public void testKernelTrace() {
- readTrace(CtfTestTrace.KERNEL, "trace-kernel", true);
- }
-
- /**
- * Benchmark reading the bigger trace "kernel_vm"
- */
- @Test
- public void testKernelVmTrace() {
- readTrace(CtfTestTrace.KERNEL_VM, "trace-kernel-vm", false);
- }
-
- private static void readTrace(CtfTestTrace testTrace, String testName, boolean inGlobalSummary) {
- assumeTrue(testTrace.exists());
-
- Performance perf = Performance.getDefault();
- PerformanceMeter pm = perf.createPerformanceMeter(TEST_ID + '#' + testName);
- perf.tagAsSummary(pm, TEST_SUITE_NAME + ':' + testName, Dimension.CPU_TIME);
-
- if (inGlobalSummary) {
- perf.tagAsGlobalSummary(pm, TEST_SUITE_NAME + ':' + testName, Dimension.CPU_TIME);
- }
-
- for (int loop = 0; loop < LOOP_COUNT; loop++) {
- pm.start();
- try (CTFTrace trace = testTrace.getTrace();
- CTFTraceReader traceReader = new CTFTraceReader(trace);) {
-
- while (traceReader.hasMoreEvents()) {
- EventDefinition ed = traceReader.getCurrentEventDef();
- /* Do something with the event */
- ed.getCPU();
- traceReader.advance();
- }
-
- } catch (CTFReaderException e) {
- /* Should not happen if assumeTrue() passed above */
- fail("Test failed at iteration " + loop + ':' + e.getMessage());
- }
- pm.stop();
- }
- pm.commit();
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2012, 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are
- * made available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- * Alexandre Montplaisir - Convert to a org.eclipse.test.performance test
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.perf.trace;
-
-import static org.junit.Assert.fail;
-import static org.junit.Assume.assumeTrue;
-
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Random;
-
-import org.eclipse.linuxtools.ctf.core.event.EventDefinition;
-import org.eclipse.linuxtools.ctf.core.tests.shared.CtfTestTrace;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTrace;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTraceReader;
-import org.eclipse.test.performance.Dimension;
-import org.eclipse.test.performance.Performance;
-import org.eclipse.test.performance.PerformanceMeter;
-import org.junit.Test;
-
-/**
- * Tests for performance regressions of the ctf reader. It only tests the ctf
- * reader, not tmf.
- * <br>
- * This test runs in 3 passes.
- * <ul>
- * <li>first it opens a trace</li>
- * <li>then it reads the trace completely</li>
- * <li>then it randomly (seeded) seeks NB_SEEKS locations in the trace and reads one
- * event at each position.</li>
- * </ul>
- *
- * @author Matthew Khouzam
- * @author Alexandre Montplaisir
- */
-public class TraceSeekBenchmark {
-
- private static final Random RND = new Random(1000);
-
- private static final int LOOP_COUNT = 25;
- private static final int NB_SEEKS = 500;
- private static final String TEST_SUITE_NAME = "CTF Read & Seek Benchmark (" + NB_SEEKS + " seeks)";
- private static final String TEST_ID = "org.eclipse.linuxtools#" + TEST_SUITE_NAME;
-
- /**
- * Run the benchmark scenario for the trace "kernel"
- */
- @Test
- public void testKernelTrace() {
- readAndSeekTrace(CtfTestTrace.KERNEL, "trace-kernel", true);
- }
-
- private static void readAndSeekTrace(CtfTestTrace testTrace, String testName, boolean inGlobalSummary) {
- assumeTrue(testTrace.exists());
-
- Performance perf = Performance.getDefault();
- PerformanceMeter pm = perf.createPerformanceMeter(TEST_ID + '#' + testName);
- perf.tagAsSummary(pm, TEST_SUITE_NAME + ':' + testName, Dimension.CPU_TIME);
-
- if (inGlobalSummary) {
- perf.tagAsGlobalSummary(pm, TEST_SUITE_NAME + ':' + testName, Dimension.CPU_TIME);
- }
-
- for (int loop = 0; loop < LOOP_COUNT; loop++) {
- try (CTFTrace trace = testTrace.getTrace();
- CTFTraceReader traceReader = new CTFTraceReader(trace);) {
-
- /* Read the whole trace to find out the start and end times */
- EventDefinition firstEvent = traceReader.getCurrentEventDef();
- final long startTime = firstEvent.getTimestamp();
- long endTime = startTime;
- while (traceReader.hasMoreEvents()) {
- EventDefinition ev = traceReader.getCurrentEventDef();
- endTime = ev.getTimestamp();
- traceReader.advance();
- }
-
- /* Generate the timestamps we will seek to */
- List<Long> seekTimestamps = new LinkedList<>();
- final long range = endTime - startTime;
- for (int i = 0; i < NB_SEEKS; i++) {
- long delta = (RND.nextLong() % range);
- if (delta < 0) {
- delta += range;
- }
- seekTimestamps.add(startTime + delta);
- }
-
- /* Benchmark seeking to the generated timestamps */
- pm.start();
- for (Long ts : seekTimestamps) {
- traceReader.seek(ts);
- traceReader.advance();
- }
- pm.stop();
-
- } catch (CTFReaderException e) {
- /* Should not happen if assumeTrue() passed above */
- fail("Test failed at iteration " + loop + ':' + e.getMessage());
- }
- }
- pm.commit();
- }
-}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are
+ * made available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Alexandre Montplaisir - Initial implementation and API
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.perf;
+
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+
+/**
+ * Run all performance test suites.
+ *
+ * @author Alexandre Montplaisir
+ */
+@RunWith(Suite.class)
+@Suite.SuiteClasses({
+ org.eclipse.tracecompass.ctf.core.tests.perf.trace.AllPerfTests.class
+})
+public class AllPerfTests {
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are
+ * made available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Alexandre Montplaisir - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.perf.trace;
+
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+
+/**
+ * Test suite
+ */
+@RunWith(Suite.class)
+@Suite.SuiteClasses({
+ TraceReadBenchmark.class,
+ TraceSeekBenchmark.class
+})
+public class AllPerfTests {
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2012, 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are
+ * made available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ * Alexandre Montplaisir - Convert to a org.eclipse.test.performance test
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.perf.trace;
+
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
+
+import org.eclipse.test.performance.Dimension;
+import org.eclipse.test.performance.Performance;
+import org.eclipse.test.performance.PerformanceMeter;
+import org.eclipse.tracecompass.ctf.core.event.EventDefinition;
+import org.eclipse.tracecompass.ctf.core.tests.shared.CtfTestTrace;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTrace;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTraceReader;
+import org.junit.Test;
+
+/**
+ * Benchmark of the CTF parser for reading a trace
+ *
+ * @author Matthew Khouzam
+ * @author Alexandre Montplaisir
+ */
+public class TraceReadBenchmark {
+
+ private static final String TEST_SUITE_NAME = "CTF Read Benchmark";
+ private static final String TEST_ID = "org.eclipse.linuxtools#" + TEST_SUITE_NAME;
+ private static final int LOOP_COUNT = 100;
+
+ /**
+ * Benchmark reading the trace "kernel"
+ */
+ @Test
+ public void testKernelTrace() {
+ readTrace(CtfTestTrace.KERNEL, "trace-kernel", true);
+ }
+
+ /**
+ * Benchmark reading the bigger trace "kernel_vm"
+ */
+ @Test
+ public void testKernelVmTrace() {
+ readTrace(CtfTestTrace.KERNEL_VM, "trace-kernel-vm", false);
+ }
+
+ private static void readTrace(CtfTestTrace testTrace, String testName, boolean inGlobalSummary) {
+ assumeTrue(testTrace.exists());
+
+ Performance perf = Performance.getDefault();
+ PerformanceMeter pm = perf.createPerformanceMeter(TEST_ID + '#' + testName);
+ perf.tagAsSummary(pm, TEST_SUITE_NAME + ':' + testName, Dimension.CPU_TIME);
+
+ if (inGlobalSummary) {
+ perf.tagAsGlobalSummary(pm, TEST_SUITE_NAME + ':' + testName, Dimension.CPU_TIME);
+ }
+
+ for (int loop = 0; loop < LOOP_COUNT; loop++) {
+ pm.start();
+ try (CTFTrace trace = testTrace.getTrace();
+ CTFTraceReader traceReader = new CTFTraceReader(trace);) {
+
+ while (traceReader.hasMoreEvents()) {
+ EventDefinition ed = traceReader.getCurrentEventDef();
+ /* Do something with the event */
+ ed.getCPU();
+ traceReader.advance();
+ }
+
+ } catch (CTFReaderException e) {
+ /* Should not happen if assumeTrue() passed above */
+ fail("Test failed at iteration " + loop + ':' + e.getMessage());
+ }
+ pm.stop();
+ }
+ pm.commit();
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2012, 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are
+ * made available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ * Alexandre Montplaisir - Convert to a org.eclipse.test.performance test
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.perf.trace;
+
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
+
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Random;
+
+import org.eclipse.test.performance.Dimension;
+import org.eclipse.test.performance.Performance;
+import org.eclipse.test.performance.PerformanceMeter;
+import org.eclipse.tracecompass.ctf.core.event.EventDefinition;
+import org.eclipse.tracecompass.ctf.core.tests.shared.CtfTestTrace;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTrace;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTraceReader;
+import org.junit.Test;
+
+/**
+ * Tests for performance regressions of the ctf reader. It only tests the ctf
+ * reader, not tmf.
+ * <br>
+ * This test runs in 3 passes.
+ * <ul>
+ * <li>first it opens a trace</li>
+ * <li>then it reads the trace completely</li>
+ * <li>then it randomly (seeded) seeks NB_SEEKS locations in the trace and reads one
+ * event at each position.</li>
+ * </ul>
+ *
+ * @author Matthew Khouzam
+ * @author Alexandre Montplaisir
+ */
+public class TraceSeekBenchmark {
+
+ private static final Random RND = new Random(1000);
+
+ private static final int LOOP_COUNT = 25;
+ private static final int NB_SEEKS = 500;
+ private static final String TEST_SUITE_NAME = "CTF Read & Seek Benchmark (" + NB_SEEKS + " seeks)";
+ private static final String TEST_ID = "org.eclipse.linuxtools#" + TEST_SUITE_NAME;
+
+ /**
+ * Run the benchmark scenario for the trace "kernel"
+ */
+ @Test
+ public void testKernelTrace() {
+ readAndSeekTrace(CtfTestTrace.KERNEL, "trace-kernel", true);
+ }
+
+ private static void readAndSeekTrace(CtfTestTrace testTrace, String testName, boolean inGlobalSummary) {
+ assumeTrue(testTrace.exists());
+
+ Performance perf = Performance.getDefault();
+ PerformanceMeter pm = perf.createPerformanceMeter(TEST_ID + '#' + testName);
+ perf.tagAsSummary(pm, TEST_SUITE_NAME + ':' + testName, Dimension.CPU_TIME);
+
+ if (inGlobalSummary) {
+ perf.tagAsGlobalSummary(pm, TEST_SUITE_NAME + ':' + testName, Dimension.CPU_TIME);
+ }
+
+ for (int loop = 0; loop < LOOP_COUNT; loop++) {
+ try (CTFTrace trace = testTrace.getTrace();
+ CTFTraceReader traceReader = new CTFTraceReader(trace);) {
+
+ /* Read the whole trace to find out the start and end times */
+ EventDefinition firstEvent = traceReader.getCurrentEventDef();
+ final long startTime = firstEvent.getTimestamp();
+ long endTime = startTime;
+ while (traceReader.hasMoreEvents()) {
+ EventDefinition ev = traceReader.getCurrentEventDef();
+ endTime = ev.getTimestamp();
+ traceReader.advance();
+ }
+
+ /* Generate the timestamps we will seek to */
+ List<Long> seekTimestamps = new LinkedList<>();
+ final long range = endTime - startTime;
+ for (int i = 0; i < NB_SEEKS; i++) {
+ long delta = (RND.nextLong() % range);
+ if (delta < 0) {
+ delta += range;
+ }
+ seekTimestamps.add(startTime + delta);
+ }
+
+ /* Benchmark seeking to the generated timestamps */
+ pm.start();
+ for (Long ts : seekTimestamps) {
+ traceReader.seek(ts);
+ traceReader.advance();
+ }
+ pm.stop();
+
+ } catch (CTFReaderException e) {
+ /* Should not happen if assumeTrue() passed above */
+ fail("Test failed at iteration " + loop + ':' + e.getMessage());
+ }
+ }
+ pm.commit();
+ }
+}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Alexandre Montplaisir - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.shared;
-
-import java.io.File;
-
-import org.eclipse.linuxtools.ctf.core.tests.synthetictraces.LttngKernelTraceGenerator;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTrace;
-
-/**
- * Here is the list of the available test traces for the CTF parser.
- *
- * Make sure you run the traces/get-traces.xml Ant script to download them
- * first!
- *
- * @author Alexandre Montplaisir
- */
-public enum CtfTestTrace {
- /**
- * Example kernel trace
- *
- * <pre>
- * Trace Size: 13 MB
- * Tracer: lttng-modules 2.0.0
- * Event count: 695 319
- * Kernel version: 3.0.0-16-generic-pae
- * Trace length: 10s
- * </pre>
- */
- KERNEL("../org.eclipse.tracecompass.ctf.core.tests/traces/kernel"),
-
- /**
- * Another kernel trace
- *
- * <pre>
- * Trace Size: 14 MB
- * Tracer: lttng-modules 2.0.0
- * Event count: 595 641
- * Kernel version: 3.2.0-18-generic
- * Trace length: 11s
- * </pre>
- */
- TRACE2("../org.eclipse.tracecompass.ctf.core.tests/traces/trace2"),
-
- /**
- * Kernel trace with event contexts: pid, ppid, tid, procname,
- * perf_page_fault, perf_major_faults, perf_minor_faults
- *
- * <pre>
- * Trace Size: 56 MB
- * Tracer: lttng-modules 2.1.0
- * Event count: 714 484
- * Kernel version: 3.8.1
- * Trace length: 29s
- * </pre>
- */
- KERNEL_VM("../org.eclipse.tracecompass.ctf.core.tests/traces/kernel_vm"),
-
- /**
- * Kernel trace with all events enabled. Contains 'inet_sock_local_*' events
- * provided by Francis's Giraldeau lttng-modules addons branch to trace TCP
- * events. Can be used along with {@link CtfTestTrace#SYNC_DEST} for trace
- * synchronization.
- *
- * <pre>
- * Trace Size: 2.4 MB
- * Tracer: lttng-modules 2.1.0
- * Event count: 110 771
- * Kernel version: 3.6.11-1-ARCH
- * Trace length: 22s
- * </pre>
- */
- SYNC_SRC("../org.eclipse.tracecompass.ctf.core.tests/traces/synctraces/scp_src"),
-
- /**
- * Kernel trace with all events enabled. Contains 'inet_sock_local_*' events
- * provided by Francis's Giraldeau lttng-modules addons branch to trace TCP
- * events. Can be used along with {@link CtfTestTrace#SYNC_SRC} for trace
- * synchronization.
- *
- * <pre>
- * Trace Size: 1.9 MB
- * Tracer: lttng-modules 2.1.0
- * Event count: 85 729
- * Kernel version: 3.6.11-1-ARCH
- * Trace length: 17s
- * </pre>
- */
- SYNC_DEST("../org.eclipse.tracecompass.ctf.core.tests/traces/synctraces/scp_dest"),
-
- /**
- * LTTng Kernel trace. Contains 'inet_sock_local_*' events provided by
- * Francis's Giraldeau lttng-modules addons branch to trace TCP events. Can
- * be used along with {@link CtfTestTrace#DJANGO_DB} and
- * {@link CtfTestTrace#DJANGO_HTTPD} for trace synchronization.
- *
- * <pre>
- * Trace Size: 33 MB
- * Tracer: lttng-modules 2.4.0
- * Event count: 754 787
- * Kernel version: 3.13.0-24-generic
- * Trace length: 15s
- * </pre>
- */
- DJANGO_CLIENT("../org.eclipse.tracecompass.ctf.core.tests/traces/django-benchmark/django-client"),
-
- /**
- * LTTng Kernel trace. Contains 'inet_sock_local_*' events provided by
- * Francis's Giraldeau lttng-modules addons branch to trace TCP events. Can
- * be used along with {@link CtfTestTrace#DJANGO_CLIENT} and
- * {@link CtfTestTrace#DJANGO_HTTPD} for trace synchronization.
- *
- * <pre>
- * Trace Size: 28 MB
- * Tracer: lttng-modules 2.4.0
- * Event count: 692 098
- * Kernel version: 3.13.0-24-generic
- * Trace length: 14s
- * </pre>
- */
- DJANGO_DB("../org.eclipse.tracecompass.ctf.core.tests/traces/django-benchmark/django-db"),
-
- /**
- * LTTng Kernel trace. Contains 'inet_sock_local_*' events provided by
- * Francis's Giraldeau lttng-modules addons branch to trace TCP events. Can
- * be used along with {@link CtfTestTrace#DJANGO_DB} and
- * {@link CtfTestTrace#DJANGO_CLIENT} for trace synchronization.
- *
- * <pre>
- * Trace Size: 31 MB
- * Tracer: lttng-modules 2.4.0
- * Event count: 779 096
- * Kernel version:3.13.0-24-generic
- * Trace length: 13s
- * </pre>
- */
- DJANGO_HTTPD("../org.eclipse.tracecompass.ctf.core.tests/traces/django-benchmark/django-httpd"),
-
- /**
- * UST trace with lots of lost events
- *
- * <pre>
- * Trace Size: 3.4 MB
- * Tracer: lttng-ust 2.3
- * Event count: 1 000 000, with 967 700 lost events
- * Trace length: 279ms
- * </pre>
- */
- HELLO_LOST("../org.eclipse.tracecompass.ctf.core.tests/traces/hello-lost"),
-
- /**
- * UST trace with lttng-ust-cyg-profile events (aka -finstrument-functions)
- *
- * <pre>
- * Trace Size: 236 KB
- * Tracer: lttng-ust 2.3
- * Event count: 4 977
- * Trace length: 10s
- * </pre>
- */
- CYG_PROFILE("../org.eclipse.tracecompass.ctf.core.tests/traces/cyg-profile/glxgears-cyg-profile"),
-
- /**
- * UST trace with lttng-ust-cyg-profile-fast events (no address in
- * func_exit)
- *
- * <pre>
- * Trace Size: 184 KB
- * Tracer: lttng-ust 2.3
- * Event count: 5 161
- * Trace length: 11s
- * </pre>
- */
- CYG_PROFILE_FAST("../org.eclipse.tracecompass.ctf.core.tests/traces/cyg-profile/glxgears-cyg-profile-fast"),
-
- /** Autogenerated Syntetic trace */
- SYNTHETIC_TRACE(LttngKernelTraceGenerator.getPath()),
-
- /** Trace with non-standard field sizes */
- FUNKY_TRACE("../org.eclipse.tracecompass.ctf.core.tests/traces/funky_trace"),
-
- /** Set of many traces, do not call getTrace */
- TRACE_EXPERIMENT("../org.eclipse.tracecompass.ctf.core.tests/traces/exp");
-
- private final String fPath;
- private CTFTrace fTrace = null;
- private CTFTrace fTraceFromFile = null;
-
- private CtfTestTrace(String path) {
- fPath = path;
- }
-
- /** @return The path to the test trace */
- public String getPath() {
- return fPath;
- }
-
- /**
- * Get a CTFTrace instance of a test trace. Make sure
- * {@link #exists()} before calling this!
- *
- * @return The CTFTrace object
- * @throws CTFReaderException
- * If the trace cannot be found.
- */
- public CTFTrace getTrace() throws CTFReaderException {
- if (fTrace == null) {
- fTrace = new CTFTrace(fPath);
- }
- return fTrace;
- }
-
- /**
- * Get a CTFTrace instance created from a File. Make sure
- * {@link #exists()} before calling this!
- *
- * @return The CTFTrace object
- * @throws CTFReaderException
- * If the trace cannot be found.
- */
- public CTFTrace getTraceFromFile() throws CTFReaderException {
- if (fTraceFromFile == null) {
- fTraceFromFile = new CTFTrace(new File(fPath));
- }
- return fTraceFromFile;
- }
-
- /**
- * Check if this test trace actually exists on disk.
- *
- * @return If the trace exists
- */
- public boolean exists() {
- try {
- getTrace();
- } catch (CTFReaderException e) {
- return false;
- }
- return true;
- }
-}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Alexandre Montplaisir - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.shared;
+
+import java.io.File;
+
+import org.eclipse.tracecompass.ctf.core.tests.synthetictraces.LttngKernelTraceGenerator;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTrace;
+
+/**
+ * Here is the list of the available test traces for the CTF parser.
+ *
+ * Make sure you run the traces/get-traces.xml Ant script to download them
+ * first!
+ *
+ * @author Alexandre Montplaisir
+ */
+public enum CtfTestTrace {
+ /**
+ * Example kernel trace
+ *
+ * <pre>
+ * Trace Size: 13 MB
+ * Tracer: lttng-modules 2.0.0
+ * Event count: 695 319
+ * Kernel version: 3.0.0-16-generic-pae
+ * Trace length: 10s
+ * </pre>
+ */
+ KERNEL("../org.eclipse.tracecompass.ctf.core.tests/traces/kernel"),
+
+ /**
+ * Another kernel trace
+ *
+ * <pre>
+ * Trace Size: 14 MB
+ * Tracer: lttng-modules 2.0.0
+ * Event count: 595 641
+ * Kernel version: 3.2.0-18-generic
+ * Trace length: 11s
+ * </pre>
+ */
+ TRACE2("../org.eclipse.tracecompass.ctf.core.tests/traces/trace2"),
+
+ /**
+ * Kernel trace with event contexts: pid, ppid, tid, procname,
+ * perf_page_fault, perf_major_faults, perf_minor_faults
+ *
+ * <pre>
+ * Trace Size: 56 MB
+ * Tracer: lttng-modules 2.1.0
+ * Event count: 714 484
+ * Kernel version: 3.8.1
+ * Trace length: 29s
+ * </pre>
+ */
+ KERNEL_VM("../org.eclipse.tracecompass.ctf.core.tests/traces/kernel_vm"),
+
+ /**
+ * Kernel trace with all events enabled. Contains 'inet_sock_local_*' events
+ * provided by Francis's Giraldeau lttng-modules addons branch to trace TCP
+ * events. Can be used along with {@link CtfTestTrace#SYNC_DEST} for trace
+ * synchronization.
+ *
+ * <pre>
+ * Trace Size: 2.4 MB
+ * Tracer: lttng-modules 2.1.0
+ * Event count: 110 771
+ * Kernel version: 3.6.11-1-ARCH
+ * Trace length: 22s
+ * </pre>
+ */
+ SYNC_SRC("../org.eclipse.tracecompass.ctf.core.tests/traces/synctraces/scp_src"),
+
+ /**
+ * Kernel trace with all events enabled. Contains 'inet_sock_local_*' events
+ * provided by Francis's Giraldeau lttng-modules addons branch to trace TCP
+ * events. Can be used along with {@link CtfTestTrace#SYNC_SRC} for trace
+ * synchronization.
+ *
+ * <pre>
+ * Trace Size: 1.9 MB
+ * Tracer: lttng-modules 2.1.0
+ * Event count: 85 729
+ * Kernel version: 3.6.11-1-ARCH
+ * Trace length: 17s
+ * </pre>
+ */
+ SYNC_DEST("../org.eclipse.tracecompass.ctf.core.tests/traces/synctraces/scp_dest"),
+
+ /**
+ * LTTng Kernel trace. Contains 'inet_sock_local_*' events provided by
+ * Francis's Giraldeau lttng-modules addons branch to trace TCP events. Can
+ * be used along with {@link CtfTestTrace#DJANGO_DB} and
+ * {@link CtfTestTrace#DJANGO_HTTPD} for trace synchronization.
+ *
+ * <pre>
+ * Trace Size: 33 MB
+ * Tracer: lttng-modules 2.4.0
+ * Event count: 754 787
+ * Kernel version: 3.13.0-24-generic
+ * Trace length: 15s
+ * </pre>
+ */
+ DJANGO_CLIENT("../org.eclipse.tracecompass.ctf.core.tests/traces/django-benchmark/django-client"),
+
+ /**
+ * LTTng Kernel trace. Contains 'inet_sock_local_*' events provided by
+ * Francis's Giraldeau lttng-modules addons branch to trace TCP events. Can
+ * be used along with {@link CtfTestTrace#DJANGO_CLIENT} and
+ * {@link CtfTestTrace#DJANGO_HTTPD} for trace synchronization.
+ *
+ * <pre>
+ * Trace Size: 28 MB
+ * Tracer: lttng-modules 2.4.0
+ * Event count: 692 098
+ * Kernel version: 3.13.0-24-generic
+ * Trace length: 14s
+ * </pre>
+ */
+ DJANGO_DB("../org.eclipse.tracecompass.ctf.core.tests/traces/django-benchmark/django-db"),
+
+ /**
+ * LTTng Kernel trace. Contains 'inet_sock_local_*' events provided by
+ * Francis's Giraldeau lttng-modules addons branch to trace TCP events. Can
+ * be used along with {@link CtfTestTrace#DJANGO_DB} and
+ * {@link CtfTestTrace#DJANGO_CLIENT} for trace synchronization.
+ *
+ * <pre>
+ * Trace Size: 31 MB
+ * Tracer: lttng-modules 2.4.0
+ * Event count: 779 096
+ * Kernel version:3.13.0-24-generic
+ * Trace length: 13s
+ * </pre>
+ */
+ DJANGO_HTTPD("../org.eclipse.tracecompass.ctf.core.tests/traces/django-benchmark/django-httpd"),
+
+ /**
+ * UST trace with lots of lost events
+ *
+ * <pre>
+ * Trace Size: 3.4 MB
+ * Tracer: lttng-ust 2.3
+ * Event count: 1 000 000, with 967 700 lost events
+ * Trace length: 279ms
+ * </pre>
+ */
+ HELLO_LOST("../org.eclipse.tracecompass.ctf.core.tests/traces/hello-lost"),
+
+ /**
+ * UST trace with lttng-ust-cyg-profile events (aka -finstrument-functions)
+ *
+ * <pre>
+ * Trace Size: 236 KB
+ * Tracer: lttng-ust 2.3
+ * Event count: 4 977
+ * Trace length: 10s
+ * </pre>
+ */
+ CYG_PROFILE("../org.eclipse.tracecompass.ctf.core.tests/traces/cyg-profile/glxgears-cyg-profile"),
+
+ /**
+ * UST trace with lttng-ust-cyg-profile-fast events (no address in
+ * func_exit)
+ *
+ * <pre>
+ * Trace Size: 184 KB
+ * Tracer: lttng-ust 2.3
+ * Event count: 5 161
+ * Trace length: 11s
+ * </pre>
+ */
+ CYG_PROFILE_FAST("../org.eclipse.tracecompass.ctf.core.tests/traces/cyg-profile/glxgears-cyg-profile-fast"),
+
+ /** Autogenerated Syntetic trace */
+ SYNTHETIC_TRACE(LttngKernelTraceGenerator.getPath()),
+
+ /** Trace with non-standard field sizes */
+ FUNKY_TRACE("../org.eclipse.tracecompass.ctf.core.tests/traces/funky_trace"),
+
+ /** Set of many traces, do not call getTrace */
+ TRACE_EXPERIMENT("../org.eclipse.tracecompass.ctf.core.tests/traces/exp");
+
+ private final String fPath;
+ private CTFTrace fTrace = null;
+ private CTFTrace fTraceFromFile = null;
+
+ private CtfTestTrace(String path) {
+ fPath = path;
+ }
+
+ /** @return The path to the test trace */
+ public String getPath() {
+ return fPath;
+ }
+
+ /**
+ * Get a CTFTrace instance of a test trace. Make sure
+ * {@link #exists()} before calling this!
+ *
+ * @return The CTFTrace object
+ * @throws CTFReaderException
+ * If the trace cannot be found.
+ */
+ public CTFTrace getTrace() throws CTFReaderException {
+ if (fTrace == null) {
+ fTrace = new CTFTrace(fPath);
+ }
+ return fTrace;
+ }
+
+ /**
+ * Get a CTFTrace instance created from a File. Make sure
+ * {@link #exists()} before calling this!
+ *
+ * @return The CTFTrace object
+ * @throws CTFReaderException
+ * If the trace cannot be found.
+ */
+ public CTFTrace getTraceFromFile() throws CTFReaderException {
+ if (fTraceFromFile == null) {
+ fTraceFromFile = new CTFTrace(new File(fPath));
+ }
+ return fTraceFromFile;
+ }
+
+ /**
+ * Check if this test trace actually exists on disk.
+ *
+ * @return If the trace exists
+ */
+ public boolean exists() {
+ try {
+ getTrace();
+ } catch (CTFReaderException e) {
+ return false;
+ }
+ return true;
+ }
+}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests;
-
-import org.junit.runner.RunWith;
-import org.junit.runners.Suite;
-
-/**
- * The class <code>TestAll</code> builds a suite that can be used to run all of
- * the tests within its package as well as within any subpackages of its
- * package.
- *
- * @author ematkho
- * @version 1.0
- */
-@RunWith(Suite.class)
-@Suite.SuiteClasses({
- CtfCorePluginTest.class,
- org.eclipse.linuxtools.ctf.core.tests.ctftestsuite.TestAll.class,
- org.eclipse.linuxtools.ctf.core.tests.event.TestAll.class,
- org.eclipse.linuxtools.ctf.core.tests.io.TestAll.class,
- org.eclipse.linuxtools.ctf.core.tests.scope.TestAll.class,
- org.eclipse.linuxtools.ctf.core.tests.trace.TestAll.class,
- org.eclipse.linuxtools.ctf.core.tests.types.TestAll.class
-})
-public class AllCtfCoreTests {
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2013 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are
- * made available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Francois Chouinard - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-
-import org.eclipse.linuxtools.internal.ctf.core.Activator;
-import org.junit.Test;
-
-/**
- * <b><u>CtfCorePluginTest</u></b>
- * <p>
- * Test the CTF core plug-in activator
- */
-@SuppressWarnings("javadoc")
-public class CtfCorePluginTest {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- // Plug-in instantiation
- private final static Activator fPlugin = Activator.getDefault();
-
-
- // ------------------------------------------------------------------------
- // Test cases
- // ------------------------------------------------------------------------
-
- @Test
- public void testCtfCorePluginId() {
- assertEquals(
- "Plugin ID", "org.eclipse.linuxtools.ctf", Activator.PLUGIN_ID);
- }
-
- @Test
- public void testGetDefault() {
- Activator plugin = Activator.getDefault();
- assertEquals("getDefault()", plugin, fPlugin);
- }
-
- @Test
- public void testLog() {
- try {
- Activator.log("Some message");
- } catch (Exception e) {
- fail();
- }
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are
- * made available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Alexandre Montplaisir - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests;
-
-import java.io.File;
-import java.net.URISyntaxException;
-
-import org.eclipse.core.runtime.Plugin;
-import org.eclipse.core.runtime.URIUtil;
-import org.eclipse.linuxtools.internal.ctf.core.Activator;
-import org.osgi.framework.BundleContext;
-
-/**
- * The activator class controls the plug-in life cycle
- */
-public class CtfCoreTestPlugin extends Plugin {
-
- private static final String TEMP_DIR_NAME = ".temp"; //$NON-NLS-1$
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- /** The plug-in ID */
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.ctf.core.tests";
-
- // The shared instance
- private static CtfCoreTestPlugin fPlugin;
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * The constructor
- */
- public CtfCoreTestPlugin() {
- setDefault(this);
- }
-
- // ------------------------------------------------------------------------
- // Accessors
- // ------------------------------------------------------------------------
-
- /**
- * @return the shared instance
- */
- public static CtfCoreTestPlugin getDefault() {
- return fPlugin;
- }
-
- /**
- * @param plugin
- * the shared instance
- */
- private static void setDefault(CtfCoreTestPlugin plugin) {
- fPlugin = plugin;
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
- setDefault(this);
- }
-
- @Override
- public void stop(BundleContext context) throws Exception {
- setDefault(null);
- super.stop(context);
- }
-
- /**
- * Get the temporary directory path. If there is an instance of Eclipse
- * running, the temporary directory will reside under the workspace.
- *
- * @return the temporary directory path suitable to be passed to the
- * java.io.File constructor without a trailing separator
- */
- public static String getTemporaryDirPath() {
- String property = System.getProperty("osgi.instance.area"); //$NON-NLS-1$
- if (property != null) {
- try {
- File dir = URIUtil.toFile(URIUtil.fromString(property));
- dir = new File(dir.getAbsolutePath() + File.separator + TEMP_DIR_NAME);
- if (!dir.exists()) {
- dir.mkdirs();
- }
- return dir.getAbsolutePath();
- } catch (URISyntaxException e) {
- Activator.logError(e.getLocalizedMessage(), e);
- }
- }
- return System.getProperty("java.io.tmpdir"); //$NON-NLS-1$
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013, 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are
- * made available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Alexandre Montplaisir - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.ctftestsuite;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
-
-import java.io.File;
-import java.util.LinkedList;
-import java.util.List;
-
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTrace;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTraceReader;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TestRule;
-import org.junit.rules.Timeout;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
-
-/**
- * Parameterized test class running the CTF Test Suite
- *
- * (from https://github.com/efficios/ctf-testsuite).
- *
- * @author Alexandre Montplaisir
- */
-@RunWith(Parameterized.class)
-public class CtfTestSuiteTests {
-
- /** Time-out tests after 10 seconds. */
- @Rule
- public TestRule globalTimeout = new Timeout(10000);
-
- private static final String BASE_PATH = "traces/ctf-testsuite/tests/1.8/";
-
- /**
- * Test we know are currently failing. Ignore them so we can at least run
- * the others.
- *
- * TODO Actually fix them!
- */
- private static final String[] IGNORED_TESTS = {
- "regression/metadata/pass/sequence-typedef-length",
- "regression/metadata/pass/array-of-struct"
- };
-
- private final String fTracePath;
- private final boolean fExpectSuccess;
-
- // ------------------------------------------------------------------------
- // Methods for the Parametrized runner
- // ------------------------------------------------------------------------
-
- /**
- * Get the existing trace paths in the CTF-Testsuite git tree.
- *
- * @return The list of CTF traces (directories) to test
- */
- @Parameters(name = "{index}: {0}")
- public static Iterable<Object[]> getTracePaths() {
- final List<Object[]> dirs = new LinkedList<>();
-
- addDirsFrom(dirs, BASE_PATH + "fuzzing/metadata/fail", false);
- addDirsFrom(dirs, BASE_PATH + "fuzzing/metadata/pass", true);
- addDirsFrom(dirs, BASE_PATH + "fuzzing/stream/fail", false);
- addDirsFrom(dirs, BASE_PATH + "fuzzing/stream/pass", true);
-
- addDirsFrom(dirs, BASE_PATH + "regression/metadata/fail", false);
- addDirsFrom(dirs, BASE_PATH + "regression/metadata/pass", true);
- addDirsFrom(dirs, BASE_PATH + "regression/stream/fail", false);
- addDirsFrom(dirs, BASE_PATH + "regression/stream/pass", true);
-
- addDirsFrom(dirs, BASE_PATH + "stress/metadata/fail", false);
- addDirsFrom(dirs, BASE_PATH + "stress/metadata/pass", true);
- addDirsFrom(dirs, BASE_PATH + "stress/stream/fail", false);
- addDirsFrom(dirs, BASE_PATH + "stress/stream/pass", true);
-
- return dirs;
- }
-
- private static void addDirsFrom(List<Object[]> dirs, String path, boolean expectSuccess) {
- File[] traceDirs = (new File(path)).listFiles();
- if (traceDirs == null) {
- return;
- }
- for (File traceDir : traceDirs) {
- /* Skip the "run.sh" files and blacklisted tests */
- if (!traceDir.isDirectory() || testIsBlacklisted(traceDir.getPath())) {
- continue;
- }
-
- /* Add this test case to the list of tests to run */
- Object array[] = new Object[] { traceDir.getPath(), expectSuccess };
- dirs.add(array);
- }
- }
-
- private static boolean testIsBlacklisted(String fullPath) {
- for (String ignoredTest : IGNORED_TESTS) {
- if (fullPath.contains(new File(ignoredTest).getPath())) {
- return true;
- }
- }
- return false;
- }
-
- // ------------------------------------------------------------------------
- // Test constructor
- // ------------------------------------------------------------------------
-
- /**
- * Constructor for the parametrized tests
- *
- * @param tracePath
- * The complete path to the trace to test
- * @param expectSuccess
- * Should this trace parse successfully, or not.
- */
- public CtfTestSuiteTests(String tracePath, boolean expectSuccess) {
- fTracePath = tracePath;
- fExpectSuccess = expectSuccess;
- }
-
- // ------------------------------------------------------------------------
- // Test methods
- // ------------------------------------------------------------------------
-
- /**
- * Test opening and reading the trace
- */
- @Test
- public void testTrace() {
- try (/* Instantiate the trace (which implies parsing the metadata) */
- CTFTrace trace = new CTFTrace(fTracePath);
- /* Read the trace until the end */
- CTFTraceReader reader = new CTFTraceReader(trace);) {
-
- reader.getCurrentEventDef();
- while (reader.advance()) {
- assertNotNull(reader.getCurrentEventDef());
- }
-
- checkIfWeShoudlSucceed();
- } catch (CTFReaderException e) {
- checkIfWeShouldFail(e);
- } catch (OutOfMemoryError e) {
- checkIfWeShouldFail(e);
- }
- }
-
- private void checkIfWeShoudlSucceed() {
- if (!fExpectSuccess) {
- fail("Trace was expected to fail parsing: " + fTracePath);
- }
- }
-
- private void checkIfWeShouldFail(Throwable e) {
- if (fExpectSuccess) {
- fail("Trace was expected to succeed, but failed parsing: " +
- fTracePath + " (" + e.getMessage() + ")");
- }
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013, 2014 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Alexandre Montplaisir - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.ctftestsuite;
-
-import org.junit.runner.RunWith;
-import org.junit.runners.Suite;
-
-/**
- * The class <code>TestAll</code> builds a suite that can be used to run all of
- * the tests within its package as well as within any subpackages of its
- * package.
- *
- * @author ematkho
- */
-@RunWith(Suite.class)
-@Suite.SuiteClasses({
- CtfTestSuiteTests.class
-})
-public class TestAll {
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013, 2014 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.event;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.linuxtools.ctf.core.event.CTFCallsite;
-import org.junit.Test;
-
-/**
- * The class <code>CTFCallsiteTest</code> contains tests for the class
- * <code>{@link CTFCallsite}</code>.
- *
- * @author Matthew Khouzam
- * @version $Revision: 1.0 $
- */
-
-public class CTFCallsiteTest {
-
- private static CTFCallsite GenerateCS(long ip){
- return new CTFCallsite("event name", "func name", ip, "file.java", 1);
- }
-
- /**
- * Test the constructor
- */
- @Test
- public void constructorTest(){
- CTFCallsite cs = GenerateCS(0x01);
- assertNotNull(cs);
- }
-
- /**
- * Test the getters
- */
- @Test
- public void getterTest(){
- CTFCallsite cs = GenerateCS(0x01);
- assertEquals("ip", 1, cs.getIp());
- assertEquals("ip", "event name", cs.getEventName());
- assertEquals("ip", "file.java", cs.getFileName());
- assertEquals("ip", "func name", cs.getFunctionName());
- }
-
- /**
- * Test the hash code
- */
- @Test
- public void hashCodeTest(){
- CTFCallsite cs = GenerateCS(0x01);
- Map<CTFCallsite, Object> test = new HashMap<>();
- test.put(cs, new Object());
- assertTrue(test.containsKey(cs));
- assertTrue(test.containsKey(GenerateCS(0x01)));
- assertFalse(test.containsKey(GenerateCS(0x02)));
- assertFalse(test.containsKey(new CTFCallsite("event nam", "func name", 1, "file.java", 1)));
- assertFalse(test.containsKey(new CTFCallsite("event name", "func nam", 1, "file.java", 1)));
- assertFalse(test.containsKey(new CTFCallsite("event name", "func name", 1, "file.jav", 1)));
- assertFalse(test.containsKey(new CTFCallsite("event name", "func name", 1, "file.java", 2)));
- }
-
- /**
- * Test the comparator (it should sort using the IP)
- */
- @Test
- public void comparatorTest(){
- CTFCallsite cs[] = new CTFCallsite[5];
- long vals[] = {1L, 0L, -2L, 2L, -1L};
- for(int i = 0 ; i < 5 ; i++ ){
- cs[i] = GenerateCS(vals[i]);
- }
-
- assertEquals(1, cs[0].compareTo(cs[1]));
- assertEquals(-1, cs[1].compareTo(cs[0]));
- assertEquals(0, cs[0].compareTo(cs[0]));
- assertEquals(-1, cs[0].compareTo(cs[2]));
- assertEquals(1, cs[2].compareTo(cs[0]));
-
- Arrays.sort(cs);
-
- assertEquals( 0L, cs[0].getIp());
- assertEquals( 1L, cs[1].getIp());
- assertEquals( 2L, cs[2].getIp());
- assertEquals( -2L , cs[3].getIp());
- assertEquals( -1L, cs[4].getIp());
- }
-
- /**
- * Tests the output of a callsite toString function
- */
- @Test
- public void toStringTest(){
- CTFCallsite cs = GenerateCS(0x01);
- assertEquals("file.java/func name:1", cs.toString());
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.event;
-
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-
-import java.nio.ByteOrder;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-import org.eclipse.linuxtools.ctf.core.event.EventDefinition;
-import org.eclipse.linuxtools.ctf.core.event.scope.LexicalScope;
-import org.eclipse.linuxtools.ctf.core.event.types.Definition;
-import org.eclipse.linuxtools.ctf.core.event.types.Encoding;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDefinition;
-import org.eclipse.linuxtools.internal.ctf.core.event.EventDeclaration;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * Test the event definition
- *
- * @author Matthew Khouzam
- *
- */
-public class CTFEventDefinitionTest {
- List<EventDefinition> fixture;
-
- /**
- * Making a power set of configurations to test the event definition
- */
- @Before
- public void init() {
- fixture = new ArrayList<>();
- IntegerDeclaration pidDec = IntegerDeclaration.createDeclaration(5, false, 10, ByteOrder.LITTLE_ENDIAN, Encoding.NONE, "", 8);
- IntegerDeclaration ctxDec = IntegerDeclaration.createDeclaration(16, false, 10, ByteOrder.LITTLE_ENDIAN, Encoding.NONE, "", 8);
- IntegerDefinition pid = new IntegerDefinition(pidDec, null, "pid", 3);
- IntegerDefinition pod = new IntegerDefinition(pidDec, null, "pod", 3);
- IntegerDefinition ctx = new IntegerDefinition(pidDec, null, "ctx", 3);
-
- StructDeclaration streamContextDec = new StructDeclaration(8);
- streamContextDec.addField("pid", pidDec);
- streamContextDec.addField("ctx", ctxDec);
- StructDeclaration eventContextDec = new StructDeclaration(8);
- streamContextDec.addField("pod", pidDec);
- streamContextDec.addField("ctx", pidDec);
- StructDeclaration fDec = new StructDeclaration(8);
- EventDeclaration eventDeclaration = new EventDeclaration();
-
- fDec.addField("pid", pidDec);
- fDec.addField("ctx", ctxDec);
- fDec.addField("pod", pidDec);
-
- List<String> sFieldNames = Arrays.asList("pid", "ctx");
- List<String> eFieldNames = Arrays.asList("pod", "ctx");
- List<String> fieldNames = Arrays.asList("pid", "ctx", "pod");
-
- Definition[] sDefs = { pid, ctx };
- Definition[] eDefs = { pod, ctx };
- Definition[] fDefs = { pid, ctx, pod };
-
- StructDeclaration pContextDec = new StructDeclaration(8);
-
- StructDefinition sContext = new StructDefinition(streamContextDec, null, LexicalScope.STREAM_PACKET_CONTEXT.toString(), sFieldNames, sDefs);
- StructDefinition eContext = new StructDefinition(eventContextDec, null, LexicalScope.STREAM_EVENT_CONTEXT.toString(), eFieldNames, eDefs);
- StructDefinition pContext = new StructDefinition(pContextDec, null, LexicalScope.FIELDS.toString(), Collections.EMPTY_LIST, new Definition[0]);
- StructDefinition fields = new StructDefinition(fDec, null, LexicalScope.FIELDS.toString(), fieldNames, fDefs);
-
- fixture.add(new EventDefinition(eventDeclaration, null, 100, null, null, null, null));
- fixture.add(new EventDefinition(eventDeclaration, null, 100, null, null, null, fields));
- fixture.add(new EventDefinition(eventDeclaration, null, 100, null, null, pContext, null));
- fixture.add(new EventDefinition(eventDeclaration, null, 100, null, null, pContext, fields));
- fixture.add(new EventDefinition(eventDeclaration, null, 100, null, eContext, null, null));
- fixture.add(new EventDefinition(eventDeclaration, null, 100, null, eContext, null, fields));
- fixture.add(new EventDefinition(eventDeclaration, null, 100, null, eContext, pContext, null));
- fixture.add(new EventDefinition(eventDeclaration, null, 100, null, eContext, pContext, fields));
- fixture.add(new EventDefinition(eventDeclaration, null, 100, sContext, null, null, null));
- fixture.add(new EventDefinition(eventDeclaration, null, 100, sContext, null, null, fields));
- fixture.add(new EventDefinition(eventDeclaration, null, 100, sContext, null, pContext, null));
- fixture.add(new EventDefinition(eventDeclaration, null, 100, sContext, null, pContext, fields));
- fixture.add(new EventDefinition(eventDeclaration, null, 100, sContext, eContext, null, null));
- fixture.add(new EventDefinition(eventDeclaration, null, 100, sContext, eContext, null, fields));
- fixture.add(new EventDefinition(eventDeclaration, null, 100, sContext, eContext, pContext, null));
- fixture.add(new EventDefinition(eventDeclaration, null, 100, sContext, eContext, pContext, fields));
- }
-
- /**
- * Test all the events
- */
- @Test
- public void testEvents() {
- int i = 0;
- for (EventDefinition ed : fixture) {
- test(i, ed);
- i++;
- }
- }
-
- private static void test(int rank, EventDefinition ed) {
- String title = "event #" + rank;
- assertEquals(title, 100L, ed.getTimestamp());
- StructDefinition context = ed.getContext();
- if (rank >= 4) {
- assertNotNull(title, context);
- if (rank >= 12) {
- assertEquals(title, 3, context.getFieldNames().size());
- } else {
- assertEquals(title, 2, context.getFieldNames().size());
- }
-
- } else {
- assertNull(title, context);
- }
- if (((rank / 4) % 2) == 1) {
- assertNotNull(title, ed.getEventContext());
- }else{
- assertNull(title, ed.getEventContext());
- }
- if (rank % 2 == 1) {
- assertNotNull(title, ed.getFields());
- assertEquals(title, 3, ed.getFields().getFieldNames().size());
- } else {
- assertNull(title, ed.getFields());
- }
- assertTrue(title, ed.toString().startsWith("Event type: null" + System.getProperty("line.separator") + "Timestamp: 100"));
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.event;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.types.Definition;
-import org.eclipse.linuxtools.ctf.core.event.types.Encoding;
-import org.eclipse.linuxtools.ctf.core.event.types.IDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.StringDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StringDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDefinition;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.internal.ctf.core.event.types.SequenceDeclaration;
-import org.junit.Test;
-
-import com.google.common.collect.ImmutableList;
-
-/**
- * The class <code>CTFEventFieldTest</code> contains tests for the class
- * <code>{@link CTFEventField}</code>.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-@SuppressWarnings("javadoc")
-public class CTFEventFieldTest {
-
- @NonNull
- private static final String fieldName = "id";
-
- /**
- * Run the CTFEventField parseField(Definition,String) method test.
- *
- * @throws CTFReaderException
- */
- @Test
- public void testParseField_complex() throws CTFReaderException {
- int len = 32;
- IntegerDeclaration id = IntegerDeclaration.createDeclaration(
- len,
- false,
- len,
- ByteOrder.LITTLE_ENDIAN,
- Encoding.ASCII,
- "",
- len);
- String lengthName = "LengthName";
- StructDeclaration structDec = new StructDeclaration(0);
- structDec.addField(lengthName, id);
- StructDefinition structDef = new StructDefinition(
- structDec,
- null,
- lengthName,
- ImmutableList.of(lengthName),
- new Definition[] {
- new IntegerDefinition(
- id,
- null,
- lengthName,
- 32)
- });
-
- SequenceDeclaration sd = new SequenceDeclaration(lengthName, id);
- ByteBuffer byb = testMemory(ByteBuffer.allocate(1024));
- for (int i = 0; i < 1024; i++) {
- byb.put((byte) i);
- }
- BitBuffer bb = new BitBuffer(byb);
- IDefinition fieldDef = sd.createDefinition(structDef, "fff-fffield", bb);
-
- assertNotNull(fieldDef);
- }
-
- @NonNull
- private static ByteBuffer testMemory(ByteBuffer buffer) {
- if (buffer == null) {
- throw new IllegalStateException("Failed to allocate memory");
- }
- return buffer;
- }
-
- /**
- * Run the CTFEventField parseField(Definition,String) method test.
- *
- * @throws CTFReaderException
- */
- @Test
- public void testParseField_simple() throws CTFReaderException {
- final StringDeclaration elemType = new StringDeclaration();
- byte[] bytes = { 'T', 'e', 's', 't', '\0' };
- ByteBuffer bb = testMemory(ByteBuffer.wrap(bytes));
- IDefinition fieldDef = elemType.createDefinition(null, fieldName, new BitBuffer(bb));
-
- assertNotNull(fieldDef);
- }
-
- /**
- * Run the CTFEventField parseField(Definition,String) method test.
- */
- @Test
- public void testParseField_simple2() {
- IntegerDefinition fieldDef = new IntegerDefinition(
- IntegerDeclaration.createDeclaration(1, false, 1, ByteOrder.BIG_ENDIAN,
- Encoding.ASCII, "", 8), null, fieldName, 1L);
-
- assertNotNull(fieldDef);
- }
-
- /**
- *
- */
- @Test
- public void testParseField_simple3() {
- StringDefinition fieldDef = new StringDefinition(
- new StringDeclaration(), null, fieldName, "Hello World");
-
- String other = "\"Hello World\"";
- assertNotNull(fieldDef);
- assertEquals(fieldDef.toString(), other);
- }
-
-}
\ No newline at end of file
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013, 2014 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.event;
-
-import org.junit.runner.RunWith;
-import org.junit.runners.Suite;
-
-/**
- * The class <code>TestAll</code> builds a suite that can be used to run all of
- * the tests within its package as well as within any subpackages of its
- * package.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-@RunWith(Suite.class)
-@Suite.SuiteClasses({
- CTFCallsiteTest.class,
- CTFEventDefinitionTest.class,
- CTFEventFieldTest.class
-})
-public class TestAll {
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013, 2014 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Alexandre Montplaisir - Extracted from BitBufferTest, cleanup
- * Matthew Khouzam - Additional tests
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.io;
-
-import static org.junit.Assert.assertEquals;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * Part of the {@link BitBuffer} tests which test the methods to read/write
- * integers. These are separated from the main file because the fixture is
- * different.
- *
- * @author Alexandre Montplaisir
- */
-public class BitBufferIntTest {
-
- private BitBuffer fixture;
-
- /**
- * Perform pre-test initialization.
- *
- * @throws CTFReaderException
- * Out of bounds, won't happen
- */
- @Before
- public void setUp() throws CTFReaderException {
- ByteBuffer allocateDirect = ByteBuffer.allocateDirect(128);
- if (allocateDirect == null) {
- throw new IllegalStateException("Failed to allocate memory");
- }
- fixture = new BitBuffer(allocateDirect);
- fixture.setByteOrder(ByteOrder.BIG_ENDIAN);
- fixture = createBuffer();
- }
-
- private static BitBuffer createBuffer() throws CTFReaderException {
- return createBuffer(16);
- }
-
- private static BitBuffer createBuffer(int j) throws CTFReaderException {
- final byte[] bytes = new byte[j];
- for (int i = 0; i < j; i++) {
- bytes[i] = (byte) (i % 0xff);
- }
- ByteBuffer wrap = ByteBuffer.wrap(bytes);
- if (wrap == null) {
- throw new IllegalStateException("Failed to allocate memory");
- }
- BitBuffer fixture = new BitBuffer(wrap);
- fixture.position(1);
- return fixture;
- }
-
- /**
- * Test {@link BitBuffer#getInt} with a basic value
- *
- * @throws CTFReaderException
- * Not expected
- */
- @Test
- public void testGetInt_base() throws CTFReaderException {
- int result = fixture.getInt();
- assertEquals(0x020406, result);
- }
-
- /**
- * Test {@link BitBuffer#getInt} with explicit seek at pos 0.
- *
- * @throws CTFReaderException
- * Not expected
- */
- @Test
- public void testGetInt_pos0() throws CTFReaderException {
- fixture.position(0);
- int result = fixture.getInt();
- assertEquals(0x010203, result);
- }
-
- /**
- * Test {@link BitBuffer#get} with seek at pos 1.
- *
- * @throws CTFReaderException
- * Not expected
- */
- @Test
- public void testGetInt_pos1() throws CTFReaderException {
- fixture.position(1);
-
- long result = fixture.get(1, true);
- assertEquals(0, result);
- }
-
- /**
- * Test {@link BitBuffer#get} with seek at pos 2.
- *
- * @throws CTFReaderException
- * Not expected
- */
- @Test
- public void testGetInt_pos2() throws CTFReaderException {
- fixture.position(2);
-
- long result = fixture.get(0, true);
- assertEquals(0, result);
- }
-
- /**
- * Test {@link BitBuffer#get} with explicit little-endian reading.
- *
- * @throws CTFReaderException
- * Not expected
- */
- @Test
- public void testGetInt_le2() throws CTFReaderException {
- BitBuffer leFixture = createBuffer(128);
- leFixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
- leFixture.position(0);
- long result = leFixture.get(24, false);
- assertEquals(0x020100, result);
- }
-
- /**
- * Test {@link BitBuffer#get} with explicit little-endian reading, with an
- * offset.
- *
- * @throws CTFReaderException
- * Not expected
- */
- @Test
- public void testGetInt_le1() throws CTFReaderException {
- BitBuffer leFixture = createBuffer(128);
- leFixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
- leFixture.position(1);
- long result = leFixture.get(24, false);
- assertEquals(0x810080, result); /* 0x020100 down-shifted */
- }
-
- /**
- * Test {@link BitBuffer#get} with a 32-bit out-of-bounds read. Should throw
- * an exception.
- *
- * @throws CTFReaderException
- * Expected
- */
- @Test(expected = CTFReaderException.class)
- public void testGetInt_invalid() throws CTFReaderException {
- BitBuffer smallFixture = createBuffer(2);
- smallFixture.setByteOrder(ByteOrder.BIG_ENDIAN);
-
- smallFixture.position(10);
-
- /* This will attempt to read past the buffer's end. */
- smallFixture.get(32, true);
- }
-
- /**
- * Test {@link BitBuffer#get} with a 64-bit out-of-bounds read. Should throw
- * an exception.
- *
- * @throws CTFReaderException
- * Expected
- */
- @Test(expected = CTFReaderException.class)
- public void testGetInt_invalid2() throws CTFReaderException {
- BitBuffer smallFixture = createBuffer(2);
- smallFixture.setByteOrder(ByteOrder.BIG_ENDIAN);
-
- smallFixture.position(1);
-
- /* This will attempt to read past the buffer's end. */
- smallFixture.get(64, true);
- }
-
- /**
- * Test {@link BitBuffer#getLong}.
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void testGetLong_pos0() throws CTFReaderException {
- fixture.position(0);
- long result = fixture.getLong();
- assertEquals(0x01020304050607L, result);
- }
-
- /**
- * Test {@link BitBuffer#getLong} with an offset of 7.
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void testGetLong_pos7() throws CTFReaderException {
- fixture.position(7);
- long result = fixture.getLong();
- assertEquals(0x81018202830384L, result);
- }
-
- /**
- * Test {@link BitBuffer#getLong} with an offset of 8.
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void testGetLong_pos8() throws CTFReaderException {
- fixture.position(8);
- long result = fixture.getLong();
- assertEquals(0x0102030405060708L, result);
- }
-
- /**
- * Test {@link BitBuffer#getLong} with a little-endian buffer.
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void testGetLong_pos0LE() throws CTFReaderException {
- fixture.position(0);
- fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
- long result = fixture.getLong();
- assertEquals(0x0706050403020100L, result);
- }
-
- /**
- * Test {@link BitBuffer#getLong} with a little-endian buffer at pos 7.
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void testGetLong_pos7LE() throws CTFReaderException {
- fixture.position(7);
- fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
- long result = fixture.getLong();
- assertEquals(0x100e0c0a08060402L, result);
- }
-
- /**
- * Test {@link BitBuffer#getLong} with a little-endian buffer at pos 8.
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void testGetLong_pos8LE() throws CTFReaderException {
- fixture.position(8);
- fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
- long result = fixture.getLong();
- assertEquals(0x0807060504030201L, result);
- }
-
- /**
- * Test {@link BitBuffer#get} for >32 bits in length.
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void testGet35_pos0BE() throws CTFReaderException {
- fixture.position(0);
- long result = fixture.get(35, false);
- assertEquals(0x081018L, result);
- }
-
- /**
- * Test {@link BitBuffer#get} for >32 bits in length at an offset position.
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void testGet35_pos8BE() throws CTFReaderException {
- fixture.position(8);
- long result = fixture.get(35, false);
- assertEquals(0x08101820L, result);
- }
-
- /**
- * Test {@link BitBuffer#get} for >32 bits in length in little-endian.
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void testGet35_pos0LE() throws CTFReaderException {
- fixture.position(0);
- fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
- long result = fixture.get(35, false);
- assertEquals(0x0403020100L, result);
- }
-
- /**
- * Test {@link BitBuffer#get} for >32 bits in length, in little-endian, at
- * position 7.
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void testGetLong35_pos7LE() throws CTFReaderException {
- fixture.position(7);
- fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
- long result = fixture.get(35, false);
- assertEquals(0x0208060402L, result);
- }
-
- /**
- * Test {@link BitBuffer#get} for >32 bits in length, in little-endian, at
- * position 8.
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void testGetLong35_pos8LE() throws CTFReaderException {
- fixture.position(8);
- fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
- long result = fixture.get(35, false);
- assertEquals(0x0504030201L, result);
- }
-
- /**
- * Test {@link BitBuffer#get} for >32 bits in length, in little-endian, for
- * a signed value.
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void testGetLong35s_pos0LE() throws CTFReaderException {
- fixture.position(0);
- fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
- long result = fixture.get(35, true);
- assertEquals(0xfffffffc03020100L, result);
- }
-
- /**
- * Test {@link BitBuffer#get} for >32 bits in length, in little-endian, for
- * a signed value, at position 7.
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void testGetLong35s_pos7LE() throws CTFReaderException {
- fixture.position(7);
- fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
- long result = fixture.get(35, true);
- assertEquals(0x0208060402L, result);
- }
-
- /**
- * Test {@link BitBuffer#get} for >32 bits in length, in little-endian, for
- * a signed value, at position 8.
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void testGetLong35s_pos8LE() throws CTFReaderException {
- fixture.position(8);
- fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
- long result = fixture.get(35, true);
- assertEquals(0xfffffffd04030201L, result);
- }
-
- /**
- * Test reading negative values as signed values.
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void testGetSigned() throws CTFReaderException {
- fixture.position(0);
- fixture.putInt(-1);
- fixture.putInt(-1);
- fixture.position(0);
- fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
-
- long result = fixture.get(32, true);
- assertEquals(-1L, result);
- }
-
- /**
- * Test reading negative values as unsigned values.
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void testGetUnsigned() throws CTFReaderException {
- fixture.position(0);
- fixture.putInt(-1);
- fixture.putInt(-1);
- fixture.position(0);
- fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
-
- long result = fixture.get(32, false);
- assertEquals(0xFFFFFFFFL, result);
- }
-
- /**
- * Test reading 24 bits of a 32-bit negative value as a signed value.
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void testGet24Signed() throws CTFReaderException {
- fixture.position(0);
- fixture.putInt(-1);
- fixture.putInt(-1);
- fixture.position(0);
- fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
-
- long result = fixture.get(24, true);
- assertEquals(-1L, result);
- }
-
- /**
- * Test reading 24 bits of a 32-bit negative value as an unsigned value.
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void testGet24Unsigned() throws CTFReaderException {
- fixture.position(0);
- fixture.putInt(-1);
- fixture.putInt(-1);
- fixture.position(0);
- fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
-
- long result = fixture.get(24, false);
- assertEquals(0xFFFFFFL, result);
- }
-
- /**
- * Test {@link BitBuffer#putInt(int)}
- *
- * @throws CTFReaderException
- * Not expected
- */
- @Test
- public void testPutInt() throws CTFReaderException {
- fixture.position(1);
- fixture.putInt(1);
- }
-
- /**
- * Test {@link BitBuffer#putInt(int, int)}
- *
- * @throws CTFReaderException
- * Not expected
- */
- @Test
- public void testPutInt_length1() throws CTFReaderException {
- fixture.position(1);
- fixture.putInt(1, 1);
- }
-
- /**
- * Test {@link BitBuffer#putInt(int, int)} with length = 0.
- *
- * @throws CTFReaderException
- * Not expected
- */
- @Test
- public void testPutInt_length0() throws CTFReaderException {
- fixture.position(1);
- fixture.putInt(0, 1);
- }
-
- /**
- * Test {@link BitBuffer#putInt(int)} Little endian
- *
- * @throws CTFReaderException
- * Not expected
- */
- @Test
- public void testPutIntLe() throws CTFReaderException {
- fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
- fixture.position(1);
- fixture.putInt(1);
- }
-
- /**
- * Test {@link BitBuffer#putInt(int, int)} Little endian
- *
- * @throws CTFReaderException
- * Not expected
- */
- @Test
- public void testPutIntLe_length1() throws CTFReaderException {
- fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
- fixture.position(1);
- fixture.putInt(1, 1);
- }
-
- /**
- * Test {@link BitBuffer#putInt(int, int)} with length = 0. Little endian
- *
- * @throws CTFReaderException
- * Not expected
- */
- @Test
- public void testPutIntLe_length0() throws CTFReaderException {
- fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
- fixture.position(1);
- fixture.putInt(0, 1);
- }
-
- /**
- * Test writing and reading a value defined in hex format.
- *
- * @throws CTFReaderException
- * Not expected
- */
- @Test
- public void testPutInt_hex() throws CTFReaderException {
- final int value = 0x010203;
-
- for (int i = 0; i <= 32; i++) {
- fixture.position(i);
- fixture.putInt(value);
-
- fixture.position(i);
- int read = fixture.getInt();
-
- assertEquals(value, read);
- }
- }
-
- /**
- * Test {@link BitBuffer#putInt} with an out-of-bounds length. An exception
- * should be thrown.
- *
- * @throws CTFReaderException
- * Expected
- */
- @Test(expected = CTFReaderException.class)
- public void testPutInt_invalid() throws CTFReaderException {
- BitBuffer fixture2;
- fixture2 = createBuffer(4);
- fixture2.setByteOrder(ByteOrder.BIG_ENDIAN);
- fixture2.position(1);
-
- /* This will try writing past the buffer's end */
- fixture2.putInt(32, 1);
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.io;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * The class <code>BitBufferTest</code> contains tests for the class
- * <code>{@link BitBuffer}</code>.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-public class BitBufferTest {
-
- private BitBuffer fixture;
-
- /**
- * Perform pre-test initialization.
- *
- * @throws CTFReaderException
- * An error that cannot happen (position is under 128)
- */
- @Before
- public void setUp() throws CTFReaderException {
- fixture = new BitBuffer(Util.testMemory(ByteBuffer.allocateDirect(1)));
- fixture.setByteOrder(ByteOrder.BIG_ENDIAN);
- fixture.position(1);
- }
-
- /**
- * Run the BitBuffer() constructor test.
- */
- @Test
- public void testBitBuffer() {
- BitBuffer result = new BitBuffer();
-
- assertNotNull(result);
- assertEquals(0, result.position());
- assertNotNull(result.getByteBuffer());
- }
-
- /**
- * Run the BitBuffer(ByteBuffer) constructor test.
- */
- @Test
- public void testBitBuffer_fromByteBuffer() {
- BitBuffer result = new BitBuffer(Util.testMemory(ByteBuffer.allocate(0)));
- assertNotNull(result);
- assertEquals(0, result.position());
- }
-
- /**
- * Run the boolean canRead(int) method test.
- */
- @Test
- public void testCanRead_1param() {
- int length = 1;
- boolean result = fixture.canRead(length);
-
- assertEquals(true, result);
- }
-
- /**
- * Run the void clear() method test.
- */
- @Test
- public void testClear() {
- fixture.clear();
- }
-
- /**
- * Run the ByteBuffer getByteBuffer() method test.
- */
- @Test
- public void testGetByteBuffer() {
- ByteBuffer result = fixture.getByteBuffer();
-
- assertNotNull(result);
- assertEquals("java.nio.DirectByteBuffer[pos=0 lim=1 cap=1]", result.toString());
- assertEquals(true, result.isDirect());
- assertEquals(false, result.hasArray());
- assertEquals(1, result.limit());
- assertEquals(1, result.remaining());
- assertEquals(0, result.position());
- assertEquals(1, result.capacity());
- assertEquals(true, result.hasRemaining());
- assertEquals(false, result.isReadOnly());
- }
-
- /**
- * Run the ByteOrder getByteOrder() method test.
- */
- @Test
- public void testGetByteOrder() {
- ByteOrder result = fixture.getByteOrder();
-
- assertNotNull(result);
- assertEquals("BIG_ENDIAN", result.toString());
- }
-
- /**
- * Run the ByteOrder order() method test.
- */
- @Test
- public void testGetOrder() {
- ByteOrder result = fixture.getByteOrder();
-
- assertNotNull(result);
- assertEquals("BIG_ENDIAN", result.toString());
- }
-
- /**
- * Run the void order(ByteOrder) method test.
- */
- @Test
- public void testSetOrder() {
- ByteOrder order = ByteOrder.BIG_ENDIAN;
-
- fixture.setByteOrder(order);
- }
-
- /**
- * Run the int position() method test.
- */
- @Test
- public void testGetPosition() {
- long result = fixture.position();
-
- assertEquals(1, result);
- }
-
- /**
- * Run the void position(int) method test.
- *
- * @throws CTFReaderException
- * out of bounds? won't happen
- */
- @Test
- public void testSetPosition() throws CTFReaderException {
- int newPosition = 1;
- fixture.position(newPosition);
- }
-
- /**
- * Run the void setByteOrder(ByteOrder) method test.
- */
- @Test
- public void testSetByteOrder() {
- ByteOrder byteOrder = ByteOrder.BIG_ENDIAN;
- fixture.setByteOrder(byteOrder);
- }
-
- /**
- * Test the get function
- */
- @Test
- public void testGetBytes() {
- @NonNull
- byte[] data = new byte[2];
- ByteBuffer bb = ByteBuffer.allocate(10);
- bb.put((byte) 0);
- bb.put((byte) 1);
- bb.put((byte) 1);
- bb.put((byte) 0);
- fixture = new BitBuffer(bb);
- fixture.get(data);
- assertEquals(0, data[0]);
- assertEquals(1, data[1]);
- fixture.get(data);
- assertEquals(1, data[0]);
- assertEquals(0, data[1]);
- }
-
- /**
- * Test the get function
- *
- * @throws CTFReaderException
- * won't happen but we seek in a buffer
- */
- @Test
- public void testGetBytesMiddle() throws CTFReaderException {
- @NonNull
- byte[] data = new byte[5];
- // this string has been carefully selected and tested... don't change
- // the string and expect the result to be the same.
- fixture = new BitBuffer(Util.testMemory(ByteBuffer.wrap(new String("hello world").getBytes())));
- fixture.position(6 * 8);
- fixture.get(data);
- String actual = new String(data);
- assertEquals("world", actual);
- }
-}
\ No newline at end of file
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.io;
-
-import org.junit.runner.RunWith;
-import org.junit.runners.Suite;
-
-/**
- * The class <code>TestAll</code> builds a suite that can be used to run all of
- * the tests within its package as well as within any subpackages of its
- * package.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-@RunWith(Suite.class)
-@Suite.SuiteClasses({
- BitBufferIntTest.class,
- BitBufferTest.class
-})
-public class TestAll {
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- ******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.io;
-
-import java.nio.ByteBuffer;
-
-import org.eclipse.jdt.annotation.NonNull;
-
-/**
- * Helpers for the tests
- *
- * @author Matthew Khouzam
- */
-public final class Util {
-
- private Util() {
- }
-
- /**
- * Wrapper to make sure the bytebuffer is not null
- *
- * @param buffer
- * a potentially null byte buffer
- * @return a non-null byte buffer or an illegal state exception
- */
- @NonNull
- public static ByteBuffer testMemory(ByteBuffer buffer) {
- if (buffer == null) {
- throw new IllegalStateException("Failed to alloc");
- }
- return buffer;
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are
- * made available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.scope;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import org.eclipse.linuxtools.ctf.core.event.scope.LexicalScope;
-import org.junit.Test;
-
-/**
- * Lexical test
- *
- * @author Matthew Khouzam
- */
-public class LexicalScopeTest {
-
- /**
- * Root test
- */
- @Test
- public void testRoot(){
- LexicalScope scope = LexicalScope.ROOT;
- assertNotNull(scope);
- }
-
- /**
- * Test a more complex node
- */
- @Test
- public void testComplexNode(){
- LexicalScope scope = LexicalScope.STREAM_EVENT_CONTEXT;
- assertEquals("context", scope.getName());
- assertEquals("stream.event.context", scope.toString());
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.scope;
-
-import org.junit.runner.RunWith;
-import org.junit.runners.Suite;
-
-/**
- * The class <code>TestAll</code> builds a suite that can be used to run all of
- * the tests within its package as well as within any subpackages of its
- * package.
- *
- * @author Matthew Khouzam
- * @version $Revision: 1.0 $
- */
-@RunWith(Suite.class)
-@Suite.SuiteClasses({
- LexicalScopeTest.class
-})
-public class TestAll {
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013, 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are
- * made available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- * Marc-Andre Laperle - Move generation to traces folder
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.synthetictraces;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.net.URL;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.nio.channels.FileChannel;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Random;
-
-import org.eclipse.core.runtime.FileLocator;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.linuxtools.ctf.core.tests.CtfCoreTestPlugin;
-
-/**
- * Generate a kernel trace
- *
- * @author Matthew Khouzam
- */
-public class LttngKernelTraceGenerator {
-
- private static final String metadata = "/* CTF 1.8 */ \n" +
- "typealias integer { size = 8; align = 8; signed = false; } := uint8_t;\n" +
- "typealias integer { size = 16; align = 8; signed = false; } := uint16_t;\n" +
- "typealias integer { size = 32; align = 8; signed = false; } := uint32_t;\n" +
- "typealias integer { size = 64; align = 8; signed = false; } := uint64_t;\n" +
- "typealias integer { size = 32; align = 8; signed = false; } := unsigned long;\n" +
- "typealias integer { size = 5; align = 1; signed = false; } := uint5_t;\n" +
- "typealias integer { size = 27; align = 1; signed = false; } := uint27_t;\n" +
- "\n" +
- "trace {\n" +
- " major = 1;\n" +
- " minor = 8;\n" +
- " uuid = \"11111111-1111-1111-1111-111111111111\";\n" +
- " byte_order = le;\n" +
- " packet.header := struct {\n" +
- " uint32_t magic;\n" +
- " uint8_t uuid[16];\n" +
- " uint32_t stream_id;\n" +
- " };\n" +
- "};\n" +
- "\n" +
- "env {\n" +
- " hostname = \"synthetic-host\";\n" +
- " domain = \"kernel\";\n" +
- " sysname = \"FakeLinux\";\n" +
- " kernel_release = \"1.0\";\n" +
- " kernel_version = \"Fake Os Synthetic Trace\";\n" +
- " tracer_name = \"lttng-modules\";\n" +
- " tracer_major = 2;\n" +
- " tracer_minor = 1;\n" +
- " tracer_patchlevel = 0;\n" +
- "};\n" +
- "\n" +
- "clock {\n" +
- " name = monotonic;\n" +
- " uuid = \"bbff68f0-c633-4ea1-92cd-bd11024ec4de\";\n" +
- " description = \"Monotonic Clock\";\n" +
- " freq = 1000000000; /* Frequency, in Hz */\n" +
- " /* clock value offset from Epoch is: offset * (1/freq) */\n" +
- " offset = 1368000272650993664;\n" +
- "};\n" +
- "\n" +
- "typealias integer {\n" +
- " size = 27; align = 1; signed = false;\n" +
- " map = clock.monotonic.value;\n" +
- "} := uint27_clock_monotonic_t;\n" +
- "\n" +
- "typealias integer {\n" +
- " size = 32; align = 8; signed = false;\n" +
- " map = clock.monotonic.value;\n" +
- "} := uint32_clock_monotonic_t;\n" +
- "\n" +
- "typealias integer {\n" +
- " size = 64; align = 8; signed = false;\n" +
- " map = clock.monotonic.value;\n" +
- "} := uint64_clock_monotonic_t;\n" +
- "\n" +
- "struct packet_context {\n" +
- " uint64_clock_monotonic_t timestamp_begin;\n" +
- " uint64_clock_monotonic_t timestamp_end;\n" +
- " uint64_t content_size;\n" +
- " uint64_t packet_size;\n" +
- " unsigned long events_discarded;\n" +
- " uint32_t cpu_id;\n" +
- "};\n" +
- "\n" +
- "struct event_header_compact {\n" +
- " enum : uint5_t { compact = 0 ... 30, extended = 31 } id;\n" +
- " variant <id> {\n" +
- " struct {\n" +
- " uint27_clock_monotonic_t timestamp;\n" +
- " } compact;\n" +
- " struct {\n" +
- " uint32_t id;\n" +
- " uint64_clock_monotonic_t timestamp;\n" +
- " } extended;\n" +
- " } v;\n" +
- "} align(8);\n" +
- "\n" +
- "struct event_header_large {\n" +
- " enum : uint16_t { compact = 0 ... 65534, extended = 65535 } id;\n" +
- " variant <id> {\n" +
- " struct {\n" +
- " uint32_clock_monotonic_t timestamp;\n" +
- " } compact;\n" +
- " struct {\n" +
- " uint32_t id;\n" +
- " uint64_clock_monotonic_t timestamp;\n" +
- " } extended;\n" +
- " } v;\n" +
- "} align(8);\n" +
- "\n" +
- "stream {\n" +
- " id = 0;\n" +
- " event.header := struct event_header_compact;\n" +
- " packet.context := struct packet_context;\n" +
- "};\n" +
- "\n" +
- "event {\n" +
- " name = sched_switch;\n" +
- " id = 0;\n" +
- " stream_id = 0;\n" +
- " fields := struct {\n" +
- " integer { size = 8; align = 8; signed = 1; encoding = UTF8; base = 10; } _prev_comm[16];\n" +
- " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _prev_tid;\n" +
- " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _prev_prio;\n" +
- " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _prev_state;\n" +
- " integer { size = 8; align = 8; signed = 1; encoding = UTF8; base = 10; } _next_comm[16];\n" +
- " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _next_tid;\n" +
- " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _next_prio;\n" +
- " };\n" +
- "};\n" +
- "\n";
-
- private final List<String> fProcesses;
- private final long fDuration;
- private final long fNbEvents;
- private final int fNbChans;
-
- private static final String[] sfProcesses = {
- "IDLE",
- "gnuplot",
- "starcraft 2:pt3",
- "bash",
- "smash",
- "thrash",
- "fireball",
- "Half-life 3",
- "ST: The game"
- };
-
-
- private static final String TRACES_DIRECTORY = "traces";
- private static final String TRACE_NAME = "synthetic-trace";
-
- /**
- * Main, not always needed
- *
- * @param args
- * args
- */
- public static void main(String[] args) {
- // not using createTempFile as this is a directory
- String path = CtfCoreTestPlugin.getTemporaryDirPath() + File.separator + TRACE_NAME;
- generateLttngKernelTrace(new File(path));
- }
-
- /**
- * Gets the name of the trace (top directory name)
- *
- * @return the name of the trace
- */
- public static String getName() {
- return TRACE_NAME;
- }
-
- /**
- * Get the path
- *
- * @return the path
- */
- public static String getPath() {
- CtfCoreTestPlugin plugin = CtfCoreTestPlugin.getDefault();
- if (plugin == null) {
- return null;
- }
- URL location = FileLocator.find(plugin.getBundle(), new Path(TRACES_DIRECTORY), null);
- File file = null;
- try {
- IPath path = new Path(FileLocator.toFileURL(location).getPath()).append(TRACE_NAME);
- file = path.toFile();
- } catch (IOException e) {
- // Shouldn't happen but at least throw something to get the test to fail early
- throw new IllegalStateException();
- }
-
- if (!file.exists()) {
- generateLttngKernelTrace(file);
- }
- return file.getAbsolutePath();
- }
-
- /**
- * Generate a trace
- *
- * @param file
- * the file to write the trace to
- */
- public static void generateLttngKernelTrace(File file) {
- final int cpus = 25;
- LttngKernelTraceGenerator gt = new LttngKernelTraceGenerator(2l * Integer.MAX_VALUE - 100, 500000, cpus);
- gt.writeTrace(file);
- }
-
- /**
- * Make a kernel trace
- *
- * @param duration
- * the duration of the trace
- * @param events
- * the number of events in a trace
- * @param nbChannels
- * the number of channels in the trace
- */
- public LttngKernelTraceGenerator(long duration, long events, int nbChannels) {
- fProcesses = Arrays.asList(sfProcesses);
- fDuration = duration;
- fNbEvents = events;
- fNbChans = nbChannels;
- }
-
- /**
- * Write the trace to a file
- *
- * @param file
- * the file to write the trace to
- */
- public void writeTrace(File file) {
-
- if (!file.exists()) {
- file.mkdir();
- } else {
- if (file.isFile()) {
- file.delete();
- file.mkdir();
- } else {
- // the ctf parser doesn't recurse, so we don't need to.
- final File[] listFiles = file.listFiles();
- for (File child : listFiles) {
- child.delete();
- }
- }
- }
-
- File metadataFile = new File(file.getPath() + File.separator + "metadata");
- File[] streams = new File[fNbChans];
- FileChannel[] channels = new FileChannel[fNbChans];
-
- try {
- for (int i = 0; i < fNbChans; i++) {
- streams[i] = new File(file.getPath() + File.separator + "channel" + i);
- channels[i] = new FileOutputStream(streams[i]).getChannel();
- }
- } catch (FileNotFoundException e) {
- }
- // determine the number of events per channel
- long evPerChan = fNbEvents / fNbChans;
- int delta = (int) (fDuration / evPerChan);
- int offsetTime = 0;
- for (int chan = 0; chan < fNbChans; chan++) {
- int currentSpace = 0;
- ByteBuffer bb = ByteBuffer.allocate(65536);
- bb.order(ByteOrder.LITTLE_ENDIAN);
- Random rnd = new Random(1337);
- int rnd0 = rnd.nextInt(fProcesses.size());
- String prevComm = fProcesses.get(rnd0);
- int prevPID = rnd0 + chan * fProcesses.size();
- if (rnd0 == 0) {
- prevPID = 0;
- }
- int prevPrio = 0;
- int prevPos = -1;
- for (int eventNb = 0; eventNb < evPerChan; eventNb++) {
- int ts = eventNb * delta + delta / (fNbChans + 1) * chan;
-
- int pos = rnd.nextInt((int) (fProcesses.size() * 1.5));
- if (pos >= fProcesses.size()) {
- pos = 0;
- }
- while (pos == prevPos) {
- pos = rnd.nextInt((int) (fProcesses.size() * 1.5));
- if (pos >= fProcesses.size()) {
- pos = 0;
- }
- }
- String nextComm = fProcesses.get(pos);
- int nextPID = pos + fProcesses.size() * chan;
- if (pos == 0) {
- nextPID = 0;
- }
- int nextPrio = 0;
- if (EventWriter.SIZE > currentSpace) {
- // pad to end
- for (int i = 0; i < currentSpace; i++) {
- bb.put((byte) 0x00);
- }
- // write new packet
- PacketWriter pw = new PacketWriter(bb);
- int tsBegin = ts;
- offsetTime = ts;
- int tsEnd = (eventNb + (PacketWriter.SIZE / EventWriter.SIZE)) * delta + 1;
- pw.writeNewHeader(tsBegin, tsEnd, chan);
- currentSpace = PacketWriter.CONTENT_SIZE;
- }
- EventWriter ew = new EventWriter(bb);
- int prev_state = rnd.nextInt(100);
- if (prev_state != 0) {
- prev_state = 1;
- }
- final int shrunkenTimestamp = ts - offsetTime;
- final int tsMask = (1 << 27) - 1;
- if (shrunkenTimestamp > ((1 << 27) + tsMask)) {
- new Object();
- System.err.println("PROBLEM");
- }
- final int clampedTs = ts & tsMask;
- int evSize = ew.writeEvent(clampedTs, prevComm, prevPID, prevPrio, prev_state, nextComm, nextPID, nextPrio);
- currentSpace -= evSize;
- prevComm = nextComm;
- prevPID = nextPID;
- prevPrio = nextPrio;
- if (bb.position() > 63000) {
- writeToDisk(channels, chan, bb);
- }
- }
- for (int i = 0; i < currentSpace; i++) {
- bb.put((byte) 0x00);
- }
- writeToDisk(channels, chan, bb);
- try {
- channels[chan].close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- try (FileOutputStream fos = new FileOutputStream(metadataFile);) {
- fos.write(metadata.getBytes());
- } catch (IOException e) {
- }
- }
-
- private static void writeToDisk(FileChannel[] channels, int chan, ByteBuffer bb) {
- try {
- bb.flip();
- channels[chan].write(bb);
- bb.clear();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- private class EventWriter {
- public static final int SIZE =
- 4 + // timestamp
- 16 + // prev_comm
- 4 + // prev_tid
- 4 + // prev_prio
- 4 + // prev_state
- 16 + // current_comm
- 4 + // next_tid
- 4; // next_prio
- private final ByteBuffer data;
-
- public EventWriter(ByteBuffer bb) {
- data = bb;
- }
-
- public int writeEvent(int ts, String prev_comm, int prev_tid, int prev_prio, int prev_state, String next_comm, int next_tid, int next_prio) {
- byte[] bOut = new byte[16];
- byte[] bIn = new byte[16];
- byte[] temp = prev_comm.getBytes();
- for (int i = 0; i < Math.min(temp.length, 16); i++) {
- bOut[i] = temp[i];
- }
- temp = next_comm.getBytes();
- for (int i = 0; i < Math.min(temp.length, 16); i++) {
- bIn[i] = temp[i];
- }
-
- int timestamp = ts << 5;
-
- data.putInt(timestamp);
- data.put(bOut);
- data.putInt(prev_tid);
- data.putInt(prev_prio);
- data.putInt(prev_state);
- data.put(bIn);
- data.putInt(next_tid);
- data.putInt(next_prio);
- return SIZE;
- }
-
- }
-
- private class PacketWriter {
- private static final int SIZE = 4096;
- private static final int HEADER_SIZE = 64;
- private static final int CONTENT_SIZE = SIZE - HEADER_SIZE;
-
- private final ByteBuffer data;
-
- public PacketWriter(ByteBuffer bb) {
- data = bb;
- }
-
- public void writeNewHeader(int tsBegin, int tsEnd, int cpu) {
- final int magicLE = 0xC1FC1FC1;
- byte uuid[] = {
- 0x11, 0x11, 0x11, 0x11,
- 0x11, 0x11, 0x11, 0x11,
- 0x11, 0x11, 0x11, 0x11,
- 0x11, 0x11, 0x11, 0x11 };
- // packet header
-
- // magic number 4
- data.putInt(magicLE);
- // uuid 16
- data.put(uuid);
- // stream ID 4
- data.putInt(0);
-
- // packet context
- // timestamp_begin 8
- data.putLong(tsBegin);
-
- // timestamp_end 8
- data.putLong(tsEnd);
-
- // content_size 8
- data.putLong((CONTENT_SIZE / EventWriter.SIZE * EventWriter.SIZE + HEADER_SIZE) * 8);
-
- // packet_size 8
- data.putLong((SIZE) * 8);
-
- // events_discarded 4
- data.putInt(0);
-
- // cpu_id 4
- data.putInt(cpu);
-
- }
-
- }
-
-
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.trace;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import org.eclipse.linuxtools.internal.ctf.core.trace.StreamInputPacketIndexEntry;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * The class <code>StreamInputPacketIndexEntryTest</code> contains tests for the
- * class <code>{@link StreamInputPacketIndexEntry}</code>.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-public class CTFStreamInputPacketIndexEntryTest {
-
- private StreamInputPacketIndexEntry fixture;
-
- /**
- * Perform pre-test initialization.
- */
- @Before
- public void setUp() {
- fixture = new StreamInputPacketIndexEntry(1L);
- }
-
- /**
- * Run the StreamInputPacketIndexEntry(long) constructor test.
- */
- @Test
- public void testStreamInputPacketIndexEntry_1() {
- String expectedResult = "StreamInputPacketIndexEntry [offsetBytes=1, " +
- "timestampBegin=0, timestampEnd=0]";
-
- assertNotNull(fixture);
- assertEquals(expectedResult, fixture.toString());
- }
-
- /**
- * Run the String toString() method test.
- */
- @Test
- public void testToString() {
- String expectedResult = "StreamInputPacketIndexEntry [offsetBytes=1,"+
- " timestampBegin=1, timestampEnd=1]";
-
-
- fixture.setContentSizeBits(1);
- fixture.setDataOffsetBits(1);
- fixture.setTimestampEnd(1L);
- fixture.setPacketSizeBits(1);
- fixture.setTimestampBegin(1L);
-
- assertEquals(expectedResult, fixture.toString());
- }
-}
\ No newline at end of file
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.trace;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import java.util.Collection;
-import java.util.ListIterator;
-
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.internal.ctf.core.trace.StreamInputPacketIndex;
-import org.eclipse.linuxtools.internal.ctf.core.trace.StreamInputPacketIndexEntry;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * The class <code>StreamInputPacketIndexTest</code> contains tests for the
- * class <code>{@link StreamInputPacketIndex}</code>.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-@SuppressWarnings("javadoc")
-public class CTFStreamInputPacketIndexTest {
-
- private StreamInputPacketIndex fixture;
- private StreamInputPacketIndexEntry entry;
-
- /**
- * Perform pre-test initialization.
- *
- * @throws CTFReaderException
- */
- @Before
- public void setUp() throws CTFReaderException {
- fixture = new StreamInputPacketIndex();
- fixture.addEntry(new StreamInputPacketIndexEntry(1L));
- entry = new StreamInputPacketIndexEntry(1L);
- }
-
- /**
- * Run the StreamInputPacketIndex() constructor test.
- */
- @Test
- public void testStreamInputPacketIndex() {
- assertNotNull(fixture);
- }
-
- /**
- * Run the void addEntry(StreamInputPacketIndexEntry) method test, by
- * specifying only 1 parameter to the entry.
- *
- * @throws CTFReaderException
- */
- @Test
- public void testAddEntry_1param() throws CTFReaderException {
- entry.setPacketSizeBits(0);
- fixture.addEntry(entry);
- }
-
- /**
- * Run the void addEntry(StreamInputPacketIndexEntry) method test by
- * specifying 2 parameters to the entry.
- *
- * @throws CTFReaderException
- */
- @Test
- public void testAddEntry_2params() throws CTFReaderException {
- entry.setPacketSizeBits(1);
- entry.setContentSizeBits(0);
- fixture.addEntry(entry);
- }
-
- /**
- * Run the void addEntry(StreamInputPacketIndexEntry) method test, by
- * specifying all 4 parameters to the entry.
- *
- * @throws CTFReaderException
- */
- @Test
- public void testAddEntry_4params() throws CTFReaderException {
- entry.setTimestampBegin(1L);
- entry.setPacketSizeBits(1);
- entry.setContentSizeBits(1);
- entry.setTimestampEnd(1L);
- fixture.addEntry(entry);
- }
-
- /**
- * Run the Collection<StreamInputPacketIndexEntry> getEntries() method test.
- */
- @Test
- public void testGetEntries() {
- Collection<StreamInputPacketIndexEntry> result = fixture.getEntries();
-
- assertNotNull(result);
- assertEquals(1, result.size());
- }
-
- /**
- * Run the ListIterator<StreamInputPacketIndexEntry> listIterator() method
- * test, with no parameter to listIterator().
- */
- @Test
- public void testListIterator_noparam() {
- ListIterator<StreamInputPacketIndexEntry> result = fixture.listIterator();
-
- assertNotNull(result);
- assertEquals(true, result.hasNext());
- assertEquals(-1, result.previousIndex());
- assertEquals(false, result.hasPrevious());
- assertEquals(0, result.nextIndex());
- }
-
- /**
- * Run the ListIterator<StreamInputPacketIndexEntry> listIterator(n) method
- * test, with n = 1.
- */
- @Test
- public void testListIterator_withparam() {
- ListIterator<StreamInputPacketIndexEntry> result = fixture.listIterator(1);
-
- assertNotNull(result);
- assertEquals(false, result.hasNext());
- assertEquals(0, result.previousIndex());
- assertEquals(true, result.hasPrevious());
- assertEquals(1, result.nextIndex());
- assertEquals(false, result.hasNext());
- }
-
- /**
- * Run the ListIterator<StreamInputPacketIndexEntry> search(long) method
- * test with a valid timestamp.
- */
- @Test
- public void testSearch_valid() {
- ListIterator<StreamInputPacketIndexEntry> result = fixture.search(1L);
-
- assertNotNull(result);
- assertEquals(true, result.hasNext());
- assertEquals(-1, result.previousIndex());
- assertEquals(false, result.hasPrevious());
- assertEquals(0, result.nextIndex());
- }
-
- /**
- * Run the ListIterator<StreamInputPacketIndexEntry> search(long) method
- * test with an invalid timestamp.
- */
- @Test(expected = java.lang.IllegalArgumentException.class)
- public void testSearch_invalid() {
- ListIterator<StreamInputPacketIndexEntry> result = fixture.search(-1L);
-
- assertNotNull(result);
- }
-}
\ No newline at end of file
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013, 2014 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.trace;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assume.assumeTrue;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Set;
-
-import org.eclipse.linuxtools.ctf.core.event.EventDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.Definition;
-import org.eclipse.linuxtools.ctf.core.event.types.StringDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StringDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDefinition;
-import org.eclipse.linuxtools.ctf.core.tests.shared.CtfTestTrace;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.ctf.core.trace.CTFResponse;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTrace;
-import org.eclipse.linuxtools.ctf.core.trace.CTFStream;
-import org.eclipse.linuxtools.ctf.core.trace.CTFStreamInput;
-import org.eclipse.linuxtools.ctf.core.trace.CTFStreamInputReader;
-import org.eclipse.linuxtools.internal.ctf.core.event.EventDeclaration;
-import org.junit.Before;
-import org.junit.Test;
-
-import com.google.common.collect.ImmutableList;
-
-/**
- * The class <code>StreamInputReaderTest</code> contains tests for the class
- * <code>{@link CTFStreamInputReader}</code>.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-@SuppressWarnings("javadoc")
-public class CTFStreamInputReaderTest {
-
- private static final CtfTestTrace testTrace = CtfTestTrace.KERNEL;
-
- private CTFStreamInputReader fixture;
-
- private static ImmutableList<String> wrap(String s) {
- return ImmutableList.<String> builder().add(s).build();
- }
-
- /**
- * Perform pre-test initialization.
- *
- * @throws CTFReaderException
- */
- @Before
- public void setUp() throws CTFReaderException {
- fixture = getStreamInputReader();
- fixture.setName(1);
- fixture.setCurrentEvent(new EventDefinition(new EventDeclaration(),
- getStreamInputReader(), 0, null, null,
- new StructDefinition(
- new StructDeclaration(0),
- null,
- "packet",
- wrap( "field" ),
- new Definition[] { new StringDefinition(new StringDeclaration(), null, "field", "test") }),
- null)
- );
- }
-
- private static CTFStreamInputReader getStreamInputReader() throws CTFReaderException {
- assumeTrue(testTrace.exists());
- CTFTrace trace = testTrace.getTrace();
- CTFStream s = trace.getStream((long) 0);
- Set<CTFStreamInput> streamInput = s.getStreamInputs();
- CTFStreamInputReader retVal = null;
- for (CTFStreamInput si : streamInput) {
- /*
- * For the tests, we'll use the stream input corresponding to the
- * CPU 0
- */
- if (si.getFilename().endsWith("0_0")) {
- retVal = new CTFStreamInputReader(si);
- break;
- }
- }
- return retVal;
- }
-
- /**
- * Run the StreamInputReader(StreamInput) constructor test, with a valid
- * trace.
- */
- @Test
- public void testStreamInputReader_valid() {
- assertNotNull(fixture);
- }
-
- /**
- * Run the StreamInputReader(StreamInput) constructor test, with an invalid
- * trace.
- *
- * @throws CTFReaderException
- * @throws IOException
- */
- @Test(expected = CTFReaderException.class)
- public void testStreamInputReader_invalid() throws CTFReaderException, IOException {
- try (CTFStreamInput streamInput = new CTFStreamInput(new CTFStream(new CTFTrace("")), new File(""));
- CTFStreamInputReader result = new CTFStreamInputReader(streamInput)) {
- assertNotNull(result);
- }
- }
-
- /**
- * Run the int getCPU() method test.
- */
- @Test
- public void testGetCPU() {
- int result = fixture.getCPU();
- assertEquals(0, result);
- }
-
- /**
- * Run the EventDefinition getCurrentEvent() method test.
- */
- @Test
- public void testGetCurrentEvent() {
- EventDefinition result = fixture.getCurrentEvent();
- assertNotNull(result);
- }
-
- /**
- * Run the StructDefinition getCurrentPacketContext() method test.
- */
- @Test
- public void testGetCurrentPacketContext() {
- StructDefinition result = fixture.getCurrentEvent().getPacketContext();
- assertNotNull(result);
- }
-
- /**
- * Run the int getName() method test.
- */
- @Test
- public void testGetName() {
- int result = fixture.getName();
- assertEquals(1, result);
- }
-
- /**
- * Run the void goToLastEvent() method test.
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void testGoToLastEvent1() throws CTFReaderException {
- final long endTimestamp = goToEnd();
- final long endTime = 4287422460315L;
- assertEquals(endTime, endTimestamp);
- }
-
- /**
- * Run the void goToLastEvent() method test.
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void testGoToLastEvent2() throws CTFReaderException {
- long timestamp = -1;
- while (fixture.readNextEvent().equals(CTFResponse.OK)) {
- timestamp = fixture.getCurrentEvent().getTimestamp();
- }
- long endTimestamp = goToEnd();
- assertEquals(0, timestamp - endTimestamp);
- }
-
- private long goToEnd() throws CTFReaderException {
- fixture.goToLastEvent();
- return fixture.getCurrentEvent().getTimestamp();
- }
-
- /**
- * Run the boolean readNextEvent() method test.
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void testReadNextEvent() throws CTFReaderException {
- assertEquals(CTFResponse.OK, fixture.readNextEvent());
- }
-
- /**
- * Run the void seek(long) method test. Seek by direct timestamp
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void testSeek_timestamp() throws CTFReaderException {
- long timestamp = 1L;
- fixture.seek(timestamp);
- }
-
- /**
- * Run the seek test. Seek by passing an EventDefinition to which we've
- * given the timestamp we want.
- *
- * @throws CTFReaderException
- */
- @Test
- public void testSeek_eventDefinition() throws CTFReaderException {
- EventDefinition eventDefinition = new EventDefinition(
- new EventDeclaration(), getStreamInputReader(), 1L, null, null, null, null);
- fixture.setCurrentEvent(eventDefinition);
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.trace;
-
-import static org.junit.Assert.assertNotNull;
-
-import org.eclipse.linuxtools.internal.ctf.core.trace.StreamInputReaderTimestampComparator;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * The class <code>StreamInputReaderTimestampComparatorTest</code> contains
- * tests for the class <code>{@link StreamInputReaderTimestampComparator}</code>
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-public class CTFStreamInputReaderTimestampComparatorTest {
-
- private StreamInputReaderTimestampComparator fixture;
-
- /**
- * Perform pre-test initialization.
- */
- @Before
- public void setUp() {
- fixture = new StreamInputReaderTimestampComparator();
- }
-
- /**
- * Run the StreamInputReaderTimestampComparator() constructor test.
- */
- @Test
- public void testStreamInputReaderTimestampComparator_1() {
- assertNotNull(fixture);
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.trace;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assume.assumeTrue;
-
-import java.io.File;
-import java.io.FilenameFilter;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.types.IDefinition;
-import org.eclipse.linuxtools.ctf.core.tests.shared.CtfTestTrace;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.ctf.core.trace.CTFStream;
-import org.eclipse.linuxtools.ctf.core.trace.CTFStreamInput;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * The class <code>StreamInputTest</code> contains tests for the class
- * <code>{@link CTFStreamInput}</code>.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-@SuppressWarnings("javadoc")
-public class CTFStreamInputTest {
-
- private static final CtfTestTrace testTrace = CtfTestTrace.KERNEL;
-
- private CTFStreamInput fixture;
-
- /**
- * Perform pre-test initialization.
- *
- * @throws CTFReaderException
- */
- @Before
- public void setUp() throws CTFReaderException {
- assumeTrue(testTrace.exists());
- fixture = new CTFStreamInput(new CTFStream(testTrace.getTrace()), createFile());
- fixture.setTimestampEnd(1L);
- }
-
- @NonNull
- private static File createFile() {
- File path = new File(testTrace.getPath());
- final File[] listFiles = path.listFiles(new FilenameFilter() {
- @Override
- public boolean accept(File dir, String name) {
- if (name.contains("hann")) {
- return true;
- }
- return false;
- }
- });
- assertNotNull(listFiles);
- final File returnFile = listFiles[0];
- assertNotNull(returnFile);
- return returnFile;
- }
-
- /**
- * Run the StreamInput(Stream,FileChannel,File) constructor test.
- */
- @Test
- public void testStreamInput() {
- assertNotNull(fixture);
- }
-
- /**
- * Run the String getFilename() method test.
- */
- @Test
- public void testGetFilename() {
- String result = fixture.getFilename();
- assertNotNull(result);
- }
-
- /**
- * Run the String getPath() method test.
- */
- @Test
- public void testGetPath() {
- String result = fixture.getScopePath().toString();
- assertNotNull(result);
- }
-
- /**
- * Run the Stream getStream() method test.
- */
- @Test
- public void testGetStream() {
- CTFStream result = fixture.getStream();
- assertNotNull(result);
- }
-
- /**
- * Run the long getTimestampEnd() method test.
- */
- @Test
- public void testGetTimestampEnd() {
- long result = fixture.getTimestampEnd();
- assertTrue(0L < result);
- }
-
- /**
- * Run the Definition lookupDefinition(String) method test.
- */
- @Test
- public void testLookupDefinition() {
- IDefinition result = fixture.lookupDefinition("id");
- assertNull(result);
- }
-
- /**
- * Run the void setTimestampEnd(long) method test.
- */
- @Test
- public void testSetTimestampEnd() {
- fixture.setTimestampEnd(1L);
- assertEquals(fixture.getTimestampEnd(), 1L);
- }
-
- CTFStreamInput s1;
- CTFStreamInput s2;
-
- @Test
- public void testEquals1() throws CTFReaderException {
- s1 = new CTFStreamInput(new CTFStream(testTrace.getTrace()),
- createFile());
- assertFalse(s1.equals(null));
- }
-
- @Test
- public void testEquals2() throws CTFReaderException {
- s1 = new CTFStreamInput(new CTFStream(testTrace.getTrace()),
- createFile());
- assertFalse(s1.equals(new Long(23L)));
-
- }
-
- @Test
- public void testEquals3() throws CTFReaderException {
- s1 = new CTFStreamInput(new CTFStream(testTrace.getTrace()),
- createFile());
- assertEquals(s1, s1);
-
- }
-
- @Test
- public void testEquals4() throws CTFReaderException {
- s1 = new CTFStreamInput(new CTFStream(testTrace.getTrace()),
- createFile());
- s2 = new CTFStreamInput(new CTFStream(testTrace.getTrace()),
- createFile());
- assertEquals(s1, s2);
- }
-}
\ No newline at end of file
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.trace;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assume.assumeTrue;
-
-import java.io.File;
-import java.io.FilenameFilter;
-import java.io.IOException;
-import java.util.Set;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.types.IDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-import org.eclipse.linuxtools.ctf.core.tests.shared.CtfTestTrace;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.ctf.core.trace.CTFStream;
-import org.eclipse.linuxtools.ctf.core.trace.CTFStreamInput;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTrace;
-import org.eclipse.linuxtools.internal.ctf.core.event.EventDeclaration;
-import org.eclipse.linuxtools.internal.ctf.core.event.metadata.exceptions.ParseException;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-/**
- * The class <code>StreamTest</code> contains tests for the class
- * <code>{@link CTFStream}</code>.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-@SuppressWarnings("javadoc")
-public class CTFStreamTest {
-
- private static final CtfTestTrace testTrace = CtfTestTrace.KERNEL;
-
- private CTFStream fixture;
-
- private CTFStreamInput fInput;
-
- @BeforeClass
- public static void initialize() {
- assumeTrue(testTrace.exists());
- }
-
- /**
- * Perform pre-test initialization.
- *
- * @throws CTFReaderException
- */
- @Before
- public void setUp() throws CTFReaderException {
- fixture = new CTFStream(testTrace.getTrace());
- fixture.setEventContext(new StructDeclaration(1L));
- fixture.setPacketContext(new StructDeclaration(1L));
- fixture.setEventHeader(new StructDeclaration(1L));
- fixture.setId(1L);
- fInput = new CTFStreamInput(new CTFStream(testTrace.getTrace()), createFile());
- fixture.addInput(fInput);
- }
-
- @After
- public void tearDown() throws IOException {
- fInput.close();
- }
-
- @NonNull
- private static File createFile() {
- File path = new File(testTrace.getPath());
- final File[] listFiles = path.listFiles(new FilenameFilter() {
- @Override
- public boolean accept(File dir, String name) {
- if (name.contains("hann")) {
- return true;
- }
- return false;
- }
- });
- assertNotNull(listFiles);
- final File returnFile = listFiles[0];
- assertNotNull(returnFile);
- return returnFile;
- }
-
- /**
- * Run the Stream(CTFTrace) constructor test.
- *
- * @throws CTFReaderException
- */
- @Test
- public void testStream() throws CTFReaderException {
- try (CTFTrace trace = testTrace.getTrace()) {
- CTFStream result = new CTFStream(trace);
- assertNotNull(result);
- }
- }
-
- /**
- * Run the void addEvent(EventDeclaration) method test with the basic event.
- *
- * @throws ParseException
- */
- @Test
- public void testAddEvent_base() throws ParseException {
- EventDeclaration event = new EventDeclaration();
- fixture.addEvent(event);
- }
-
- /**
- * Run the boolean eventContextIsSet() method test.
- */
- @Test
- public void testEventContextIsSet() {
- assertTrue(fixture.isEventContextSet());
- }
-
- /**
- * Run the boolean eventContextIsSet() method test.
- */
- @Test
- public void testToString() {
- assertNotNull(fixture.toString());
- }
-
- /**
- * Run the boolean eventHeaderIsSet() method test.
- */
- @Test
- public void testEventHeaderIsSet() {
- assertTrue(fixture.isEventHeaderSet());
- }
-
- /**
- * Run the StructDeclaration getEventContextDecl() method test.
- */
- @Test
- public void testGetEventContextDecl() {
- assertNotNull(fixture.getEventContextDecl());
- }
-
- /**
- * Run the StructDeclaration getEventHeaderDecl() method test.
- */
- @Test
- public void testGetEventHeaderDecl() {
- IDeclaration eventHeaderDecl = fixture.getEventHeaderDeclaration();
- assertNotNull(eventHeaderDecl);
- }
-
- /**
- * Run the HashMap<Long, EventDeclaration> getEvents() method test.
- */
- @Test
- public void testGetEvents() {
- assertNotNull(fixture.getEventDeclarations());
- }
-
- /**
- * Run the Long getId() method test.
- */
- @Test
- public void testGetId() {
- Long result = fixture.getId();
- assertNotNull(result);
- }
-
- /**
- * Run the StructDeclaration getPacketContextDecl() method test.
- */
- @Test
- public void testGetPacketContextDecl() {
- StructDeclaration result = fixture.getPacketContextDecl();
- assertNotNull(result);
- }
-
- /**
- * Run the Set<StreamInput> getStreamInputs() method test.
- */
- @Test
- public void testGetStreamInputs() {
- Set<CTFStreamInput> result = fixture.getStreamInputs();
- assertNotNull(result);
- }
-
- /**
- * Run the CTFTrace getTrace() method test.
- */
- @Test
- public void testGetTrace() {
- try (CTFTrace result = fixture.getTrace();) {
- assertNotNull(result);
- }
- }
-
- /**
- * Run the boolean idIsSet() method test.
- */
- @Test
- public void testIdIsSet() {
- boolean result = fixture.isIdSet();
- assertTrue(result);
- }
-
- /**
- * Run the boolean packetContextIsSet() method test.
- */
- @Test
- public void testPacketContextIsSet() {
- boolean result = fixture.isPacketContextSet();
- assertTrue(result);
- }
-
- /**
- * Run the void setEventContext(StructDeclaration) method test.
- */
- @Test
- public void testSetEventContext() {
- StructDeclaration eventContext = new StructDeclaration(1L);
- fixture.setEventContext(eventContext);
- }
-
- /**
- * Run the void setEventHeader(StructDeclaration) method test.
- */
- @Test
- public void testSetEventHeader() {
- StructDeclaration eventHeader = new StructDeclaration(1L);
- fixture.setEventHeader(eventHeader);
- }
-
- /**
- * Run the void setId(long) method test.
- */
- @Test
- public void testSetId() {
- long id = 1L;
- fixture.setId(id);
- }
-
- /**
- * Run the void setPacketContext(StructDeclaration) method test.
- */
- @Test
- public void testSetPacketContext() {
- StructDeclaration packetContext = new StructDeclaration(1L);
- fixture.setPacketContext(packetContext);
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.trace;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assume.assumeTrue;
-
-import java.util.Random;
-import java.util.TreeSet;
-
-import org.eclipse.linuxtools.ctf.core.event.CTFCallsite;
-import org.eclipse.linuxtools.ctf.core.tests.shared.CtfTestTrace;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTrace;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * Test the performance of the callsite storage in the CTF trace.
- *
- * @author Matthew Khouzam
- */
-public class CTFTraceCallsitePerformanceTest {
-
- private static final CtfTestTrace testTrace = CtfTestTrace.KERNEL;
-
- private static final int NUMBER_OF_SEEKS = 100000;
-
- private final String[] callsites = { "Alligator", "Bunny", "Cat",
- "Dolphin", "Echidna", "Gazelle", "Heron", "Ibex", "Jackalope",
- "Koala", "Lynx", "Meerkat", "Narwhal", "Ocelot", "Pangolin",
- "Quetzal", "Ringtail", "Sandpiper", "Tiger", "Urchin", "Vulture",
- "Walrus", "X-Ray Tetra", "Zonkey" };
-
- private final String[] functions = { "sentence", "together", "children",
- "mountain", "chipmunk", "crashing", "drinking", "insisted",
- "insulted", "invented", "squinted", "standing", "swishing",
- "talented", "whiplash", "complain", "granddad", "sprinkle",
- "surprise", "umbrella", "anything", "anywhere", "baseball",
- "birthday", "bluebird", "cheerful", "colorful", "daylight",
- "doghouse", "driveway", "everyone" };
-
- private final String[] files = { "Adult.java", "Aeroplane.java",
- "Air.java", "Airforce.java", "Airport.java", "Album.java",
- "Alphabet.java", "Apple.java", "Arm.java", "Army.java", "Babby.java" };
-
- Random rnd = new Random();
- CTFTrace fTrace = null;
-
- /**
- * main, launches the tests.
- * @param args not read
- */
- public static void main(String[] args) {
- new org.junit.runner.JUnitCore().run(CTFTraceCallsitePerformanceTest.class);
- }
-
-
- /**
- * sets up the test by making a new trace.
- * @throws CTFReaderException an exception from the reader
- * @throws SecurityException an exception from accessing files illegally
- * @throws IllegalArgumentException an exception for passing bad values
- */
- @Before
- public void setup() throws CTFReaderException, SecurityException,
- IllegalArgumentException {
- assumeTrue(testTrace.exists());
- fTrace = new CTFTrace(testTrace.getPath());
- }
-
- private void addCallsites(int numCallsites) {
- long stepSize = (Long.MAX_VALUE / (numCallsites + 1));
- int jitter = (int) Math.min(stepSize, Integer.MAX_VALUE);
- for (int i = 0; i < numCallsites; i++) {
- final long ip = ((i)) * stepSize + rnd.nextInt(jitter);
- fTrace.addCallsite(getRandomElement(callsites),
- getRandomElement(functions), ip, getRandomElement(files),
- (ip / 1000000) * 100);
- }
- }
-
- private String getRandomElement(String[] array) {
- return array[rnd.nextInt(array.length)];
- }
-
- private long testMain() {
- TreeSet<CTFCallsite> l = fTrace.getCallsiteCandidates(callsites[0]);
- CTFCallsite cs = fTrace.getCallsite(1);
- CTFCallsite cs1 = fTrace.getCallsite(callsites[0]);
- CTFCallsite cs2 = fTrace.getCallsite(callsites[0], 1);
- assertNotNull(l);
- assertNotNull(cs);
- assertNotNull(cs1);
- assertNotNull(cs2);
- /* performance test */
- long start = System.nanoTime();
- perfTest();
- long end = System.nanoTime();
- long diff = end - start;
- assertTrue(diff > 0);
- return diff;
- }
-
- /**
- * @param callsiteSize
- */
- private void test(int callsiteSize) {
- addCallsites(callsiteSize);
- long ns = testMain();
- System.out.println( "perf ( " + callsiteSize + ", " + ns + ")");
- }
-
- private void perfTest() {
- for (int i = 0; i < NUMBER_OF_SEEKS; i++) {
- fTrace.getCallsite((((long) rnd.nextInt()) << 16L));
- }
- }
-
- /**
- * Test seeks with 1000 callsites
- */
- @Test
- public void test1KCallsites() {
- test(1000);
- }
-
- /**
- * Test seeks with 2000 callsites
- */
- @Test
- public void test2KCallsites() {
- test(2000);
- }
-
- /**
- * Test seeks with 5000 callsites
- */
- @Test
- public void test5KCallsites() {
- test(5000);
- }
-
- /**
- * Test seeks with 10000 callsites
- */
- @Test
- public void test10KCallsites() {
- test(10000);
- }
-
- /**
- * Test seeks with 20000 callsites
- */
- @Test
- public void test20KCallsites() {
- test(20000);
- }
-
- /**
- * Test seeks with 50000 callsites
- */
- @Test
- public void test50KCallsites() {
- test(50000);
- }
-
- /**
- * Test seeks with 100000 callsites
- */
- @Test
- public void test100KCallsites() {
- test(100000);
- }
-
- /**
- * Test seeks with 1000000 callsites
- */
- @Test
- public void test1MCallsites() {
- test(1000000);
- }
-
- /**
- * Test seeks with 2000000 callsites
- */
- @Test
- public void test2MCallsites() {
- test(2000000);
- }
-}
-
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.trace;
-
-import static org.junit.Assert.*;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.attribute.FileAttribute;
-import java.util.UUID;
-
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTrace;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTraceReader;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * Tests growing streams
- *
- * @author Matthew Khouzam
- *
- */
-public class CTFTraceGrowingStreamTest {
-
- private Path fCtfDirectory;
- private File fGrowingStream;
- private byte[][] fPackets;
- private CTFTrace fFixture;
- private UUID fUUID;
-
- /**
- * Run before every test
- *
- * @throws IOException won't happen
- * @throws CTFReaderException won't happen
- */
- @Before
- public void init() throws IOException, CTFReaderException {
- fCtfDirectory = Files.createTempDirectory("temptrace", new FileAttribute<?>[] {});
- File metadata = new File(fCtfDirectory.toString() + "/" + "metadata");
- fGrowingStream = new File(fCtfDirectory.toString() + "/" + "stream");
- fUUID = UUID.randomUUID();
- fPackets = new byte[2][];
- fPackets[0] = new byte[32];
- fPackets[1] = new byte[32];
- try (PrintWriter pw = new PrintWriter(metadata)) {
- pw.println("/*CTF 1.8*/");
- pw.println("typealias integer { size = 8; align = 8; signed = false; base = 10; } := uint8_t;");
- pw.println("typealias integer { size = 32; align = 32; signed = false; base = hex; } := uint32_t;");
-
- pw.println("trace {");
- pw.println(" major = 0;");
- pw.println(" minor = 1;");
- pw.println(" uuid = \"" + fUUID.toString() + "\";");
- pw.println(" byte_order = le;");
- pw.println(" packet.header := struct {");
- pw.println(" uint32_t magic;");
- pw.println(" uint8_t uuid[16];");
- pw.println(" };");
- pw.println("};");
- pw.println("");
- pw.println("stream {");
- pw.println(" packet.context := struct {");
- pw.println(" uint32_t packet_size;");
- pw.println(" uint32_t content_size;");
- pw.println(" };");
- pw.println("};");
- pw.println("");
- pw.println("event {");
- pw.println(" name = thing;");
- pw.println(" fields := struct { uint32_t f; };");
- pw.println("};");
- pw.println("");
- pw.close();
- }
- setupPacket(fPackets[0], 41);
- setupPacket(fPackets[1], 0xbab4face);
-
- try (FileOutputStream fos = new FileOutputStream(fGrowingStream)) {
- fos.write(fPackets[0]);
- }
- fFixture = new CTFTrace(fCtfDirectory.toString());
- }
-
- private void setupPacket(byte data[], int value) {
- ByteBuffer bb = ByteBuffer.wrap(data);
- bb.clear();
- bb.order(ByteOrder.LITTLE_ENDIAN);
- bb.putInt(0xc1fc1fc1);
- bb.order(ByteOrder.BIG_ENDIAN);
- bb.putLong(fUUID.getMostSignificantBits());
- bb.putLong(fUUID.getLeastSignificantBits());
- bb.order(ByteOrder.LITTLE_ENDIAN);
- bb.putInt(256);
- bb.putInt(256);
- bb.putInt(value);
- }
-
- /**
- * Test a growing stream
- *
- * @throws CTFReaderException won't happen
- * @throws IOException won't happen
- * @throws FileNotFoundException won't happen
- */
- @Test
- public void testGrowingLive() throws CTFReaderException, FileNotFoundException, IOException {
- try (CTFTraceReader reader = new CTFTraceReader(fFixture);) {
- reader.setLive(true);
- assertEquals("0x29", reader.getCurrentEventDef().getFields().getDefinition("f").toString());
- reader.advance();
- try (FileOutputStream fos = new FileOutputStream(fGrowingStream, true)) {
- fos.write(fPackets[1]);
- }
- reader.advance();
- assertNotNull(reader.getCurrentEventDef());
- assertEquals("0xbab4face", reader.getCurrentEventDef().getFields().getDefinition("f").toString());
- }
- }
-
- /**
- * Test a growing stream
- *
- * @throws CTFReaderException won't happen
- * @throws IOException won't happen
- * @throws FileNotFoundException won't happen
- */
- @Test
- public void testGrowingNotLive() throws CTFReaderException, FileNotFoundException, IOException {
- try (CTFTraceReader reader = new CTFTraceReader(fFixture);) {
- reader.setLive(false);
- assertEquals("0x29", reader.getCurrentEventDef().getFields().getDefinition("f").toString());
- reader.advance();
- try (FileOutputStream fos = new FileOutputStream(fGrowingStream, true)) {
- fos.write(fPackets[1]);
- }
- reader.advance();
- assertNull(reader.getCurrentEventDef());
- }
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.trace;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStreamReader;
-
-import org.eclipse.linuxtools.ctf.core.event.EventDefinition;
-import org.eclipse.linuxtools.ctf.core.tests.shared.CtfTestTrace;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTrace;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTraceReader;
-import org.eclipse.linuxtools.ctf.core.trace.Metadata;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * Tests for streaming support
- *
- * @author Matthew Khouzam
- *
- */
-public class CTFTraceGrowingTest {
- final private String fPathName = CtfTestTrace.SYNTHETIC_TRACE.getPath();
-
- final private CTFTrace fixture = new CTFTrace();
-
- /**
- * Init
- *
- * @throws IOException
- * an IO error
- * @throws FileNotFoundException
- * file's not there
- * @throws CTFReaderException
- * error in metadata
- */
- @Before
- public void init() throws FileNotFoundException, IOException, CTFReaderException {
- Metadata md = new Metadata(fixture);
- File metadata = new File(fPathName + "/" + "metadata");
-
- try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(metadata)))) {
-
- StringBuilder sb = new StringBuilder();
- String line = null;
- while ((line = reader.readLine()) != null) {
- sb.append(line);
- }
- String result = sb.toString();
- md.parseText(result);
- }
- }
-
- /**
- * Empty trace test
- *
- * @throws CTFReaderException
- * will not happen
- */
- @Test
- public void testEmptyStream() throws CTFReaderException {
- try (CTFTraceReader reader = new CTFTraceReader(fixture);) {
- assertNull(reader.getCurrentEventDef());
- }
- }
-
- /**
- * Add a stream
- *
- * @throws CTFReaderException
- * should not happen
- */
- @Test
- public void testAddStream() throws CTFReaderException {
- File stream = new File(fPathName + "/" + "channel1");
- try (CTFTraceReader reader = new CTFTraceReader(fixture);) {
- fixture.addStreamFile(stream);
- reader.update();
- assertTrue(reader.advance());
- assertNotNull(reader.getCurrentEventDef());
- }
- }
-
- /**
- * Adds two a stream
- *
- * @throws CTFReaderException
- * should not happen
- */
- @Test
- public void testAddTwoStreams1() throws CTFReaderException {
- File stream = new File(fPathName + "/" + "channel1");
- try (CTFTraceReader reader = new CTFTraceReader(fixture);) {
- fixture.addStreamFile(stream);
- stream = new File(fPathName + "/" + "channel2");
- fixture.addStreamFile(stream);
- reader.update();
- assertTrue(reader.advance());
- EventDefinition currentEventDef = reader.getCurrentEventDef();
- assertNotNull(reader.getCurrentEventDef());
- assertEquals(16518l, currentEventDef.getTimestamp());
- }
- }
-
- /**
- * Adds two a stream
- *
- * @throws CTFReaderException
- * should not happen
- */
- @Test
- public void testAddTwoStreams2() throws CTFReaderException {
- File stream = new File(fPathName + "/" + "channel1");
- try (CTFTraceReader reader = new CTFTraceReader(fixture);) {
- fixture.addStreamFile(stream);
- stream = new File(fPathName + "/" + "channel2");
- reader.update();
- assertTrue(reader.advance());
- fixture.addStreamFile(stream);
- reader.update();
- assertTrue(reader.advance());
- EventDefinition currentEventDef = reader.getCurrentEventDef();
- assertNotNull(currentEventDef);
- assertEquals(223007L, currentEventDef.getTimestamp());
- }
- }
-
- /**
- * Tests that update does not change the position
- *
- * @throws CTFReaderException
- * should not happen
- */
- @Test
- public void testAddTwoStreams3() throws CTFReaderException {
- File stream = new File(fPathName + "/" + "channel1");
- try (CTFTraceReader reader = new CTFTraceReader(fixture);) {
- fixture.addStreamFile(stream);
- stream = new File(fPathName + "/" + "channel2");
- reader.update();
- reader.update();
- reader.update();
- assertTrue(reader.advance());
- fixture.addStreamFile(stream);
- reader.update();
- reader.update();
- reader.update();
- reader.update();
- assertTrue(reader.advance());
- EventDefinition currentEventDef = reader.getCurrentEventDef();
- assertNotNull(currentEventDef);
- assertEquals(223007L, currentEventDef.getTimestamp());
- }
- }
-
- /**
- * Test adding a bad stream
- *
- * @throws CTFReaderException
- * should happen
- */
- @Test(expected = CTFReaderException.class)
- public void testAddStreamFail() throws CTFReaderException {
- File stream = new File(fPathName + "/" + "metadata");
- try (CTFTraceReader reader = new CTFTraceReader(fixture);) {
- fixture.addStreamFile(stream);
- assertNull(reader.getCurrentEventDef());
- }
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.trace;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assume.assumeTrue;
-
-import org.eclipse.linuxtools.ctf.core.event.EventDefinition;
-import org.eclipse.linuxtools.ctf.core.tests.shared.CtfTestTrace;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTrace;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTraceReader;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * The class <code>CTFTraceReaderTest</code> contains tests for the class
- * <code>{@link CTFTraceReader}</code>.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-@SuppressWarnings("javadoc")
-public class CTFTraceReaderTest {
-
- private static final CtfTestTrace testTrace = CtfTestTrace.KERNEL;
-
- private CTFTraceReader fixture;
-
- /**
- * Perform pre-test initialization.
- *
- * @throws CTFReaderException
- */
- @Before
- public void setUp() throws CTFReaderException {
- assumeTrue(testTrace.exists());
- fixture = new CTFTraceReader(testTrace.getTrace());
- }
-
- /**
- * Run the CTFTraceReader(CTFTrace) constructor test. Open a known good
- * trace.
- *
- * @throws CTFReaderException
- */
- @Test
- public void testOpen_existing() throws CTFReaderException {
- try (CTFTrace trace = testTrace.getTrace();
- CTFTraceReader result = new CTFTraceReader(trace);) {
- assertNotNull(result);
- }
- }
-
- /**
- * Run the CTFTraceReader(CTFTrace) constructor test. Open a non-existing
- * trace, expect the exception.
- *
- * @throws CTFReaderException
- */
- @Test(expected = org.eclipse.linuxtools.ctf.core.trace.CTFReaderException.class)
- public void testOpen_nonexisting() throws CTFReaderException {
- try (CTFTrace trace = new CTFTrace("badfile.bad");
- CTFTraceReader result = new CTFTraceReader(trace);) {
- assertNotNull(result);
- }
- }
-
- /**
- * Run the CTFTraceReader(CTFTrace) constructor test. Try to pen an invalid
- * path, expect exception.
- *
- * @throws CTFReaderException
- */
- @Test(expected = org.eclipse.linuxtools.ctf.core.trace.CTFReaderException.class)
- public void testOpen_invalid() throws CTFReaderException {
- try (CTFTrace trace = new CTFTrace("");
- CTFTraceReader result = new CTFTraceReader(trace);) {
- assertNotNull(result);
- }
- }
-
- /**
- * Run the boolean advance() method test. Test advancing normally.
- * @throws CTFReaderException error
- */
- @Test
- public void testAdvance_normal() throws CTFReaderException {
- boolean result = fixture.advance();
- assertTrue(result);
- }
-
- /**
- * Run the boolean advance() method test. Test advancing when we're at the
- * end, so we expect that there is no more events.
- * @throws CTFReaderException error
- */
- @Test
- public void testAdvance_end() throws CTFReaderException {
- int i = 0;
- boolean result = fixture.advance();
- while (result) {
- result = fixture.advance();
- i++;
- }
- fixture.seek(0);
- fixture.advance();
- fixture.goToLastEvent();
- i = 1;
- result = fixture.advance();
- while (result) {
- result = fixture.advance();
- i++;
- }
- assertFalse(result);
- assertEquals(i, 1);
- }
-
- /**
- * Run the CTFTraceReader copy constructor test.
- * @throws CTFReaderException error
- */
- @Test
- public void testCopyFrom() throws CTFReaderException {
- try (CTFTraceReader result = fixture.copyFrom();) {
- assertNotNull(result);
- }
- }
-
- /**
- * Test the hashCode method.
- */
- @Test
- public void testHash() {
- int result = fixture.hashCode();
- assertTrue(0 != result);
- }
-
- /**
- * Test the equals method. Uses the class-wide 'fixture' and another
- * method-local 'fixture2', which both point to the same trace.
- *
- * Both trace reader are different objects, so they shouldn't "equals" each
- * other.
- *
- * @throws CTFReaderException
- */
- @Test
- public void testEquals() throws CTFReaderException {
- try (CTFTraceReader fixture2 = new CTFTraceReader(testTrace.getTrace());) {
- assertEquals(fixture, fixture2);
- }
- }
-
- /**
- * Run the getCurrentEventDef() method test. Get the first event's
- * definition.
- */
- @Test
- public void testGetCurrentEventDef_first() {
- EventDefinition result = fixture.getCurrentEventDef();
- assertNotNull(result);
- }
-
- /**
- * Run the getCurrentEventDef() method test. Get the last event's
- * definition.
- * @throws CTFReaderException error
- */
- @Test
- public void testGetCurrentEventDef_last() throws CTFReaderException {
- fixture.goToLastEvent();
- EventDefinition result = fixture.getCurrentEventDef();
- assertNotNull(result);
- }
-
- /**
- * Run the long getEndTime() method test.
- */
- @Test
- public void testGetEndTime() {
- long result = fixture.getEndTime();
- assertTrue(0L < result);
- }
-
- /**
- * Run the long getStartTime() method test.
- */
- @Test
- public void testGetStartTime() {
- long result = fixture.getStartTime();
- assertTrue(0L < result);
- }
-
- /**
- * Run the void goToLastEvent() method test.
- * @throws CTFReaderException error
- */
- @Test
- public void testGoToLastEvent() throws CTFReaderException {
- fixture.goToLastEvent();
- long ts1 = getTimestamp();
- long ts2 = fixture.getEndTime();
- assertEquals(ts1, ts2);
- }
-
- /**
- * Run the boolean hasMoreEvents() method test.
- *
- * @throws CTFReaderException
- */
- @Test
- public void testHasMoreEvents() {
- boolean result = fixture.hasMoreEvents();
- assertTrue(result);
- }
-
- /**
- * Run the void printStats() method test with no 'width' parameter.
- * @throws CTFReaderException error
- */
- @Test
- public void testPrintStats_noparam() throws CTFReaderException {
- fixture.advance();
- fixture.printStats();
- }
-
- /**
- * Run the void printStats(int) method test with width = 0.
- * @throws CTFReaderException error
- */
- @Test
- public void testPrintStats_width0() throws CTFReaderException {
- fixture.advance();
- fixture.printStats(0);
- }
-
- /**
- * Run the void printStats(int) method test with width = 1.
- * @throws CTFReaderException error
- */
- @Test
- public void testPrintStats_width1() throws CTFReaderException {
- fixture.advance();
- fixture.printStats(1);
- }
-
- /**
- * Run the void printStats(int) method test with width = 2.
- * @throws CTFReaderException error
- */
- @Test
- public void testPrintStats_width2() throws CTFReaderException {
- fixture.advance();
- fixture.printStats(2);
- }
-
- /**
- * Run the void printStats(int) method test with width = 10.
- * @throws CTFReaderException error
- */
- @Test
- public void testPrintStats_width10() throws CTFReaderException {
- fixture.advance();
- fixture.printStats(10);
- }
-
- /**
- * Run the void printStats(int) method test with width = 100.
- * @throws CTFReaderException error
- */
- @Test
- public void testPrintStats_100() throws CTFReaderException {
- for (int i = 0; i < 1000; i++) {
- fixture.advance();
- }
- fixture.printStats(100);
- }
-
- /**
- * Run the boolean seek(long) method test.
- * @throws CTFReaderException error
- */
- @Test
- public void testSeek() throws CTFReaderException {
- long timestamp = 1L;
- boolean result = fixture.seek(timestamp);
- assertTrue(result);
- }
-
-
-
- /**
- * @return
- */
- private long getTimestamp() {
- if (fixture.getCurrentEventDef() != null) {
- return fixture.getTrace().timestampCyclesToNanos(fixture.getCurrentEventDef().getTimestamp());
- }
- return -1;
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013, 2014 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- * Marc-Andre Laperle - Test in traces directory recursively
- * Simon Delisle - Add test for getCallsite(eventName, ip)
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.trace;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.junit.Assume.assumeTrue;
-
-import java.io.File;
-import java.nio.ByteOrder;
-import java.util.UUID;
-
-import org.eclipse.linuxtools.ctf.core.event.CTFClock;
-import org.eclipse.linuxtools.ctf.core.event.types.IDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-import org.eclipse.linuxtools.ctf.core.tests.shared.CtfTestTrace;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTrace;
-import org.eclipse.linuxtools.ctf.core.trace.CTFStream;
-import org.eclipse.linuxtools.internal.ctf.core.event.metadata.exceptions.ParseException;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * The class <code>CTFTraceTest</code> contains tests for the class
- * <code>{@link CTFTrace}</code>.
- *
- * @author ematkho
- */
-public class CTFTraceTest {
-
- private static final CtfTestTrace testTrace = CtfTestTrace.KERNEL;
-
- private CTFTrace fixture;
-
- /**
- * Perform pre-test initialization.
- */
- @Before
- public void setUp() {
- assumeTrue(testTrace.exists());
- try {
- fixture = testTrace.getTraceFromFile();
- } catch (CTFReaderException e) {
- /* If the assumeTrue() call passed, this should not happen. */
- fail();
- }
- fixture.setMinor(1L);
- fixture.setUUID(UUID.randomUUID());
- fixture.setPacketHeader(new StructDeclaration(1L));
- fixture.setMajor(1L);
- fixture.setByteOrder(ByteOrder.BIG_ENDIAN);
- }
-
- /**
- * Run the CTFTrace(File) constructor test with a known existing trace.
- */
- @Test
- public void testOpen_existing() {
- try (CTFTrace result = testTrace.getTraceFromFile();) {
- assertNotNull(result.getUUID());
- } catch (CTFReaderException e) {
- fail();
- }
- }
-
- /**
- * Run the CTFTrace(File) constructor test with an invalid path.
- *
- * @throws CTFReaderException
- * is expected
- */
- @Test(expected = org.eclipse.linuxtools.ctf.core.trace.CTFReaderException.class)
- public void testOpen_invalid() throws CTFReaderException {
- File path = new File("");
- try (CTFTrace result = new CTFTrace(path);) {
- assertNotNull(result);
- }
- }
-
- /**
- * Run the boolean UUIDIsSet() method test.
- */
- @Test
- public void testUUIDIsSet() {
- boolean result = fixture.uuidIsSet();
- assertTrue(result);
- }
-
- /**
- * Run the void addStream(Stream) method test.
- */
- @Test
- public void testAddStream() {
- // test number of streams
- int nbStreams = fixture.nbStreams();
- assertEquals(1, nbStreams);
-
- // Add a stream
- try {
- CTFStream stream = new CTFStream(testTrace.getTrace());
- stream.setId(1234);
- fixture.addStream(stream);
- } catch (CTFReaderException e) {
- fail();
- } catch (ParseException e) {
- fail();
- }
-
- // test number of streams
- nbStreams = fixture.nbStreams();
- assertEquals(2, nbStreams);
- }
-
- /**
- * Run the boolean byteOrderIsSet() method test.
- */
- @Test
- public void testByteOrderIsSet() {
- boolean result = fixture.byteOrderIsSet();
- assertTrue(result);
- }
-
- /**
- * Run the ByteOrder getByteOrder() method test.
- */
- @Test
- public void testGetByteOrder_1() {
- ByteOrder result = fixture.getByteOrder();
- assertNotNull(result);
- }
-
- /**
- * Run the long getMajor() method test.
- */
- @Test
- public void testGetMajor() {
- long result = fixture.getMajor();
- assertEquals(1L, result);
- }
-
- /**
- * Run the long getMinor() method test.
- */
- @Test
- public void testGetMinor() {
- long result = fixture.getMinor();
- assertEquals(1L, result);
- }
-
- /**
- * Run the StructDeclaration getPacketHeader() method test.
- */
- @Test
- public void testGetPacketHeader() {
- StructDeclaration result = fixture.getPacketHeader();
- assertNotNull(result);
- }
-
- /**
- * Run the String getPath() method test.
- */
- @Test
- public void testGetPath() {
- String result = fixture.getPath();
- assertNotNull(result);
- }
-
- /**
- * Run the Stream getStream(Long) method test.
- */
- @Test
- public void testGetStream() {
- Long id = new Long(0L);
- CTFStream result = fixture.getStream(id);
- assertNotNull(result);
- }
-
- /**
- * Run the File getTraceDirectory() method test.
- */
- @Test
- public void testGetTraceDirectory() {
- File result = fixture.getTraceDirectory();
- assertNotNull(result);
- }
-
- /**
- * Run the UUID getUUID() method test.
- */
- @Test
- public void testGetUUID() {
- UUID result = fixture.getUUID();
- assertNotNull(result);
- }
-
- /**
- * Run the Definition lookupDefinition(String) method test.
- */
- @Test
- public void testLookupDefinition() {
- String lookupPath = "trace.packet.header";
- IDefinition result = fixture.lookupDefinition(lookupPath);
- assertNotNull(result);
- }
-
- /**
- * Run the boolean majorIsSet() method test.
- */
- @Test
- public void testMajorIsSet() {
- boolean result = fixture.majorIsSet();
- assertTrue(result);
- }
-
- /**
- * Run the boolean minorIsSet() method test.
- */
- @Test
- public void testMinorIsSet() {
- boolean result = fixture.minorIsSet();
- assertTrue(result);
- }
-
- /**
- * Run the boolean packetHeaderIsSet() method test with a valid header set.
- */
- @Test
- public void testPacketHeaderIsSet_valid() {
- boolean result = fixture.packetHeaderIsSet();
- assertTrue(result);
- }
-
- /**
- * Run the boolean packetHeaderIsSet() method test, without having a valid
- * header set.
- */
- @Test
- public void testPacketHeaderIsSet_invalid() {
- try (CTFTrace fixture2 = testTrace.getTraceFromFile();){
- fixture2.setMinor(1L);
- fixture2.setUUID(UUID.randomUUID());
- fixture2.setPacketHeader((StructDeclaration) null); /* it's null here! */
- fixture2.setMajor(1L);
- fixture2.setByteOrder(ByteOrder.BIG_ENDIAN);
-
- boolean result = fixture2.packetHeaderIsSet();
- assertFalse(result);
- } catch (CTFReaderException e) {
- fail();
- }
- }
-
- /**
- * Run the void setByteOrder(ByteOrder) method test.
- */
- @Test
- public void testSetByteOrder() {
- ByteOrder byteOrder = ByteOrder.BIG_ENDIAN;
- fixture.setByteOrder(byteOrder);
- }
-
- /**
- * Run the void setMajor(long) method test.
- */
- @Test
- public void testSetMajor() {
- long major = 1L;
- fixture.setMajor(major);
- }
-
- /**
- * Run the void setMinor(long) method test.
- */
- @Test
- public void testSetMinor() {
- long minor = 1L;
- fixture.setMinor(minor);
- }
-
- /**
- * Run the void setPacketHeader(StructDeclaration) method test.
- */
- @Test
- public void testSetPacketHeader() {
- StructDeclaration packetHeader = new StructDeclaration(1L);
- fixture.setPacketHeader(packetHeader);
- }
-
- /**
- * Run the void setUUID(UUID) method test.
- */
- @Test
- public void testSetUUID() {
- UUID uuid = UUID.randomUUID();
- fixture.setUUID(uuid);
- }
-
- /**
- * Run the CTFClock getClock/setClock method test.
- */
- @Test
- public void testGetSetClock_1() {
- String name = "clockyClock";
- fixture.addClock(name, new CTFClock());
- CTFClock result = fixture.getClock(name);
-
- assertNotNull(result);
- }
-
- /**
- * Run the CTFClock getClock/setClock method test.
- */
- @Test
- public void testGetSetClock_2() {
- String name = "";
- CTFClock ctfClock = new CTFClock();
- ctfClock.addAttribute("name", "Bob");
- ctfClock.addAttribute("pi", new Double(java.lang.Math.PI));
- fixture.addClock(name, ctfClock);
- CTFClock result = fixture.getClock(name);
-
- assertNotNull(result);
- assertTrue((Double) ctfClock.getProperty("pi") > 3.0);
- assertTrue(ctfClock.getName().equals("Bob"));
- }
-
- /**
- * Run the String lookupEnvironment(String) method test.
- */
- @Test
- public void testLookupEnvironment_1() {
- String key = "";
- String result = fixture.getEnvironment().get(key);
- assertNull(result);
- }
-
- /**
- * Run the String lookupEnvironment(String) method test.
- */
- @Test
- public void testLookupEnvironment_2() {
- String key = "otherTest";
- String result = fixture.getEnvironment().get(key);
- assertNull(result);
- }
-
- /**
- * Run the String lookupEnvironment(String) method test.
- */
- @Test
- public void testLookupEnvironment_3() {
- String key = "test";
- fixture.addEnvironmentVar(key, key);
- String result = fixture.getEnvironment().get(key);
- assertTrue(result.equals(key));
- }
-
- /**
- * Run the String lookupEnvironment(String) method test.
- */
- @Test
- public void testLookupEnvironment_4() {
- String key = "test";
- fixture.addEnvironmentVar(key, "bozo");
- fixture.addEnvironmentVar(key, "the clown");
- String result = fixture.getEnvironment().get(key);
- assertNotNull(result);
- }
-
- /**
- * Test for getCallsite(eventName, ip)
- * @throws CTFReaderException not expected
- */
- @Test
- public void callsitePosition() throws CTFReaderException {
- long ip1 = 2;
- long ip2 = 5;
- long ip3 = 7;
- try (CTFTrace callsiteTest = testTrace.getTraceFromFile()) {
- callsiteTest.addCallsite("testEvent", null, ip1, null, 23);
- callsiteTest.addCallsite("testEvent", null, ip2, null, 50);
- callsiteTest.addCallsite("testEvent", null, ip3, null, 15);
-
- assertEquals(2, (callsiteTest.getCallsite("testEvent", 1)).getIp());
- assertEquals(2, (callsiteTest.getCallsite("testEvent", 2)).getIp());
- assertEquals(5, (callsiteTest.getCallsite("testEvent", 3)).getIp());
- assertEquals(5, (callsiteTest.getCallsite("testEvent", 5)).getIp());
- assertEquals(7, (callsiteTest.getCallsite("testEvent", 6)).getIp());
- assertEquals(7, (callsiteTest.getCallsite("testEvent", 7)).getIp());
- assertEquals(7, (callsiteTest.getCallsite("testEvent", 8)).getIp());
- }
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013, 2014 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- * Simon Delisle - Generate dummy trace
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.trace;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.linuxtools.ctf.core.event.IEventDeclaration;
-import org.eclipse.linuxtools.ctf.core.tests.CtfCoreTestPlugin;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTrace;
-import org.eclipse.linuxtools.internal.ctf.core.event.EventDeclaration;
-import org.eclipse.linuxtools.internal.ctf.core.event.metadata.IOStructGen;
-import org.junit.After;
-import org.junit.Test;
-
-/**
- * Unit tests for {@link IOStructGen}
- *
- * @author Matthew Khouzam
- */
-public class IOstructgenTest {
-
- private static final String metadataDecs = "typealias integer { size = 8; align = 8; signed = false; } := uint8_t;\n"
- + "typealias integer { size = 16; align = 8; signed = false; } := uint16_t;\n"
- + "typealias integer { size = 32; align = 8; signed = false; } := uint32_t;\n"
- + "typealias integer { size = 64; align = 8; signed = false; } := uint64_t;\n"
- + "typealias integer { size = 64; align = 8; signed = false; } := unsigned long;\n"
- + "typealias integer { size = 5; align = 1; signed = false; } := uint5_t;\n"
- + "typealias integer { size = 27; align = 1; signed = false; } := uint27_t;\n"
- + "typealias integer { size = 32; align = 1; signed = true; base = decimal; } := int32_t;\n"
- + "typealias integer { size = 31; align = 1; signed = true; base = dec; } := int31_t;\n"
- + "typealias integer { size = 30; align = 1; signed = true; base = d; } := int30_t;\n"
- + "typealias integer { size = 29; align = 1; signed = true; base = i; } := int29_t;\n"
- + "typealias integer { size = 28; align = 1; signed = true; base = u; } := int28_t;\n"
- + "typealias integer { size = 27; align = 1; signed = true; base = hexadecimal; } := int27_t;\n"
- + "typealias integer { size = 26; align = 1; signed = true; base = hex; } := int26_t;\n"
- + "typealias integer { size = 25; align = 1; signed = true; base = x; } := int25_t;\n"
- + "typealias integer { size = 24; align = 1; signed = true; base = X; } := int24_t;\n"
- + "typealias integer { size = 23; align = 1; signed = true; base = p; } := int23_t;\n"
- + "typealias integer { size = 22; align = 1; signed = true; base = 16; } := int22_t;\n"
- + "typealias integer { size = 21; align = 1; signed = true; base = oct; } := int21_t;\n"
- + "typealias integer { size = 20; align = 1; signed = true; base = b; } := int20_t;\n"
- + "typealias integer { size = 19; align = 1; signed = true; base = octal; } := int19_t;\n"
- + "typealias integer { size = 18; align = 1; signed = true; base = o; } := int18_t;\n"
- + "typealias integer { size = 17; align = 1; signed = true; base = binary; } := int17_t;\n"
- + "\n"
- + "trace {\n"
- + " major = 1;\n"
- + " minor = 8;\n"
- + " uuid = \"b04d391b-e736-44c1-8d89-4bb438857f8d\";\n"
- + " byte_order = le;\n"
- + " packet.header := struct {\n"
- + " uint32_t magic;\n"
- + " uint8_t uuid[16];\n"
- + " uint32_t stream_id;\n" + " };\n" + "};\n" + "\n";
- private static final String environmentMD = "env {\n"
- + " hostname = \"DemoSystem\";\n"
- + " vpid = 1337;\n"
- + " procname = \"demo\";\n"
- + " domain = \"autogenerated\";\n"
- + " tracer_name = \"tmf\";\n"
- + " tracer_major = 2;\n"
- + " tracer_minor = 0x01;\n"
- + " tracer_patchlevel = 0;\n"
- + "};\n" + "\n";
- private static final String clockMD = "clock {\n" + " name = monotonic;\n"
- + " uuid = \"cbf9f42e-9be7-4798-a96f-11db556e2ebb\";\n"
- + " description = \"Monotonic Clock\";\n"
- + " freq = 1000000000; /* Frequency, in Hz */\n"
- + " /* clock value offset from Epoch is: offset * (1/freq) */\n"
- + " offset = 1350310657466295832;\n" + "};\n"
- + "\n";
-
- private static final String ctfStart =
- "typealias integer {\n"
- + " size = 27; align = 1; signed = false;\n"
- + " map = clock.monotonic.value;\n"
- + "} := uint27_clock_monotonic_t;\n"
- + "\n"
- + "typealias integer {\n"
- + " size = 32; align = 8; signed = false;\n"
- + " map = clock.monotonic.value;\n"
- + "} := uint32_clock_monotonic_t;\n"
- + "\n"
- + "typealias integer {\n"
- + " size = 64; align = 8; signed = false;\n"
- + " map = clock.monotonic.value;\n"
- + "} := uint64_clock_monotonic_t;\n"
- + "\n";
-
- private static final String ctfHeaders =
- "struct packet_context {\n"
- + " uint64_clock_monotonic_t timestamp_begin;\n"
- + " uint64_clock_monotonic_t timestamp_end;\n"
- + " uint64_t content_size;\n"
- + " uint64_t packet_size;\n"
- + " unsigned long events_discarded;\n"
- + " uint32_t cpu_id;\n"
- + "};\n"
- + "\n"
- + "struct event_header_compact {\n"
- + " enum : uint5_t { compact = 0 ... 30, extended = 31 } id;\n"
- + " variant <id> {\n"
- + " struct {\n"
- + " uint27_clock_monotonic_t timestamp;\n"
- + " } compact;\n"
- + " struct {\n"
- + " uint32_t id;\n"
- + " uint64_clock_monotonic_t timestamp;\n"
- + " } extended;\n"
- + " } v;\n"
- + "} align(8);\n"
- + "\n"
- + "struct event_header_large {\n"
- + " enum : uint16_t { compact = 0 ... 65534, extended = 65535 } id;\n"
- + " variant <id> {\n" + " struct {\n"
- + " uint32_clock_monotonic_t timestamp;\n"
- + " } compact;\n" + " struct {\n"
- + " uint32_t id;\n"
- + " uint64_clock_monotonic_t timestamp;\n"
- + " } extended;\n" + " } v;\n" + "} align(8);\n" + "\n";
-
- private static final String ctfBody = "stream {\n"
- + " id = 0;\n"
- + " event.header := struct event_header_compact;\n"
- + " packet.context := struct packet_context;\n"
- + " event.context := struct {\n"
- + " integer { size = 64; align = 8; signed = 0; encoding = none; base = 16; } _ip;\n"
- + " };\n"
- + "};\n"
- + "\n"
- + "event {\n"
- + " name = \"ust_tests_demo3:done\";\n"
- + " id = 0;\n"
- + " stream_id = 0;\n"
- + " loglevel = 4;\n"
- + " fields := struct {\n"
- + " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _value;\n"
- + " };\n"
- + "};\n"
- + "\n"
- + "event {\n"
- + " name = \"ust_tests_demo:starting\";\n"
- + " id = 1;\n"
- + " stream_id = 0;\n"
- + " loglevel = 2;\n"
- + " model.emf.uri = \"http://example.com/path_to_model?q=ust_tests_demo:starting\";\n"
- + " fields := struct {\n"
- + " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _value;\n"
- + " };\n"
- + "};\n"
- + "\n"
- + "event {\n"
- + " name = \"ust_tests_demo:done\";\n"
- + " id = 2;\n"
- + " stream_id = 0;\n"
- + " loglevel = 2;\n"
- + " model.emf.uri = \"http://example.com/path_to_model?q=ust_tests_demo:done\";\n"
- + " fields := struct {\n"
- + " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _value;\n"
- + " };\n"
- + "};\n"
- + "\n"
- + "event {\n"
- + " name = \"ust_tests_demo2:loop\";\n"
- + " id = 3;\n"
- + " stream_id = 0;\n"
- + " loglevel = 4;\n"
- + " fields := struct {\n"
- + " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _intfield;\n"
- + " integer { size = 32; align = 8; signed = 1; encoding = none; base = 16; } _intfield2;\n"
- + " integer { size = 64; align = 8; signed = 1; encoding = none; base = 10; } _longfield;\n"
- + " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; byte_order = be; } _netintfield;\n"
- + " integer { size = 32; align = 8; signed = 1; encoding = none; base = 16; byte_order = be; } _netintfieldhex;\n"
- + " integer { size = 64; align = 8; signed = 1; encoding = none; base = 10; } _arrfield1[3];\n"
- + " integer { size = 8; align = 8; signed = 1; encoding = UTF8; base = 10; } _arrfield2[10];\n"
- + " integer { size = 64; align = 8; signed = 0; encoding = none; base = 10; } __seqfield1_length;\n"
- + " integer { size = 8; align = 8; signed = 1; encoding = none; base = 10; } _seqfield1[ __seqfield1_length ];\n"
- + " integer { size = 64; align = 8; signed = 0; encoding = none; base = 10; } __seqfield2_length;\n"
- + " integer { size = 8; align = 8; signed = 1; encoding = UTF8; base = 10; } _seqfield2[ __seqfield2_length ];\n"
- + " string _stringfield;\n"
- + " floating_point { exp_dig = 8; mant_dig = 24; align = 8; } _floatfield;\n"
- + " floating_point { exp_dig = 11; mant_dig = 53; align = 8; } _doublefield;\n"
- + " };\n"
- + "};\n"
- + "\n";
-
- private static final String enumMd =
- "typealias integer { size = 32; align = 8; signed = false; } := int;\n"
- + "typealias enum { ONE = 0, a,b,c=10, d} := useless_enum;\n"
- + "struct useless{ \n"
- + " enum : uint8_t { A=0, \"B\",} enum3;\n"
- + " useless_enum enum2;"
- + " enum { C, D, E } enum4;\n"
- + " uint16_t val;\n"
- + "} ;\n"
- + "\n"
- + "event {\n"
- + " name = \"enumEvent\";\n"
- + " id = 6;\n"
- + " stream_id = 0;\n"
- + " loglevel = 5;\n"
- + " fields := struct{\n"
- + " uint16_t _some_field;\n"
- // + " useless junk;\n"
- // + " bad_enum a;\n"
- + " enum {A, B, C = 3 , } _other_enum;\n"
- + " };\n"
- + "};\n"
- + "\n";
-
- private final static String contextMD =
- "event {\n" +
- " name = \"someOtherEvent\";\n" +
- " id = 5;\n" +
- " stream_id = 0;\n" +
- " loglevel = 5;\n" +
- " context := struct{\n" +
- " uint16_t _someContext;\n" +
- " };\n" +
- " fields := struct{\n" +
- " uint16_t _somefield;\n" +
- " };\n" +
- "};\n " +
- "\n";
-
- private static final String callsiteMD =
- "callsite {\n"
- + " name = \"ust_tests_demo2:loop\";\n"
- + " func = \"main\";\n" + " ip = 0x400a29;\n"
- + " file = \"demo.c\";\n" + " line = 59;\n" + "};\n" + "\n"
- + "callsite {\n" + " name = \"ust_tests_demo3:done\";\n"
- + " func = \"main\";\n" + " ip = 0x400a6c;\n"
- + " file = \"demo.c\";\n" + " line = 62;\n" + "};\n" + "\n"
- + "callsite {\n" + " name = \"ust_tests_demo:done\";\n"
- + " func = \"main\";\n" + " ip = 0x400aaf;\n"
- + " file = \"demo.c\";\n" + " line = 61;\n" + "};\n" + "\n"
- + "callsite {\n" + " name = \"ust_tests_demo:starting\";\n"
- + " func = \"main\";\n" + " ip = 0x400af2;\n"
- + " file = \"demo.c\";\n" + " line = 55;\n" + "};\n";
-
- private static final String simpleTSDL = metadataDecs + ctfStart + ctfHeaders
- + ctfBody;
- private static final String enumTSDL = metadataDecs + ctfStart + ctfHeaders
- + ctfBody + enumMd;
- private static final String clockTSDL = metadataDecs + clockMD + ctfStart
- + ctfHeaders + ctfBody;
- private static final String envTSDL = metadataDecs + environmentMD + ctfStart
- + ctfHeaders + ctfBody;
- private static final String contextTSDL = metadataDecs + environmentMD + ctfStart
- + ctfHeaders + ctfBody + contextMD;
- private static final String callsiteTSDL = metadataDecs + ctfStart + ctfHeaders
- + ctfBody + callsiteMD;
- private static final String allDressedTSDL = metadataDecs + environmentMD + clockMD
- + ctfStart + ctfHeaders + ctfBody + enumMd + callsiteMD;
-
- static final String tempTraceDir = CtfCoreTestPlugin.getTemporaryDirPath()
- + File.separator + "tempTrace";
-
- private static final int DATA_SIZE = 4096;
-
- private static final int HEADER_SIZE = 68;
-
- private static final int PACKET_SIZE = DATA_SIZE + HEADER_SIZE + 512;
-
- private CTFTrace trace;
-
- private static class Event {
- private static final int EVENT_SIZE = 16;
- private int eventId;
- private int eventTimestamp;
- private int eventContent;
-
- public Event(int id, int content) {
- eventId = id;
- eventTimestamp = 0;
- eventContent = content;
- }
-
- public void setEventTimestamp(int eventTimestamp) {
- this.eventTimestamp = eventTimestamp;
- }
-
- public void setEventContent(int eventContent) {
- this.eventContent = eventContent;
- }
-
- public void writeEvent(ByteBuffer data) {
- // Id and Timestamp
- int timeId = eventTimestamp << 5;
- timeId |= eventId & 0x1f;
- data.putInt(timeId);
-
- // Context
- long ip = 0x0000facedecafe00L + ((data.position() /
- getSize()) & 0x0F);
- data.putLong(ip);
-
- // Content
- data.putInt(eventContent);
-
- }
-
- public int getSize() {
- return EVENT_SIZE;
- }
-
- }
-
- private static void deltree(File f) {
- for (File elem : f.listFiles()) {
- if (elem.isDirectory()) {
- deltree(elem);
- }
- elem.delete();
- }
- f.delete();
- }
-
- private static void createDummyTrace(String metadata) {
- File dir = new File(tempTraceDir);
- if (dir.exists()) {
- deltree(dir);
- }
- dir.mkdirs();
-
- File metadataFile = new File(tempTraceDir + "/metadata");
- try (FileWriter fw = new FileWriter(metadataFile);) {
- fw.write(metadata);
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- byte magicLE[] = { (byte) 0xC1, (byte) 0x1F, (byte) 0xFC,
- (byte) 0xC1 };
- byte uuid[] = { (byte) 0xb0, 0x4d, 0x39, 0x1b, (byte) 0xe7,
- 0x36, 0x44, (byte) 0xc1, (byte) 0x8d, (byte) 0x89, 0x4b,
- (byte) 0xb4, 0x38, (byte) 0x85, 0x7f, (byte) 0x8d };
-
- Event ev = new Event(2, 2);
-
- final int nbEvents = (DATA_SIZE / ev.getSize()) - 1;
- final int contentSize = (nbEvents * ev.getSize() +
- HEADER_SIZE) * 8;
-
- ByteBuffer data = ByteBuffer.allocate(PACKET_SIZE);
- data.order(ByteOrder.LITTLE_ENDIAN);
- data.clear();
-
- // packet header
- // magic number 4
- data.put(magicLE);
- // uuid 16
- data.put(uuid);
- // stream ID 4
- data.putInt(0);
-
- // packet context
- // timestamp_begin 8
- data.putLong(0xa500);
-
- // timestamp_end 8
- data.putLong(nbEvents * 0x10000 + 0xa5a6);
-
- // content_size 8
- data.putLong(contentSize);
-
- // packet_size 8
- data.putLong(PACKET_SIZE * 8);
-
- // events_discarded 8
- data.putLong(0);
-
- // cpu_id 4
- data.putInt(0);
-
- // fill me
- for (int i = 0; i < nbEvents; i++) {
- ev.setEventTimestamp(i * 0x10000 + 0xa5a5);
- ev.setEventContent(i);
- ev.writeEvent(data);
- }
-
- // The byteBuffer needs to be flipped in file writing mode
- data.flip();
-
- File dummyFile = new File(tempTraceDir + "/dummyChan");
- try (FileOutputStream fos = new FileOutputStream(dummyFile);) {
- fos.getChannel().write(data);
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- }
-
- /**
- * Close trace
- */
- @After
- public void tearDown(){
- trace.close();
- }
-
- /**
- * Simple test (only the minimum)
- *
- * @throws CTFReaderException
- * something wrong happened
- */
- @Test
- public void TSDLSimpleTest() throws CTFReaderException {
- createDummyTrace(simpleTSDL);
- trace = new CTFTrace(tempTraceDir);
- assertNotNull(trace);
- }
-
- /**
- * Test with environment variables
- *
- * @throws CTFReaderException
- * something wrong happened
- */
- @Test
- public void TSDLEnvironmentTest() throws CTFReaderException {
- createDummyTrace(envTSDL);
- trace = new CTFTrace(tempTraceDir);
- assertNotNull(trace);
- }
-
- /**
- * Test with Clocks
- *
- * @throws CTFReaderException
- * something wrong happened
- */
- @Test
- public void TSDLEnumTest() throws CTFReaderException {
- createDummyTrace(enumTSDL);
- trace = new CTFTrace(tempTraceDir);
- assertNotNull(trace);
- }
-
- /**
- * Test with Clocks
- *
- * @throws CTFReaderException
- * something wrong happened
- */
- @Test
- public void TSDLClockTest() throws CTFReaderException {
- createDummyTrace(clockTSDL);
- trace = new CTFTrace(tempTraceDir);
- assertNotNull(trace);
- }
-
- /**
- * Test with Contexts
- *
- * @throws CTFReaderException
- * something wrong happened
- */
- @Test
- public void TSDLContextTest() throws CTFReaderException {
- createDummyTrace(contextTSDL);
- trace = new CTFTrace(tempTraceDir);
- assertNotNull(trace);
- }
-
- /**
- * Test with Callsites
- *
- * @throws CTFReaderException
- * something wrong happened
- */
- @Test
- public void TSDLCallsiteTest() throws CTFReaderException {
- createDummyTrace(callsiteTSDL);
- trace = new CTFTrace(tempTraceDir);
- assertNotNull(trace);
- }
-
- /**
- * Test everything
- *
- * @throws CTFReaderException
- * something wrong happened
- */
- @Test
- public void TSDLAllTest() throws CTFReaderException {
- createDummyTrace(allDressedTSDL);
- trace = new CTFTrace(tempTraceDir);
- assertNotNull(trace);
-
- final List<IEventDeclaration> eventDeclarations = new ArrayList<>(trace.getEventDeclarations(0L));
- final EventDeclaration eventDeclaration = (EventDeclaration) eventDeclarations.get(2);
- assertEquals("http://example.com/path_to_model?q=ust_tests_demo:done",
- eventDeclaration.getCustomAttribute("model.emf.uri"));
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013, 2014 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.trace;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
-import static org.junit.Assume.assumeTrue;
-
-import java.nio.ByteOrder;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.UUID;
-
-import org.eclipse.linuxtools.ctf.core.event.IEventDeclaration;
-import org.eclipse.linuxtools.ctf.core.tests.shared.CtfTestTrace;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.ctf.core.trace.CTFStream;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTrace;
-import org.eclipse.linuxtools.ctf.core.trace.Metadata;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * The class <code>MetadataTest</code> contains tests for the class
- * <code>{@link Metadata}</code>.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-@SuppressWarnings("javadoc")
-public class MetadataTest {
-
- private static final CtfTestTrace testTrace = CtfTestTrace.KERNEL;
- private static final String mdStart = "typealias integer { size = 8; align = 8; signed = false; } := uint8_t;\n" +
- " typealias integer { size = 16; align = 8; signed = false; } := uint16_t;\n" +
- " typealias integer { size = 32; align = 8; signed = false; } := uint32_t;\n" +
- " typealias integer { size = 64; align = 8; signed = false; } := uint64_t;\n" +
- " typealias integer { size = 64; align = 8; signed = false; } := unsigned long;\n" +
- " typealias integer { size = 5; align = 1; signed = false; } := uint5_t;\n" +
- " typealias integer { size = 27; align = 1; signed = false; } := uint27_t;\n" +
- "" +
- " trace {\n" +
- " major = 1;\n" +
- " minor = 8;\n" +
- " uuid = \"8b1258ba-effb-554b-b779-fbd676746000\";\n" +
- " byte_order = le;\n" +
- " packet.header := struct {\n" +
- " uint32_t magic;\n" +
- " uint8_t uuid[16];\n" +
- " uint32_t stream_id;\n" +
- " };\n" +
- " };\n" +
- "" +
- " env {\n" +
- " hostname = \"computer\";\n" +
- " domain = \"kernel\";\n" +
- " sysname = \"BeOS\";\n" +
- " kernel_release = \"95\";\n" +
- " kernel_version = \"BeWare 95\";\n" +
- " tracer_name = \"BeOS Tracer\";\n" +
- " tracer_major = 2;\n" +
- " tracer_minor = 3;\n" +
- " tracer_patchlevel = 0;\n" +
- " };\n" +
- " clock {\n" +
- " name = monotonic;\n" +
- " uuid = \"4d737a79-e3f1-4f4d-a649-42015266baf5\";\n" +
- " description = \"Monotonic Clock\";\n" +
- " freq = 1000000000; /* Frequency, in Hz */\n" +
- " /* clock value offset from Epoch is: offset * (1/freq) */\n" +
- " offset = 1383600210829415521;\n" +
- " };\n" +
-
- " typealias integer {\n" +
- "size = 27; align = 1; signed = false;\n" +
- " map = clock.monotonic.value;\n" +
- " } := uint27_clock_monotonic_t;\n" +
- " \n" +
- " typealias integer {\n" +
- " size = 32; align = 8; signed = false;\n" +
- " map = clock.monotonic.value;\n" +
- " } := uint32_clock_monotonic_t;\n" +
- " \n" +
- " typealias integer {\n" +
- " size = 64; align = 8; signed = false;\n" +
- " map = clock.monotonic.value;\n" +
- " } := uint64_clock_monotonic_t;\n" +
- " \n" +
- " struct packet_context {\n" +
- " uint64_clock_monotonic_t timestamp_begin;\n" +
- " uint64_clock_monotonic_t timestamp_end;\n" +
- " uint64_t content_size;\n" +
- " uint64_t packet_size;\n" +
- " unsigned long events_discarded;\n" +
- " uint32_t cpu_id;\n" +
- " };\n" +
- " \n" +
- " struct event_header_compact {\n" +
- " enum : uint5_t { compact = 0 ... 30, extended = 31 } id;\n" +
- " variant <id> {\n" +
- " struct {\n" +
- " uint27_clock_monotonic_t timestamp;\n" +
- " } compact;\n" +
- " struct {\n" +
- " uint32_t id;\n" +
- " uint64_clock_monotonic_t timestamp;\n" +
- " } extended;\n" +
- " } v;\n" +
- " } align(8);\n" +
- " \n" +
- " struct event_header_large {\n" +
- " enum : uint16_t { compact = 0 ... 65534, extended = 65535 } id;\n" +
- " variant <id> {\n" +
- " struct {\n" +
- " uint32_clock_monotonic_t timestamp;\n" +
- " } compact;\n" +
- " struct {\n" +
- " uint32_t id;\n" +
- " uint64_clock_monotonic_t timestamp;\n" +
- " } extended;\n" +
- " } v;\n" +
- " } align(8);\n" +
- " \n" +
- " stream {\n" +
- " id = 0;\n" +
- " event.header := struct event_header_compact;\n" +
- " packet.context := struct packet_context;\n" +
- " };\n" +
- " \n" +
- " event {\n" +
- " name = sched_switch;\n" +
- " id = 0;\n" +
- " stream_id = 0;\n" +
- " fields := struct {\n" +
- " integer { size = 8; align = 8; signed = 1; encoding = UTF8; base = 10; } _prev_comm[16];\n" +
- " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _prev_tid;\n" +
- " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _prev_prio;\n" +
- " integer { size = 64; align = 8; signed = 1; encoding = none; base = 10; } _prev_state;\n" +
- " integer { size = 8; align = 8; signed = 1; encoding = UTF8; base = 10; } _next_comm[16];\n" +
- " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _next_tid;\n" +
- " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _next_prio;\n" +
- " };\n" +
- " };";
-
- private static final String mdSecond = " event {\n" +
- " name = bozo_the_clown;\n" +
- " id = 1;\n" +
- " stream_id = 0;\n" +
- " fields := struct {\n" +
- " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } clown_nose;\n" +
- " };\n" +
- " };";
-
- private Metadata fixture;
-
- /**
- * Perform pre-test initialization.
- *
- * @throws CTFReaderException
- */
- @Before
- public void setUp() throws CTFReaderException {
- assumeTrue(testTrace.exists());
- fixture = new Metadata(testTrace.getTrace());
- }
-
- /**
- * Run the Metadata(CTFTrace) constructor test.
- */
- @Test
- public void testMetadata() {
- assertNotNull(fixture);
- }
-
- @Test
- public void testTextMD() throws CTFReaderException {
- testSingleFragment();
- }
-
- protected CTFTrace testSingleFragment() throws CTFReaderException {
- fixture = new Metadata();
- CTFTrace trace = fixture.getTrace();
- for (CTFStream s : trace.getStreams()) {
- fail("This should be empty, has" + s.toString());
- }
- fixture.parseText(mdStart);
- int count = 0;
- for (CTFStream s : trace.getStreams()) {
- count++;
- assertNotNull(s);
- }
- assertEquals(1, count);
- assertEquals(1, trace.getEventDeclarations(0L).size());
- return trace;
- }
-
- @Test
- public void testStreamTextMD() throws CTFReaderException {
- try (CTFTrace trace = testSingleFragment();) {
- fixture.parseTextFragment(mdSecond);
- final List<IEventDeclaration> eventDeclarations = new ArrayList<>(trace.getEventDeclarations(0L));
- assertEquals(2, eventDeclarations.size());
- assertEquals("bozo_the_clown", eventDeclarations.get(1).getName());
- }
- }
-
- /**
- * Run the ByteOrder getDetectedByteOrder() method test.
- *
- * @throws CTFReaderException
- */
- @Test
- public void testGetDetectedByteOrder() throws CTFReaderException {
- setUp();
- ByteOrder result = fixture.getDetectedByteOrder();
- assertNull(result);
- }
-
- /**
- * Test toString
- *
- * @throws CTFReaderException
- */
- @Test
- public void testToString() throws CTFReaderException {
- setUp();
- String result = fixture.toString();
- assertNotNull(result);
- }
-
- /**
- * Run the void parse() method test.
- *
- * @throws CTFReaderException
- */
- @Test
- public void testParse() throws CTFReaderException {
- setUp();
- assertEquals(new UUID(0xd18e637435a1cd42L, 0x8e70a9cffa712793L), testTrace.getTrace().getUUID());
- assertEquals(1332166405241713920.0, testTrace.getTrace().getClock().getClockOffset(), 200.0);
- assertEquals(8, testTrace.getTrace().getEnvironment().size());
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013-2014 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.trace;
-
-import org.junit.runner.RunWith;
-import org.junit.runners.Suite;
-
-/**
- * The class <code>TestAll</code> builds a suite that can be used to run all of
- * the tests within its package as well as within any subpackages of its
- * package.
- *
- * @author Matthew Khouzam
- * @version $Revision: 1.0 $
- */
-@RunWith(Suite.class)
-@Suite.SuiteClasses({
- CTFTraceCallsitePerformanceTest.class,
- CTFTraceReaderTest.class,
- CTFTraceTest.class,
- CTFTraceGrowingTest.class,
- IOstructgenTest.class,
- MetadataTest.class,
- CTFStreamInputPacketIndexEntryTest.class,
- CTFStreamInputPacketIndexTest.class,
- CTFStreamInputReaderTest.class,
- CTFStreamInputReaderTimestampComparatorTest.class,
- CTFStreamInputTest.class,
- CTFStreamTest.class,
- UtilsTest.class
-})
-public class TestAll {
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.trace;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import java.util.UUID;
-
-import org.eclipse.linuxtools.ctf.core.trace.Utils;
-import org.junit.Test;
-
-/**
- * The class <code>UtilsTest</code> contains tests for the class
- * {@link Utils}.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-public class UtilsTest {
-
- /**
- * Run the UUID makeUUID(byte[]) method test.
- */
- @Test
- public void testMakeUUID() {
- int byteSize = 32;
- byte[] bytes = new byte[byteSize];
- for (int i = 0; i < byteSize; i++) {
- bytes[i] = (byte) (i);
- }
-
- UUID result = Utils.makeUUID(bytes);
- assertNotNull(result);
- }
-
- /**
- * Run the UUID makeUUID(byte[]) method test.
- */
- @Test
- public void testMakeUUID_2() {
- byte[] bytes = new byte[] { (byte) 1, (byte) 1, (byte) 0, (byte) 0,
- (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 1, (byte) 1,
- (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0 };
-
- UUID result = Utils.makeUUID(bytes);
-
- assertNotNull(result);
- assertEquals(72339069014638592L, result.getLeastSignificantBits());
- assertEquals(72339069014638592L, result.getMostSignificantBits());
- assertEquals("01010000-0000-0000-0101-000000000000", result.toString());
- assertEquals(0, result.variant());
- assertEquals(0, result.version());
- }
-
- /**
- * Run the UUID makeUUID(byte[]) method test.
- */
- @Test
- public void testMakeUUID_3() {
- byte[] bytes = new byte[] { (byte) 0, (byte) 0, (byte) 0, (byte) 0,
- (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0,
- (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0 };
-
- UUID result = Utils.makeUUID(bytes);
-
- assertNotNull(result);
- assertEquals(0L, result.getLeastSignificantBits());
- assertEquals(0L, result.getMostSignificantBits());
- assertEquals("00000000-0000-0000-0000-000000000000", result.toString());
- assertEquals(0, result.variant());
- assertEquals(0, result.version());
- }
-
- /**
- * Run the int unsignedCompare(long,long) method test.
- */
- @Test
- public void testUnsignedCompare() {
- long a = 1L;
- long b = 1L;
- int result;
-
- result = Utils.unsignedCompare(a, b);
- assertEquals(0, result);
-
- result = Utils.unsignedCompare(0L, 1L);
- assertEquals(-1, result);
- result = Utils.unsignedCompare(0xFFFFFFFFL, 0x100000000L);
- assertEquals(-1, result);
- result = Utils.unsignedCompare(-4L, -1L);
- assertEquals(-1, result);
- result = Utils.unsignedCompare(-0x80000000L, -1L);
- assertEquals(-1, result);
- result = Utils.unsignedCompare(0x7FFFFFFFFFFFFFFEL, 0x7FFFFFFFFFFFFFFFL);
- assertEquals(-1, result);
-
- result = Utils.unsignedCompare(1L, 0L);
- assertEquals(1, result);
- result = Utils.unsignedCompare(0x100000000L, 0xFFFFFFFFL);
- assertEquals(1, result);
- result = Utils.unsignedCompare(-1L, -4L);
- assertEquals(1, result);
- result = Utils.unsignedCompare(-1L, -0x80000000L);
- assertEquals(1, result);
- result = Utils.unsignedCompare(0x7FFFFFFFFFFFFFFFL, 0x7FFFFFFFFFFFFFFEL);
- assertEquals(1, result);
- }
-}
\ No newline at end of file
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.types;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.event.types.AbstractArrayDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.CompoundDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.Encoding;
-import org.eclipse.linuxtools.ctf.core.event.types.IDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StringDeclaration;
-import org.eclipse.linuxtools.ctf.core.tests.io.Util;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.internal.ctf.core.event.types.ArrayDeclaration;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * The class <code>ArrayDeclaration2Test</code> contains tests for the class
- * <code>{@link ArrayDeclaration}</code>.
- *
- * @author Matthew Khouzam
- * @version $Revision: 1.0 $
- */
-public class ArrayDeclaration2Test {
-
- private ArrayDeclaration fixture;
-
- /**
- * Perform pre-test initialization.
- */
- @Before
- public void setUp() {
- fixture = new ArrayDeclaration(1, new StringDeclaration());
- }
-
- /**
- * Run the ArrayDeclaration(int,Declaration) constructor test.
- */
- @Test
- public void testArrayDeclaration() {
- int length = 1;
- IDeclaration elemType = new StringDeclaration();
- ArrayDeclaration result = new ArrayDeclaration(length, elemType);
-
- assertNotNull(result);
- String left = "[declaration] array[";
- String right = result.toString().substring(0, left.length());
- assertEquals(left, right);
- assertEquals(1, result.getLength());
- }
-
- /**
- * Run the ArrayDefinition createDefinition(DefinitionScope,String) method
- * test.
- *
- * @throws CTFReaderException
- * error in the bitbuffer
- */
- @Test
- public void testCreateDefinition() throws CTFReaderException {
- String fieldName = "";
- IDefinitionScope definitionScope = null;
- AbstractArrayDefinition result;
- byte[] array = { 't', 'e', 's', 't', '\0', 't', 'h', 'i', 's', '\0' };
- BitBuffer bb = new BitBuffer(Util.testMemory(ByteBuffer.wrap(array)));
- result = fixture.createDefinition(definitionScope, fieldName, bb);
-
- assertNotNull(result);
- }
-
-
-
- /**
- * Run the Declaration getElementType() method test.
- */
- @Test
- public void testGetElementType() {
- IDeclaration result = fixture.getElementType();
- assertNotNull(result);
- }
-
- /**
- * Run the int getLength() method test.
- */
- @Test
- public void testGetLength() {
- int result = fixture.getLength();
- assertEquals(1, result);
- }
-
- /**
- * Run the boolean isString() method test.
- */
- @Test
- public void testIsString_ownDefs() {
- // it's an array of strings, not a string
- assertFalse(fixture.isString());
- }
-
- /**
- * Run the boolean isString() method test.
- */
- @Test
- public void testIsString_complex() {
- final IntegerDeclaration id = IntegerDeclaration.createDeclaration(8, false, 16,
- ByteOrder.LITTLE_ENDIAN, Encoding.UTF8, "", 8);
- CompoundDeclaration ad = new ArrayDeclaration(0, id);
-
- boolean result = ad.isString();
-
- assertTrue(result);
- }
-
- /**
- * Run the String toString() method test.
- */
- @Test
- public void testToString() {
- String result = fixture.toString();
- String left = "[declaration] array[";
- String right = result.substring(0, left.length());
-
- assertEquals(left, right);
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.types;
-
-import static org.junit.Assert.assertNotNull;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.event.scope.LexicalScope;
-import org.eclipse.linuxtools.ctf.core.event.types.CompoundDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.Definition;
-import org.eclipse.linuxtools.ctf.core.event.types.Encoding;
-import org.eclipse.linuxtools.ctf.core.event.types.IDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.StringDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StringDefinition;
-import org.eclipse.linuxtools.ctf.core.tests.io.Util;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTrace;
-import org.eclipse.linuxtools.internal.ctf.core.event.types.ArrayDeclaration;
-import org.eclipse.linuxtools.internal.ctf.core.event.types.ArrayDefinition;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * The class <code>ArrayDefinition2Test</code> contains tests for the class
- * <code>{@link ArrayDefinition}</code>.
- *
- */
-public class ArrayDefinition2Test {
-
- private @NonNull CTFTrace trace = new CTFTrace();
- private ArrayDefinition charArrayFixture;
- private ArrayDefinition stringArrayFixture;
- private ArrayDefinition longArrayFixture;
-
- /**
- * Perform pre-test initialization.
- *
- * structDef shouldn't be null after parsing the CTFTraceReader object, so
- * we can ignore the warning.
- */
- @Before
- public void setUp() {
- charArrayFixture = createCharArray();
- stringArrayFixture = createStringArray();
- longArrayFixture = createLongArray();
- }
-
- private ArrayDefinition createLongArray() {
- IntegerDeclaration decl = IntegerDeclaration.createDeclaration(32, false, 10, ByteOrder.BIG_ENDIAN, Encoding.NONE, "none", 8);
- List<Definition> defs = createIntDefs(10, 32);
- ArrayDefinition temp = setUpDeclaration(decl, defs);
- return temp;
- }
-
- private ArrayDefinition createCharArray() {
- IntegerDeclaration decl = IntegerDeclaration.createDeclaration(8, false, 10, ByteOrder.BIG_ENDIAN, Encoding.UTF8, "none", 8);
- List<Definition> defs = createIntDefs(4, 8);
- ArrayDefinition temp = setUpDeclaration(decl, defs);
- return temp;
- }
-
- private ArrayDefinition createStringArray() {
- StringDeclaration strDecl = new StringDeclaration();
- List<Definition> defs = createDefs();
- ArrayDefinition temp = setUpDeclaration(strDecl, defs);
- return temp;
- }
-
- private ArrayDefinition setUpDeclaration(IDeclaration decl,
- @NonNull List<Definition> defs) {
- CompoundDeclaration ad = new ArrayDeclaration(0, decl);
- ArrayDefinition temp = new ArrayDefinition(ad, this.trace, "Testx", defs);
- return temp;
- }
-
- @NonNull
- private static List<Definition> createIntDefs(int size, int bits) {
- List<Definition> defs = new ArrayList<>(size);
- for (int i = 0; i < size; i++) {
- String content = "test" + i;
- defs.add(new IntegerDefinition(IntegerDeclaration.createDeclaration(bits, false,
- 16, ByteOrder.LITTLE_ENDIAN, Encoding.UTF8, content, 24), null, content, i));
- }
- return defs;
- }
-
- @NonNull
- private static List<Definition> createDefs() {
- int size = 4;
- List<Definition> defs = new ArrayList<>();
- for (int i = 0; i < size; i++) {
- String content = "test" + i;
- defs.add(new StringDefinition(
- new StringDeclaration(Encoding.UTF8), null, content, content));
- }
- return defs;
- }
-
- /**
- * Run the ArrayDefinition(ArrayDeclaration,DefinitionScope,String)
- * constructor test.
- */
- @Test
- public void testArrayDefinition_baseDeclaration() {
- CompoundDeclaration declaration = (CompoundDeclaration) charArrayFixture.getDeclaration();
- String fieldName = "";
-
- @SuppressWarnings("null")
- ArrayDefinition result = new ArrayDefinition(declaration, this.trace, fieldName, Arrays.asList(new Definition[0]));
- assertNotNull(result);
- }
-
- /**
- * Run the ArrayDefinition(ArrayDeclaration,DefinitionScope,String)
- * constructor test.
- */
- @Test
- public void testArrayDefinition_newDeclaration() {
- CompoundDeclaration declaration = new ArrayDeclaration(0,
- new StringDeclaration());
- IDefinitionScope definitionScope = getDefinitionScope();
-
- String fieldName = "";
- @SuppressWarnings("null")
- ArrayDefinition result = new ArrayDefinition(declaration, definitionScope, fieldName, Arrays.asList(new Definition[0]));
- assertNotNull(result);
- }
-
- /**
- * Run the ArrayDeclaration getDeclaration() method test.
- */
- @Test
- public void testGetDeclaration() {
- CompoundDeclaration result = (CompoundDeclaration) charArrayFixture.getDeclaration();
-
- assertNotNull(result);
- }
-
- /**
- * Run the Definition getDefinitions().get(int) method test.
- */
- @Test
- public void testgetElem_noDefs() {
- int i = 0;
- IDefinition result = charArrayFixture.getDefinitions().get(i);
-
- assertNotNull(result);
- }
-
- /**
- * Run the Definition getDefinitions().get(int) method test.
- */
- @Test
- public void testgetElem_withDefs() {
- List<Definition> defs = createDefs();
- IDefinitionScope definitionScope = getDefinitionScope();
- ArrayDefinition ad = new ArrayDefinition((CompoundDeclaration) charArrayFixture.getDeclaration(), definitionScope, "test", defs);
- int j = 1;
-
- IDefinition result = ad.getDefinitions().get(j);
-
- assertNotNull(result);
- }
-
- @NonNull
- private static IDefinitionScope getDefinitionScope() {
- return new IDefinitionScope() {
-
- @Override
- public Definition lookupDefinition(String lookupPath) {
- return null;
- }
-
- @Override
- public LexicalScope getScopePath() {
- return null;
- }
- };
- }
-
- /**
- * Run the void read(BitBuffer) method test.
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void testRead_noDefs() throws CTFReaderException {
- BitBuffer input = new BitBuffer(Util.testMemory(ByteBuffer.allocateDirect(128)));
- charArrayFixture.getDeclaration().createDefinition(null, "test", input);
- }
-
- /**
- * Run the String toString() method test.
- */
- @Test
- public void testToString_char() {
- String result = charArrayFixture.toString();
- assertNotNull(result);
- }
-
- /**
- * Run the String toString() method test.
- */
- @Test
- public void testToString_long() {
- String result = longArrayFixture.toString();
- assertNotNull(result);
- }
-
- /**
- * Run the String toString() method test.
- */
- @Test
- public void testToString_string() {
- String result = stringArrayFixture.toString();
- assertNotNull(result);
- }
-
- /**
- * Run the String toString() method test.
- */
- @Test
- public void testToString_withDefs() {
- String result = charArrayFixture.toString();
-
- assertNotNull(result);
- }
-
- /**
- * Run the String toString() method test.
- */
- @Test
- public void testToStringStringArray() {
- String result = stringArrayFixture.toString();
-
- assertNotNull(result);
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.types;
-
-import static org.junit.Assert.assertNotNull;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.event.types.Definition;
-import org.eclipse.linuxtools.ctf.core.event.types.IDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.StringDeclaration;
-import org.junit.Test;
-
-/**
- * The class <code>DefinitionTest</code> contains tests for the class
- * <code>{@link Definition}</code>.
- *
- * @author Matthew Khouzam
- * @version $Revision: 1.0 $
- */
-public class DefinitionTest {
-
- /**
- * Since Definition is abstract, we'll minimally extend it here to
- * instantiate it.
- */
- static class DefTest extends Definition {
-
- @NonNull
- private static final StringDeclaration STRINGDEF = new StringDeclaration();
-
- public DefTest(IDefinitionScope definitionScope, @NonNull String fieldName) {
- super(DefTest.STRINGDEF, definitionScope, fieldName);
- }
-
- @Override
- @NonNull
- public IDeclaration getDeclaration() {
- return DefTest.STRINGDEF;
- }
-
- }
-
- /**
- * Test a definition
- */
- @Test
- public void testToString() {
- IDefinition fixture = new DefTest(null, "Hello");
- String result = fixture.toString();
-
- assertNotNull(result);
- }
-}
\ No newline at end of file
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.types;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.event.types.Encoding;
-import org.eclipse.linuxtools.ctf.core.event.types.EnumDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.EnumDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDeclaration;
-import org.eclipse.linuxtools.ctf.core.tests.io.Util;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * The class <code>EnumDeclarationTest</code> contains tests for the class
- * <code>{@link EnumDeclaration}</code>.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-public class EnumDeclarationTest {
-
- private EnumDeclaration fixture;
-
- /**
- * Perform pre-test initialization.
- */
- @Before
- public void setUp() {
- fixture = new EnumDeclaration(IntegerDeclaration.createDeclaration(1, false, 1,
- ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 8));
- }
-
- /**
- * Run the EnumDeclaration(IntegerDeclaration) constructor test.
- */
- @Test
- public void testEnumDeclaration() {
- IntegerDeclaration containerType = IntegerDeclaration.createDeclaration(1, false, 1,
- ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 8);
-
- EnumDeclaration result = new EnumDeclaration(containerType);
-
- assertNotNull(result);
- String left = "[declaration] enum[";
- assertEquals(left, result.toString().substring(0, left.length()));
- }
-
- /**
- * Run the boolean add(long,long,String) method test.
- */
- @Test
- public void testAdd() {
- long low = 1L;
- long high = 1L;
- String label = "";
-
- boolean result = fixture.add(low, high, label);
-
- assertTrue(result);
- }
-
- /**
- * Run the EnumDefinition createDefinition(DefinitionScope,String) method
- * test.
- *
- * @throws CTFReaderException
- * out of bounds error, won't happen
- */
- @Test
- public void testCreateDefinition() throws CTFReaderException {
- IDefinitionScope definitionScope = null;
- String fieldName = "";
- byte[] array = { 't', 'e', 's', 't', '\0', 't', 'h', 'i', 's', '\0' };
- BitBuffer bb = new BitBuffer(Util.testMemory(ByteBuffer.wrap(array)));
-
- EnumDefinition result = fixture.createDefinition(definitionScope,
- fieldName, bb);
-
- assertNotNull(result);
- }
-
- /**
- * Run the String query(long) method test.
- */
- @Test
- public void testQuery() {
- long value = 0;
- String result = fixture.query(value);
-
- assertNull(result);
- }
-
- /**
- * Run the String toString() method test.
- */
- @Test
- public void testToString() {
- String result = fixture.toString();
-
- String left = "[declaration] enum[";
- assertEquals(left, result.substring(0, left.length()));
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.types;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import java.nio.ByteOrder;
-
-import org.eclipse.linuxtools.ctf.core.event.types.Encoding;
-import org.eclipse.linuxtools.ctf.core.event.types.EnumDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.EnumDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDefinition;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * The class <code>EnumDefinitionTest</code> contains tests for the class
- * <code>{@link EnumDefinition}</code>.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-public class EnumDefinitionTest {
-
- private EnumDefinition fixtureA;
- private EnumDefinition fixtureB;
-
- /**
- * Perform pre-test initialization.
- */
- @Before
- public void setUp() {
- IntegerDeclaration integerDeclaration = IntegerDeclaration.createDeclaration(1, false, 1, ByteOrder.BIG_ENDIAN,
- Encoding.ASCII, "", 8);
- EnumDeclaration declaration = new EnumDeclaration(
- integerDeclaration);
- declaration.add(0, 10, "a");
- declaration.add(11, 20, "b");
- String fieldName = "";
-
- fixtureA = new EnumDefinition(declaration, null, fieldName, new IntegerDefinition(integerDeclaration, null, fieldName, 4));
- fixtureB = new EnumDefinition(declaration, null, fieldName, new IntegerDefinition(integerDeclaration, null, fieldName, 12));
- }
-
- /**
- * Run the EnumDefinition(EnumDeclaration,DefinitionScope,String)
- * constructor test.
- */
- @Test
- public void testEnumDefinition() {
- assertNotNull(fixtureA);
- assertNotNull(fixtureB);
- }
-
- /**
- * Run the String getValue() method test.
- */
- @Test
- public void testGetValue() {
- String result = fixtureA.getValue();
-
- assertNotNull(result);
- assertEquals("a", result);
- }
-
- /**
- * Run the long getIntegerValue() method test.
- */
- @Test
- public void testGetIntegerValue_one() {
- long result = fixtureA.getIntegerValue();
- assertEquals(4L, result);
- }
-
- /**
- * Run the String toString() method test.
- */
- @Test
- public void testToString() {
- String result = fixtureB.toString();
-
- assertEquals("{ value = b, container = 12 }", result);
- }
-}
\ No newline at end of file
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.types;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assume.assumeTrue;
-
-import org.eclipse.linuxtools.ctf.core.event.EventDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-import org.eclipse.linuxtools.ctf.core.tests.shared.CtfTestTrace;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTrace;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTraceReader;
-import org.eclipse.linuxtools.ctf.core.trace.CTFStream;
-import org.eclipse.linuxtools.internal.ctf.core.event.EventDeclaration;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * The class <code>EventDeclarationTest</code> contains tests for the class
- * <code>{@link EventDeclaration}</code>.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-@SuppressWarnings("javadoc")
-public class EventDeclarationTest {
-
- private static final CtfTestTrace testTrace = CtfTestTrace.KERNEL;
-
- private EventDeclaration fixture;
-
- /**
- * Perform pre-test initialization.
- *
- * @throws CTFReaderException
- */
- @Before
- public void setUp() throws CTFReaderException {
- assumeTrue(testTrace.exists());
- fixture = new EventDeclaration();
- fixture.setContext(new StructDeclaration(1L));
- fixture.setId(1L);
- fixture.setFields(new StructDeclaration(1L));
- fixture.setStream(new CTFStream(testTrace.getTrace()));
- fixture.setName("");
- }
-
- /**
- * Run the EventDeclaration() constructor test.
- */
- @Test
- public void testEventDeclaration() {
- EventDeclaration result = new EventDeclaration();
- assertNotNull(result);
- }
-
- /**
- * Run the boolean contextIsSet() method test.
- */
- @Test
- public void testContextIsSet() {
- boolean result = fixture.contextIsSet();
- assertTrue(result);
- }
-
- /**
- * Run the boolean contextIsSet() method test.
- */
- @Test
- public void testContextIsSet_null() {
- fixture.setContext((StructDeclaration) null);
-
- boolean result = fixture.contextIsSet();
- assertFalse(result);
- }
-
- /**
- * Run the boolean equals(Object) method test.
- *
- * @throws CTFReaderException
- */
- @Test
- public void testEquals() throws CTFReaderException {
- EventDeclaration obj = new EventDeclaration();
- obj.setContext(new StructDeclaration(1L));
- obj.setId(1L);
- obj.setFields(new StructDeclaration(1L));
- obj.setStream(new CTFStream(testTrace.getTrace()));
- obj.setName("");
-
- assertTrue(fixture.equals(fixture));
- boolean result = fixture.equals(obj);
- assertFalse(result);
- }
-
- /**
- * Run the boolean equals(Object) method test.
- */
- @Test
- public void testEquals_null() {
- Object obj = null;
-
- boolean result = fixture.equals(obj);
- assertFalse(result);
- }
-
- /**
- * Run the boolean equals(Object) method test.
- */
- @Test
- public void testEquals_emptyObject() {
- Object obj = new Object();
-
- boolean result = fixture.equals(obj);
- assertFalse(result);
- }
-
- /**
- * Run the boolean equals(Object) method test.
- */
- @Test
- public void testEquals_other1() {
- EventDeclaration obj = new EventDeclaration();
- obj.setContext(fixture.getContext());
-
- boolean result = fixture.equals(obj);
- assertFalse(result);
- }
-
- /**
- * Run the boolean equals(Object) method test.
- */
- @Test
- public void testEquals_other2() {
- EventDeclaration obj = new EventDeclaration();
- obj.setContext(new StructDeclaration(1L));
- obj.setFields(new StructDeclaration(1L));
-
- boolean result = fixture.equals(obj);
- assertFalse(result);
- }
-
- /**
- * Run the boolean equals(Object) method test.
- */
- @Test
- public void testEquals_other3() {
- EventDeclaration obj = new EventDeclaration();
- obj.setContext(new StructDeclaration(1L));
- obj.setId(1L);
- obj.setFields(new StructDeclaration(1L));
-
- boolean result = fixture.equals(obj);
- assertFalse(result);
- }
-
- /**
- * Run the boolean equals(Object) method test.
- */
- @Test
- public void testEquals_other4() {
- EventDeclaration obj = new EventDeclaration();
- obj.setContext(new StructDeclaration(1L));
- obj.setId(1L);
- obj.setFields(new StructDeclaration(1L));
- obj.setName("");
-
- boolean result = fixture.equals(obj);
- assertFalse(result);
- }
-
- /**
- * Run the boolean fieldsIsSet() method test.
- */
- @Test
- public void testFieldsIsSet() {
- boolean result = fixture.fieldsIsSet();
- assertTrue(result);
- }
-
- /**
- * Run the boolean fieldsIsSet() method test.
- */
- @Test
- public void testFieldsIsSet_null() {
- fixture.setFields((StructDeclaration) null);
-
- boolean result = fixture.fieldsIsSet();
- assertFalse(result);
- }
-
- /**
- * Run the StructDeclaration getFields() method test.
- */
- @Test
- public void testGetFields() {
- StructDeclaration result = fixture.getFields();
- assertNotNull(result);
- }
-
- /**
- * Run the Long getId() method test.
- */
- @Test
- public void testGetId() {
- assertEquals(1,fixture.id());
- }
-
- /**
- * Run the String getName() method test.
- */
- @Test
- public void testGetName() {
- String result = fixture.getName();
- assertNotNull(result);
- }
-
- /**
- * Run the Stream getStream() method test.
- */
- @Test
- public void testGetStream() {
- CTFStream result = fixture.getStream();
- assertNotNull(result);
- }
-
- /**
- * Run the int hashCode() method test.
- */
- @Test
- public void testHashCode() {
- int result = fixture.hashCode();
- assertTrue(0 != result);
- }
-
- /**
- * Run the int hashCode() method test.
- */
- @Test
- public void testHashCode_null() {
- fixture.setStream((CTFStream) null);
- fixture.setName((String) null);
-
- int result = fixture.hashCode();
- assertTrue(0 != result);
- }
-
- /**
- * Run the boolean idIsSet() method test.
- */
- @Test
- public void testIdIsSet() {
- boolean result = fixture.idIsSet();
- assertTrue(result);
- }
-
- /**
- * Run the boolean nameIsSet() method test.
- */
- @Test
- public void testNameIsSet() {
- boolean result = fixture.nameIsSet();
- assertTrue(result);
- }
-
- /**
- * Run the boolean nameIsSet() method test.
- */
- @Test
- public void testNameIsSet_null() {
- fixture.setName((String) null);
-
- boolean result = fixture.nameIsSet();
- assertFalse(result);
- }
-
- /**
- * Run the boolean streamIsSet() method test.
- */
- @Test
- public void testStreamIsSet() {
- boolean result = fixture.streamIsSet();
- assertTrue(result);
- }
-
- /**
- * Run the boolean streamIsSet() method test.
- */
- @Test
- public void testStreamIsSet_null() {
- fixture.setStream((CTFStream) null);
-
- boolean result = fixture.streamIsSet();
- assertEquals(false, result);
- }
-
- /**
- * Test for the EventDefinition class
- *
- * @throws CTFReaderException
- */
- @Test
- public void testEventDefinition() throws CTFReaderException {
- try (CTFTrace trace = testTrace.getTrace();) {
- EventDefinition ed = null;
- try (CTFTraceReader tr = new CTFTraceReader(trace);) {
- tr.advance();
- ed = tr.getCurrentEventDef();
- }
-
- assertNotNull(ed);
- assertNotNull(ed.getScopePath());
- assertNotNull(ed.getDeclaration());
- assertNotNull(ed.getFields());
- assertNull(ed.getContext());
- assertNotNull(ed.getPacketContext());
- assertNotNull(ed.getCPU());
- assertNotNull(ed.getStreamInputReader());
- assertNull(ed.lookupDefinition("context"));
- assertNotNull(ed.lookupDefinition("fields"));
- assertNull(ed.lookupDefinition("other"));
- assertNotNull(ed.toString());
- }
- }
-
- EventDeclaration e1;
- EventDeclaration e2;
-
-
- @Test
- public void testEquals1(){
- e1 = new EventDeclaration();
- assertFalse(e1.equals(null));
- }
-
- @Test
- public void testEquals2(){
- e1 = EventDeclaration.getLostEventDeclaration();
- assertFalse(e1.equals(new Long(23L)));
- }
-
- @Test
- public void testEquals3(){
- e1 = EventDeclaration.getLostEventDeclaration();
- assertEquals(e1,e1);
- }
-
- @Test
- public void testEquals4(){
- e1 = EventDeclaration.getLostEventDeclaration();
- e2 = EventDeclaration.getLostEventDeclaration();
- assertEquals(e1,e2);
- }
-
- @Test
- public void testEquals5(){
- e1 = EventDeclaration.getLostEventDeclaration();
- e2 = new EventDeclaration();
- assertFalse(e1.equals(e2));
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-package org.eclipse.linuxtools.ctf.core.tests.types;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.types.EnumDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.FloatDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.StringDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.VariantDeclaration;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.internal.ctf.core.event.types.composite.EventHeaderCompactDeclaration;
-import org.eclipse.linuxtools.internal.ctf.core.event.types.composite.EventHeaderDefinition;
-import org.eclipse.linuxtools.internal.ctf.core.event.types.composite.EventHeaderLargeDeclaration;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * Event header declaration tests
- *
- * @author Matthew Khouzam
- *
- */
-public class EventHeaderDeclarationTest {
-
- private static final int ID = 2222;
- private static final int TIMESTAMP = 1000;
- private static final int VALID_LARGE = 1;
- private static final int VALID_COMPACT = 0;
-
- private final List<StructDeclaration> declarations = new ArrayList<>();
-
- /**
- * Setup
- */
- @Before
- public void init() {
- declarations.clear();
-
- /**
- * do not reflow
- *
- * <pre>
- * struct event_header_compact {
- * enum : uint5_t { compact = 0 ... 30, extended = 31 } id;
- * variant <id> {
- * struct {
- * uint27_clock_monotonic_t timestamp;
- * } compact;
- * struct {
- * uint32_t id;
- * uint64_clock_monotonic_t timestamp;
- * } extended;
- * } v;
- * } align(8);
- * </pre>
- */
-
- StructDeclaration base = new StructDeclaration(8);
- base.addField("id", new EnumDeclaration(IntegerDeclaration.UINT_5B_DECL));
- VariantDeclaration variantV = new VariantDeclaration();
- StructDeclaration compact = new StructDeclaration(8);
- compact.addField("timestamp", IntegerDeclaration.UINT_27B_DECL);
- variantV.addField("compact", compact);
- StructDeclaration large = new StructDeclaration(8);
- large.addField("id", IntegerDeclaration.UINT_32B_DECL);
- large.addField("timestamp", IntegerDeclaration.UINT_64B_DECL);
- variantV.addField("extended", large);
- base.addField("v", variantV);
- declarations.add(base);
-
- /**
- * Do not reflow
- *
- * <pre>
- * struct event_header_large {
- * enum : uint16_t { compact = 0 ... 65534, extended = 65535 } id;
- * variant <id> {
- * struct {
- * uint32_clock_monotonic_t timestamp;
- * } compact;
- * struct {
- * uint32_t id;
- * uint64_clock_monotonic_t timestamp;
- * } extended;
- * } v;
- * } align(8);
- * </pre>
- */
-
- base = new StructDeclaration(8);
- base.addField("id", new EnumDeclaration(IntegerDeclaration.UINT_16B_DECL));
- variantV = new VariantDeclaration();
- compact = new StructDeclaration(8);
- compact.addField("timestamp", IntegerDeclaration.UINT_32B_DECL);
- variantV.addField("compact", compact);
- large = new StructDeclaration(8);
- large.addField("id", IntegerDeclaration.UINT_32B_DECL);
- large.addField("timestamp", IntegerDeclaration.UINT_64B_DECL);
- variantV.addField("extended", large);
- base.addField("v", variantV);
- declarations.add(base);
-
- // bad - well, sounds nice though
- base = new StructDeclaration(8);
- base.addField("potato salad", new FloatDeclaration(8, 8, ByteOrder.BIG_ENDIAN, 8));
- base.addField("bbq ribs", new FloatDeclaration(8, 8, ByteOrder.BIG_ENDIAN, 8));
- declarations.add(base);
- // bad
- base = new StructDeclaration(8);
- base.addField("id", new EnumDeclaration(IntegerDeclaration.UINT_16B_DECL));
- base.addField("v", new FloatDeclaration(8, 8, ByteOrder.BIG_ENDIAN, 8));
- declarations.add(base);
- // bad
- base = new StructDeclaration(8);
- base.addField("id", new EnumDeclaration(IntegerDeclaration.UINT_5B_DECL));
- base.addField("v", new FloatDeclaration(8, 8, ByteOrder.BIG_ENDIAN, 8));
- declarations.add(base);
- // bad
- base = new StructDeclaration(8);
- base.addField("id", new EnumDeclaration(IntegerDeclaration.UINT_5B_DECL));
- variantV = new VariantDeclaration();
- compact = new StructDeclaration(8);
- compact.addField("timestamp", IntegerDeclaration.UINT_27B_DECL);
- variantV.addField("compact1", compact);
- large = new StructDeclaration(8);
- large.addField("id", IntegerDeclaration.UINT_32B_DECL);
- large.addField("timestamp", IntegerDeclaration.UINT_64B_DECL);
- variantV.addField("extended", large);
- base.addField("v", variantV);
- declarations.add(base);
-
- // bad
- base = new StructDeclaration(8);
- base.addField("id", new EnumDeclaration(IntegerDeclaration.UINT_5B_DECL));
- variantV = new VariantDeclaration();
- compact = new StructDeclaration(8);
- compact.addField("timestamp", IntegerDeclaration.UINT_27B_DECL);
- variantV.addField("compact", compact);
- large = new StructDeclaration(8);
- large.addField("id", IntegerDeclaration.UINT_32B_DECL);
- large.addField("timestamp1", IntegerDeclaration.UINT_64B_DECL);
- variantV.addField("extended", large);
- base.addField("v", variantV);
- declarations.add(base);
-
- // bad
- base = new StructDeclaration(8);
- base.addField("id", new EnumDeclaration(IntegerDeclaration.UINT_5B_DECL));
- variantV = new VariantDeclaration();
- compact = new StructDeclaration(8);
- compact.addField("timestamp", IntegerDeclaration.UINT_27B_DECL);
- variantV.addField("compact", compact);
- large = new StructDeclaration(8);
- large.addField("id", IntegerDeclaration.UINT_32B_DECL);
- large.addField("timestamp", new StringDeclaration());
- variantV.addField("extended", large);
- base.addField("v", variantV);
- declarations.add(base);
-
- // bad
- base = new StructDeclaration(8);
- base.addField("id", new EnumDeclaration(IntegerDeclaration.UINT_5B_DECL));
- variantV = new VariantDeclaration();
- compact = new StructDeclaration(8);
- compact.addField("timestamp", IntegerDeclaration.UINT_27B_DECL);
- variantV.addField("compact", compact);
- variantV.addField("surprise!", compact);
- large = new StructDeclaration(8);
- large.addField("id", IntegerDeclaration.UINT_32B_DECL);
- large.addField("timestamp", new StringDeclaration());
- variantV.addField("extended", large);
- base.addField("v", variantV);
- declarations.add(base);
-
- // bad
- base = new StructDeclaration(8);
- base.addField("id", new EnumDeclaration(IntegerDeclaration.UINT_16B_DECL));
- variantV = new VariantDeclaration();
- compact = new StructDeclaration(8);
- compact.addField("timestamp", IntegerDeclaration.UINT_27B_DECL);
- variantV.addField("compact", compact);
- variantV.addField("surprise!", compact);
- large = new StructDeclaration(8);
- large.addField("id", IntegerDeclaration.UINT_32B_DECL);
- large.addField("timestamp", new StringDeclaration());
- variantV.addField("extended", large);
- base.addField("v", variantV);
- declarations.add(base);
- // bad
- base = new StructDeclaration(8);
- base.addField("id", new FloatDeclaration(8, 8, ByteOrder.BIG_ENDIAN, 8));
- base.addField("v", new FloatDeclaration(8, 8, ByteOrder.BIG_ENDIAN, 8));
- declarations.add(base);
- // bad
- base = new StructDeclaration(8);
- base.addField("id", IntegerDeclaration.INT_32B_DECL);
- base.addField("timestamp", IntegerDeclaration.INT_32B_DECL);
- declarations.add(base);
- // bad
- base = new StructDeclaration(8);
- base.addField("id", new EnumDeclaration(IntegerDeclaration.INT_8_DECL));
- base.addField("timestamp", IntegerDeclaration.INT_32B_DECL);
- declarations.add(base);
- }
-
- /**
- * Validate a compact declaration
- */
- @Test
- public void validateCompact() {
- assertEquals(true, EventHeaderCompactDeclaration.isCompactEventHeader(declarations.get(VALID_COMPACT)));
- }
-
- /**
- * Fail if it validates
- */
- @Test
- public void validateCompactFail() {
- for (int i = 0; i < declarations.size(); i++) {
- if (i == VALID_COMPACT) {
- continue;
- }
- assertEquals(false, EventHeaderCompactDeclaration.isCompactEventHeader(declarations.get(i)));
- }
- }
-
- /**
- * Validate a large declaration
- */
- @Test
- public void validateLarge() {
- assertEquals(true, EventHeaderLargeDeclaration.isLargeEventHeader(declarations.get(VALID_LARGE)));
- }
-
- /**
- * Fail if it validates
- */
- @Test
- public void validateLargeFail() {
- for (int i = 0; i < declarations.size(); i++) {
- if (i == VALID_LARGE) {
- continue;
- }
- assertEquals(false, EventHeaderLargeDeclaration.isLargeEventHeader(declarations.get(i)));
- }
- }
-
- /**
- * Test an compact compact header
- *
- * @throws CTFReaderException
- * if {@link BitBuffer} is null
- */
- @Test
- public void testCompactCompact() throws CTFReaderException {
- ByteBuffer buffer = ByteBuffer.allocate(16);
- buffer.putInt(0x80000042);
- byte[] validCompact1 = buffer.array();
-
- EventHeaderCompactDeclaration decl = new EventHeaderCompactDeclaration(ByteOrder.BIG_ENDIAN);
- final ByteBuffer input = ByteBuffer.wrap(validCompact1);
- assertNotNull(input);
- EventHeaderDefinition def = decl.createDefinition(null, "bla", new BitBuffer(input));
- assertNotNull(def);
- assertEquals(16, def.getId());
- assertEquals(0x42, def.getTimestamp());
- }
-
- /**
- * Test an extended compact header
- *
- * @throws CTFReaderException
- * if {@link BitBuffer} is null
- */
- @Test
- public void testCompactExtended() throws CTFReaderException {
- ByteBuffer buffer = ByteBuffer.allocate(16);
- buffer.put((byte) 0xFF);
- buffer.putInt(ID);
- buffer.putLong(TIMESTAMP);
- byte[] validCompact2 = buffer.array();
-
- EventHeaderCompactDeclaration decl = new EventHeaderCompactDeclaration(ByteOrder.BIG_ENDIAN);
- final ByteBuffer input = ByteBuffer.wrap(validCompact2);
- assertNotNull(input);
- EventHeaderDefinition def = decl.createDefinition(null, "bla", new BitBuffer(input));
- assertNotNull(def);
- assertEquals(ID, def.getId());
- assertEquals(TIMESTAMP, def.getTimestamp());
- }
-
- /**
- * Test an compact large header
- *
- * @throws CTFReaderException
- * if {@link BitBuffer} is null
- */
- @Test
- public void testLargeCompact() throws CTFReaderException {
- ByteBuffer buffer = ByteBuffer.allocate(16);
- buffer.putShort((short) ID);
- buffer.putInt(TIMESTAMP);
- byte[] validLarge1 = buffer.array();
-
- EventHeaderLargeDeclaration decl = new EventHeaderLargeDeclaration(ByteOrder.BIG_ENDIAN);
- final ByteBuffer input = ByteBuffer.wrap(validLarge1);
- assertNotNull(input);
- EventHeaderDefinition def = decl.createDefinition(null, "bla", new BitBuffer(input));
- assertNotNull(def);
- assertEquals(ID, def.getId());
- assertEquals(TIMESTAMP, def.getTimestamp());
- assertEquals(ID, ((IntegerDefinition) def.getDefinition("id")).getValue());
- assertEquals(TIMESTAMP, ((IntegerDefinition) def.getDefinition("timestamp")).getValue());
- }
-
- /**
- * Test an large large header
- *
- * @throws CTFReaderException
- * if {@link BitBuffer} is null
- */
- @Test
- public void testLargeExtended() throws CTFReaderException {
- ByteBuffer buffer = ByteBuffer.allocate(16);
- buffer.putShort((short) -1);
- buffer.putInt(ID);
- buffer.putLong(TIMESTAMP);
- byte[] validLarge2 = buffer.array();
-
- EventHeaderLargeDeclaration decl = new EventHeaderLargeDeclaration(ByteOrder.BIG_ENDIAN);
- final ByteBuffer input = ByteBuffer.wrap(validLarge2);
- assertNotNull(input);
- EventHeaderDefinition def = decl.createDefinition(null, "bla", new BitBuffer(input));
- assertNotNull(def);
- assertEquals(ID, def.getId());
- assertEquals(TIMESTAMP, def.getTimestamp());
- assertEquals(ID, ((IntegerDefinition) def.getDefinition("id")).getValue());
- assertEquals(TIMESTAMP, ((IntegerDefinition) def.getDefinition("timestamp")).getValue());
- }
-
- /**
- * Test maximum sizes, make sure they don't change unannounced
- */
- @Test
- public void testMaxSizes() {
- assertEquals(112, (new EventHeaderLargeDeclaration(ByteOrder.BIG_ENDIAN)).getMaximumSize());
- assertEquals(104, (new EventHeaderCompactDeclaration(ByteOrder.BIG_ENDIAN)).getMaximumSize());
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.types;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.nio.ByteOrder;
-
-import org.eclipse.linuxtools.ctf.core.event.types.FloatDeclaration;
-import org.junit.Test;
-
-@SuppressWarnings("javadoc")
-public class FloatDeclarationTest {
- private FloatDeclaration fixture;
-
-
- @Test
- public void ctorTest() {
- for( int i = 1; i < 20; i++) {
- fixture = new FloatDeclaration(i, 32-i, ByteOrder.nativeOrder(), 0);
- assertNotNull(fixture);
- }
- }
-
- @Test
- public void getterTest() {
- fixture = new FloatDeclaration(8, 24, ByteOrder.nativeOrder(), 1);
- assertEquals( fixture.getAlignment(), 1);
- assertEquals( fixture.getByteOrder(), ByteOrder.nativeOrder());
- assertEquals( fixture.getExponent(), 8);
- assertEquals( fixture.getMantissa(), 24);
- }
-
- @Test
- public void toStringTest() {
- fixture = new FloatDeclaration(8, 24, ByteOrder.nativeOrder(), 0);
- assertTrue(fixture.toString().contains("float"));
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.types;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.types.FloatDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.FloatDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDefinition;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * The class <code>IntegerDefinitionTest</code> contains tests for the class
- * <code>{@link IntegerDefinition}</code>.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-@SuppressWarnings("javadoc")
-public class FloatDefinitionTest {
-
- private FloatDefinition fixture;
- private FloatDefinition singleFixture;
- private FloatDefinition doubleFixture; // all the way.
- private FloatDeclaration parent;
- @NonNull
- private static final String fieldName = "float";
-
- /**
- * Perform pre-test initialization.
- *
- * @throws CTFReaderException
- * error creating floats
- */
- @Before
- public void setUp() throws CTFReaderException {
- testFloat248();
- testFloat5311();
- }
-
- @Test
- public void testFloat248() throws CTFReaderException {
- parent = new FloatDeclaration(8, 24, ByteOrder.nativeOrder(), 0);
- BitBuffer bb = create32BitFloatByteBuffer();
- singleFixture = parent.createDefinition(null, fieldName, bb);
- assertNotNull(singleFixture);
- }
-
- @Test
- public void testFloat5311() throws CTFReaderException {
- parent = new FloatDeclaration(11, 53, ByteOrder.nativeOrder(), 0);
- BitBuffer bb = create64BitFloatByteBuffer();
- doubleFixture = parent.createDefinition(null, fieldName, bb);
- assertNotNull(doubleFixture);
- }
-
- @Test
- public void testFloat32Bit() throws CTFReaderException {
- for (int i = 1; i < 31; i++) {
- parent = new FloatDeclaration(i, 32 - i, ByteOrder.nativeOrder(), 0);
-
- fixture = parent.createDefinition(null, fieldName, create32BitFloatByteBuffer());
- assertNotNull(fixture);
- assertEquals("test" + i, "2.0", fixture.toString());
- }
- }
-
- @Test
- public void testFloat64Bit() throws CTFReaderException {
- for (int i = 1; i < 63; i++) {
- parent = new FloatDeclaration(i, 64 - i, ByteOrder.nativeOrder(), 0);
- fixture = parent.createDefinition(null, fieldName, create64BitFloatByteBuffer());
- assertNotNull(fixture);
- if (i <= 32) {
- assertEquals("test" + i, "2.0", fixture.toString());
- } else if (i == 33) {
- assertEquals("test" + i, "1.0", fixture.toString());
- } else {
- assertNotNull(fixture.getValue());
- }
-
- }
- }
-
- @Test
- public void testFloat48Bit() throws CTFReaderException {
- parent = new FloatDeclaration(12, 32, ByteOrder.nativeOrder(), 0);
- fixture = parent.createDefinition(null, fieldName, create64BitFloatByteBuffer());
- assertNotNull(fixture);
- assertEquals(Double.NaN, fixture.getValue(), 0.1);
- }
-
- /**
- * Run the IntegerDeclaration getDeclaration() method test.
- */
- @Test
- public void testGetDeclaration() {
- FloatDeclaration result = singleFixture.getDeclaration();
- assertNotNull(result);
- }
-
- /**
- * Run the long getValue() method test.
- */
- @Test
- public void testGetValue() {
- double result = singleFixture.getValue();
- assertEquals(2.0, result, 0.1);
- }
-
- /**
- * Run the String toString() method test.
- */
- @Test
- public void testToString() {
- String result = singleFixture.toString();
- assertNotNull(result);
- assertEquals("2.0", result);
- }
-
- @NonNull
- private static BitBuffer create32BitFloatByteBuffer() {
- float[] data = new float[2];
- data[0] = 2.0f;
- data[1] = 3.14f;
- ByteBuffer byb = ByteBuffer.allocate(128);
- byb.order(ByteOrder.nativeOrder());
- byb.mark();
- byb.putFloat(data[0]);
- byb.putFloat(data[1]);
- byb.reset();
- BitBuffer bb = new BitBuffer(byb);
- return bb;
- }
-
- @NonNull
- private static BitBuffer create64BitFloatByteBuffer() {
- double[] data = new double[2];
- data[0] = 2.0f;
- data[1] = 3.14f;
- ByteBuffer byb = ByteBuffer.allocate(128);
- byb.order(ByteOrder.nativeOrder());
- byb.mark();
- byb.putDouble(data[0]);
- byb.putDouble(data[1]);
- byb.reset();
- BitBuffer bb = new BitBuffer(byb);
- return bb;
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013, 2014 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- * Marc-Andre Laperle - Add min/maximum for validation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.types;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import java.math.BigInteger;
-import java.nio.ByteOrder;
-
-import org.eclipse.linuxtools.ctf.core.event.types.Encoding;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDeclaration;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * The class <code>IntegerDeclarationTest</code> contains tests for the class
- * <code>{@link IntegerDeclaration}</code>.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-public class IntegerDeclarationTest {
-
- private IntegerDeclaration fixture;
-
- /**
- * Perform pre-test initialization.
- */
- @Before
- public void setUp() {
- fixture = IntegerDeclaration.createDeclaration(1, false, 1, ByteOrder.BIG_ENDIAN,
- Encoding.ASCII, "", 32);
- }
-
- /**
- * Run the IntegerDeclaration(int,boolean,int,ByteOrder,Encoding)
- * constructor test.
- */
- @Test
- public void testIntegerDeclaration() {
- int len = 1;
- boolean signed = false;
- int base = 1;
- ByteOrder byteOrder = ByteOrder.BIG_ENDIAN;
- Encoding encoding = Encoding.ASCII;
-
- IntegerDeclaration result = IntegerDeclaration.createDeclaration(len, signed, base,
- byteOrder, encoding, "", 16);
-
- assertNotNull(result);
- assertEquals(1, result.getBase());
- assertEquals(false, result.isCharacter());
- String outputValue = "[declaration] integer[";
- assertEquals(outputValue,
- result.toString().substring(0, outputValue.length()));
- assertEquals(1, result.getLength());
- assertEquals(false, result.isSigned());
- }
-
- /**
- * Test that IntegerDeclaration throws when constructing a signed 1 bit
- * declaration
- */
- @Test(expected = java.lang.IllegalArgumentException.class)
- public void testIntegerDeclarationIllegalArgSignedBit() {
- int len = 1;
- boolean signed = true;
- int base = 1;
- ByteOrder byteOrder = ByteOrder.BIG_ENDIAN;
- Encoding encoding = Encoding.ASCII;
- IntegerDeclaration.createDeclaration(len, signed, base, byteOrder, encoding, "", 16);
- }
-
- /**
- * Test that IntegerDeclaration throws when constructing a invalid length
- * declaration
- */
- @Test(expected = java.lang.IllegalArgumentException.class)
- public void testIntegerDeclarationIllegalArgBadLenght() {
- int len = 0;
- boolean signed = false;
- int base = 1;
- ByteOrder byteOrder = ByteOrder.BIG_ENDIAN;
- Encoding encoding = Encoding.ASCII;
- IntegerDeclaration.createDeclaration(len, signed, base, byteOrder, encoding, "", 16);
- }
-
- /**
- * Test the factory part more rigorously to make sure there are no
- * regressions
- */
- @Test
- public void testIntegerDeclarationBruteForce() {
- ByteOrder[] bos = { ByteOrder.LITTLE_ENDIAN, ByteOrder.BIG_ENDIAN };
- Encoding[] encodings = { Encoding.ASCII, Encoding.NONE, Encoding.UTF8 };
- boolean[] signeds = { true, false }; // not a real word
- String[] clocks = { "something", "" };
- int[] bases = { 2, 4, 6, 8, 10, 12, 16 };
- for (int len = 2; len < 65; len++) {
- for (ByteOrder bo : bos) {
- for (boolean signed : signeds) {
- for (int base : bases) {
- for (Encoding enc : encodings) {
- for (String clock : clocks) {
- assertNotNull(enc);
- assertNotNull(clock);
- IntegerDeclaration intDec = IntegerDeclaration.createDeclaration(len, signed, base, bo, enc, clock, 8);
- String title = Integer.toString(len) + " " + bo + " " + signed + " " + base + " " + enc;
- assertEquals(title, signed, intDec.isSigned());
- assertEquals(title, base, intDec.getBase());
- // at len 8 le and be are the same
- if (len != 8) {
- assertEquals(title, bo, intDec.getByteOrder());
- }
- assertEquals(title, len, intDec.getLength());
- assertEquals(title, len, intDec.getMaximumSize());
- assertEquals(title, clock, intDec.getClock());
- assertEquals(title, !signed && len == 8, intDec.isUnsignedByte());
- }
- }
- }
- }
- }
- }
- }
-
- /**
- * Run the int getBase() method test.
- */
- @Test
- public void testGetBase() {
- int result = fixture.getBase();
- assertEquals(1, result);
- }
-
- /**
- * Run the ByteOrder getByteOrder() method test.
- */
- @Test
- public void testGetByteOrder() {
- ByteOrder result = fixture.getByteOrder();
- assertNotNull(result);
- assertEquals("BIG_ENDIAN", result.toString());
- }
-
- /**
- * Run the Encoding getEncoding() method test.
- */
- @Test
- public void testGetEncoding() {
- Encoding result = fixture.getEncoding();
- assertNotNull(result);
- assertEquals("ASCII", result.name());
- assertEquals("ASCII", result.toString());
- assertEquals(1, result.ordinal());
- }
-
- /**
- * Run the int getLength() method test.
- */
- @Test
- public void testGetLength() {
- int result = fixture.getLength();
- assertEquals(1, result);
- }
-
- /**
- * Run the boolean isCharacter() method test.
- */
- @Test
- public void testIsCharacter() {
- boolean result = fixture.isCharacter();
- assertEquals(false, result);
- }
-
- /**
- * Run the boolean isCharacter() method test.
- */
- @Test
- public void testIsCharacter_8bytes() {
- IntegerDeclaration fixture8 = IntegerDeclaration.createDeclaration(8, true, 1,
- ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 8);
-
- boolean result = fixture8.isCharacter();
- assertEquals(true, result);
- }
-
- /**
- * Run the boolean isSigned() method test.
- */
- @Test
- public void testIsSigned_signed() {
- IntegerDeclaration fixtureSigned = IntegerDeclaration.createDeclaration(2, true,
- 1, ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 8);
- boolean result = fixtureSigned.isSigned();
- assertEquals(true, result);
- }
-
- /**
- * Run the boolean isSigned() method test.
- */
- @Test
- public void testIsSigned_unsigned() {
- boolean result = fixture.isSigned();
- assertEquals(false, result);
- }
-
- /**
- * Run the String toString() method test.
- */
- @Test
- public void testToString() {
- String result = fixture.toString();
- String trunc = result.substring(0, 22);
- assertEquals("[declaration] integer[", trunc);
- }
-
- /**
- * Run the long getMaxValue() method test.
- */
- @Test
- public void testMaxValue() {
- assertEquals(BigInteger.ONE, fixture.getMaxValue());
-
- IntegerDeclaration signed8bit = IntegerDeclaration.createDeclaration(8, true, 1, ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 32);
- assertEquals(BigInteger.valueOf(127), signed8bit.getMaxValue());
-
- IntegerDeclaration unsigned8bit = IntegerDeclaration.createDeclaration(8, false, 1, ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 32);
- assertEquals(BigInteger.valueOf(255), unsigned8bit.getMaxValue());
-
- IntegerDeclaration signed32bit = IntegerDeclaration.createDeclaration(32, true, 1, ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 32);
- assertEquals(BigInteger.valueOf(2147483647), signed32bit.getMaxValue());
-
- IntegerDeclaration unsigned32bit = IntegerDeclaration.createDeclaration(32, false, 1, ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 32);
- assertEquals(BigInteger.valueOf(4294967295l), unsigned32bit.getMaxValue());
-
- IntegerDeclaration signed64bit = IntegerDeclaration.createDeclaration(64, true, 1, ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 32);
- assertEquals(BigInteger.valueOf(9223372036854775807L), signed64bit.getMaxValue());
-
- IntegerDeclaration unsigned64bit = IntegerDeclaration.createDeclaration(64, false, 1, ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 32);
- assertEquals(BigInteger.valueOf(2).pow(64).subtract(BigInteger.ONE), unsigned64bit.getMaxValue());
- }
-
- /**
- * Run the long getMinValue() method test.
- */
- @Test
- public void testMinValue() {
- assertEquals(BigInteger.ZERO, fixture.getMinValue());
-
- IntegerDeclaration signed8bit = IntegerDeclaration.createDeclaration(8, true, 1, ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 32);
- assertEquals(BigInteger.valueOf(-128), signed8bit.getMinValue());
-
- IntegerDeclaration unsigned8bit = IntegerDeclaration.createDeclaration(8, false, 1, ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 32);
- assertEquals(BigInteger.ZERO, unsigned8bit.getMinValue());
-
- IntegerDeclaration signed32bit = IntegerDeclaration.createDeclaration(32, true, 1, ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 32);
- assertEquals(BigInteger.valueOf(-2147483648), signed32bit.getMinValue());
-
- IntegerDeclaration unsigned32bit = IntegerDeclaration.createDeclaration(32, false, 1, ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 32);
- assertEquals(BigInteger.ZERO, unsigned32bit.getMinValue());
-
- IntegerDeclaration signed64bit = IntegerDeclaration.createDeclaration(64, true, 1, ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 32);
- assertEquals(BigInteger.valueOf(-9223372036854775808L), signed64bit.getMinValue());
-
- IntegerDeclaration unsigned64bit = IntegerDeclaration.createDeclaration(64, false, 1, ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 32);
- assertEquals(BigInteger.ZERO, unsigned64bit.getMinValue());
- }
-}
\ No newline at end of file
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.types;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.event.types.Encoding;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDefinition;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * The class <code>IntegerDefinitionTest</code> contains tests for the class
- * <code>{@link IntegerDefinition}</code>.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-public class IntegerDefinitionTest {
-
- private IntegerDefinition fixture;
- @NonNull private static final String NAME = "testInt";
- @NonNull private static final String clockName = "clock";
-
- /**
- * Perform pre-test initialization.
- *
- * @throws CTFReaderException
- * won't happen
- */
- @Before
- public void setUp() throws CTFReaderException {
- IntegerDeclaration id = IntegerDeclaration.createDeclaration(1, false, 1, ByteOrder.BIG_ENDIAN, Encoding.NONE, clockName, 8);
- ByteBuffer byb = ByteBuffer.allocate(128);
- byb.mark();
- byb.putInt(1);
- byb.reset();
- BitBuffer bb = new BitBuffer(byb);
- fixture = id.createDefinition(null, NAME, bb);
- }
-
- /**
- * Run the IntegerDefinition(IntegerDeclaration,DefinitionScope,String)
- * constructor test.
- */
- @Test
- public void testIntegerDefinition() {
- IntegerDeclaration declaration = IntegerDeclaration.createDeclaration(1, false, 1,
- ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 8);
- IDefinitionScope definitionScope = null;
- String fieldName = "";
-
- IntegerDefinition result = new IntegerDefinition(declaration,
- definitionScope, fieldName, 1);
- assertNotNull(result);
- }
-
- /**
- * Run the IntegerDeclaration getDeclaration() method test.
- */
- @Test
- public void testGetDeclaration() {
- IntegerDeclaration result = fixture.getDeclaration();
- assertNotNull(result);
- }
-
- /**
- * Run the long getValue() method test.
- */
- @Test
- public void testGetValue() {
- long result = fixture.getValue();
- assertEquals(0L, result);
- }
-
- /**
- * Run the String toString() method test.
- */
- @Test
- public void testToString() {
- String result = fixture.toString();
- assertEquals("0", result);
- }
-
- /**
- * Run the IntegerDefinition formatNumber(Long, int, boolean) method test
- * for unsigned values.
- */
- @Test
- public void testFormatNumber_unsignedLong() {
-
- long unsignedLongValue = -64;
- String result = IntegerDefinition.formatNumber(unsignedLongValue, 10, false);
- // -64 + 2^64 = 18446744073709551552
- assertEquals("18446744073709551552", result);
-
- unsignedLongValue = -131940199973272L;
- result = IntegerDefinition.formatNumber(unsignedLongValue, 10, false);
- // -131940199973272l + 2^64 = 18446612133509578344
- assertEquals("18446612133509578344", result);
-
- unsignedLongValue = 123456789L;
- result = IntegerDefinition.formatNumber(unsignedLongValue, 10, false);
- assertEquals("123456789", result);
- }
-
- /**
- * Run the IntegerDefinition formatNumber(Long, int, boolean) method test
- * for signed values.
- */
- @Test
- public void testFormatNumber_signedLong() {
- long signedValue = -64L;
- String result = IntegerDefinition.formatNumber(signedValue, 10, true);
- assertEquals("-64", result);
-
- signedValue = -131940199973272L;
- result = IntegerDefinition.formatNumber(signedValue, 10, true);
- assertEquals("-131940199973272", result);
-
- signedValue = 123456789L;
- result = IntegerDefinition.formatNumber(signedValue, 10, true);
- assertEquals("123456789", result);
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 École Polytechnique de Montréal, Ericsson
- *
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Geneviève Bastien - Initial API and implementation
- * Alexandre Montplaisir - Split out in separate class
- * Matthew Khouzam - update api (exceptions)
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.types;
-
-import static org.junit.Assert.assertEquals;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.types.Encoding;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDefinition;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * Endianness test for {@link IntegerDefinition}.
- *
- * @author Geneviève Bastien
- */
-public class IntegerEndiannessTest {
-
- private static final @NonNull String name = "testInt";
- private static final @NonNull String clockName = "clock";
-
- private ByteBuffer bb;
-
- private @NonNull BitBuffer input = new BitBuffer();
-
- /**
- * Set up the bit-buffer to be used
- */
- @Before
- public void setUp() {
- bb = java.nio.ByteBuffer.allocateDirect(8);
- final ByteBuffer byb = bb;
- if (byb == null) {
- throw new IllegalStateException("Failed to allocate memory");
- }
- bb.put((byte) 0xab);
- bb.put((byte) 0xcd);
- bb.put((byte) 0xef);
- bb.put((byte) 0x12);
- bb.put((byte) 0x34);
- bb.put((byte) 0x56);
- bb.put((byte) 0x78);
- bb.put((byte) 0x9a);
-
- input = new BitBuffer(byb);
- }
-
- /**
- * Read 32-bits BE
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void test32BE() throws CTFReaderException {
- IntegerDeclaration be = IntegerDeclaration.createDeclaration(32, true, 1, ByteOrder.BIG_ENDIAN, Encoding.NONE, clockName, 8);
- IntegerDefinition fixture_be = be.createDefinition(null, name, input);
- assertEquals(0xabcdef12, fixture_be.getValue());
- }
-
- /**
- * Read 64-bits BE
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void test64BE() throws CTFReaderException {
- IntegerDeclaration be = IntegerDeclaration.createDeclaration(64, true, 1, ByteOrder.BIG_ENDIAN, Encoding.NONE, clockName, 8);
- IntegerDefinition fixture_be = be.createDefinition(null, name, input);
- assertEquals(0xabcdef123456789aL, fixture_be.getValue());
- }
-
- /**
- * Read 32-bits LE
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void test32LE() throws CTFReaderException {
- IntegerDeclaration le = IntegerDeclaration.createDeclaration(32, true, 1, ByteOrder.LITTLE_ENDIAN, Encoding.NONE, clockName, 8);
- IntegerDefinition fixture_le = le.createDefinition(null, name, input);
- assertEquals(0x12efcdab, fixture_le.getValue());
- }
-
- /**
- * Read 64-bits LE
- *
- * @throws CTFReaderException
- * error
- */
- @Test
- public void test64LE() throws CTFReaderException {
- IntegerDeclaration le = IntegerDeclaration.createDeclaration(64, true, 1, ByteOrder.LITTLE_ENDIAN, Encoding.NONE, clockName, 8);
- IntegerDefinition fixture_le = le.createDefinition(null, name, input);
- assertEquals(0x9a78563412efcdabL, fixture_le.getValue());
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.types;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.types.AbstractArrayDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.Definition;
-import org.eclipse.linuxtools.ctf.core.event.types.Encoding;
-import org.eclipse.linuxtools.ctf.core.event.types.IDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.StringDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDefinition;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.internal.ctf.core.event.types.SequenceDeclaration;
-import org.junit.Before;
-import org.junit.Test;
-
-import com.google.common.collect.ImmutableList;
-
-/**
- * The class <code>SequenceDeclarationTest</code> contains tests for the class
- * <code>{@link SequenceDeclaration}</code>.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-@SuppressWarnings("javadoc")
-public class SequenceDeclaration2Test {
-
- @NonNull private static final String FIELD_NAME = "LengthName";
-
- private SequenceDeclaration fixture;
- @NonNull private BitBuffer input = new BitBuffer();
-
- @Before
- public void setUp() {
- fixture = new SequenceDeclaration(FIELD_NAME, new StringDeclaration());
- byte array[] = { 't', 'e', 's', 't', '\0', 't', 'h', 'i', 's', '\0' };
- ByteBuffer byb = ByteBuffer.wrap(array);
- if( byb == null){
- throw new IllegalStateException("Failed to allocate memory");
- }
- input = new BitBuffer(byb);
- }
-
- /**
- * Run the SequenceDeclaration(String,Declaration) constructor test.
- */
- @Test
- public void testSequenceDeclaration() {
- String lengthName = "";
- IDeclaration elemType = new StringDeclaration();
-
- SequenceDeclaration result = new SequenceDeclaration(lengthName, elemType);
- assertNotNull(result);
- String string = "[declaration] sequence[";
- assertEquals(string, result.toString().substring(0, string.length()));
- }
-
- /**
- * Run the SequenceDefinition createDefinition(DefinitionScope,String)
- * method test.
- *
- * @throws CTFReaderException
- * an error in the bitbuffer
- */
- @Test
- public void testCreateDefinition() throws CTFReaderException {
- long seqLen = 2;
- IntegerDeclaration id = IntegerDeclaration.createDeclaration(8, false, 8,
- ByteOrder.LITTLE_ENDIAN, Encoding.UTF8, "", 32);
- StructDeclaration structDec = new StructDeclaration(0);
- structDec.addField(FIELD_NAME, id);
- StructDefinition structDef = new StructDefinition(
- structDec,
- null,
- "x",
- ImmutableList.of(FIELD_NAME),
- new Definition[] {
- new IntegerDefinition(
- id,
- null,
- FIELD_NAME,
- seqLen)
- });
- AbstractArrayDefinition result = fixture.createDefinition(structDef, FIELD_NAME, input);
- assertNotNull(result);
- }
-
- /**
- * Run the Declaration getElementType() method test.
- */
- @Test
- public void testGetElementType() {
- IDeclaration result = fixture.getElementType();
- assertNotNull(result);
- }
-
- /**
- * Run the String toString() method test.
- */
- @Test
- public void testToString() {
- String result = fixture.toString();
- String left = "[declaration] sequence[";
- assertEquals(left, result.substring(0, left.length()));
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.types;
-
-import static org.junit.Assert.assertNotNull;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.types.Definition;
-import org.eclipse.linuxtools.ctf.core.event.types.Encoding;
-import org.eclipse.linuxtools.ctf.core.event.types.IDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDefinition;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.internal.ctf.core.event.types.ByteArrayDefinition;
-import org.eclipse.linuxtools.internal.ctf.core.event.types.SequenceDeclaration;
-import org.junit.Before;
-import org.junit.Test;
-
-import com.google.common.collect.ImmutableList;
-
-/**
- * The class <code>SequenceDefinition2Test</code> contains tests for the class
- * <code>{@link SequenceDefinition2}</code>.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-@SuppressWarnings("javadoc")
-public class SequenceDefinition2Test {
-
- private ByteArrayDefinition fixture;
- private final static int seqLen = 15;
-
- private static ImmutableList<String> wrap(String s) {
- return ImmutableList.<String> builder().add(s).build();
- }
-
- /**
- * Perform pre-test initialization.
- *
- * @throws CTFReaderException
- */
- @Before
- public void setUp() throws CTFReaderException {
- fixture = initString();
- }
-
- private static ByteArrayDefinition initString() throws CTFReaderException {
- StructDeclaration structDec;
- StructDefinition structDef;
-
- int len = 8;
- IntegerDeclaration id = IntegerDeclaration.createDeclaration(len, false, len,
- ByteOrder.LITTLE_ENDIAN, Encoding.UTF8, "", 8);
- String lengthName = "LengthName";
- structDec = new StructDeclaration(0);
- structDec.addField(lengthName, id);
-
- structDef = new StructDefinition(structDec, null, "x", wrap(lengthName), new Definition[] { new IntegerDefinition(id, null, lengthName, seqLen) });
-
- SequenceDeclaration sd = new SequenceDeclaration(lengthName, id);
- ByteBuffer allocateDirect = java.nio.ByteBuffer.allocateDirect(seqLen * len);
- if( allocateDirect == null){
- throw new IllegalStateException("Failed to allocate memory");
- }
- BitBuffer input = new BitBuffer(allocateDirect);
- for (int i = 0; i < seqLen; i++) {
- input.putInt(i);
- }
-
- ByteArrayDefinition ret = (ByteArrayDefinition) sd.createDefinition(structDef, "TestX", input);
- assertNotNull(ret);
- return ret;
- }
-
- /**
- * Run the FixedStringDefinition(SequenceDeclaration,DefinitionScope,String)
- * constructor test.
- */
- @Test
- public void testFixedStringDefinition() {
- assertNotNull(fixture);
- }
-
- /**
- * Run the SequenceDeclaration getDeclaration() method test.
- */
- @Test
- public void testGetDeclaration() {
- SequenceDeclaration result = (SequenceDeclaration) fixture.getDeclaration();
- assertNotNull(result);
- }
-
- /**
- * Run the Definition getElem(int) method test.
- */
- @Test
- public void testGetElem() {
- int i = 1;
- IDefinition result = fixture.getDefinitions().get(i);
- assertNotNull(result);
- }
-
- /**
- * Run the String toString() method test.
- */
- @Test
- public void testToString() {
- String result = fixture.toString();
- assertNotNull(result);
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.types;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import java.nio.ByteBuffer;
-
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.event.types.Encoding;
-import org.eclipse.linuxtools.ctf.core.event.types.StringDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StringDefinition;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * The class <code>StringDeclarationTest</code> contains tests for the class
- * <code>{@link StringDeclaration}</code>.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-public class StringDeclarationTest {
-
- private StringDeclaration fixture;
-
- /**
- * Perform pre-test initialization.
- */
- @Before
- public void setUp() {
- fixture = new StringDeclaration(Encoding.ASCII);
- }
-
- /**
- * Run the StringDeclaration() constructor test.
- */
- @Test
- public void testStringDeclaration() {
- StringDeclaration result = new StringDeclaration();
-
- assertNotNull(result);
- String string = "[declaration] string[";
- assertEquals(string, result.toString().substring(0, string.length()));
- }
-
- /**
- * Run the StringDeclaration(Encoding) constructor test.
- */
- @Test
- public void testStringDeclaration_2() {
- Encoding encoding = Encoding.ASCII;
- StringDeclaration result = new StringDeclaration(encoding);
-
- assertNotNull(result);
- String string = "[declaration] string[";
- assertEquals(string, result.toString().substring(0, string.length()));
- }
-
- /**
- * Run the StringDefinition createDefinition(DefinitionScope,String) method
- * test.
- *
- * @throws CTFReaderException
- * out of buffer exception
- */
- @Test
- public void testCreateDefinition() throws CTFReaderException {
- IDefinitionScope definitionScope = null;
- String fieldName = "id";
- ByteBuffer allocate = ByteBuffer.allocate(100);
- if (allocate == null) {
- throw new IllegalStateException("Failed to allocate memory");
- }
- BitBuffer bb = new BitBuffer(allocate);
- StringDefinition result = fixture.createDefinition(definitionScope,
- fieldName, bb);
-
- assertNotNull(result);
- }
-
- /**
- * Run the Encoding getEncoding() method test.
- */
- @Test
- public void testGetEncoding() {
- Encoding result = fixture.getEncoding();
-
- assertNotNull(result);
- assertEquals("ASCII", result.name());
- assertEquals("ASCII", result.toString());
- assertEquals(1, result.ordinal());
- }
-
- /**
- * Run the String toString() method test.
- */
- @Test
- public void testToString() {
- String result = fixture.toString();
- String left = "[declaration] string[";
- String right = result.substring(0, left.length());
-
- assertEquals(left, right);
- }
-}
\ No newline at end of file
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.types;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import java.nio.ByteBuffer;
-
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.event.types.StringDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StringDefinition;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * The class <code>StringDefinitionTest</code> contains tests for the class
- * <code>{@link StringDefinition}</code>.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-public class StringDefinitionTest {
-
- private StringDefinition fixture;
- private String testString;
-
- /**
- * Perform pre-test initialization.
- *
- * @throws CTFReaderException
- * won't happen
- */
- @Before
- public void setUp() throws CTFReaderException {
- String name = "testString";
- StringDeclaration stringDec = new StringDeclaration();
- ByteBuffer byteBuffer = ByteBuffer.allocate(100);
- if (byteBuffer == null) {
- throw new IllegalStateException("Failed to allocate memory");
- }
- BitBuffer bb = new BitBuffer(byteBuffer);
- byteBuffer.mark();
- testString = new String("testString");
- byteBuffer.put(testString.getBytes());
- byteBuffer.reset();
- fixture = stringDec.createDefinition(null, name, bb);
- }
-
- /**
- * Run the StringDefinition(StringDeclaration,DefinitionScope,String)
- * constructor test.
- */
- @Test
- public void testStringDefinition() {
- StringDeclaration declaration = new StringDeclaration();
- IDefinitionScope definitionScope = null;
- String fieldName = "";
-
- StringDefinition result = new StringDefinition(declaration,
- definitionScope, fieldName, "");
-
- assertNotNull(result);
- }
-
- /**
- * Run the StringDeclaration getDeclaration() method test.
- */
- @Test
- public void testGetDeclaration() {
- StringDeclaration result = fixture.getDeclaration();
- assertNotNull(result);
- }
-
- /**
- * Run the String getValue() method test.
- */
- @Test
- public void testGetValue() {
- String result = fixture.getValue();
- assertNotNull(result);
- }
-
- /**
- * Run the String setValue() method test.
- */
- @Test
- public void testSetValue() {
-
- String result = fixture.getValue();
- assertNotNull(result);
- assertEquals("testString", result);
- }
-
- /**
- * Run the String toString() method test.
- */
- @Test
- public void testToString() {
- String result = fixture.toString();
- assertNotNull(result);
- }
-}
\ No newline at end of file
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.types;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-import java.nio.ByteBuffer;
-
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.types.IDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StringDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDefinition;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * The class <code>StructDeclarationTest</code> contains tests for the class
- * <code>{@link StructDeclaration}</code>.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-public class StructDeclarationTest {
-
- private StructDeclaration fixture;
-
- /**
- * Perform pre-test initialization.
- */
- @Before
- public void setUp() {
- fixture = new StructDeclaration(1L);
- }
-
- /**
- * Run the StructDeclaration(long) constructor test.
- */
- @Test
- public void testStructDeclaration() {
- assertNotNull(fixture);
- assertEquals(1L, fixture.getMaxAlign());
-
- String regex = "^\\[declaration\\] struct\\[[0-9a-f]{1,8}\\]$";
- assertTrue(fixture.toString().matches(regex));
- }
-
- /**
- * Run the void addField(String,Declaration) method test.
- */
- @Test
- public void testAddField() {
- String name = "";
- IDeclaration declaration = new StringDeclaration();
- fixture.addField(name, declaration);
- }
-
- /**
- * Run the StructDefinition createDefinition(DefinitionScope,String) method
- * test.
- *
- * @throws CTFReaderException
- * out of bounds
- */
- @Test
- public void testCreateDefinition() throws CTFReaderException {
- String fieldName = "";
- ByteBuffer allocate = ByteBuffer.allocate(100);
- if( allocate == null){
- throw new IllegalStateException("Failed to allocate memory");
- }
- BitBuffer bb = new BitBuffer(allocate);
- StructDefinition result = fixture.createDefinition(null, fieldName, bb);
- assertNotNull(result);
- }
-
- /**
- * Run the Declaration getField(String) method test.
- */
- @Test
- public void testGetField() {
- IDeclaration result = fixture.getField("test");
-
- assertNull(result);
- }
-
- /**
- * Run the List<String> getFieldsList() method test.
- */
- @Test
- public void testGetFieldsList() {
- Iterable<String> result = fixture.getFieldsList();
-
- assertNotNull(result);
- assertEquals(false, result.iterator().hasNext());
- }
-
- /**
- * Run the long getMinAlign() method test.
- */
- @Test
- public void testGetMinAlign() {
- long result = fixture.getMaxAlign();
- assertEquals(1L, result);
- }
-
- /**
- * Run the boolean hasField(String) method test.
- */
- @Test
- public void testHasField() {
- String name = "";
- boolean result = fixture.hasField(name);
-
- assertEquals(false, result);
- }
-
- /**
- * Run the String toString() method test.
- */
- @Test
- public void testToString() {
- String result = fixture.toString();
- String trunc = result.substring(0, 21);
-
- assertEquals("[declaration] struct[", trunc);
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.types;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-
-import java.nio.ByteBuffer;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.types.AbstractArrayDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.EnumDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.EnumDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.IDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.StringDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StringDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.VariantDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.VariantDefinition;
-import org.eclipse.linuxtools.ctf.core.tests.io.Util;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.internal.ctf.core.event.types.SequenceDeclaration;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * The class <code>StructDefinitionTest</code> contains tests for the class
- * <code>{@link StructDefinition}</code>.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-public class StructDefinitionTest {
-
- private static final @NonNull String TEST_STRUCT_ID = "testStruct";
- private static final @NonNull String ENUM_2 = "y";
- private static final @NonNull String ENUM_1 = "x";
- private static final @NonNull String TAG_ID = "Tag";
- private static final @NonNull String INT_ID = "_id";
- private static final @NonNull String STRING_ID = "_args";
- private static final @NonNull String ENUM_ID = "_enumArgs";
- private static final @NonNull String SEQUENCE_ID = "_seq";
- private static final @NonNull String LENGTH_SEQ = "_len";
- private static final @NonNull String VAR_FIELD_NAME = "SomeVariant";
-
- private StructDefinition fixture;
- private StructDefinition emptyStruct;
- private StructDefinition simpleStruct;
-
- /**
- * Perform pre-test initialization.
- *
- * @throws CTFReaderException
- * won't happen
- */
- @Before
- public void setUp() throws CTFReaderException {
- StructDeclaration sDec = new StructDeclaration(12);
- IntegerDeclaration id = IntegerDeclaration.INT_32B_DECL;
- IntegerDeclaration lenDec = IntegerDeclaration.UINT_8_DECL;
- StringDeclaration sd = new StringDeclaration();
- EnumDeclaration ed = new EnumDeclaration(id);
- SequenceDeclaration seqDec = new SequenceDeclaration(LENGTH_SEQ, id);
- VariantDeclaration varDec = new VariantDeclaration();
- EnumDeclaration tagDec = new EnumDeclaration(id);
- tagDec.add(0, 1, ENUM_1);
- tagDec.add(2, 3, ENUM_2);
- varDec.addField(ENUM_2, id);
- varDec.addField(ENUM_1, sd);
- varDec.setTag(TAG_ID);
- sDec.addField(INT_ID, id);
- sDec.addField(STRING_ID, sd);
- sDec.addField(ENUM_ID, ed);
- sDec.addField(TAG_ID, tagDec);
- sDec.addField(LENGTH_SEQ, lenDec);
- sDec.addField(SEQUENCE_ID, seqDec);
- sDec.addField(VAR_FIELD_NAME, varDec);
- byte bytes[] = new byte[100];
- bytes[4] = 1;
- bytes[8] = 2;
- bytes[13] = 3;
- BitBuffer bb = new BitBuffer(Util.testMemory(ByteBuffer.wrap(bytes)));
- fixture = sDec.createDefinition(null, TEST_STRUCT_ID, bb);
- EnumDefinition eDef = tagDec.createDefinition(fixture, TAG_ID, bb);
- assertNotNull(eDef);
- VariantDefinition vd = varDec.createDefinition(fixture, VAR_FIELD_NAME, bb);
- assertNotNull(vd);
- // Create an empty struct
- StructDeclaration esDec = new StructDeclaration(32);
- emptyStruct = esDec.createDefinition(null, TEST_STRUCT_ID, bb);
-
- // Create a simple struct with two items
- StructDeclaration ssDec = new StructDeclaration(32);
- ssDec.addField(INT_ID, id);
- ssDec.addField(STRING_ID, sd);
- simpleStruct = ssDec.createDefinition(null, TEST_STRUCT_ID, bb);
- }
-
- /**
- * Run the StructDeclaration getDeclaration() method test.
- */
- @Test
- public void testGetDeclaration() {
- StructDeclaration result = fixture.getDeclaration();
- assertNotNull(result);
- }
-
- /**
- * Run the HashMap<String, Definition> getDefinitions() method test.
- */
- @Test
- public void testGetDefinitions_1() {
- IDefinition result = fixture.getDefinition("_id");
- assertNotNull(result);
- }
-
- /**
- * Run the ArrayDefinition lookupArray(String) method test.
- */
- @Test
- public void testLookupArray() {
- String name = INT_ID;
- AbstractArrayDefinition result = fixture.lookupArrayDefinition(name);
- assertNull(result);
- }
-
- /**
- * Run the Definition lookupDefinition(String) method test.
- */
- @Test
- public void testLookupDefinition() {
- String lookupPath = "args";
- IDefinition result = fixture.lookupDefinition(lookupPath);
-
- assertNotNull(result);
- }
-
- /**
- * Run the EnumDefinition lookupEnum(String) method test.
- */
- @Test
- public void testLookupEnum() {
- String name = ENUM_ID;
- EnumDefinition result = fixture.lookupEnum(name);
- assertNotNull(result);
- }
-
- /**
- * Run the IntegerDefinition lookupInteger(String) method test.
- */
- @Test
- public void testLookupInteger_1() {
- String name = "_id";
- IntegerDefinition result = fixture.lookupInteger(name);
- assertNotNull(result);
- }
-
- /**
- * Run the IntegerDefinition lookupInteger(String) method test.
- */
- @Test
- public void testLookupInteger_2() {
- String name = VAR_FIELD_NAME;
- IntegerDefinition result = fixture.lookupInteger(name);
- assertNull(result);
- }
-
- /**
- * Run the SequenceDefinition lookupSequence(String) method test.
- */
- @Test
- public void testLookupFixedStringDefinition() {
- String name = SEQUENCE_ID;
- AbstractArrayDefinition result = fixture.lookupArrayDefinition(name);
- assertNotNull(result);
- }
-
- /**
- * Run the StringDefinition lookupString(String) method test.
- */
- @Test
- public void testLookupString() {
- String name = VAR_FIELD_NAME;
- StringDefinition result = fixture.lookupString(name);
-
- assertNull(result);
- }
-
- /**
- * Run the StructDefinition lookupStruct(String) method test.
- */
- @Test
- public void testLookupStruct() {
- String name = VAR_FIELD_NAME;
- StructDefinition result = fixture.lookupStruct(name);
-
- assertNull(result);
- }
-
- /**
- * Run the VariantDefinition lookupVariant(String) method test.
- */
- @Test
- public void testLookupVariant() {
- String name = VAR_FIELD_NAME;
- VariantDefinition result = fixture.lookupVariant(name);
-
- assertNotNull(result);
- }
-
- /**
- * Run the String toString() method test.
- */
- @Test
- public void testToString() {
- String result = fixture.toString();
- assertNotNull(result);
-
- result = emptyStruct.toString();
- assertEquals("{ }", result);
-
- result = simpleStruct.toString();
- assertEquals("{ _id = 0, _args = \"\" }", result);
- }
-}
\ No newline at end of file
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.types;
-
-import org.junit.runner.RunWith;
-import org.junit.runners.Suite;
-
-/**
- * The class <code>TestAll</code> builds a suite that can be used to run all of
- * the tests within its package as well as within any subpackages of its
- * package.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-@RunWith(Suite.class)
-@Suite.SuiteClasses({
- ArrayDeclaration2Test.class,
- ArrayDefinition2Test.class,
- DefinitionTest.class,
- EnumDeclarationTest.class,
- EnumDefinitionTest.class,
- EventDeclarationTest.class,
- EventHeaderDeclarationTest.class,
- FloatDeclarationTest.class,
- FloatDefinitionTest.class,
- IntegerDeclarationTest.class,
- IntegerDefinitionTest.class,
- IntegerEndiannessTest.class,
- SequenceDeclaration2Test.class,
- SequenceDefinition2Test.class,
- StringDeclarationTest.class,
- StringDefinitionTest.class,
- StructDeclarationTest.class,
- StructDefinitionTest.class,
- VariantDeclarationTest.class,
- VariantDefinitionTest.class,
-})
-public class TestAll {
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.types;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assume.assumeTrue;
-
-import java.nio.ByteBuffer;
-
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.event.types.Definition;
-import org.eclipse.linuxtools.ctf.core.event.types.EnumDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.EnumDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.IDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.StringDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StringDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.VariantDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.VariantDefinition;
-import org.eclipse.linuxtools.ctf.core.tests.shared.CtfTestTrace;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.junit.Before;
-import org.junit.Test;
-
-import com.google.common.collect.ImmutableList;
-
-/**
- * The class <code>VariantDeclarationTest</code> contains tests for the class
- * <code>{@link VariantDeclaration}</code>.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-public class VariantDeclarationTest {
-
- private static final CtfTestTrace testTrace = CtfTestTrace.KERNEL;
-
- private VariantDeclaration fixture;
-
- /**
- * Perform pre-test initialization.
- */
- @Before
- public void setUp() {
- fixture = new VariantDeclaration();
- }
-
- private static IDefinitionScope createDefinitionScope() throws CTFReaderException {
- assumeTrue(testTrace.exists());
- StructDeclaration declaration = new StructDeclaration(8);
- VariantDeclaration variantDeclaration = new VariantDeclaration();
- variantDeclaration.addField("a", IntegerDeclaration.INT_32B_DECL);
- variantDeclaration.addField("b", IntegerDeclaration.INT_32L_DECL);
- variantDeclaration.setTag("a");
-
- EnumDeclaration enumDeclaration = new EnumDeclaration(IntegerDeclaration.UINT_8_DECL);
- enumDeclaration.add(0, 1, "a");
- enumDeclaration.add(2, 2, "b");
- declaration.addField("tag", enumDeclaration);
- declaration.addField("variant", variantDeclaration);
- EnumDefinition tagDef = new EnumDefinition(
- enumDeclaration,
- null,
- "tag",
- new IntegerDefinition(
- IntegerDeclaration.UINT_8_DECL,
- null,
- "test",
- 0)
- );
- VariantDefinition variantDefinition = new VariantDefinition(
- variantDeclaration,
- testTrace.getTrace(),
- "tag",
- "tag",
- new StringDefinition(
- new StringDeclaration(),
- null,
- "f",
- "tag"
- ));
-
- IDefinitionScope definitionScope = new StructDefinition(
- declaration,
- variantDefinition,
- "",
- ImmutableList.of("tag", variantDefinition.getCurrentFieldName()),
- new Definition[] { tagDef, variantDefinition }
- );
-
- return definitionScope;
- }
-
- /**
- * Run the VariantDeclaration() constructor test.
- */
- @Test
- public void testVariantDeclaration() {
- assertNotNull(fixture);
- assertEquals(false, fixture.isTagged());
- String left = "[declaration] variant[";
- assertEquals(left, fixture.toString().substring(0, left.length()));
- }
-
- /**
- * Run the void addField(String,Declaration) method test.
- */
- @Test
- public void testAddField() {
- fixture.setTag("");
- String tag = "";
- IDeclaration declaration = new StringDeclaration();
- fixture.addField(tag, declaration);
- }
-
- /**
- * Run the VariantDefinition createDefinition(DefinitionScope,String) method
- * test.
- *
- * @throws CTFReaderException
- * Should not happen
- */
- @Test
- public void testCreateDefinition() throws CTFReaderException {
- fixture.setTag("tag");
- fixture.addField("a", IntegerDeclaration.UINT_64B_DECL);
- IDefinitionScope definitionScope = createDefinitionScope();
- String fieldName = "";
- ByteBuffer allocate = ByteBuffer.allocate(100);
- if( allocate == null){
- throw new IllegalStateException("Failed to allocate memory");
- }
- BitBuffer bb = new BitBuffer(allocate);
- VariantDefinition result = fixture.createDefinition(definitionScope, fieldName, bb);
-
- assertNotNull(result);
- }
-
- /**
- * Run the boolean hasField(String) method test.
- */
- @Test
- public void testHasField() {
- fixture.setTag("");
- String tag = "";
- boolean result = fixture.hasField(tag);
-
- assertEquals(false, result);
- }
-
- /**
- * Run the boolean isTagged() method test.
- */
- @Test
- public void testIsTagged() {
- fixture.setTag("");
- boolean result = fixture.isTagged();
-
- assertEquals(true, result);
- }
-
- /**
- * Run the boolean isTagged() method test.
- */
- @Test
- public void testIsTagged_null() {
- fixture.setTag((String) null);
- boolean result = fixture.isTagged();
-
- assertEquals(false, result);
- }
-
- /**
- * Run the void setTag(String) method test.
- */
- @Test
- public void testSetTag() {
- fixture.setTag("");
- String tag = "";
- fixture.setTag(tag);
- }
-
- /**
- * Run the String toString() method test.
- */
- @Test
- public void testToString() {
- fixture.setTag("");
- String result = fixture.toString();
- String left = "[declaration] variant[";
- String right = result.substring(0, left.length());
-
- assertEquals(left, right);
- }
-}
\ No newline at end of file
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013, 2014 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.tests.types;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.event.types.AbstractArrayDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.CompoundDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.Definition;
-import org.eclipse.linuxtools.ctf.core.event.types.Encoding;
-import org.eclipse.linuxtools.ctf.core.event.types.EnumDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.EnumDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.FloatDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.StringDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StringDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.VariantDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.VariantDefinition;
-import org.eclipse.linuxtools.ctf.core.tests.io.Util;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.internal.ctf.core.event.types.ArrayDeclaration;
-import org.junit.Before;
-import org.junit.Test;
-
-import com.google.common.collect.ImmutableList;
-
-/**
- * The class <code>VariantDefinitionTest</code> contains tests for the class
- * <code>{@link VariantDefinition}</code>.
- *
- * @author ematkho
- * @version $Revision: 1.0 $
- */
-public class VariantDefinitionTest {
-
- private VariantDefinition fixture;
-
- StructDefinition fStructDefinition;
- private static final @NonNull String TEST_STRUCT_ID = "testStruct";
- private static final @NonNull String ENUM_7 = "g";
- private static final @NonNull String ENUM_6 = "f";
- private static final @NonNull String ENUM_5 = "e";
- private static final @NonNull String ENUM_4 = "d";
- private static final @NonNull String ENUM_3 = "c";
- private static final @NonNull String ENUM_2 = "b";
- private static final @NonNull String ENUM_1 = "a";
- private static final @NonNull String TAG_ID = "a";
- private static final @NonNull String LENGTH_SEQ = "_len";
- private static final @NonNull String VAR_FIELD_NAME = "var";
- private static final @NonNull String ENUM_8 = "bbq ribs";
-
- /**
- * Perform pre-test initialization.
- *
- * Not sure it needs to be that complicated, oh well...
- *
- * @throws CTFReaderException
- * won't happen
- */
- @Before
- public void setUp() throws CTFReaderException {
- StructDeclaration sDec = new StructDeclaration(12);
- StructDeclaration smallStruct = new StructDeclaration(8);
- IntegerDeclaration iDec = IntegerDeclaration.createDeclaration(32, false, 32, ByteOrder.BIG_ENDIAN, Encoding.NONE, "", 8);
- IntegerDeclaration lenDec = IntegerDeclaration.createDeclaration(8, false, 8, ByteOrder.BIG_ENDIAN, Encoding.NONE, "", 8);
- StringDeclaration strDec = new StringDeclaration();
- EnumDeclaration enDec = new EnumDeclaration(iDec);
- VariantDeclaration varDec = new VariantDeclaration();
- EnumDeclaration tagDec = new EnumDeclaration(iDec);
- CompoundDeclaration arrDec = new ArrayDeclaration(2, iDec);
- FloatDeclaration fDec = new FloatDeclaration(8, 24, ByteOrder.BIG_ENDIAN, 8);
- tagDec.add(0, 1, ENUM_1);
- tagDec.add(2, 3, ENUM_2);
- tagDec.add(4, 5, ENUM_3);
- tagDec.add(8, 9, ENUM_5);
- tagDec.add(10, 11, ENUM_6);
- tagDec.add(12, 13, ENUM_7);
- varDec.addField(ENUM_4, lenDec);
- varDec.addField(ENUM_7, fDec);
- varDec.addField(ENUM_6, smallStruct);
- varDec.addField(ENUM_5, enDec);
- varDec.addField(ENUM_3, arrDec);
- varDec.addField(ENUM_2, iDec);
- varDec.addField(ENUM_1, strDec);
-
- sDec.addField(TAG_ID, tagDec);
- sDec.addField(LENGTH_SEQ, lenDec);
-
- sDec.addField(VAR_FIELD_NAME, varDec);
- varDec.setTag(TAG_ID);
-
- final ByteBuffer byteBuffer = Util.testMemory(ByteBuffer.allocate(100));
- BitBuffer bb = new BitBuffer(byteBuffer);
- byteBuffer.mark();
- byteBuffer.putInt(1);
- byteBuffer.putInt(2);
- byteBuffer.putInt(3);
- byteBuffer.reset();
- fStructDefinition = sDec.createDefinition(null, TEST_STRUCT_ID, bb);
- fixture = (VariantDefinition) fStructDefinition.getDefinition(VAR_FIELD_NAME);
- }
-
- /**
- * Run the VariantDefinition(VariantDeclaration,DefinitionScope,String)
- *
- * @throws CTFReaderException
- * should not happen
- */
- @Test
- public void testVariantDefinition() throws CTFReaderException {
- VariantDeclaration declaration = new VariantDeclaration();
- declaration.setTag("");
- VariantDeclaration variantDeclaration = new VariantDeclaration();
- variantDeclaration.addField("", new EnumDeclaration(IntegerDeclaration.INT_32B_DECL));
- variantDeclaration.addField("a", IntegerDeclaration.INT_64B_DECL);
- declaration.addField(ENUM_3, new StringDeclaration());
- variantDeclaration.setTag("a");
-
- byte[] bytes = new byte[128];
- ByteBuffer byb = ByteBuffer.wrap(bytes);
- byb.mark();
- byb.putInt(0);
- byb.putShort((short) 2);
- byb.put(new String("hello").getBytes());
- byb.reset();
- BitBuffer bb = new BitBuffer(byb);
- VariantDefinition variantDefinition = variantDeclaration.createDefinition(fStructDefinition, "field", bb);
- EnumDeclaration declaration2 = new EnumDeclaration(IntegerDeclaration.INT_8_DECL);
- declaration2.add(0, 2, ENUM_3);
- EnumDefinition enumDefinition = new EnumDefinition(
- declaration2,
- null,
- "a",
- new IntegerDefinition(
- IntegerDeclaration.INT_8_DECL,
- null,
- "A",
- 1
- ));
- IDefinitionScope definitionScope = new StructDefinition(
- new StructDeclaration(1L),
- variantDefinition,
- "",
- ImmutableList.<String> of("", "variant"),
- new Definition[] { enumDefinition, variantDefinition }
- );
- String fieldName = "";
- declaration.setTag("");
- VariantDefinition result = declaration.createDefinition(definitionScope, fieldName, bb);
- assertNotNull(result);
- }
-
- /**
- * Run the Definition getCurrentField() method test.
- */
- @Test
- public void testGetCurrentField() {
- IDefinition result = fixture.getCurrentField();
- assertNotNull(result);
- }
-
- /**
- * Run the String getCurrentFieldName() method test.
- */
- @Test
- public void testGetCurrentFieldName() {
- String result = fixture.getCurrentFieldName();
- assertNotNull(result);
- }
-
- /**
- * Run the VariantDeclaration getDeclaration() method test.
- */
- @Test
- public void testGetDeclaration() {
- VariantDeclaration result = fixture.getDeclaration();
- assertNotNull(result);
- }
-
- /**
- * Run the HashMap<String, Definition> getDefinitions() method test.
- */
- @Test
- public void testGetDefinitions() {
- IDefinition result = fixture.getCurrentField();
- assertNotNull(result);
- }
-
- /**
- * Run the String getPath() method test.
- */
- @Test
- public void testGetPath() {
- String result = fixture.getScopePath().toString();
- assertNotNull(result);
- }
-
- /**
- * Run the ArrayDefinition lookupArray(String) method test.
- */
- @Test
- public void testLookupArray() {
- AbstractArrayDefinition result = fixture.lookupArrayDefinition(ENUM_3);
- assertNull(result);
- }
-
- /**
- * Run the Definition lookupDefinition(String) method test.
- */
- @Test
- public void testLookupDefinition() {
- IDefinition result = fixture.lookupDefinition(ENUM_1);
- assertNotNull(result);
- assertEquals("a", ((EnumDefinition) result).getStringValue());
- }
-
- /**
- * Run the EnumDefinition lookupEnum(String) method test.
- */
- @Test
- public void testLookupEnum() {
- EnumDefinition result = fixture.lookupEnum(ENUM_5);
- assertNull(result);
- }
-
- /**
- * Run the IntegerDefinition lookupInteger(String) method test.
- */
- @Test
- public void testLookupInteger() {
- IntegerDefinition result = fixture.lookupInteger(ENUM_2);
- assertNull(result);
- }
-
- /**
- * Run the StringDefinition lookupString(String) method test.
- */
- @Test
- public void testLookupString() {
- StringDefinition result = fixture.lookupString(ENUM_1);
- assertNull(result);
- }
-
- /**
- * Run the StructDefinition lookupStruct(String) method test.
- */
- @Test
- public void testLookupStruct() {
- StructDefinition result = fixture.lookupStruct(ENUM_6);
- assertNull(result);
- }
-
- /**
- * Run the VariantDefinition lookupVariant(String) method test.
- */
- @Test
- public void testLookupVariant() {
- VariantDefinition result = fixture.lookupVariant(ENUM_8);
- assertNull(result);
- }
-
- /**
- * Run the String toString() method test.
- */
- @Test
- public void testToString() {
- String result = fixture.toString();
- assertEquals("{ a = \"\" }", result);
- }
-}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests;
+
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+
+/**
+ * The class <code>TestAll</code> builds a suite that can be used to run all of
+ * the tests within its package as well as within any subpackages of its
+ * package.
+ *
+ * @author ematkho
+ * @version 1.0
+ */
+@RunWith(Suite.class)
+@Suite.SuiteClasses({
+ CtfCorePluginTest.class,
+ org.eclipse.tracecompass.ctf.core.tests.ctftestsuite.TestAll.class,
+ org.eclipse.tracecompass.ctf.core.tests.event.TestAll.class,
+ org.eclipse.tracecompass.ctf.core.tests.io.TestAll.class,
+ org.eclipse.tracecompass.ctf.core.tests.scope.TestAll.class,
+ org.eclipse.tracecompass.ctf.core.tests.trace.TestAll.class,
+ org.eclipse.tracecompass.ctf.core.tests.types.TestAll.class
+})
+public class AllCtfCoreTests {
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2013 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are
+ * made available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Francois Chouinard - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import org.eclipse.tracecompass.internal.ctf.core.Activator;
+import org.junit.Test;
+
+/**
+ * <b><u>CtfCorePluginTest</u></b>
+ * <p>
+ * Test the CTF core plug-in activator
+ */
+@SuppressWarnings("javadoc")
+public class CtfCorePluginTest {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ // Plug-in instantiation
+ private final static Activator fPlugin = Activator.getDefault();
+
+
+ // ------------------------------------------------------------------------
+ // Test cases
+ // ------------------------------------------------------------------------
+
+ @Test
+ public void testCtfCorePluginId() {
+ assertEquals(
+ "Plugin ID", "org.eclipse.linuxtools.ctf", Activator.PLUGIN_ID);
+ }
+
+ @Test
+ public void testGetDefault() {
+ Activator plugin = Activator.getDefault();
+ assertEquals("getDefault()", plugin, fPlugin);
+ }
+
+ @Test
+ public void testLog() {
+ try {
+ Activator.log("Some message");
+ } catch (Exception e) {
+ fail();
+ }
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are
+ * made available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Alexandre Montplaisir - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests;
+
+import java.io.File;
+import java.net.URISyntaxException;
+
+import org.eclipse.core.runtime.Plugin;
+import org.eclipse.core.runtime.URIUtil;
+import org.eclipse.tracecompass.internal.ctf.core.Activator;
+import org.osgi.framework.BundleContext;
+
+/**
+ * The activator class controls the plug-in life cycle
+ */
+public class CtfCoreTestPlugin extends Plugin {
+
+ private static final String TEMP_DIR_NAME = ".temp"; //$NON-NLS-1$
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ /** The plug-in ID */
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.ctf.core.tests";
+
+ // The shared instance
+ private static CtfCoreTestPlugin fPlugin;
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * The constructor
+ */
+ public CtfCoreTestPlugin() {
+ setDefault(this);
+ }
+
+ // ------------------------------------------------------------------------
+ // Accessors
+ // ------------------------------------------------------------------------
+
+ /**
+ * @return the shared instance
+ */
+ public static CtfCoreTestPlugin getDefault() {
+ return fPlugin;
+ }
+
+ /**
+ * @param plugin
+ * the shared instance
+ */
+ private static void setDefault(CtfCoreTestPlugin plugin) {
+ fPlugin = plugin;
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ @Override
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ setDefault(this);
+ }
+
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ setDefault(null);
+ super.stop(context);
+ }
+
+ /**
+ * Get the temporary directory path. If there is an instance of Eclipse
+ * running, the temporary directory will reside under the workspace.
+ *
+ * @return the temporary directory path suitable to be passed to the
+ * java.io.File constructor without a trailing separator
+ */
+ public static String getTemporaryDirPath() {
+ String property = System.getProperty("osgi.instance.area"); //$NON-NLS-1$
+ if (property != null) {
+ try {
+ File dir = URIUtil.toFile(URIUtil.fromString(property));
+ dir = new File(dir.getAbsolutePath() + File.separator + TEMP_DIR_NAME);
+ if (!dir.exists()) {
+ dir.mkdirs();
+ }
+ return dir.getAbsolutePath();
+ } catch (URISyntaxException e) {
+ Activator.logError(e.getLocalizedMessage(), e);
+ }
+ }
+ return System.getProperty("java.io.tmpdir"); //$NON-NLS-1$
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013, 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are
+ * made available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Alexandre Montplaisir - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.ctftestsuite;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
+
+import java.io.File;
+import java.util.LinkedList;
+import java.util.List;
+
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTrace;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTraceReader;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestRule;
+import org.junit.rules.Timeout;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameters;
+
+/**
+ * Parameterized test class running the CTF Test Suite
+ *
+ * (from https://github.com/efficios/ctf-testsuite).
+ *
+ * @author Alexandre Montplaisir
+ */
+@RunWith(Parameterized.class)
+public class CtfTestSuiteTests {
+
+ /** Time-out tests after 10 seconds. */
+ @Rule
+ public TestRule globalTimeout = new Timeout(10000);
+
+ private static final String BASE_PATH = "traces/ctf-testsuite/tests/1.8/";
+
+ /**
+ * Test we know are currently failing. Ignore them so we can at least run
+ * the others.
+ *
+ * TODO Actually fix them!
+ */
+ private static final String[] IGNORED_TESTS = {
+ "regression/metadata/pass/sequence-typedef-length",
+ "regression/metadata/pass/array-of-struct"
+ };
+
+ private final String fTracePath;
+ private final boolean fExpectSuccess;
+
+ // ------------------------------------------------------------------------
+ // Methods for the Parametrized runner
+ // ------------------------------------------------------------------------
+
+ /**
+ * Get the existing trace paths in the CTF-Testsuite git tree.
+ *
+ * @return The list of CTF traces (directories) to test
+ */
+ @Parameters(name = "{index}: {0}")
+ public static Iterable<Object[]> getTracePaths() {
+ final List<Object[]> dirs = new LinkedList<>();
+
+ addDirsFrom(dirs, BASE_PATH + "fuzzing/metadata/fail", false);
+ addDirsFrom(dirs, BASE_PATH + "fuzzing/metadata/pass", true);
+ addDirsFrom(dirs, BASE_PATH + "fuzzing/stream/fail", false);
+ addDirsFrom(dirs, BASE_PATH + "fuzzing/stream/pass", true);
+
+ addDirsFrom(dirs, BASE_PATH + "regression/metadata/fail", false);
+ addDirsFrom(dirs, BASE_PATH + "regression/metadata/pass", true);
+ addDirsFrom(dirs, BASE_PATH + "regression/stream/fail", false);
+ addDirsFrom(dirs, BASE_PATH + "regression/stream/pass", true);
+
+ addDirsFrom(dirs, BASE_PATH + "stress/metadata/fail", false);
+ addDirsFrom(dirs, BASE_PATH + "stress/metadata/pass", true);
+ addDirsFrom(dirs, BASE_PATH + "stress/stream/fail", false);
+ addDirsFrom(dirs, BASE_PATH + "stress/stream/pass", true);
+
+ return dirs;
+ }
+
+ private static void addDirsFrom(List<Object[]> dirs, String path, boolean expectSuccess) {
+ File[] traceDirs = (new File(path)).listFiles();
+ if (traceDirs == null) {
+ return;
+ }
+ for (File traceDir : traceDirs) {
+ /* Skip the "run.sh" files and blacklisted tests */
+ if (!traceDir.isDirectory() || testIsBlacklisted(traceDir.getPath())) {
+ continue;
+ }
+
+ /* Add this test case to the list of tests to run */
+ Object array[] = new Object[] { traceDir.getPath(), expectSuccess };
+ dirs.add(array);
+ }
+ }
+
+ private static boolean testIsBlacklisted(String fullPath) {
+ for (String ignoredTest : IGNORED_TESTS) {
+ if (fullPath.contains(new File(ignoredTest).getPath())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // ------------------------------------------------------------------------
+ // Test constructor
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructor for the parametrized tests
+ *
+ * @param tracePath
+ * The complete path to the trace to test
+ * @param expectSuccess
+ * Should this trace parse successfully, or not.
+ */
+ public CtfTestSuiteTests(String tracePath, boolean expectSuccess) {
+ fTracePath = tracePath;
+ fExpectSuccess = expectSuccess;
+ }
+
+ // ------------------------------------------------------------------------
+ // Test methods
+ // ------------------------------------------------------------------------
+
+ /**
+ * Test opening and reading the trace
+ */
+ @Test
+ public void testTrace() {
+ try (/* Instantiate the trace (which implies parsing the metadata) */
+ CTFTrace trace = new CTFTrace(fTracePath);
+ /* Read the trace until the end */
+ CTFTraceReader reader = new CTFTraceReader(trace);) {
+
+ reader.getCurrentEventDef();
+ while (reader.advance()) {
+ assertNotNull(reader.getCurrentEventDef());
+ }
+
+ checkIfWeShoudlSucceed();
+ } catch (CTFReaderException e) {
+ checkIfWeShouldFail(e);
+ } catch (OutOfMemoryError e) {
+ checkIfWeShouldFail(e);
+ }
+ }
+
+ private void checkIfWeShoudlSucceed() {
+ if (!fExpectSuccess) {
+ fail("Trace was expected to fail parsing: " + fTracePath);
+ }
+ }
+
+ private void checkIfWeShouldFail(Throwable e) {
+ if (fExpectSuccess) {
+ fail("Trace was expected to succeed, but failed parsing: " +
+ fTracePath + " (" + e.getMessage() + ")");
+ }
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013, 2014 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Alexandre Montplaisir - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.ctftestsuite;
+
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+
+/**
+ * The class <code>TestAll</code> builds a suite that can be used to run all of
+ * the tests within its package as well as within any subpackages of its
+ * package.
+ *
+ * @author ematkho
+ */
+@RunWith(Suite.class)
+@Suite.SuiteClasses({
+ CtfTestSuiteTests.class
+})
+public class TestAll {
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013, 2014 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.event;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.eclipse.tracecompass.ctf.core.event.CTFCallsite;
+import org.junit.Test;
+
+/**
+ * The class <code>CTFCallsiteTest</code> contains tests for the class
+ * <code>{@link CTFCallsite}</code>.
+ *
+ * @author Matthew Khouzam
+ * @version $Revision: 1.0 $
+ */
+
+public class CTFCallsiteTest {
+
+ private static CTFCallsite GenerateCS(long ip){
+ return new CTFCallsite("event name", "func name", ip, "file.java", 1);
+ }
+
+ /**
+ * Test the constructor
+ */
+ @Test
+ public void constructorTest(){
+ CTFCallsite cs = GenerateCS(0x01);
+ assertNotNull(cs);
+ }
+
+ /**
+ * Test the getters
+ */
+ @Test
+ public void getterTest(){
+ CTFCallsite cs = GenerateCS(0x01);
+ assertEquals("ip", 1, cs.getIp());
+ assertEquals("ip", "event name", cs.getEventName());
+ assertEquals("ip", "file.java", cs.getFileName());
+ assertEquals("ip", "func name", cs.getFunctionName());
+ }
+
+ /**
+ * Test the hash code
+ */
+ @Test
+ public void hashCodeTest(){
+ CTFCallsite cs = GenerateCS(0x01);
+ Map<CTFCallsite, Object> test = new HashMap<>();
+ test.put(cs, new Object());
+ assertTrue(test.containsKey(cs));
+ assertTrue(test.containsKey(GenerateCS(0x01)));
+ assertFalse(test.containsKey(GenerateCS(0x02)));
+ assertFalse(test.containsKey(new CTFCallsite("event nam", "func name", 1, "file.java", 1)));
+ assertFalse(test.containsKey(new CTFCallsite("event name", "func nam", 1, "file.java", 1)));
+ assertFalse(test.containsKey(new CTFCallsite("event name", "func name", 1, "file.jav", 1)));
+ assertFalse(test.containsKey(new CTFCallsite("event name", "func name", 1, "file.java", 2)));
+ }
+
+ /**
+ * Test the comparator (it should sort using the IP)
+ */
+ @Test
+ public void comparatorTest(){
+ CTFCallsite cs[] = new CTFCallsite[5];
+ long vals[] = {1L, 0L, -2L, 2L, -1L};
+ for(int i = 0 ; i < 5 ; i++ ){
+ cs[i] = GenerateCS(vals[i]);
+ }
+
+ assertEquals(1, cs[0].compareTo(cs[1]));
+ assertEquals(-1, cs[1].compareTo(cs[0]));
+ assertEquals(0, cs[0].compareTo(cs[0]));
+ assertEquals(-1, cs[0].compareTo(cs[2]));
+ assertEquals(1, cs[2].compareTo(cs[0]));
+
+ Arrays.sort(cs);
+
+ assertEquals( 0L, cs[0].getIp());
+ assertEquals( 1L, cs[1].getIp());
+ assertEquals( 2L, cs[2].getIp());
+ assertEquals( -2L , cs[3].getIp());
+ assertEquals( -1L, cs[4].getIp());
+ }
+
+ /**
+ * Tests the output of a callsite toString function
+ */
+ @Test
+ public void toStringTest(){
+ CTFCallsite cs = GenerateCS(0x01);
+ assertEquals("file.java/func name:1", cs.toString());
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.event;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+import java.nio.ByteOrder;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import org.eclipse.tracecompass.ctf.core.event.EventDefinition;
+import org.eclipse.tracecompass.ctf.core.event.scope.LexicalScope;
+import org.eclipse.tracecompass.ctf.core.event.types.Definition;
+import org.eclipse.tracecompass.ctf.core.event.types.Encoding;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDefinition;
+import org.eclipse.tracecompass.internal.ctf.core.event.EventDeclaration;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * Test the event definition
+ *
+ * @author Matthew Khouzam
+ *
+ */
+public class CTFEventDefinitionTest {
+ List<EventDefinition> fixture;
+
+ /**
+ * Making a power set of configurations to test the event definition
+ */
+ @Before
+ public void init() {
+ fixture = new ArrayList<>();
+ IntegerDeclaration pidDec = IntegerDeclaration.createDeclaration(5, false, 10, ByteOrder.LITTLE_ENDIAN, Encoding.NONE, "", 8);
+ IntegerDeclaration ctxDec = IntegerDeclaration.createDeclaration(16, false, 10, ByteOrder.LITTLE_ENDIAN, Encoding.NONE, "", 8);
+ IntegerDefinition pid = new IntegerDefinition(pidDec, null, "pid", 3);
+ IntegerDefinition pod = new IntegerDefinition(pidDec, null, "pod", 3);
+ IntegerDefinition ctx = new IntegerDefinition(pidDec, null, "ctx", 3);
+
+ StructDeclaration streamContextDec = new StructDeclaration(8);
+ streamContextDec.addField("pid", pidDec);
+ streamContextDec.addField("ctx", ctxDec);
+ StructDeclaration eventContextDec = new StructDeclaration(8);
+ streamContextDec.addField("pod", pidDec);
+ streamContextDec.addField("ctx", pidDec);
+ StructDeclaration fDec = new StructDeclaration(8);
+ EventDeclaration eventDeclaration = new EventDeclaration();
+
+ fDec.addField("pid", pidDec);
+ fDec.addField("ctx", ctxDec);
+ fDec.addField("pod", pidDec);
+
+ List<String> sFieldNames = Arrays.asList("pid", "ctx");
+ List<String> eFieldNames = Arrays.asList("pod", "ctx");
+ List<String> fieldNames = Arrays.asList("pid", "ctx", "pod");
+
+ Definition[] sDefs = { pid, ctx };
+ Definition[] eDefs = { pod, ctx };
+ Definition[] fDefs = { pid, ctx, pod };
+
+ StructDeclaration pContextDec = new StructDeclaration(8);
+
+ StructDefinition sContext = new StructDefinition(streamContextDec, null, LexicalScope.STREAM_PACKET_CONTEXT.toString(), sFieldNames, sDefs);
+ StructDefinition eContext = new StructDefinition(eventContextDec, null, LexicalScope.STREAM_EVENT_CONTEXT.toString(), eFieldNames, eDefs);
+ StructDefinition pContext = new StructDefinition(pContextDec, null, LexicalScope.FIELDS.toString(), Collections.EMPTY_LIST, new Definition[0]);
+ StructDefinition fields = new StructDefinition(fDec, null, LexicalScope.FIELDS.toString(), fieldNames, fDefs);
+
+ fixture.add(new EventDefinition(eventDeclaration, null, 100, null, null, null, null));
+ fixture.add(new EventDefinition(eventDeclaration, null, 100, null, null, null, fields));
+ fixture.add(new EventDefinition(eventDeclaration, null, 100, null, null, pContext, null));
+ fixture.add(new EventDefinition(eventDeclaration, null, 100, null, null, pContext, fields));
+ fixture.add(new EventDefinition(eventDeclaration, null, 100, null, eContext, null, null));
+ fixture.add(new EventDefinition(eventDeclaration, null, 100, null, eContext, null, fields));
+ fixture.add(new EventDefinition(eventDeclaration, null, 100, null, eContext, pContext, null));
+ fixture.add(new EventDefinition(eventDeclaration, null, 100, null, eContext, pContext, fields));
+ fixture.add(new EventDefinition(eventDeclaration, null, 100, sContext, null, null, null));
+ fixture.add(new EventDefinition(eventDeclaration, null, 100, sContext, null, null, fields));
+ fixture.add(new EventDefinition(eventDeclaration, null, 100, sContext, null, pContext, null));
+ fixture.add(new EventDefinition(eventDeclaration, null, 100, sContext, null, pContext, fields));
+ fixture.add(new EventDefinition(eventDeclaration, null, 100, sContext, eContext, null, null));
+ fixture.add(new EventDefinition(eventDeclaration, null, 100, sContext, eContext, null, fields));
+ fixture.add(new EventDefinition(eventDeclaration, null, 100, sContext, eContext, pContext, null));
+ fixture.add(new EventDefinition(eventDeclaration, null, 100, sContext, eContext, pContext, fields));
+ }
+
+ /**
+ * Test all the events
+ */
+ @Test
+ public void testEvents() {
+ int i = 0;
+ for (EventDefinition ed : fixture) {
+ test(i, ed);
+ i++;
+ }
+ }
+
+ private static void test(int rank, EventDefinition ed) {
+ String title = "event #" + rank;
+ assertEquals(title, 100L, ed.getTimestamp());
+ StructDefinition context = ed.getContext();
+ if (rank >= 4) {
+ assertNotNull(title, context);
+ if (rank >= 12) {
+ assertEquals(title, 3, context.getFieldNames().size());
+ } else {
+ assertEquals(title, 2, context.getFieldNames().size());
+ }
+
+ } else {
+ assertNull(title, context);
+ }
+ if (((rank / 4) % 2) == 1) {
+ assertNotNull(title, ed.getEventContext());
+ }else{
+ assertNull(title, ed.getEventContext());
+ }
+ if (rank % 2 == 1) {
+ assertNotNull(title, ed.getFields());
+ assertEquals(title, 3, ed.getFields().getFieldNames().size());
+ } else {
+ assertNull(title, ed.getFields());
+ }
+ assertTrue(title, ed.toString().startsWith("Event type: null" + System.getProperty("line.separator") + "Timestamp: 100"));
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.event;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.types.Definition;
+import org.eclipse.tracecompass.ctf.core.event.types.Encoding;
+import org.eclipse.tracecompass.ctf.core.event.types.IDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.StringDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StringDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDefinition;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.internal.ctf.core.event.types.SequenceDeclaration;
+import org.junit.Test;
+
+import com.google.common.collect.ImmutableList;
+
+/**
+ * The class <code>CTFEventFieldTest</code> contains tests for the class
+ * <code>{@link CTFEventField}</code>.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+@SuppressWarnings("javadoc")
+public class CTFEventFieldTest {
+
+ @NonNull
+ private static final String fieldName = "id";
+
+ /**
+ * Run the CTFEventField parseField(Definition,String) method test.
+ *
+ * @throws CTFReaderException
+ */
+ @Test
+ public void testParseField_complex() throws CTFReaderException {
+ int len = 32;
+ IntegerDeclaration id = IntegerDeclaration.createDeclaration(
+ len,
+ false,
+ len,
+ ByteOrder.LITTLE_ENDIAN,
+ Encoding.ASCII,
+ "",
+ len);
+ String lengthName = "LengthName";
+ StructDeclaration structDec = new StructDeclaration(0);
+ structDec.addField(lengthName, id);
+ StructDefinition structDef = new StructDefinition(
+ structDec,
+ null,
+ lengthName,
+ ImmutableList.of(lengthName),
+ new Definition[] {
+ new IntegerDefinition(
+ id,
+ null,
+ lengthName,
+ 32)
+ });
+
+ SequenceDeclaration sd = new SequenceDeclaration(lengthName, id);
+ ByteBuffer byb = testMemory(ByteBuffer.allocate(1024));
+ for (int i = 0; i < 1024; i++) {
+ byb.put((byte) i);
+ }
+ BitBuffer bb = new BitBuffer(byb);
+ IDefinition fieldDef = sd.createDefinition(structDef, "fff-fffield", bb);
+
+ assertNotNull(fieldDef);
+ }
+
+ @NonNull
+ private static ByteBuffer testMemory(ByteBuffer buffer) {
+ if (buffer == null) {
+ throw new IllegalStateException("Failed to allocate memory");
+ }
+ return buffer;
+ }
+
+ /**
+ * Run the CTFEventField parseField(Definition,String) method test.
+ *
+ * @throws CTFReaderException
+ */
+ @Test
+ public void testParseField_simple() throws CTFReaderException {
+ final StringDeclaration elemType = new StringDeclaration();
+ byte[] bytes = { 'T', 'e', 's', 't', '\0' };
+ ByteBuffer bb = testMemory(ByteBuffer.wrap(bytes));
+ IDefinition fieldDef = elemType.createDefinition(null, fieldName, new BitBuffer(bb));
+
+ assertNotNull(fieldDef);
+ }
+
+ /**
+ * Run the CTFEventField parseField(Definition,String) method test.
+ */
+ @Test
+ public void testParseField_simple2() {
+ IntegerDefinition fieldDef = new IntegerDefinition(
+ IntegerDeclaration.createDeclaration(1, false, 1, ByteOrder.BIG_ENDIAN,
+ Encoding.ASCII, "", 8), null, fieldName, 1L);
+
+ assertNotNull(fieldDef);
+ }
+
+ /**
+ *
+ */
+ @Test
+ public void testParseField_simple3() {
+ StringDefinition fieldDef = new StringDefinition(
+ new StringDeclaration(), null, fieldName, "Hello World");
+
+ String other = "\"Hello World\"";
+ assertNotNull(fieldDef);
+ assertEquals(fieldDef.toString(), other);
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013, 2014 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.event;
+
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+
+/**
+ * The class <code>TestAll</code> builds a suite that can be used to run all of
+ * the tests within its package as well as within any subpackages of its
+ * package.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+@RunWith(Suite.class)
+@Suite.SuiteClasses({
+ CTFCallsiteTest.class,
+ CTFEventDefinitionTest.class,
+ CTFEventFieldTest.class
+})
+public class TestAll {
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013, 2014 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Alexandre Montplaisir - Extracted from BitBufferTest, cleanup
+ * Matthew Khouzam - Additional tests
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.io;
+
+import static org.junit.Assert.assertEquals;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * Part of the {@link BitBuffer} tests which test the methods to read/write
+ * integers. These are separated from the main file because the fixture is
+ * different.
+ *
+ * @author Alexandre Montplaisir
+ */
+public class BitBufferIntTest {
+
+ private BitBuffer fixture;
+
+ /**
+ * Perform pre-test initialization.
+ *
+ * @throws CTFReaderException
+ * Out of bounds, won't happen
+ */
+ @Before
+ public void setUp() throws CTFReaderException {
+ ByteBuffer allocateDirect = ByteBuffer.allocateDirect(128);
+ if (allocateDirect == null) {
+ throw new IllegalStateException("Failed to allocate memory");
+ }
+ fixture = new BitBuffer(allocateDirect);
+ fixture.setByteOrder(ByteOrder.BIG_ENDIAN);
+ fixture = createBuffer();
+ }
+
+ private static BitBuffer createBuffer() throws CTFReaderException {
+ return createBuffer(16);
+ }
+
+ private static BitBuffer createBuffer(int j) throws CTFReaderException {
+ final byte[] bytes = new byte[j];
+ for (int i = 0; i < j; i++) {
+ bytes[i] = (byte) (i % 0xff);
+ }
+ ByteBuffer wrap = ByteBuffer.wrap(bytes);
+ if (wrap == null) {
+ throw new IllegalStateException("Failed to allocate memory");
+ }
+ BitBuffer fixture = new BitBuffer(wrap);
+ fixture.position(1);
+ return fixture;
+ }
+
+ /**
+ * Test {@link BitBuffer#getInt} with a basic value
+ *
+ * @throws CTFReaderException
+ * Not expected
+ */
+ @Test
+ public void testGetInt_base() throws CTFReaderException {
+ int result = fixture.getInt();
+ assertEquals(0x020406, result);
+ }
+
+ /**
+ * Test {@link BitBuffer#getInt} with explicit seek at pos 0.
+ *
+ * @throws CTFReaderException
+ * Not expected
+ */
+ @Test
+ public void testGetInt_pos0() throws CTFReaderException {
+ fixture.position(0);
+ int result = fixture.getInt();
+ assertEquals(0x010203, result);
+ }
+
+ /**
+ * Test {@link BitBuffer#get} with seek at pos 1.
+ *
+ * @throws CTFReaderException
+ * Not expected
+ */
+ @Test
+ public void testGetInt_pos1() throws CTFReaderException {
+ fixture.position(1);
+
+ long result = fixture.get(1, true);
+ assertEquals(0, result);
+ }
+
+ /**
+ * Test {@link BitBuffer#get} with seek at pos 2.
+ *
+ * @throws CTFReaderException
+ * Not expected
+ */
+ @Test
+ public void testGetInt_pos2() throws CTFReaderException {
+ fixture.position(2);
+
+ long result = fixture.get(0, true);
+ assertEquals(0, result);
+ }
+
+ /**
+ * Test {@link BitBuffer#get} with explicit little-endian reading.
+ *
+ * @throws CTFReaderException
+ * Not expected
+ */
+ @Test
+ public void testGetInt_le2() throws CTFReaderException {
+ BitBuffer leFixture = createBuffer(128);
+ leFixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
+ leFixture.position(0);
+ long result = leFixture.get(24, false);
+ assertEquals(0x020100, result);
+ }
+
+ /**
+ * Test {@link BitBuffer#get} with explicit little-endian reading, with an
+ * offset.
+ *
+ * @throws CTFReaderException
+ * Not expected
+ */
+ @Test
+ public void testGetInt_le1() throws CTFReaderException {
+ BitBuffer leFixture = createBuffer(128);
+ leFixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
+ leFixture.position(1);
+ long result = leFixture.get(24, false);
+ assertEquals(0x810080, result); /* 0x020100 down-shifted */
+ }
+
+ /**
+ * Test {@link BitBuffer#get} with a 32-bit out-of-bounds read. Should throw
+ * an exception.
+ *
+ * @throws CTFReaderException
+ * Expected
+ */
+ @Test(expected = CTFReaderException.class)
+ public void testGetInt_invalid() throws CTFReaderException {
+ BitBuffer smallFixture = createBuffer(2);
+ smallFixture.setByteOrder(ByteOrder.BIG_ENDIAN);
+
+ smallFixture.position(10);
+
+ /* This will attempt to read past the buffer's end. */
+ smallFixture.get(32, true);
+ }
+
+ /**
+ * Test {@link BitBuffer#get} with a 64-bit out-of-bounds read. Should throw
+ * an exception.
+ *
+ * @throws CTFReaderException
+ * Expected
+ */
+ @Test(expected = CTFReaderException.class)
+ public void testGetInt_invalid2() throws CTFReaderException {
+ BitBuffer smallFixture = createBuffer(2);
+ smallFixture.setByteOrder(ByteOrder.BIG_ENDIAN);
+
+ smallFixture.position(1);
+
+ /* This will attempt to read past the buffer's end. */
+ smallFixture.get(64, true);
+ }
+
+ /**
+ * Test {@link BitBuffer#getLong}.
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void testGetLong_pos0() throws CTFReaderException {
+ fixture.position(0);
+ long result = fixture.getLong();
+ assertEquals(0x01020304050607L, result);
+ }
+
+ /**
+ * Test {@link BitBuffer#getLong} with an offset of 7.
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void testGetLong_pos7() throws CTFReaderException {
+ fixture.position(7);
+ long result = fixture.getLong();
+ assertEquals(0x81018202830384L, result);
+ }
+
+ /**
+ * Test {@link BitBuffer#getLong} with an offset of 8.
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void testGetLong_pos8() throws CTFReaderException {
+ fixture.position(8);
+ long result = fixture.getLong();
+ assertEquals(0x0102030405060708L, result);
+ }
+
+ /**
+ * Test {@link BitBuffer#getLong} with a little-endian buffer.
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void testGetLong_pos0LE() throws CTFReaderException {
+ fixture.position(0);
+ fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
+ long result = fixture.getLong();
+ assertEquals(0x0706050403020100L, result);
+ }
+
+ /**
+ * Test {@link BitBuffer#getLong} with a little-endian buffer at pos 7.
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void testGetLong_pos7LE() throws CTFReaderException {
+ fixture.position(7);
+ fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
+ long result = fixture.getLong();
+ assertEquals(0x100e0c0a08060402L, result);
+ }
+
+ /**
+ * Test {@link BitBuffer#getLong} with a little-endian buffer at pos 8.
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void testGetLong_pos8LE() throws CTFReaderException {
+ fixture.position(8);
+ fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
+ long result = fixture.getLong();
+ assertEquals(0x0807060504030201L, result);
+ }
+
+ /**
+ * Test {@link BitBuffer#get} for >32 bits in length.
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void testGet35_pos0BE() throws CTFReaderException {
+ fixture.position(0);
+ long result = fixture.get(35, false);
+ assertEquals(0x081018L, result);
+ }
+
+ /**
+ * Test {@link BitBuffer#get} for >32 bits in length at an offset position.
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void testGet35_pos8BE() throws CTFReaderException {
+ fixture.position(8);
+ long result = fixture.get(35, false);
+ assertEquals(0x08101820L, result);
+ }
+
+ /**
+ * Test {@link BitBuffer#get} for >32 bits in length in little-endian.
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void testGet35_pos0LE() throws CTFReaderException {
+ fixture.position(0);
+ fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
+ long result = fixture.get(35, false);
+ assertEquals(0x0403020100L, result);
+ }
+
+ /**
+ * Test {@link BitBuffer#get} for >32 bits in length, in little-endian, at
+ * position 7.
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void testGetLong35_pos7LE() throws CTFReaderException {
+ fixture.position(7);
+ fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
+ long result = fixture.get(35, false);
+ assertEquals(0x0208060402L, result);
+ }
+
+ /**
+ * Test {@link BitBuffer#get} for >32 bits in length, in little-endian, at
+ * position 8.
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void testGetLong35_pos8LE() throws CTFReaderException {
+ fixture.position(8);
+ fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
+ long result = fixture.get(35, false);
+ assertEquals(0x0504030201L, result);
+ }
+
+ /**
+ * Test {@link BitBuffer#get} for >32 bits in length, in little-endian, for
+ * a signed value.
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void testGetLong35s_pos0LE() throws CTFReaderException {
+ fixture.position(0);
+ fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
+ long result = fixture.get(35, true);
+ assertEquals(0xfffffffc03020100L, result);
+ }
+
+ /**
+ * Test {@link BitBuffer#get} for >32 bits in length, in little-endian, for
+ * a signed value, at position 7.
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void testGetLong35s_pos7LE() throws CTFReaderException {
+ fixture.position(7);
+ fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
+ long result = fixture.get(35, true);
+ assertEquals(0x0208060402L, result);
+ }
+
+ /**
+ * Test {@link BitBuffer#get} for >32 bits in length, in little-endian, for
+ * a signed value, at position 8.
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void testGetLong35s_pos8LE() throws CTFReaderException {
+ fixture.position(8);
+ fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
+ long result = fixture.get(35, true);
+ assertEquals(0xfffffffd04030201L, result);
+ }
+
+ /**
+ * Test reading negative values as signed values.
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void testGetSigned() throws CTFReaderException {
+ fixture.position(0);
+ fixture.putInt(-1);
+ fixture.putInt(-1);
+ fixture.position(0);
+ fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
+
+ long result = fixture.get(32, true);
+ assertEquals(-1L, result);
+ }
+
+ /**
+ * Test reading negative values as unsigned values.
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void testGetUnsigned() throws CTFReaderException {
+ fixture.position(0);
+ fixture.putInt(-1);
+ fixture.putInt(-1);
+ fixture.position(0);
+ fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
+
+ long result = fixture.get(32, false);
+ assertEquals(0xFFFFFFFFL, result);
+ }
+
+ /**
+ * Test reading 24 bits of a 32-bit negative value as a signed value.
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void testGet24Signed() throws CTFReaderException {
+ fixture.position(0);
+ fixture.putInt(-1);
+ fixture.putInt(-1);
+ fixture.position(0);
+ fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
+
+ long result = fixture.get(24, true);
+ assertEquals(-1L, result);
+ }
+
+ /**
+ * Test reading 24 bits of a 32-bit negative value as an unsigned value.
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void testGet24Unsigned() throws CTFReaderException {
+ fixture.position(0);
+ fixture.putInt(-1);
+ fixture.putInt(-1);
+ fixture.position(0);
+ fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
+
+ long result = fixture.get(24, false);
+ assertEquals(0xFFFFFFL, result);
+ }
+
+ /**
+ * Test {@link BitBuffer#putInt(int)}
+ *
+ * @throws CTFReaderException
+ * Not expected
+ */
+ @Test
+ public void testPutInt() throws CTFReaderException {
+ fixture.position(1);
+ fixture.putInt(1);
+ }
+
+ /**
+ * Test {@link BitBuffer#putInt(int, int)}
+ *
+ * @throws CTFReaderException
+ * Not expected
+ */
+ @Test
+ public void testPutInt_length1() throws CTFReaderException {
+ fixture.position(1);
+ fixture.putInt(1, 1);
+ }
+
+ /**
+ * Test {@link BitBuffer#putInt(int, int)} with length = 0.
+ *
+ * @throws CTFReaderException
+ * Not expected
+ */
+ @Test
+ public void testPutInt_length0() throws CTFReaderException {
+ fixture.position(1);
+ fixture.putInt(0, 1);
+ }
+
+ /**
+ * Test {@link BitBuffer#putInt(int)} Little endian
+ *
+ * @throws CTFReaderException
+ * Not expected
+ */
+ @Test
+ public void testPutIntLe() throws CTFReaderException {
+ fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
+ fixture.position(1);
+ fixture.putInt(1);
+ }
+
+ /**
+ * Test {@link BitBuffer#putInt(int, int)} Little endian
+ *
+ * @throws CTFReaderException
+ * Not expected
+ */
+ @Test
+ public void testPutIntLe_length1() throws CTFReaderException {
+ fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
+ fixture.position(1);
+ fixture.putInt(1, 1);
+ }
+
+ /**
+ * Test {@link BitBuffer#putInt(int, int)} with length = 0. Little endian
+ *
+ * @throws CTFReaderException
+ * Not expected
+ */
+ @Test
+ public void testPutIntLe_length0() throws CTFReaderException {
+ fixture.setByteOrder(ByteOrder.LITTLE_ENDIAN);
+ fixture.position(1);
+ fixture.putInt(0, 1);
+ }
+
+ /**
+ * Test writing and reading a value defined in hex format.
+ *
+ * @throws CTFReaderException
+ * Not expected
+ */
+ @Test
+ public void testPutInt_hex() throws CTFReaderException {
+ final int value = 0x010203;
+
+ for (int i = 0; i <= 32; i++) {
+ fixture.position(i);
+ fixture.putInt(value);
+
+ fixture.position(i);
+ int read = fixture.getInt();
+
+ assertEquals(value, read);
+ }
+ }
+
+ /**
+ * Test {@link BitBuffer#putInt} with an out-of-bounds length. An exception
+ * should be thrown.
+ *
+ * @throws CTFReaderException
+ * Expected
+ */
+ @Test(expected = CTFReaderException.class)
+ public void testPutInt_invalid() throws CTFReaderException {
+ BitBuffer fixture2;
+ fixture2 = createBuffer(4);
+ fixture2.setByteOrder(ByteOrder.BIG_ENDIAN);
+ fixture2.position(1);
+
+ /* This will try writing past the buffer's end */
+ fixture2.putInt(32, 1);
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.io;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * The class <code>BitBufferTest</code> contains tests for the class
+ * <code>{@link BitBuffer}</code>.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+public class BitBufferTest {
+
+ private BitBuffer fixture;
+
+ /**
+ * Perform pre-test initialization.
+ *
+ * @throws CTFReaderException
+ * An error that cannot happen (position is under 128)
+ */
+ @Before
+ public void setUp() throws CTFReaderException {
+ fixture = new BitBuffer(Util.testMemory(ByteBuffer.allocateDirect(1)));
+ fixture.setByteOrder(ByteOrder.BIG_ENDIAN);
+ fixture.position(1);
+ }
+
+ /**
+ * Run the BitBuffer() constructor test.
+ */
+ @Test
+ public void testBitBuffer() {
+ BitBuffer result = new BitBuffer();
+
+ assertNotNull(result);
+ assertEquals(0, result.position());
+ assertNotNull(result.getByteBuffer());
+ }
+
+ /**
+ * Run the BitBuffer(ByteBuffer) constructor test.
+ */
+ @Test
+ public void testBitBuffer_fromByteBuffer() {
+ BitBuffer result = new BitBuffer(Util.testMemory(ByteBuffer.allocate(0)));
+ assertNotNull(result);
+ assertEquals(0, result.position());
+ }
+
+ /**
+ * Run the boolean canRead(int) method test.
+ */
+ @Test
+ public void testCanRead_1param() {
+ int length = 1;
+ boolean result = fixture.canRead(length);
+
+ assertEquals(true, result);
+ }
+
+ /**
+ * Run the void clear() method test.
+ */
+ @Test
+ public void testClear() {
+ fixture.clear();
+ }
+
+ /**
+ * Run the ByteBuffer getByteBuffer() method test.
+ */
+ @Test
+ public void testGetByteBuffer() {
+ ByteBuffer result = fixture.getByteBuffer();
+
+ assertNotNull(result);
+ assertEquals("java.nio.DirectByteBuffer[pos=0 lim=1 cap=1]", result.toString());
+ assertEquals(true, result.isDirect());
+ assertEquals(false, result.hasArray());
+ assertEquals(1, result.limit());
+ assertEquals(1, result.remaining());
+ assertEquals(0, result.position());
+ assertEquals(1, result.capacity());
+ assertEquals(true, result.hasRemaining());
+ assertEquals(false, result.isReadOnly());
+ }
+
+ /**
+ * Run the ByteOrder getByteOrder() method test.
+ */
+ @Test
+ public void testGetByteOrder() {
+ ByteOrder result = fixture.getByteOrder();
+
+ assertNotNull(result);
+ assertEquals("BIG_ENDIAN", result.toString());
+ }
+
+ /**
+ * Run the ByteOrder order() method test.
+ */
+ @Test
+ public void testGetOrder() {
+ ByteOrder result = fixture.getByteOrder();
+
+ assertNotNull(result);
+ assertEquals("BIG_ENDIAN", result.toString());
+ }
+
+ /**
+ * Run the void order(ByteOrder) method test.
+ */
+ @Test
+ public void testSetOrder() {
+ ByteOrder order = ByteOrder.BIG_ENDIAN;
+
+ fixture.setByteOrder(order);
+ }
+
+ /**
+ * Run the int position() method test.
+ */
+ @Test
+ public void testGetPosition() {
+ long result = fixture.position();
+
+ assertEquals(1, result);
+ }
+
+ /**
+ * Run the void position(int) method test.
+ *
+ * @throws CTFReaderException
+ * out of bounds? won't happen
+ */
+ @Test
+ public void testSetPosition() throws CTFReaderException {
+ int newPosition = 1;
+ fixture.position(newPosition);
+ }
+
+ /**
+ * Run the void setByteOrder(ByteOrder) method test.
+ */
+ @Test
+ public void testSetByteOrder() {
+ ByteOrder byteOrder = ByteOrder.BIG_ENDIAN;
+ fixture.setByteOrder(byteOrder);
+ }
+
+ /**
+ * Test the get function
+ */
+ @Test
+ public void testGetBytes() {
+ @NonNull
+ byte[] data = new byte[2];
+ ByteBuffer bb = ByteBuffer.allocate(10);
+ bb.put((byte) 0);
+ bb.put((byte) 1);
+ bb.put((byte) 1);
+ bb.put((byte) 0);
+ fixture = new BitBuffer(bb);
+ fixture.get(data);
+ assertEquals(0, data[0]);
+ assertEquals(1, data[1]);
+ fixture.get(data);
+ assertEquals(1, data[0]);
+ assertEquals(0, data[1]);
+ }
+
+ /**
+ * Test the get function
+ *
+ * @throws CTFReaderException
+ * won't happen but we seek in a buffer
+ */
+ @Test
+ public void testGetBytesMiddle() throws CTFReaderException {
+ @NonNull
+ byte[] data = new byte[5];
+ // this string has been carefully selected and tested... don't change
+ // the string and expect the result to be the same.
+ fixture = new BitBuffer(Util.testMemory(ByteBuffer.wrap(new String("hello world").getBytes())));
+ fixture.position(6 * 8);
+ fixture.get(data);
+ String actual = new String(data);
+ assertEquals("world", actual);
+ }
+}
\ No newline at end of file
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.io;
+
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+
+/**
+ * The class <code>TestAll</code> builds a suite that can be used to run all of
+ * the tests within its package as well as within any subpackages of its
+ * package.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+@RunWith(Suite.class)
+@Suite.SuiteClasses({
+ BitBufferIntTest.class,
+ BitBufferTest.class
+})
+public class TestAll {
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ ******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.io;
+
+import java.nio.ByteBuffer;
+
+import org.eclipse.jdt.annotation.NonNull;
+
+/**
+ * Helpers for the tests
+ *
+ * @author Matthew Khouzam
+ */
+public final class Util {
+
+ private Util() {
+ }
+
+ /**
+ * Wrapper to make sure the bytebuffer is not null
+ *
+ * @param buffer
+ * a potentially null byte buffer
+ * @return a non-null byte buffer or an illegal state exception
+ */
+ @NonNull
+ public static ByteBuffer testMemory(ByteBuffer buffer) {
+ if (buffer == null) {
+ throw new IllegalStateException("Failed to alloc");
+ }
+ return buffer;
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are
+ * made available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.scope;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import org.eclipse.tracecompass.ctf.core.event.scope.LexicalScope;
+import org.junit.Test;
+
+/**
+ * Lexical test
+ *
+ * @author Matthew Khouzam
+ */
+public class LexicalScopeTest {
+
+ /**
+ * Root test
+ */
+ @Test
+ public void testRoot(){
+ LexicalScope scope = LexicalScope.ROOT;
+ assertNotNull(scope);
+ }
+
+ /**
+ * Test a more complex node
+ */
+ @Test
+ public void testComplexNode(){
+ LexicalScope scope = LexicalScope.STREAM_EVENT_CONTEXT;
+ assertEquals("context", scope.getName());
+ assertEquals("stream.event.context", scope.toString());
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.scope;
+
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+
+/**
+ * The class <code>TestAll</code> builds a suite that can be used to run all of
+ * the tests within its package as well as within any subpackages of its
+ * package.
+ *
+ * @author Matthew Khouzam
+ * @version $Revision: 1.0 $
+ */
+@RunWith(Suite.class)
+@Suite.SuiteClasses({
+ LexicalScopeTest.class
+})
+public class TestAll {
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013, 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are
+ * made available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ * Marc-Andre Laperle - Move generation to traces folder
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.synthetictraces;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.net.URL;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.channels.FileChannel;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Random;
+
+import org.eclipse.core.runtime.FileLocator;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.tracecompass.ctf.core.tests.CtfCoreTestPlugin;
+
+/**
+ * Generate a kernel trace
+ *
+ * @author Matthew Khouzam
+ */
+public class LttngKernelTraceGenerator {
+
+ private static final String metadata = "/* CTF 1.8 */ \n" +
+ "typealias integer { size = 8; align = 8; signed = false; } := uint8_t;\n" +
+ "typealias integer { size = 16; align = 8; signed = false; } := uint16_t;\n" +
+ "typealias integer { size = 32; align = 8; signed = false; } := uint32_t;\n" +
+ "typealias integer { size = 64; align = 8; signed = false; } := uint64_t;\n" +
+ "typealias integer { size = 32; align = 8; signed = false; } := unsigned long;\n" +
+ "typealias integer { size = 5; align = 1; signed = false; } := uint5_t;\n" +
+ "typealias integer { size = 27; align = 1; signed = false; } := uint27_t;\n" +
+ "\n" +
+ "trace {\n" +
+ " major = 1;\n" +
+ " minor = 8;\n" +
+ " uuid = \"11111111-1111-1111-1111-111111111111\";\n" +
+ " byte_order = le;\n" +
+ " packet.header := struct {\n" +
+ " uint32_t magic;\n" +
+ " uint8_t uuid[16];\n" +
+ " uint32_t stream_id;\n" +
+ " };\n" +
+ "};\n" +
+ "\n" +
+ "env {\n" +
+ " hostname = \"synthetic-host\";\n" +
+ " domain = \"kernel\";\n" +
+ " sysname = \"FakeLinux\";\n" +
+ " kernel_release = \"1.0\";\n" +
+ " kernel_version = \"Fake Os Synthetic Trace\";\n" +
+ " tracer_name = \"lttng-modules\";\n" +
+ " tracer_major = 2;\n" +
+ " tracer_minor = 1;\n" +
+ " tracer_patchlevel = 0;\n" +
+ "};\n" +
+ "\n" +
+ "clock {\n" +
+ " name = monotonic;\n" +
+ " uuid = \"bbff68f0-c633-4ea1-92cd-bd11024ec4de\";\n" +
+ " description = \"Monotonic Clock\";\n" +
+ " freq = 1000000000; /* Frequency, in Hz */\n" +
+ " /* clock value offset from Epoch is: offset * (1/freq) */\n" +
+ " offset = 1368000272650993664;\n" +
+ "};\n" +
+ "\n" +
+ "typealias integer {\n" +
+ " size = 27; align = 1; signed = false;\n" +
+ " map = clock.monotonic.value;\n" +
+ "} := uint27_clock_monotonic_t;\n" +
+ "\n" +
+ "typealias integer {\n" +
+ " size = 32; align = 8; signed = false;\n" +
+ " map = clock.monotonic.value;\n" +
+ "} := uint32_clock_monotonic_t;\n" +
+ "\n" +
+ "typealias integer {\n" +
+ " size = 64; align = 8; signed = false;\n" +
+ " map = clock.monotonic.value;\n" +
+ "} := uint64_clock_monotonic_t;\n" +
+ "\n" +
+ "struct packet_context {\n" +
+ " uint64_clock_monotonic_t timestamp_begin;\n" +
+ " uint64_clock_monotonic_t timestamp_end;\n" +
+ " uint64_t content_size;\n" +
+ " uint64_t packet_size;\n" +
+ " unsigned long events_discarded;\n" +
+ " uint32_t cpu_id;\n" +
+ "};\n" +
+ "\n" +
+ "struct event_header_compact {\n" +
+ " enum : uint5_t { compact = 0 ... 30, extended = 31 } id;\n" +
+ " variant <id> {\n" +
+ " struct {\n" +
+ " uint27_clock_monotonic_t timestamp;\n" +
+ " } compact;\n" +
+ " struct {\n" +
+ " uint32_t id;\n" +
+ " uint64_clock_monotonic_t timestamp;\n" +
+ " } extended;\n" +
+ " } v;\n" +
+ "} align(8);\n" +
+ "\n" +
+ "struct event_header_large {\n" +
+ " enum : uint16_t { compact = 0 ... 65534, extended = 65535 } id;\n" +
+ " variant <id> {\n" +
+ " struct {\n" +
+ " uint32_clock_monotonic_t timestamp;\n" +
+ " } compact;\n" +
+ " struct {\n" +
+ " uint32_t id;\n" +
+ " uint64_clock_monotonic_t timestamp;\n" +
+ " } extended;\n" +
+ " } v;\n" +
+ "} align(8);\n" +
+ "\n" +
+ "stream {\n" +
+ " id = 0;\n" +
+ " event.header := struct event_header_compact;\n" +
+ " packet.context := struct packet_context;\n" +
+ "};\n" +
+ "\n" +
+ "event {\n" +
+ " name = sched_switch;\n" +
+ " id = 0;\n" +
+ " stream_id = 0;\n" +
+ " fields := struct {\n" +
+ " integer { size = 8; align = 8; signed = 1; encoding = UTF8; base = 10; } _prev_comm[16];\n" +
+ " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _prev_tid;\n" +
+ " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _prev_prio;\n" +
+ " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _prev_state;\n" +
+ " integer { size = 8; align = 8; signed = 1; encoding = UTF8; base = 10; } _next_comm[16];\n" +
+ " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _next_tid;\n" +
+ " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _next_prio;\n" +
+ " };\n" +
+ "};\n" +
+ "\n";
+
+ private final List<String> fProcesses;
+ private final long fDuration;
+ private final long fNbEvents;
+ private final int fNbChans;
+
+ private static final String[] sfProcesses = {
+ "IDLE",
+ "gnuplot",
+ "starcraft 2:pt3",
+ "bash",
+ "smash",
+ "thrash",
+ "fireball",
+ "Half-life 3",
+ "ST: The game"
+ };
+
+
+ private static final String TRACES_DIRECTORY = "traces";
+ private static final String TRACE_NAME = "synthetic-trace";
+
+ /**
+ * Main, not always needed
+ *
+ * @param args
+ * args
+ */
+ public static void main(String[] args) {
+ // not using createTempFile as this is a directory
+ String path = CtfCoreTestPlugin.getTemporaryDirPath() + File.separator + TRACE_NAME;
+ generateLttngKernelTrace(new File(path));
+ }
+
+ /**
+ * Gets the name of the trace (top directory name)
+ *
+ * @return the name of the trace
+ */
+ public static String getName() {
+ return TRACE_NAME;
+ }
+
+ /**
+ * Get the path
+ *
+ * @return the path
+ */
+ public static String getPath() {
+ CtfCoreTestPlugin plugin = CtfCoreTestPlugin.getDefault();
+ if (plugin == null) {
+ return null;
+ }
+ URL location = FileLocator.find(plugin.getBundle(), new Path(TRACES_DIRECTORY), null);
+ File file = null;
+ try {
+ IPath path = new Path(FileLocator.toFileURL(location).getPath()).append(TRACE_NAME);
+ file = path.toFile();
+ } catch (IOException e) {
+ // Shouldn't happen but at least throw something to get the test to fail early
+ throw new IllegalStateException();
+ }
+
+ if (!file.exists()) {
+ generateLttngKernelTrace(file);
+ }
+ return file.getAbsolutePath();
+ }
+
+ /**
+ * Generate a trace
+ *
+ * @param file
+ * the file to write the trace to
+ */
+ public static void generateLttngKernelTrace(File file) {
+ final int cpus = 25;
+ LttngKernelTraceGenerator gt = new LttngKernelTraceGenerator(2l * Integer.MAX_VALUE - 100, 500000, cpus);
+ gt.writeTrace(file);
+ }
+
+ /**
+ * Make a kernel trace
+ *
+ * @param duration
+ * the duration of the trace
+ * @param events
+ * the number of events in a trace
+ * @param nbChannels
+ * the number of channels in the trace
+ */
+ public LttngKernelTraceGenerator(long duration, long events, int nbChannels) {
+ fProcesses = Arrays.asList(sfProcesses);
+ fDuration = duration;
+ fNbEvents = events;
+ fNbChans = nbChannels;
+ }
+
+ /**
+ * Write the trace to a file
+ *
+ * @param file
+ * the file to write the trace to
+ */
+ public void writeTrace(File file) {
+
+ if (!file.exists()) {
+ file.mkdir();
+ } else {
+ if (file.isFile()) {
+ file.delete();
+ file.mkdir();
+ } else {
+ // the ctf parser doesn't recurse, so we don't need to.
+ final File[] listFiles = file.listFiles();
+ for (File child : listFiles) {
+ child.delete();
+ }
+ }
+ }
+
+ File metadataFile = new File(file.getPath() + File.separator + "metadata");
+ File[] streams = new File[fNbChans];
+ FileChannel[] channels = new FileChannel[fNbChans];
+
+ try {
+ for (int i = 0; i < fNbChans; i++) {
+ streams[i] = new File(file.getPath() + File.separator + "channel" + i);
+ channels[i] = new FileOutputStream(streams[i]).getChannel();
+ }
+ } catch (FileNotFoundException e) {
+ }
+ // determine the number of events per channel
+ long evPerChan = fNbEvents / fNbChans;
+ int delta = (int) (fDuration / evPerChan);
+ int offsetTime = 0;
+ for (int chan = 0; chan < fNbChans; chan++) {
+ int currentSpace = 0;
+ ByteBuffer bb = ByteBuffer.allocate(65536);
+ bb.order(ByteOrder.LITTLE_ENDIAN);
+ Random rnd = new Random(1337);
+ int rnd0 = rnd.nextInt(fProcesses.size());
+ String prevComm = fProcesses.get(rnd0);
+ int prevPID = rnd0 + chan * fProcesses.size();
+ if (rnd0 == 0) {
+ prevPID = 0;
+ }
+ int prevPrio = 0;
+ int prevPos = -1;
+ for (int eventNb = 0; eventNb < evPerChan; eventNb++) {
+ int ts = eventNb * delta + delta / (fNbChans + 1) * chan;
+
+ int pos = rnd.nextInt((int) (fProcesses.size() * 1.5));
+ if (pos >= fProcesses.size()) {
+ pos = 0;
+ }
+ while (pos == prevPos) {
+ pos = rnd.nextInt((int) (fProcesses.size() * 1.5));
+ if (pos >= fProcesses.size()) {
+ pos = 0;
+ }
+ }
+ String nextComm = fProcesses.get(pos);
+ int nextPID = pos + fProcesses.size() * chan;
+ if (pos == 0) {
+ nextPID = 0;
+ }
+ int nextPrio = 0;
+ if (EventWriter.SIZE > currentSpace) {
+ // pad to end
+ for (int i = 0; i < currentSpace; i++) {
+ bb.put((byte) 0x00);
+ }
+ // write new packet
+ PacketWriter pw = new PacketWriter(bb);
+ int tsBegin = ts;
+ offsetTime = ts;
+ int tsEnd = (eventNb + (PacketWriter.SIZE / EventWriter.SIZE)) * delta + 1;
+ pw.writeNewHeader(tsBegin, tsEnd, chan);
+ currentSpace = PacketWriter.CONTENT_SIZE;
+ }
+ EventWriter ew = new EventWriter(bb);
+ int prev_state = rnd.nextInt(100);
+ if (prev_state != 0) {
+ prev_state = 1;
+ }
+ final int shrunkenTimestamp = ts - offsetTime;
+ final int tsMask = (1 << 27) - 1;
+ if (shrunkenTimestamp > ((1 << 27) + tsMask)) {
+ new Object();
+ System.err.println("PROBLEM");
+ }
+ final int clampedTs = ts & tsMask;
+ int evSize = ew.writeEvent(clampedTs, prevComm, prevPID, prevPrio, prev_state, nextComm, nextPID, nextPrio);
+ currentSpace -= evSize;
+ prevComm = nextComm;
+ prevPID = nextPID;
+ prevPrio = nextPrio;
+ if (bb.position() > 63000) {
+ writeToDisk(channels, chan, bb);
+ }
+ }
+ for (int i = 0; i < currentSpace; i++) {
+ bb.put((byte) 0x00);
+ }
+ writeToDisk(channels, chan, bb);
+ try {
+ channels[chan].close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ try (FileOutputStream fos = new FileOutputStream(metadataFile);) {
+ fos.write(metadata.getBytes());
+ } catch (IOException e) {
+ }
+ }
+
+ private static void writeToDisk(FileChannel[] channels, int chan, ByteBuffer bb) {
+ try {
+ bb.flip();
+ channels[chan].write(bb);
+ bb.clear();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private class EventWriter {
+ public static final int SIZE =
+ 4 + // timestamp
+ 16 + // prev_comm
+ 4 + // prev_tid
+ 4 + // prev_prio
+ 4 + // prev_state
+ 16 + // current_comm
+ 4 + // next_tid
+ 4; // next_prio
+ private final ByteBuffer data;
+
+ public EventWriter(ByteBuffer bb) {
+ data = bb;
+ }
+
+ public int writeEvent(int ts, String prev_comm, int prev_tid, int prev_prio, int prev_state, String next_comm, int next_tid, int next_prio) {
+ byte[] bOut = new byte[16];
+ byte[] bIn = new byte[16];
+ byte[] temp = prev_comm.getBytes();
+ for (int i = 0; i < Math.min(temp.length, 16); i++) {
+ bOut[i] = temp[i];
+ }
+ temp = next_comm.getBytes();
+ for (int i = 0; i < Math.min(temp.length, 16); i++) {
+ bIn[i] = temp[i];
+ }
+
+ int timestamp = ts << 5;
+
+ data.putInt(timestamp);
+ data.put(bOut);
+ data.putInt(prev_tid);
+ data.putInt(prev_prio);
+ data.putInt(prev_state);
+ data.put(bIn);
+ data.putInt(next_tid);
+ data.putInt(next_prio);
+ return SIZE;
+ }
+
+ }
+
+ private class PacketWriter {
+ private static final int SIZE = 4096;
+ private static final int HEADER_SIZE = 64;
+ private static final int CONTENT_SIZE = SIZE - HEADER_SIZE;
+
+ private final ByteBuffer data;
+
+ public PacketWriter(ByteBuffer bb) {
+ data = bb;
+ }
+
+ public void writeNewHeader(int tsBegin, int tsEnd, int cpu) {
+ final int magicLE = 0xC1FC1FC1;
+ byte uuid[] = {
+ 0x11, 0x11, 0x11, 0x11,
+ 0x11, 0x11, 0x11, 0x11,
+ 0x11, 0x11, 0x11, 0x11,
+ 0x11, 0x11, 0x11, 0x11 };
+ // packet header
+
+ // magic number 4
+ data.putInt(magicLE);
+ // uuid 16
+ data.put(uuid);
+ // stream ID 4
+ data.putInt(0);
+
+ // packet context
+ // timestamp_begin 8
+ data.putLong(tsBegin);
+
+ // timestamp_end 8
+ data.putLong(tsEnd);
+
+ // content_size 8
+ data.putLong((CONTENT_SIZE / EventWriter.SIZE * EventWriter.SIZE + HEADER_SIZE) * 8);
+
+ // packet_size 8
+ data.putLong((SIZE) * 8);
+
+ // events_discarded 4
+ data.putInt(0);
+
+ // cpu_id 4
+ data.putInt(cpu);
+
+ }
+
+ }
+
+
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.trace;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import org.eclipse.tracecompass.internal.ctf.core.trace.StreamInputPacketIndexEntry;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * The class <code>StreamInputPacketIndexEntryTest</code> contains tests for the
+ * class <code>{@link StreamInputPacketIndexEntry}</code>.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+public class CTFStreamInputPacketIndexEntryTest {
+
+ private StreamInputPacketIndexEntry fixture;
+
+ /**
+ * Perform pre-test initialization.
+ */
+ @Before
+ public void setUp() {
+ fixture = new StreamInputPacketIndexEntry(1L);
+ }
+
+ /**
+ * Run the StreamInputPacketIndexEntry(long) constructor test.
+ */
+ @Test
+ public void testStreamInputPacketIndexEntry_1() {
+ String expectedResult = "StreamInputPacketIndexEntry [offsetBytes=1, " +
+ "timestampBegin=0, timestampEnd=0]";
+
+ assertNotNull(fixture);
+ assertEquals(expectedResult, fixture.toString());
+ }
+
+ /**
+ * Run the String toString() method test.
+ */
+ @Test
+ public void testToString() {
+ String expectedResult = "StreamInputPacketIndexEntry [offsetBytes=1,"+
+ " timestampBegin=1, timestampEnd=1]";
+
+
+ fixture.setContentSizeBits(1);
+ fixture.setDataOffsetBits(1);
+ fixture.setTimestampEnd(1L);
+ fixture.setPacketSizeBits(1);
+ fixture.setTimestampBegin(1L);
+
+ assertEquals(expectedResult, fixture.toString());
+ }
+}
\ No newline at end of file
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.trace;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import java.util.Collection;
+import java.util.ListIterator;
+
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.internal.ctf.core.trace.StreamInputPacketIndex;
+import org.eclipse.tracecompass.internal.ctf.core.trace.StreamInputPacketIndexEntry;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * The class <code>StreamInputPacketIndexTest</code> contains tests for the
+ * class <code>{@link StreamInputPacketIndex}</code>.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+@SuppressWarnings("javadoc")
+public class CTFStreamInputPacketIndexTest {
+
+ private StreamInputPacketIndex fixture;
+ private StreamInputPacketIndexEntry entry;
+
+ /**
+ * Perform pre-test initialization.
+ *
+ * @throws CTFReaderException
+ */
+ @Before
+ public void setUp() throws CTFReaderException {
+ fixture = new StreamInputPacketIndex();
+ fixture.addEntry(new StreamInputPacketIndexEntry(1L));
+ entry = new StreamInputPacketIndexEntry(1L);
+ }
+
+ /**
+ * Run the StreamInputPacketIndex() constructor test.
+ */
+ @Test
+ public void testStreamInputPacketIndex() {
+ assertNotNull(fixture);
+ }
+
+ /**
+ * Run the void addEntry(StreamInputPacketIndexEntry) method test, by
+ * specifying only 1 parameter to the entry.
+ *
+ * @throws CTFReaderException
+ */
+ @Test
+ public void testAddEntry_1param() throws CTFReaderException {
+ entry.setPacketSizeBits(0);
+ fixture.addEntry(entry);
+ }
+
+ /**
+ * Run the void addEntry(StreamInputPacketIndexEntry) method test by
+ * specifying 2 parameters to the entry.
+ *
+ * @throws CTFReaderException
+ */
+ @Test
+ public void testAddEntry_2params() throws CTFReaderException {
+ entry.setPacketSizeBits(1);
+ entry.setContentSizeBits(0);
+ fixture.addEntry(entry);
+ }
+
+ /**
+ * Run the void addEntry(StreamInputPacketIndexEntry) method test, by
+ * specifying all 4 parameters to the entry.
+ *
+ * @throws CTFReaderException
+ */
+ @Test
+ public void testAddEntry_4params() throws CTFReaderException {
+ entry.setTimestampBegin(1L);
+ entry.setPacketSizeBits(1);
+ entry.setContentSizeBits(1);
+ entry.setTimestampEnd(1L);
+ fixture.addEntry(entry);
+ }
+
+ /**
+ * Run the Collection<StreamInputPacketIndexEntry> getEntries() method test.
+ */
+ @Test
+ public void testGetEntries() {
+ Collection<StreamInputPacketIndexEntry> result = fixture.getEntries();
+
+ assertNotNull(result);
+ assertEquals(1, result.size());
+ }
+
+ /**
+ * Run the ListIterator<StreamInputPacketIndexEntry> listIterator() method
+ * test, with no parameter to listIterator().
+ */
+ @Test
+ public void testListIterator_noparam() {
+ ListIterator<StreamInputPacketIndexEntry> result = fixture.listIterator();
+
+ assertNotNull(result);
+ assertEquals(true, result.hasNext());
+ assertEquals(-1, result.previousIndex());
+ assertEquals(false, result.hasPrevious());
+ assertEquals(0, result.nextIndex());
+ }
+
+ /**
+ * Run the ListIterator<StreamInputPacketIndexEntry> listIterator(n) method
+ * test, with n = 1.
+ */
+ @Test
+ public void testListIterator_withparam() {
+ ListIterator<StreamInputPacketIndexEntry> result = fixture.listIterator(1);
+
+ assertNotNull(result);
+ assertEquals(false, result.hasNext());
+ assertEquals(0, result.previousIndex());
+ assertEquals(true, result.hasPrevious());
+ assertEquals(1, result.nextIndex());
+ assertEquals(false, result.hasNext());
+ }
+
+ /**
+ * Run the ListIterator<StreamInputPacketIndexEntry> search(long) method
+ * test with a valid timestamp.
+ */
+ @Test
+ public void testSearch_valid() {
+ ListIterator<StreamInputPacketIndexEntry> result = fixture.search(1L);
+
+ assertNotNull(result);
+ assertEquals(true, result.hasNext());
+ assertEquals(-1, result.previousIndex());
+ assertEquals(false, result.hasPrevious());
+ assertEquals(0, result.nextIndex());
+ }
+
+ /**
+ * Run the ListIterator<StreamInputPacketIndexEntry> search(long) method
+ * test with an invalid timestamp.
+ */
+ @Test(expected = java.lang.IllegalArgumentException.class)
+ public void testSearch_invalid() {
+ ListIterator<StreamInputPacketIndexEntry> result = fixture.search(-1L);
+
+ assertNotNull(result);
+ }
+}
\ No newline at end of file
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013, 2014 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.trace;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assume.assumeTrue;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Set;
+
+import org.eclipse.tracecompass.ctf.core.event.EventDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.Definition;
+import org.eclipse.tracecompass.ctf.core.event.types.StringDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StringDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDefinition;
+import org.eclipse.tracecompass.ctf.core.tests.shared.CtfTestTrace;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.ctf.core.trace.CTFResponse;
+import org.eclipse.tracecompass.ctf.core.trace.CTFStream;
+import org.eclipse.tracecompass.ctf.core.trace.CTFStreamInput;
+import org.eclipse.tracecompass.ctf.core.trace.CTFStreamInputReader;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTrace;
+import org.eclipse.tracecompass.internal.ctf.core.event.EventDeclaration;
+import org.junit.Before;
+import org.junit.Test;
+
+import com.google.common.collect.ImmutableList;
+
+/**
+ * The class <code>StreamInputReaderTest</code> contains tests for the class
+ * <code>{@link CTFStreamInputReader}</code>.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+@SuppressWarnings("javadoc")
+public class CTFStreamInputReaderTest {
+
+ private static final CtfTestTrace testTrace = CtfTestTrace.KERNEL;
+
+ private CTFStreamInputReader fixture;
+
+ private static ImmutableList<String> wrap(String s) {
+ return ImmutableList.<String> builder().add(s).build();
+ }
+
+ /**
+ * Perform pre-test initialization.
+ *
+ * @throws CTFReaderException
+ */
+ @Before
+ public void setUp() throws CTFReaderException {
+ fixture = getStreamInputReader();
+ fixture.setName(1);
+ fixture.setCurrentEvent(new EventDefinition(new EventDeclaration(),
+ getStreamInputReader(), 0, null, null,
+ new StructDefinition(
+ new StructDeclaration(0),
+ null,
+ "packet",
+ wrap( "field" ),
+ new Definition[] { new StringDefinition(new StringDeclaration(), null, "field", "test") }),
+ null)
+ );
+ }
+
+ private static CTFStreamInputReader getStreamInputReader() throws CTFReaderException {
+ assumeTrue(testTrace.exists());
+ CTFTrace trace = testTrace.getTrace();
+ CTFStream s = trace.getStream((long) 0);
+ Set<CTFStreamInput> streamInput = s.getStreamInputs();
+ CTFStreamInputReader retVal = null;
+ for (CTFStreamInput si : streamInput) {
+ /*
+ * For the tests, we'll use the stream input corresponding to the
+ * CPU 0
+ */
+ if (si.getFilename().endsWith("0_0")) {
+ retVal = new CTFStreamInputReader(si);
+ break;
+ }
+ }
+ return retVal;
+ }
+
+ /**
+ * Run the StreamInputReader(StreamInput) constructor test, with a valid
+ * trace.
+ */
+ @Test
+ public void testStreamInputReader_valid() {
+ assertNotNull(fixture);
+ }
+
+ /**
+ * Run the StreamInputReader(StreamInput) constructor test, with an invalid
+ * trace.
+ *
+ * @throws CTFReaderException
+ * @throws IOException
+ */
+ @Test(expected = CTFReaderException.class)
+ public void testStreamInputReader_invalid() throws CTFReaderException, IOException {
+ try (CTFStreamInput streamInput = new CTFStreamInput(new CTFStream(new CTFTrace("")), new File(""));
+ CTFStreamInputReader result = new CTFStreamInputReader(streamInput)) {
+ assertNotNull(result);
+ }
+ }
+
+ /**
+ * Run the int getCPU() method test.
+ */
+ @Test
+ public void testGetCPU() {
+ int result = fixture.getCPU();
+ assertEquals(0, result);
+ }
+
+ /**
+ * Run the EventDefinition getCurrentEvent() method test.
+ */
+ @Test
+ public void testGetCurrentEvent() {
+ EventDefinition result = fixture.getCurrentEvent();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the StructDefinition getCurrentPacketContext() method test.
+ */
+ @Test
+ public void testGetCurrentPacketContext() {
+ StructDefinition result = fixture.getCurrentEvent().getPacketContext();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the int getName() method test.
+ */
+ @Test
+ public void testGetName() {
+ int result = fixture.getName();
+ assertEquals(1, result);
+ }
+
+ /**
+ * Run the void goToLastEvent() method test.
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void testGoToLastEvent1() throws CTFReaderException {
+ final long endTimestamp = goToEnd();
+ final long endTime = 4287422460315L;
+ assertEquals(endTime, endTimestamp);
+ }
+
+ /**
+ * Run the void goToLastEvent() method test.
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void testGoToLastEvent2() throws CTFReaderException {
+ long timestamp = -1;
+ while (fixture.readNextEvent().equals(CTFResponse.OK)) {
+ timestamp = fixture.getCurrentEvent().getTimestamp();
+ }
+ long endTimestamp = goToEnd();
+ assertEquals(0, timestamp - endTimestamp);
+ }
+
+ private long goToEnd() throws CTFReaderException {
+ fixture.goToLastEvent();
+ return fixture.getCurrentEvent().getTimestamp();
+ }
+
+ /**
+ * Run the boolean readNextEvent() method test.
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void testReadNextEvent() throws CTFReaderException {
+ assertEquals(CTFResponse.OK, fixture.readNextEvent());
+ }
+
+ /**
+ * Run the void seek(long) method test. Seek by direct timestamp
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void testSeek_timestamp() throws CTFReaderException {
+ long timestamp = 1L;
+ fixture.seek(timestamp);
+ }
+
+ /**
+ * Run the seek test. Seek by passing an EventDefinition to which we've
+ * given the timestamp we want.
+ *
+ * @throws CTFReaderException
+ */
+ @Test
+ public void testSeek_eventDefinition() throws CTFReaderException {
+ EventDefinition eventDefinition = new EventDefinition(
+ new EventDeclaration(), getStreamInputReader(), 1L, null, null, null, null);
+ fixture.setCurrentEvent(eventDefinition);
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.trace;
+
+import static org.junit.Assert.assertNotNull;
+
+import org.eclipse.tracecompass.internal.ctf.core.trace.StreamInputReaderTimestampComparator;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * The class <code>StreamInputReaderTimestampComparatorTest</code> contains
+ * tests for the class <code>{@link StreamInputReaderTimestampComparator}</code>
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+public class CTFStreamInputReaderTimestampComparatorTest {
+
+ private StreamInputReaderTimestampComparator fixture;
+
+ /**
+ * Perform pre-test initialization.
+ */
+ @Before
+ public void setUp() {
+ fixture = new StreamInputReaderTimestampComparator();
+ }
+
+ /**
+ * Run the StreamInputReaderTimestampComparator() constructor test.
+ */
+ @Test
+ public void testStreamInputReaderTimestampComparator_1() {
+ assertNotNull(fixture);
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.trace;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assume.assumeTrue;
+
+import java.io.File;
+import java.io.FilenameFilter;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.types.IDefinition;
+import org.eclipse.tracecompass.ctf.core.tests.shared.CtfTestTrace;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.ctf.core.trace.CTFStream;
+import org.eclipse.tracecompass.ctf.core.trace.CTFStreamInput;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * The class <code>StreamInputTest</code> contains tests for the class
+ * <code>{@link CTFStreamInput}</code>.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+@SuppressWarnings("javadoc")
+public class CTFStreamInputTest {
+
+ private static final CtfTestTrace testTrace = CtfTestTrace.KERNEL;
+
+ private CTFStreamInput fixture;
+
+ /**
+ * Perform pre-test initialization.
+ *
+ * @throws CTFReaderException
+ */
+ @Before
+ public void setUp() throws CTFReaderException {
+ assumeTrue(testTrace.exists());
+ fixture = new CTFStreamInput(new CTFStream(testTrace.getTrace()), createFile());
+ fixture.setTimestampEnd(1L);
+ }
+
+ @NonNull
+ private static File createFile() {
+ File path = new File(testTrace.getPath());
+ final File[] listFiles = path.listFiles(new FilenameFilter() {
+ @Override
+ public boolean accept(File dir, String name) {
+ if (name.contains("hann")) {
+ return true;
+ }
+ return false;
+ }
+ });
+ assertNotNull(listFiles);
+ final File returnFile = listFiles[0];
+ assertNotNull(returnFile);
+ return returnFile;
+ }
+
+ /**
+ * Run the StreamInput(Stream,FileChannel,File) constructor test.
+ */
+ @Test
+ public void testStreamInput() {
+ assertNotNull(fixture);
+ }
+
+ /**
+ * Run the String getFilename() method test.
+ */
+ @Test
+ public void testGetFilename() {
+ String result = fixture.getFilename();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the String getPath() method test.
+ */
+ @Test
+ public void testGetPath() {
+ String result = fixture.getScopePath().toString();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the Stream getStream() method test.
+ */
+ @Test
+ public void testGetStream() {
+ CTFStream result = fixture.getStream();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the long getTimestampEnd() method test.
+ */
+ @Test
+ public void testGetTimestampEnd() {
+ long result = fixture.getTimestampEnd();
+ assertTrue(0L < result);
+ }
+
+ /**
+ * Run the Definition lookupDefinition(String) method test.
+ */
+ @Test
+ public void testLookupDefinition() {
+ IDefinition result = fixture.lookupDefinition("id");
+ assertNull(result);
+ }
+
+ /**
+ * Run the void setTimestampEnd(long) method test.
+ */
+ @Test
+ public void testSetTimestampEnd() {
+ fixture.setTimestampEnd(1L);
+ assertEquals(fixture.getTimestampEnd(), 1L);
+ }
+
+ CTFStreamInput s1;
+ CTFStreamInput s2;
+
+ @Test
+ public void testEquals1() throws CTFReaderException {
+ s1 = new CTFStreamInput(new CTFStream(testTrace.getTrace()),
+ createFile());
+ assertFalse(s1.equals(null));
+ }
+
+ @Test
+ public void testEquals2() throws CTFReaderException {
+ s1 = new CTFStreamInput(new CTFStream(testTrace.getTrace()),
+ createFile());
+ assertFalse(s1.equals(new Long(23L)));
+
+ }
+
+ @Test
+ public void testEquals3() throws CTFReaderException {
+ s1 = new CTFStreamInput(new CTFStream(testTrace.getTrace()),
+ createFile());
+ assertEquals(s1, s1);
+
+ }
+
+ @Test
+ public void testEquals4() throws CTFReaderException {
+ s1 = new CTFStreamInput(new CTFStream(testTrace.getTrace()),
+ createFile());
+ s2 = new CTFStreamInput(new CTFStream(testTrace.getTrace()),
+ createFile());
+ assertEquals(s1, s2);
+ }
+}
\ No newline at end of file
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.trace;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assume.assumeTrue;
+
+import java.io.File;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.util.Set;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.types.IDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+import org.eclipse.tracecompass.ctf.core.tests.shared.CtfTestTrace;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.ctf.core.trace.CTFStream;
+import org.eclipse.tracecompass.ctf.core.trace.CTFStreamInput;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTrace;
+import org.eclipse.tracecompass.internal.ctf.core.event.EventDeclaration;
+import org.eclipse.tracecompass.internal.ctf.core.event.metadata.exceptions.ParseException;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+/**
+ * The class <code>StreamTest</code> contains tests for the class
+ * <code>{@link CTFStream}</code>.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+@SuppressWarnings("javadoc")
+public class CTFStreamTest {
+
+ private static final CtfTestTrace testTrace = CtfTestTrace.KERNEL;
+
+ private CTFStream fixture;
+
+ private CTFStreamInput fInput;
+
+ @BeforeClass
+ public static void initialize() {
+ assumeTrue(testTrace.exists());
+ }
+
+ /**
+ * Perform pre-test initialization.
+ *
+ * @throws CTFReaderException
+ */
+ @Before
+ public void setUp() throws CTFReaderException {
+ fixture = new CTFStream(testTrace.getTrace());
+ fixture.setEventContext(new StructDeclaration(1L));
+ fixture.setPacketContext(new StructDeclaration(1L));
+ fixture.setEventHeader(new StructDeclaration(1L));
+ fixture.setId(1L);
+ fInput = new CTFStreamInput(new CTFStream(testTrace.getTrace()), createFile());
+ fixture.addInput(fInput);
+ }
+
+ @After
+ public void tearDown() throws IOException {
+ fInput.close();
+ }
+
+ @NonNull
+ private static File createFile() {
+ File path = new File(testTrace.getPath());
+ final File[] listFiles = path.listFiles(new FilenameFilter() {
+ @Override
+ public boolean accept(File dir, String name) {
+ if (name.contains("hann")) {
+ return true;
+ }
+ return false;
+ }
+ });
+ assertNotNull(listFiles);
+ final File returnFile = listFiles[0];
+ assertNotNull(returnFile);
+ return returnFile;
+ }
+
+ /**
+ * Run the Stream(CTFTrace) constructor test.
+ *
+ * @throws CTFReaderException
+ */
+ @Test
+ public void testStream() throws CTFReaderException {
+ try (CTFTrace trace = testTrace.getTrace()) {
+ CTFStream result = new CTFStream(trace);
+ assertNotNull(result);
+ }
+ }
+
+ /**
+ * Run the void addEvent(EventDeclaration) method test with the basic event.
+ *
+ * @throws ParseException
+ */
+ @Test
+ public void testAddEvent_base() throws ParseException {
+ EventDeclaration event = new EventDeclaration();
+ fixture.addEvent(event);
+ }
+
+ /**
+ * Run the boolean eventContextIsSet() method test.
+ */
+ @Test
+ public void testEventContextIsSet() {
+ assertTrue(fixture.isEventContextSet());
+ }
+
+ /**
+ * Run the boolean eventContextIsSet() method test.
+ */
+ @Test
+ public void testToString() {
+ assertNotNull(fixture.toString());
+ }
+
+ /**
+ * Run the boolean eventHeaderIsSet() method test.
+ */
+ @Test
+ public void testEventHeaderIsSet() {
+ assertTrue(fixture.isEventHeaderSet());
+ }
+
+ /**
+ * Run the StructDeclaration getEventContextDecl() method test.
+ */
+ @Test
+ public void testGetEventContextDecl() {
+ assertNotNull(fixture.getEventContextDecl());
+ }
+
+ /**
+ * Run the StructDeclaration getEventHeaderDecl() method test.
+ */
+ @Test
+ public void testGetEventHeaderDecl() {
+ IDeclaration eventHeaderDecl = fixture.getEventHeaderDeclaration();
+ assertNotNull(eventHeaderDecl);
+ }
+
+ /**
+ * Run the HashMap<Long, EventDeclaration> getEvents() method test.
+ */
+ @Test
+ public void testGetEvents() {
+ assertNotNull(fixture.getEventDeclarations());
+ }
+
+ /**
+ * Run the Long getId() method test.
+ */
+ @Test
+ public void testGetId() {
+ Long result = fixture.getId();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the StructDeclaration getPacketContextDecl() method test.
+ */
+ @Test
+ public void testGetPacketContextDecl() {
+ StructDeclaration result = fixture.getPacketContextDecl();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the Set<StreamInput> getStreamInputs() method test.
+ */
+ @Test
+ public void testGetStreamInputs() {
+ Set<CTFStreamInput> result = fixture.getStreamInputs();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the CTFTrace getTrace() method test.
+ */
+ @Test
+ public void testGetTrace() {
+ try (CTFTrace result = fixture.getTrace();) {
+ assertNotNull(result);
+ }
+ }
+
+ /**
+ * Run the boolean idIsSet() method test.
+ */
+ @Test
+ public void testIdIsSet() {
+ boolean result = fixture.isIdSet();
+ assertTrue(result);
+ }
+
+ /**
+ * Run the boolean packetContextIsSet() method test.
+ */
+ @Test
+ public void testPacketContextIsSet() {
+ boolean result = fixture.isPacketContextSet();
+ assertTrue(result);
+ }
+
+ /**
+ * Run the void setEventContext(StructDeclaration) method test.
+ */
+ @Test
+ public void testSetEventContext() {
+ StructDeclaration eventContext = new StructDeclaration(1L);
+ fixture.setEventContext(eventContext);
+ }
+
+ /**
+ * Run the void setEventHeader(StructDeclaration) method test.
+ */
+ @Test
+ public void testSetEventHeader() {
+ StructDeclaration eventHeader = new StructDeclaration(1L);
+ fixture.setEventHeader(eventHeader);
+ }
+
+ /**
+ * Run the void setId(long) method test.
+ */
+ @Test
+ public void testSetId() {
+ long id = 1L;
+ fixture.setId(id);
+ }
+
+ /**
+ * Run the void setPacketContext(StructDeclaration) method test.
+ */
+ @Test
+ public void testSetPacketContext() {
+ StructDeclaration packetContext = new StructDeclaration(1L);
+ fixture.setPacketContext(packetContext);
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.trace;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assume.assumeTrue;
+
+import java.util.Random;
+import java.util.TreeSet;
+
+import org.eclipse.tracecompass.ctf.core.event.CTFCallsite;
+import org.eclipse.tracecompass.ctf.core.tests.shared.CtfTestTrace;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTrace;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * Test the performance of the callsite storage in the CTF trace.
+ *
+ * @author Matthew Khouzam
+ */
+public class CTFTraceCallsitePerformanceTest {
+
+ private static final CtfTestTrace testTrace = CtfTestTrace.KERNEL;
+
+ private static final int NUMBER_OF_SEEKS = 100000;
+
+ private final String[] callsites = { "Alligator", "Bunny", "Cat",
+ "Dolphin", "Echidna", "Gazelle", "Heron", "Ibex", "Jackalope",
+ "Koala", "Lynx", "Meerkat", "Narwhal", "Ocelot", "Pangolin",
+ "Quetzal", "Ringtail", "Sandpiper", "Tiger", "Urchin", "Vulture",
+ "Walrus", "X-Ray Tetra", "Zonkey" };
+
+ private final String[] functions = { "sentence", "together", "children",
+ "mountain", "chipmunk", "crashing", "drinking", "insisted",
+ "insulted", "invented", "squinted", "standing", "swishing",
+ "talented", "whiplash", "complain", "granddad", "sprinkle",
+ "surprise", "umbrella", "anything", "anywhere", "baseball",
+ "birthday", "bluebird", "cheerful", "colorful", "daylight",
+ "doghouse", "driveway", "everyone" };
+
+ private final String[] files = { "Adult.java", "Aeroplane.java",
+ "Air.java", "Airforce.java", "Airport.java", "Album.java",
+ "Alphabet.java", "Apple.java", "Arm.java", "Army.java", "Babby.java" };
+
+ Random rnd = new Random();
+ CTFTrace fTrace = null;
+
+ /**
+ * main, launches the tests.
+ * @param args not read
+ */
+ public static void main(String[] args) {
+ new org.junit.runner.JUnitCore().run(CTFTraceCallsitePerformanceTest.class);
+ }
+
+
+ /**
+ * sets up the test by making a new trace.
+ * @throws CTFReaderException an exception from the reader
+ * @throws SecurityException an exception from accessing files illegally
+ * @throws IllegalArgumentException an exception for passing bad values
+ */
+ @Before
+ public void setup() throws CTFReaderException, SecurityException,
+ IllegalArgumentException {
+ assumeTrue(testTrace.exists());
+ fTrace = new CTFTrace(testTrace.getPath());
+ }
+
+ private void addCallsites(int numCallsites) {
+ long stepSize = (Long.MAX_VALUE / (numCallsites + 1));
+ int jitter = (int) Math.min(stepSize, Integer.MAX_VALUE);
+ for (int i = 0; i < numCallsites; i++) {
+ final long ip = ((i)) * stepSize + rnd.nextInt(jitter);
+ fTrace.addCallsite(getRandomElement(callsites),
+ getRandomElement(functions), ip, getRandomElement(files),
+ (ip / 1000000) * 100);
+ }
+ }
+
+ private String getRandomElement(String[] array) {
+ return array[rnd.nextInt(array.length)];
+ }
+
+ private long testMain() {
+ TreeSet<CTFCallsite> l = fTrace.getCallsiteCandidates(callsites[0]);
+ CTFCallsite cs = fTrace.getCallsite(1);
+ CTFCallsite cs1 = fTrace.getCallsite(callsites[0]);
+ CTFCallsite cs2 = fTrace.getCallsite(callsites[0], 1);
+ assertNotNull(l);
+ assertNotNull(cs);
+ assertNotNull(cs1);
+ assertNotNull(cs2);
+ /* performance test */
+ long start = System.nanoTime();
+ perfTest();
+ long end = System.nanoTime();
+ long diff = end - start;
+ assertTrue(diff > 0);
+ return diff;
+ }
+
+ /**
+ * @param callsiteSize
+ */
+ private void test(int callsiteSize) {
+ addCallsites(callsiteSize);
+ long ns = testMain();
+ System.out.println( "perf ( " + callsiteSize + ", " + ns + ")");
+ }
+
+ private void perfTest() {
+ for (int i = 0; i < NUMBER_OF_SEEKS; i++) {
+ fTrace.getCallsite((((long) rnd.nextInt()) << 16L));
+ }
+ }
+
+ /**
+ * Test seeks with 1000 callsites
+ */
+ @Test
+ public void test1KCallsites() {
+ test(1000);
+ }
+
+ /**
+ * Test seeks with 2000 callsites
+ */
+ @Test
+ public void test2KCallsites() {
+ test(2000);
+ }
+
+ /**
+ * Test seeks with 5000 callsites
+ */
+ @Test
+ public void test5KCallsites() {
+ test(5000);
+ }
+
+ /**
+ * Test seeks with 10000 callsites
+ */
+ @Test
+ public void test10KCallsites() {
+ test(10000);
+ }
+
+ /**
+ * Test seeks with 20000 callsites
+ */
+ @Test
+ public void test20KCallsites() {
+ test(20000);
+ }
+
+ /**
+ * Test seeks with 50000 callsites
+ */
+ @Test
+ public void test50KCallsites() {
+ test(50000);
+ }
+
+ /**
+ * Test seeks with 100000 callsites
+ */
+ @Test
+ public void test100KCallsites() {
+ test(100000);
+ }
+
+ /**
+ * Test seeks with 1000000 callsites
+ */
+ @Test
+ public void test1MCallsites() {
+ test(1000000);
+ }
+
+ /**
+ * Test seeks with 2000000 callsites
+ */
+ @Test
+ public void test2MCallsites() {
+ test(2000000);
+ }
+}
+
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.trace;
+
+import static org.junit.Assert.*;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.FileAttribute;
+import java.util.UUID;
+
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTrace;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTraceReader;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * Tests growing streams
+ *
+ * @author Matthew Khouzam
+ *
+ */
+public class CTFTraceGrowingStreamTest {
+
+ private Path fCtfDirectory;
+ private File fGrowingStream;
+ private byte[][] fPackets;
+ private CTFTrace fFixture;
+ private UUID fUUID;
+
+ /**
+ * Run before every test
+ *
+ * @throws IOException won't happen
+ * @throws CTFReaderException won't happen
+ */
+ @Before
+ public void init() throws IOException, CTFReaderException {
+ fCtfDirectory = Files.createTempDirectory("temptrace", new FileAttribute<?>[] {});
+ File metadata = new File(fCtfDirectory.toString() + "/" + "metadata");
+ fGrowingStream = new File(fCtfDirectory.toString() + "/" + "stream");
+ fUUID = UUID.randomUUID();
+ fPackets = new byte[2][];
+ fPackets[0] = new byte[32];
+ fPackets[1] = new byte[32];
+ try (PrintWriter pw = new PrintWriter(metadata)) {
+ pw.println("/*CTF 1.8*/");
+ pw.println("typealias integer { size = 8; align = 8; signed = false; base = 10; } := uint8_t;");
+ pw.println("typealias integer { size = 32; align = 32; signed = false; base = hex; } := uint32_t;");
+
+ pw.println("trace {");
+ pw.println(" major = 0;");
+ pw.println(" minor = 1;");
+ pw.println(" uuid = \"" + fUUID.toString() + "\";");
+ pw.println(" byte_order = le;");
+ pw.println(" packet.header := struct {");
+ pw.println(" uint32_t magic;");
+ pw.println(" uint8_t uuid[16];");
+ pw.println(" };");
+ pw.println("};");
+ pw.println("");
+ pw.println("stream {");
+ pw.println(" packet.context := struct {");
+ pw.println(" uint32_t packet_size;");
+ pw.println(" uint32_t content_size;");
+ pw.println(" };");
+ pw.println("};");
+ pw.println("");
+ pw.println("event {");
+ pw.println(" name = thing;");
+ pw.println(" fields := struct { uint32_t f; };");
+ pw.println("};");
+ pw.println("");
+ pw.close();
+ }
+ setupPacket(fPackets[0], 41);
+ setupPacket(fPackets[1], 0xbab4face);
+
+ try (FileOutputStream fos = new FileOutputStream(fGrowingStream)) {
+ fos.write(fPackets[0]);
+ }
+ fFixture = new CTFTrace(fCtfDirectory.toString());
+ }
+
+ private void setupPacket(byte data[], int value) {
+ ByteBuffer bb = ByteBuffer.wrap(data);
+ bb.clear();
+ bb.order(ByteOrder.LITTLE_ENDIAN);
+ bb.putInt(0xc1fc1fc1);
+ bb.order(ByteOrder.BIG_ENDIAN);
+ bb.putLong(fUUID.getMostSignificantBits());
+ bb.putLong(fUUID.getLeastSignificantBits());
+ bb.order(ByteOrder.LITTLE_ENDIAN);
+ bb.putInt(256);
+ bb.putInt(256);
+ bb.putInt(value);
+ }
+
+ /**
+ * Test a growing stream
+ *
+ * @throws CTFReaderException won't happen
+ * @throws IOException won't happen
+ * @throws FileNotFoundException won't happen
+ */
+ @Test
+ public void testGrowingLive() throws CTFReaderException, FileNotFoundException, IOException {
+ try (CTFTraceReader reader = new CTFTraceReader(fFixture);) {
+ reader.setLive(true);
+ assertEquals("0x29", reader.getCurrentEventDef().getFields().getDefinition("f").toString());
+ reader.advance();
+ try (FileOutputStream fos = new FileOutputStream(fGrowingStream, true)) {
+ fos.write(fPackets[1]);
+ }
+ reader.advance();
+ assertNotNull(reader.getCurrentEventDef());
+ assertEquals("0xbab4face", reader.getCurrentEventDef().getFields().getDefinition("f").toString());
+ }
+ }
+
+ /**
+ * Test a growing stream
+ *
+ * @throws CTFReaderException won't happen
+ * @throws IOException won't happen
+ * @throws FileNotFoundException won't happen
+ */
+ @Test
+ public void testGrowingNotLive() throws CTFReaderException, FileNotFoundException, IOException {
+ try (CTFTraceReader reader = new CTFTraceReader(fFixture);) {
+ reader.setLive(false);
+ assertEquals("0x29", reader.getCurrentEventDef().getFields().getDefinition("f").toString());
+ reader.advance();
+ try (FileOutputStream fos = new FileOutputStream(fGrowingStream, true)) {
+ fos.write(fPackets[1]);
+ }
+ reader.advance();
+ assertNull(reader.getCurrentEventDef());
+ }
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.trace;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStreamReader;
+
+import org.eclipse.tracecompass.ctf.core.event.EventDefinition;
+import org.eclipse.tracecompass.ctf.core.tests.shared.CtfTestTrace;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTrace;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTraceReader;
+import org.eclipse.tracecompass.ctf.core.trace.Metadata;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * Tests for streaming support
+ *
+ * @author Matthew Khouzam
+ *
+ */
+public class CTFTraceGrowingTest {
+ final private String fPathName = CtfTestTrace.SYNTHETIC_TRACE.getPath();
+
+ final private CTFTrace fixture = new CTFTrace();
+
+ /**
+ * Init
+ *
+ * @throws IOException
+ * an IO error
+ * @throws FileNotFoundException
+ * file's not there
+ * @throws CTFReaderException
+ * error in metadata
+ */
+ @Before
+ public void init() throws FileNotFoundException, IOException, CTFReaderException {
+ Metadata md = new Metadata(fixture);
+ File metadata = new File(fPathName + "/" + "metadata");
+
+ try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(metadata)))) {
+
+ StringBuilder sb = new StringBuilder();
+ String line = null;
+ while ((line = reader.readLine()) != null) {
+ sb.append(line);
+ }
+ String result = sb.toString();
+ md.parseText(result);
+ }
+ }
+
+ /**
+ * Empty trace test
+ *
+ * @throws CTFReaderException
+ * will not happen
+ */
+ @Test
+ public void testEmptyStream() throws CTFReaderException {
+ try (CTFTraceReader reader = new CTFTraceReader(fixture);) {
+ assertNull(reader.getCurrentEventDef());
+ }
+ }
+
+ /**
+ * Add a stream
+ *
+ * @throws CTFReaderException
+ * should not happen
+ */
+ @Test
+ public void testAddStream() throws CTFReaderException {
+ File stream = new File(fPathName + "/" + "channel1");
+ try (CTFTraceReader reader = new CTFTraceReader(fixture);) {
+ fixture.addStreamFile(stream);
+ reader.update();
+ assertTrue(reader.advance());
+ assertNotNull(reader.getCurrentEventDef());
+ }
+ }
+
+ /**
+ * Adds two a stream
+ *
+ * @throws CTFReaderException
+ * should not happen
+ */
+ @Test
+ public void testAddTwoStreams1() throws CTFReaderException {
+ File stream = new File(fPathName + "/" + "channel1");
+ try (CTFTraceReader reader = new CTFTraceReader(fixture);) {
+ fixture.addStreamFile(stream);
+ stream = new File(fPathName + "/" + "channel2");
+ fixture.addStreamFile(stream);
+ reader.update();
+ assertTrue(reader.advance());
+ EventDefinition currentEventDef = reader.getCurrentEventDef();
+ assertNotNull(reader.getCurrentEventDef());
+ assertEquals(16518l, currentEventDef.getTimestamp());
+ }
+ }
+
+ /**
+ * Adds two a stream
+ *
+ * @throws CTFReaderException
+ * should not happen
+ */
+ @Test
+ public void testAddTwoStreams2() throws CTFReaderException {
+ File stream = new File(fPathName + "/" + "channel1");
+ try (CTFTraceReader reader = new CTFTraceReader(fixture);) {
+ fixture.addStreamFile(stream);
+ stream = new File(fPathName + "/" + "channel2");
+ reader.update();
+ assertTrue(reader.advance());
+ fixture.addStreamFile(stream);
+ reader.update();
+ assertTrue(reader.advance());
+ EventDefinition currentEventDef = reader.getCurrentEventDef();
+ assertNotNull(currentEventDef);
+ assertEquals(223007L, currentEventDef.getTimestamp());
+ }
+ }
+
+ /**
+ * Tests that update does not change the position
+ *
+ * @throws CTFReaderException
+ * should not happen
+ */
+ @Test
+ public void testAddTwoStreams3() throws CTFReaderException {
+ File stream = new File(fPathName + "/" + "channel1");
+ try (CTFTraceReader reader = new CTFTraceReader(fixture);) {
+ fixture.addStreamFile(stream);
+ stream = new File(fPathName + "/" + "channel2");
+ reader.update();
+ reader.update();
+ reader.update();
+ assertTrue(reader.advance());
+ fixture.addStreamFile(stream);
+ reader.update();
+ reader.update();
+ reader.update();
+ reader.update();
+ assertTrue(reader.advance());
+ EventDefinition currentEventDef = reader.getCurrentEventDef();
+ assertNotNull(currentEventDef);
+ assertEquals(223007L, currentEventDef.getTimestamp());
+ }
+ }
+
+ /**
+ * Test adding a bad stream
+ *
+ * @throws CTFReaderException
+ * should happen
+ */
+ @Test(expected = CTFReaderException.class)
+ public void testAddStreamFail() throws CTFReaderException {
+ File stream = new File(fPathName + "/" + "metadata");
+ try (CTFTraceReader reader = new CTFTraceReader(fixture);) {
+ fixture.addStreamFile(stream);
+ assertNull(reader.getCurrentEventDef());
+ }
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.trace;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assume.assumeTrue;
+
+import org.eclipse.tracecompass.ctf.core.event.EventDefinition;
+import org.eclipse.tracecompass.ctf.core.tests.shared.CtfTestTrace;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTrace;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTraceReader;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * The class <code>CTFTraceReaderTest</code> contains tests for the class
+ * <code>{@link CTFTraceReader}</code>.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+@SuppressWarnings("javadoc")
+public class CTFTraceReaderTest {
+
+ private static final CtfTestTrace testTrace = CtfTestTrace.KERNEL;
+
+ private CTFTraceReader fixture;
+
+ /**
+ * Perform pre-test initialization.
+ *
+ * @throws CTFReaderException
+ */
+ @Before
+ public void setUp() throws CTFReaderException {
+ assumeTrue(testTrace.exists());
+ fixture = new CTFTraceReader(testTrace.getTrace());
+ }
+
+ /**
+ * Run the CTFTraceReader(CTFTrace) constructor test. Open a known good
+ * trace.
+ *
+ * @throws CTFReaderException
+ */
+ @Test
+ public void testOpen_existing() throws CTFReaderException {
+ try (CTFTrace trace = testTrace.getTrace();
+ CTFTraceReader result = new CTFTraceReader(trace);) {
+ assertNotNull(result);
+ }
+ }
+
+ /**
+ * Run the CTFTraceReader(CTFTrace) constructor test. Open a non-existing
+ * trace, expect the exception.
+ *
+ * @throws CTFReaderException
+ */
+ @Test(expected = org.eclipse.tracecompass.ctf.core.trace.CTFReaderException.class)
+ public void testOpen_nonexisting() throws CTFReaderException {
+ try (CTFTrace trace = new CTFTrace("badfile.bad");
+ CTFTraceReader result = new CTFTraceReader(trace);) {
+ assertNotNull(result);
+ }
+ }
+
+ /**
+ * Run the CTFTraceReader(CTFTrace) constructor test. Try to pen an invalid
+ * path, expect exception.
+ *
+ * @throws CTFReaderException
+ */
+ @Test(expected = org.eclipse.tracecompass.ctf.core.trace.CTFReaderException.class)
+ public void testOpen_invalid() throws CTFReaderException {
+ try (CTFTrace trace = new CTFTrace("");
+ CTFTraceReader result = new CTFTraceReader(trace);) {
+ assertNotNull(result);
+ }
+ }
+
+ /**
+ * Run the boolean advance() method test. Test advancing normally.
+ * @throws CTFReaderException error
+ */
+ @Test
+ public void testAdvance_normal() throws CTFReaderException {
+ boolean result = fixture.advance();
+ assertTrue(result);
+ }
+
+ /**
+ * Run the boolean advance() method test. Test advancing when we're at the
+ * end, so we expect that there is no more events.
+ * @throws CTFReaderException error
+ */
+ @Test
+ public void testAdvance_end() throws CTFReaderException {
+ int i = 0;
+ boolean result = fixture.advance();
+ while (result) {
+ result = fixture.advance();
+ i++;
+ }
+ fixture.seek(0);
+ fixture.advance();
+ fixture.goToLastEvent();
+ i = 1;
+ result = fixture.advance();
+ while (result) {
+ result = fixture.advance();
+ i++;
+ }
+ assertFalse(result);
+ assertEquals(i, 1);
+ }
+
+ /**
+ * Run the CTFTraceReader copy constructor test.
+ * @throws CTFReaderException error
+ */
+ @Test
+ public void testCopyFrom() throws CTFReaderException {
+ try (CTFTraceReader result = fixture.copyFrom();) {
+ assertNotNull(result);
+ }
+ }
+
+ /**
+ * Test the hashCode method.
+ */
+ @Test
+ public void testHash() {
+ int result = fixture.hashCode();
+ assertTrue(0 != result);
+ }
+
+ /**
+ * Test the equals method. Uses the class-wide 'fixture' and another
+ * method-local 'fixture2', which both point to the same trace.
+ *
+ * Both trace reader are different objects, so they shouldn't "equals" each
+ * other.
+ *
+ * @throws CTFReaderException
+ */
+ @Test
+ public void testEquals() throws CTFReaderException {
+ try (CTFTraceReader fixture2 = new CTFTraceReader(testTrace.getTrace());) {
+ assertEquals(fixture, fixture2);
+ }
+ }
+
+ /**
+ * Run the getCurrentEventDef() method test. Get the first event's
+ * definition.
+ */
+ @Test
+ public void testGetCurrentEventDef_first() {
+ EventDefinition result = fixture.getCurrentEventDef();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the getCurrentEventDef() method test. Get the last event's
+ * definition.
+ * @throws CTFReaderException error
+ */
+ @Test
+ public void testGetCurrentEventDef_last() throws CTFReaderException {
+ fixture.goToLastEvent();
+ EventDefinition result = fixture.getCurrentEventDef();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the long getEndTime() method test.
+ */
+ @Test
+ public void testGetEndTime() {
+ long result = fixture.getEndTime();
+ assertTrue(0L < result);
+ }
+
+ /**
+ * Run the long getStartTime() method test.
+ */
+ @Test
+ public void testGetStartTime() {
+ long result = fixture.getStartTime();
+ assertTrue(0L < result);
+ }
+
+ /**
+ * Run the void goToLastEvent() method test.
+ * @throws CTFReaderException error
+ */
+ @Test
+ public void testGoToLastEvent() throws CTFReaderException {
+ fixture.goToLastEvent();
+ long ts1 = getTimestamp();
+ long ts2 = fixture.getEndTime();
+ assertEquals(ts1, ts2);
+ }
+
+ /**
+ * Run the boolean hasMoreEvents() method test.
+ *
+ * @throws CTFReaderException
+ */
+ @Test
+ public void testHasMoreEvents() {
+ boolean result = fixture.hasMoreEvents();
+ assertTrue(result);
+ }
+
+ /**
+ * Run the void printStats() method test with no 'width' parameter.
+ * @throws CTFReaderException error
+ */
+ @Test
+ public void testPrintStats_noparam() throws CTFReaderException {
+ fixture.advance();
+ fixture.printStats();
+ }
+
+ /**
+ * Run the void printStats(int) method test with width = 0.
+ * @throws CTFReaderException error
+ */
+ @Test
+ public void testPrintStats_width0() throws CTFReaderException {
+ fixture.advance();
+ fixture.printStats(0);
+ }
+
+ /**
+ * Run the void printStats(int) method test with width = 1.
+ * @throws CTFReaderException error
+ */
+ @Test
+ public void testPrintStats_width1() throws CTFReaderException {
+ fixture.advance();
+ fixture.printStats(1);
+ }
+
+ /**
+ * Run the void printStats(int) method test with width = 2.
+ * @throws CTFReaderException error
+ */
+ @Test
+ public void testPrintStats_width2() throws CTFReaderException {
+ fixture.advance();
+ fixture.printStats(2);
+ }
+
+ /**
+ * Run the void printStats(int) method test with width = 10.
+ * @throws CTFReaderException error
+ */
+ @Test
+ public void testPrintStats_width10() throws CTFReaderException {
+ fixture.advance();
+ fixture.printStats(10);
+ }
+
+ /**
+ * Run the void printStats(int) method test with width = 100.
+ * @throws CTFReaderException error
+ */
+ @Test
+ public void testPrintStats_100() throws CTFReaderException {
+ for (int i = 0; i < 1000; i++) {
+ fixture.advance();
+ }
+ fixture.printStats(100);
+ }
+
+ /**
+ * Run the boolean seek(long) method test.
+ * @throws CTFReaderException error
+ */
+ @Test
+ public void testSeek() throws CTFReaderException {
+ long timestamp = 1L;
+ boolean result = fixture.seek(timestamp);
+ assertTrue(result);
+ }
+
+
+
+ /**
+ * @return
+ */
+ private long getTimestamp() {
+ if (fixture.getCurrentEventDef() != null) {
+ return fixture.getTrace().timestampCyclesToNanos(fixture.getCurrentEventDef().getTimestamp());
+ }
+ return -1;
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013, 2014 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ * Marc-Andre Laperle - Test in traces directory recursively
+ * Simon Delisle - Add test for getCallsite(eventName, ip)
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.trace;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
+
+import java.io.File;
+import java.nio.ByteOrder;
+import java.util.UUID;
+
+import org.eclipse.tracecompass.ctf.core.event.CTFClock;
+import org.eclipse.tracecompass.ctf.core.event.types.IDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+import org.eclipse.tracecompass.ctf.core.tests.shared.CtfTestTrace;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.ctf.core.trace.CTFStream;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTrace;
+import org.eclipse.tracecompass.internal.ctf.core.event.metadata.exceptions.ParseException;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * The class <code>CTFTraceTest</code> contains tests for the class
+ * <code>{@link CTFTrace}</code>.
+ *
+ * @author ematkho
+ */
+public class CTFTraceTest {
+
+ private static final CtfTestTrace testTrace = CtfTestTrace.KERNEL;
+
+ private CTFTrace fixture;
+
+ /**
+ * Perform pre-test initialization.
+ */
+ @Before
+ public void setUp() {
+ assumeTrue(testTrace.exists());
+ try {
+ fixture = testTrace.getTraceFromFile();
+ } catch (CTFReaderException e) {
+ /* If the assumeTrue() call passed, this should not happen. */
+ fail();
+ }
+ fixture.setMinor(1L);
+ fixture.setUUID(UUID.randomUUID());
+ fixture.setPacketHeader(new StructDeclaration(1L));
+ fixture.setMajor(1L);
+ fixture.setByteOrder(ByteOrder.BIG_ENDIAN);
+ }
+
+ /**
+ * Run the CTFTrace(File) constructor test with a known existing trace.
+ */
+ @Test
+ public void testOpen_existing() {
+ try (CTFTrace result = testTrace.getTraceFromFile();) {
+ assertNotNull(result.getUUID());
+ } catch (CTFReaderException e) {
+ fail();
+ }
+ }
+
+ /**
+ * Run the CTFTrace(File) constructor test with an invalid path.
+ *
+ * @throws CTFReaderException
+ * is expected
+ */
+ @Test(expected = org.eclipse.tracecompass.ctf.core.trace.CTFReaderException.class)
+ public void testOpen_invalid() throws CTFReaderException {
+ File path = new File("");
+ try (CTFTrace result = new CTFTrace(path);) {
+ assertNotNull(result);
+ }
+ }
+
+ /**
+ * Run the boolean UUIDIsSet() method test.
+ */
+ @Test
+ public void testUUIDIsSet() {
+ boolean result = fixture.uuidIsSet();
+ assertTrue(result);
+ }
+
+ /**
+ * Run the void addStream(Stream) method test.
+ */
+ @Test
+ public void testAddStream() {
+ // test number of streams
+ int nbStreams = fixture.nbStreams();
+ assertEquals(1, nbStreams);
+
+ // Add a stream
+ try {
+ CTFStream stream = new CTFStream(testTrace.getTrace());
+ stream.setId(1234);
+ fixture.addStream(stream);
+ } catch (CTFReaderException e) {
+ fail();
+ } catch (ParseException e) {
+ fail();
+ }
+
+ // test number of streams
+ nbStreams = fixture.nbStreams();
+ assertEquals(2, nbStreams);
+ }
+
+ /**
+ * Run the boolean byteOrderIsSet() method test.
+ */
+ @Test
+ public void testByteOrderIsSet() {
+ boolean result = fixture.byteOrderIsSet();
+ assertTrue(result);
+ }
+
+ /**
+ * Run the ByteOrder getByteOrder() method test.
+ */
+ @Test
+ public void testGetByteOrder_1() {
+ ByteOrder result = fixture.getByteOrder();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the long getMajor() method test.
+ */
+ @Test
+ public void testGetMajor() {
+ long result = fixture.getMajor();
+ assertEquals(1L, result);
+ }
+
+ /**
+ * Run the long getMinor() method test.
+ */
+ @Test
+ public void testGetMinor() {
+ long result = fixture.getMinor();
+ assertEquals(1L, result);
+ }
+
+ /**
+ * Run the StructDeclaration getPacketHeader() method test.
+ */
+ @Test
+ public void testGetPacketHeader() {
+ StructDeclaration result = fixture.getPacketHeader();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the String getPath() method test.
+ */
+ @Test
+ public void testGetPath() {
+ String result = fixture.getPath();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the Stream getStream(Long) method test.
+ */
+ @Test
+ public void testGetStream() {
+ Long id = new Long(0L);
+ CTFStream result = fixture.getStream(id);
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the File getTraceDirectory() method test.
+ */
+ @Test
+ public void testGetTraceDirectory() {
+ File result = fixture.getTraceDirectory();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the UUID getUUID() method test.
+ */
+ @Test
+ public void testGetUUID() {
+ UUID result = fixture.getUUID();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the Definition lookupDefinition(String) method test.
+ */
+ @Test
+ public void testLookupDefinition() {
+ String lookupPath = "trace.packet.header";
+ IDefinition result = fixture.lookupDefinition(lookupPath);
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the boolean majorIsSet() method test.
+ */
+ @Test
+ public void testMajorIsSet() {
+ boolean result = fixture.majorIsSet();
+ assertTrue(result);
+ }
+
+ /**
+ * Run the boolean minorIsSet() method test.
+ */
+ @Test
+ public void testMinorIsSet() {
+ boolean result = fixture.minorIsSet();
+ assertTrue(result);
+ }
+
+ /**
+ * Run the boolean packetHeaderIsSet() method test with a valid header set.
+ */
+ @Test
+ public void testPacketHeaderIsSet_valid() {
+ boolean result = fixture.packetHeaderIsSet();
+ assertTrue(result);
+ }
+
+ /**
+ * Run the boolean packetHeaderIsSet() method test, without having a valid
+ * header set.
+ */
+ @Test
+ public void testPacketHeaderIsSet_invalid() {
+ try (CTFTrace fixture2 = testTrace.getTraceFromFile();){
+ fixture2.setMinor(1L);
+ fixture2.setUUID(UUID.randomUUID());
+ fixture2.setPacketHeader((StructDeclaration) null); /* it's null here! */
+ fixture2.setMajor(1L);
+ fixture2.setByteOrder(ByteOrder.BIG_ENDIAN);
+
+ boolean result = fixture2.packetHeaderIsSet();
+ assertFalse(result);
+ } catch (CTFReaderException e) {
+ fail();
+ }
+ }
+
+ /**
+ * Run the void setByteOrder(ByteOrder) method test.
+ */
+ @Test
+ public void testSetByteOrder() {
+ ByteOrder byteOrder = ByteOrder.BIG_ENDIAN;
+ fixture.setByteOrder(byteOrder);
+ }
+
+ /**
+ * Run the void setMajor(long) method test.
+ */
+ @Test
+ public void testSetMajor() {
+ long major = 1L;
+ fixture.setMajor(major);
+ }
+
+ /**
+ * Run the void setMinor(long) method test.
+ */
+ @Test
+ public void testSetMinor() {
+ long minor = 1L;
+ fixture.setMinor(minor);
+ }
+
+ /**
+ * Run the void setPacketHeader(StructDeclaration) method test.
+ */
+ @Test
+ public void testSetPacketHeader() {
+ StructDeclaration packetHeader = new StructDeclaration(1L);
+ fixture.setPacketHeader(packetHeader);
+ }
+
+ /**
+ * Run the void setUUID(UUID) method test.
+ */
+ @Test
+ public void testSetUUID() {
+ UUID uuid = UUID.randomUUID();
+ fixture.setUUID(uuid);
+ }
+
+ /**
+ * Run the CTFClock getClock/setClock method test.
+ */
+ @Test
+ public void testGetSetClock_1() {
+ String name = "clockyClock";
+ fixture.addClock(name, new CTFClock());
+ CTFClock result = fixture.getClock(name);
+
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the CTFClock getClock/setClock method test.
+ */
+ @Test
+ public void testGetSetClock_2() {
+ String name = "";
+ CTFClock ctfClock = new CTFClock();
+ ctfClock.addAttribute("name", "Bob");
+ ctfClock.addAttribute("pi", new Double(java.lang.Math.PI));
+ fixture.addClock(name, ctfClock);
+ CTFClock result = fixture.getClock(name);
+
+ assertNotNull(result);
+ assertTrue((Double) ctfClock.getProperty("pi") > 3.0);
+ assertTrue(ctfClock.getName().equals("Bob"));
+ }
+
+ /**
+ * Run the String lookupEnvironment(String) method test.
+ */
+ @Test
+ public void testLookupEnvironment_1() {
+ String key = "";
+ String result = fixture.getEnvironment().get(key);
+ assertNull(result);
+ }
+
+ /**
+ * Run the String lookupEnvironment(String) method test.
+ */
+ @Test
+ public void testLookupEnvironment_2() {
+ String key = "otherTest";
+ String result = fixture.getEnvironment().get(key);
+ assertNull(result);
+ }
+
+ /**
+ * Run the String lookupEnvironment(String) method test.
+ */
+ @Test
+ public void testLookupEnvironment_3() {
+ String key = "test";
+ fixture.addEnvironmentVar(key, key);
+ String result = fixture.getEnvironment().get(key);
+ assertTrue(result.equals(key));
+ }
+
+ /**
+ * Run the String lookupEnvironment(String) method test.
+ */
+ @Test
+ public void testLookupEnvironment_4() {
+ String key = "test";
+ fixture.addEnvironmentVar(key, "bozo");
+ fixture.addEnvironmentVar(key, "the clown");
+ String result = fixture.getEnvironment().get(key);
+ assertNotNull(result);
+ }
+
+ /**
+ * Test for getCallsite(eventName, ip)
+ * @throws CTFReaderException not expected
+ */
+ @Test
+ public void callsitePosition() throws CTFReaderException {
+ long ip1 = 2;
+ long ip2 = 5;
+ long ip3 = 7;
+ try (CTFTrace callsiteTest = testTrace.getTraceFromFile()) {
+ callsiteTest.addCallsite("testEvent", null, ip1, null, 23);
+ callsiteTest.addCallsite("testEvent", null, ip2, null, 50);
+ callsiteTest.addCallsite("testEvent", null, ip3, null, 15);
+
+ assertEquals(2, (callsiteTest.getCallsite("testEvent", 1)).getIp());
+ assertEquals(2, (callsiteTest.getCallsite("testEvent", 2)).getIp());
+ assertEquals(5, (callsiteTest.getCallsite("testEvent", 3)).getIp());
+ assertEquals(5, (callsiteTest.getCallsite("testEvent", 5)).getIp());
+ assertEquals(7, (callsiteTest.getCallsite("testEvent", 6)).getIp());
+ assertEquals(7, (callsiteTest.getCallsite("testEvent", 7)).getIp());
+ assertEquals(7, (callsiteTest.getCallsite("testEvent", 8)).getIp());
+ }
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013, 2014 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ * Simon Delisle - Generate dummy trace
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.trace;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.tracecompass.ctf.core.event.IEventDeclaration;
+import org.eclipse.tracecompass.ctf.core.tests.CtfCoreTestPlugin;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTrace;
+import org.eclipse.tracecompass.internal.ctf.core.event.EventDeclaration;
+import org.eclipse.tracecompass.internal.ctf.core.event.metadata.IOStructGen;
+import org.junit.After;
+import org.junit.Test;
+
+/**
+ * Unit tests for {@link IOStructGen}
+ *
+ * @author Matthew Khouzam
+ */
+public class IOstructgenTest {
+
+ private static final String metadataDecs = "typealias integer { size = 8; align = 8; signed = false; } := uint8_t;\n"
+ + "typealias integer { size = 16; align = 8; signed = false; } := uint16_t;\n"
+ + "typealias integer { size = 32; align = 8; signed = false; } := uint32_t;\n"
+ + "typealias integer { size = 64; align = 8; signed = false; } := uint64_t;\n"
+ + "typealias integer { size = 64; align = 8; signed = false; } := unsigned long;\n"
+ + "typealias integer { size = 5; align = 1; signed = false; } := uint5_t;\n"
+ + "typealias integer { size = 27; align = 1; signed = false; } := uint27_t;\n"
+ + "typealias integer { size = 32; align = 1; signed = true; base = decimal; } := int32_t;\n"
+ + "typealias integer { size = 31; align = 1; signed = true; base = dec; } := int31_t;\n"
+ + "typealias integer { size = 30; align = 1; signed = true; base = d; } := int30_t;\n"
+ + "typealias integer { size = 29; align = 1; signed = true; base = i; } := int29_t;\n"
+ + "typealias integer { size = 28; align = 1; signed = true; base = u; } := int28_t;\n"
+ + "typealias integer { size = 27; align = 1; signed = true; base = hexadecimal; } := int27_t;\n"
+ + "typealias integer { size = 26; align = 1; signed = true; base = hex; } := int26_t;\n"
+ + "typealias integer { size = 25; align = 1; signed = true; base = x; } := int25_t;\n"
+ + "typealias integer { size = 24; align = 1; signed = true; base = X; } := int24_t;\n"
+ + "typealias integer { size = 23; align = 1; signed = true; base = p; } := int23_t;\n"
+ + "typealias integer { size = 22; align = 1; signed = true; base = 16; } := int22_t;\n"
+ + "typealias integer { size = 21; align = 1; signed = true; base = oct; } := int21_t;\n"
+ + "typealias integer { size = 20; align = 1; signed = true; base = b; } := int20_t;\n"
+ + "typealias integer { size = 19; align = 1; signed = true; base = octal; } := int19_t;\n"
+ + "typealias integer { size = 18; align = 1; signed = true; base = o; } := int18_t;\n"
+ + "typealias integer { size = 17; align = 1; signed = true; base = binary; } := int17_t;\n"
+ + "\n"
+ + "trace {\n"
+ + " major = 1;\n"
+ + " minor = 8;\n"
+ + " uuid = \"b04d391b-e736-44c1-8d89-4bb438857f8d\";\n"
+ + " byte_order = le;\n"
+ + " packet.header := struct {\n"
+ + " uint32_t magic;\n"
+ + " uint8_t uuid[16];\n"
+ + " uint32_t stream_id;\n" + " };\n" + "};\n" + "\n";
+ private static final String environmentMD = "env {\n"
+ + " hostname = \"DemoSystem\";\n"
+ + " vpid = 1337;\n"
+ + " procname = \"demo\";\n"
+ + " domain = \"autogenerated\";\n"
+ + " tracer_name = \"tmf\";\n"
+ + " tracer_major = 2;\n"
+ + " tracer_minor = 0x01;\n"
+ + " tracer_patchlevel = 0;\n"
+ + "};\n" + "\n";
+ private static final String clockMD = "clock {\n" + " name = monotonic;\n"
+ + " uuid = \"cbf9f42e-9be7-4798-a96f-11db556e2ebb\";\n"
+ + " description = \"Monotonic Clock\";\n"
+ + " freq = 1000000000; /* Frequency, in Hz */\n"
+ + " /* clock value offset from Epoch is: offset * (1/freq) */\n"
+ + " offset = 1350310657466295832;\n" + "};\n"
+ + "\n";
+
+ private static final String ctfStart =
+ "typealias integer {\n"
+ + " size = 27; align = 1; signed = false;\n"
+ + " map = clock.monotonic.value;\n"
+ + "} := uint27_clock_monotonic_t;\n"
+ + "\n"
+ + "typealias integer {\n"
+ + " size = 32; align = 8; signed = false;\n"
+ + " map = clock.monotonic.value;\n"
+ + "} := uint32_clock_monotonic_t;\n"
+ + "\n"
+ + "typealias integer {\n"
+ + " size = 64; align = 8; signed = false;\n"
+ + " map = clock.monotonic.value;\n"
+ + "} := uint64_clock_monotonic_t;\n"
+ + "\n";
+
+ private static final String ctfHeaders =
+ "struct packet_context {\n"
+ + " uint64_clock_monotonic_t timestamp_begin;\n"
+ + " uint64_clock_monotonic_t timestamp_end;\n"
+ + " uint64_t content_size;\n"
+ + " uint64_t packet_size;\n"
+ + " unsigned long events_discarded;\n"
+ + " uint32_t cpu_id;\n"
+ + "};\n"
+ + "\n"
+ + "struct event_header_compact {\n"
+ + " enum : uint5_t { compact = 0 ... 30, extended = 31 } id;\n"
+ + " variant <id> {\n"
+ + " struct {\n"
+ + " uint27_clock_monotonic_t timestamp;\n"
+ + " } compact;\n"
+ + " struct {\n"
+ + " uint32_t id;\n"
+ + " uint64_clock_monotonic_t timestamp;\n"
+ + " } extended;\n"
+ + " } v;\n"
+ + "} align(8);\n"
+ + "\n"
+ + "struct event_header_large {\n"
+ + " enum : uint16_t { compact = 0 ... 65534, extended = 65535 } id;\n"
+ + " variant <id> {\n" + " struct {\n"
+ + " uint32_clock_monotonic_t timestamp;\n"
+ + " } compact;\n" + " struct {\n"
+ + " uint32_t id;\n"
+ + " uint64_clock_monotonic_t timestamp;\n"
+ + " } extended;\n" + " } v;\n" + "} align(8);\n" + "\n";
+
+ private static final String ctfBody = "stream {\n"
+ + " id = 0;\n"
+ + " event.header := struct event_header_compact;\n"
+ + " packet.context := struct packet_context;\n"
+ + " event.context := struct {\n"
+ + " integer { size = 64; align = 8; signed = 0; encoding = none; base = 16; } _ip;\n"
+ + " };\n"
+ + "};\n"
+ + "\n"
+ + "event {\n"
+ + " name = \"ust_tests_demo3:done\";\n"
+ + " id = 0;\n"
+ + " stream_id = 0;\n"
+ + " loglevel = 4;\n"
+ + " fields := struct {\n"
+ + " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _value;\n"
+ + " };\n"
+ + "};\n"
+ + "\n"
+ + "event {\n"
+ + " name = \"ust_tests_demo:starting\";\n"
+ + " id = 1;\n"
+ + " stream_id = 0;\n"
+ + " loglevel = 2;\n"
+ + " model.emf.uri = \"http://example.com/path_to_model?q=ust_tests_demo:starting\";\n"
+ + " fields := struct {\n"
+ + " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _value;\n"
+ + " };\n"
+ + "};\n"
+ + "\n"
+ + "event {\n"
+ + " name = \"ust_tests_demo:done\";\n"
+ + " id = 2;\n"
+ + " stream_id = 0;\n"
+ + " loglevel = 2;\n"
+ + " model.emf.uri = \"http://example.com/path_to_model?q=ust_tests_demo:done\";\n"
+ + " fields := struct {\n"
+ + " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _value;\n"
+ + " };\n"
+ + "};\n"
+ + "\n"
+ + "event {\n"
+ + " name = \"ust_tests_demo2:loop\";\n"
+ + " id = 3;\n"
+ + " stream_id = 0;\n"
+ + " loglevel = 4;\n"
+ + " fields := struct {\n"
+ + " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _intfield;\n"
+ + " integer { size = 32; align = 8; signed = 1; encoding = none; base = 16; } _intfield2;\n"
+ + " integer { size = 64; align = 8; signed = 1; encoding = none; base = 10; } _longfield;\n"
+ + " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; byte_order = be; } _netintfield;\n"
+ + " integer { size = 32; align = 8; signed = 1; encoding = none; base = 16; byte_order = be; } _netintfieldhex;\n"
+ + " integer { size = 64; align = 8; signed = 1; encoding = none; base = 10; } _arrfield1[3];\n"
+ + " integer { size = 8; align = 8; signed = 1; encoding = UTF8; base = 10; } _arrfield2[10];\n"
+ + " integer { size = 64; align = 8; signed = 0; encoding = none; base = 10; } __seqfield1_length;\n"
+ + " integer { size = 8; align = 8; signed = 1; encoding = none; base = 10; } _seqfield1[ __seqfield1_length ];\n"
+ + " integer { size = 64; align = 8; signed = 0; encoding = none; base = 10; } __seqfield2_length;\n"
+ + " integer { size = 8; align = 8; signed = 1; encoding = UTF8; base = 10; } _seqfield2[ __seqfield2_length ];\n"
+ + " string _stringfield;\n"
+ + " floating_point { exp_dig = 8; mant_dig = 24; align = 8; } _floatfield;\n"
+ + " floating_point { exp_dig = 11; mant_dig = 53; align = 8; } _doublefield;\n"
+ + " };\n"
+ + "};\n"
+ + "\n";
+
+ private static final String enumMd =
+ "typealias integer { size = 32; align = 8; signed = false; } := int;\n"
+ + "typealias enum { ONE = 0, a,b,c=10, d} := useless_enum;\n"
+ + "struct useless{ \n"
+ + " enum : uint8_t { A=0, \"B\",} enum3;\n"
+ + " useless_enum enum2;"
+ + " enum { C, D, E } enum4;\n"
+ + " uint16_t val;\n"
+ + "} ;\n"
+ + "\n"
+ + "event {\n"
+ + " name = \"enumEvent\";\n"
+ + " id = 6;\n"
+ + " stream_id = 0;\n"
+ + " loglevel = 5;\n"
+ + " fields := struct{\n"
+ + " uint16_t _some_field;\n"
+ // + " useless junk;\n"
+ // + " bad_enum a;\n"
+ + " enum {A, B, C = 3 , } _other_enum;\n"
+ + " };\n"
+ + "};\n"
+ + "\n";
+
+ private final static String contextMD =
+ "event {\n" +
+ " name = \"someOtherEvent\";\n" +
+ " id = 5;\n" +
+ " stream_id = 0;\n" +
+ " loglevel = 5;\n" +
+ " context := struct{\n" +
+ " uint16_t _someContext;\n" +
+ " };\n" +
+ " fields := struct{\n" +
+ " uint16_t _somefield;\n" +
+ " };\n" +
+ "};\n " +
+ "\n";
+
+ private static final String callsiteMD =
+ "callsite {\n"
+ + " name = \"ust_tests_demo2:loop\";\n"
+ + " func = \"main\";\n" + " ip = 0x400a29;\n"
+ + " file = \"demo.c\";\n" + " line = 59;\n" + "};\n" + "\n"
+ + "callsite {\n" + " name = \"ust_tests_demo3:done\";\n"
+ + " func = \"main\";\n" + " ip = 0x400a6c;\n"
+ + " file = \"demo.c\";\n" + " line = 62;\n" + "};\n" + "\n"
+ + "callsite {\n" + " name = \"ust_tests_demo:done\";\n"
+ + " func = \"main\";\n" + " ip = 0x400aaf;\n"
+ + " file = \"demo.c\";\n" + " line = 61;\n" + "};\n" + "\n"
+ + "callsite {\n" + " name = \"ust_tests_demo:starting\";\n"
+ + " func = \"main\";\n" + " ip = 0x400af2;\n"
+ + " file = \"demo.c\";\n" + " line = 55;\n" + "};\n";
+
+ private static final String simpleTSDL = metadataDecs + ctfStart + ctfHeaders
+ + ctfBody;
+ private static final String enumTSDL = metadataDecs + ctfStart + ctfHeaders
+ + ctfBody + enumMd;
+ private static final String clockTSDL = metadataDecs + clockMD + ctfStart
+ + ctfHeaders + ctfBody;
+ private static final String envTSDL = metadataDecs + environmentMD + ctfStart
+ + ctfHeaders + ctfBody;
+ private static final String contextTSDL = metadataDecs + environmentMD + ctfStart
+ + ctfHeaders + ctfBody + contextMD;
+ private static final String callsiteTSDL = metadataDecs + ctfStart + ctfHeaders
+ + ctfBody + callsiteMD;
+ private static final String allDressedTSDL = metadataDecs + environmentMD + clockMD
+ + ctfStart + ctfHeaders + ctfBody + enumMd + callsiteMD;
+
+ static final String tempTraceDir = CtfCoreTestPlugin.getTemporaryDirPath()
+ + File.separator + "tempTrace";
+
+ private static final int DATA_SIZE = 4096;
+
+ private static final int HEADER_SIZE = 68;
+
+ private static final int PACKET_SIZE = DATA_SIZE + HEADER_SIZE + 512;
+
+ private CTFTrace trace;
+
+ private static class Event {
+ private static final int EVENT_SIZE = 16;
+ private int eventId;
+ private int eventTimestamp;
+ private int eventContent;
+
+ public Event(int id, int content) {
+ eventId = id;
+ eventTimestamp = 0;
+ eventContent = content;
+ }
+
+ public void setEventTimestamp(int eventTimestamp) {
+ this.eventTimestamp = eventTimestamp;
+ }
+
+ public void setEventContent(int eventContent) {
+ this.eventContent = eventContent;
+ }
+
+ public void writeEvent(ByteBuffer data) {
+ // Id and Timestamp
+ int timeId = eventTimestamp << 5;
+ timeId |= eventId & 0x1f;
+ data.putInt(timeId);
+
+ // Context
+ long ip = 0x0000facedecafe00L + ((data.position() /
+ getSize()) & 0x0F);
+ data.putLong(ip);
+
+ // Content
+ data.putInt(eventContent);
+
+ }
+
+ public int getSize() {
+ return EVENT_SIZE;
+ }
+
+ }
+
+ private static void deltree(File f) {
+ for (File elem : f.listFiles()) {
+ if (elem.isDirectory()) {
+ deltree(elem);
+ }
+ elem.delete();
+ }
+ f.delete();
+ }
+
+ private static void createDummyTrace(String metadata) {
+ File dir = new File(tempTraceDir);
+ if (dir.exists()) {
+ deltree(dir);
+ }
+ dir.mkdirs();
+
+ File metadataFile = new File(tempTraceDir + "/metadata");
+ try (FileWriter fw = new FileWriter(metadataFile);) {
+ fw.write(metadata);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ byte magicLE[] = { (byte) 0xC1, (byte) 0x1F, (byte) 0xFC,
+ (byte) 0xC1 };
+ byte uuid[] = { (byte) 0xb0, 0x4d, 0x39, 0x1b, (byte) 0xe7,
+ 0x36, 0x44, (byte) 0xc1, (byte) 0x8d, (byte) 0x89, 0x4b,
+ (byte) 0xb4, 0x38, (byte) 0x85, 0x7f, (byte) 0x8d };
+
+ Event ev = new Event(2, 2);
+
+ final int nbEvents = (DATA_SIZE / ev.getSize()) - 1;
+ final int contentSize = (nbEvents * ev.getSize() +
+ HEADER_SIZE) * 8;
+
+ ByteBuffer data = ByteBuffer.allocate(PACKET_SIZE);
+ data.order(ByteOrder.LITTLE_ENDIAN);
+ data.clear();
+
+ // packet header
+ // magic number 4
+ data.put(magicLE);
+ // uuid 16
+ data.put(uuid);
+ // stream ID 4
+ data.putInt(0);
+
+ // packet context
+ // timestamp_begin 8
+ data.putLong(0xa500);
+
+ // timestamp_end 8
+ data.putLong(nbEvents * 0x10000 + 0xa5a6);
+
+ // content_size 8
+ data.putLong(contentSize);
+
+ // packet_size 8
+ data.putLong(PACKET_SIZE * 8);
+
+ // events_discarded 8
+ data.putLong(0);
+
+ // cpu_id 4
+ data.putInt(0);
+
+ // fill me
+ for (int i = 0; i < nbEvents; i++) {
+ ev.setEventTimestamp(i * 0x10000 + 0xa5a5);
+ ev.setEventContent(i);
+ ev.writeEvent(data);
+ }
+
+ // The byteBuffer needs to be flipped in file writing mode
+ data.flip();
+
+ File dummyFile = new File(tempTraceDir + "/dummyChan");
+ try (FileOutputStream fos = new FileOutputStream(dummyFile);) {
+ fos.getChannel().write(data);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ /**
+ * Close trace
+ */
+ @After
+ public void tearDown(){
+ trace.close();
+ }
+
+ /**
+ * Simple test (only the minimum)
+ *
+ * @throws CTFReaderException
+ * something wrong happened
+ */
+ @Test
+ public void TSDLSimpleTest() throws CTFReaderException {
+ createDummyTrace(simpleTSDL);
+ trace = new CTFTrace(tempTraceDir);
+ assertNotNull(trace);
+ }
+
+ /**
+ * Test with environment variables
+ *
+ * @throws CTFReaderException
+ * something wrong happened
+ */
+ @Test
+ public void TSDLEnvironmentTest() throws CTFReaderException {
+ createDummyTrace(envTSDL);
+ trace = new CTFTrace(tempTraceDir);
+ assertNotNull(trace);
+ }
+
+ /**
+ * Test with Clocks
+ *
+ * @throws CTFReaderException
+ * something wrong happened
+ */
+ @Test
+ public void TSDLEnumTest() throws CTFReaderException {
+ createDummyTrace(enumTSDL);
+ trace = new CTFTrace(tempTraceDir);
+ assertNotNull(trace);
+ }
+
+ /**
+ * Test with Clocks
+ *
+ * @throws CTFReaderException
+ * something wrong happened
+ */
+ @Test
+ public void TSDLClockTest() throws CTFReaderException {
+ createDummyTrace(clockTSDL);
+ trace = new CTFTrace(tempTraceDir);
+ assertNotNull(trace);
+ }
+
+ /**
+ * Test with Contexts
+ *
+ * @throws CTFReaderException
+ * something wrong happened
+ */
+ @Test
+ public void TSDLContextTest() throws CTFReaderException {
+ createDummyTrace(contextTSDL);
+ trace = new CTFTrace(tempTraceDir);
+ assertNotNull(trace);
+ }
+
+ /**
+ * Test with Callsites
+ *
+ * @throws CTFReaderException
+ * something wrong happened
+ */
+ @Test
+ public void TSDLCallsiteTest() throws CTFReaderException {
+ createDummyTrace(callsiteTSDL);
+ trace = new CTFTrace(tempTraceDir);
+ assertNotNull(trace);
+ }
+
+ /**
+ * Test everything
+ *
+ * @throws CTFReaderException
+ * something wrong happened
+ */
+ @Test
+ public void TSDLAllTest() throws CTFReaderException {
+ createDummyTrace(allDressedTSDL);
+ trace = new CTFTrace(tempTraceDir);
+ assertNotNull(trace);
+
+ final List<IEventDeclaration> eventDeclarations = new ArrayList<>(trace.getEventDeclarations(0L));
+ final EventDeclaration eventDeclaration = (EventDeclaration) eventDeclarations.get(2);
+ assertEquals("http://example.com/path_to_model?q=ust_tests_demo:done",
+ eventDeclaration.getCustomAttribute("model.emf.uri"));
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013, 2014 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.trace;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
+
+import java.nio.ByteOrder;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+
+import org.eclipse.tracecompass.ctf.core.event.IEventDeclaration;
+import org.eclipse.tracecompass.ctf.core.tests.shared.CtfTestTrace;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.ctf.core.trace.CTFStream;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTrace;
+import org.eclipse.tracecompass.ctf.core.trace.Metadata;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * The class <code>MetadataTest</code> contains tests for the class
+ * <code>{@link Metadata}</code>.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+@SuppressWarnings("javadoc")
+public class MetadataTest {
+
+ private static final CtfTestTrace testTrace = CtfTestTrace.KERNEL;
+ private static final String mdStart = "typealias integer { size = 8; align = 8; signed = false; } := uint8_t;\n" +
+ " typealias integer { size = 16; align = 8; signed = false; } := uint16_t;\n" +
+ " typealias integer { size = 32; align = 8; signed = false; } := uint32_t;\n" +
+ " typealias integer { size = 64; align = 8; signed = false; } := uint64_t;\n" +
+ " typealias integer { size = 64; align = 8; signed = false; } := unsigned long;\n" +
+ " typealias integer { size = 5; align = 1; signed = false; } := uint5_t;\n" +
+ " typealias integer { size = 27; align = 1; signed = false; } := uint27_t;\n" +
+ "" +
+ " trace {\n" +
+ " major = 1;\n" +
+ " minor = 8;\n" +
+ " uuid = \"8b1258ba-effb-554b-b779-fbd676746000\";\n" +
+ " byte_order = le;\n" +
+ " packet.header := struct {\n" +
+ " uint32_t magic;\n" +
+ " uint8_t uuid[16];\n" +
+ " uint32_t stream_id;\n" +
+ " };\n" +
+ " };\n" +
+ "" +
+ " env {\n" +
+ " hostname = \"computer\";\n" +
+ " domain = \"kernel\";\n" +
+ " sysname = \"BeOS\";\n" +
+ " kernel_release = \"95\";\n" +
+ " kernel_version = \"BeWare 95\";\n" +
+ " tracer_name = \"BeOS Tracer\";\n" +
+ " tracer_major = 2;\n" +
+ " tracer_minor = 3;\n" +
+ " tracer_patchlevel = 0;\n" +
+ " };\n" +
+ " clock {\n" +
+ " name = monotonic;\n" +
+ " uuid = \"4d737a79-e3f1-4f4d-a649-42015266baf5\";\n" +
+ " description = \"Monotonic Clock\";\n" +
+ " freq = 1000000000; /* Frequency, in Hz */\n" +
+ " /* clock value offset from Epoch is: offset * (1/freq) */\n" +
+ " offset = 1383600210829415521;\n" +
+ " };\n" +
+
+ " typealias integer {\n" +
+ "size = 27; align = 1; signed = false;\n" +
+ " map = clock.monotonic.value;\n" +
+ " } := uint27_clock_monotonic_t;\n" +
+ " \n" +
+ " typealias integer {\n" +
+ " size = 32; align = 8; signed = false;\n" +
+ " map = clock.monotonic.value;\n" +
+ " } := uint32_clock_monotonic_t;\n" +
+ " \n" +
+ " typealias integer {\n" +
+ " size = 64; align = 8; signed = false;\n" +
+ " map = clock.monotonic.value;\n" +
+ " } := uint64_clock_monotonic_t;\n" +
+ " \n" +
+ " struct packet_context {\n" +
+ " uint64_clock_monotonic_t timestamp_begin;\n" +
+ " uint64_clock_monotonic_t timestamp_end;\n" +
+ " uint64_t content_size;\n" +
+ " uint64_t packet_size;\n" +
+ " unsigned long events_discarded;\n" +
+ " uint32_t cpu_id;\n" +
+ " };\n" +
+ " \n" +
+ " struct event_header_compact {\n" +
+ " enum : uint5_t { compact = 0 ... 30, extended = 31 } id;\n" +
+ " variant <id> {\n" +
+ " struct {\n" +
+ " uint27_clock_monotonic_t timestamp;\n" +
+ " } compact;\n" +
+ " struct {\n" +
+ " uint32_t id;\n" +
+ " uint64_clock_monotonic_t timestamp;\n" +
+ " } extended;\n" +
+ " } v;\n" +
+ " } align(8);\n" +
+ " \n" +
+ " struct event_header_large {\n" +
+ " enum : uint16_t { compact = 0 ... 65534, extended = 65535 } id;\n" +
+ " variant <id> {\n" +
+ " struct {\n" +
+ " uint32_clock_monotonic_t timestamp;\n" +
+ " } compact;\n" +
+ " struct {\n" +
+ " uint32_t id;\n" +
+ " uint64_clock_monotonic_t timestamp;\n" +
+ " } extended;\n" +
+ " } v;\n" +
+ " } align(8);\n" +
+ " \n" +
+ " stream {\n" +
+ " id = 0;\n" +
+ " event.header := struct event_header_compact;\n" +
+ " packet.context := struct packet_context;\n" +
+ " };\n" +
+ " \n" +
+ " event {\n" +
+ " name = sched_switch;\n" +
+ " id = 0;\n" +
+ " stream_id = 0;\n" +
+ " fields := struct {\n" +
+ " integer { size = 8; align = 8; signed = 1; encoding = UTF8; base = 10; } _prev_comm[16];\n" +
+ " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _prev_tid;\n" +
+ " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _prev_prio;\n" +
+ " integer { size = 64; align = 8; signed = 1; encoding = none; base = 10; } _prev_state;\n" +
+ " integer { size = 8; align = 8; signed = 1; encoding = UTF8; base = 10; } _next_comm[16];\n" +
+ " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _next_tid;\n" +
+ " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _next_prio;\n" +
+ " };\n" +
+ " };";
+
+ private static final String mdSecond = " event {\n" +
+ " name = bozo_the_clown;\n" +
+ " id = 1;\n" +
+ " stream_id = 0;\n" +
+ " fields := struct {\n" +
+ " integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } clown_nose;\n" +
+ " };\n" +
+ " };";
+
+ private Metadata fixture;
+
+ /**
+ * Perform pre-test initialization.
+ *
+ * @throws CTFReaderException
+ */
+ @Before
+ public void setUp() throws CTFReaderException {
+ assumeTrue(testTrace.exists());
+ fixture = new Metadata(testTrace.getTrace());
+ }
+
+ /**
+ * Run the Metadata(CTFTrace) constructor test.
+ */
+ @Test
+ public void testMetadata() {
+ assertNotNull(fixture);
+ }
+
+ @Test
+ public void testTextMD() throws CTFReaderException {
+ testSingleFragment();
+ }
+
+ protected CTFTrace testSingleFragment() throws CTFReaderException {
+ fixture = new Metadata();
+ CTFTrace trace = fixture.getTrace();
+ for (CTFStream s : trace.getStreams()) {
+ fail("This should be empty, has" + s.toString());
+ }
+ fixture.parseText(mdStart);
+ int count = 0;
+ for (CTFStream s : trace.getStreams()) {
+ count++;
+ assertNotNull(s);
+ }
+ assertEquals(1, count);
+ assertEquals(1, trace.getEventDeclarations(0L).size());
+ return trace;
+ }
+
+ @Test
+ public void testStreamTextMD() throws CTFReaderException {
+ try (CTFTrace trace = testSingleFragment();) {
+ fixture.parseTextFragment(mdSecond);
+ final List<IEventDeclaration> eventDeclarations = new ArrayList<>(trace.getEventDeclarations(0L));
+ assertEquals(2, eventDeclarations.size());
+ assertEquals("bozo_the_clown", eventDeclarations.get(1).getName());
+ }
+ }
+
+ /**
+ * Run the ByteOrder getDetectedByteOrder() method test.
+ *
+ * @throws CTFReaderException
+ */
+ @Test
+ public void testGetDetectedByteOrder() throws CTFReaderException {
+ setUp();
+ ByteOrder result = fixture.getDetectedByteOrder();
+ assertNull(result);
+ }
+
+ /**
+ * Test toString
+ *
+ * @throws CTFReaderException
+ */
+ @Test
+ public void testToString() throws CTFReaderException {
+ setUp();
+ String result = fixture.toString();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the void parse() method test.
+ *
+ * @throws CTFReaderException
+ */
+ @Test
+ public void testParse() throws CTFReaderException {
+ setUp();
+ assertEquals(new UUID(0xd18e637435a1cd42L, 0x8e70a9cffa712793L), testTrace.getTrace().getUUID());
+ assertEquals(1332166405241713920.0, testTrace.getTrace().getClock().getClockOffset(), 200.0);
+ assertEquals(8, testTrace.getTrace().getEnvironment().size());
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013-2014 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.trace;
+
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+
+/**
+ * The class <code>TestAll</code> builds a suite that can be used to run all of
+ * the tests within its package as well as within any subpackages of its
+ * package.
+ *
+ * @author Matthew Khouzam
+ * @version $Revision: 1.0 $
+ */
+@RunWith(Suite.class)
+@Suite.SuiteClasses({
+ CTFTraceCallsitePerformanceTest.class,
+ CTFTraceReaderTest.class,
+ CTFTraceTest.class,
+ CTFTraceGrowingTest.class,
+ IOstructgenTest.class,
+ MetadataTest.class,
+ CTFStreamInputPacketIndexEntryTest.class,
+ CTFStreamInputPacketIndexTest.class,
+ CTFStreamInputReaderTest.class,
+ CTFStreamInputReaderTimestampComparatorTest.class,
+ CTFStreamInputTest.class,
+ CTFStreamTest.class,
+ UtilsTest.class
+})
+public class TestAll {
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.trace;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import java.util.UUID;
+
+import org.eclipse.tracecompass.ctf.core.trace.Utils;
+import org.junit.Test;
+
+/**
+ * The class <code>UtilsTest</code> contains tests for the class
+ * {@link Utils}.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+public class UtilsTest {
+
+ /**
+ * Run the UUID makeUUID(byte[]) method test.
+ */
+ @Test
+ public void testMakeUUID() {
+ int byteSize = 32;
+ byte[] bytes = new byte[byteSize];
+ for (int i = 0; i < byteSize; i++) {
+ bytes[i] = (byte) (i);
+ }
+
+ UUID result = Utils.makeUUID(bytes);
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the UUID makeUUID(byte[]) method test.
+ */
+ @Test
+ public void testMakeUUID_2() {
+ byte[] bytes = new byte[] { (byte) 1, (byte) 1, (byte) 0, (byte) 0,
+ (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 1, (byte) 1,
+ (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0 };
+
+ UUID result = Utils.makeUUID(bytes);
+
+ assertNotNull(result);
+ assertEquals(72339069014638592L, result.getLeastSignificantBits());
+ assertEquals(72339069014638592L, result.getMostSignificantBits());
+ assertEquals("01010000-0000-0000-0101-000000000000", result.toString());
+ assertEquals(0, result.variant());
+ assertEquals(0, result.version());
+ }
+
+ /**
+ * Run the UUID makeUUID(byte[]) method test.
+ */
+ @Test
+ public void testMakeUUID_3() {
+ byte[] bytes = new byte[] { (byte) 0, (byte) 0, (byte) 0, (byte) 0,
+ (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0,
+ (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0 };
+
+ UUID result = Utils.makeUUID(bytes);
+
+ assertNotNull(result);
+ assertEquals(0L, result.getLeastSignificantBits());
+ assertEquals(0L, result.getMostSignificantBits());
+ assertEquals("00000000-0000-0000-0000-000000000000", result.toString());
+ assertEquals(0, result.variant());
+ assertEquals(0, result.version());
+ }
+
+ /**
+ * Run the int unsignedCompare(long,long) method test.
+ */
+ @Test
+ public void testUnsignedCompare() {
+ long a = 1L;
+ long b = 1L;
+ int result;
+
+ result = Utils.unsignedCompare(a, b);
+ assertEquals(0, result);
+
+ result = Utils.unsignedCompare(0L, 1L);
+ assertEquals(-1, result);
+ result = Utils.unsignedCompare(0xFFFFFFFFL, 0x100000000L);
+ assertEquals(-1, result);
+ result = Utils.unsignedCompare(-4L, -1L);
+ assertEquals(-1, result);
+ result = Utils.unsignedCompare(-0x80000000L, -1L);
+ assertEquals(-1, result);
+ result = Utils.unsignedCompare(0x7FFFFFFFFFFFFFFEL, 0x7FFFFFFFFFFFFFFFL);
+ assertEquals(-1, result);
+
+ result = Utils.unsignedCompare(1L, 0L);
+ assertEquals(1, result);
+ result = Utils.unsignedCompare(0x100000000L, 0xFFFFFFFFL);
+ assertEquals(1, result);
+ result = Utils.unsignedCompare(-1L, -4L);
+ assertEquals(1, result);
+ result = Utils.unsignedCompare(-1L, -0x80000000L);
+ assertEquals(1, result);
+ result = Utils.unsignedCompare(0x7FFFFFFFFFFFFFFFL, 0x7FFFFFFFFFFFFFFEL);
+ assertEquals(1, result);
+ }
+}
\ No newline at end of file
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.types;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.event.types.AbstractArrayDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.CompoundDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.Encoding;
+import org.eclipse.tracecompass.ctf.core.event.types.IDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StringDeclaration;
+import org.eclipse.tracecompass.ctf.core.tests.io.Util;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.internal.ctf.core.event.types.ArrayDeclaration;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * The class <code>ArrayDeclaration2Test</code> contains tests for the class
+ * <code>{@link ArrayDeclaration}</code>.
+ *
+ * @author Matthew Khouzam
+ * @version $Revision: 1.0 $
+ */
+public class ArrayDeclaration2Test {
+
+ private ArrayDeclaration fixture;
+
+ /**
+ * Perform pre-test initialization.
+ */
+ @Before
+ public void setUp() {
+ fixture = new ArrayDeclaration(1, new StringDeclaration());
+ }
+
+ /**
+ * Run the ArrayDeclaration(int,Declaration) constructor test.
+ */
+ @Test
+ public void testArrayDeclaration() {
+ int length = 1;
+ IDeclaration elemType = new StringDeclaration();
+ ArrayDeclaration result = new ArrayDeclaration(length, elemType);
+
+ assertNotNull(result);
+ String left = "[declaration] array[";
+ String right = result.toString().substring(0, left.length());
+ assertEquals(left, right);
+ assertEquals(1, result.getLength());
+ }
+
+ /**
+ * Run the ArrayDefinition createDefinition(DefinitionScope,String) method
+ * test.
+ *
+ * @throws CTFReaderException
+ * error in the bitbuffer
+ */
+ @Test
+ public void testCreateDefinition() throws CTFReaderException {
+ String fieldName = "";
+ IDefinitionScope definitionScope = null;
+ AbstractArrayDefinition result;
+ byte[] array = { 't', 'e', 's', 't', '\0', 't', 'h', 'i', 's', '\0' };
+ BitBuffer bb = new BitBuffer(Util.testMemory(ByteBuffer.wrap(array)));
+ result = fixture.createDefinition(definitionScope, fieldName, bb);
+
+ assertNotNull(result);
+ }
+
+
+
+ /**
+ * Run the Declaration getElementType() method test.
+ */
+ @Test
+ public void testGetElementType() {
+ IDeclaration result = fixture.getElementType();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the int getLength() method test.
+ */
+ @Test
+ public void testGetLength() {
+ int result = fixture.getLength();
+ assertEquals(1, result);
+ }
+
+ /**
+ * Run the boolean isString() method test.
+ */
+ @Test
+ public void testIsString_ownDefs() {
+ // it's an array of strings, not a string
+ assertFalse(fixture.isString());
+ }
+
+ /**
+ * Run the boolean isString() method test.
+ */
+ @Test
+ public void testIsString_complex() {
+ final IntegerDeclaration id = IntegerDeclaration.createDeclaration(8, false, 16,
+ ByteOrder.LITTLE_ENDIAN, Encoding.UTF8, "", 8);
+ CompoundDeclaration ad = new ArrayDeclaration(0, id);
+
+ boolean result = ad.isString();
+
+ assertTrue(result);
+ }
+
+ /**
+ * Run the String toString() method test.
+ */
+ @Test
+ public void testToString() {
+ String result = fixture.toString();
+ String left = "[declaration] array[";
+ String right = result.substring(0, left.length());
+
+ assertEquals(left, right);
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.types;
+
+import static org.junit.Assert.assertNotNull;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.event.scope.LexicalScope;
+import org.eclipse.tracecompass.ctf.core.event.types.CompoundDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.Definition;
+import org.eclipse.tracecompass.ctf.core.event.types.Encoding;
+import org.eclipse.tracecompass.ctf.core.event.types.IDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.StringDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StringDefinition;
+import org.eclipse.tracecompass.ctf.core.tests.io.Util;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTrace;
+import org.eclipse.tracecompass.internal.ctf.core.event.types.ArrayDeclaration;
+import org.eclipse.tracecompass.internal.ctf.core.event.types.ArrayDefinition;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * The class <code>ArrayDefinition2Test</code> contains tests for the class
+ * <code>{@link ArrayDefinition}</code>.
+ *
+ */
+public class ArrayDefinition2Test {
+
+ private @NonNull CTFTrace trace = new CTFTrace();
+ private ArrayDefinition charArrayFixture;
+ private ArrayDefinition stringArrayFixture;
+ private ArrayDefinition longArrayFixture;
+
+ /**
+ * Perform pre-test initialization.
+ *
+ * structDef shouldn't be null after parsing the CTFTraceReader object, so
+ * we can ignore the warning.
+ */
+ @Before
+ public void setUp() {
+ charArrayFixture = createCharArray();
+ stringArrayFixture = createStringArray();
+ longArrayFixture = createLongArray();
+ }
+
+ private ArrayDefinition createLongArray() {
+ IntegerDeclaration decl = IntegerDeclaration.createDeclaration(32, false, 10, ByteOrder.BIG_ENDIAN, Encoding.NONE, "none", 8);
+ List<Definition> defs = createIntDefs(10, 32);
+ ArrayDefinition temp = setUpDeclaration(decl, defs);
+ return temp;
+ }
+
+ private ArrayDefinition createCharArray() {
+ IntegerDeclaration decl = IntegerDeclaration.createDeclaration(8, false, 10, ByteOrder.BIG_ENDIAN, Encoding.UTF8, "none", 8);
+ List<Definition> defs = createIntDefs(4, 8);
+ ArrayDefinition temp = setUpDeclaration(decl, defs);
+ return temp;
+ }
+
+ private ArrayDefinition createStringArray() {
+ StringDeclaration strDecl = new StringDeclaration();
+ List<Definition> defs = createDefs();
+ ArrayDefinition temp = setUpDeclaration(strDecl, defs);
+ return temp;
+ }
+
+ private ArrayDefinition setUpDeclaration(IDeclaration decl,
+ @NonNull List<Definition> defs) {
+ CompoundDeclaration ad = new ArrayDeclaration(0, decl);
+ ArrayDefinition temp = new ArrayDefinition(ad, this.trace, "Testx", defs);
+ return temp;
+ }
+
+ @NonNull
+ private static List<Definition> createIntDefs(int size, int bits) {
+ List<Definition> defs = new ArrayList<>(size);
+ for (int i = 0; i < size; i++) {
+ String content = "test" + i;
+ defs.add(new IntegerDefinition(IntegerDeclaration.createDeclaration(bits, false,
+ 16, ByteOrder.LITTLE_ENDIAN, Encoding.UTF8, content, 24), null, content, i));
+ }
+ return defs;
+ }
+
+ @NonNull
+ private static List<Definition> createDefs() {
+ int size = 4;
+ List<Definition> defs = new ArrayList<>();
+ for (int i = 0; i < size; i++) {
+ String content = "test" + i;
+ defs.add(new StringDefinition(
+ new StringDeclaration(Encoding.UTF8), null, content, content));
+ }
+ return defs;
+ }
+
+ /**
+ * Run the ArrayDefinition(ArrayDeclaration,DefinitionScope,String)
+ * constructor test.
+ */
+ @Test
+ public void testArrayDefinition_baseDeclaration() {
+ CompoundDeclaration declaration = (CompoundDeclaration) charArrayFixture.getDeclaration();
+ String fieldName = "";
+
+ @SuppressWarnings("null")
+ ArrayDefinition result = new ArrayDefinition(declaration, this.trace, fieldName, Arrays.asList(new Definition[0]));
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the ArrayDefinition(ArrayDeclaration,DefinitionScope,String)
+ * constructor test.
+ */
+ @Test
+ public void testArrayDefinition_newDeclaration() {
+ CompoundDeclaration declaration = new ArrayDeclaration(0,
+ new StringDeclaration());
+ IDefinitionScope definitionScope = getDefinitionScope();
+
+ String fieldName = "";
+ @SuppressWarnings("null")
+ ArrayDefinition result = new ArrayDefinition(declaration, definitionScope, fieldName, Arrays.asList(new Definition[0]));
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the ArrayDeclaration getDeclaration() method test.
+ */
+ @Test
+ public void testGetDeclaration() {
+ CompoundDeclaration result = (CompoundDeclaration) charArrayFixture.getDeclaration();
+
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the Definition getDefinitions().get(int) method test.
+ */
+ @Test
+ public void testgetElem_noDefs() {
+ int i = 0;
+ IDefinition result = charArrayFixture.getDefinitions().get(i);
+
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the Definition getDefinitions().get(int) method test.
+ */
+ @Test
+ public void testgetElem_withDefs() {
+ List<Definition> defs = createDefs();
+ IDefinitionScope definitionScope = getDefinitionScope();
+ ArrayDefinition ad = new ArrayDefinition((CompoundDeclaration) charArrayFixture.getDeclaration(), definitionScope, "test", defs);
+ int j = 1;
+
+ IDefinition result = ad.getDefinitions().get(j);
+
+ assertNotNull(result);
+ }
+
+ @NonNull
+ private static IDefinitionScope getDefinitionScope() {
+ return new IDefinitionScope() {
+
+ @Override
+ public Definition lookupDefinition(String lookupPath) {
+ return null;
+ }
+
+ @Override
+ public LexicalScope getScopePath() {
+ return null;
+ }
+ };
+ }
+
+ /**
+ * Run the void read(BitBuffer) method test.
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void testRead_noDefs() throws CTFReaderException {
+ BitBuffer input = new BitBuffer(Util.testMemory(ByteBuffer.allocateDirect(128)));
+ charArrayFixture.getDeclaration().createDefinition(null, "test", input);
+ }
+
+ /**
+ * Run the String toString() method test.
+ */
+ @Test
+ public void testToString_char() {
+ String result = charArrayFixture.toString();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the String toString() method test.
+ */
+ @Test
+ public void testToString_long() {
+ String result = longArrayFixture.toString();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the String toString() method test.
+ */
+ @Test
+ public void testToString_string() {
+ String result = stringArrayFixture.toString();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the String toString() method test.
+ */
+ @Test
+ public void testToString_withDefs() {
+ String result = charArrayFixture.toString();
+
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the String toString() method test.
+ */
+ @Test
+ public void testToStringStringArray() {
+ String result = stringArrayFixture.toString();
+
+ assertNotNull(result);
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.types;
+
+import static org.junit.Assert.assertNotNull;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.event.types.Definition;
+import org.eclipse.tracecompass.ctf.core.event.types.IDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.StringDeclaration;
+import org.junit.Test;
+
+/**
+ * The class <code>DefinitionTest</code> contains tests for the class
+ * <code>{@link Definition}</code>.
+ *
+ * @author Matthew Khouzam
+ * @version $Revision: 1.0 $
+ */
+public class DefinitionTest {
+
+ /**
+ * Since Definition is abstract, we'll minimally extend it here to
+ * instantiate it.
+ */
+ static class DefTest extends Definition {
+
+ @NonNull
+ private static final StringDeclaration STRINGDEF = new StringDeclaration();
+
+ public DefTest(IDefinitionScope definitionScope, @NonNull String fieldName) {
+ super(DefTest.STRINGDEF, definitionScope, fieldName);
+ }
+
+ @Override
+ @NonNull
+ public IDeclaration getDeclaration() {
+ return DefTest.STRINGDEF;
+ }
+
+ }
+
+ /**
+ * Test a definition
+ */
+ @Test
+ public void testToString() {
+ IDefinition fixture = new DefTest(null, "Hello");
+ String result = fixture.toString();
+
+ assertNotNull(result);
+ }
+}
\ No newline at end of file
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.types;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.event.types.Encoding;
+import org.eclipse.tracecompass.ctf.core.event.types.EnumDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.EnumDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDeclaration;
+import org.eclipse.tracecompass.ctf.core.tests.io.Util;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * The class <code>EnumDeclarationTest</code> contains tests for the class
+ * <code>{@link EnumDeclaration}</code>.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+public class EnumDeclarationTest {
+
+ private EnumDeclaration fixture;
+
+ /**
+ * Perform pre-test initialization.
+ */
+ @Before
+ public void setUp() {
+ fixture = new EnumDeclaration(IntegerDeclaration.createDeclaration(1, false, 1,
+ ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 8));
+ }
+
+ /**
+ * Run the EnumDeclaration(IntegerDeclaration) constructor test.
+ */
+ @Test
+ public void testEnumDeclaration() {
+ IntegerDeclaration containerType = IntegerDeclaration.createDeclaration(1, false, 1,
+ ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 8);
+
+ EnumDeclaration result = new EnumDeclaration(containerType);
+
+ assertNotNull(result);
+ String left = "[declaration] enum[";
+ assertEquals(left, result.toString().substring(0, left.length()));
+ }
+
+ /**
+ * Run the boolean add(long,long,String) method test.
+ */
+ @Test
+ public void testAdd() {
+ long low = 1L;
+ long high = 1L;
+ String label = "";
+
+ boolean result = fixture.add(low, high, label);
+
+ assertTrue(result);
+ }
+
+ /**
+ * Run the EnumDefinition createDefinition(DefinitionScope,String) method
+ * test.
+ *
+ * @throws CTFReaderException
+ * out of bounds error, won't happen
+ */
+ @Test
+ public void testCreateDefinition() throws CTFReaderException {
+ IDefinitionScope definitionScope = null;
+ String fieldName = "";
+ byte[] array = { 't', 'e', 's', 't', '\0', 't', 'h', 'i', 's', '\0' };
+ BitBuffer bb = new BitBuffer(Util.testMemory(ByteBuffer.wrap(array)));
+
+ EnumDefinition result = fixture.createDefinition(definitionScope,
+ fieldName, bb);
+
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the String query(long) method test.
+ */
+ @Test
+ public void testQuery() {
+ long value = 0;
+ String result = fixture.query(value);
+
+ assertNull(result);
+ }
+
+ /**
+ * Run the String toString() method test.
+ */
+ @Test
+ public void testToString() {
+ String result = fixture.toString();
+
+ String left = "[declaration] enum[";
+ assertEquals(left, result.substring(0, left.length()));
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.types;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import java.nio.ByteOrder;
+
+import org.eclipse.tracecompass.ctf.core.event.types.Encoding;
+import org.eclipse.tracecompass.ctf.core.event.types.EnumDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.EnumDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDefinition;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * The class <code>EnumDefinitionTest</code> contains tests for the class
+ * <code>{@link EnumDefinition}</code>.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+public class EnumDefinitionTest {
+
+ private EnumDefinition fixtureA;
+ private EnumDefinition fixtureB;
+
+ /**
+ * Perform pre-test initialization.
+ */
+ @Before
+ public void setUp() {
+ IntegerDeclaration integerDeclaration = IntegerDeclaration.createDeclaration(1, false, 1, ByteOrder.BIG_ENDIAN,
+ Encoding.ASCII, "", 8);
+ EnumDeclaration declaration = new EnumDeclaration(
+ integerDeclaration);
+ declaration.add(0, 10, "a");
+ declaration.add(11, 20, "b");
+ String fieldName = "";
+
+ fixtureA = new EnumDefinition(declaration, null, fieldName, new IntegerDefinition(integerDeclaration, null, fieldName, 4));
+ fixtureB = new EnumDefinition(declaration, null, fieldName, new IntegerDefinition(integerDeclaration, null, fieldName, 12));
+ }
+
+ /**
+ * Run the EnumDefinition(EnumDeclaration,DefinitionScope,String)
+ * constructor test.
+ */
+ @Test
+ public void testEnumDefinition() {
+ assertNotNull(fixtureA);
+ assertNotNull(fixtureB);
+ }
+
+ /**
+ * Run the String getValue() method test.
+ */
+ @Test
+ public void testGetValue() {
+ String result = fixtureA.getValue();
+
+ assertNotNull(result);
+ assertEquals("a", result);
+ }
+
+ /**
+ * Run the long getIntegerValue() method test.
+ */
+ @Test
+ public void testGetIntegerValue_one() {
+ long result = fixtureA.getIntegerValue();
+ assertEquals(4L, result);
+ }
+
+ /**
+ * Run the String toString() method test.
+ */
+ @Test
+ public void testToString() {
+ String result = fixtureB.toString();
+
+ assertEquals("{ value = b, container = 12 }", result);
+ }
+}
\ No newline at end of file
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.types;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assume.assumeTrue;
+
+import org.eclipse.tracecompass.ctf.core.event.EventDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+import org.eclipse.tracecompass.ctf.core.tests.shared.CtfTestTrace;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.ctf.core.trace.CTFStream;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTrace;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTraceReader;
+import org.eclipse.tracecompass.internal.ctf.core.event.EventDeclaration;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * The class <code>EventDeclarationTest</code> contains tests for the class
+ * <code>{@link EventDeclaration}</code>.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+@SuppressWarnings("javadoc")
+public class EventDeclarationTest {
+
+ private static final CtfTestTrace testTrace = CtfTestTrace.KERNEL;
+
+ private EventDeclaration fixture;
+
+ /**
+ * Perform pre-test initialization.
+ *
+ * @throws CTFReaderException
+ */
+ @Before
+ public void setUp() throws CTFReaderException {
+ assumeTrue(testTrace.exists());
+ fixture = new EventDeclaration();
+ fixture.setContext(new StructDeclaration(1L));
+ fixture.setId(1L);
+ fixture.setFields(new StructDeclaration(1L));
+ fixture.setStream(new CTFStream(testTrace.getTrace()));
+ fixture.setName("");
+ }
+
+ /**
+ * Run the EventDeclaration() constructor test.
+ */
+ @Test
+ public void testEventDeclaration() {
+ EventDeclaration result = new EventDeclaration();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the boolean contextIsSet() method test.
+ */
+ @Test
+ public void testContextIsSet() {
+ boolean result = fixture.contextIsSet();
+ assertTrue(result);
+ }
+
+ /**
+ * Run the boolean contextIsSet() method test.
+ */
+ @Test
+ public void testContextIsSet_null() {
+ fixture.setContext((StructDeclaration) null);
+
+ boolean result = fixture.contextIsSet();
+ assertFalse(result);
+ }
+
+ /**
+ * Run the boolean equals(Object) method test.
+ *
+ * @throws CTFReaderException
+ */
+ @Test
+ public void testEquals() throws CTFReaderException {
+ EventDeclaration obj = new EventDeclaration();
+ obj.setContext(new StructDeclaration(1L));
+ obj.setId(1L);
+ obj.setFields(new StructDeclaration(1L));
+ obj.setStream(new CTFStream(testTrace.getTrace()));
+ obj.setName("");
+
+ assertTrue(fixture.equals(fixture));
+ boolean result = fixture.equals(obj);
+ assertFalse(result);
+ }
+
+ /**
+ * Run the boolean equals(Object) method test.
+ */
+ @Test
+ public void testEquals_null() {
+ Object obj = null;
+
+ boolean result = fixture.equals(obj);
+ assertFalse(result);
+ }
+
+ /**
+ * Run the boolean equals(Object) method test.
+ */
+ @Test
+ public void testEquals_emptyObject() {
+ Object obj = new Object();
+
+ boolean result = fixture.equals(obj);
+ assertFalse(result);
+ }
+
+ /**
+ * Run the boolean equals(Object) method test.
+ */
+ @Test
+ public void testEquals_other1() {
+ EventDeclaration obj = new EventDeclaration();
+ obj.setContext(fixture.getContext());
+
+ boolean result = fixture.equals(obj);
+ assertFalse(result);
+ }
+
+ /**
+ * Run the boolean equals(Object) method test.
+ */
+ @Test
+ public void testEquals_other2() {
+ EventDeclaration obj = new EventDeclaration();
+ obj.setContext(new StructDeclaration(1L));
+ obj.setFields(new StructDeclaration(1L));
+
+ boolean result = fixture.equals(obj);
+ assertFalse(result);
+ }
+
+ /**
+ * Run the boolean equals(Object) method test.
+ */
+ @Test
+ public void testEquals_other3() {
+ EventDeclaration obj = new EventDeclaration();
+ obj.setContext(new StructDeclaration(1L));
+ obj.setId(1L);
+ obj.setFields(new StructDeclaration(1L));
+
+ boolean result = fixture.equals(obj);
+ assertFalse(result);
+ }
+
+ /**
+ * Run the boolean equals(Object) method test.
+ */
+ @Test
+ public void testEquals_other4() {
+ EventDeclaration obj = new EventDeclaration();
+ obj.setContext(new StructDeclaration(1L));
+ obj.setId(1L);
+ obj.setFields(new StructDeclaration(1L));
+ obj.setName("");
+
+ boolean result = fixture.equals(obj);
+ assertFalse(result);
+ }
+
+ /**
+ * Run the boolean fieldsIsSet() method test.
+ */
+ @Test
+ public void testFieldsIsSet() {
+ boolean result = fixture.fieldsIsSet();
+ assertTrue(result);
+ }
+
+ /**
+ * Run the boolean fieldsIsSet() method test.
+ */
+ @Test
+ public void testFieldsIsSet_null() {
+ fixture.setFields((StructDeclaration) null);
+
+ boolean result = fixture.fieldsIsSet();
+ assertFalse(result);
+ }
+
+ /**
+ * Run the StructDeclaration getFields() method test.
+ */
+ @Test
+ public void testGetFields() {
+ StructDeclaration result = fixture.getFields();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the Long getId() method test.
+ */
+ @Test
+ public void testGetId() {
+ assertEquals(1,fixture.id());
+ }
+
+ /**
+ * Run the String getName() method test.
+ */
+ @Test
+ public void testGetName() {
+ String result = fixture.getName();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the Stream getStream() method test.
+ */
+ @Test
+ public void testGetStream() {
+ CTFStream result = fixture.getStream();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the int hashCode() method test.
+ */
+ @Test
+ public void testHashCode() {
+ int result = fixture.hashCode();
+ assertTrue(0 != result);
+ }
+
+ /**
+ * Run the int hashCode() method test.
+ */
+ @Test
+ public void testHashCode_null() {
+ fixture.setStream((CTFStream) null);
+ fixture.setName((String) null);
+
+ int result = fixture.hashCode();
+ assertTrue(0 != result);
+ }
+
+ /**
+ * Run the boolean idIsSet() method test.
+ */
+ @Test
+ public void testIdIsSet() {
+ boolean result = fixture.idIsSet();
+ assertTrue(result);
+ }
+
+ /**
+ * Run the boolean nameIsSet() method test.
+ */
+ @Test
+ public void testNameIsSet() {
+ boolean result = fixture.nameIsSet();
+ assertTrue(result);
+ }
+
+ /**
+ * Run the boolean nameIsSet() method test.
+ */
+ @Test
+ public void testNameIsSet_null() {
+ fixture.setName((String) null);
+
+ boolean result = fixture.nameIsSet();
+ assertFalse(result);
+ }
+
+ /**
+ * Run the boolean streamIsSet() method test.
+ */
+ @Test
+ public void testStreamIsSet() {
+ boolean result = fixture.streamIsSet();
+ assertTrue(result);
+ }
+
+ /**
+ * Run the boolean streamIsSet() method test.
+ */
+ @Test
+ public void testStreamIsSet_null() {
+ fixture.setStream((CTFStream) null);
+
+ boolean result = fixture.streamIsSet();
+ assertEquals(false, result);
+ }
+
+ /**
+ * Test for the EventDefinition class
+ *
+ * @throws CTFReaderException
+ */
+ @Test
+ public void testEventDefinition() throws CTFReaderException {
+ try (CTFTrace trace = testTrace.getTrace();) {
+ EventDefinition ed = null;
+ try (CTFTraceReader tr = new CTFTraceReader(trace);) {
+ tr.advance();
+ ed = tr.getCurrentEventDef();
+ }
+
+ assertNotNull(ed);
+ assertNotNull(ed.getScopePath());
+ assertNotNull(ed.getDeclaration());
+ assertNotNull(ed.getFields());
+ assertNull(ed.getContext());
+ assertNotNull(ed.getPacketContext());
+ assertNotNull(ed.getCPU());
+ assertNotNull(ed.getStreamInputReader());
+ assertNull(ed.lookupDefinition("context"));
+ assertNotNull(ed.lookupDefinition("fields"));
+ assertNull(ed.lookupDefinition("other"));
+ assertNotNull(ed.toString());
+ }
+ }
+
+ EventDeclaration e1;
+ EventDeclaration e2;
+
+
+ @Test
+ public void testEquals1(){
+ e1 = new EventDeclaration();
+ assertFalse(e1.equals(null));
+ }
+
+ @Test
+ public void testEquals2(){
+ e1 = EventDeclaration.getLostEventDeclaration();
+ assertFalse(e1.equals(new Long(23L)));
+ }
+
+ @Test
+ public void testEquals3(){
+ e1 = EventDeclaration.getLostEventDeclaration();
+ assertEquals(e1,e1);
+ }
+
+ @Test
+ public void testEquals4(){
+ e1 = EventDeclaration.getLostEventDeclaration();
+ e2 = EventDeclaration.getLostEventDeclaration();
+ assertEquals(e1,e2);
+ }
+
+ @Test
+ public void testEquals5(){
+ e1 = EventDeclaration.getLostEventDeclaration();
+ e2 = new EventDeclaration();
+ assertFalse(e1.equals(e2));
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+package org.eclipse.tracecompass.ctf.core.tests.types;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.types.EnumDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.FloatDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.StringDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.VariantDeclaration;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.internal.ctf.core.event.types.composite.EventHeaderCompactDeclaration;
+import org.eclipse.tracecompass.internal.ctf.core.event.types.composite.EventHeaderDefinition;
+import org.eclipse.tracecompass.internal.ctf.core.event.types.composite.EventHeaderLargeDeclaration;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * Event header declaration tests
+ *
+ * @author Matthew Khouzam
+ *
+ */
+public class EventHeaderDeclarationTest {
+
+ private static final int ID = 2222;
+ private static final int TIMESTAMP = 1000;
+ private static final int VALID_LARGE = 1;
+ private static final int VALID_COMPACT = 0;
+
+ private final List<StructDeclaration> declarations = new ArrayList<>();
+
+ /**
+ * Setup
+ */
+ @Before
+ public void init() {
+ declarations.clear();
+
+ /**
+ * do not reflow
+ *
+ * <pre>
+ * struct event_header_compact {
+ * enum : uint5_t { compact = 0 ... 30, extended = 31 } id;
+ * variant <id> {
+ * struct {
+ * uint27_clock_monotonic_t timestamp;
+ * } compact;
+ * struct {
+ * uint32_t id;
+ * uint64_clock_monotonic_t timestamp;
+ * } extended;
+ * } v;
+ * } align(8);
+ * </pre>
+ */
+
+ StructDeclaration base = new StructDeclaration(8);
+ base.addField("id", new EnumDeclaration(IntegerDeclaration.UINT_5B_DECL));
+ VariantDeclaration variantV = new VariantDeclaration();
+ StructDeclaration compact = new StructDeclaration(8);
+ compact.addField("timestamp", IntegerDeclaration.UINT_27B_DECL);
+ variantV.addField("compact", compact);
+ StructDeclaration large = new StructDeclaration(8);
+ large.addField("id", IntegerDeclaration.UINT_32B_DECL);
+ large.addField("timestamp", IntegerDeclaration.UINT_64B_DECL);
+ variantV.addField("extended", large);
+ base.addField("v", variantV);
+ declarations.add(base);
+
+ /**
+ * Do not reflow
+ *
+ * <pre>
+ * struct event_header_large {
+ * enum : uint16_t { compact = 0 ... 65534, extended = 65535 } id;
+ * variant <id> {
+ * struct {
+ * uint32_clock_monotonic_t timestamp;
+ * } compact;
+ * struct {
+ * uint32_t id;
+ * uint64_clock_monotonic_t timestamp;
+ * } extended;
+ * } v;
+ * } align(8);
+ * </pre>
+ */
+
+ base = new StructDeclaration(8);
+ base.addField("id", new EnumDeclaration(IntegerDeclaration.UINT_16B_DECL));
+ variantV = new VariantDeclaration();
+ compact = new StructDeclaration(8);
+ compact.addField("timestamp", IntegerDeclaration.UINT_32B_DECL);
+ variantV.addField("compact", compact);
+ large = new StructDeclaration(8);
+ large.addField("id", IntegerDeclaration.UINT_32B_DECL);
+ large.addField("timestamp", IntegerDeclaration.UINT_64B_DECL);
+ variantV.addField("extended", large);
+ base.addField("v", variantV);
+ declarations.add(base);
+
+ // bad - well, sounds nice though
+ base = new StructDeclaration(8);
+ base.addField("potato salad", new FloatDeclaration(8, 8, ByteOrder.BIG_ENDIAN, 8));
+ base.addField("bbq ribs", new FloatDeclaration(8, 8, ByteOrder.BIG_ENDIAN, 8));
+ declarations.add(base);
+ // bad
+ base = new StructDeclaration(8);
+ base.addField("id", new EnumDeclaration(IntegerDeclaration.UINT_16B_DECL));
+ base.addField("v", new FloatDeclaration(8, 8, ByteOrder.BIG_ENDIAN, 8));
+ declarations.add(base);
+ // bad
+ base = new StructDeclaration(8);
+ base.addField("id", new EnumDeclaration(IntegerDeclaration.UINT_5B_DECL));
+ base.addField("v", new FloatDeclaration(8, 8, ByteOrder.BIG_ENDIAN, 8));
+ declarations.add(base);
+ // bad
+ base = new StructDeclaration(8);
+ base.addField("id", new EnumDeclaration(IntegerDeclaration.UINT_5B_DECL));
+ variantV = new VariantDeclaration();
+ compact = new StructDeclaration(8);
+ compact.addField("timestamp", IntegerDeclaration.UINT_27B_DECL);
+ variantV.addField("compact1", compact);
+ large = new StructDeclaration(8);
+ large.addField("id", IntegerDeclaration.UINT_32B_DECL);
+ large.addField("timestamp", IntegerDeclaration.UINT_64B_DECL);
+ variantV.addField("extended", large);
+ base.addField("v", variantV);
+ declarations.add(base);
+
+ // bad
+ base = new StructDeclaration(8);
+ base.addField("id", new EnumDeclaration(IntegerDeclaration.UINT_5B_DECL));
+ variantV = new VariantDeclaration();
+ compact = new StructDeclaration(8);
+ compact.addField("timestamp", IntegerDeclaration.UINT_27B_DECL);
+ variantV.addField("compact", compact);
+ large = new StructDeclaration(8);
+ large.addField("id", IntegerDeclaration.UINT_32B_DECL);
+ large.addField("timestamp1", IntegerDeclaration.UINT_64B_DECL);
+ variantV.addField("extended", large);
+ base.addField("v", variantV);
+ declarations.add(base);
+
+ // bad
+ base = new StructDeclaration(8);
+ base.addField("id", new EnumDeclaration(IntegerDeclaration.UINT_5B_DECL));
+ variantV = new VariantDeclaration();
+ compact = new StructDeclaration(8);
+ compact.addField("timestamp", IntegerDeclaration.UINT_27B_DECL);
+ variantV.addField("compact", compact);
+ large = new StructDeclaration(8);
+ large.addField("id", IntegerDeclaration.UINT_32B_DECL);
+ large.addField("timestamp", new StringDeclaration());
+ variantV.addField("extended", large);
+ base.addField("v", variantV);
+ declarations.add(base);
+
+ // bad
+ base = new StructDeclaration(8);
+ base.addField("id", new EnumDeclaration(IntegerDeclaration.UINT_5B_DECL));
+ variantV = new VariantDeclaration();
+ compact = new StructDeclaration(8);
+ compact.addField("timestamp", IntegerDeclaration.UINT_27B_DECL);
+ variantV.addField("compact", compact);
+ variantV.addField("surprise!", compact);
+ large = new StructDeclaration(8);
+ large.addField("id", IntegerDeclaration.UINT_32B_DECL);
+ large.addField("timestamp", new StringDeclaration());
+ variantV.addField("extended", large);
+ base.addField("v", variantV);
+ declarations.add(base);
+
+ // bad
+ base = new StructDeclaration(8);
+ base.addField("id", new EnumDeclaration(IntegerDeclaration.UINT_16B_DECL));
+ variantV = new VariantDeclaration();
+ compact = new StructDeclaration(8);
+ compact.addField("timestamp", IntegerDeclaration.UINT_27B_DECL);
+ variantV.addField("compact", compact);
+ variantV.addField("surprise!", compact);
+ large = new StructDeclaration(8);
+ large.addField("id", IntegerDeclaration.UINT_32B_DECL);
+ large.addField("timestamp", new StringDeclaration());
+ variantV.addField("extended", large);
+ base.addField("v", variantV);
+ declarations.add(base);
+ // bad
+ base = new StructDeclaration(8);
+ base.addField("id", new FloatDeclaration(8, 8, ByteOrder.BIG_ENDIAN, 8));
+ base.addField("v", new FloatDeclaration(8, 8, ByteOrder.BIG_ENDIAN, 8));
+ declarations.add(base);
+ // bad
+ base = new StructDeclaration(8);
+ base.addField("id", IntegerDeclaration.INT_32B_DECL);
+ base.addField("timestamp", IntegerDeclaration.INT_32B_DECL);
+ declarations.add(base);
+ // bad
+ base = new StructDeclaration(8);
+ base.addField("id", new EnumDeclaration(IntegerDeclaration.INT_8_DECL));
+ base.addField("timestamp", IntegerDeclaration.INT_32B_DECL);
+ declarations.add(base);
+ }
+
+ /**
+ * Validate a compact declaration
+ */
+ @Test
+ public void validateCompact() {
+ assertEquals(true, EventHeaderCompactDeclaration.isCompactEventHeader(declarations.get(VALID_COMPACT)));
+ }
+
+ /**
+ * Fail if it validates
+ */
+ @Test
+ public void validateCompactFail() {
+ for (int i = 0; i < declarations.size(); i++) {
+ if (i == VALID_COMPACT) {
+ continue;
+ }
+ assertEquals(false, EventHeaderCompactDeclaration.isCompactEventHeader(declarations.get(i)));
+ }
+ }
+
+ /**
+ * Validate a large declaration
+ */
+ @Test
+ public void validateLarge() {
+ assertEquals(true, EventHeaderLargeDeclaration.isLargeEventHeader(declarations.get(VALID_LARGE)));
+ }
+
+ /**
+ * Fail if it validates
+ */
+ @Test
+ public void validateLargeFail() {
+ for (int i = 0; i < declarations.size(); i++) {
+ if (i == VALID_LARGE) {
+ continue;
+ }
+ assertEquals(false, EventHeaderLargeDeclaration.isLargeEventHeader(declarations.get(i)));
+ }
+ }
+
+ /**
+ * Test an compact compact header
+ *
+ * @throws CTFReaderException
+ * if {@link BitBuffer} is null
+ */
+ @Test
+ public void testCompactCompact() throws CTFReaderException {
+ ByteBuffer buffer = ByteBuffer.allocate(16);
+ buffer.putInt(0x80000042);
+ byte[] validCompact1 = buffer.array();
+
+ EventHeaderCompactDeclaration decl = new EventHeaderCompactDeclaration(ByteOrder.BIG_ENDIAN);
+ final ByteBuffer input = ByteBuffer.wrap(validCompact1);
+ assertNotNull(input);
+ EventHeaderDefinition def = decl.createDefinition(null, "bla", new BitBuffer(input));
+ assertNotNull(def);
+ assertEquals(16, def.getId());
+ assertEquals(0x42, def.getTimestamp());
+ }
+
+ /**
+ * Test an extended compact header
+ *
+ * @throws CTFReaderException
+ * if {@link BitBuffer} is null
+ */
+ @Test
+ public void testCompactExtended() throws CTFReaderException {
+ ByteBuffer buffer = ByteBuffer.allocate(16);
+ buffer.put((byte) 0xFF);
+ buffer.putInt(ID);
+ buffer.putLong(TIMESTAMP);
+ byte[] validCompact2 = buffer.array();
+
+ EventHeaderCompactDeclaration decl = new EventHeaderCompactDeclaration(ByteOrder.BIG_ENDIAN);
+ final ByteBuffer input = ByteBuffer.wrap(validCompact2);
+ assertNotNull(input);
+ EventHeaderDefinition def = decl.createDefinition(null, "bla", new BitBuffer(input));
+ assertNotNull(def);
+ assertEquals(ID, def.getId());
+ assertEquals(TIMESTAMP, def.getTimestamp());
+ }
+
+ /**
+ * Test an compact large header
+ *
+ * @throws CTFReaderException
+ * if {@link BitBuffer} is null
+ */
+ @Test
+ public void testLargeCompact() throws CTFReaderException {
+ ByteBuffer buffer = ByteBuffer.allocate(16);
+ buffer.putShort((short) ID);
+ buffer.putInt(TIMESTAMP);
+ byte[] validLarge1 = buffer.array();
+
+ EventHeaderLargeDeclaration decl = new EventHeaderLargeDeclaration(ByteOrder.BIG_ENDIAN);
+ final ByteBuffer input = ByteBuffer.wrap(validLarge1);
+ assertNotNull(input);
+ EventHeaderDefinition def = decl.createDefinition(null, "bla", new BitBuffer(input));
+ assertNotNull(def);
+ assertEquals(ID, def.getId());
+ assertEquals(TIMESTAMP, def.getTimestamp());
+ assertEquals(ID, ((IntegerDefinition) def.getDefinition("id")).getValue());
+ assertEquals(TIMESTAMP, ((IntegerDefinition) def.getDefinition("timestamp")).getValue());
+ }
+
+ /**
+ * Test an large large header
+ *
+ * @throws CTFReaderException
+ * if {@link BitBuffer} is null
+ */
+ @Test
+ public void testLargeExtended() throws CTFReaderException {
+ ByteBuffer buffer = ByteBuffer.allocate(16);
+ buffer.putShort((short) -1);
+ buffer.putInt(ID);
+ buffer.putLong(TIMESTAMP);
+ byte[] validLarge2 = buffer.array();
+
+ EventHeaderLargeDeclaration decl = new EventHeaderLargeDeclaration(ByteOrder.BIG_ENDIAN);
+ final ByteBuffer input = ByteBuffer.wrap(validLarge2);
+ assertNotNull(input);
+ EventHeaderDefinition def = decl.createDefinition(null, "bla", new BitBuffer(input));
+ assertNotNull(def);
+ assertEquals(ID, def.getId());
+ assertEquals(TIMESTAMP, def.getTimestamp());
+ assertEquals(ID, ((IntegerDefinition) def.getDefinition("id")).getValue());
+ assertEquals(TIMESTAMP, ((IntegerDefinition) def.getDefinition("timestamp")).getValue());
+ }
+
+ /**
+ * Test maximum sizes, make sure they don't change unannounced
+ */
+ @Test
+ public void testMaxSizes() {
+ assertEquals(112, (new EventHeaderLargeDeclaration(ByteOrder.BIG_ENDIAN)).getMaximumSize());
+ assertEquals(104, (new EventHeaderCompactDeclaration(ByteOrder.BIG_ENDIAN)).getMaximumSize());
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.types;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.nio.ByteOrder;
+
+import org.eclipse.tracecompass.ctf.core.event.types.FloatDeclaration;
+import org.junit.Test;
+
+@SuppressWarnings("javadoc")
+public class FloatDeclarationTest {
+ private FloatDeclaration fixture;
+
+
+ @Test
+ public void ctorTest() {
+ for( int i = 1; i < 20; i++) {
+ fixture = new FloatDeclaration(i, 32-i, ByteOrder.nativeOrder(), 0);
+ assertNotNull(fixture);
+ }
+ }
+
+ @Test
+ public void getterTest() {
+ fixture = new FloatDeclaration(8, 24, ByteOrder.nativeOrder(), 1);
+ assertEquals( fixture.getAlignment(), 1);
+ assertEquals( fixture.getByteOrder(), ByteOrder.nativeOrder());
+ assertEquals( fixture.getExponent(), 8);
+ assertEquals( fixture.getMantissa(), 24);
+ }
+
+ @Test
+ public void toStringTest() {
+ fixture = new FloatDeclaration(8, 24, ByteOrder.nativeOrder(), 0);
+ assertTrue(fixture.toString().contains("float"));
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.types;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.types.FloatDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.FloatDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDefinition;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * The class <code>IntegerDefinitionTest</code> contains tests for the class
+ * <code>{@link IntegerDefinition}</code>.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+@SuppressWarnings("javadoc")
+public class FloatDefinitionTest {
+
+ private FloatDefinition fixture;
+ private FloatDefinition singleFixture;
+ private FloatDefinition doubleFixture; // all the way.
+ private FloatDeclaration parent;
+ @NonNull
+ private static final String fieldName = "float";
+
+ /**
+ * Perform pre-test initialization.
+ *
+ * @throws CTFReaderException
+ * error creating floats
+ */
+ @Before
+ public void setUp() throws CTFReaderException {
+ testFloat248();
+ testFloat5311();
+ }
+
+ @Test
+ public void testFloat248() throws CTFReaderException {
+ parent = new FloatDeclaration(8, 24, ByteOrder.nativeOrder(), 0);
+ BitBuffer bb = create32BitFloatByteBuffer();
+ singleFixture = parent.createDefinition(null, fieldName, bb);
+ assertNotNull(singleFixture);
+ }
+
+ @Test
+ public void testFloat5311() throws CTFReaderException {
+ parent = new FloatDeclaration(11, 53, ByteOrder.nativeOrder(), 0);
+ BitBuffer bb = create64BitFloatByteBuffer();
+ doubleFixture = parent.createDefinition(null, fieldName, bb);
+ assertNotNull(doubleFixture);
+ }
+
+ @Test
+ public void testFloat32Bit() throws CTFReaderException {
+ for (int i = 1; i < 31; i++) {
+ parent = new FloatDeclaration(i, 32 - i, ByteOrder.nativeOrder(), 0);
+
+ fixture = parent.createDefinition(null, fieldName, create32BitFloatByteBuffer());
+ assertNotNull(fixture);
+ assertEquals("test" + i, "2.0", fixture.toString());
+ }
+ }
+
+ @Test
+ public void testFloat64Bit() throws CTFReaderException {
+ for (int i = 1; i < 63; i++) {
+ parent = new FloatDeclaration(i, 64 - i, ByteOrder.nativeOrder(), 0);
+ fixture = parent.createDefinition(null, fieldName, create64BitFloatByteBuffer());
+ assertNotNull(fixture);
+ if (i <= 32) {
+ assertEquals("test" + i, "2.0", fixture.toString());
+ } else if (i == 33) {
+ assertEquals("test" + i, "1.0", fixture.toString());
+ } else {
+ assertNotNull(fixture.getValue());
+ }
+
+ }
+ }
+
+ @Test
+ public void testFloat48Bit() throws CTFReaderException {
+ parent = new FloatDeclaration(12, 32, ByteOrder.nativeOrder(), 0);
+ fixture = parent.createDefinition(null, fieldName, create64BitFloatByteBuffer());
+ assertNotNull(fixture);
+ assertEquals(Double.NaN, fixture.getValue(), 0.1);
+ }
+
+ /**
+ * Run the IntegerDeclaration getDeclaration() method test.
+ */
+ @Test
+ public void testGetDeclaration() {
+ FloatDeclaration result = singleFixture.getDeclaration();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the long getValue() method test.
+ */
+ @Test
+ public void testGetValue() {
+ double result = singleFixture.getValue();
+ assertEquals(2.0, result, 0.1);
+ }
+
+ /**
+ * Run the String toString() method test.
+ */
+ @Test
+ public void testToString() {
+ String result = singleFixture.toString();
+ assertNotNull(result);
+ assertEquals("2.0", result);
+ }
+
+ @NonNull
+ private static BitBuffer create32BitFloatByteBuffer() {
+ float[] data = new float[2];
+ data[0] = 2.0f;
+ data[1] = 3.14f;
+ ByteBuffer byb = ByteBuffer.allocate(128);
+ byb.order(ByteOrder.nativeOrder());
+ byb.mark();
+ byb.putFloat(data[0]);
+ byb.putFloat(data[1]);
+ byb.reset();
+ BitBuffer bb = new BitBuffer(byb);
+ return bb;
+ }
+
+ @NonNull
+ private static BitBuffer create64BitFloatByteBuffer() {
+ double[] data = new double[2];
+ data[0] = 2.0f;
+ data[1] = 3.14f;
+ ByteBuffer byb = ByteBuffer.allocate(128);
+ byb.order(ByteOrder.nativeOrder());
+ byb.mark();
+ byb.putDouble(data[0]);
+ byb.putDouble(data[1]);
+ byb.reset();
+ BitBuffer bb = new BitBuffer(byb);
+ return bb;
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013, 2014 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ * Marc-Andre Laperle - Add min/maximum for validation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.types;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import java.math.BigInteger;
+import java.nio.ByteOrder;
+
+import org.eclipse.tracecompass.ctf.core.event.types.Encoding;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDeclaration;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * The class <code>IntegerDeclarationTest</code> contains tests for the class
+ * <code>{@link IntegerDeclaration}</code>.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+public class IntegerDeclarationTest {
+
+ private IntegerDeclaration fixture;
+
+ /**
+ * Perform pre-test initialization.
+ */
+ @Before
+ public void setUp() {
+ fixture = IntegerDeclaration.createDeclaration(1, false, 1, ByteOrder.BIG_ENDIAN,
+ Encoding.ASCII, "", 32);
+ }
+
+ /**
+ * Run the IntegerDeclaration(int,boolean,int,ByteOrder,Encoding)
+ * constructor test.
+ */
+ @Test
+ public void testIntegerDeclaration() {
+ int len = 1;
+ boolean signed = false;
+ int base = 1;
+ ByteOrder byteOrder = ByteOrder.BIG_ENDIAN;
+ Encoding encoding = Encoding.ASCII;
+
+ IntegerDeclaration result = IntegerDeclaration.createDeclaration(len, signed, base,
+ byteOrder, encoding, "", 16);
+
+ assertNotNull(result);
+ assertEquals(1, result.getBase());
+ assertEquals(false, result.isCharacter());
+ String outputValue = "[declaration] integer[";
+ assertEquals(outputValue,
+ result.toString().substring(0, outputValue.length()));
+ assertEquals(1, result.getLength());
+ assertEquals(false, result.isSigned());
+ }
+
+ /**
+ * Test that IntegerDeclaration throws when constructing a signed 1 bit
+ * declaration
+ */
+ @Test(expected = java.lang.IllegalArgumentException.class)
+ public void testIntegerDeclarationIllegalArgSignedBit() {
+ int len = 1;
+ boolean signed = true;
+ int base = 1;
+ ByteOrder byteOrder = ByteOrder.BIG_ENDIAN;
+ Encoding encoding = Encoding.ASCII;
+ IntegerDeclaration.createDeclaration(len, signed, base, byteOrder, encoding, "", 16);
+ }
+
+ /**
+ * Test that IntegerDeclaration throws when constructing a invalid length
+ * declaration
+ */
+ @Test(expected = java.lang.IllegalArgumentException.class)
+ public void testIntegerDeclarationIllegalArgBadLenght() {
+ int len = 0;
+ boolean signed = false;
+ int base = 1;
+ ByteOrder byteOrder = ByteOrder.BIG_ENDIAN;
+ Encoding encoding = Encoding.ASCII;
+ IntegerDeclaration.createDeclaration(len, signed, base, byteOrder, encoding, "", 16);
+ }
+
+ /**
+ * Test the factory part more rigorously to make sure there are no
+ * regressions
+ */
+ @Test
+ public void testIntegerDeclarationBruteForce() {
+ ByteOrder[] bos = { ByteOrder.LITTLE_ENDIAN, ByteOrder.BIG_ENDIAN };
+ Encoding[] encodings = { Encoding.ASCII, Encoding.NONE, Encoding.UTF8 };
+ boolean[] signeds = { true, false }; // not a real word
+ String[] clocks = { "something", "" };
+ int[] bases = { 2, 4, 6, 8, 10, 12, 16 };
+ for (int len = 2; len < 65; len++) {
+ for (ByteOrder bo : bos) {
+ for (boolean signed : signeds) {
+ for (int base : bases) {
+ for (Encoding enc : encodings) {
+ for (String clock : clocks) {
+ assertNotNull(enc);
+ assertNotNull(clock);
+ IntegerDeclaration intDec = IntegerDeclaration.createDeclaration(len, signed, base, bo, enc, clock, 8);
+ String title = Integer.toString(len) + " " + bo + " " + signed + " " + base + " " + enc;
+ assertEquals(title, signed, intDec.isSigned());
+ assertEquals(title, base, intDec.getBase());
+ // at len 8 le and be are the same
+ if (len != 8) {
+ assertEquals(title, bo, intDec.getByteOrder());
+ }
+ assertEquals(title, len, intDec.getLength());
+ assertEquals(title, len, intDec.getMaximumSize());
+ assertEquals(title, clock, intDec.getClock());
+ assertEquals(title, !signed && len == 8, intDec.isUnsignedByte());
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Run the int getBase() method test.
+ */
+ @Test
+ public void testGetBase() {
+ int result = fixture.getBase();
+ assertEquals(1, result);
+ }
+
+ /**
+ * Run the ByteOrder getByteOrder() method test.
+ */
+ @Test
+ public void testGetByteOrder() {
+ ByteOrder result = fixture.getByteOrder();
+ assertNotNull(result);
+ assertEquals("BIG_ENDIAN", result.toString());
+ }
+
+ /**
+ * Run the Encoding getEncoding() method test.
+ */
+ @Test
+ public void testGetEncoding() {
+ Encoding result = fixture.getEncoding();
+ assertNotNull(result);
+ assertEquals("ASCII", result.name());
+ assertEquals("ASCII", result.toString());
+ assertEquals(1, result.ordinal());
+ }
+
+ /**
+ * Run the int getLength() method test.
+ */
+ @Test
+ public void testGetLength() {
+ int result = fixture.getLength();
+ assertEquals(1, result);
+ }
+
+ /**
+ * Run the boolean isCharacter() method test.
+ */
+ @Test
+ public void testIsCharacter() {
+ boolean result = fixture.isCharacter();
+ assertEquals(false, result);
+ }
+
+ /**
+ * Run the boolean isCharacter() method test.
+ */
+ @Test
+ public void testIsCharacter_8bytes() {
+ IntegerDeclaration fixture8 = IntegerDeclaration.createDeclaration(8, true, 1,
+ ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 8);
+
+ boolean result = fixture8.isCharacter();
+ assertEquals(true, result);
+ }
+
+ /**
+ * Run the boolean isSigned() method test.
+ */
+ @Test
+ public void testIsSigned_signed() {
+ IntegerDeclaration fixtureSigned = IntegerDeclaration.createDeclaration(2, true,
+ 1, ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 8);
+ boolean result = fixtureSigned.isSigned();
+ assertEquals(true, result);
+ }
+
+ /**
+ * Run the boolean isSigned() method test.
+ */
+ @Test
+ public void testIsSigned_unsigned() {
+ boolean result = fixture.isSigned();
+ assertEquals(false, result);
+ }
+
+ /**
+ * Run the String toString() method test.
+ */
+ @Test
+ public void testToString() {
+ String result = fixture.toString();
+ String trunc = result.substring(0, 22);
+ assertEquals("[declaration] integer[", trunc);
+ }
+
+ /**
+ * Run the long getMaxValue() method test.
+ */
+ @Test
+ public void testMaxValue() {
+ assertEquals(BigInteger.ONE, fixture.getMaxValue());
+
+ IntegerDeclaration signed8bit = IntegerDeclaration.createDeclaration(8, true, 1, ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 32);
+ assertEquals(BigInteger.valueOf(127), signed8bit.getMaxValue());
+
+ IntegerDeclaration unsigned8bit = IntegerDeclaration.createDeclaration(8, false, 1, ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 32);
+ assertEquals(BigInteger.valueOf(255), unsigned8bit.getMaxValue());
+
+ IntegerDeclaration signed32bit = IntegerDeclaration.createDeclaration(32, true, 1, ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 32);
+ assertEquals(BigInteger.valueOf(2147483647), signed32bit.getMaxValue());
+
+ IntegerDeclaration unsigned32bit = IntegerDeclaration.createDeclaration(32, false, 1, ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 32);
+ assertEquals(BigInteger.valueOf(4294967295l), unsigned32bit.getMaxValue());
+
+ IntegerDeclaration signed64bit = IntegerDeclaration.createDeclaration(64, true, 1, ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 32);
+ assertEquals(BigInteger.valueOf(9223372036854775807L), signed64bit.getMaxValue());
+
+ IntegerDeclaration unsigned64bit = IntegerDeclaration.createDeclaration(64, false, 1, ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 32);
+ assertEquals(BigInteger.valueOf(2).pow(64).subtract(BigInteger.ONE), unsigned64bit.getMaxValue());
+ }
+
+ /**
+ * Run the long getMinValue() method test.
+ */
+ @Test
+ public void testMinValue() {
+ assertEquals(BigInteger.ZERO, fixture.getMinValue());
+
+ IntegerDeclaration signed8bit = IntegerDeclaration.createDeclaration(8, true, 1, ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 32);
+ assertEquals(BigInteger.valueOf(-128), signed8bit.getMinValue());
+
+ IntegerDeclaration unsigned8bit = IntegerDeclaration.createDeclaration(8, false, 1, ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 32);
+ assertEquals(BigInteger.ZERO, unsigned8bit.getMinValue());
+
+ IntegerDeclaration signed32bit = IntegerDeclaration.createDeclaration(32, true, 1, ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 32);
+ assertEquals(BigInteger.valueOf(-2147483648), signed32bit.getMinValue());
+
+ IntegerDeclaration unsigned32bit = IntegerDeclaration.createDeclaration(32, false, 1, ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 32);
+ assertEquals(BigInteger.ZERO, unsigned32bit.getMinValue());
+
+ IntegerDeclaration signed64bit = IntegerDeclaration.createDeclaration(64, true, 1, ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 32);
+ assertEquals(BigInteger.valueOf(-9223372036854775808L), signed64bit.getMinValue());
+
+ IntegerDeclaration unsigned64bit = IntegerDeclaration.createDeclaration(64, false, 1, ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 32);
+ assertEquals(BigInteger.ZERO, unsigned64bit.getMinValue());
+ }
+}
\ No newline at end of file
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.types;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.event.types.Encoding;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDefinition;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * The class <code>IntegerDefinitionTest</code> contains tests for the class
+ * <code>{@link IntegerDefinition}</code>.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+public class IntegerDefinitionTest {
+
+ private IntegerDefinition fixture;
+ @NonNull private static final String NAME = "testInt";
+ @NonNull private static final String clockName = "clock";
+
+ /**
+ * Perform pre-test initialization.
+ *
+ * @throws CTFReaderException
+ * won't happen
+ */
+ @Before
+ public void setUp() throws CTFReaderException {
+ IntegerDeclaration id = IntegerDeclaration.createDeclaration(1, false, 1, ByteOrder.BIG_ENDIAN, Encoding.NONE, clockName, 8);
+ ByteBuffer byb = ByteBuffer.allocate(128);
+ byb.mark();
+ byb.putInt(1);
+ byb.reset();
+ BitBuffer bb = new BitBuffer(byb);
+ fixture = id.createDefinition(null, NAME, bb);
+ }
+
+ /**
+ * Run the IntegerDefinition(IntegerDeclaration,DefinitionScope,String)
+ * constructor test.
+ */
+ @Test
+ public void testIntegerDefinition() {
+ IntegerDeclaration declaration = IntegerDeclaration.createDeclaration(1, false, 1,
+ ByteOrder.BIG_ENDIAN, Encoding.ASCII, "", 8);
+ IDefinitionScope definitionScope = null;
+ String fieldName = "";
+
+ IntegerDefinition result = new IntegerDefinition(declaration,
+ definitionScope, fieldName, 1);
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the IntegerDeclaration getDeclaration() method test.
+ */
+ @Test
+ public void testGetDeclaration() {
+ IntegerDeclaration result = fixture.getDeclaration();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the long getValue() method test.
+ */
+ @Test
+ public void testGetValue() {
+ long result = fixture.getValue();
+ assertEquals(0L, result);
+ }
+
+ /**
+ * Run the String toString() method test.
+ */
+ @Test
+ public void testToString() {
+ String result = fixture.toString();
+ assertEquals("0", result);
+ }
+
+ /**
+ * Run the IntegerDefinition formatNumber(Long, int, boolean) method test
+ * for unsigned values.
+ */
+ @Test
+ public void testFormatNumber_unsignedLong() {
+
+ long unsignedLongValue = -64;
+ String result = IntegerDefinition.formatNumber(unsignedLongValue, 10, false);
+ // -64 + 2^64 = 18446744073709551552
+ assertEquals("18446744073709551552", result);
+
+ unsignedLongValue = -131940199973272L;
+ result = IntegerDefinition.formatNumber(unsignedLongValue, 10, false);
+ // -131940199973272l + 2^64 = 18446612133509578344
+ assertEquals("18446612133509578344", result);
+
+ unsignedLongValue = 123456789L;
+ result = IntegerDefinition.formatNumber(unsignedLongValue, 10, false);
+ assertEquals("123456789", result);
+ }
+
+ /**
+ * Run the IntegerDefinition formatNumber(Long, int, boolean) method test
+ * for signed values.
+ */
+ @Test
+ public void testFormatNumber_signedLong() {
+ long signedValue = -64L;
+ String result = IntegerDefinition.formatNumber(signedValue, 10, true);
+ assertEquals("-64", result);
+
+ signedValue = -131940199973272L;
+ result = IntegerDefinition.formatNumber(signedValue, 10, true);
+ assertEquals("-131940199973272", result);
+
+ signedValue = 123456789L;
+ result = IntegerDefinition.formatNumber(signedValue, 10, true);
+ assertEquals("123456789", result);
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 École Polytechnique de Montréal, Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Geneviève Bastien - Initial API and implementation
+ * Alexandre Montplaisir - Split out in separate class
+ * Matthew Khouzam - update api (exceptions)
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.types;
+
+import static org.junit.Assert.assertEquals;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.types.Encoding;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDefinition;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * Endianness test for {@link IntegerDefinition}.
+ *
+ * @author Geneviève Bastien
+ */
+public class IntegerEndiannessTest {
+
+ private static final @NonNull String name = "testInt";
+ private static final @NonNull String clockName = "clock";
+
+ private ByteBuffer bb;
+
+ private @NonNull BitBuffer input = new BitBuffer();
+
+ /**
+ * Set up the bit-buffer to be used
+ */
+ @Before
+ public void setUp() {
+ bb = java.nio.ByteBuffer.allocateDirect(8);
+ final ByteBuffer byb = bb;
+ if (byb == null) {
+ throw new IllegalStateException("Failed to allocate memory");
+ }
+ bb.put((byte) 0xab);
+ bb.put((byte) 0xcd);
+ bb.put((byte) 0xef);
+ bb.put((byte) 0x12);
+ bb.put((byte) 0x34);
+ bb.put((byte) 0x56);
+ bb.put((byte) 0x78);
+ bb.put((byte) 0x9a);
+
+ input = new BitBuffer(byb);
+ }
+
+ /**
+ * Read 32-bits BE
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void test32BE() throws CTFReaderException {
+ IntegerDeclaration be = IntegerDeclaration.createDeclaration(32, true, 1, ByteOrder.BIG_ENDIAN, Encoding.NONE, clockName, 8);
+ IntegerDefinition fixture_be = be.createDefinition(null, name, input);
+ assertEquals(0xabcdef12, fixture_be.getValue());
+ }
+
+ /**
+ * Read 64-bits BE
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void test64BE() throws CTFReaderException {
+ IntegerDeclaration be = IntegerDeclaration.createDeclaration(64, true, 1, ByteOrder.BIG_ENDIAN, Encoding.NONE, clockName, 8);
+ IntegerDefinition fixture_be = be.createDefinition(null, name, input);
+ assertEquals(0xabcdef123456789aL, fixture_be.getValue());
+ }
+
+ /**
+ * Read 32-bits LE
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void test32LE() throws CTFReaderException {
+ IntegerDeclaration le = IntegerDeclaration.createDeclaration(32, true, 1, ByteOrder.LITTLE_ENDIAN, Encoding.NONE, clockName, 8);
+ IntegerDefinition fixture_le = le.createDefinition(null, name, input);
+ assertEquals(0x12efcdab, fixture_le.getValue());
+ }
+
+ /**
+ * Read 64-bits LE
+ *
+ * @throws CTFReaderException
+ * error
+ */
+ @Test
+ public void test64LE() throws CTFReaderException {
+ IntegerDeclaration le = IntegerDeclaration.createDeclaration(64, true, 1, ByteOrder.LITTLE_ENDIAN, Encoding.NONE, clockName, 8);
+ IntegerDefinition fixture_le = le.createDefinition(null, name, input);
+ assertEquals(0x9a78563412efcdabL, fixture_le.getValue());
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.types;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.types.AbstractArrayDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.Definition;
+import org.eclipse.tracecompass.ctf.core.event.types.Encoding;
+import org.eclipse.tracecompass.ctf.core.event.types.IDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.StringDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDefinition;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.internal.ctf.core.event.types.SequenceDeclaration;
+import org.junit.Before;
+import org.junit.Test;
+
+import com.google.common.collect.ImmutableList;
+
+/**
+ * The class <code>SequenceDeclarationTest</code> contains tests for the class
+ * <code>{@link SequenceDeclaration}</code>.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+@SuppressWarnings("javadoc")
+public class SequenceDeclaration2Test {
+
+ @NonNull private static final String FIELD_NAME = "LengthName";
+
+ private SequenceDeclaration fixture;
+ @NonNull private BitBuffer input = new BitBuffer();
+
+ @Before
+ public void setUp() {
+ fixture = new SequenceDeclaration(FIELD_NAME, new StringDeclaration());
+ byte array[] = { 't', 'e', 's', 't', '\0', 't', 'h', 'i', 's', '\0' };
+ ByteBuffer byb = ByteBuffer.wrap(array);
+ if( byb == null){
+ throw new IllegalStateException("Failed to allocate memory");
+ }
+ input = new BitBuffer(byb);
+ }
+
+ /**
+ * Run the SequenceDeclaration(String,Declaration) constructor test.
+ */
+ @Test
+ public void testSequenceDeclaration() {
+ String lengthName = "";
+ IDeclaration elemType = new StringDeclaration();
+
+ SequenceDeclaration result = new SequenceDeclaration(lengthName, elemType);
+ assertNotNull(result);
+ String string = "[declaration] sequence[";
+ assertEquals(string, result.toString().substring(0, string.length()));
+ }
+
+ /**
+ * Run the SequenceDefinition createDefinition(DefinitionScope,String)
+ * method test.
+ *
+ * @throws CTFReaderException
+ * an error in the bitbuffer
+ */
+ @Test
+ public void testCreateDefinition() throws CTFReaderException {
+ long seqLen = 2;
+ IntegerDeclaration id = IntegerDeclaration.createDeclaration(8, false, 8,
+ ByteOrder.LITTLE_ENDIAN, Encoding.UTF8, "", 32);
+ StructDeclaration structDec = new StructDeclaration(0);
+ structDec.addField(FIELD_NAME, id);
+ StructDefinition structDef = new StructDefinition(
+ structDec,
+ null,
+ "x",
+ ImmutableList.of(FIELD_NAME),
+ new Definition[] {
+ new IntegerDefinition(
+ id,
+ null,
+ FIELD_NAME,
+ seqLen)
+ });
+ AbstractArrayDefinition result = fixture.createDefinition(structDef, FIELD_NAME, input);
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the Declaration getElementType() method test.
+ */
+ @Test
+ public void testGetElementType() {
+ IDeclaration result = fixture.getElementType();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the String toString() method test.
+ */
+ @Test
+ public void testToString() {
+ String result = fixture.toString();
+ String left = "[declaration] sequence[";
+ assertEquals(left, result.substring(0, left.length()));
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.types;
+
+import static org.junit.Assert.assertNotNull;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.types.Definition;
+import org.eclipse.tracecompass.ctf.core.event.types.Encoding;
+import org.eclipse.tracecompass.ctf.core.event.types.IDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDefinition;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.internal.ctf.core.event.types.ByteArrayDefinition;
+import org.eclipse.tracecompass.internal.ctf.core.event.types.SequenceDeclaration;
+import org.junit.Before;
+import org.junit.Test;
+
+import com.google.common.collect.ImmutableList;
+
+/**
+ * The class <code>SequenceDefinition2Test</code> contains tests for the class
+ * <code>{@link SequenceDefinition2}</code>.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+@SuppressWarnings("javadoc")
+public class SequenceDefinition2Test {
+
+ private ByteArrayDefinition fixture;
+ private final static int seqLen = 15;
+
+ private static ImmutableList<String> wrap(String s) {
+ return ImmutableList.<String> builder().add(s).build();
+ }
+
+ /**
+ * Perform pre-test initialization.
+ *
+ * @throws CTFReaderException
+ */
+ @Before
+ public void setUp() throws CTFReaderException {
+ fixture = initString();
+ }
+
+ private static ByteArrayDefinition initString() throws CTFReaderException {
+ StructDeclaration structDec;
+ StructDefinition structDef;
+
+ int len = 8;
+ IntegerDeclaration id = IntegerDeclaration.createDeclaration(len, false, len,
+ ByteOrder.LITTLE_ENDIAN, Encoding.UTF8, "", 8);
+ String lengthName = "LengthName";
+ structDec = new StructDeclaration(0);
+ structDec.addField(lengthName, id);
+
+ structDef = new StructDefinition(structDec, null, "x", wrap(lengthName), new Definition[] { new IntegerDefinition(id, null, lengthName, seqLen) });
+
+ SequenceDeclaration sd = new SequenceDeclaration(lengthName, id);
+ ByteBuffer allocateDirect = java.nio.ByteBuffer.allocateDirect(seqLen * len);
+ if( allocateDirect == null){
+ throw new IllegalStateException("Failed to allocate memory");
+ }
+ BitBuffer input = new BitBuffer(allocateDirect);
+ for (int i = 0; i < seqLen; i++) {
+ input.putInt(i);
+ }
+
+ ByteArrayDefinition ret = (ByteArrayDefinition) sd.createDefinition(structDef, "TestX", input);
+ assertNotNull(ret);
+ return ret;
+ }
+
+ /**
+ * Run the FixedStringDefinition(SequenceDeclaration,DefinitionScope,String)
+ * constructor test.
+ */
+ @Test
+ public void testFixedStringDefinition() {
+ assertNotNull(fixture);
+ }
+
+ /**
+ * Run the SequenceDeclaration getDeclaration() method test.
+ */
+ @Test
+ public void testGetDeclaration() {
+ SequenceDeclaration result = (SequenceDeclaration) fixture.getDeclaration();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the Definition getElem(int) method test.
+ */
+ @Test
+ public void testGetElem() {
+ int i = 1;
+ IDefinition result = fixture.getDefinitions().get(i);
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the String toString() method test.
+ */
+ @Test
+ public void testToString() {
+ String result = fixture.toString();
+ assertNotNull(result);
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.types;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import java.nio.ByteBuffer;
+
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.event.types.Encoding;
+import org.eclipse.tracecompass.ctf.core.event.types.StringDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StringDefinition;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * The class <code>StringDeclarationTest</code> contains tests for the class
+ * <code>{@link StringDeclaration}</code>.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+public class StringDeclarationTest {
+
+ private StringDeclaration fixture;
+
+ /**
+ * Perform pre-test initialization.
+ */
+ @Before
+ public void setUp() {
+ fixture = new StringDeclaration(Encoding.ASCII);
+ }
+
+ /**
+ * Run the StringDeclaration() constructor test.
+ */
+ @Test
+ public void testStringDeclaration() {
+ StringDeclaration result = new StringDeclaration();
+
+ assertNotNull(result);
+ String string = "[declaration] string[";
+ assertEquals(string, result.toString().substring(0, string.length()));
+ }
+
+ /**
+ * Run the StringDeclaration(Encoding) constructor test.
+ */
+ @Test
+ public void testStringDeclaration_2() {
+ Encoding encoding = Encoding.ASCII;
+ StringDeclaration result = new StringDeclaration(encoding);
+
+ assertNotNull(result);
+ String string = "[declaration] string[";
+ assertEquals(string, result.toString().substring(0, string.length()));
+ }
+
+ /**
+ * Run the StringDefinition createDefinition(DefinitionScope,String) method
+ * test.
+ *
+ * @throws CTFReaderException
+ * out of buffer exception
+ */
+ @Test
+ public void testCreateDefinition() throws CTFReaderException {
+ IDefinitionScope definitionScope = null;
+ String fieldName = "id";
+ ByteBuffer allocate = ByteBuffer.allocate(100);
+ if (allocate == null) {
+ throw new IllegalStateException("Failed to allocate memory");
+ }
+ BitBuffer bb = new BitBuffer(allocate);
+ StringDefinition result = fixture.createDefinition(definitionScope,
+ fieldName, bb);
+
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the Encoding getEncoding() method test.
+ */
+ @Test
+ public void testGetEncoding() {
+ Encoding result = fixture.getEncoding();
+
+ assertNotNull(result);
+ assertEquals("ASCII", result.name());
+ assertEquals("ASCII", result.toString());
+ assertEquals(1, result.ordinal());
+ }
+
+ /**
+ * Run the String toString() method test.
+ */
+ @Test
+ public void testToString() {
+ String result = fixture.toString();
+ String left = "[declaration] string[";
+ String right = result.substring(0, left.length());
+
+ assertEquals(left, right);
+ }
+}
\ No newline at end of file
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.types;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import java.nio.ByteBuffer;
+
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.event.types.StringDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StringDefinition;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * The class <code>StringDefinitionTest</code> contains tests for the class
+ * <code>{@link StringDefinition}</code>.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+public class StringDefinitionTest {
+
+ private StringDefinition fixture;
+ private String testString;
+
+ /**
+ * Perform pre-test initialization.
+ *
+ * @throws CTFReaderException
+ * won't happen
+ */
+ @Before
+ public void setUp() throws CTFReaderException {
+ String name = "testString";
+ StringDeclaration stringDec = new StringDeclaration();
+ ByteBuffer byteBuffer = ByteBuffer.allocate(100);
+ if (byteBuffer == null) {
+ throw new IllegalStateException("Failed to allocate memory");
+ }
+ BitBuffer bb = new BitBuffer(byteBuffer);
+ byteBuffer.mark();
+ testString = new String("testString");
+ byteBuffer.put(testString.getBytes());
+ byteBuffer.reset();
+ fixture = stringDec.createDefinition(null, name, bb);
+ }
+
+ /**
+ * Run the StringDefinition(StringDeclaration,DefinitionScope,String)
+ * constructor test.
+ */
+ @Test
+ public void testStringDefinition() {
+ StringDeclaration declaration = new StringDeclaration();
+ IDefinitionScope definitionScope = null;
+ String fieldName = "";
+
+ StringDefinition result = new StringDefinition(declaration,
+ definitionScope, fieldName, "");
+
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the StringDeclaration getDeclaration() method test.
+ */
+ @Test
+ public void testGetDeclaration() {
+ StringDeclaration result = fixture.getDeclaration();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the String getValue() method test.
+ */
+ @Test
+ public void testGetValue() {
+ String result = fixture.getValue();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the String setValue() method test.
+ */
+ @Test
+ public void testSetValue() {
+
+ String result = fixture.getValue();
+ assertNotNull(result);
+ assertEquals("testString", result);
+ }
+
+ /**
+ * Run the String toString() method test.
+ */
+ @Test
+ public void testToString() {
+ String result = fixture.toString();
+ assertNotNull(result);
+ }
+}
\ No newline at end of file
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.types;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.nio.ByteBuffer;
+
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.types.IDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StringDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDefinition;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * The class <code>StructDeclarationTest</code> contains tests for the class
+ * <code>{@link StructDeclaration}</code>.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+public class StructDeclarationTest {
+
+ private StructDeclaration fixture;
+
+ /**
+ * Perform pre-test initialization.
+ */
+ @Before
+ public void setUp() {
+ fixture = new StructDeclaration(1L);
+ }
+
+ /**
+ * Run the StructDeclaration(long) constructor test.
+ */
+ @Test
+ public void testStructDeclaration() {
+ assertNotNull(fixture);
+ assertEquals(1L, fixture.getMaxAlign());
+
+ String regex = "^\\[declaration\\] struct\\[[0-9a-f]{1,8}\\]$";
+ assertTrue(fixture.toString().matches(regex));
+ }
+
+ /**
+ * Run the void addField(String,Declaration) method test.
+ */
+ @Test
+ public void testAddField() {
+ String name = "";
+ IDeclaration declaration = new StringDeclaration();
+ fixture.addField(name, declaration);
+ }
+
+ /**
+ * Run the StructDefinition createDefinition(DefinitionScope,String) method
+ * test.
+ *
+ * @throws CTFReaderException
+ * out of bounds
+ */
+ @Test
+ public void testCreateDefinition() throws CTFReaderException {
+ String fieldName = "";
+ ByteBuffer allocate = ByteBuffer.allocate(100);
+ if( allocate == null){
+ throw new IllegalStateException("Failed to allocate memory");
+ }
+ BitBuffer bb = new BitBuffer(allocate);
+ StructDefinition result = fixture.createDefinition(null, fieldName, bb);
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the Declaration getField(String) method test.
+ */
+ @Test
+ public void testGetField() {
+ IDeclaration result = fixture.getField("test");
+
+ assertNull(result);
+ }
+
+ /**
+ * Run the List<String> getFieldsList() method test.
+ */
+ @Test
+ public void testGetFieldsList() {
+ Iterable<String> result = fixture.getFieldsList();
+
+ assertNotNull(result);
+ assertEquals(false, result.iterator().hasNext());
+ }
+
+ /**
+ * Run the long getMinAlign() method test.
+ */
+ @Test
+ public void testGetMinAlign() {
+ long result = fixture.getMaxAlign();
+ assertEquals(1L, result);
+ }
+
+ /**
+ * Run the boolean hasField(String) method test.
+ */
+ @Test
+ public void testHasField() {
+ String name = "";
+ boolean result = fixture.hasField(name);
+
+ assertEquals(false, result);
+ }
+
+ /**
+ * Run the String toString() method test.
+ */
+ @Test
+ public void testToString() {
+ String result = fixture.toString();
+ String trunc = result.substring(0, 21);
+
+ assertEquals("[declaration] struct[", trunc);
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.types;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+import java.nio.ByteBuffer;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.types.AbstractArrayDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.EnumDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.EnumDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.IDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.StringDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StringDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.VariantDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.VariantDefinition;
+import org.eclipse.tracecompass.ctf.core.tests.io.Util;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.internal.ctf.core.event.types.SequenceDeclaration;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * The class <code>StructDefinitionTest</code> contains tests for the class
+ * <code>{@link StructDefinition}</code>.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+public class StructDefinitionTest {
+
+ private static final @NonNull String TEST_STRUCT_ID = "testStruct";
+ private static final @NonNull String ENUM_2 = "y";
+ private static final @NonNull String ENUM_1 = "x";
+ private static final @NonNull String TAG_ID = "Tag";
+ private static final @NonNull String INT_ID = "_id";
+ private static final @NonNull String STRING_ID = "_args";
+ private static final @NonNull String ENUM_ID = "_enumArgs";
+ private static final @NonNull String SEQUENCE_ID = "_seq";
+ private static final @NonNull String LENGTH_SEQ = "_len";
+ private static final @NonNull String VAR_FIELD_NAME = "SomeVariant";
+
+ private StructDefinition fixture;
+ private StructDefinition emptyStruct;
+ private StructDefinition simpleStruct;
+
+ /**
+ * Perform pre-test initialization.
+ *
+ * @throws CTFReaderException
+ * won't happen
+ */
+ @Before
+ public void setUp() throws CTFReaderException {
+ StructDeclaration sDec = new StructDeclaration(12);
+ IntegerDeclaration id = IntegerDeclaration.INT_32B_DECL;
+ IntegerDeclaration lenDec = IntegerDeclaration.UINT_8_DECL;
+ StringDeclaration sd = new StringDeclaration();
+ EnumDeclaration ed = new EnumDeclaration(id);
+ SequenceDeclaration seqDec = new SequenceDeclaration(LENGTH_SEQ, id);
+ VariantDeclaration varDec = new VariantDeclaration();
+ EnumDeclaration tagDec = new EnumDeclaration(id);
+ tagDec.add(0, 1, ENUM_1);
+ tagDec.add(2, 3, ENUM_2);
+ varDec.addField(ENUM_2, id);
+ varDec.addField(ENUM_1, sd);
+ varDec.setTag(TAG_ID);
+ sDec.addField(INT_ID, id);
+ sDec.addField(STRING_ID, sd);
+ sDec.addField(ENUM_ID, ed);
+ sDec.addField(TAG_ID, tagDec);
+ sDec.addField(LENGTH_SEQ, lenDec);
+ sDec.addField(SEQUENCE_ID, seqDec);
+ sDec.addField(VAR_FIELD_NAME, varDec);
+ byte bytes[] = new byte[100];
+ bytes[4] = 1;
+ bytes[8] = 2;
+ bytes[13] = 3;
+ BitBuffer bb = new BitBuffer(Util.testMemory(ByteBuffer.wrap(bytes)));
+ fixture = sDec.createDefinition(null, TEST_STRUCT_ID, bb);
+ EnumDefinition eDef = tagDec.createDefinition(fixture, TAG_ID, bb);
+ assertNotNull(eDef);
+ VariantDefinition vd = varDec.createDefinition(fixture, VAR_FIELD_NAME, bb);
+ assertNotNull(vd);
+ // Create an empty struct
+ StructDeclaration esDec = new StructDeclaration(32);
+ emptyStruct = esDec.createDefinition(null, TEST_STRUCT_ID, bb);
+
+ // Create a simple struct with two items
+ StructDeclaration ssDec = new StructDeclaration(32);
+ ssDec.addField(INT_ID, id);
+ ssDec.addField(STRING_ID, sd);
+ simpleStruct = ssDec.createDefinition(null, TEST_STRUCT_ID, bb);
+ }
+
+ /**
+ * Run the StructDeclaration getDeclaration() method test.
+ */
+ @Test
+ public void testGetDeclaration() {
+ StructDeclaration result = fixture.getDeclaration();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the HashMap<String, Definition> getDefinitions() method test.
+ */
+ @Test
+ public void testGetDefinitions_1() {
+ IDefinition result = fixture.getDefinition("_id");
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the ArrayDefinition lookupArray(String) method test.
+ */
+ @Test
+ public void testLookupArray() {
+ String name = INT_ID;
+ AbstractArrayDefinition result = fixture.lookupArrayDefinition(name);
+ assertNull(result);
+ }
+
+ /**
+ * Run the Definition lookupDefinition(String) method test.
+ */
+ @Test
+ public void testLookupDefinition() {
+ String lookupPath = "args";
+ IDefinition result = fixture.lookupDefinition(lookupPath);
+
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the EnumDefinition lookupEnum(String) method test.
+ */
+ @Test
+ public void testLookupEnum() {
+ String name = ENUM_ID;
+ EnumDefinition result = fixture.lookupEnum(name);
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the IntegerDefinition lookupInteger(String) method test.
+ */
+ @Test
+ public void testLookupInteger_1() {
+ String name = "_id";
+ IntegerDefinition result = fixture.lookupInteger(name);
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the IntegerDefinition lookupInteger(String) method test.
+ */
+ @Test
+ public void testLookupInteger_2() {
+ String name = VAR_FIELD_NAME;
+ IntegerDefinition result = fixture.lookupInteger(name);
+ assertNull(result);
+ }
+
+ /**
+ * Run the SequenceDefinition lookupSequence(String) method test.
+ */
+ @Test
+ public void testLookupFixedStringDefinition() {
+ String name = SEQUENCE_ID;
+ AbstractArrayDefinition result = fixture.lookupArrayDefinition(name);
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the StringDefinition lookupString(String) method test.
+ */
+ @Test
+ public void testLookupString() {
+ String name = VAR_FIELD_NAME;
+ StringDefinition result = fixture.lookupString(name);
+
+ assertNull(result);
+ }
+
+ /**
+ * Run the StructDefinition lookupStruct(String) method test.
+ */
+ @Test
+ public void testLookupStruct() {
+ String name = VAR_FIELD_NAME;
+ StructDefinition result = fixture.lookupStruct(name);
+
+ assertNull(result);
+ }
+
+ /**
+ * Run the VariantDefinition lookupVariant(String) method test.
+ */
+ @Test
+ public void testLookupVariant() {
+ String name = VAR_FIELD_NAME;
+ VariantDefinition result = fixture.lookupVariant(name);
+
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the String toString() method test.
+ */
+ @Test
+ public void testToString() {
+ String result = fixture.toString();
+ assertNotNull(result);
+
+ result = emptyStruct.toString();
+ assertEquals("{ }", result);
+
+ result = simpleStruct.toString();
+ assertEquals("{ _id = 0, _args = \"\" }", result);
+ }
+}
\ No newline at end of file
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.types;
+
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+
+/**
+ * The class <code>TestAll</code> builds a suite that can be used to run all of
+ * the tests within its package as well as within any subpackages of its
+ * package.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+@RunWith(Suite.class)
+@Suite.SuiteClasses({
+ ArrayDeclaration2Test.class,
+ ArrayDefinition2Test.class,
+ DefinitionTest.class,
+ EnumDeclarationTest.class,
+ EnumDefinitionTest.class,
+ EventDeclarationTest.class,
+ EventHeaderDeclarationTest.class,
+ FloatDeclarationTest.class,
+ FloatDefinitionTest.class,
+ IntegerDeclarationTest.class,
+ IntegerDefinitionTest.class,
+ IntegerEndiannessTest.class,
+ SequenceDeclaration2Test.class,
+ SequenceDefinition2Test.class,
+ StringDeclarationTest.class,
+ StringDefinitionTest.class,
+ StructDeclarationTest.class,
+ StructDefinitionTest.class,
+ VariantDeclarationTest.class,
+ VariantDefinitionTest.class,
+})
+public class TestAll {
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.types;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assume.assumeTrue;
+
+import java.nio.ByteBuffer;
+
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.event.types.Definition;
+import org.eclipse.tracecompass.ctf.core.event.types.EnumDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.EnumDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.IDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.StringDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StringDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.VariantDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.VariantDefinition;
+import org.eclipse.tracecompass.ctf.core.tests.shared.CtfTestTrace;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.junit.Before;
+import org.junit.Test;
+
+import com.google.common.collect.ImmutableList;
+
+/**
+ * The class <code>VariantDeclarationTest</code> contains tests for the class
+ * <code>{@link VariantDeclaration}</code>.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+public class VariantDeclarationTest {
+
+ private static final CtfTestTrace testTrace = CtfTestTrace.KERNEL;
+
+ private VariantDeclaration fixture;
+
+ /**
+ * Perform pre-test initialization.
+ */
+ @Before
+ public void setUp() {
+ fixture = new VariantDeclaration();
+ }
+
+ private static IDefinitionScope createDefinitionScope() throws CTFReaderException {
+ assumeTrue(testTrace.exists());
+ StructDeclaration declaration = new StructDeclaration(8);
+ VariantDeclaration variantDeclaration = new VariantDeclaration();
+ variantDeclaration.addField("a", IntegerDeclaration.INT_32B_DECL);
+ variantDeclaration.addField("b", IntegerDeclaration.INT_32L_DECL);
+ variantDeclaration.setTag("a");
+
+ EnumDeclaration enumDeclaration = new EnumDeclaration(IntegerDeclaration.UINT_8_DECL);
+ enumDeclaration.add(0, 1, "a");
+ enumDeclaration.add(2, 2, "b");
+ declaration.addField("tag", enumDeclaration);
+ declaration.addField("variant", variantDeclaration);
+ EnumDefinition tagDef = new EnumDefinition(
+ enumDeclaration,
+ null,
+ "tag",
+ new IntegerDefinition(
+ IntegerDeclaration.UINT_8_DECL,
+ null,
+ "test",
+ 0)
+ );
+ VariantDefinition variantDefinition = new VariantDefinition(
+ variantDeclaration,
+ testTrace.getTrace(),
+ "tag",
+ "tag",
+ new StringDefinition(
+ new StringDeclaration(),
+ null,
+ "f",
+ "tag"
+ ));
+
+ IDefinitionScope definitionScope = new StructDefinition(
+ declaration,
+ variantDefinition,
+ "",
+ ImmutableList.of("tag", variantDefinition.getCurrentFieldName()),
+ new Definition[] { tagDef, variantDefinition }
+ );
+
+ return definitionScope;
+ }
+
+ /**
+ * Run the VariantDeclaration() constructor test.
+ */
+ @Test
+ public void testVariantDeclaration() {
+ assertNotNull(fixture);
+ assertEquals(false, fixture.isTagged());
+ String left = "[declaration] variant[";
+ assertEquals(left, fixture.toString().substring(0, left.length()));
+ }
+
+ /**
+ * Run the void addField(String,Declaration) method test.
+ */
+ @Test
+ public void testAddField() {
+ fixture.setTag("");
+ String tag = "";
+ IDeclaration declaration = new StringDeclaration();
+ fixture.addField(tag, declaration);
+ }
+
+ /**
+ * Run the VariantDefinition createDefinition(DefinitionScope,String) method
+ * test.
+ *
+ * @throws CTFReaderException
+ * Should not happen
+ */
+ @Test
+ public void testCreateDefinition() throws CTFReaderException {
+ fixture.setTag("tag");
+ fixture.addField("a", IntegerDeclaration.UINT_64B_DECL);
+ IDefinitionScope definitionScope = createDefinitionScope();
+ String fieldName = "";
+ ByteBuffer allocate = ByteBuffer.allocate(100);
+ if( allocate == null){
+ throw new IllegalStateException("Failed to allocate memory");
+ }
+ BitBuffer bb = new BitBuffer(allocate);
+ VariantDefinition result = fixture.createDefinition(definitionScope, fieldName, bb);
+
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the boolean hasField(String) method test.
+ */
+ @Test
+ public void testHasField() {
+ fixture.setTag("");
+ String tag = "";
+ boolean result = fixture.hasField(tag);
+
+ assertEquals(false, result);
+ }
+
+ /**
+ * Run the boolean isTagged() method test.
+ */
+ @Test
+ public void testIsTagged() {
+ fixture.setTag("");
+ boolean result = fixture.isTagged();
+
+ assertEquals(true, result);
+ }
+
+ /**
+ * Run the boolean isTagged() method test.
+ */
+ @Test
+ public void testIsTagged_null() {
+ fixture.setTag((String) null);
+ boolean result = fixture.isTagged();
+
+ assertEquals(false, result);
+ }
+
+ /**
+ * Run the void setTag(String) method test.
+ */
+ @Test
+ public void testSetTag() {
+ fixture.setTag("");
+ String tag = "";
+ fixture.setTag(tag);
+ }
+
+ /**
+ * Run the String toString() method test.
+ */
+ @Test
+ public void testToString() {
+ fixture.setTag("");
+ String result = fixture.toString();
+ String left = "[declaration] variant[";
+ String right = result.substring(0, left.length());
+
+ assertEquals(left, right);
+ }
+}
\ No newline at end of file
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013, 2014 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.tests.types;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.event.types.AbstractArrayDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.CompoundDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.Definition;
+import org.eclipse.tracecompass.ctf.core.event.types.Encoding;
+import org.eclipse.tracecompass.ctf.core.event.types.EnumDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.EnumDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.FloatDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.StringDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StringDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.VariantDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.VariantDefinition;
+import org.eclipse.tracecompass.ctf.core.tests.io.Util;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.internal.ctf.core.event.types.ArrayDeclaration;
+import org.junit.Before;
+import org.junit.Test;
+
+import com.google.common.collect.ImmutableList;
+
+/**
+ * The class <code>VariantDefinitionTest</code> contains tests for the class
+ * <code>{@link VariantDefinition}</code>.
+ *
+ * @author ematkho
+ * @version $Revision: 1.0 $
+ */
+public class VariantDefinitionTest {
+
+ private VariantDefinition fixture;
+
+ StructDefinition fStructDefinition;
+ private static final @NonNull String TEST_STRUCT_ID = "testStruct";
+ private static final @NonNull String ENUM_7 = "g";
+ private static final @NonNull String ENUM_6 = "f";
+ private static final @NonNull String ENUM_5 = "e";
+ private static final @NonNull String ENUM_4 = "d";
+ private static final @NonNull String ENUM_3 = "c";
+ private static final @NonNull String ENUM_2 = "b";
+ private static final @NonNull String ENUM_1 = "a";
+ private static final @NonNull String TAG_ID = "a";
+ private static final @NonNull String LENGTH_SEQ = "_len";
+ private static final @NonNull String VAR_FIELD_NAME = "var";
+ private static final @NonNull String ENUM_8 = "bbq ribs";
+
+ /**
+ * Perform pre-test initialization.
+ *
+ * Not sure it needs to be that complicated, oh well...
+ *
+ * @throws CTFReaderException
+ * won't happen
+ */
+ @Before
+ public void setUp() throws CTFReaderException {
+ StructDeclaration sDec = new StructDeclaration(12);
+ StructDeclaration smallStruct = new StructDeclaration(8);
+ IntegerDeclaration iDec = IntegerDeclaration.createDeclaration(32, false, 32, ByteOrder.BIG_ENDIAN, Encoding.NONE, "", 8);
+ IntegerDeclaration lenDec = IntegerDeclaration.createDeclaration(8, false, 8, ByteOrder.BIG_ENDIAN, Encoding.NONE, "", 8);
+ StringDeclaration strDec = new StringDeclaration();
+ EnumDeclaration enDec = new EnumDeclaration(iDec);
+ VariantDeclaration varDec = new VariantDeclaration();
+ EnumDeclaration tagDec = new EnumDeclaration(iDec);
+ CompoundDeclaration arrDec = new ArrayDeclaration(2, iDec);
+ FloatDeclaration fDec = new FloatDeclaration(8, 24, ByteOrder.BIG_ENDIAN, 8);
+ tagDec.add(0, 1, ENUM_1);
+ tagDec.add(2, 3, ENUM_2);
+ tagDec.add(4, 5, ENUM_3);
+ tagDec.add(8, 9, ENUM_5);
+ tagDec.add(10, 11, ENUM_6);
+ tagDec.add(12, 13, ENUM_7);
+ varDec.addField(ENUM_4, lenDec);
+ varDec.addField(ENUM_7, fDec);
+ varDec.addField(ENUM_6, smallStruct);
+ varDec.addField(ENUM_5, enDec);
+ varDec.addField(ENUM_3, arrDec);
+ varDec.addField(ENUM_2, iDec);
+ varDec.addField(ENUM_1, strDec);
+
+ sDec.addField(TAG_ID, tagDec);
+ sDec.addField(LENGTH_SEQ, lenDec);
+
+ sDec.addField(VAR_FIELD_NAME, varDec);
+ varDec.setTag(TAG_ID);
+
+ final ByteBuffer byteBuffer = Util.testMemory(ByteBuffer.allocate(100));
+ BitBuffer bb = new BitBuffer(byteBuffer);
+ byteBuffer.mark();
+ byteBuffer.putInt(1);
+ byteBuffer.putInt(2);
+ byteBuffer.putInt(3);
+ byteBuffer.reset();
+ fStructDefinition = sDec.createDefinition(null, TEST_STRUCT_ID, bb);
+ fixture = (VariantDefinition) fStructDefinition.getDefinition(VAR_FIELD_NAME);
+ }
+
+ /**
+ * Run the VariantDefinition(VariantDeclaration,DefinitionScope,String)
+ *
+ * @throws CTFReaderException
+ * should not happen
+ */
+ @Test
+ public void testVariantDefinition() throws CTFReaderException {
+ VariantDeclaration declaration = new VariantDeclaration();
+ declaration.setTag("");
+ VariantDeclaration variantDeclaration = new VariantDeclaration();
+ variantDeclaration.addField("", new EnumDeclaration(IntegerDeclaration.INT_32B_DECL));
+ variantDeclaration.addField("a", IntegerDeclaration.INT_64B_DECL);
+ declaration.addField(ENUM_3, new StringDeclaration());
+ variantDeclaration.setTag("a");
+
+ byte[] bytes = new byte[128];
+ ByteBuffer byb = ByteBuffer.wrap(bytes);
+ byb.mark();
+ byb.putInt(0);
+ byb.putShort((short) 2);
+ byb.put(new String("hello").getBytes());
+ byb.reset();
+ BitBuffer bb = new BitBuffer(byb);
+ VariantDefinition variantDefinition = variantDeclaration.createDefinition(fStructDefinition, "field", bb);
+ EnumDeclaration declaration2 = new EnumDeclaration(IntegerDeclaration.INT_8_DECL);
+ declaration2.add(0, 2, ENUM_3);
+ EnumDefinition enumDefinition = new EnumDefinition(
+ declaration2,
+ null,
+ "a",
+ new IntegerDefinition(
+ IntegerDeclaration.INT_8_DECL,
+ null,
+ "A",
+ 1
+ ));
+ IDefinitionScope definitionScope = new StructDefinition(
+ new StructDeclaration(1L),
+ variantDefinition,
+ "",
+ ImmutableList.<String> of("", "variant"),
+ new Definition[] { enumDefinition, variantDefinition }
+ );
+ String fieldName = "";
+ declaration.setTag("");
+ VariantDefinition result = declaration.createDefinition(definitionScope, fieldName, bb);
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the Definition getCurrentField() method test.
+ */
+ @Test
+ public void testGetCurrentField() {
+ IDefinition result = fixture.getCurrentField();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the String getCurrentFieldName() method test.
+ */
+ @Test
+ public void testGetCurrentFieldName() {
+ String result = fixture.getCurrentFieldName();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the VariantDeclaration getDeclaration() method test.
+ */
+ @Test
+ public void testGetDeclaration() {
+ VariantDeclaration result = fixture.getDeclaration();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the HashMap<String, Definition> getDefinitions() method test.
+ */
+ @Test
+ public void testGetDefinitions() {
+ IDefinition result = fixture.getCurrentField();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the String getPath() method test.
+ */
+ @Test
+ public void testGetPath() {
+ String result = fixture.getScopePath().toString();
+ assertNotNull(result);
+ }
+
+ /**
+ * Run the ArrayDefinition lookupArray(String) method test.
+ */
+ @Test
+ public void testLookupArray() {
+ AbstractArrayDefinition result = fixture.lookupArrayDefinition(ENUM_3);
+ assertNull(result);
+ }
+
+ /**
+ * Run the Definition lookupDefinition(String) method test.
+ */
+ @Test
+ public void testLookupDefinition() {
+ IDefinition result = fixture.lookupDefinition(ENUM_1);
+ assertNotNull(result);
+ assertEquals("a", ((EnumDefinition) result).getStringValue());
+ }
+
+ /**
+ * Run the EnumDefinition lookupEnum(String) method test.
+ */
+ @Test
+ public void testLookupEnum() {
+ EnumDefinition result = fixture.lookupEnum(ENUM_5);
+ assertNull(result);
+ }
+
+ /**
+ * Run the IntegerDefinition lookupInteger(String) method test.
+ */
+ @Test
+ public void testLookupInteger() {
+ IntegerDefinition result = fixture.lookupInteger(ENUM_2);
+ assertNull(result);
+ }
+
+ /**
+ * Run the StringDefinition lookupString(String) method test.
+ */
+ @Test
+ public void testLookupString() {
+ StringDefinition result = fixture.lookupString(ENUM_1);
+ assertNull(result);
+ }
+
+ /**
+ * Run the StructDefinition lookupStruct(String) method test.
+ */
+ @Test
+ public void testLookupStruct() {
+ StructDefinition result = fixture.lookupStruct(ENUM_6);
+ assertNull(result);
+ }
+
+ /**
+ * Run the VariantDefinition lookupVariant(String) method test.
+ */
+ @Test
+ public void testLookupVariant() {
+ VariantDefinition result = fixture.lookupVariant(ENUM_8);
+ assertNull(result);
+ }
+
+ /**
+ * Run the String toString() method test.
+ */
+ @Test
+ public void testToString() {
+ String result = fixture.toString();
+ assertEquals("{ a = \"\" }", result);
+ }
+}
Bundle-Version: 3.2.0.qualifier
Bundle-Localization: plugin
Bundle-SymbolicName: org.eclipse.tracecompass.ctf.core;singleton:=true
-Bundle-Activator: org.eclipse.linuxtools.internal.ctf.core.Activator
+Bundle-Activator: org.eclipse.tracecompass.internal.ctf.core.Activator
Bundle-ActivationPolicy: lazy
Bundle-RequiredExecutionEnvironment: JavaSE-1.7
Require-Bundle: org.eclipse.core.runtime,
org.eclipse.tracecompass.ctf.parser;bundle-version="3.1.0"
-Export-Package: org.eclipse.linuxtools.ctf.core,
- org.eclipse.linuxtools.ctf.core.event,
- org.eclipse.linuxtools.ctf.core.event.io,
- org.eclipse.linuxtools.ctf.core.event.scope,
- org.eclipse.linuxtools.ctf.core.event.types,
- org.eclipse.linuxtools.ctf.core.trace,
- org.eclipse.linuxtools.internal.ctf.core;x-friends:="org.eclipse.tracecompass.ctf.core.tests",
- org.eclipse.linuxtools.internal.ctf.core.event;x-friends:="org.eclipse.tracecompass.ctf.core.tests",
- org.eclipse.linuxtools.internal.ctf.core.event.metadata;x-friends:="org.eclipse.tracecompass.ctf.core.tests",
- org.eclipse.linuxtools.internal.ctf.core.event.metadata.exceptions;x-friends:="org.eclipse.tracecompass.ctf.core.tests",
- org.eclipse.linuxtools.internal.ctf.core.event.types;x-friends:="org.eclipse.tracecompass.ctf.core.tests,org.eclipse.tracecompass.tmf.ctf.core,org.eclipse.tracecompass.tmf.ctf.core.tests",
- org.eclipse.linuxtools.internal.ctf.core.event.types.composite;x-friends:="org.eclipse.tracecompass.ctf.core.tests",
- org.eclipse.linuxtools.internal.ctf.core.trace;x-friends:="org.eclipse.tracecompass.ctf.core.tests"
+Export-Package: org.eclipse.tracecompass.ctf.core,
+ org.eclipse.tracecompass.ctf.core.event,
+ org.eclipse.tracecompass.ctf.core.event.io,
+ org.eclipse.tracecompass.ctf.core.event.scope,
+ org.eclipse.tracecompass.ctf.core.event.types,
+ org.eclipse.tracecompass.ctf.core.trace,
+ org.eclipse.tracecompass.internal.ctf.core;x-friends:="org.eclipse.tracecompass.ctf.core.tests",
+ org.eclipse.tracecompass.internal.ctf.core.event;x-friends:="org.eclipse.tracecompass.ctf.core.tests",
+ org.eclipse.tracecompass.internal.ctf.core.event.metadata;x-friends:="org.eclipse.tracecompass.ctf.core.tests",
+ org.eclipse.tracecompass.internal.ctf.core.event.metadata.exceptions;x-friends:="org.eclipse.tracecompass.ctf.core.tests",
+ org.eclipse.tracecompass.internal.ctf.core.event.types;x-friends:="org.eclipse.tracecompass.ctf.core.tests,org.eclipse.tracecompass.tmf.ctf.core,org.eclipse.tracecompass.tmf.ctf.core.tests",
+ org.eclipse.tracecompass.internal.ctf.core.event.types.composite;x-friends:="org.eclipse.tracecompass.ctf.core.tests",
+ org.eclipse.tracecompass.internal.ctf.core.trace;x-friends:="org.eclipse.tracecompass.ctf.core.tests"
Import-Package: com.google.common.base,
com.google.common.collect,
org.antlr.runtime;version="3.2.0",
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Alexandre Montplaisir - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core;
-
-import org.eclipse.jdt.annotation.NonNullByDefault;
-
-/**
- * Non-externalized strings for use with the CTF plugin (event names, field
- * names, etc.)
- *
- * @author Alexandre Montplaisir
- * @since 2.2
- */
-@SuppressWarnings("nls")
-@NonNullByDefault
-public interface CTFStrings {
-
- /** Event name for lost events */
- static final String LOST_EVENT_NAME = "Lost event";
-
- /**
- * Name of the field in lost events indicating how many actual events were
- * lost
- */
- static final String LOST_EVENTS_FIELD = "Lost events";
-
- /**
- * Name of the field in lost events indicating the time range
- */
- static final String LOST_EVENTS_DURATION = "duration";
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2012, 2013 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event;
-
-/**
- * Callsite information to help with cdt integration
- *
- * @author Matthew Khouzam
- *
- * @since 1.2
- */
-public class CTFCallsite implements Comparable<CTFCallsite> {
-
- private static final long MASK32 = 0x00000000ffffffffL;
-
- /**
- * The event name
- */
- private final String fEventName;
-
- /**
- * the file name of the callsite
- */
- private final String fFileName;
-
- /**
- * the instruction pointer
- */
- private final long fIp;
-
- /**
- * the function name
- */
- private final String fFunctionName;
-
- /**
- * the line number of the callsite
- */
- private final long fLineNumber;
-
- /**
- * The callsite constructor
- *
- * @param en
- * The event name
- * @param func
- * the function name
- * @param ip
- * the instruction pointer of the callsite
- * @param fn
- * the file name of the callsite
- * @param line
- * the line number of the callsite
- */
- public CTFCallsite(String en, String func, long ip, String fn, long line) {
- fEventName = en;
- fFileName = fn;
- fFunctionName = func;
- fIp = ip;
- fLineNumber = line;
- }
-
- /**
- * @return the eventName
- */
- public String getEventName() {
- return fEventName;
- }
-
- /**
- * @return the fileName
- */
- public String getFileName() {
- return fFileName;
- }
-
- /**
- * @return the ip
- */
- public long getIp() {
- return fIp;
- }
-
- /**
- * @return the functionName
- */
- public String getFunctionName() {
- return fFunctionName;
- }
-
- /**
- * @return the lineNumber
- */
- public long getLineNumber() {
- return fLineNumber;
- }
-
- /*
- * The callsites will be sorted by calling addresses. To do this we take IPs
- * (instruction pointers) and compare them. Java only supports signed
- * operation and since memory addresses are unsigned, we will convert the
- * longs into integers that contain the high and low bytes and compare them.
- */
- @Override
- public int compareTo(CTFCallsite o) {
- /*
- * mask32 is 32 zeros followed by 32 ones, when we bitwise and this it
- * will return the lower 32 bits
- */
-
- long other = o.fIp;
- /*
- * To get a high int: we downshift by 32 and bitwise and with the mask
- * to get rid of the sign
- *
- * To get the low int: we bitwise and with the mask.
- */
- long otherHigh = (other >> 32) & MASK32;
- long otherLow = other & MASK32;
- long ownHigh = (fIp >> 32) & MASK32;
- long ownLow = fIp & MASK32;
- /* are the high values different, if so ignore the lower values */
- if (ownHigh > otherHigh) {
- return 1;
- }
- if (ownHigh < otherHigh ) {
- return -1;
- }
- /* the high values are the same, compare the lower values */
- if (ownLow > otherLow) {
- return 1;
- }
- if (ownLow < otherLow) {
- return -1;
- }
- /* the values are identical */
- return 0;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((fEventName == null) ? 0 : fEventName.hashCode());
- result = prime * result + ((fFileName == null) ? 0 : fFileName.hashCode());
- result = prime * result + ((fFunctionName == null) ? 0 : fFunctionName.hashCode());
- result = prime * result + (int) (fIp ^ (fIp >>> 32));
- result = prime * result + (int) (fLineNumber ^ (fLineNumber >>> 32));
- return result;
- }
-
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- CTFCallsite other = (CTFCallsite) obj;
- if (fEventName == null) {
- if (other.fEventName != null) {
- return false;
- }
- } else if (!fEventName.equals(other.fEventName)) {
- return false;
- }
- if (fFileName == null) {
- if (other.fFileName != null) {
- return false;
- }
- } else if (!fFileName.equals(other.fFileName)) {
- return false;
- }
- if (fFunctionName == null) {
- if (other.fFunctionName != null) {
- return false;
- }
- } else if (!fFunctionName.equals(other.fFunctionName)) {
- return false;
- }
- if (fIp != other.fIp) {
- return false;
- }
- if (fLineNumber != other.fLineNumber) {
- return false;
- }
- return true;
- }
-
- @Override
- public String toString() {
- return fFileName + "/" + fFunctionName + ":" + fLineNumber; //$NON-NLS-1$ //$NON-NLS-2$
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Clock description used in CTF traces
- */
-public class CTFClock {
-
- private static final long ONE_BILLION_L = 1000000000L;
- private static final double ONE_BILLION_D = 1000000000.0;
-
- private static final String NAME = "name"; //$NON-NLS-1$
- private static final String FREQ = "freq"; //$NON-NLS-1$
- private static final String OFFSET = "offset"; //$NON-NLS-1$
-
- private long fClockOffset = 0;
- private double fClockScale = 1.0;
- private double fClockAntiScale = 1.0;
-
- /**
- * Field properties.
- */
- private final Map<String, Object> fProperties = new HashMap<>();
- /**
- * Field name.
- */
- private String fName;
- private boolean fIsScaled = false;
-
- /**
- * Default constructor
- */
- public CTFClock() {
- }
-
- /**
- * Method addAttribute.
- *
- * @param key
- * String
- * @param value
- * Object
- */
- public void addAttribute(String key, Object value) {
- fProperties.put(key, value);
- if (key.equals(NAME)) {
- fName = (String) value;
- }
- if (key.equals(FREQ)) {
- /*
- * Long is converted to a double. the double is then dividing
- * another double that double is saved. this is precise as long as
- * the long is under 53 bits long. this is ok as long as we don't
- * have a system with a frequency of > 1 600 000 000 GHz with
- * 200 ppm precision
- */
- fIsScaled = !((Long) getProperty(FREQ)).equals(ONE_BILLION_L);
- fClockScale = ONE_BILLION_D / ((Long) getProperty(FREQ)).doubleValue();
- fClockAntiScale = 1.0 / fClockScale;
-
- }
- if (key.equals(OFFSET)) {
- fClockOffset = (Long) getProperty(OFFSET);
- }
- }
-
- /**
- * Method getName.
- *
- * @return String
- */
- public String getName() {
- return fName;
- }
-
- /**
- * Method getProperty.
- *
- * @param key
- * String
- * @return Object
- */
- public Object getProperty(String key) {
- return fProperties.get(key);
- }
-
- /**
- * @return the clockOffset
- * @since 2.0
- */
- public long getClockOffset() {
- return fClockOffset;
- }
-
- /**
- * @return the clockScale
- * @since 2.0
- */
- public double getClockScale() {
- return fClockScale;
- }
-
- /**
- * @return the clockAntiScale
- * @since 2.0
- */
- public double getClockAntiScale() {
- return fClockAntiScale;
- }
-
- /**
- * @return is the clock in ns or cycles?
- * @since 2.0
- */
- public boolean isClockScaled() {
- return fIsScaled;
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011-2013 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.event.scope.LexicalScope;
-import org.eclipse.linuxtools.ctf.core.event.types.Definition;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDefinition;
-import org.eclipse.linuxtools.ctf.core.trace.CTFStreamInputReader;
-import org.eclipse.linuxtools.internal.ctf.core.event.EventDeclaration;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableList.Builder;
-
-/**
- * Representation of a particular instance of an event.
- */
-public final class EventDefinition implements IDefinitionScope {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- /**
- * A null event, can be used for testing or poison pilling
- *
- * @since 3.0
- */
- @NonNull
- public static final EventDefinition NULL_EVENT = new EventDefinition(new EventDeclaration(), null, -1L, null, null, null, null);
-
- /**
- * The corresponding event declaration.
- */
- private final IEventDeclaration fDeclaration;
-
- /**
- * The timestamp of the current event.
- */
- private final long fTimestamp;
-
- /**
- * The event context structure definition.
- */
- private final StructDefinition fEventContext;
-
- private final StructDefinition fStreamContext;
-
- private final StructDefinition fPacketContext;
-
- /**
- * The event fields structure definition.
- */
- private final StructDefinition fFields;
-
- /**
- * The StreamInputReader that reads this event definition.
- */
- private final CTFStreamInputReader fStreamInputReader;
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Constructs an event definition.
- *
- * @param declaration
- * The corresponding event declaration
- * @param streamInputReader
- * The SIR from where this EventDef was read
- * @param timestamp
- * event timestamp
- * @param eventContext
- * The event context
- * @param packetContext
- * the packet context
- * @param streamContext
- * the stream context
- * @param fields
- * The event fields
- * @since 3.0
- */
- public EventDefinition(IEventDeclaration declaration,
- CTFStreamInputReader streamInputReader,
- long timestamp,
- StructDefinition streamContext,
- StructDefinition eventContext,
- StructDefinition packetContext,
- StructDefinition fields) {
- fDeclaration = declaration;
- fStreamInputReader = streamInputReader;
- fTimestamp = timestamp;
- fFields = fields;
- fEventContext = eventContext;
- fPacketContext = packetContext;
- fStreamContext = streamContext;
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- /**
- * @since 3.0
- */
- @Override
- public LexicalScope getScopePath() {
- String eventName = fDeclaration.getName();
- if (eventName == null) {
- return null;
- }
- LexicalScope myScope = LexicalScope.EVENT.getChild(eventName);
- if (myScope == null) {
- myScope = new LexicalScope(LexicalScope.EVENT, eventName);
- }
- return myScope;
- }
-
- /**
- * Gets the declaration (the form) of the data
- *
- * @return the event declaration
- * @since 2.0
- */
- public IEventDeclaration getDeclaration() {
- return fDeclaration;
- }
-
- /**
- * Gets the fields of a definition
- *
- * @return the fields of a definition in struct form. Can be null.
- */
- public StructDefinition getFields() {
- return fFields;
- }
-
- /**
- * Gets the context of this event without the context of the stream
- *
- * @return the context in struct form
- * @since 1.2
- */
- public StructDefinition getEventContext() {
- return fEventContext;
- }
-
- /**
- * Gets the context of this event within a stream
- *
- * @return the context in struct form
- */
- public StructDefinition getContext() {
-
- /* Most common case so far */
- if (fStreamContext == null) {
- return fEventContext;
- }
-
- /* streamContext is not null, but the context of the event is null */
- if (fEventContext == null) {
- return fStreamContext;
- }
-
- // TODO: cache if this is a performance issue
-
- /* The stream context and event context are assigned. */
- StructDeclaration mergedDeclaration = new StructDeclaration(1);
-
- Builder<String> builder = ImmutableList.<String> builder();
- List<Definition> fieldValues = new ArrayList<>();
-
- /* Add fields from the stream */
- for (String fieldName : fStreamContext.getFieldNames()) {
- Definition definition = fStreamContext.getDefinition(fieldName);
- mergedDeclaration.addField(fieldName, definition.getDeclaration());
- builder.add(fieldName);
- fieldValues.add(definition);
- }
-
- ImmutableList<String> fieldNames = builder.build();
- /*
- * Add fields from the event context, overwrite the stream ones if
- * needed.
- */
- for (String fieldName : fEventContext.getFieldNames()) {
- Definition definition = fEventContext.getDefinition(fieldName);
- mergedDeclaration.addField(fieldName, definition.getDeclaration());
- if (fieldNames.contains(fieldName)) {
- fieldValues.set((fieldNames.indexOf(fieldName)), definition);
- } else {
- builder.add(fieldName);
- fieldValues.add(definition);
- }
- }
- fieldNames = builder.build();
- StructDefinition mergedContext = new StructDefinition(mergedDeclaration, this, "context", //$NON-NLS-1$
- fieldNames,
- fieldValues.toArray(new Definition[fieldValues.size()]));
- return mergedContext;
- }
-
- /**
- * Gets the stream input reader that this event was made by
- *
- * @return the parent
- * @since 3.0
- */
- public CTFStreamInputReader getStreamInputReader() {
- return fStreamInputReader;
- }
-
- /**
- * Gets the context of packet the event is in.
- *
- * @return the packet context
- */
- public StructDefinition getPacketContext() {
- return fPacketContext;
- }
-
- /**
- * gets the CPU the event was generated by. Slightly LTTng specific
- *
- * @return The CPU the event was generated by
- */
- public int getCPU() {
- return fStreamInputReader.getCPU();
- }
-
- /**
- * @return the timestamp
- */
- public long getTimestamp() {
- return fTimestamp;
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- @Override
- public Definition lookupDefinition(String lookupPath) {
- if (lookupPath.equals("context")) { //$NON-NLS-1$
- return fEventContext;
- } else if (lookupPath.equals("fields")) { //$NON-NLS-1$
- return fFields;
- } else {
- return null;
- }
- }
-
- @Override
- public String toString() {
- Iterable<String> list;
- StringBuilder retString = new StringBuilder();
- final String cr = System.getProperty("line.separator");//$NON-NLS-1$
-
- retString.append("Event type: " + fDeclaration.getName() + cr); //$NON-NLS-1$
- retString.append("Timestamp: " + Long.toString(fTimestamp) + cr); //$NON-NLS-1$
-
- if (fEventContext != null) {
- list = fEventContext.getDeclaration().getFieldsList();
-
- for (String field : list) {
- retString.append(field
- + " : " + fEventContext.getDefinition(field).toString() + cr); //$NON-NLS-1$
- }
- }
-
- if (fFields != null) {
- list = fFields.getDeclaration().getFieldsList();
-
- for (String field : list) {
- retString.append(field
- + " : " + fFields.getDefinition(field).toString() + cr); //$NON-NLS-1$
- }
- }
-
- return retString.toString();
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011-2013 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event;
-
-import java.util.Set;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.ctf.core.trace.CTFStream;
-import org.eclipse.linuxtools.ctf.core.trace.CTFStreamInputReader;
-
-/**
- * Representation of one type of event. A bit like "int" or "long" but for trace
- * events.
- *
- * @author Matthew Khouzam
- * @since 2.0
- */
-public interface IEventDeclaration {
-
- /**
- * Creates an instance of EventDefinition corresponding to this declaration.
- *
- * @param streamInputReader
- * The StreamInputReader for which this definition is created.
- * @param input
- * the bitbuffer input source
- * @param timestamp
- * The timestamp when the event was taken
- * @return A new EventDefinition.
- * @throws CTFReaderException
- * As a bitbuffer is used to read, it could have wrapped
- * IOExceptions.
- * @since 3.0
- */
- EventDefinition createDefinition(CTFStreamInputReader streamInputReader, @NonNull BitBuffer input, long timestamp) throws CTFReaderException;
-
- /**
- * Gets the name of an event declaration
- *
- * @return the name
- */
- String getName();
-
- /**
- * Gets the fields of an event declaration
- *
- * @return fields the fields in {@link StructDeclaration} format
- */
- StructDeclaration getFields();
-
- /**
- * Gets the context of an event declaration
- *
- * @return context the fields in {@link StructDeclaration} format
- */
- StructDeclaration getContext();
-
- /**
- * Gets the id of an event declaration
- *
- * @return The EventDeclaration ID
- */
- Long getId();
-
- /**
- * Gets the {@link CTFStream} of an event declaration
- *
- * @return the stream
- * @since 3.0
- */
- CTFStream getStream();
-
- /**
- * What is the log level of this event?
- *
- * @return the log level.
- * @since 2.0
- */
- long getLogLevel();
-
- /**
- * Get the {@link Set} of names of the custom CTF attributes.
- *
- * @return The set of custom attributes
- * @since 2.0
- */
- Set<String> getCustomAttributes();
-
- /**
- * Get the value of a given CTF attribute.
- *
- * @param key
- * The CTF attribute name
- * @return the CTF attribute
- * @since 2.0
- */
- String getCustomAttribute(String key);
-
-}
+++ /dev/null
-/*******************************************************************************.
- * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial Design and implementation + overhaul
- * Francis Giraldeau - Initial API and implementation
- * Philippe Proulx - Some refinement and optimization
- * Etienne Bergeron <Etienne.Bergeron@gmail.com> - fix zero size read + cleanup
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.io;
-
-import java.nio.BufferUnderflowException;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-
-/**
- * <b><u>BitBuffer</u></b>
- * <p>
- * A bitwise buffer capable of accessing fields with bit offsets.
- *
- * @since 2.0
- */
-public final class BitBuffer {
-
- // ------------------------------------------------------------------------
- // Constants
- // ------------------------------------------------------------------------
-
- /* default bit width */
- /** 8 bits to a char */
- public static final int BIT_CHAR = 8;
- /** 16 bits to a short */
- public static final int BIT_SHORT = 16;
- /** 32 bits to an int */
- public static final int BIT_INT = 32;
- /** 32 bits to a float */
- public static final int BIT_FLOAT = 32;
- /** 64 bits to a long */
- public static final int BIT_LONG = 64;
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- private final @NonNull ByteBuffer fBuffer;
- private final long fBitCapacity;
-
- /**
- * Bit-buffer's position, maximum value = Integer.MAX_VALUE * 8
- */
- private long fPosition;
- private ByteOrder fByteOrder;
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
- /**
- * Default constructor, makes a big-endian buffer
- */
- @SuppressWarnings("null")
- public BitBuffer() {
- this(ByteBuffer.allocateDirect(0), ByteOrder.BIG_ENDIAN);
- }
-
- /**
- * Constructor, makes a big-endian buffer
- *
- * @param buf
- * the bytebuffer to read
- */
- public BitBuffer(@NonNull ByteBuffer buf) {
- this(buf, ByteOrder.BIG_ENDIAN);
- }
-
- /**
- * Constructor that is fully parameterizable
- *
- * @param buf
- * the buffer to read
- * @param order
- * the byte order (big-endian, little-endian, network?)
- */
- public BitBuffer(@NonNull ByteBuffer buf, ByteOrder order) {
- fBuffer = buf;
- setByteOrder(order);
- resetPosition();
- fBitCapacity = fBuffer.capacity() * BIT_CHAR;
- }
-
- private void resetPosition() {
- fPosition = 0;
- }
-
- // ------------------------------------------------------------------------
- // 'Get' operations on buffer
- // ------------------------------------------------------------------------
-
- /**
- * Relative <i>get</i> method for reading 32-bit integer.
- *
- * Reads next four bytes from the current bit position according to current
- * byte order.
- *
- * @return The int value (signed) read from the buffer
- * @throws CTFReaderException
- * An error occurred reading the long. This exception can be
- * raised if the buffer tries to read out of bounds
- */
- public int getInt() throws CTFReaderException {
- return getInt(BIT_INT, true);
- }
-
- /**
- * Relative <i>get</i> method for reading 64-bit integer.
- *
- * Reads next eight bytes from the current bit position according to current
- * byte order.
- *
- * @return The long value (signed) read from the buffer
- * @throws CTFReaderException
- * An error occurred reading the long. This exception can be
- * raised if the buffer tries to read out of bounds
- * @since 3.0
- */
- public long getLong() throws CTFReaderException {
- return get(BIT_LONG, true);
- }
-
- /**
- * Relative <i>get</i> method for reading long of <i>length</i> bits.
- *
- * Reads <i>length</i> bits starting at the current position. The result is
- * signed extended if <i>signed</i> is true. The current position is
- * increased of <i>length</i> bits.
- *
- * @param length
- * The length in bits of this integer
- * @param signed
- * The sign extended flag
- * @return The long value read from the buffer
- * @throws CTFReaderException
- * An error occurred reading the data. If more than 64 bits at a
- * time are read, or the buffer is read beyond its end, this
- * exception will be raised.
- * @since 3.0
- */
- public long get(int length, boolean signed) throws CTFReaderException {
- if (length > BIT_LONG) {
- throw new CTFReaderException("Cannot read a long longer than 64 bits. Rquested: " + length); //$NON-NLS-1$
- }
- if (length > BIT_INT) {
- final int highShift = length - BIT_INT;
- long a = getInt();
- long b = getInt(highShift, false);
- long retVal;
- /* Cast the signed-extended int into a unsigned int. */
- a &= 0xFFFFFFFFL;
- b &= (1L << highShift) - 1L;
-
- retVal = (fByteOrder == ByteOrder.BIG_ENDIAN) ? ((a << highShift) | b) : ((b << BIT_INT) | a);
- /* sign extend */
- if (signed) {
- int signExtendBits = BIT_LONG - length;
- retVal = (retVal << signExtendBits) >> signExtendBits;
- }
- return retVal;
- }
- long retVal = getInt(length, signed);
- return (signed ? retVal : (retVal & 0xFFFFFFFFL));
- }
-
- /**
- * Relative bulk <i>get</i> method.
- *
- * <p>
- * This method transfers <strong>bytes</strong> from this buffer into the
- * given destination array. This method currently only supports reads
- * aligned to 8 bytes. It is up to the developer to shift the bits in
- * post-processing to do unaligned reads.
- *
- * @param dst
- * the bytes to write to
- * @throws BufferUnderflowException
- * - If there are fewer than length bytes remaining in this
- * buffer
- * @since 3.1
- */
- public void get(@NonNull byte[] dst) {
- fBuffer.position((int) (fPosition / 8));
- fBuffer.get(dst);
- fPosition += dst.length * 8;
- }
-
- /**
- * Relative <i>get</i> method for reading integer of <i>length</i> bits.
- *
- * Reads <i>length</i> bits starting at the current position. The result is
- * signed extended if <i>signed</i> is true. The current position is
- * increased of <i>length</i> bits.
- *
- * @param length
- * The length in bits of this integer
- * @param signed
- * The sign extended flag
- * @return The int value read from the buffer
- * @throws CTFReaderException
- * An error occurred reading the data. When the buffer is read
- * beyond its end, this exception will be raised.
- */
- private int getInt(int length, boolean signed) throws CTFReaderException {
-
- /* Nothing to read. */
- if (length == 0) {
- return 0;
- }
-
- /* Validate that the buffer has enough bits. */
- if (!canRead(length)) {
- throw new CTFReaderException("Cannot read the integer, " + //$NON-NLS-1$
- "the buffer does not have enough remaining space. " + //$NON-NLS-1$
- "Requested:" + length); //$NON-NLS-1$
- }
-
- /* Get the value from the byte buffer. */
- int val = 0;
- boolean gotIt = false;
-
- /*
- * Try a fast read when the position is byte-aligned by using
- * java.nio.ByteBuffer's native methods
- */
- /*
- * A faster alignment detection as the compiler cannot guaranty that pos
- * is always positive.
- */
- if ((fPosition & (BitBuffer.BIT_CHAR - 1)) == 0) {
- switch (length) {
- case BitBuffer.BIT_CHAR:
- // Byte
- val = fBuffer.get((int) (fPosition / 8));
- if (!signed) {
- val = val & 0xff;
- }
- gotIt = true;
- break;
-
- case BitBuffer.BIT_SHORT:
- // Word
- val = fBuffer.getShort((int) (fPosition / 8));
- if (!signed) {
- val = val & 0xffff;
- }
- gotIt = true;
- break;
-
- case BitBuffer.BIT_INT:
- // Double word
- val = fBuffer.getInt((int) (fPosition / 8));
- gotIt = true;
- break;
-
- default:
- break;
- }
- }
-
- /* When not byte-aligned, fall-back to a general decoder. */
- if (!gotIt) {
- // Nothing read yet: use longer methods
- if (fByteOrder == ByteOrder.LITTLE_ENDIAN) {
- val = getIntLE(fPosition, length, signed);
- } else {
- val = getIntBE(fPosition, length, signed);
- }
- }
- fPosition += length;
-
- return val;
- }
-
- private int getIntBE(long index, int length, boolean signed) {
- if ((length <= 0) || (length > BIT_INT)) {
- throw new IllegalArgumentException("Length must be between 1-32 bits"); //$NON-NLS-1$
- }
- long end = index + length;
- int startByte = (int) (index / BIT_CHAR);
- int endByte = (int) ((end + (BIT_CHAR - 1)) / BIT_CHAR);
- int currByte, lshift, cshift, mask, cmask, cache;
- int value = 0;
-
- currByte = startByte;
- cache = fBuffer.get(currByte) & 0xFF;
- boolean isNeg = (cache & (1 << (BIT_CHAR - (index % BIT_CHAR) - 1))) != 0;
- if (signed && isNeg) {
- value = ~0;
- }
- if (startByte == (endByte - 1)) {
- cmask = cache >>> ((BIT_CHAR - (end % BIT_CHAR)) % BIT_CHAR);
- if (((length) % BIT_CHAR) > 0) {
- mask = ~((~0) << length);
- cmask &= mask;
- }
- value <<= length;
- value |= cmask;
- return value;
- }
- cshift = (int) (index % BIT_CHAR);
- if (cshift > 0) {
- mask = ~((~0) << (BIT_CHAR - cshift));
- cmask = cache & mask;
- lshift = BIT_CHAR - cshift;
- value <<= lshift;
- value |= cmask;
- currByte++;
- }
- for (; currByte < (endByte - 1); currByte++) {
- value <<= BIT_CHAR;
- value |= fBuffer.get(currByte) & 0xFF;
- }
- lshift = (int) (end % BIT_CHAR);
- if (lshift > 0) {
- mask = ~((~0) << lshift);
- cmask = fBuffer.get(currByte) & 0xFF;
- cmask >>>= BIT_CHAR - lshift;
- cmask &= mask;
- value <<= lshift;
- value |= cmask;
- } else {
- value <<= BIT_CHAR;
- value |= fBuffer.get(currByte) & 0xFF;
- }
- return value;
- }
-
- private int getIntLE(long index, int length, boolean signed) {
- if ((length <= 0) || (length > BIT_INT)) {
- throw new IllegalArgumentException("Length must be between 1-32 bits"); //$NON-NLS-1$
- }
- long end = index + length;
- int startByte = (int) (index / BIT_CHAR);
- int endByte = (int) ((end + (BIT_CHAR - 1)) / BIT_CHAR);
- int currByte, lshift, cshift, mask, cmask, cache, mod;
- int value = 0;
-
- currByte = endByte - 1;
- cache = fBuffer.get(currByte) & 0xFF;
- mod = (int) (end % BIT_CHAR);
- lshift = (mod > 0) ? mod : BIT_CHAR;
- boolean isNeg = (cache & (1 << (lshift - 1))) != 0;
- if (signed && isNeg) {
- value = ~0;
- }
- if (startByte == (endByte - 1)) {
- cmask = cache >>> (index % BIT_CHAR);
- if (((length) % BIT_CHAR) > 0) {
- mask = ~((~0) << length);
- cmask &= mask;
- }
- value <<= length;
- value |= cmask;
- return value;
- }
- cshift = (int) (end % BIT_CHAR);
- if (cshift > 0) {
- mask = ~((~0) << cshift);
- cmask = cache & mask;
- value <<= cshift;
- value |= cmask;
- currByte--;
- }
- for (; currByte >= (startByte + 1); currByte--) {
- value <<= BIT_CHAR;
- value |= fBuffer.get(currByte) & 0xFF;
- }
- lshift = (int) (index % BIT_CHAR);
- if (lshift > 0) {
- mask = ~((~0) << (BIT_CHAR - lshift));
- cmask = fBuffer.get(currByte) & 0xFF;
- cmask >>>= lshift;
- cmask &= mask;
- value <<= (BIT_CHAR - lshift);
- value |= cmask;
- } else {
- value <<= BIT_CHAR;
- value |= fBuffer.get(currByte) & 0xFF;
- }
- return value;
- }
-
- // ------------------------------------------------------------------------
- // 'Put' operations on buffer
- // ------------------------------------------------------------------------
-
- /**
- * Relative <i>put</i> method to write signed 32-bit integer.
- *
- * Write four bytes starting from current bit position in the buffer
- * according to the current byte order. The current position is increased of
- * <i>length</i> bits.
- *
- * @param value
- * The int value to write
- * @throws CTFReaderException
- * An error occurred writing the data. If the buffer is written
- * beyond its end, this exception will be raised.
- */
- public void putInt(int value) throws CTFReaderException {
- putInt(BIT_INT, value);
- }
-
- /**
- * Relative <i>put</i> method to write <i>length</i> bits integer.
- *
- * Writes <i>length</i> lower-order bits from the provided <i>value</i>,
- * starting from current bit position in the buffer. Sequential bytes are
- * written according to the current byte order. The sign bit is carried to
- * the MSB if signed is true. The sign bit is included in <i>length</i>. The
- * current position is increased of <i>length</i>.
- *
- * @param length
- * The number of bits to write
- * @param value
- * The value to write
- * @throws CTFReaderException
- * An error occurred writing the data. If the buffer is written
- * beyond its end, this exception will be raised.
- */
- public void putInt(int length, int value) throws CTFReaderException {
- final long curPos = fPosition;
-
- if (!canRead(length)) {
- throw new CTFReaderException("Cannot write to bitbuffer, " //$NON-NLS-1$
- + "insufficient space. Requested: " + length); //$NON-NLS-1$
- }
- if (length == 0) {
- return;
- }
- if (fByteOrder == ByteOrder.LITTLE_ENDIAN) {
- putIntLE(curPos, length, value);
- } else {
- putIntBE(curPos, length, value);
- }
- fPosition += length;
- }
-
- private void putIntBE(long index, int length, int value) {
- if ((length <= 0) || (length > BIT_INT)) {
- throw new IllegalArgumentException("Length must be between 1-32 bits"); //$NON-NLS-1$
- }
- long end = index + length;
- int startByte = (int) (index / BIT_CHAR);
- int endByte = (int) ((end + (BIT_CHAR - 1)) / BIT_CHAR);
- int currByte, lshift, cshift, mask, cmask;
- int correctedValue = value;
-
- /*
- * mask v high bits. Works for unsigned and two complement signed
- * numbers which value do not overflow on length bits.
- */
-
- if (length < BIT_INT) {
- correctedValue &= ~(~0 << length);
- }
-
- /* sub byte */
- if (startByte == (endByte - 1)) {
- lshift = (int) ((BIT_CHAR - (end % BIT_CHAR)) % BIT_CHAR);
- mask = ~((~0) << lshift);
- if ((index % BIT_CHAR) > 0) {
- mask |= (~(0)) << (BIT_CHAR - (index % BIT_CHAR));
- }
- cmask = correctedValue << lshift;
- /*
- * low bits are cleared because of left-shift and high bits are
- * already cleared
- */
- cmask &= ~mask;
- int b = fBuffer.get(startByte) & 0xFF;
- fBuffer.put(startByte, (byte) ((b & mask) | cmask));
- return;
- }
-
- /* head byte contains MSB */
- currByte = endByte - 1;
- cshift = (int) (end % BIT_CHAR);
- if (cshift > 0) {
- lshift = BIT_CHAR - cshift;
- mask = ~((~0) << lshift);
- cmask = correctedValue << lshift;
- cmask &= ~mask;
- int b = fBuffer.get(currByte) & 0xFF;
- fBuffer.put(currByte, (byte) ((b & mask) | cmask));
- correctedValue >>>= cshift;
- currByte--;
- }
-
- /* middle byte(s) */
- for (; currByte >= (startByte + 1); currByte--) {
- fBuffer.put(currByte, (byte) correctedValue);
- correctedValue >>>= BIT_CHAR;
- }
- /* end byte contains LSB */
- if ((index % BIT_CHAR) > 0) {
- mask = (~0) << (BIT_CHAR - (index % BIT_CHAR));
- cmask = correctedValue & ~mask;
- int b = fBuffer.get(currByte) & 0xFF;
- fBuffer.put(currByte, (byte) ((b & mask) | cmask));
- } else {
- fBuffer.put(currByte, (byte) correctedValue);
- }
- }
-
- private void putIntLE(long index, int length, int value) {
- if ((length <= 0) || (length > BIT_INT)) {
- throw new IllegalArgumentException("Length must be between 1-32 bits"); //$NON-NLS-1$
- }
- long end = index + length;
- int startByte = (int) (index / BIT_CHAR);
- int endByte = (int) ((end + (BIT_CHAR - 1)) / BIT_CHAR);
- int currByte, lshift, cshift, mask, cmask;
- int correctedValue = value;
-
- /*
- * mask v high bits. Works for unsigned and two complement signed
- * numbers which value do not overflow on length bits.
- */
-
- if (length < BIT_INT) {
- correctedValue &= ~(~0 << length);
- }
-
- /* sub byte */
- if (startByte == (endByte - 1)) {
- lshift = (int) (index % BIT_CHAR);
- mask = ~((~0) << lshift);
- if ((end % BIT_CHAR) > 0) {
- mask |= (~(0)) << (end % BIT_CHAR);
- }
- cmask = correctedValue << lshift;
- /*
- * low bits are cleared because of left-shift and high bits are
- * already cleared
- */
- cmask &= ~mask;
- int b = fBuffer.get(startByte) & 0xFF;
- fBuffer.put(startByte, (byte) ((b & mask) | cmask));
- return;
- }
-
- /* head byte */
- currByte = startByte;
- cshift = (int) (index % BIT_CHAR);
- if (cshift > 0) {
- mask = ~((~0) << cshift);
- cmask = correctedValue << cshift;
- cmask &= ~mask;
- int b = fBuffer.get(currByte) & 0xFF;
- fBuffer.put(currByte, (byte) ((b & mask) | cmask));
- correctedValue >>>= BIT_CHAR - cshift;
- currByte++;
- }
-
- /* middle byte(s) */
- for (; currByte < (endByte - 1); currByte++) {
- fBuffer.put(currByte, (byte) correctedValue);
- correctedValue >>>= BIT_CHAR;
- }
- /* end byte */
- if ((end % BIT_CHAR) > 0) {
- mask = (~0) << (end % BIT_CHAR);
- cmask = correctedValue & ~mask;
- int b = fBuffer.get(currByte) & 0xFF;
- fBuffer.put(currByte, (byte) ((b & mask) | cmask));
- } else {
- fBuffer.put(currByte, (byte) correctedValue);
- }
- }
-
- // ------------------------------------------------------------------------
- // Buffer attributes handling
- // ------------------------------------------------------------------------
-
- /**
- * Can this buffer be read for thus amount of bits?
- *
- * @param length
- * the length in bits to read
- * @return does the buffer have enough room to read the next "length"
- */
- public boolean canRead(int length) {
- return ((fPosition + length) <= fBitCapacity);
- }
-
- /**
- * Sets the order of the buffer.
- *
- * @param order
- * The order of the buffer.
- */
- public void setByteOrder(ByteOrder order) {
- fByteOrder = order;
- fBuffer.order(order);
- }
-
- /**
- * Sets the order of the buffer.
- *
- * @return The order of the buffer.
- */
- public ByteOrder getByteOrder() {
- return fByteOrder;
- }
-
- /**
- * Sets the position in the buffer.
- *
- * @param newPosition
- * The new position of the buffer.
- * @throws CTFReaderException
- * Thrown on out of bounds exceptions
- * @since 3.0
- */
- public void position(long newPosition) throws CTFReaderException {
-
-
- if (newPosition > fBitCapacity) {
- throw new CTFReaderException("Out of bounds exception on a position move, attempting to access position: " + newPosition); //$NON-NLS-1$
- }
- fPosition = newPosition;
- }
-
- /**
- *
- * Sets the position in the buffer.
- *
- * @return order The position of the buffer.
- * @since 3.0
- */
- public long position() {
- return fPosition;
- }
-
- /**
- * Sets the byte buffer
- *
- * @param buf
- * the byte buffer
- */
- @Deprecated
- public void setByteBuffer(ByteBuffer buf) {
- /*
- * to avoid "The method setByteBuffer(ByteBuffer) from the type
- * BitBuffer can be declared as static"
- */
- long data = fPosition;
- fPosition = data;
- throw new UnsupportedOperationException("Bytebuffers are now final"); //$NON-NLS-1$
-
- }
-
- /**
- * Gets the byte buffer
- *
- * @return The byte buffer
- */
- public ByteBuffer getByteBuffer() {
- return fBuffer;
- }
-
- /**
- * Resets the bitbuffer.
- */
- public void clear() {
- resetPosition();
- fBuffer.clear();
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.scope;
-
-import org.eclipse.jdt.annotation.NonNullByDefault;
-import org.eclipse.jdt.annotation.Nullable;
-
-/**
- * A lttng specific speedup node (the packet header with ID and V) of a lexical
- * scope
- *
- * @author Matthew Khouzam
- * @since 3.1
- */
-@NonNullByDefault
-public class EventHeaderScope extends LexicalScope {
-
- /**
- * Event header id string
- */
- public static final LexicalScope EVENT_HEADER_ID = new LexicalScope(EVENT_HEADER, "id"); //$NON-NLS-1$
-
- /**
- * Event header v as in variant string
- */
- public static final LexicalScope EVENT_HEADER_V = new EventHeaderVScope(EVENT_HEADER, "v"); //$NON-NLS-1$
-
- /**
- * The scope constructor
- *
- * @param parent
- * The parent node, can be null, but shouldn't
- * @param name
- * the name of the field
- */
- public EventHeaderScope(LexicalScope parent, String name) {
- super(parent, name);
- }
-
- @Override
- @Nullable
- public LexicalScope getChild(String name) {
- if (name.equals(EVENT_HEADER_ID.getName())) {
- return EVENT_HEADER_ID;
- }
- if (name.equals(EVENT_HEADER_V.getName())) {
- return EVENT_HEADER_V;
- }
- return super.getChild(name);
- }
-
- @Override
- public String toString() {
- return "event.header"; //$NON-NLS-1$
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.scope;
-
-import org.eclipse.jdt.annotation.NonNullByDefault;
-import org.eclipse.jdt.annotation.Nullable;
-
-/**
- * A lttng specific speedup node (v variant for event headers) of a lexical
- * scope they normally contain a timestamp
- *
- * @author Matthew Khouzam
- * @since 3.1
- */
-@NonNullByDefault
-public class EventHeaderVScope extends LexicalScope {
-
- /**
- * Packet header v id string
- */
- public static final LexicalScope PACKET_HEADER_V_ID = new LexicalScope(PACKET_HEADER, "id"); //$NON-NLS-1$
- /**
- * Packet header v timestamp string
- */
- public static final LexicalScope PACKET_HEADER_V_TIMESTAMP = new LexicalScope(PACKET_HEADER, "timestamp"); //$NON-NLS-1$
-
- /**
- * The scope constructor
- *
- * @param parent
- * The parent node, can be null, but shouldn't
- * @param name
- * the name of the field
- */
- public EventHeaderVScope(LexicalScope parent, String name) {
- super(parent, name);
- }
-
- @Override
- @Nullable
- public LexicalScope getChild(String name) {
- if (name.equals(PACKET_HEADER_V_TIMESTAMP.getName())) {
- return PACKET_HEADER_V_TIMESTAMP;
- }
- if (name.equals(PACKET_HEADER_V_ID.getName())) {
- return PACKET_HEADER_V_ID;
- }
- return super.getChild(name);
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.scope;
-
-import org.eclipse.jdt.annotation.NonNullByDefault;
-import org.eclipse.jdt.annotation.Nullable;
-
-/**
- * A lttng specific speedup node field scope of a lexical scope
- *
- * @author Matthew Khouzam
- * @since 3.1
- */
-@NonNullByDefault
-public class FieldsScope extends LexicalScope {
-
- /**
- * ret field
- */
- public static final LexicalScope FIELDS_RET = new LexicalScope(FIELDS, "_ret"); //$NON-NLS-1$
-
- /**
- * tid field
- */
- public static final LexicalScope FIELDS_TID = new LexicalScope(FIELDS, "_tid"); //$NON-NLS-1$
-
- /**
- * The scope constructor
- *
- * @param parent
- * The parent node, can be null, but shouldn't
- * @param name
- * the name of the field
- */
- public FieldsScope(LexicalScope parent, String name) {
- super(parent, name);
- }
-
- @Override
- @Nullable
- public LexicalScope getChild(String name) {
- if (name.equals(FIELDS_RET.getName())) {
- return FIELDS_RET;
- }
- if (name.equals(FIELDS_TID.getName())) {
- return FIELDS_TID;
- }
- return super.getChild(name);
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.scope;
-
-import org.eclipse.linuxtools.ctf.core.event.types.Definition;
-
-/**
- * The scope of a CTF definition. Used for compound types.
- *
- * @version 1.0
- * @author Matthew Khouzam
- * @author Simon Marchi
- * @since 3.0
- */
-public interface IDefinitionScope {
-
- /**
- * Gets the path in a C style for the scope.
- *
- * @return the path
- * @since 3.0
- */
- LexicalScope getScopePath();
-
- /**
- * Looks up in this definition scope.
- *
- * @param lookupPath
- * The path to look up
- * @return The Definition that was read
- */
- // TODO: change to IDefintion
- Definition lookupDefinition(String lookupPath);
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.scope;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.jdt.annotation.NonNullByDefault;
-import org.eclipse.jdt.annotation.Nullable;
-
-import com.google.common.base.Joiner;
-
-/**
- * A node of a lexical scope
- *
- * @author Matthew Khouzam
- * @since 3.0
- */
-@NonNullByDefault
-public class LexicalScope implements Comparable<LexicalScope> {
- /**
- * Empty string
- *
- * @since 3.0
- */
- public static final LexicalScope ROOT = new RootScope();
-
- /**
- * Trace string
- *
- * @since 3.0
- */
- public static final LexicalScope TRACE = new LexicalScope(ROOT, "trace"); //$NON-NLS-1$
-
- /**
- * Env string
- *
- * @since 3.0
- */
- public static final LexicalScope ENV = new LexicalScope(ROOT, "env"); //$NON-NLS-1$
-
- /**
- * Stream string
- *
- * @since 3.0
- */
- public static final LexicalScope STREAM = new LexicalScope(ROOT, "stream"); //$NON-NLS-1$
-
- /**
- * Event string
- *
- * @since 3.0
- */
- public static final LexicalScope EVENT = new LexicalScope(ROOT, "event"); //$NON-NLS-1$
-
- /**
- * Variant string
- *
- * @since 3.0
- */
- public static final LexicalScope VARIANT = new LexicalScope(ROOT, "variant"); //$NON-NLS-1$
-
- /**
- * packet string
- *
- * @since 3.0
- */
- public static final LexicalScope PACKET = new LexicalScope(ROOT, "packet"); //$NON-NLS-1$
-
- /**
- * Packet header string
- *
- * @since 3.0
- *
- */
- public static final LexicalScope PACKET_HEADER = new PacketHeaderScope();
-
- /**
- * Stream packet scope
- *
- * @since 3.0
- */
- public static final LexicalScope STREAM_PACKET = new LexicalScope(STREAM, "packet"); //$NON-NLS-1$
-
- /**
- * Stream Packet header string
- *
- * @since 3.0
- */
- public static final LexicalScope STREAM_PACKET_CONTEXT = new LexicalScope(STREAM_PACKET, "context"); //$NON-NLS-1$
-
- /**
- * Trace packet scope
- *
- * @since 3.0
- */
- public static final LexicalScope TRACE_PACKET = new LexicalScope(TRACE, "packet"); //$NON-NLS-1$
-
- /**
- * Stream event scope
- *
- * @since 3.0
- */
- public static final LexicalScope STREAM_EVENT = new LexicalScope(STREAM, "event"); //$NON-NLS-1$
-
- /**
- * Trace packet header string
- *
- * @since 3.0
- */
- public static final LexicalScope TRACE_PACKET_HEADER = new LexicalScope(TRACE_PACKET, "header"); //$NON-NLS-1$
-
- /**
- * Stream event context
- *
- * @since 3.0
- */
- public static final LexicalScope STREAM_EVENT_CONTEXT = new LexicalScope(STREAM_EVENT, "context"); //$NON-NLS-1$
-
- /**
- * Stream event header
- *
- * @since 3.0
- */
- public static final LexicalScope STREAM_EVENT_HEADER = new LexicalScope(STREAM_EVENT, "header"); //$NON-NLS-1$
-
- /**
- * Event header
- *
- * @since 3.1
- */
- public static final LexicalScope EVENT_HEADER = new EventHeaderScope(EVENT, "header"); //$NON-NLS-1$
-
- /**
- * Fields in an event
- *
- * @since 3.0
- */
- public static final LexicalScope FIELDS = new FieldsScope(ROOT, "fields"); //$NON-NLS-1$
-
- /**
- * Context of an event
- *
- * @since 3.0
- */
- public static final LexicalScope CONTEXT = new LexicalScope(ROOT, "context"); //$NON-NLS-1$
-
- /**
- * Sorted list of parent paths
- *
- * @since 3.0
- */
- public static final LexicalScope[] PARENT_PATHS = {
- ROOT,
- CONTEXT,
- FIELDS,
- PACKET_HEADER,
- STREAM_EVENT_CONTEXT,
- STREAM_EVENT_HEADER,
- STREAM_PACKET_CONTEXT,
- TRACE_PACKET_HEADER
- };
-
- private int hash = 0;
- private final String fName;
- private final String fPath;
- private final Map<String, LexicalScope> fChildren;
-
- /**
- * The scope constructor
- *
- * @param parent
- * The parent node, can be null, but shouldn't
- * @param name
- * the name of the field
- */
- @SuppressWarnings("null")
- public LexicalScope(@Nullable LexicalScope parent, String name) {
- fName = name;
- if (parent != null) {
- String pathString = Joiner.on('.').skipNulls().join(parent.fPath, parent.getName());
- /*
- * if joiner return null, we get an NPE... so we won't assign fPath
- * to null
- */
- if (pathString.startsWith(".")) { //$NON-NLS-1$
- /*
- * substring throws an exception or returns a string, it won't
- * return null
- */
- pathString = pathString.substring(1);
- }
- fPath = pathString;
- parent.addChild(fName, this);
- } else {
- fPath = ""; //$NON-NLS-1$
- }
- @NonNull
- Map<String, LexicalScope> children =
- Collections.synchronizedMap(new HashMap<String, LexicalScope>());
- fChildren = children;
- }
-
- /**
- * Adds a child lexical scope
- *
- * @param name
- * the name of the child
- * @param child
- * the child
- */
- private void addChild(String name, LexicalScope child) {
- fChildren.put(name, child);
- }
-
- /**
- * Get the name
- *
- * @return the name
- */
- public String getName() {
- return fName;
- }
-
- /**
- * Gets a child of a given name
- *
- * @param name
- * the child
- * @return the scope, can be null
- */
- @Nullable
- public LexicalScope getChild(String name) {
- return fChildren.get(name);
- }
-
- @Override
- public String toString() {
- return (fPath.isEmpty() ? fName : fPath + '.' + fName);
- }
-
- @Override
- public int compareTo(@Nullable LexicalScope other) {
- if (other == null) {
- throw new IllegalArgumentException();
- }
- int comp = fPath.compareTo(other.fPath);
- if (comp == 0) {
- return fName.compareTo(other.fName);
- }
- return comp;
- }
-
- @Override
- public synchronized int hashCode() {
- if (hash == 0) {
- final int prime = 31;
- hash = prime * (prime + fName.hashCode()) + fPath.hashCode();
- }
- return hash;
- }
-
- @Override
- public boolean equals(@Nullable Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- LexicalScope other = (LexicalScope) obj;
- if (!fName.equals(other.fName)) {
- return false;
- }
- return fPath.equals(other.fPath);
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.scope;
-
-import org.eclipse.jdt.annotation.NonNullByDefault;
-
-/**
- * A lttng specific speedup node (the packet header with magic, uuid and stream
- * id ) of a lexical scope the sole reason to have this is to accelerate tostring()
- *
- * @author Matthew Khouzam
- * @since 3.1
- */
-@NonNullByDefault
-public class PacketHeaderScope extends LexicalScope {
-
- /**
- * Constructor
- */
- public PacketHeaderScope() {
- super(PACKET, "header"); //$NON-NLS-1$
- }
-
- @Override
- public String toString() {
- return "packet.header"; //$NON-NLS-1$
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.scope;
-
-import org.eclipse.jdt.annotation.NonNullByDefault;
-import org.eclipse.jdt.annotation.Nullable;
-
-/**
- * A lttng specific speedup node a root with accelerated returns for some scopes
- * of a lexical scope
- *
- * @author Matthew Khouzam
- * @since 3.1
- */
-@NonNullByDefault
-public class RootScope extends LexicalScope {
-
- /**
- * The scope constructor
- */
- public RootScope() {
- super(null, ""); //$NON-NLS-1$
- }
-
- @Override
- @Nullable
- public LexicalScope getChild(String name) {
- /*
- * This happens ~40 % of the time
- */
- if (name.equals(EVENT_HEADER.toString())) {
- return EVENT_HEADER;
- }
- /*
- * This happens ~30 % of the time
- */
- if (name.equals(FIELDS.toString())) {
- return FIELDS;
- }
- /*
- * This happens ~30 % of the time
- */
- if (name.equals(CONTEXT.toString())) {
- return CONTEXT;
- }
- /*
- * This happens ~1 % of the time
- */
- if (name.equals(PACKET_HEADER.toString())) {
- return PACKET_HEADER;
- }
- return super.getChild(name);
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-import java.util.List;
-
-import org.eclipse.jdt.annotation.NonNullByDefault;
-import org.eclipse.jdt.annotation.Nullable;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-
-/**
- * Array definition, used for compound definitions and fixed length strings
- *
- * @author Matthew Khouzam
- * @since 3.1
- */
-@NonNullByDefault
-public abstract class AbstractArrayDefinition extends Definition {
-
- /**
- * Constructor
- *
- * @param declaration
- * the event declaration
- *
- * @param definitionScope
- * the definition is in a scope, (normally a struct) what is it?
- * @param fieldName
- * the name of the definition. (it is a field in the parent
- * scope)
- */
- public AbstractArrayDefinition(IDeclaration declaration, @Nullable IDefinitionScope definitionScope, String fieldName) {
- super(declaration, definitionScope, fieldName);
- }
-
- /**
- * Get the defintions, an array is a collection of definitions
- *
- * @return the definitions
- */
- public abstract List<Definition> getDefinitions();
-
-}
\ No newline at end of file
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-import java.util.List;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-
-import com.google.common.collect.ArrayListMultimap;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableList.Builder;
-import com.google.common.collect.Multimap;
-
-/**
- * A CTF array declaration
- *
- * Arrays are fixed-length. Their length is declared in the type declaration
- * within the meta-data. They contain an array of "inner type" elements, which
- * can refer to any type not containing the type of the array being declared (no
- * circular dependency). The length is the number of elements in an array.
- *
- * @deprecated use
- * {@link org.eclipse.linuxtools.internal.ctf.core.event.types.ArrayDeclaration}
- * @version 1.0
- * @author Matthew Khouzam
- * @author Simon Marchi
- */
-@Deprecated
-public class ArrayDeclaration extends CompoundDeclaration {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- private final int fLength;
- private final IDeclaration fElemType;
-
- /**
- * <pre>
- * Cache where we can pre-generate the children names
- * Key: parent name
- * Value: children names
- * ex: field → {field[0], field[1], … field[n]}
- * </pre>
- *
- * TODO: investigate performance
- */
- private final Multimap<String, String> fChildrenNames = ArrayListMultimap.<String, String> create();
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Constructor
- *
- * @param length
- * how many elements in the array
- * @param elemType
- * what type of element is in the array
- */
- public ArrayDeclaration(int length, IDeclaration elemType) {
- fLength = length;
- fElemType = elemType;
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- @Override
- public IDeclaration getElementType() {
- return fElemType;
- }
-
- /**
- *
- * @return how many elements in the array
- */
- public int getLength() {
- return fLength;
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- /**
- * @since 3.0
- */
- @Deprecated
- @Override
- public ArrayDefinition createDefinition(IDefinitionScope definitionScope,
- @NonNull String fieldName, BitBuffer input) throws CTFReaderException {
- alignRead(input);
- List<Definition> definitions = read(input, definitionScope, fieldName);
- return new ArrayDefinition(this, definitionScope, fieldName, definitions);
- }
-
- @Override
- public String toString() {
- /* Only used for debugging */
- return "[declaration] array[" + Integer.toHexString(hashCode()) + ']'; //$NON-NLS-1$
- }
-
- @NonNull
- private List<Definition> read(@NonNull BitBuffer input, IDefinitionScope definitionScope, String fieldName) throws CTFReaderException {
- Builder<Definition> definitions = new ImmutableList.Builder<>();
- if (!fChildrenNames.containsKey(fieldName)) {
- for (int i = 0; i < fLength; i++) {
- fChildrenNames.put(fieldName, fieldName + '[' + i + ']');
- }
- }
- List<String> elemNames = (List<String>) fChildrenNames.get(fieldName);
- for (int i = 0; i < fLength; i++) {
- String name = elemNames.get(i);
- if (name == null) {
- throw new IllegalStateException();
- }
- definitions.add(fElemType.createDefinition(definitionScope, name, input));
- }
- @SuppressWarnings("null")
- @NonNull ImmutableList<Definition> ret = definitions.build();
- return ret;
- }
-
- /**
- * @since 3.0
- */
- @Override
- public int getMaximumSize() {
- long val = (long) fLength * fElemType.getMaximumSize();
- return (int) Math.min(Integer.MAX_VALUE, val);
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-import java.util.List;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.jdt.annotation.NonNullByDefault;
-import org.eclipse.jdt.annotation.Nullable;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-
-import com.google.common.base.Joiner;
-import com.google.common.collect.ImmutableList;
-
-/**
- * A CTF array definition
- *
- * Arrays are fixed-length. Their length is declared in the type declaration
- * within the meta-data. They contain an array of "inner type" elements, which
- * can refer to any type not containing the type of the array being declared (no
- * circular dependency). The length is the number of elements in an array.
- *
- * @deprecated use {@link AbstractArrayDefinition}
- * @version 1.0
- * @author Matthew Khouzam
- * @author Simon Marchi
- */
-@NonNullByDefault
-@Deprecated
-public final class ArrayDefinition extends AbstractArrayDefinition{
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- private final ImmutableList<Definition> fDefinitions;
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Constructor
- *
- * @param declaration
- * the parent declaration
- * @param definitionScope
- * the parent scope
- * @param fieldName
- * the field name
- * @param definitions
- * the content of the array
- * @since 3.0
- */
- public ArrayDefinition(ArrayDeclaration declaration,
- @Nullable IDefinitionScope definitionScope,
- String fieldName,
- List<Definition> definitions) {
- super(declaration, definitionScope, fieldName);
- @SuppressWarnings("null")
- @NonNull ImmutableList<Definition> list = ImmutableList.copyOf(definitions);
- fDefinitions = list;
-
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- @Override
- public List<Definition> getDefinitions() {
- return fDefinitions;
- }
-
- /**
- * Get the element at i
- *
- * @param i the index (cannot be negative)
- * @return The element at I, if I > length, null, if I < 0, the method throws an out of bounds exception
- */
- @Nullable
- public Definition getElem(int i) {
- if (i > fDefinitions.size()) {
- return null;
- }
-
- return fDefinitions.get(i);
- }
-
- @Override
- public ArrayDeclaration getDeclaration() {
- return (ArrayDeclaration) super.getDeclaration();
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- @Override
- public String toString() {
- StringBuilder b = new StringBuilder();
-
- if (getDeclaration().isString()) {
- for (Definition def : fDefinitions) {
- IntegerDefinition character = (IntegerDefinition) def;
-
- if (character.getValue() == 0) {
- break;
- }
-
- b.append(character.toString());
- }
- } else {
- b.append('[');
- Joiner joiner = Joiner.on(", ").skipNulls(); //$NON-NLS-1$
- b.append(joiner.join(fDefinitions));
- b.append(']');
- }
-
- @SuppressWarnings("null")
- @NonNull String ret = b.toString();
- return ret;
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-
-/**
- * Parent of sequences and arrays
- *
- * @author Matthew Khouzam
- * @since 3.1
- */
-public abstract class CompoundDeclaration extends Declaration {
-
- /**
- * Get the element type
- *
- * @return the type of element in the array
- */
- public abstract IDeclaration getElementType();
-
- @Override
- public long getAlignment() {
- return getElementType().getAlignment();
- }
-
- /**
- * Sometimes, strings are encoded as an array of 1-byte integers (each one
- * being an UTF-8 byte).
- *
- * @return true if this array is in fact an UTF-8 string. false if it's a
- * "normal" array of generic Definition's.
- */
- public boolean isString(){
- IDeclaration elementType = getElementType();
- if (elementType instanceof IntegerDeclaration) {
- IntegerDeclaration elemInt = (IntegerDeclaration) elementType;
- return elemInt.isCharacter();
- }
- return false;
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.event.scope.LexicalScope;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-
-/**
- * Declaration base, it helps for basic functionality that is often called, so
- * performance is often a high priority in this class
- *
- * @author Matthew Khouzam
- * @since 3.0
- */
-public abstract class Declaration implements IDeclaration {
-
- @Override
- public LexicalScope getPath(IDefinitionScope definitionScope, @NonNull String fieldName) {
- if (definitionScope != null) {
- final LexicalScope parentPath = definitionScope.getScopePath();
- if (parentPath != null) {
- LexicalScope myScope = parentPath.getChild(fieldName);
- if (myScope == null) {
- myScope = new LexicalScope(parentPath, fieldName);
- }
- return myScope;
- }
- }
- LexicalScope child = LexicalScope.ROOT.getChild(fieldName);
- if (child != null) {
- return child;
- }
- return new LexicalScope(LexicalScope.ROOT, fieldName);
- }
-
- /**
- * Offset the buffer position wrt the current alignment.
- *
- * @param input
- * The bitbuffer that is being read
- * @throws CTFReaderException
- * Happens when there is an out of bounds exception
- * @since 3.0
- */
- protected final void alignRead(BitBuffer input) throws CTFReaderException {
- long mask = getAlignment() - 1;
- /*
- * The alignment is a power of 2
- */
- long pos = input.position();
- if ((pos & mask) == 0) {
- return;
- }
- pos = (pos + mask) & ~mask;
- input.position(pos);
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.event.scope.LexicalScope;
-
-/**
- * A CTF definition
- *
- * A definition is like an object of a declaration class. It fills the
- * declaration with values. <br>
- * An example: <br>
- * int i = 0; <br>
- * <b>int</b> is the declaration.<br>
- * <b>i</b> is the definition.<br>
- * <b>0</b> is the value assigned to the definition, not the declaration.<br>
- *
- * @version 1.0
- * @author Matthew Khouzam
- * @author Simon Marchi
- */
-public abstract class Definition implements IDefinition {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- private final String fFieldName;
-
- /** The complete path of this field */
- private final @NonNull LexicalScope fPath;
-
- private final IDefinitionScope fDefinitionScope;
-
- @NonNull
- private final IDeclaration fDeclaration;
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Constructor
- *
- * @param declaration
- * the event declaration
- * @param definitionScope
- * the definition is in a scope, (normally a struct) what is it?
- * @param fieldName
- * the name of the definition. (it is a field in the parent
- * scope)
- * @since 3.0
- */
- public Definition(@NonNull IDeclaration declaration, IDefinitionScope definitionScope, @NonNull String fieldName) {
- this(declaration, definitionScope, fieldName, declaration.getPath(definitionScope, fieldName));
- }
-
- /**
- * Constructor This one takes the scope and thus speeds up definition
- * creation
- *
- *
- * @param declaration
- * the event declaration
- *
- * @param definitionScope
- * the definition is in a scope, (normally a struct) what is it?
- *
- * @param fieldName
- * the name of the defintions. it is a field in the parent scope.
- *
- * @param scope
- * the scope
- * @since 3.1
- */
- public Definition(@NonNull IDeclaration declaration, IDefinitionScope definitionScope, @NonNull String fieldName, @NonNull LexicalScope scope) {
- fDeclaration = declaration;
- fDefinitionScope = definitionScope;
- fFieldName = fieldName;
- fPath = scope;
- }
-
- // ------------------------------------------------------------------------
- // Getters
- // ------------------------------------------------------------------------
-
- /**
- * Get the field name in its container.
- *
- * @return The field name
- * @since 2.0
- */
- protected String getFieldName() {
- return fFieldName;
- }
-
- @Override
- public LexicalScope getScopePath() {
- return fPath;
- }
-
- /**
- * Get the definition scope in which this definition is found.
- *
- * The complete path of a definition is thus the path of the definition
- * scope DOT the name of the definition (name of the field in its container)
- *
- * @return The definition scope
- * @since 3.0
- */
- protected IDefinitionScope getDefinitionScope() {
- return fDefinitionScope;
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- @Override
- public IDeclaration getDeclaration() {
- return fDeclaration;
- }
-
- @Override
- public String toString() {
- return fPath.toString() + '[' + Integer.toHexString(hashCode()) + ']';
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011-2012 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-import org.eclipse.jdt.annotation.NonNullByDefault;
-
-/**
- * CTF encoding types
- *
- * @version 1.0
- * @author Matthew Khouzam
- * @author Simon Marchi
- */
-@NonNullByDefault
-public enum Encoding {
- /** UTF-8 encoding */
- UTF8,
- /** Ascii encoding */
- ASCII,
- /** No encoding, maybe not even text */
- NONE
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-
-/**
- * A CTF enum declaration.
- *
- * The definition of a enum point basic data type. It will take the data from a
- * trace and store it (and make it fit) as an integer and a string.
- *
- * @version 1.0
- * @author Matthew Khouzam
- * @author Simon Marchi
- */
-public final class EnumDeclaration extends Declaration implements ISimpleDatatypeDeclaration {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- private final EnumTable fTable = new EnumTable();
- private final IntegerDeclaration fContainerType;
- private final Set<String> fLabels = new HashSet<>();
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * constructor
- *
- * @param containerType
- * the enum is an int, this is the type that the data is
- * contained in. If you have 1000 possible values, you need at
- * least a 10 bit enum. If you store 2 values in a 128 bit int,
- * you are wasting space.
- */
- public EnumDeclaration(IntegerDeclaration containerType) {
- fContainerType = containerType;
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- /**
- *
- * @return The container type
- */
- public IntegerDeclaration getContainerType() {
- return fContainerType;
- }
-
- @Override
- public long getAlignment() {
- return this.getContainerType().getAlignment();
- }
-
- /**
- * @since 3.0
- */
- @Override
- public int getMaximumSize() {
- return fContainerType.getMaximumSize();
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- /**
- * @since 3.0
- */
- @Override
- public EnumDefinition createDefinition(IDefinitionScope definitionScope, String fieldName, BitBuffer input) throws CTFReaderException {
- alignRead(input);
- IntegerDefinition value = getContainerType().createDefinition(definitionScope, fieldName, input);
- return new EnumDefinition(this, definitionScope, fieldName, value);
- }
-
- /**
- * Add a value. Do not overlap, this is <em><strong>not</strong></em> an
- * interval tree.
- *
- * @param low
- * lowest value that this int can be to have label as a return
- * string
- * @param high
- * highest value that this int can be to have label as a return
- * string
- * @param label
- * the name of the value.
- * @return was the value be added? true == success
- */
- public boolean add(long low, long high, String label) {
- fLabels.add(label);
- return fTable.add(low, high, label);
- }
-
- /**
- * Check if the label for a value (enum a{day=0,night=1} would return "day"
- * for query(0)
- *
- * @param value
- * the value to lookup
- * @return the label of that value, can be null
- */
- public String query(long value) {
- return fTable.query(value);
- }
-
- /**
- * Gets a set of labels of the enum
- *
- * @return A set of labels of the enum, can be empty but not null
- * @since 3.0
- */
- public Set<String> getLabels() {
- return Collections.unmodifiableSet(fLabels);
- }
-
- /*
- * Maps integer range -> string. A simple list for now, but feel free to
- * optimize it. Babeltrace suggests an interval tree.
- */
- private class EnumTable {
-
- private final List<LabelAndRange> ranges = new LinkedList<>();
-
- public EnumTable() {
- }
-
- public boolean add(long low, long high, String label) {
- LabelAndRange newRange = new LabelAndRange(low, high, label);
-
- for (LabelAndRange r : ranges) {
- if (r.intersects(newRange)) {
- return false;
- }
- }
-
- ranges.add(newRange);
-
- return true;
- }
-
- /**
- * Return the first label that matches a value
- *
- * @param value
- * the value to query
- * @return the label corresponding to that value
- */
- public String query(long value) {
- for (LabelAndRange r : ranges) {
- if (r.intersects(value)) {
- return r.getLabel();
- }
- }
- return null;
- }
-
- }
-
- private static class LabelAndRange {
-
- private final long low, high;
- private final String fLabel;
-
- /**
- * Get the label
- *
- * @return the label
- */
- public String getLabel() {
- return fLabel;
- }
-
- public LabelAndRange(long low, long high, String str) {
- this.low = low;
- this.high = high;
- this.fLabel = str;
- }
-
- public boolean intersects(long i) {
- return (i >= this.low) && (i <= this.high);
- }
-
- public boolean intersects(LabelAndRange other) {
- return this.intersects(other.low)
- || this.intersects(other.high);
- }
- }
-
- @Override
- public String toString() {
- /* Only used for debugging */
- return "[declaration] enum[" + Integer.toHexString(hashCode()) + ']'; //$NON-NLS-1$
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-
-/**
- * A CTF enum definition.
- *
- * The definition of a enum point basic data type. It will take the data from a
- * trace and store it (and make it fit) as an integer and a string.
- *
- * @version 1.0
- * @author Matthew Khouzam
- * @author Simon Marchi
- */
-public final class EnumDefinition extends SimpleDatatypeDefinition {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- private final long fIntegerValue;
-
- private final String fValue;
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Constructor
- *
- * @param declaration
- * the parent declaration
- * @param definitionScope
- * the parent scope
- * @param fieldName
- * the field name
- * @param intValue
- * the value of the enum
- * @since 3.0
- */
- public EnumDefinition(@NonNull EnumDeclaration declaration,
- IDefinitionScope definitionScope, @NonNull String fieldName, IntegerDefinition intValue) {
- super(declaration, definitionScope, fieldName);
-
- fIntegerValue = intValue.getValue();
- fValue = declaration.query(fIntegerValue);
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- /**
- * Gets the value of the enum in string format so
- * "Enum a{DAY="0", NIGHT="1"}; will return "DAY"
- *
- * @return the value of the enum.
- */
- public String getValue() {
- return fValue;
- }
-
- @Override
- public String getStringValue() {
- return getValue();
- }
-
- /**
- * Gets the value of the enum in string format so
- * "Enum a{DAY="0", NIGHT="1"}; will return 0
- *
- * @return the value of the enum.
- */
- @Override
- public Long getIntegerValue() {
- return fIntegerValue;
- }
-
- @Override
- public EnumDeclaration getDeclaration() {
- return (EnumDeclaration) super.getDeclaration();
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- @Override
- public String toString() {
- return "{ value = " + getValue() + //$NON-NLS-1$
- ", container = " + fIntegerValue + //$NON-NLS-1$
- " }"; //$NON-NLS-1$
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-import java.nio.ByteOrder;
-
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-
-/**
- * A CTF float declaration.
- *
- * The declaration of a floating point basic data type.
- *
- * @version 1.0
- * @author Matthew Khouzam
- */
-public final class FloatDeclaration extends Declaration implements ISimpleDatatypeDeclaration {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- private final int fMantissa;
- private final int fExponent;
- private final ByteOrder fByteOrder;
- private final long fAlignement;
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Constructor
- *
- * @param exponent
- * The exponent size in bits
- * @param mantissa
- * The mantissa size in bits (+1 for sign) (see CTF spec)
- * @param byteOrder
- * The byte order
- * @param alignment
- * The alignment. Should be ≥ 1
- */
- public FloatDeclaration(int exponent, int mantissa, ByteOrder byteOrder,
- long alignment) {
- fMantissa = mantissa;
- fExponent = exponent;
- fByteOrder = byteOrder;
- fAlignement = Math.max(alignment, 1);
-
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- /**
- * @return the mant
- */
- public int getMantissa() {
- return fMantissa;
- }
-
- /**
- * @return the exp
- */
- public int getExponent() {
- return fExponent;
- }
-
- /**
- * @return the byteOrder
- */
- public ByteOrder getByteOrder() {
- return fByteOrder;
- }
-
- @Override
- public long getAlignment() {
- return fAlignement;
- }
-
- /**
- * @since 3.0
- */
- @Override
- public int getMaximumSize() {
- return fMantissa + fExponent + 1;
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- /**
- * @since 3.0
- */
- @Override
- public FloatDefinition createDefinition(IDefinitionScope definitionScope,
- String fieldName, BitBuffer input) throws CTFReaderException {
- ByteOrder byteOrder = input.getByteOrder();
- input.setByteOrder(fByteOrder);
- double value = read(input);
- input.setByteOrder(byteOrder);
- return new FloatDefinition(this, definitionScope, fieldName, value);
- }
-
- @Override
- public String toString() {
- /* Only used for debugging */
- return "[declaration] float[" + Integer.toHexString(hashCode()) + ']'; //$NON-NLS-1$
- }
-
- private double read(BitBuffer input) throws CTFReaderException {
- /* Offset the buffer position wrt the current alignment */
- alignRead(input);
- final int exp = getExponent();
- final int mant = getMantissa();
- double value = Double.NaN;
- if ((exp + mant) == 32) {
- value = readRawFloat32(input, mant, exp);
- } else if ((exp + mant) == 64) {
- value = readRawFloat64(input, mant, exp);
- }
- return value;
- }
-
- private static double readRawFloat32(BitBuffer input, final int manBits,
- final int expBits) throws CTFReaderException {
- long temp = input.get(32, false);
- return createFloat(temp, manBits - 1, expBits);
- }
-
- private static double readRawFloat64(BitBuffer input, final int manBits,
- final int expBits) throws CTFReaderException {
- long temp = input.get(64, false);
- return createFloat(temp, manBits - 1, expBits);
- }
-
- /**
- * Create a float from the raw value, Mathematicians beware.
- *
- * @param rawValue
- * The raw value( up to 64 bits)
- * @param manBits
- * number of bits in the mantissa
- * @param expBits
- * number of bits in the exponent
- */
- private static double createFloat(long rawValue, final int manBits,
- final int expBits) {
- long manShift = 1L << (manBits);
- long manMask = manShift - 1;
- long expMask = (1L << expBits) - 1;
-
- int exp = (int) ((rawValue >> (manBits)) & expMask) + 1;
- long man = (rawValue & manMask);
- final int offsetExponent = exp - (1 << (expBits - 1));
- double expPow = Math.pow(2.0, offsetExponent);
- double ret = man * 1.0f;
- ret /= manShift;
- ret += 1.0;
- ret *= expPow;
- return ret;
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-
-/**
- * A CTF float definition.
- *
- * The definition of a floating point basic data type. It will take the data
- * from a trace and store it (and make it fit) as a double.
- *
- * @version 1.0
- * @author Matthew Khouzam
- * @author Simon Marchi
- */
-public final class FloatDefinition extends Definition {
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- private final double fValue;
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Constructor
- *
- * @param declaration
- * the parent declaration
- * @param definitionScope
- * the parent scope
- * @param fieldName
- * the field name
- * @param value
- * field value
- * @since 3.0
- */
- public FloatDefinition(@NonNull FloatDeclaration declaration,
- IDefinitionScope definitionScope, @NonNull String fieldName, double value) {
- super(declaration, definitionScope, fieldName);
- fValue = value;
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- /**
- * The value of a float stored, fit into a double. This should be extended
- * for exotic floats if this is necessary.
- *
- * @return the value of the float field fit into a double.
- */
- public double getValue() {
- return fValue;
- }
-
- @Override
- public FloatDeclaration getDeclaration() {
- return (FloatDeclaration) super.getDeclaration();
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- @Override
- public String toString() {
- return String.valueOf(fValue);
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-import java.util.List;
-
-/**
- * Interface for data definitions containing heterogenous definitions
- * (subfields)
- *
- * @author Matthew Khouzam
- * @since 3.1
- */
-public interface ICompositeDefinition extends IDefinition {
-
- /**
- * Gets the definition of the field
- *
- * @param fieldName
- * the fieldname
- * @return The definitions of all the fields
- */
- Definition getDefinition(String fieldName);
-
- /**
- * Gets an array of the field names
- *
- * @return the field names array
- */
- List<String> getFieldNames();
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.event.scope.LexicalScope;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-
-/**
- * A CTF data type declaration.
- *
- * An example: <br>
- * int i = 0; <br>
- * <b>int</b> is the declaration.<br>
- * <b>i</b> is the definition.<br>
- * <b>0</b> is the value assigned to the definition, not the declaration.<br>
- *
- * @version 1.0
- * @author Matthew Khouzam
- * @author Simon Marchi
- */
-public interface IDeclaration {
-
- /**
- * Create a definition from this declaration
- *
- * @param definitionScope
- * the definition scope, the parent where the definition will be
- * placed
- * @param fieldName
- * the name of the definition
- * @param input
- * a bitbuffer to read from
- * @return a reference to the definition
- * @throws CTFReaderException
- * error in reading
- * @since 3.0
- */
- Definition createDefinition(IDefinitionScope definitionScope, @NonNull String fieldName, @NonNull BitBuffer input) throws CTFReaderException;
-
- /**
- * Get the path of a definition
- *
- * @param definitionScope
- * the scope of the definition
- * @param fieldName
- * the name of the definition
- * @return the path of the definition
- * @since 3.0
- */
- public @NonNull LexicalScope getPath(IDefinitionScope definitionScope, @NonNull String fieldName);
-
- /**
- * The minimum alignment. if the field is 32 bits, the definition will pad
- * all the data up to (position%32==0)
- *
- * @return the alignment in bits
- */
- long getAlignment();
-
- /**
- * The MAXIMUM size of this declaration
- *
- * @return the maximum size
- * @since 3.0
- */
- int getMaximumSize();
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-import org.eclipse.jdt.annotation.NonNullByDefault;
-import org.eclipse.linuxtools.ctf.core.event.scope.LexicalScope;
-
-/**
- * Interface for data definitions. A definition is when a value is given to a
- * declaration
- *
- * @author Matthew Khouzam
- * @since 3.1
- */
-@NonNullByDefault
-public interface IDefinition {
-
- /**
- * Get the complete path of this field.
- *
- * @return The path
- */
- LexicalScope getScopePath();
-
- /**
- * Get the declaration of this definition
- *
- * @return the declaration of a datatype
- */
- IDeclaration getDeclaration();
-
-}
\ No newline at end of file
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-import org.eclipse.jdt.annotation.NonNullByDefault;
-
-/**
- * Event header declaration abstract class
- *
- * @author Matthew Khouzam
- * @since 3.1
- */
-@NonNullByDefault
-public interface IEventHeaderDeclaration extends IDeclaration {
- /**
- * The id of an event
- */
- String ID = "id"; //$NON-NLS-1$
- /**
- * The name of a timestamp field
- */
- String TIMESTAMP = "timestamp"; //$NON-NLS-1$
- /**
- * Extended header
- */
- String EXTENDED = "extended"; //$NON-NLS-1$
- /**
- * Compact header (not to be confused with compact vs large)
- */
- String COMPACT = "compact"; //$NON-NLS-1$
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-/**
- * Common interface for simple CTF data types (which do not contain sub-fields).
- *
- * @author Matthew Khouzam
- * @since 3.1
- */
-public interface ISimpleDatatypeDeclaration {
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- * Simon Marchi - Initial API and implementation
- * Marc-Andre Laperle - Add min/maximum for validation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-import java.math.BigInteger;
-import java.nio.ByteOrder;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.jdt.annotation.NonNullByDefault;
-import org.eclipse.jdt.annotation.Nullable;
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-
-/**
- * A CTF integer declaration.
- *
- * The declaration of a integer basic data type.
- *
- * @version 1.0
- * @author Matthew Khouzam
- * @author Simon Marchi
- */
-@NonNullByDefault
-public class IntegerDeclaration extends Declaration implements ISimpleDatatypeDeclaration {
-
- // ------------------------------------------------------------------------
- // Helpers
- // ------------------------------------------------------------------------
-
- /**
- * unsigned int 32 bits big endian
- *
- * @since 3.0
- */
- public static final IntegerDeclaration UINT_32B_DECL = new IntegerDeclaration(32, false, ByteOrder.BIG_ENDIAN);
- /**
- * unsigned int 32 bits little endian
- *
- * @since 3.0
- */
- public static final IntegerDeclaration UINT_32L_DECL = new IntegerDeclaration(32, false, ByteOrder.LITTLE_ENDIAN);
- /**
- * signed int 32 bits big endian
- *
- * @since 3.0
- */
- public static final IntegerDeclaration INT_32B_DECL = new IntegerDeclaration(32, true, ByteOrder.BIG_ENDIAN);
- /**
- * signed int 32 bits little endian
- *
- * @since 3.0
- */
- public static final IntegerDeclaration INT_32L_DECL = new IntegerDeclaration(32, true, ByteOrder.LITTLE_ENDIAN);
- /**
- * unsigned int 32 bits big endian
- *
- * @since 3.0
- */
- public static final IntegerDeclaration UINT_64B_DECL = new IntegerDeclaration(64, false, ByteOrder.BIG_ENDIAN);
- /**
- * unsigned int 64 bits little endian
- *
- * @since 3.0
- */
- public static final IntegerDeclaration UINT_64L_DECL = new IntegerDeclaration(64, false, ByteOrder.LITTLE_ENDIAN);
- /**
- * signed int 64 bits big endian
- *
- * @since 3.0
- */
- public static final IntegerDeclaration INT_64B_DECL = new IntegerDeclaration(64, true, ByteOrder.BIG_ENDIAN);
- /**
- * signed int 64 bits little endian
- *
- * @since 3.0
- */
- public static final IntegerDeclaration INT_64L_DECL = new IntegerDeclaration(64, true, ByteOrder.LITTLE_ENDIAN);
- /**
- * unsigned 8 bit int endianness doesn't matter since it's 8 bits (byte)
- *
- * @since 3.0
- */
- public static final IntegerDeclaration UINT_8_DECL = new IntegerDeclaration(8, false, ByteOrder.BIG_ENDIAN);
- /**
- * signed 8 bit int endianness doesn't matter since it's 8 bits (char)
- *
- * @since 3.0
- */
- public static final IntegerDeclaration INT_8_DECL = new IntegerDeclaration(8, true, ByteOrder.BIG_ENDIAN);
- /**
- * Unsigned 5 bit int, used for event headers
- *
- * @since 3.1
- */
- public static final IntegerDeclaration UINT_5B_DECL = new IntegerDeclaration(5, false, ByteOrder.BIG_ENDIAN);
- /**
- * Unsigned 5 bit int, used for event headers
- *
- * @since 3.1
- */
- public static final IntegerDeclaration UINT_5L_DECL = new IntegerDeclaration(5, false, ByteOrder.LITTLE_ENDIAN);
- /**
- * Unsigned 5 bit int, used for event headers
- *
- * @since 3.1
- */
- public static final IntegerDeclaration UINT_27B_DECL = new IntegerDeclaration(27, false, ByteOrder.BIG_ENDIAN);
- /**
- * Unsigned 5 bit int, used for event headers
- *
- * @since 3.1
- */
- public static final IntegerDeclaration UINT_27L_DECL = new IntegerDeclaration(27, false, ByteOrder.LITTLE_ENDIAN);
- /**
- * Unsigned 16 bit int, used for event headers
- *
- * @since 3.1
- */
- public static final IntegerDeclaration UINT_16B_DECL = new IntegerDeclaration(16, false, ByteOrder.BIG_ENDIAN);
- /**
- * Unsigned 16 bit int, used for event headers
- *
- * @since 3.1
- */
- public static final IntegerDeclaration UINT_16L_DECL = new IntegerDeclaration(16, false, ByteOrder.LITTLE_ENDIAN);
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- private final int fLength;
- private final boolean fSigned;
- private final int fBase;
- private final ByteOrder fByteOrder;
- private final Encoding fEncoding;
- private final long fAlignment;
- private final String fClock;
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Factory, some common types cached
- *
- * @param len
- * The length in bits
- * @param signed
- * Is the integer signed? false == unsigned
- * @param base
- * The base (10-16 are most common)
- * @param byteOrder
- * Big-endian little-endian or other
- * @param encoding
- * ascii, utf8 or none.
- * @param clock
- * The clock path, can be null
- * @param alignment
- * The minimum alignment. Should be >= 1
- * @return the integer declaration
- * @since 3.0
- */
- public static IntegerDeclaration createDeclaration(int len, boolean signed, int base,
- @Nullable ByteOrder byteOrder, Encoding encoding, String clock, long alignment) {
- if (encoding.equals(Encoding.NONE) && (alignment == 8) && (clock.equals("")) && base == 10) { //$NON-NLS-1$
- switch (len) {
- case 5:
- if (!signed) {
- if (byteOrder != null && byteOrder.equals(ByteOrder.BIG_ENDIAN)) {
- return UINT_5B_DECL;
- }
- return UINT_5L_DECL;
- }
- break;
- case 8:
- return signed ? INT_8_DECL : UINT_8_DECL;
- case 16:
- if (!signed) {
- if (byteOrder != null && byteOrder.equals(ByteOrder.BIG_ENDIAN)) {
- return UINT_16B_DECL;
- }
- return UINT_16L_DECL;
- }
- break;
- case 27:
- if (!signed) {
- if (byteOrder != null && byteOrder.equals(ByteOrder.BIG_ENDIAN)) {
- return UINT_27B_DECL;
- }
- return UINT_27L_DECL;
- }
- break;
- case 32:
- if (signed) {
- if (byteOrder != null && byteOrder.equals(ByteOrder.BIG_ENDIAN)) {
- return INT_32B_DECL;
- }
- return INT_32L_DECL;
- }
- if (byteOrder != null && byteOrder.equals(ByteOrder.BIG_ENDIAN)) {
- return UINT_32B_DECL;
- }
- return UINT_32L_DECL;
- case 64:
- if (signed) {
- if (byteOrder != null && byteOrder.equals(ByteOrder.BIG_ENDIAN)) {
- return INT_64B_DECL;
- }
- return INT_64L_DECL;
- }
- if (byteOrder != null && byteOrder.equals(ByteOrder.BIG_ENDIAN)) {
- return UINT_64B_DECL;
- }
- return UINT_64L_DECL;
- default:
- }
- }
- return new IntegerDeclaration(len, signed, base, byteOrder, encoding, clock, alignment);
- }
-
- /**
- * Constructor
- *
- * @param len
- * The length in bits
- * @param signed
- * Is the integer signed? false == unsigned
- * @param base
- * The base (10-16 are most common)
- * @param byteOrder
- * Big-endian little-endian or other
- * @param encoding
- * ascii, utf8 or none.
- * @param clock
- * The clock path, can be null
- * @param alignment
- * The minimum alignment. Should be ≥ 1
- */
- private IntegerDeclaration(int len, boolean signed, int base,
- @Nullable ByteOrder byteOrder, Encoding encoding, String clock, long alignment) {
- if (len <= 0 || len == 1 && signed) {
- throw new IllegalArgumentException();
- }
-
- fLength = len;
- fSigned = signed;
- fBase = base;
-
- @SuppressWarnings("null")
- @NonNull
- ByteOrder actualByteOrder = (byteOrder == null ? ByteOrder.nativeOrder() : byteOrder);
- fByteOrder = actualByteOrder;
-
- fEncoding = encoding;
- fClock = clock;
- fAlignment = Math.max(alignment, 1);
- }
-
- private IntegerDeclaration(int len, boolean signed, @Nullable ByteOrder byteOrder) {
- this(len, signed, 10, byteOrder, Encoding.NONE, "", 8); //$NON-NLS-1$
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- /**
- * Is the integer signed?
- *
- * @return the is the integer signed
- */
- public boolean isSigned() {
- return fSigned;
- }
-
- /**
- * Get the integer base commonly decimal or hex
- *
- * @return the integer base
- */
- public int getBase() {
- return fBase;
- }
-
- /**
- * Get the byte order
- *
- * @return the byte order
- */
- public ByteOrder getByteOrder() {
- return fByteOrder;
- }
-
- /**
- * Get encoding, chars are 8 bit ints
- *
- * @return the encoding
- */
- public Encoding getEncoding() {
- return fEncoding;
- }
-
- /**
- * Is the integer a character (8 bits and encoded?)
- *
- * @return is the integer a char
- */
- public boolean isCharacter() {
- return (fLength == 8) && (fEncoding != Encoding.NONE);
- }
-
- /**
- * Is the integer an unsigned byte (8 bits and no sign)?
- *
- * @return is the integer an unsigned byte
- * @since 3.1
- */
- public boolean isUnsignedByte() {
- return (fLength == 8) && (!fSigned);
- }
-
- /**
- * Get the length in bits for this integer
- *
- * @return the length of the integer
- */
- public int getLength() {
- return fLength;
- }
-
- @Override
- public long getAlignment() {
- return fAlignment;
- }
-
- /**
- * The integer's clock, since timestamps are stored in ints
- *
- * @return the integer's clock, can be null. (most often it is)
- */
- public String getClock() {
- return fClock;
- }
-
- /**
- * @since 3.0
- */
- @Override
- public int getMaximumSize() {
- return fLength;
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- /**
- * @since 3.0
- */
- @Override
- public IntegerDefinition createDefinition(@Nullable IDefinitionScope definitionScope,
- String fieldName, BitBuffer input) throws CTFReaderException {
- ByteOrder byteOrder = input.getByteOrder();
- input.setByteOrder(fByteOrder);
- long value = read(input);
- input.setByteOrder(byteOrder);
- return new IntegerDefinition(this, definitionScope, fieldName, value);
- }
-
- @Override
- public String toString() {
- /* Only used for debugging */
- return "[declaration] integer[" + Integer.toHexString(hashCode()) + ']'; //$NON-NLS-1$
- }
-
- /**
- * Get the maximum value for this integer declaration.
- *
- * @return The maximum value for this integer declaration
- * @since 2.0
- */
- public BigInteger getMaxValue() {
- /*
- * Compute the number of bits able to represent an unsigned number,
- * ignoring sign bit.
- */
- int significantBits = fLength - (fSigned ? 1 : 0);
- /*
- * For a given N significant bits, compute the maximal value which is (1
- * << N) - 1.
- */
-
- @SuppressWarnings("null")
- @NonNull
- BigInteger ret = BigInteger.ONE.shiftLeft(significantBits).subtract(BigInteger.ONE);
- return ret;
- }
-
- /**
- * Get the minimum value for this integer declaration.
- *
- * @return The minimum value for this integer declaration
- * @since 2.0
- */
- public BigInteger getMinValue() {
- if (!fSigned) {
- @SuppressWarnings("null")
- @NonNull
- BigInteger ret = BigInteger.ZERO;
- return ret;
- }
-
- /*
- * Compute the number of bits able to represent an unsigned number,
- * without the sign bit.
- */
- int significantBits = fLength - 1;
- /*
- * For a given N significant bits, compute the minimal value which is -
- * (1 << N).
- */
- @SuppressWarnings("null")
- @NonNull
- BigInteger ret = BigInteger.ONE.shiftLeft(significantBits).negate();
- return ret;
- }
-
- private long read(BitBuffer input) throws CTFReaderException {
- /* Offset the buffer position wrt the current alignment */
- alignRead(input);
-
- boolean signed = isSigned();
- int length = getLength();
- long bits = 0;
-
- /*
- * Is the endianness of this field the same as the endianness of the
- * input buffer? If not, then temporarily set the buffer's endianness to
- * this field's just to read the data
- */
- ByteOrder previousByteOrder = input.getByteOrder();
- if ((getByteOrder() != input.getByteOrder())) {
- input.setByteOrder(getByteOrder());
- }
-
- if (length > 64) {
- throw new CTFReaderException("Cannot read an integer with over 64 bits. Length given: " + length); //$NON-NLS-1$
- }
-
- bits = input.get(length, signed);
-
- /*
- * Put the input buffer's endianness back to original if it was changed
- */
- if (previousByteOrder != input.getByteOrder()) {
- input.setByteOrder(previousByteOrder);
- }
-
- return bits;
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-import java.math.BigInteger;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-
-/**
- * A CTF integer definition.
- *
- * The definition of a integer basic data type. It will take the data from a
- * trace and store it (and make it fit) as a long.
- *
- * @version 1.0
- * @author Matthew Khouzam
- * @author Simon Marchi
- */
-public final class IntegerDefinition extends SimpleDatatypeDefinition {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- private final long fValue;
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Constructor
- *
- * @param declaration
- * the parent declaration
- * @param definitionScope
- * the parent scope
- * @param fieldName
- * the field name
- * @param value
- * integer value
- * @since 3.0
- */
- public IntegerDefinition(@NonNull IntegerDeclaration declaration,
- IDefinitionScope definitionScope, @NonNull String fieldName, long value) {
- super(declaration, definitionScope, fieldName);
- fValue = value;
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- /**
- * Gets the value of the integer
- *
- * @return the value of the integer (in long)
- */
- public long getValue() {
- return fValue;
- }
-
- @Override
- public IntegerDeclaration getDeclaration() {
- return (IntegerDeclaration) super.getDeclaration();
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- @Override
- public Long getIntegerValue() {
- return getValue();
- }
-
- @Override
- public String getStringValue() {
- return this.toString();
- }
-
- @Override
- public String toString() {
- if (getDeclaration().isCharacter()) {
- char c = (char) fValue;
- return Character.toString(c);
- }
- return formatNumber(fValue, getDeclaration().getBase(), getDeclaration().isSigned());
- }
-
- /**
- * Print a numeric value as a string in a given base
- *
- * @param value
- * The value to print as string
- * @param base
- * The base for this value
- * @param signed
- * Is the value signed or not
- * @return formatted number string
- * @since 3.0
- */
- public static final String formatNumber(long value, int base, boolean signed) {
- String s;
- /* Format the number correctly according to the integer's base */
- switch (base) {
- case 2:
- s = "0b" + Long.toBinaryString(value); //$NON-NLS-1$
- break;
- case 8:
- s = "0" + Long.toOctalString(value); //$NON-NLS-1$
- break;
- case 16:
- s = "0x" + Long.toHexString(value); //$NON-NLS-1$
- break;
- case 10:
- default:
- /* For non-standard base, we'll just print it as a decimal number */
- if (!signed && value < 0) {
- /*
- * Since there are no 'unsigned long', handle this case with
- * BigInteger
- */
- BigInteger bigInteger = BigInteger.valueOf(value);
- /*
- * we add 2^64 to the negative number to get the real unsigned
- * value
- */
- bigInteger = bigInteger.add(BigInteger.valueOf(1).shiftLeft(64));
- s = bigInteger.toString();
- } else {
- s = Long.toString(value);
- }
- break;
- }
- return s;
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-import org.eclipse.jdt.annotation.NonNullByDefault;
-import org.eclipse.jdt.annotation.Nullable;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.event.scope.LexicalScope;
-
-/**
- * Scoped defintion. a defintion where you can lookup various datatypes
- *
- * TODO: replace by default methods and an interface when java 8 is upon us
- *
- * @author Matthew Khouzam
- * @since 3.1
- */
-@NonNullByDefault
-public abstract class ScopedDefinition extends Definition implements IDefinitionScope {
-
- /**
- * Constructor
- *
- * @param declaration
- * the event declaration
- * @param definitionScope
- * the definition is in a scope, (normally a struct) what is it?
- * @param fieldName
- * the name of the definition. (it is a field in the parent
- * scope)
- */
- public ScopedDefinition(IDeclaration declaration, @Nullable IDefinitionScope definitionScope, String fieldName) {
- super(declaration, definitionScope, fieldName);
- }
-
- /**
- * Constructor This one takes the scope and thus speeds up definition
- * creation
- *
- * @param declaration
- * the parent declaration
- * @param definitionScope
- * the parent scope
- * @param fieldName
- * the field name
- * @param scope
- * the lexical scope
- * @since 3.1
- */
- public ScopedDefinition(StructDeclaration declaration, @Nullable IDefinitionScope definitionScope, String fieldName, LexicalScope scope) {
- super(declaration, definitionScope, fieldName, scope);
- }
-
- /**
- * Lookup an array in a struct. If the name returns a non-array (like an
- * int) then the method returns null
- *
- * @param name
- * the name of the array
- * @return the array or null.
- */
- public @Nullable AbstractArrayDefinition lookupArrayDefinition(String name) {
- Definition def = lookupDefinition(name);
- return (AbstractArrayDefinition) ((def instanceof AbstractArrayDefinition) ? def : null);
- }
-
- /**
- * Lookup an array in a struct. If the name returns a non-array (like an
- * int) then the method returns null
- *
- * @param name
- * the name of the array
- * @return the array or null.
- * @deprecated use {@link ScopedDefinition#lookupArrayDefinition(String)}
- */
- @Deprecated
- @Nullable
- public ArrayDefinition lookupArray(String name) {
- Definition def = lookupDefinition(name);
- return (ArrayDefinition) ((def instanceof ArrayDefinition) ? def : null);
- }
-
- /**
- * Lookup an enum in a struct. If the name returns a non-enum (like an int)
- * then the method returns null
- *
- * @param name
- * the name of the enum
- * @return the enum or null if a definition is not found or it does not
- * match the desired datatype.
- */
- @Nullable
- public EnumDefinition lookupEnum(String name) {
- Definition def = lookupDefinition(name);
- return (EnumDefinition) ((def instanceof EnumDefinition) ? def : null);
- }
-
- /**
- * Lookup an integer in a struct. If the name returns a non-integer (like an
- * float) then the method returns null
- *
- * @param name
- * the name of the integer
- * @return the integer or null if a definition is not found or it does not
- * match the desired datatype.
- */
- @Nullable
- public IntegerDefinition lookupInteger(String name) {
- Definition def = lookupDefinition(name);
- return (IntegerDefinition) ((def instanceof IntegerDefinition) ? def : null);
- }
-
- /**
- * Lookup a sequence in a struct. If the name returns a non-sequence (like
- * an int) then the method returns null
- *
- * @param name
- * the name of the sequence
- * @return the sequence or null if a definition is not found or it does not
- * match the desired datatype.
- * @since 3.0
- * @deprecated use {@link ScopedDefinition#lookupArrayDefinition(String)}
- */
- @Deprecated
- @Nullable
- public SequenceDefinition lookupSequence(String name) {
- Definition def = lookupDefinition(name);
- return (SequenceDefinition) ((def instanceof SequenceDefinition) ? def : null);
- }
-
- /**
- * Lookup a string in a struct. If the name returns a non-string (like an
- * int) then the method returns null
- *
- * @param name
- * the name of the string
- * @return the string or null if a definition is not found or it does not
- * match the desired datatype.
- */
- @Nullable
- public StringDefinition lookupString(String name) {
- Definition def = lookupDefinition(name);
- return (StringDefinition) ((def instanceof StringDefinition) ? def : null);
- }
-
- /**
- * Lookup a struct in a struct. If the name returns a non-struct (like an
- * int) then the method returns null
- *
- * @param name
- * the name of the struct
- * @return the struct or null if a definition is not found or it does not
- * match the desired datatype.
- */
- @Nullable
- public StructDefinition lookupStruct(String name) {
- Definition def = lookupDefinition(name);
- return (StructDefinition) ((def instanceof StructDefinition) ? def : null);
- }
-
- /**
- * Lookup a variant in a struct. If the name returns a non-variant (like an
- * int) then the method returns null
- *
- * @param name
- * the name of the variant
- * @return the variant or null if a definition is not found or it does not
- * match the desired datatype.
- */
- @Nullable
- public VariantDefinition lookupVariant(String name) {
- Definition def = lookupDefinition(name);
- return (VariantDefinition) ((def instanceof VariantDefinition) ? def : null);
- }
-}
\ No newline at end of file
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011-2012 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-import java.util.Collection;
-import java.util.List;
-
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-
-import com.google.common.collect.ArrayListMultimap;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableList.Builder;
-import com.google.common.collect.Multimap;
-
-/**
- * A CTF sequence declaration.
- *
- * An array where the size is fixed but declared in the trace, unlike array
- * where it is declared with a literal
- * @deprecated use {@link org.eclipse.linuxtools.internal.ctf.core.event.types.SequenceDeclaration}
- * @version 1.0
- * @author Matthew Khouzam
- * @author Simon Marchi
- */
-@Deprecated
-public class SequenceDeclaration extends CompoundDeclaration {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- private final IDeclaration fElemType;
- private final String fLengthName;
- private final Multimap<String, String> fPaths = ArrayListMultimap.<String, String>create();
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Constructor
- *
- * @param lengthName
- * the name of the field describing the length
- * @param elemType
- * The element type
- */
- public SequenceDeclaration(String lengthName, IDeclaration elemType) {
- fElemType = elemType;
- fLengthName = lengthName;
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- @Override
- public IDeclaration getElementType() {
- return fElemType;
- }
-
- /**
- * Gets the name of the length field
- *
- * @return the name of the length field
- */
- public String getLengthName() {
- return fLengthName;
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- /**
- * @since 3.0
- */
- @SuppressWarnings("null") // immutablelist
- @Override
- public SequenceDefinition createDefinition(
- IDefinitionScope definitionScope, String fieldName, BitBuffer input) throws CTFReaderException {
- IDefinition lenDef = null;
-
- if (definitionScope != null) {
- lenDef = definitionScope.lookupDefinition(getLengthName());
- }
-
- if (lenDef == null) {
- throw new CTFReaderException("Sequence length field not found"); //$NON-NLS-1$
- }
-
- if (!(lenDef instanceof IntegerDefinition)) {
- throw new CTFReaderException("Sequence length field not integer"); //$NON-NLS-1$
- }
-
- IntegerDefinition lengthDefinition = (IntegerDefinition) lenDef;
-
- if (lengthDefinition.getDeclaration().isSigned()) {
- throw new CTFReaderException("Sequence length must not be signed"); //$NON-NLS-1$
- }
-
- long length = lengthDefinition.getValue();
- if ((length > Integer.MAX_VALUE) || (!input.canRead((int) length * fElemType.getMaximumSize()))) {
- throw new CTFReaderException("Sequence length too long " + length); //$NON-NLS-1$
- }
-
- Collection<String> collection = fPaths.get(fieldName);
- while (collection.size() < length) {
- fPaths.put(fieldName, fieldName + '[' + collection.size() + ']');
- }
- List<String> paths = (List<String>) fPaths.get(fieldName);
- Builder<Definition> definitions = new ImmutableList.Builder<>();
- for (int i = 0; i < length; i++) {
- definitions.add(fElemType.createDefinition(definitionScope, paths.get(i), input));
- }
- return new SequenceDefinition(this, definitionScope, fieldName, definitions.build());
- }
-
- @Override
- public String toString() {
- /* Only used for debugging */
- return "[declaration] sequence[" + Integer.toHexString(hashCode()) + ']'; //$NON-NLS-1$
- }
-
- /**
- * @since 3.0
- */
- @Override
- public int getMaximumSize() {
- return Integer.MAX_VALUE;
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-import java.util.List;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-
-import com.google.common.base.Joiner;
-import com.google.common.collect.ImmutableList;
-
-/**
- * A CTF sequence definition (a fixed-size array).
- *
- * An array where the size is fixed but declared in the trace, unlike array
- * where it is declared with a literal
- *
- * @deprecated use {@link AbstractArrayDefinition}
- * @version 1.0
- * @author Matthew Khouzam
- * @author Simon Marchi
- */
-@Deprecated
-public final class SequenceDefinition extends Definition {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- private final ImmutableList<Definition> fDefinitions;
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Constructor
- *
- * @param declaration
- * the parent declaration
- * @param definitionScope
- * the parent scope
- * @param fieldName
- * the field name
- * @param definitions
- * Definitions
- * @since 3.0
- */
- public SequenceDefinition(@NonNull SequenceDeclaration declaration, IDefinitionScope definitionScope, @NonNull String fieldName, List<Definition> definitions) {
- super(declaration, definitionScope, fieldName);
- fDefinitions = ImmutableList.copyOf(definitions);
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- @Override
- public SequenceDeclaration getDeclaration() {
- return (SequenceDeclaration) super.getDeclaration();
- }
-
- /**
- * The length of the sequence in number of elements so a sequence of 5
- * GIANT_rediculous_long_ints is the same as a sequence of 5 bits. (5)
- *
- * @return the length of the sequence
- */
- public int getLength() {
- return fDefinitions.size();
- }
-
- /**
- * Get the element at i
- *
- * @param i
- * the index (cannot be negative)
- * @return The element at I, if I > length, null, if I < 0, the method
- * throws an out of bounds exception
- */
- public Definition getElem(int i) {
- if (i > fDefinitions.size()) {
- return null;
- }
- return fDefinitions.get(i);
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- @Override
- public String toString() {
- StringBuilder b = new StringBuilder();
-
- if (getDeclaration().isString()) {
- for (Definition def : fDefinitions) {
- IntegerDefinition character = (IntegerDefinition) def;
-
- if (character.getValue() == 0) {
- break;
- }
-
- b.append(character.toString());
- }
- } else {
- b.append('[');
- Joiner joiner = Joiner.on(", ").skipNulls(); //$NON-NLS-1$
- b.append(joiner.join(fDefinitions));
- b.append(']');
- }
-
- return b.toString();
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-
-/**
- * Simple Datatype definition is a datatype that allows the addition of
- * getIntegerValue and getStringValue to a class.
- *
- * @author Matthew Khouzam
- * @since 1.2
- */
-public abstract class SimpleDatatypeDefinition extends Definition {
-
- /**
- * Create a new SimpleDatatypeDefinition
- *
- * @param declaration
- * definition's declaration
- * @param definitionScope
- * The scope of this definition
- * @param fieldName
- * The name of the field matching this definition in the parent
- * scope
- * @since 3.0
- */
- public SimpleDatatypeDefinition(@NonNull IDeclaration declaration, IDefinitionScope definitionScope,
- @NonNull String fieldName) {
- super(declaration, definitionScope, fieldName);
- }
-
- /**
- * Gets the value in integer form
- *
- * @return the integer in a Long, can be null
- */
- public Long getIntegerValue() {
- return null;
- }
-
- /**
- * Gets the value in string form
- *
- * @return the integer in a String, can be null
- */
- public String getStringValue() {
- return null;
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-
-/**
- * A CTF string declaration.
- *
- * Strings are an array of bytes of variable size and are terminated by a '\0'
- * "NULL" character. Their encoding is described in the TSDL meta-data. In
- * absence of encoding attribute information, the default encoding is UTF-8.
- *
- * @version 1.0
- * @author Matthew Khouzam
- * @author Simon Marchi
- */
-public class StringDeclaration extends Declaration {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- private final Encoding fEncoding;
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Generate a UTF8 string declaration
- */
- public StringDeclaration() {
- fEncoding = Encoding.UTF8;
- }
-
- /**
- * Generate an encoded string declaration
- * @param encoding the encoding, utf8 or ascii
- */
- public StringDeclaration(Encoding encoding) {
- fEncoding = encoding;
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- /**
- *
- * @return the character encoding.
- */
- public Encoding getEncoding() {
- return fEncoding;
- }
-
- @Override
- public long getAlignment() {
- // See ctf 4.2.5: Strings are always aligned on byte size.
- return 8;
- }
-
- /**
- * @since 3.0
- */
- @Override
- public int getMaximumSize() {
- return Integer.MAX_VALUE;
- }
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- /**
- * @since 3.0
- */
- @Override
- public StringDefinition createDefinition(IDefinitionScope definitionScope,
- String fieldName, BitBuffer input) throws CTFReaderException {
- String value = read(input);
- return new StringDefinition(this, definitionScope, fieldName, value);
- }
-
- private String read(BitBuffer input) throws CTFReaderException {
- /* Offset the buffer position wrt the current alignment */
- alignRead(input);
-
- StringBuilder sb = new StringBuilder();
- char c = (char) input.get(8, false);
- while (c != 0) {
- sb.append(c);
- c = (char) input.get(8, false);
- }
- return sb.toString();
- }
- @Override
- public String toString() {
- /* Only used for debugging */
- return "[declaration] string[" + Integer.toHexString(hashCode()) + ']'; //$NON-NLS-1$
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-
-/**
- * A CTF string definition (similar to a C null-terminated byte array).
- *
- * Strings are an array of bytes of variable size and are terminated by a '\0'
- * "NULL" character. Their encoding is described in the TSDL meta-data. In
- * absence of encoding attribute information, the default encoding is UTF-8.
- *
- * @version 1.0
- * @author Matthew Khouzam
- * @author Simon Marchi
- */
-public final class StringDefinition extends Definition {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- private final String fString;
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Constructor
- *
- * @param declaration
- * the parent declaration
- * @param definitionScope
- * the parent scope
- * @param fieldName
- * the field name
- * @param value
- * The String value
- * @since 3.0
- */
- public StringDefinition(@NonNull StringDeclaration declaration,
- IDefinitionScope definitionScope, @NonNull String fieldName, String value) {
- super(declaration, definitionScope, fieldName);
- fString = value;
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- @Override
- public StringDeclaration getDeclaration() {
- return (StringDeclaration) super.getDeclaration();
- }
-
- /**
- * Gets the string (value)
- *
- * @return the string
- */
- public String getValue() {
- return fString;
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- @Override
- public String toString() {
- return '\"' + getValue() + '\"';
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.jdt.annotation.Nullable;
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.event.scope.LexicalScope;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-
-/**
- * A CTF structure declaration.
- *
- * A structure is similar to a C structure, it is a compound data type that
- * contains other datatypes in fields. they are stored in an hashmap and indexed
- * by names which are strings.
- *
- * @version 1.0
- * @author Matthew Khouzam
- * @author Simon Marchi
- */
-public class StructDeclaration extends Declaration {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- /** linked list of field names. So fieldName->fieldValue */
- private final @NonNull Map<String, IDeclaration> fFieldMap = new LinkedHashMap<>();
-
- /** maximum bit alignment */
- private long fMaxAlign;
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * The struct declaration, add fields later
- *
- * @param align
- * the minimum alignment of the struct. (if a struct is 8bit
- * aligned and has a 32 bit aligned field, the struct becomes 32
- * bit aligned.
- */
- public StructDeclaration(long align) {
- fMaxAlign = Math.max(align, 1);
- }
-
- /**
- * Struct declaration constructor
- *
- * @param names
- * the names of all the fields
- * @param declarations
- * all the fields
- * @since 3.0
- */
- public StructDeclaration(String[] names, Declaration[] declarations) {
- fMaxAlign = 1;
-
- for (int i = 0; i < names.length; i++) {
- addField(names[i], declarations[i]);
- }
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- /**
- * Get current alignment
- *
- * @return the alignment of the struct and all its fields
- */
- public long getMaxAlign() {
- return fMaxAlign;
- }
-
- /**
- * Query if the struct has a given field
- *
- * @param name
- * the name of the field, scopeless please
- * @return does the field exist?
- */
- public boolean hasField(String name) {
- return fFieldMap.containsKey(name);
- }
-
- /**
- * Get the fields of the struct as a map.
- *
- * @return a Map of the fields (key is the name)
- * @since 2.0
- */
- public Map<String, IDeclaration> getFields() {
- return fFieldMap;
- }
-
- /**
- * Get the field declaration corresponding to a field name.
- *
- * @param fieldName
- * The field name
- * @return The declaration of the field, or null if there is no such field.
- * @since 3.1
- */
- @Nullable
- public IDeclaration getField(String fieldName) {
- return fFieldMap.get(fieldName);
- }
-
- /**
- * Gets the field list. Very important since the map of fields does not
- * retain the order of the fields.
- *
- * @return the field list.
- * @since 3.0
- */
- public Iterable<String> getFieldsList() {
- return fFieldMap.keySet();
- }
-
- @Override
- public long getAlignment() {
- return this.fMaxAlign;
- }
-
- /**
- * @since 3.0
- */
- @Override
- public int getMaximumSize() {
- int maxSize = 0;
- for (IDeclaration field : fFieldMap.values()) {
- maxSize += field.getMaximumSize();
- }
- return Math.min(maxSize, Integer.MAX_VALUE);
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- /**
- * @since 3.0
- */
- @Override
- public StructDefinition createDefinition(IDefinitionScope definitionScope,
- String fieldName, BitBuffer input) throws CTFReaderException {
- alignRead(input);
- final Definition[] myFields = new Definition[fFieldMap.size()];
- StructDefinition structDefinition = new StructDefinition(this, definitionScope, fieldName, fFieldMap.keySet(), myFields);
- fillStruct(input, myFields, structDefinition);
- return structDefinition;
- }
-
- /**
- * Create a definition from this declaration. This is a faster constructor
- * as it has a lexical scope and this does not need to look it up.
- *
- * @param definitionScope
- * the definition scope, the parent where the definition will be
- * placed
- * @param fieldScope
- * the scope of the definition
- * @param input
- * a bitbuffer to read from
- * @return a reference to the definition
- * @throws CTFReaderException
- * error in reading
- * @since 3.1
- */
- public StructDefinition createDefinition(IDefinitionScope definitionScope,
- LexicalScope fieldScope, @NonNull BitBuffer input) throws CTFReaderException {
- alignRead(input);
- final Definition[] myFields = new Definition[fFieldMap.size()];
- /*
- * Key set is NOT null
- */
- @SuppressWarnings("null")
- StructDefinition structDefinition = new StructDefinition(this, definitionScope, fieldScope, fieldScope.getName(), fFieldMap.keySet(), myFields);
- fillStruct(input, myFields, structDefinition);
- return structDefinition;
- }
-
- /**
- * Add a field to the struct
- *
- * @param name
- * the name of the field, scopeless
- * @param declaration
- * the declaration of the field
- */
- public void addField(String name, IDeclaration declaration) {
- fFieldMap.put(name, declaration);
- fMaxAlign = Math.max(fMaxAlign, declaration.getAlignment());
- }
-
- @SuppressWarnings("null")
- private void fillStruct(@NonNull BitBuffer input, final Definition[] myFields, StructDefinition structDefinition) throws CTFReaderException {
- Iterator<Map.Entry<String, IDeclaration>> iter = fFieldMap.entrySet().iterator();
- for (int i = 0; i < fFieldMap.size(); i++) {
- Map.Entry<String, IDeclaration> entry = iter.next();
- myFields[i] = entry.getValue().createDefinition(structDefinition, entry.getKey(), input);
- }
- }
-
- @Override
- public String toString() {
- /* Only used for debugging */
- return "[declaration] struct[" + Integer.toHexString(hashCode()) + ']'; //$NON-NLS-1$
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = (prime * result) + fFieldMap.entrySet().hashCode();
- result = (prime * result) + (int) (fMaxAlign ^ (fMaxAlign >>> 32));
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (!(obj instanceof StructDeclaration)) {
- return false;
- }
- StructDeclaration other = (StructDeclaration) obj;
- if (!fFieldMap.entrySet().equals(other.fFieldMap.entrySet())) {
- return false;
- }
- if (fMaxAlign != other.fMaxAlign) {
- return false;
- }
- return true;
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-import java.util.Collections;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.event.scope.LexicalScope;
-
-import com.google.common.base.Joiner;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableMap.Builder;
-
-/**
- * A CTF structure definition (similar to a C structure).
- *
- * A structure is similar to a C structure, it is a compound data type that
- * contains other datatypes in fields. they are stored in an hashmap and indexed
- * by names which are strings.
- *
- * TODO: move me to internal
- *
- * @version 1.0
- * @author Matthew Khouzam
- * @author Simon Marchi
- */
-public final class StructDefinition extends ScopedDefinition implements ICompositeDefinition {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- private final ImmutableList<String> fFieldNames;
- private final Definition[] fDefinitions;
- private Map<String, Definition> fDefinitionsMap = null;
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * *DEPRECATED* TODO: To remove once we break the API...
- *
- * Not marked with the annotation to not annoy callers using a List, which
- * is still as valid with the new constructor. But the compiler gives an
- * error even though a Iterable is a List too...
- *
- * @param declaration
- * the parent declaration
- * @param definitionScope
- * the parent scope
- * @param structFieldName
- * the field name
- * @param fieldNames
- * the list of fields
- * @param definitions
- * the definitions
- * @since 3.1
- */
- public StructDefinition(@NonNull StructDeclaration declaration,
- IDefinitionScope definitionScope,
- @NonNull String structFieldName,
- List<String> fieldNames,
- Definition[] definitions) {
- this(declaration, definitionScope, structFieldName, (Iterable<String>) fieldNames, definitions);
- }
-
- /**
- * Constructor
- *
- * @param declaration
- * the parent declaration
- * @param definitionScope
- * the parent scope
- * @param structFieldName
- * the field name
- * @param fieldNames
- * the list of fields
- * @param definitions
- * the definitions
- * @since 3.1
- */
- public StructDefinition(@NonNull StructDeclaration declaration,
- IDefinitionScope definitionScope,
- @NonNull String structFieldName,
- Iterable<String> fieldNames,
- Definition[] definitions) {
- super(declaration, definitionScope, structFieldName);
- fFieldNames = ImmutableList.copyOf(fieldNames);
- fDefinitions = definitions;
- if (fFieldNames.isEmpty()) {
- fDefinitionsMap = Collections.EMPTY_MAP;
- }
- }
-
- /**
- * Constructor This one takes the scope and thus speeds up definition
- * creation
- *
- * @param declaration
- * the parent declaration
- * @param definitionScope
- * the parent scope
- * @param scope
- * the scope of this variable
- * @param structFieldName
- * the field name
- * @param fieldNames
- * the list of fields
- * @param definitions
- * the definitions
- * @since 3.1
- */
- public StructDefinition(@NonNull StructDeclaration declaration,
- IDefinitionScope definitionScope, @NonNull LexicalScope scope,
- @NonNull String structFieldName, @NonNull Iterable<String> fieldNames, Definition[] definitions) {
- super(declaration, definitionScope, structFieldName, scope);
- fFieldNames = ImmutableList.copyOf(fieldNames);
- fDefinitions = definitions;
- if (fFieldNames.isEmpty()) {
- fDefinitionsMap = Collections.EMPTY_MAP;
- }
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- @Override
- public Definition getDefinition(String fieldName) {
- if (fDefinitionsMap == null) {
- /* Build the definitions map */
- Builder<String, Definition> mapBuilder = new ImmutableMap.Builder<>();
- for (int i = 0; i < fFieldNames.size(); i++) {
- if (fDefinitions[i] != null) {
- mapBuilder.put(fFieldNames.get(i), fDefinitions[i]);
- }
- }
- fDefinitionsMap = mapBuilder.build();
- }
- return fDefinitionsMap.get(fieldName);
- }
-
- @Override
- public List<String> getFieldNames() {
- return fFieldNames;
- }
-
- @Override
- public StructDeclaration getDeclaration() {
- return (StructDeclaration) super.getDeclaration();
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- @Override
- public Definition lookupDefinition(String lookupPath) {
- /*
- * The fields are created in order of appearance, so if a variant or
- * sequence refers to a field that is after it, the field's definition
- * will not be there yet in the hashmap.
- */
- int val = fFieldNames.indexOf(lookupPath);
- if (val != -1) {
- return fDefinitions[val];
- }
- String lookupUnderscored = "_" + lookupPath; //$NON-NLS-1$
- val = fFieldNames.indexOf(lookupUnderscored);
- if (val != -1) {
- return fDefinitions[val];
- }
- return null;
- }
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
-
- builder.append("{ "); //$NON-NLS-1$
-
- if (fFieldNames != null) {
- List<String> fields = new LinkedList<>();
- for (String field : fFieldNames) {
- String appendee = field + " = " + lookupDefinition(field).toString(); //$NON-NLS-1$
- fields.add(appendee);
- }
- Joiner joiner = Joiner.on(", ").skipNulls(); //$NON-NLS-1$
- builder.append(joiner.join(fields));
- }
-
- builder.append(" }"); //$NON-NLS-1$
-
- return builder.toString();
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-
-/**
- * A CTFC variant declaration.
- *
- * A variant is similar to a C union, only taking the minimum size of the types,
- * it is a compound data type that contains other datatypes in fields. they are
- * stored in an hashmap and indexed by names which are strings.
- *
- * @version 1.0
- * @author Matthew Khouzam
- * @author Simon Marchi
- */
-public class VariantDeclaration extends Declaration {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- private String fTag = null;
- private static final long ALIGNMENT = 1;
- private final Map<String, IDeclaration> fFields = Collections.synchronizedMap(new HashMap<String, IDeclaration>());
- private EnumDefinition fTagDef;
- private IDeclaration fDeclarationToPopulate;
- private IDefinitionScope fPrevDefinitionScope;
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Constructor
- */
- public VariantDeclaration() {
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- /**
- * @return Does the variant have a tag
- */
- public boolean isTagged() {
- return fTag != null;
- }
-
- /**
- * Lookup if a field exists in the variant
- *
- * @param fieldTag
- * the field tag name
- * @return true = field tag exists
- */
- public boolean hasField(String fieldTag) {
- return fFields.containsKey(fieldTag);
- }
-
- /**
- * Sets the tag in a variant
- *
- * @param tag
- * the tag
- */
- public void setTag(String tag) {
- fTag = tag;
- fTagDef = null;
- }
-
- /**
- * Gets current variant tag
- *
- * @return the variant tag.
- */
- public String getTag() {
- return fTag;
- }
-
- /**
- * Gets the fields of the variant
- *
- * @return the fields of the variant
- * @since 2.0
- */
- public Map<String, IDeclaration> getFields() {
- return this.fFields;
- }
-
- @Override
- public long getAlignment() {
- return ALIGNMENT;
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- /**
- * @since 3.0
- */
- @Override
- public VariantDefinition createDefinition(IDefinitionScope definitionScope,
- String fieldName, BitBuffer input) throws CTFReaderException {
- alignRead(input);
- if (fPrevDefinitionScope != definitionScope) {
- fTagDef = null;
- fPrevDefinitionScope = definitionScope;
- }
- EnumDefinition tagDef = fTagDef;
- if (tagDef == null) {
- Definition def = definitionScope.lookupDefinition(fTag);
- tagDef = (EnumDefinition) ((def instanceof EnumDefinition) ? def : null);
- }
- if (tagDef == null) {
- throw new CTFReaderException("Tag is not defined " + fTag); //$NON-NLS-1$
- }
- String varFieldName = tagDef.getStringValue();
- fDeclarationToPopulate = fFields.get(varFieldName);
- if (fDeclarationToPopulate == null) {
- throw new CTFReaderException("Unknown enum selector for variant " + //$NON-NLS-1$
- definitionScope.getScopePath().toString());
- }
- Definition fieldValue = fDeclarationToPopulate.createDefinition(definitionScope, fieldName, input);
- return new VariantDefinition(this, definitionScope, varFieldName, fieldName, fieldValue);
- }
-
- /**
- * Add a field to this CTF Variant
- *
- * @param fieldTag
- * The tag of the new field
- * @param declaration
- * The Declaration of this new field
- */
- public void addField(String fieldTag, IDeclaration declaration) {
- fFields.put(fieldTag, declaration);
- }
-
- /**
- * gets the tag definition
- *
- * @return the fTagDef
- * @since 3.0
- */
- public EnumDefinition getTagDef() {
- return fTagDef;
- }
-
- /**
- * @since 3.0
- */
- @Override
- public int getMaximumSize() {
- Collection<IDeclaration> values = fFields.values();
- int maxSize = 0;
- for (IDeclaration field : values) {
- maxSize = Math.max(maxSize, field.getMaximumSize());
- }
- return maxSize;
- }
-
- @Override
- public String toString() {
- /* Only used for debugging */
- return "[declaration] variant[" + Integer.toHexString(hashCode()) + ']'; //$NON-NLS-1$
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.event.types;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-
-/**
- * A CTF variant definition (similar to a C union).
- *
- * A variant is similar to a C union, only taking the minimum size of the types,
- * it is a compound data type that contains other datatypes in fields. they are
- * stored in an hashmap and indexed by names which are strings.
- *
- * @version 1.0
- * @author Matthew Khouzam
- * @author Simon Marchi
- */
-public final class VariantDefinition extends ScopedDefinition {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- private final Definition fDefinition;
- private final String fCurrentField;
- private final String fFieldName;
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Constructor
- *
- * @param declaration
- * the parent declaration
- * @param definitionScope
- * the parent scope
- * @param selectedField
- * the selected field
- * @param fieldName
- * the field name
- * @param fieldValue
- * the field value
- * @since 3.0
- */
- public VariantDefinition(@NonNull VariantDeclaration declaration,
- IDefinitionScope definitionScope, String selectedField, @NonNull String fieldName, Definition fieldValue) {
- super(declaration, definitionScope, fieldName);
-
- fFieldName = fieldName;
- fCurrentField = selectedField;
- fDefinition = fieldValue;
-
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- @Override
- public VariantDeclaration getDeclaration() {
- return (VariantDeclaration) super.getDeclaration();
- }
-
- /**
- * Get the current field name
- *
- * @return the current field name
- */
- public String getCurrentFieldName() {
- return fCurrentField;
- }
-
- /**
- * Get the current field
- *
- * @return the current field
- */
- public Definition getCurrentField() {
- return fDefinition;
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- @Override
- public Definition lookupDefinition(String lookupPath) {
- if (lookupPath == null) {
- return null;
- }
- if (lookupPath.equals(fFieldName)) {
- return fDefinition;
- }
- return getDefinitionScope().lookupDefinition(lookupPath);
- }
-
- @Override
- public String toString() {
- return "{ " + getCurrentFieldName() + //$NON-NLS-1$
- " = " + getCurrentField() + //$NON-NLS-1$
- " }"; //$NON-NLS-1$
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Alexandre Montplaisir - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.trace;
-
-/**
- * General exception that is thrown when there is a problem somewhere with the
- * CTF trace reader.
- *
- * @version 1.0
- * @author Alexandre Montplaisir
- */
-public class CTFReaderException extends Exception {
-
- private static final long serialVersionUID = 2065258365219777672L;
-
- /**
- * Default constructor with no message.
- */
- public CTFReaderException() {
- super();
- }
-
- /**
- * Constructor with an attached message.
- *
- * @param message
- * The message attached to this exception
- */
- public CTFReaderException(String message) {
- super(message);
- }
-
- /**
- * Re-throw an exception into this type.
- *
- * @param e
- * The previous Exception we caught
- */
- public CTFReaderException(Exception e) {
- super(e);
- }
-
- /**
- * Constructor with an attached message and re-throw an exception into this type.
- *
- * @param message
- * The message attached to this exception
- * @param exception
- * The previous Exception caught
- * @since 2.0
- */
- public CTFReaderException(String message, Throwable exception) {
- super(message, exception);
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-package org.eclipse.linuxtools.ctf.core.trace;
-
-/**
- * A response to a request
- *
- * @author Matthew Khouzam
- * @since 3.0
- *
- */
-public enum CTFResponse {
- /**
- * The operation was successful
- */
- OK,
- /**
- * The operation cannot be yet completed
- */
- WAIT,
- /**
- * The operation was finished
- */
- FINISH,
- /**
- * The operation failed
- */
- ERROR
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.trace;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.jdt.annotation.Nullable;
-import org.eclipse.linuxtools.ctf.core.event.IEventDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IEventHeaderDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-import org.eclipse.linuxtools.internal.ctf.core.event.EventDeclaration;
-import org.eclipse.linuxtools.internal.ctf.core.event.metadata.exceptions.ParseException;
-
-/**
- * <b><u>Stream</u></b>
- * <p>
- * Represents a stream in a trace.
- *
- * @since 3.0
- */
-public class CTFStream {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- /**
- * The numerical ID of the stream
- */
- private Long fId = null;
-
- /**
- * Declarations of the stream-specific structures
- */
- private StructDeclaration fPacketContextDecl = null;
- private IDeclaration fEventHeaderDecl = null;
- private StructDeclaration fEventContextDecl = null;
-
- /**
- * The trace to which the stream belongs
- */
- private CTFTrace fTrace = null;
-
- /**
- * Maps event ids to events
- */
- private final ArrayList<IEventDeclaration> fEvents = new ArrayList<>();
-
- private boolean fEventUnsetId = false;
-
- /**
- * The inputs associated to this stream
- */
- private final Set<CTFStreamInput> fInputs = new HashSet<>();
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Constructs a Stream that belongs to a Trace
- *
- * @param trace
- * The trace to which belongs this stream.
- */
- public CTFStream(CTFTrace trace) {
- fTrace = trace;
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- /**
- * Sets the id of a stream
- *
- * @param id
- * the id of a stream
- */
- public void setId(long id) {
- fId = id;
- }
-
- /**
- * Gets the id of a stream
- *
- * @return id the id of a stream
- */
- public Long getId() {
- return fId;
- }
-
- /**
- * Is the id of a stream set
- *
- * @return If the ID is set or not
- */
- public boolean isIdSet() {
- return fId != null;
- }
-
- /**
- *
- * @return is the event header set (timestamp and stuff) (see Ctf Spec)
- */
- public boolean isEventHeaderSet() {
- return fEventHeaderDecl != null;
- }
-
- /**
- *
- * @return is the event context set (pid and stuff) (see Ctf Spec)
- */
- public boolean isEventContextSet() {
- return fEventContextDecl != null;
- }
-
- /**
- *
- * @return Is the packet context set (see Ctf Spec)
- */
- public boolean isPacketContextSet() {
- return fPacketContextDecl != null;
- }
-
- /**
- * Sets the event header
- *
- * @param eventHeader
- * the current event header for all events in this stream
- */
- public void setEventHeader(StructDeclaration eventHeader) {
- fEventHeaderDecl = eventHeader;
- }
-
- /**
- * Sets the event header, this typically has the id and the timestamp
- *
- * @param eventHeader
- * the current event header for all events in this stream
- * @since 3.1
- */
- public void setEventHeader(IEventHeaderDeclaration eventHeader) {
- fEventHeaderDecl = eventHeader;
- }
-
- /**
- *
- * @param eventContext
- * the context for all events in this stream
- */
- public void setEventContext(StructDeclaration eventContext) {
- fEventContextDecl = eventContext;
- }
-
- /**
- *
- * @param packetContext
- * the packet context for all packets in this stream
- */
- public void setPacketContext(StructDeclaration packetContext) {
- fPacketContextDecl = packetContext;
- }
-
- /**
- *
- * @return the event header declaration in structdeclaration form
- * @deprecated use {@link CTFStream#getEventHeaderDeclaration()}
- */
- @Deprecated
- public StructDeclaration getEventHeaderDecl() {
- return (StructDeclaration) ((fEventHeaderDecl instanceof StructDeclaration) ? fEventHeaderDecl : null);
- }
-
- /**
- * Gets the event header declaration
- *
- * @return the event header declaration in declaration form
- * @since 3.1
- */
- public IDeclaration getEventHeaderDeclaration() {
- return fEventHeaderDecl;
- }
-
- /**
- *
- * @return the event context declaration in structdeclaration form
- */
- public StructDeclaration getEventContextDecl() {
- return fEventContextDecl;
- }
-
- /**
- *
- * @return the packet context declaration in structdeclaration form
- */
- public StructDeclaration getPacketContextDecl() {
- return fPacketContextDecl;
- }
-
- /**
- *
- * @return the set of all stream inputs for this stream
- */
- public Set<CTFStreamInput> getStreamInputs() {
- return fInputs;
- }
-
- /**
- *
- * @return the parent trace
- */
- public CTFTrace getTrace() {
- return fTrace;
- }
-
- /**
- *
- * @return all the event declarations for this stream, using the id as a key
- * for the hashmap.
- * @deprecated use {@link CTFStream#getEventDeclarations()}
- */
- @Deprecated
- public Map<Long, IEventDeclaration> getEvents() {
- throw new UnsupportedOperationException();
- }
-
- /**
- * Get all the event declarations in this stream.
- *
- * @return The event declarations for this stream
- * @since 3.2
- */
- public @NonNull Collection<IEventDeclaration> getEventDeclarations() {
- List<IEventDeclaration> retVal = new ArrayList<>(fEvents);
- retVal.removeAll(Collections.<IEventDeclaration> singletonList(null));
- return retVal;
- }
-
- /**
- * Get the event declaration for a given ID.
- *
- * @param eventId
- * The ID, can be {@link EventDeclaration#UNSET_EVENT_ID}, or any
- * positive value
- * @return The event declaration with the given ID for this stream, or
- * 'null' if there are no declaration with this ID
- * @throws IllegalArgumentException
- * If the passed ID is invalid
- * @since 3.2
- */
- public @Nullable IEventDeclaration getEventDeclaration(int eventId) {
- int eventIndex = (eventId == EventDeclaration.UNSET_EVENT_ID) ? 0 : eventId;
- if (eventIndex < 0) {
- /* Any negative value other than UNSET_EVENT_ID is invalid */
- throw new IllegalArgumentException("Event ID cannot be negative."); //$NON-NLS-1$
- }
- if (eventIndex >= fEvents.size()) {
- /* This ID could be valid, but there are no declarations with it */
- return null;
- }
- return fEvents.get(eventIndex);
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- /**
- * Adds an event to the event list.
- *
- * An event in a stream can omit its id if it is the only event in this
- * stream. An event for which no id has been specified has a null id. It is
- * thus not possible to add an event with the null key if the map is not
- * empty. It is also not possible to add an event to the map if the null key
- * is present in the map.
- *
- * @param event
- * The event to add
- * @throws ParseException
- * If there was a problem reading the event or adding it to the
- * stream
- */
- public void addEvent(IEventDeclaration event) throws ParseException {
- if (fEventUnsetId) {
- throw new ParseException("Event without id with multiple events in a stream"); //$NON-NLS-1$
- }
- int id = ((EventDeclaration) event).id();
-
- /*
- * If there is an event without id (the null key), it must be the only
- * one
- */
- if (id == EventDeclaration.UNSET_EVENT_ID) {
- if (!fEvents.isEmpty()) {
- throw new ParseException("Event without id with multiple events in a stream"); //$NON-NLS-1$
- }
- fEventUnsetId = true;
- fEvents.add(event);
- } else {
- /* Check if an event with the same ID already exists */
- if (fEvents.size() > id && fEvents.get(id) != null) {
- throw new ParseException("Event id already exists"); //$NON-NLS-1$
- }
- ensureSize(fEvents, id);
- /* Put the event in the list */
- fEvents.set(id, event);
- }
- }
-
- /**
- * Add a list of event declarations to this stream. There must be no overlap
- * between the two lists of event declarations. This will merge the two
- * lists and preserve the indexes of both lists.
- *
- * @param events
- * list of the events to add
- * @throws CTFReaderException
- * if the list already contains data
- * @since 3.2
- */
- public void addEvents(Collection<IEventDeclaration> events) throws CTFReaderException {
- if (fEventUnsetId) {
- throw new CTFReaderException("Cannot add to a stream with an unidentified event"); //$NON-NLS-1$
- }
- if (fEvents.isEmpty()) {
- fEvents.addAll(events);
- return;
- }
- for (IEventDeclaration event : events) {
- if (event != null) {
- int index = event.getId().intValue();
- ensureSize(fEvents, index);
- if (fEvents.get(index) != null) {
- throw new CTFReaderException("Both lists have an event defined at position " + index); //$NON-NLS-1$
- }
- fEvents.set(index, event);
- }
- }
- }
-
- private static void ensureSize(ArrayList<? extends Object> list, int index) {
- list.ensureCapacity(index);
- while (list.size() <= index) {
- list.add(null);
- }
- }
-
- /**
- * Add an input to this Stream
- *
- * @param input
- * The StreamInput to add.
- */
- public void addInput(CTFStreamInput input) {
- fInputs.add(input);
- }
-
- @Override
- public String toString() {
- return "Stream [id=" + fId + ", packetContextDecl=" + fPacketContextDecl //$NON-NLS-1$ //$NON-NLS-2$
- + ", eventHeaderDecl=" + fEventHeaderDecl //$NON-NLS-1$
- + ", eventContextDecl=" + fEventContextDecl + ", trace=" + fTrace //$NON-NLS-1$ //$NON-NLS-2$
- + ", events=" + fEvents + ", inputs=" + fInputs + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.trace;
-
-import java.io.File;
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.nio.channels.FileChannel;
-import java.nio.channels.FileChannel.MapMode;
-import java.nio.file.StandardOpenOption;
-import java.util.UUID;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.event.scope.LexicalScope;
-import org.eclipse.linuxtools.ctf.core.event.types.Definition;
-import org.eclipse.linuxtools.ctf.core.event.types.EnumDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.FloatDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.IDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.StringDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDefinition;
-import org.eclipse.linuxtools.internal.ctf.core.SafeMappedByteBuffer;
-import org.eclipse.linuxtools.internal.ctf.core.event.types.ArrayDefinition;
-import org.eclipse.linuxtools.internal.ctf.core.trace.StreamInputPacketIndex;
-import org.eclipse.linuxtools.internal.ctf.core.trace.StreamInputPacketIndexEntry;
-
-/**
- * <b><u>StreamInput</u></b>
- * <p>
- * Represents a trace file that belongs to a certain stream.
- *
- * @since 3.0
- */
-// TODO: remove AutoCloseable
-public class CTFStreamInput implements IDefinitionScope, AutoCloseable {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- /**
- * The associated Stream
- */
- private final CTFStream fStream;
-
- /**
- * Information on the file (used for debugging)
- */
- @NonNull
- private final File fFile;
-
- /**
- * The packet index of this input
- */
- private final StreamInputPacketIndex fIndex;
-
- private long fTimestampEnd;
-
- /**
- * Definition of trace packet header
- */
- private StructDeclaration fTracePacketHeaderDecl = null;
-
- /**
- * Definition of trace stream packet context
- */
- private StructDeclaration fStreamPacketContextDecl = null;
-
- /**
- * Total number of lost events in this stream
- */
- private long fLostSoFar = 0;
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Constructs a StreamInput.
- *
- * @param stream
- * The stream to which this StreamInput belongs to.
- * @param file
- * Information about the trace file (for debugging purposes).
- */
- public CTFStreamInput(CTFStream stream, @NonNull File file) {
- fStream = stream;
- fFile = file;
- fIndex = new StreamInputPacketIndex();
- }
-
- @Override
- public void close() throws IOException {
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- /**
- * Gets the stream the streamInput wrapper is wrapping
- *
- * @return the stream the streamInput wrapper is wrapping
- */
- public CTFStream getStream() {
- return fStream;
- }
-
- /**
- * The common streamInput Index
- *
- * @return the stream input Index
- */
- StreamInputPacketIndex getIndex() {
- return fIndex;
- }
-
- /**
- * Gets the filename of the streamInput file.
- *
- * @return the filename of the streaminput file.
- */
- public String getFilename() {
- return fFile.getName();
- }
-
- /**
- * Gets the last read timestamp of a stream. (this is not necessarily the
- * last time in the stream.)
- *
- * @return the last read timestamp
- */
- public long getTimestampEnd() {
- return fTimestampEnd;
- }
-
- /**
- * Sets the last read timestamp of a stream. (this is not necessarily the
- * last time in the stream.)
- *
- * @param timestampEnd
- * the last read timestamp
- */
- public void setTimestampEnd(long timestampEnd) {
- fTimestampEnd = timestampEnd;
- }
-
- /**
- * Useless for streaminputs
- */
- @Override
- public LexicalScope getScopePath() {
- return LexicalScope.STREAM;
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- @Override
- public Definition lookupDefinition(String lookupPath) {
- /* TODO: lookup in different dynamic scopes is not supported yet. */
- return null;
- }
-
- /**
- * Create the index for this trace file.
- */
- public void setupIndex() {
-
- /*
- * The BitBuffer to extract data from the StreamInput
- */
- BitBuffer bitBuffer = new BitBuffer();
- bitBuffer.setByteOrder(getStream().getTrace().getByteOrder());
-
- /*
- * Create the definitions we need to read the packet headers + contexts
- */
- if (getStream().getTrace().getPacketHeader() != null) {
- fTracePacketHeaderDecl = getStream().getTrace().getPacketHeader();
- }
-
- if (getStream().getPacketContextDecl() != null) {
- fStreamPacketContextDecl = getStream().getPacketContextDecl();
- }
-
- }
-
- /**
- * Adds the next packet header index entry to the index of a stream input.
- *
- * <strong>This method is slow and can corrupt data if not used
- * properly</strong>
- *
- * @return true if there are more packets to add
- * @throws CTFReaderException
- * If there was a problem reading the packed header
- */
- public boolean addPacketHeaderIndex() throws CTFReaderException {
- long currentPos = 0L;
- if (!fIndex.getEntries().isEmpty()) {
- StreamInputPacketIndexEntry pos = fIndex.getEntries().lastElement();
- currentPos = computeNextOffset(pos);
- }
- long fileSize = getStreamSize();
- if (currentPos < fileSize) {
-
- StreamInputPacketIndexEntry packetIndex = new StreamInputPacketIndexEntry(
- currentPos);
- createPacketIndexEntry(fileSize, currentPos, packetIndex);
- fIndex.addEntry(packetIndex);
- return true;
- }
- return false;
- }
-
- private long getStreamSize() {
- return fFile.length();
- }
-
- private long createPacketIndexEntry(long fileSizeBytes, long packetOffsetBytes, StreamInputPacketIndexEntry packetIndex)
- throws CTFReaderException {
-
- long pos = readPacketHeader(fileSizeBytes, packetOffsetBytes, packetIndex);
-
- /* Basic validation */
- if (packetIndex.getContentSizeBits() > packetIndex.getPacketSizeBits()) {
- throw new CTFReaderException("Content size > packet size"); //$NON-NLS-1$
- }
-
- if (packetIndex.getPacketSizeBits() > ((fileSizeBytes - packetIndex
- .getOffsetBytes()) * 8)) {
- throw new CTFReaderException("Not enough data remaining in the file for the size of this packet"); //$NON-NLS-1$
- }
-
- /*
- * Offset in the file, in bits
- */
- packetIndex.setDataOffsetBits(pos);
-
- /*
- * Update the counting packet offset
- */
- return computeNextOffset(packetIndex);
- }
-
- /**
- * @param packetIndex
- * @return
- */
- private static long computeNextOffset(
- StreamInputPacketIndexEntry packetIndex) {
- return packetIndex.getOffsetBytes()
- + ((packetIndex.getPacketSizeBits() + 7) / 8);
- }
-
- private long readPacketHeader(long fileSizeBytes,
- long packetOffsetBytes, StreamInputPacketIndexEntry packetIndex) throws CTFReaderException {
- long position = -1;
- /*
- * Initial size, it should map at least the packet header + context
- * size.
- *
- * TODO: use a less arbitrary size.
- */
- long mapSize = 4096;
- /*
- * If there is less data remaining than what we want to map, reduce the
- * map size.
- */
- if ((fileSizeBytes - packetIndex.getOffsetBytes()) < mapSize) {
- mapSize = fileSizeBytes - packetIndex.getOffsetBytes();
- }
-
- /*
- * Map the packet.
- */
- try (FileChannel fc = FileChannel.open(fFile.toPath(), StandardOpenOption.READ)) {
- ByteBuffer map = SafeMappedByteBuffer.map(fc, MapMode.READ_ONLY, packetOffsetBytes, mapSize);
- if (map == null) {
- throw new CTFReaderException("Failed to allocate mapped byte buffer"); //$NON-NLS-1$
- }
- /*
- * create a packet bit buffer to read the packet header
- */
- BitBuffer bitBuffer = new BitBuffer(map);
- bitBuffer.setByteOrder(getStream().getTrace().getByteOrder());
- /*
- * Read the trace packet header if it exists.
- */
- if (fTracePacketHeaderDecl != null) {
- parseTracePacketHeader(fTracePacketHeaderDecl, bitBuffer);
- }
-
- /*
- * Read the stream packet context if it exists.
- */
- if (fStreamPacketContextDecl != null) {
- parsePacketContext(fileSizeBytes, fStreamPacketContextDecl,
- bitBuffer, packetIndex);
- } else {
- setPacketContextNull(fileSizeBytes, packetIndex);
- }
-
- position = bitBuffer.position();
- } catch (IOException e) {
- throw new CTFReaderException(e);
- }
- return position;
- }
-
- private void parseTracePacketHeader(StructDeclaration tracePacketHeaderDecl,
- @NonNull BitBuffer bitBuffer) throws CTFReaderException {
- StructDefinition tracePacketHeaderDef = tracePacketHeaderDecl.createDefinition(fStream.getTrace(), LexicalScope.TRACE_PACKET_HEADER, bitBuffer);
-
- /*
- * Check the CTF magic number
- */
- IntegerDefinition magicDef = (IntegerDefinition) tracePacketHeaderDef
- .lookupDefinition("magic"); //$NON-NLS-1$
- if (magicDef != null) {
- int magic = (int) magicDef.getValue();
- if (magic != Utils.CTF_MAGIC) {
- throw new CTFReaderException(
- "CTF magic mismatch " + Integer.toHexString(magic) + " vs " + Integer.toHexString(Utils.CTF_MAGIC)); //$NON-NLS-1$//$NON-NLS-2$
- }
- }
-
- /*
- * Check the trace UUID
- */
- ArrayDefinition uuidDef =
- (ArrayDefinition) tracePacketHeaderDef.lookupDefinition("uuid"); //$NON-NLS-1$
- if (uuidDef != null) {
- UUID uuid = Utils.getUUIDfromDefinition(uuidDef);
-
- if (!getStream().getTrace().getUUID().equals(uuid)) {
- throw new CTFReaderException("UUID mismatch"); //$NON-NLS-1$
- }
- }
-
- /*
- * Check that the stream id did not change
- */
- IntegerDefinition streamIDDef = (IntegerDefinition) tracePacketHeaderDef
- .lookupDefinition("stream_id"); //$NON-NLS-1$
- if (streamIDDef != null) {
- long streamID = streamIDDef.getValue();
-
- if (streamID != getStream().getId()) {
- throw new CTFReaderException("Stream ID changing within a StreamInput"); //$NON-NLS-1$
- }
- }
- }
-
- /**
- * Gets the wrapped file
- *
- * @return the file
- */
- @NonNull
- File getFile() {
- return fFile;
- }
-
- private static void setPacketContextNull(long fileSizeBytes,
- StreamInputPacketIndexEntry packetIndex) {
- /*
- * If there is no packet context, infer the content and packet size from
- * the file size (assume that there is only one packet and no padding)
- */
- packetIndex.setContentSizeBits(fileSizeBytes * 8);
- packetIndex.setPacketSizeBits(fileSizeBytes * 8);
- }
-
- private void parsePacketContext(long fileSizeBytes,
- StructDeclaration streamPacketContextDecl, @NonNull BitBuffer bitBuffer,
- StreamInputPacketIndexEntry packetIndex) throws CTFReaderException {
- StructDefinition streamPacketContextDef = streamPacketContextDecl.createDefinition(this, LexicalScope.STREAM_PACKET_CONTEXT, bitBuffer);
-
- for (String field : streamPacketContextDef.getDeclaration()
- .getFieldsList()) {
- IDefinition id = streamPacketContextDef.lookupDefinition(field);
- if (id instanceof IntegerDefinition) {
- packetIndex.addAttribute(field,
- ((IntegerDefinition) id).getValue());
- } else if (id instanceof FloatDefinition) {
- packetIndex.addAttribute(field,
- ((FloatDefinition) id).getValue());
- } else if (id instanceof EnumDefinition) {
- packetIndex.addAttribute(field,
- ((EnumDefinition) id).getValue());
- } else if (id instanceof StringDefinition) {
- packetIndex.addAttribute(field,
- ((StringDefinition) id).getValue());
- }
- }
-
- Long contentSize = (Long) packetIndex.lookupAttribute("content_size"); //$NON-NLS-1$
- Long packetSize = (Long) packetIndex.lookupAttribute("packet_size"); //$NON-NLS-1$
- Long tsBegin = (Long) packetIndex.lookupAttribute("timestamp_begin"); //$NON-NLS-1$
- Long tsEnd = (Long) packetIndex.lookupAttribute("timestamp_end"); //$NON-NLS-1$
- String device = (String) packetIndex.lookupAttribute("device"); //$NON-NLS-1$
- // LTTng Specific
- Long cpuId = (Long) packetIndex.lookupAttribute("cpu_id"); //$NON-NLS-1$
- Long lostEvents = (Long) packetIndex.lookupAttribute("events_discarded"); //$NON-NLS-1$
-
- /* Read the content size in bits */
- if (contentSize != null) {
- packetIndex.setContentSizeBits(contentSize.intValue());
- } else if (packetSize != null) {
- packetIndex.setContentSizeBits(packetSize.longValue());
- } else {
- packetIndex.setContentSizeBits((int) (fileSizeBytes * 8));
- }
-
- /* Read the packet size in bits */
- if (packetSize != null) {
- packetIndex.setPacketSizeBits(packetSize.intValue());
- } else if (packetIndex.getContentSizeBits() != 0) {
- packetIndex.setPacketSizeBits(packetIndex.getContentSizeBits());
- } else {
- packetIndex.setPacketSizeBits((int) (fileSizeBytes * 8));
- }
-
- /* Read the begin timestamp */
- if (tsBegin != null) {
- packetIndex.setTimestampBegin(tsBegin.longValue());
- }
-
- /* Read the end timestamp */
- if (tsEnd != null) {
- if (tsEnd == -1) {
- tsEnd = Long.MAX_VALUE;
- }
- packetIndex.setTimestampEnd(tsEnd.longValue());
- setTimestampEnd(packetIndex.getTimestampEnd());
- }
-
- if (device != null) {
- packetIndex.setTarget(device);
- }
-
- if (cpuId != null) {
- packetIndex.setTarget("CPU" + cpuId.toString()); //$NON-NLS-1$
- }
-
- if (lostEvents != null) {
- packetIndex.setLostEvents(lostEvents - fLostSoFar);
- fLostSoFar = lostEvents;
- }
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = (prime * result) + fFile.hashCode();
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (!(obj instanceof CTFStreamInput)) {
- return false;
- }
- CTFStreamInput other = (CTFStreamInput) obj;
- if (!fFile.equals(other.fFile)) {
- return false;
- }
- return true;
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-package org.eclipse.linuxtools.ctf.core.trace;
-
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.nio.channels.FileChannel.MapMode;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.jdt.annotation.Nullable;
-import org.eclipse.linuxtools.ctf.core.CTFStrings;
-import org.eclipse.linuxtools.ctf.core.event.EventDefinition;
-import org.eclipse.linuxtools.ctf.core.event.IEventDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.event.scope.LexicalScope;
-import org.eclipse.linuxtools.ctf.core.event.types.Definition;
-import org.eclipse.linuxtools.ctf.core.event.types.ICompositeDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.IDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.IEventHeaderDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.SimpleDatatypeDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.VariantDefinition;
-import org.eclipse.linuxtools.internal.ctf.core.SafeMappedByteBuffer;
-import org.eclipse.linuxtools.internal.ctf.core.event.EventDeclaration;
-import org.eclipse.linuxtools.internal.ctf.core.event.types.composite.EventHeaderDefinition;
-import org.eclipse.linuxtools.internal.ctf.core.trace.StreamInputPacketIndexEntry;
-
-import com.google.common.collect.ImmutableList;
-
-/**
- * CTF trace packet reader. Reads the events of a packet of a trace file.
- *
- * @author Matthew Khouzam
- * @author Simon Marchi
- * @since 3.0
- */
-public class CTFStreamInputPacketReader implements IDefinitionScope, AutoCloseable {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- /** BitBuffer used to read the trace file. */
- @Nullable
- private BitBuffer fBitBuffer;
-
- /** StreamInputReader that uses this StreamInputPacketReader. */
- private final CTFStreamInputReader fStreamInputReader;
-
- /** Trace packet header. */
- private final StructDeclaration fTracePacketHeaderDecl;
-
- /** Stream packet context definition. */
- private final StructDeclaration fStreamPacketContextDecl;
-
- /** Stream event header definition. */
- private final IDeclaration fStreamEventHeaderDecl;
-
- /** Stream event context definition. */
- private final StructDeclaration fStreamEventContextDecl;
-
- private ICompositeDefinition fCurrentTracePacketHeaderDef;
- private ICompositeDefinition fCurrentStreamEventHeaderDef;
- private ICompositeDefinition fCurrentStreamPacketContextDef;
- /** Reference to the index entry of the current packet. */
- private StreamInputPacketIndexEntry fCurrentPacket = null;
-
- /**
- * Last timestamp recorded.
- *
- * Needed to calculate the complete timestamp values for the events with
- * compact headers.
- */
- private long fLastTimestamp = 0;
-
- /** CPU id of current packet. */
- private int fCurrentCpu = 0;
-
- private int fLostEventsInThisPacket;
-
- private long fLostEventsDuration;
-
- private boolean fHasLost = false;
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Constructs a StreamInputPacketReader.
- *
- * @param streamInputReader
- * The StreamInputReader to which this packet reader belongs to.
- */
- public CTFStreamInputPacketReader(CTFStreamInputReader streamInputReader) {
- fStreamInputReader = streamInputReader;
-
- /* Set the BitBuffer's byte order. */
- ByteBuffer allocateDirect = ByteBuffer.allocateDirect(0);
- if (allocateDirect == null) {
- throw new IllegalStateException("Unable to allocate 0 bytes!"); //$NON-NLS-1$
- }
- fBitBuffer = new BitBuffer(allocateDirect);
-
- final CTFStream currentStream = streamInputReader.getStreamInput().getStream();
- fTracePacketHeaderDecl = currentStream.getTrace().getPacketHeader();
- fStreamPacketContextDecl = currentStream.getPacketContextDecl();
- fStreamEventHeaderDecl = currentStream.getEventHeaderDeclaration();
- fStreamEventContextDecl = currentStream.getEventContextDecl();
- }
-
- /**
- * Get the event context defintiion
- *
- * @param input
- * the bitbuffer to read from
- * @return an context definition, can be null
- * @throws CTFReaderException
- * out of bounds exception or such
- */
- public StructDefinition getEventContextDefinition(@NonNull BitBuffer input) throws CTFReaderException {
- return fStreamEventContextDecl.createDefinition(fStreamInputReader.getStreamInput(), LexicalScope.STREAM_EVENT_CONTEXT, input);
- }
-
- /**
- * Get the stream context defintiion
- *
- * @param input
- * the bitbuffer to read from
- * @return an context definition, can be null
- * @throws CTFReaderException
- * out of bounds exception or such
- * @deprecated it was not used
- */
- @Deprecated
- public StructDefinition getStreamEventHeaderDefinition(@NonNull BitBuffer input) throws CTFReaderException {
- if (!(fStreamEventHeaderDecl instanceof StructDeclaration)) {
- throw new IllegalStateException("Definition is not a struct definition, this is a deprecated method that doesn't work so well, stop using it."); //$NON-NLS-1$
- }
- return ((StructDeclaration) fStreamEventHeaderDecl).createDefinition(this, LexicalScope.STREAM_EVENT_HEADER, input);
- }
-
- /**
- * Get the packet context defintiion
- *
- * @param input
- * the bitbuffer to read from
- * @return an context definition, can be null
- * @throws CTFReaderException
- * out of bounds exception or such
- */
- public StructDefinition getStreamPacketContextDefinition(@NonNull BitBuffer input) throws CTFReaderException {
- return fStreamPacketContextDecl.createDefinition(fStreamInputReader.getStreamInput(), LexicalScope.STREAM_PACKET_CONTEXT, input);
- }
-
- /**
- * Get the event header defintiion
- *
- * @param input
- * the bitbuffer to read from
- * @return an header definition, can be null
- * @throws CTFReaderException
- * out of bounds exception or such
- */
- public StructDefinition getTracePacketHeaderDefinition(@NonNull BitBuffer input) throws CTFReaderException {
- return fTracePacketHeaderDecl.createDefinition(fStreamInputReader.getStreamInput().getStream().getTrace(), LexicalScope.TRACE_PACKET_HEADER, input);
- }
-
- /**
- * Dispose the StreamInputPacketReader
- */
- @Override
- public void close() {
- fBitBuffer = null;
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- /**
- * Gets the current packet
- *
- * @return the current packet
- */
- StreamInputPacketIndexEntry getCurrentPacket() {
- return fCurrentPacket;
- }
-
- /**
- * Gets the CPU (core) number
- *
- * @return the CPU (core) number
- */
- public int getCPU() {
- return fCurrentCpu;
- }
-
- @Override
- public LexicalScope getScopePath() {
- return LexicalScope.PACKET;
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- @NonNull
- private ByteBuffer getByteBufferAt(long position, long size) throws CTFReaderException, IOException {
- ByteBuffer map = SafeMappedByteBuffer.map(fStreamInputReader.getFc(), MapMode.READ_ONLY, position, size);
- if (map == null) {
- throw new CTFReaderException("Failed to allocate mapped byte buffer"); //$NON-NLS-1$
- }
- return map;
- }
- /**
- * Changes the current packet to the given one.
- *
- * @param currentPacket
- * The index entry of the packet to switch to.
- * @throws CTFReaderException
- * If we get an error reading the packet
- */
- void setCurrentPacket(StreamInputPacketIndexEntry currentPacket) throws CTFReaderException {
- StreamInputPacketIndexEntry prevPacket = null;
- fCurrentPacket = currentPacket;
-
- if (fCurrentPacket != null) {
- /*
- * Change the map of the BitBuffer.
- */
- ByteBuffer bb = null;
- try {
- bb = getByteBufferAt(
- fCurrentPacket.getOffsetBytes(),
- (fCurrentPacket.getPacketSizeBits() + 7) / 8);
- } catch (IOException e) {
- throw new CTFReaderException(e.getMessage(), e);
- }
-
- BitBuffer bitBuffer = new BitBuffer(bb);
- fBitBuffer = bitBuffer;
- /*
- * Read trace packet header.
- */
- if (fTracePacketHeaderDecl != null) {
- fCurrentTracePacketHeaderDef = getTracePacketHeaderDefinition(bitBuffer);
- }
-
- /*
- * Read stream packet context.
- */
- if (fStreamPacketContextDecl != null) {
- fCurrentStreamPacketContextDef = getStreamPacketContextDefinition(bitBuffer);
-
- /* Read CPU ID */
- if (getCurrentPacket().getTarget() != null) {
- fCurrentCpu = (int) getCurrentPacket().getTargetId();
- }
-
- /* Read number of lost events */
- fLostEventsInThisPacket = (int) getCurrentPacket().getLostEvents();
- if (fLostEventsInThisPacket != 0) {
- fHasLost = true;
- /*
- * Compute the duration of the lost event time range. If the
- * current packet is the first packet, duration will be set
- * to 1.
- */
- long lostEventsStartTime;
- int index = fStreamInputReader.getStreamInput().getIndex().getEntries().indexOf(currentPacket);
- if (index == 0) {
- lostEventsStartTime = currentPacket.getTimestampBegin() + 1;
- } else {
- prevPacket = fStreamInputReader.getStreamInput().getIndex().getEntries().get(index - 1);
- lostEventsStartTime = prevPacket.getTimestampEnd();
- }
- fLostEventsDuration = Math.abs(lostEventsStartTime - currentPacket.getTimestampBegin());
- }
- }
-
- /*
- * Use the timestamp begin of the packet as the reference for the
- * timestamp reconstitution.
- */
- fLastTimestamp = currentPacket.getTimestampBegin();
- } else {
- fBitBuffer = null;
- fLastTimestamp = 0;
- }
- }
-
- /**
- * Returns whether it is possible to read any more events from this packet.
- *
- * @return True if it is possible to read any more events from this packet.
- */
- public boolean hasMoreEvents() {
- BitBuffer bitBuffer = fBitBuffer;
- StreamInputPacketIndexEntry currentPacket = fCurrentPacket;
- if (currentPacket != null && bitBuffer != null) {
- return fHasLost || (bitBuffer.position() < currentPacket.getContentSizeBits());
- }
- return false;
- }
-
- /**
- * Reads the next event of the packet into the right event definition.
- *
- * @return The event definition containing the event data that was just
- * read.
- * @throws CTFReaderException
- * If there was a problem reading the trace
- */
- public EventDefinition readNextEvent() throws CTFReaderException {
- /* Default values for those fields */
- // compromise since we cannot have 64 bit addressing of arrays yet.
- int eventID = (int) EventDeclaration.UNSET_EVENT_ID;
- long timestamp = 0;
- if (fHasLost) {
- fHasLost = false;
- EventDeclaration lostEventDeclaration = EventDeclaration.getLostEventDeclaration();
- StructDeclaration lostFields = lostEventDeclaration.getFields();
- // this is a hard coded map, we know it's not null
- IntegerDeclaration lostFieldsDecl = (IntegerDeclaration) lostFields.getField(CTFStrings.LOST_EVENTS_FIELD);
- if (lostFieldsDecl == null)
- {
- throw new IllegalStateException("Lost events count not declared!"); //$NON-NLS-1$
- }
- IntegerDeclaration lostEventsDurationDecl = (IntegerDeclaration) lostFields.getField(CTFStrings.LOST_EVENTS_DURATION);
- if (lostEventsDurationDecl == null) {
- throw new IllegalStateException("Lost events duration not declared!"); //$NON-NLS-1$
- }
- IntegerDefinition lostDurationDef = new IntegerDefinition(lostFieldsDecl, null, CTFStrings.LOST_EVENTS_DURATION, fLostEventsDuration);
- IntegerDefinition lostCountDef = new IntegerDefinition(lostEventsDurationDecl, null, CTFStrings.LOST_EVENTS_FIELD, fLostEventsInThisPacket);
- IntegerDefinition[] fields = new IntegerDefinition[] { lostCountDef, lostDurationDef };
- /* this is weird notation, but it's the java notation */
- final ImmutableList<String> fieldNameList = ImmutableList.<String> builder().add(CTFStrings.LOST_EVENTS_FIELD).add(CTFStrings.LOST_EVENTS_DURATION).build();
- return new EventDefinition(
- lostEventDeclaration,
- fStreamInputReader,
- fLastTimestamp,
- null,
- null,
- null,
- new StructDefinition(
- lostFields,
- this, "fields", //$NON-NLS-1$
- fieldNameList,
- fields
- ));
-
- }
-
- final BitBuffer currentBitBuffer = fBitBuffer;
- if (currentBitBuffer == null) {
- return null;
- }
- final long posStart = currentBitBuffer.position();
- /* Read the stream event header. */
- if (fStreamEventHeaderDecl != null) {
- if (fStreamEventHeaderDecl instanceof IEventHeaderDeclaration) {
- fCurrentStreamEventHeaderDef = (ICompositeDefinition) fStreamEventHeaderDecl.createDefinition(null, "", currentBitBuffer); //$NON-NLS-1$
- EventHeaderDefinition ehd = (EventHeaderDefinition) fCurrentStreamEventHeaderDef;
- eventID = ehd.getId();
- timestamp = calculateTimestamp(ehd.getTimestamp(), ehd.getTimestampLength());
- } else {
- fCurrentStreamEventHeaderDef = ((StructDeclaration) fStreamEventHeaderDecl).createDefinition(null, LexicalScope.EVENT_HEADER, currentBitBuffer);
- StructDefinition StructEventHeaderDef = (StructDefinition) fCurrentStreamEventHeaderDef;
- /* Check for the event id. */
- IDefinition idDef = StructEventHeaderDef.lookupDefinition("id"); //$NON-NLS-1$
- SimpleDatatypeDefinition simpleIdDef = null;
- if (idDef instanceof SimpleDatatypeDefinition) {
- simpleIdDef = ((SimpleDatatypeDefinition) idDef);
- } else if (idDef != null) {
- throw new CTFReaderException("Id defintion not an integer, enum or float definiton in event header."); //$NON-NLS-1$
- }
-
- /*
- * Get the timestamp from the event header (may be overridden
- * later on)
- */
- IntegerDefinition timestampDef = StructEventHeaderDef.lookupInteger("timestamp"); //$NON-NLS-1$
-
- /* Check for the variant v. */
- IDefinition variantDef = StructEventHeaderDef.lookupDefinition("v"); //$NON-NLS-1$
- if (variantDef instanceof VariantDefinition) {
-
- /* Get the variant current field */
- StructDefinition variantCurrentField = (StructDefinition) ((VariantDefinition) variantDef).getCurrentField();
-
- /*
- * Try to get the id field in the current field of the
- * variant. If it is present, it overrides the previously
- * read event id.
- */
- IDefinition vIdDef = variantCurrentField.lookupDefinition("id"); //$NON-NLS-1$
- if (vIdDef instanceof IntegerDefinition) {
- simpleIdDef = (SimpleDatatypeDefinition) vIdDef;
- }
-
- /*
- * Get the timestamp. This would overwrite any previous
- * timestamp definition
- */
- timestampDef = variantCurrentField.lookupInteger("timestamp"); //$NON-NLS-1$
- }
- if (simpleIdDef != null) {
- eventID = simpleIdDef.getIntegerValue().intValue();
- }
- if (timestampDef != null) {
- timestamp = calculateTimestamp(timestampDef);
- } // else timestamp remains 0
- }
- }
- /* Get the right event definition using the event id. */
- IEventDeclaration eventDeclaration = fStreamInputReader.getStreamInput().getStream().getEventDeclaration(eventID);
- if (eventDeclaration == null) {
- throw new CTFReaderException("Incorrect event id : " + eventID); //$NON-NLS-1$
- }
- EventDefinition eventDef = eventDeclaration.createDefinition(fStreamInputReader, currentBitBuffer, timestamp);
-
- /*
- * Set the event timestamp using the timestamp calculated by
- * updateTimestamp.
- */
-
- if (posStart == currentBitBuffer.position()) {
- throw new CTFReaderException("Empty event not allowed, event: " + eventDef.getDeclaration().getName()); //$NON-NLS-1$
- }
-
- return eventDef;
- }
-
- /**
- * Calculates the timestamp value of the event, possibly using the timestamp
- * from the last event.
- *
- * @param timestampDef
- * Integer definition of the timestamp.
- * @return The calculated timestamp value.
- */
- private long calculateTimestamp(IntegerDefinition timestampDef) {
- int len = timestampDef.getDeclaration().getLength();
- final long value = timestampDef.getValue();
-
- return calculateTimestamp(value, len);
- }
-
- private long calculateTimestamp(final long value, int len) {
- long newval;
- long majorasbitmask;
- /*
- * If the timestamp length is 64 bits, it is a full timestamp.
- */
- if (len == 64) {
- fLastTimestamp = value;
- return fLastTimestamp;
- }
-
- /*
- * Bit mask to keep / remove all old / new bits.
- */
- majorasbitmask = (1L << len) - 1;
-
- /*
- * If the new value is smaller than the corresponding bits of the last
- * timestamp, we assume an overflow of the compact representation.
- */
- newval = value;
- if (newval < (fLastTimestamp & majorasbitmask)) {
- newval = newval + (1L << len);
- }
-
- /* Keep only the high bits of the old value */
- fLastTimestamp = fLastTimestamp & ~majorasbitmask;
-
- /* Then add the low bits of the new value */
- fLastTimestamp = fLastTimestamp + newval;
-
- return fLastTimestamp;
- }
-
- @Override
- public Definition lookupDefinition(String lookupPath) {
- if (lookupPath.equals(LexicalScope.STREAM_PACKET_CONTEXT.toString())) {
- return (Definition) fCurrentStreamPacketContextDef;
- }
- if (lookupPath.equals(LexicalScope.TRACE_PACKET_HEADER.toString())) {
- return (Definition) fCurrentTracePacketHeaderDef;
- }
- return null;
- }
-
- /**
- * Get stream event header
- *
- * @return the stream event header
- * @deprecated use
- * {@link CTFStreamInputPacketReader#getStreamEventHeaderDefinition()}
- */
- @Deprecated
- public StructDefinition getCurrentStreamEventHeader() {
- return (StructDefinition) ((fCurrentStreamEventHeaderDef instanceof StructDefinition) ? fCurrentStreamEventHeaderDef : null);
- }
-
- /**
- * Get stream event header
- *
- * @return the stream event header
- * @since 3.1
- */
- public ICompositeDefinition getStreamEventHeaderDefinition() {
- return fCurrentStreamEventHeaderDef;
- }
-
- /**
- * Get the current packet event header
- *
- * @return the current packet event header
- */
- public StructDefinition getCurrentPacketEventHeader() {
- if (fCurrentTracePacketHeaderDef instanceof StructDefinition) {
- return (StructDefinition) fCurrentTracePacketHeaderDef;
- }
- return null;
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.trace;
-
-import java.io.File;
-import java.io.IOException;
-import java.nio.ByteOrder;
-import java.nio.channels.FileChannel;
-import java.nio.file.StandardOpenOption;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.EventDefinition;
-import org.eclipse.linuxtools.ctf.core.event.IEventDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-import org.eclipse.linuxtools.internal.ctf.core.Activator;
-import org.eclipse.linuxtools.internal.ctf.core.trace.StreamInputPacketIndexEntry;
-
-import com.google.common.collect.ImmutableList;
-
-/**
- * A CTF trace event reader. Reads the events of a trace file.
- *
- * @author Matthew Khouzam
- * @author Simon Marchi
- * @since 3.0
- */
-public class CTFStreamInputReader implements AutoCloseable {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- /**
- * The StreamInput we are reading.
- */
- private final @NonNull File fFile;
-
- private final @NonNull CTFStreamInput fStreamInput;
-
- private final FileChannel fFileChannel;
-
- /**
- * The packet reader used to read packets from this trace file.
- */
- private final CTFStreamInputPacketReader fPacketReader;
-
- /**
- * Iterator on the packet index
- */
- private int fPacketIndex;
-
- /**
- * Reference to the current event of this trace file (iow, the last on that
- * was read, the next one to be returned)
- */
- private EventDefinition fCurrentEvent = null;
-
- private int fId;
-
- private CTFTraceReader fParent;
-
- /**
- * Live trace reading
- */
- private boolean fLive = false;
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
- /**
- * Constructs a StreamInputReader that reads a StreamInput.
- *
- * @param streamInput
- * The StreamInput to read.
- * @throws CTFReaderException
- * If the file cannot be opened
- */
- public CTFStreamInputReader(CTFStreamInput streamInput) throws CTFReaderException {
- if (streamInput == null) {
- throw new IllegalArgumentException("stream cannot be null"); //$NON-NLS-1$
- }
- fStreamInput = streamInput;
- fFile = fStreamInput.getFile();
- try {
- fFileChannel = FileChannel.open(fFile.toPath(), StandardOpenOption.READ);
- } catch (IOException e) {
- throw new CTFReaderException(e);
- }
- fPacketReader = new CTFStreamInputPacketReader(this);
- /*
- * Get the iterator on the packet index.
- */
- fPacketIndex = 0;
- /*
- * Make first packet the current one.
- */
- goToNextPacket();
- }
-
- /**
- * Dispose the StreamInputReader, closes the file channel and its packet
- * reader
- *
- * @throws IOException
- * If an I/O error occurs
- */
- @Override
- public void close() throws IOException {
- fFileChannel.close();
- fPacketReader.close();
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- /**
- * Gets the current event in this stream
- *
- * @return the current event in the stream, null if the stream is
- * finished/empty/malformed
- */
- public EventDefinition getCurrentEvent() {
- return fCurrentEvent;
- }
-
- /**
- * Gets the byte order for a trace
- *
- * @return the trace byte order
- */
- public ByteOrder getByteOrder() {
- return fStreamInput.getStream().getTrace().getByteOrder();
- }
-
- /**
- * Gets the name of the stream (it's an id and a number)
- *
- * @return gets the stream name (it's a number)
- */
- public int getName() {
- return fId;
- }
-
- /**
- * Sets the name of the stream
- *
- * @param name
- * the name of the stream, (it's a number)
- */
- public void setName(int name) {
- fId = name;
- }
-
- /**
- * Gets the CPU of a stream. It's the same as the one in /proc or running
- * the asm CPUID instruction
- *
- * @return The CPU id (a number)
- */
- public int getCPU() {
- return fPacketReader.getCPU();
- }
-
- /**
- * Gets the filename of the stream being read
- *
- * @return The filename of the stream being read
- */
- public String getFilename() {
- return fStreamInput.getFilename();
- }
-
- /*
- * for internal use only
- */
- CTFStreamInput getStreamInput() {
- return fStreamInput;
- }
-
- /**
- * Gets the event definition set for this StreamInput
- *
- * @return Unmodifiable set with the event definitions
- */
- public Iterable<IEventDeclaration> getEventDeclarations() {
- return ImmutableList.copyOf(fStreamInput.getStream().getEventDeclarations());
- }
-
- /**
- * Set the trace to live mode
- *
- * @param live
- * whether the trace is read live or not
- */
- public void setLive(boolean live) {
- fLive = live;
- }
-
- /**
- * Get if the trace is to read live or not
- *
- * @return whether the trace is live or not
- */
- public boolean isLive() {
- return fLive;
- }
-
- /**
- * Get the event context of the stream
- *
- * @return the event context declaration of the stream
- */
- public StructDeclaration getStreamEventContextDecl() {
- return getStreamInput().getStream().getEventContextDecl();
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
- /**
- * Reads the next event in the current event variable.
- *
- * @return If an event has been successfully read.
- * @throws CTFReaderException
- * if an error occurs
- */
- public CTFResponse readNextEvent() throws CTFReaderException {
-
- /*
- * Change packet if needed
- */
- if (!fPacketReader.hasMoreEvents()) {
- final StreamInputPacketIndexEntry prevPacket = fPacketReader
- .getCurrentPacket();
- if (prevPacket != null || fLive) {
- goToNextPacket();
- }
-
- }
-
- /*
- * If an event is available, read it.
- */
- if (fPacketReader.hasMoreEvents()) {
- setCurrentEvent(fPacketReader.readNextEvent());
- return CTFResponse.OK;
- }
- this.setCurrentEvent(null);
- return fLive ? CTFResponse.WAIT : CTFResponse.FINISH;
- }
-
- /**
- * Change the current packet of the packet reader to the next one.
- *
- * @throws CTFReaderException
- * if an error occurs
- */
- private void goToNextPacket() throws CTFReaderException {
- fPacketIndex++;
- // did we already index the packet?
- if (getPacketSize() >= (fPacketIndex + 1)) {
- fPacketReader.setCurrentPacket(getPacket());
- } else {
- // go to the next packet if there is one, index it at the same time
- if (fStreamInput.addPacketHeaderIndex()) {
- fPacketIndex = getPacketSize() - 1;
- fPacketReader.setCurrentPacket(getPacket());
- } else {
- // out of packets
- fPacketReader.setCurrentPacket(null);
- }
- }
- }
-
- /**
- * @return
- */
- private int getPacketSize() {
- return fStreamInput.getIndex().getEntries().size();
- }
-
- /**
- * Changes the location of the trace file reader so that the current event
- * is the first event with a timestamp greater or equal the given timestamp.
- *
- * @param timestamp
- * The timestamp to seek to.
- * @return The offset compared to the current position
- * @throws CTFReaderException
- * if an error occurs
- */
- public long seek(long timestamp) throws CTFReaderException {
- long offset = 0;
-
- gotoPacket(timestamp);
-
- /*
- * index up to the desired timestamp.
- */
- while ((fPacketReader.getCurrentPacket() != null)
- && (fPacketReader.getCurrentPacket().getTimestampEnd() < timestamp)) {
- try {
- fStreamInput.addPacketHeaderIndex();
- goToNextPacket();
- } catch (CTFReaderException e) {
- // do nothing here
- Activator.log(e.getMessage());
- }
- }
- if (fPacketReader.getCurrentPacket() == null) {
- gotoPacket(timestamp);
- }
-
- /*
- * Advance until either of these conditions are met:
- *
- * - reached the end of the trace file (the given timestamp is after the
- * last event)
- *
- * - found the first event with a timestamp greater or equal the given
- * timestamp.
- */
- readNextEvent();
- boolean done = (this.getCurrentEvent() == null);
- while (!done && (this.getCurrentEvent().getTimestamp() < timestamp)) {
- readNextEvent();
- done = (this.getCurrentEvent() == null);
- offset++;
- }
- return offset;
- }
-
- /**
- * @param timestamp
- * the time to seek
- * @throws CTFReaderException
- * if an error occurs
- */
- private void gotoPacket(long timestamp) throws CTFReaderException {
- fPacketIndex = fStreamInput.getIndex().search(timestamp)
- .previousIndex();
- /*
- * Switch to this packet.
- */
- goToNextPacket();
- }
-
- /**
- * Seeks the last event of a stream and returns it.
- *
- * @throws CTFReaderException
- * if an error occurs
- */
- public void goToLastEvent() throws CTFReaderException {
- /*
- * Search in the index for the packet to search in.
- */
- final int len = fStreamInput.getIndex().getEntries().size();
-
- /*
- * Go to beginning of trace.
- */
- seek(0);
- /*
- * if the trace is empty.
- */
- if ((len == 0) || (fPacketReader.hasMoreEvents() == false)) {
- /*
- * This means the trace is empty. abort.
- */
- return;
- }
- /*
- * Go to the last packet that contains events.
- */
- for (int pos = len - 1; pos > 0; pos--) {
- fPacketIndex = pos;
- fPacketReader.setCurrentPacket(getPacket());
- if (fPacketReader.hasMoreEvents()) {
- break;
- }
- }
-
- /*
- * Go until the end of that packet
- */
- EventDefinition prevEvent = null;
- while (fCurrentEvent != null) {
- prevEvent = fCurrentEvent;
- this.readNextEvent();
- }
- /*
- * Go back to the previous event
- */
- this.setCurrentEvent(prevEvent);
- }
-
- /**
- * @return the parent
- */
- public CTFTraceReader getParent() {
- return fParent;
- }
-
- /**
- * @param parent
- * the parent to set
- */
- public void setParent(CTFTraceReader parent) {
- fParent = parent;
- }
-
- /**
- * Sets the current event in a stream input reader
- *
- * @param currentEvent
- * the event to set
- */
- public void setCurrentEvent(EventDefinition currentEvent) {
- fCurrentEvent = currentEvent;
- }
-
- /**
- * @return the packetIndexIt
- */
- private int getPacketIndex() {
- return fPacketIndex;
- }
-
- private StreamInputPacketIndexEntry getPacket() {
- return fStreamInput.getIndex().getEntries().get(getPacketIndex());
- }
-
- /**
- * Get the file channel wrapped by this reader
- *
- * @return the file channel
- */
- FileChannel getFc() {
- return fFileChannel;
- }
-
- /**
- * @return the packetReader
- */
- public CTFStreamInputPacketReader getPacketReader() {
- return fPacketReader;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = (prime * result) + fId;
- result = (prime * result)
- + fFile.hashCode();
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (!(obj instanceof CTFStreamInputReader)) {
- return false;
- }
- CTFStreamInputReader other = (CTFStreamInputReader) obj;
- if (fId != other.fId) {
- return false;
- }
- return fFile.equals(other.fFile);
- }
-
- @Override
- public String toString() {
- // this helps debugging
- return fId + ' ' + fCurrentEvent.toString();
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- * Alexandre Montplaisir - Initial API and implementation
- * Simon Delisle - Replace LinkedList by TreeSet in callsitesByName attribute
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.trace;
-
-import java.io.File;
-import java.io.FileFilter;
-import java.io.IOException;
-import java.io.Serializable;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.nio.channels.FileChannel;
-import java.nio.channels.FileChannel.MapMode;
-import java.nio.file.StandardOpenOption;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-import java.util.UUID;
-
-import org.eclipse.linuxtools.ctf.core.event.CTFCallsite;
-import org.eclipse.linuxtools.ctf.core.event.CTFClock;
-import org.eclipse.linuxtools.ctf.core.event.IEventDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.event.scope.LexicalScope;
-import org.eclipse.linuxtools.ctf.core.event.types.Definition;
-import org.eclipse.linuxtools.ctf.core.event.types.IDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDefinition;
-import org.eclipse.linuxtools.internal.ctf.core.SafeMappedByteBuffer;
-import org.eclipse.linuxtools.internal.ctf.core.event.CTFCallsiteComparator;
-import org.eclipse.linuxtools.internal.ctf.core.event.metadata.exceptions.ParseException;
-import org.eclipse.linuxtools.internal.ctf.core.event.types.ArrayDefinition;
-
-/**
- * A CTF trace on the file system.
- *
- * Represents a trace on the filesystem. It is responsible of parsing the
- * metadata, creating declarations data structures, indexing the event packets
- * (in other words, all the work that can be shared between readers), but the
- * actual reading of events is left to TraceReader.
- *
- * @author Matthew Khouzam
- * @version $Revision: 1.0 $
- */
-public class CTFTrace implements IDefinitionScope, AutoCloseable {
-
- @Override
- public String toString() {
- /* Only for debugging, shouldn't be externalized */
- return "CTFTrace [path=" + fPath + ", major=" + fMajor + ", minor=" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- + fMinor + ", uuid=" + fUuid + "]"; //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /**
- * The trace directory on the filesystem.
- */
- private final File fPath;
-
- /**
- * Major CTF version number
- */
- private Long fMajor;
-
- /**
- * Minor CTF version number
- */
- private Long fMinor;
-
- /**
- * Trace UUID
- */
- private UUID fUuid;
-
- /**
- * Trace byte order
- */
- private ByteOrder fByteOrder;
-
- /**
- * Packet header structure declaration
- */
- private StructDeclaration fPacketHeaderDecl = null;
-
- /**
- * The clock of the trace
- */
- private CTFClock fSingleClock = null;
-
- /**
- * Packet header structure definition
- *
- * This is only used when opening the trace files, to read the first packet
- * header and see if they are valid trace files.
- */
- private StructDefinition fPacketHeaderDef;
-
- /**
- * Collection of streams contained in the trace.
- */
- private final Map<Long, CTFStream> fStreams = new HashMap<>();
-
- /**
- * Collection of environment variables set by the tracer
- */
- private final Map<String, String> fEnvironment = new HashMap<>();
-
- /**
- * Collection of all the clocks in a system.
- */
- private final Map<String, CTFClock> fClocks = new HashMap<>();
-
- /** Handlers for the metadata files */
- private static final FileFilter METADATA_FILE_FILTER = new MetadataFileFilter();
- private static final Comparator<File> METADATA_COMPARATOR = new MetadataComparator();
-
- /** Callsite helpers */
- private CTFCallsiteComparator fCtfCallsiteComparator = new CTFCallsiteComparator();
-
- private Map<String, TreeSet<CTFCallsite>> fCallsitesByName = new HashMap<>();
-
- /** Callsite helpers */
- private TreeSet<CTFCallsite> fCallsitesByIP = new TreeSet<>();
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Trace constructor.
- *
- * @param path
- * Filesystem path of the trace directory
- * @throws CTFReaderException
- * If no CTF trace was found at the path
- */
- public CTFTrace(String path) throws CTFReaderException {
- this(new File(path));
-
- }
-
- /**
- * Trace constructor.
- *
- * @param path
- * Filesystem path of the trace directory.
- * @throws CTFReaderException
- * If no CTF trace was found at the path
- */
- public CTFTrace(File path) throws CTFReaderException {
- fPath = path;
- final Metadata metadata = new Metadata(this);
-
- /* Set up the internal containers for this trace */
- if (!fPath.exists()) {
- throw new CTFReaderException("Trace (" + path.getPath() + ") doesn't exist. Deleted or moved?"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- if (!fPath.isDirectory()) {
- throw new CTFReaderException("Path must be a valid directory"); //$NON-NLS-1$
- }
-
- /* Open and parse the metadata file */
- metadata.parseFile();
-
- init(path);
- }
-
- /**
- * Streamed constructor
- *
- * @since 3.0
- */
- public CTFTrace() {
- fPath = null;
- }
-
- private void init(File path) throws CTFReaderException {
-
- /* Open all the trace files */
-
- /* List files not called metadata and not hidden. */
- File[] files = path.listFiles(METADATA_FILE_FILTER);
- Arrays.sort(files, METADATA_COMPARATOR);
-
- /* Try to open each file */
- for (File streamFile : files) {
- openStreamInput(streamFile);
- }
-
- /* Create their index */
- for (CTFStream stream : getStreams()) {
- Set<CTFStreamInput> inputs = stream.getStreamInputs();
- for (CTFStreamInput s : inputs) {
- addStream(s);
- }
- }
- }
-
- /**
- * Dispose the trace
- *
- * FIXME Not needed anymore, class doesn't need to be AutoCloseable.
- *
- * @since 3.0
- */
- @Override
- public void close() {
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- /**
- * Gets an event declaration hash map for a given streamID
- *
- * @param streamId
- * The ID of the stream from which to read
- * @return The Hash map with the event declarations
- * @since 2.0
- * @deprecated use {@link CTFTrace#getEventDeclarations(Long)}
- */
- @Deprecated
- public Map<Long, IEventDeclaration> getEvents(Long streamId) {
- return fStreams.get(streamId).getEvents();
- }
-
- /**
- * Gets an event declaration list for a given streamID
- *
- * @param streamId
- * The ID of the stream from which to read
- * @return The list of event declarations
- * @since 3.2
- */
- public Collection<IEventDeclaration> getEventDeclarations(Long streamId) {
- return fStreams.get(streamId).getEventDeclarations();
- }
-
- /**
- * Get an event by it's ID
- *
- * @param streamId
- * The ID of the stream from which to read
- * @param id
- * the ID of the event
- * @return the event declaration
- * @since 2.0
- * @deprecated use {@link CTFTrace#getEventType(long, int)} instead
- */
- @Deprecated
- public IEventDeclaration getEventType(long streamId, long id) {
- return getStream(streamId).getEventDeclaration((int) id);
- }
-
- /**
- * Get an event by it's ID
- *
- * @param streamId
- * The ID of the stream from which to read
- * @param id
- * the ID of the event
- * @return the event declaration
- * @since 3.2
- */
- public IEventDeclaration getEventType(long streamId, int id) {
- return getEvents(streamId).get(id);
- }
-
- /**
- * Method getStream gets the stream for a given id
- *
- * @param id
- * Long the id of the stream
- * @return Stream the stream that we need
- * @since 3.0
- */
- public CTFStream getStream(Long id) {
- return fStreams.get(id);
- }
-
- /**
- * Method nbStreams gets the number of available streams
- *
- * @return int the number of streams
- */
- public int nbStreams() {
- return fStreams.size();
- }
-
- /**
- * Method setMajor sets the major version of the trace (DO NOT USE)
- *
- * @param major
- * long the major version
- */
- public void setMajor(long major) {
- fMajor = major;
- }
-
- /**
- * Method setMinor sets the minor version of the trace (DO NOT USE)
- *
- * @param minor
- * long the minor version
- */
- public void setMinor(long minor) {
- fMinor = minor;
- }
-
- /**
- * Method setUUID sets the UUID of a trace
- *
- * @param uuid
- * UUID
- */
- public void setUUID(UUID uuid) {
- fUuid = uuid;
- }
-
- /**
- * Method setByteOrder sets the byte order
- *
- * @param byteOrder
- * ByteOrder of the trace, can be little-endian or big-endian
- */
- public void setByteOrder(ByteOrder byteOrder) {
- fByteOrder = byteOrder;
- }
-
- /**
- * Method setPacketHeader sets the packet header of a trace (DO NOT USE)
- *
- * @param packetHeader
- * StructDeclaration the header in structdeclaration form
- */
- public void setPacketHeader(StructDeclaration packetHeader) {
- fPacketHeaderDecl = packetHeader;
- }
-
- /**
- * Method majorIsSet is the major version number set?
- *
- * @return boolean is the major set?
- * @since 3.0
- */
- public boolean majorIsSet() {
- return fMajor != null;
- }
-
- /**
- * Method minorIsSet. is the minor version number set?
- *
- * @return boolean is the minor set?
- */
- public boolean minorIsSet() {
- return fMinor != null;
- }
-
- /**
- * Method UUIDIsSet is the UUID set?
- *
- * @return boolean is the UUID set?
- * @since 2.0
- */
- public boolean uuidIsSet() {
- return fUuid != null;
- }
-
- /**
- * Method byteOrderIsSet is the byteorder set?
- *
- * @return boolean is the byteorder set?
- */
- public boolean byteOrderIsSet() {
- return fByteOrder != null;
- }
-
- /**
- * Method packetHeaderIsSet is the packet header set?
- *
- * @return boolean is the packet header set?
- */
- public boolean packetHeaderIsSet() {
- return fPacketHeaderDecl != null;
- }
-
- /**
- * Method getUUID gets the trace UUID
- *
- * @return UUID gets the trace UUID
- */
- public UUID getUUID() {
- return fUuid;
- }
-
- /**
- * Method getMajor gets the trace major version
- *
- * @return long gets the trace major version
- */
- public long getMajor() {
- return fMajor;
- }
-
- /**
- * Method getMinor gets the trace minor version
- *
- * @return long gets the trace minor version
- */
- public long getMinor() {
- return fMinor;
- }
-
- /**
- * Method getByteOrder gets the trace byte order
- *
- * @return ByteOrder gets the trace byte order
- */
- public final ByteOrder getByteOrder() {
- return fByteOrder;
- }
-
- /**
- * Method getPacketHeader gets the trace packet header
- *
- * @return StructDeclaration gets the trace packet header
- */
- public StructDeclaration getPacketHeader() {
- return fPacketHeaderDecl;
- }
-
- /**
- * Method getTraceDirectory gets the trace directory
- *
- * @return File the path in "File" format.
- */
- public File getTraceDirectory() {
- return fPath;
- }
-
- /**
- * Get all the streams as an iterable.
- *
- * @return Iterable<Stream> an iterable over streams.
- * @since 3.0
- */
- public Iterable<CTFStream> getStreams() {
- return fStreams.values();
- }
-
- /**
- * Method getPath gets the path of the trace directory
- *
- * @return String the path of the trace directory, in string format.
- * @see java.io.File#getPath()
- */
- public String getPath() {
- return (fPath != null) ? fPath.getPath() : ""; //$NON-NLS-1$
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- private void addStream(CTFStreamInput s) {
-
- /*
- * add the stream
- */
- CTFStream stream = s.getStream();
- fStreams.put(stream.getId(), stream);
-
- /*
- * index the trace
- */
- s.setupIndex();
- }
-
- /**
- * Tries to open the given file, reads the first packet header of the file
- * and check its validity. This will add a file to a stream as a streaminput
- *
- * @param streamFile
- * A trace file in the trace directory.
- * @param index
- * Which index in the class' streamFileChannel array this file
- * must use
- * @throws CTFReaderException
- * if there is a file error
- */
- private CTFStream openStreamInput(File streamFile) throws CTFReaderException {
- ByteBuffer byteBuffer;
- BitBuffer streamBitBuffer;
- CTFStream stream;
-
- if (!streamFile.canRead()) {
- throw new CTFReaderException("Unreadable file : " //$NON-NLS-1$
- + streamFile.getPath());
- }
-
- try (FileChannel fc = FileChannel.open(streamFile.toPath(), StandardOpenOption.READ)) {
- /* Map one memory page of 4 kiB */
- byteBuffer = SafeMappedByteBuffer.map(fc, MapMode.READ_ONLY, 0, (int) Math.min(fc.size(), 4096L));
- if (byteBuffer == null) {
- throw new IllegalStateException("Failed to allocate memory"); //$NON-NLS-1$
- }
- /* Create a BitBuffer with this mapping and the trace byte order */
- streamBitBuffer = new BitBuffer(byteBuffer, this.getByteOrder());
-
- if (fPacketHeaderDecl != null) {
- /* Read the packet header */
- fPacketHeaderDef = fPacketHeaderDecl.createDefinition(this, LexicalScope.PACKET_HEADER, streamBitBuffer);
- }
- } catch (IOException e) {
- /* Shouldn't happen at this stage if every other check passed */
- throw new CTFReaderException(e);
- }
- if (fPacketHeaderDef != null) {
- validateMagicNumber(fPacketHeaderDef);
-
- validateUUID(fPacketHeaderDef);
-
- /* Read the stream ID */
- IDefinition streamIDDef = fPacketHeaderDef.lookupDefinition("stream_id"); //$NON-NLS-1$
-
- if (streamIDDef instanceof IntegerDefinition) {
- /* This doubles as a null check */
- long streamID = ((IntegerDefinition) streamIDDef).getValue();
- stream = fStreams.get(streamID);
- } else {
- /* No stream_id in the packet header */
- stream = fStreams.get(null);
- }
-
- } else {
- /* No packet header, we suppose there is only one stream */
- stream = fStreams.get(null);
- }
-
- if (stream == null) {
- throw new CTFReaderException("Unexpected end of stream"); //$NON-NLS-1$
- }
-
- /*
- * Create the stream input and add a reference to the streamInput in the
- * stream.
- */
- stream.addInput(new CTFStreamInput(stream, streamFile));
- return stream;
- }
-
- private void validateUUID(StructDefinition packetHeaderDef) throws CTFReaderException {
- IDefinition lookupDefinition = packetHeaderDef.lookupDefinition("uuid"); //$NON-NLS-1$
- ArrayDefinition uuidDef = (ArrayDefinition) lookupDefinition;
- if (uuidDef != null) {
- UUID otheruuid = Utils.getUUIDfromDefinition(uuidDef);
- if (!fUuid.equals(otheruuid)) {
- throw new CTFReaderException("UUID mismatch"); //$NON-NLS-1$
- }
- }
- }
-
- private static void validateMagicNumber(StructDefinition packetHeaderDef) throws CTFReaderException {
- IntegerDefinition magicDef = (IntegerDefinition) packetHeaderDef.lookupDefinition("magic"); //$NON-NLS-1$
- int magic = (int) magicDef.getValue();
- if (magic != Utils.CTF_MAGIC) {
- throw new CTFReaderException("CTF magic mismatch"); //$NON-NLS-1$
- }
- }
-
- // ------------------------------------------------------------------------
- // IDefinitionScope
- // ------------------------------------------------------------------------
-
- /**
- * @since 3.0
- */
- @Override
- public LexicalScope getScopePath() {
- return LexicalScope.TRACE;
- }
-
- /**
- * Looks up a definition from packet
- *
- * @param lookupPath
- * String
- * @return Definition
- * @see org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope#lookupDefinition(String)
- */
- @Override
- public Definition lookupDefinition(String lookupPath) {
- if (lookupPath.equals(LexicalScope.TRACE_PACKET_HEADER.toString())) {
- return fPacketHeaderDef;
- }
- return null;
- }
-
- // ------------------------------------------------------------------------
- // Live trace reading
- // ------------------------------------------------------------------------
-
- /**
- * Add a new stream file to support new streams while the trace is being
- * read.
- *
- * @param streamFile
- * the file of the stream
- * @throws CTFReaderException
- * A stream had an issue being read
- * @since 3.0
- */
- public void addStreamFile(File streamFile) throws CTFReaderException {
- openStreamInput(streamFile);
- }
-
- /**
- * Registers a new stream to the trace.
- *
- * @param stream
- * A stream object.
- * @throws ParseException
- * If there was some problem reading the metadata
- * @since 3.0
- */
- public void addStream(CTFStream stream) throws ParseException {
- /*
- * If there is already a stream without id (the null key), it must be
- * the only one
- */
- if (fStreams.get(null) != null) {
- throw new ParseException("Stream without id with multiple streams"); //$NON-NLS-1$
- }
-
- /*
- * If the stream we try to add has the null key, it must be the only
- * one. Thus, if the streams container is not empty, it is not valid.
- */
- if ((stream.getId() == null) && (fStreams.size() != 0)) {
- throw new ParseException("Stream without id with multiple streams"); //$NON-NLS-1$
- }
-
- /*
- * If a stream with the same ID already exists, it is not valid.
- */
- CTFStream existingStream = fStreams.get(stream.getId());
- if (existingStream != null) {
- throw new ParseException("Stream id already exists"); //$NON-NLS-1$
- }
-
- /* This stream is valid and has a unique id. */
- fStreams.put(stream.getId(), stream);
- }
-
- /**
- * Gets the Environment variables from the trace metadata (See CTF spec)
- *
- * @return The environment variables in the form of an unmodifiable map
- * (key, value)
- * @since 2.0
- */
- public Map<String, String> getEnvironment() {
- return Collections.unmodifiableMap(fEnvironment);
- }
-
- /**
- * Add a variable to the environment variables
- *
- * @param varName
- * the name of the variable
- * @param varValue
- * the value of the variable
- */
- public void addEnvironmentVar(String varName, String varValue) {
- fEnvironment.put(varName, varValue);
- }
-
- /**
- * Add a clock to the clock list
- *
- * @param nameValue
- * the name of the clock (full name with scope)
- * @param ctfClock
- * the clock
- */
- public void addClock(String nameValue, CTFClock ctfClock) {
- fClocks.put(nameValue, ctfClock);
- }
-
- /**
- * gets the clock with a specific name
- *
- * @param name
- * the name of the clock.
- * @return the clock
- */
- public CTFClock getClock(String name) {
- return fClocks.get(name);
- }
-
- /**
- * gets the clock if there is only one. (this is 100% of the use cases as of
- * June 2012)
- *
- * @return the clock
- */
- public final CTFClock getClock() {
- if (fSingleClock != null && fClocks.size() == 1) {
- return fSingleClock;
- }
- if (fClocks.size() == 1) {
- fSingleClock = fClocks.get(fClocks.keySet().iterator().next());
- return fSingleClock;
- }
- return null;
- }
-
- /**
- * gets the time offset of a clock with respect to UTC in nanoseconds
- *
- * @return the time offset of a clock with respect to UTC in nanoseconds
- */
- public final long getOffset() {
- if (getClock() == null) {
- return 0;
- }
- return fSingleClock.getClockOffset();
- }
-
- /**
- * gets the time offset of a clock with respect to UTC in nanoseconds
- *
- * @return the time offset of a clock with respect to UTC in nanoseconds
- */
- private double getTimeScale() {
- if (getClock() == null) {
- return 1.0;
- }
- return fSingleClock.getClockScale();
- }
-
- /**
- * Gets the current first packet start time
- *
- * @return the current start time
- * @since 3.0
- */
- public long getCurrentStartTime() {
- long currentStart = Long.MAX_VALUE;
- for (CTFStream stream : fStreams.values()) {
- for (CTFStreamInput si : stream.getStreamInputs()) {
- currentStart = Math.min(currentStart, si.getIndex().getEntries().get(0).getTimestampBegin());
- }
- }
- return timestampCyclesToNanos(currentStart);
- }
-
- /**
- * Gets the current last packet end time
- *
- * @return the current end time
- * @since 3.0
- */
- public long getCurrentEndTime() {
- long currentEnd = Long.MIN_VALUE;
- for (CTFStream stream : fStreams.values()) {
- for (CTFStreamInput si : stream.getStreamInputs()) {
- currentEnd = Math.max(currentEnd, si.getTimestampEnd());
- }
- }
- return timestampCyclesToNanos(currentEnd);
- }
-
- /**
- * Does the trace need to time scale?
- *
- * @return if the trace is in ns or cycles.
- */
- private boolean clockNeedsScale() {
- if (getClock() == null) {
- return false;
- }
- return fSingleClock.isClockScaled();
- }
-
- /**
- * the inverse clock for returning to a scale.
- *
- * @return 1.0 / scale
- */
- private double getInverseTimeScale() {
- if (getClock() == null) {
- return 1.0;
- }
- return fSingleClock.getClockAntiScale();
- }
-
- /**
- * @param cycles
- * clock cycles since boot
- * @return time in nanoseconds UTC offset
- * @since 2.0
- */
- public long timestampCyclesToNanos(long cycles) {
- long retVal = cycles + getOffset();
- /*
- * this fix is since quite often the offset will be > than 53 bits and
- * therefore the conversion will be lossy
- */
- if (clockNeedsScale()) {
- retVal = (long) (retVal * getTimeScale());
- }
- return retVal;
- }
-
- /**
- * @param nanos
- * time in nanoseconds UTC offset
- * @return clock cycles since boot.
- * @since 2.0
- */
- public long timestampNanoToCycles(long nanos) {
- long retVal;
- /*
- * this fix is since quite often the offset will be > than 53 bits and
- * therefore the conversion will be lossy
- */
- if (clockNeedsScale()) {
- retVal = (long) (nanos * getInverseTimeScale());
- } else {
- retVal = nanos;
- }
- return retVal - getOffset();
- }
-
- /**
- * Adds a callsite
- *
- * @param eventName
- * the event name of the callsite
- * @param funcName
- * the name of the callsite function
- * @param ip
- * the ip of the callsite
- * @param fileName
- * the filename of the callsite
- * @param lineNumber
- * the line number of the callsite
- */
- public void addCallsite(String eventName, String funcName, long ip,
- String fileName, long lineNumber) {
- final CTFCallsite cs = new CTFCallsite(eventName, funcName, ip,
- fileName, lineNumber);
- TreeSet<CTFCallsite> csl = fCallsitesByName.get(eventName);
- if (csl == null) {
- csl = new TreeSet<>(fCtfCallsiteComparator);
- fCallsitesByName.put(eventName, csl);
- }
-
- csl.add(cs);
-
- fCallsitesByIP.add(cs);
- }
-
- /**
- * Gets the set of callsites associated to an event name. O(1)
- *
- * @param eventName
- * the event name
- * @return the callsite set can be empty
- * @since 3.0
- */
- public TreeSet<CTFCallsite> getCallsiteCandidates(String eventName) {
- TreeSet<CTFCallsite> retVal = fCallsitesByName.get(eventName);
- if (retVal == null) {
- retVal = new TreeSet<>(fCtfCallsiteComparator);
- }
- return retVal;
- }
-
- /**
- * The I'm feeling lucky of getCallsiteCandidates O(1)
- *
- * @param eventName
- * the event name
- * @return the first callsite that has that event name, can be null
- * @since 1.2
- */
- public CTFCallsite getCallsite(String eventName) {
- TreeSet<CTFCallsite> callsites = fCallsitesByName.get(eventName);
- if (callsites != null) {
- return callsites.first();
- }
- return null;
- }
-
- /**
- * Gets a callsite from the instruction pointer O(log(n))
- *
- * @param ip
- * the instruction pointer to lookup
- * @return the callsite just before that IP in the list remember the IP is
- * backwards on X86, can be null if no callsite is before the IP.
- * @since 1.2
- */
- public CTFCallsite getCallsite(long ip) {
- CTFCallsite cs = new CTFCallsite(null, null, ip, null, 0L);
- return fCallsitesByIP.ceiling(cs);
- }
-
- /**
- * Gets a callsite using the event name and instruction pointer O(log(n))
- *
- * @param eventName
- * the name of the event
- * @param ip
- * the instruction pointer
- * @return the closest matching callsite, can be null
- */
- public CTFCallsite getCallsite(String eventName, long ip) {
- final TreeSet<CTFCallsite> candidates = fCallsitesByName.get(eventName);
- if (candidates == null) {
- return null;
- }
- final CTFCallsite dummyCs = new CTFCallsite(null, null, ip, null, -1);
- final CTFCallsite callsite = candidates.ceiling(dummyCs);
- if (callsite == null) {
- return candidates.floor(dummyCs);
- }
- return callsite;
- }
-
- /**
- * Add a new stream
- *
- * @param id
- * the ID of the stream
- * @param streamFile
- * new file in the stream
- * @throws CTFReaderException
- * The file must exist
- * @since 3.0
- */
- // TODO: remove suppress warning
- @SuppressWarnings("resource")
- public void addStream(long id, File streamFile) throws CTFReaderException {
- CTFStream stream = null;
- final File file = streamFile;
- if (file == null) {
- throw new CTFReaderException("cannot create a stream with no file"); //$NON-NLS-1$
- }
- if (fStreams.containsKey(id)) {
- stream = fStreams.get(id);
- } else {
- stream = new CTFStream(this);
- fStreams.put(id, stream);
- }
- stream.addInput(new CTFStreamInput(stream, file));
- }
-}
-
-class MetadataFileFilter implements FileFilter {
-
- @Override
- public boolean accept(File pathname) {
- if (pathname.isDirectory()) {
- return false;
- }
- if (pathname.isHidden()) {
- return false;
- }
- if (pathname.getName().equals("metadata")) { //$NON-NLS-1$
- return false;
- }
- return true;
- }
-
-}
-
-class MetadataComparator implements Comparator<File>, Serializable {
-
- private static final long serialVersionUID = 1L;
-
- @Override
- public int compare(File o1, File o2) {
- return o1.getName().compareTo(o2.getName());
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- * Alexandre Montplaisir - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.trace;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.PriorityQueue;
-import java.util.Set;
-
-import org.eclipse.linuxtools.ctf.core.event.EventDefinition;
-import org.eclipse.linuxtools.ctf.core.event.IEventDeclaration;
-import org.eclipse.linuxtools.internal.ctf.core.Activator;
-import org.eclipse.linuxtools.internal.ctf.core.trace.StreamInputReaderTimestampComparator;
-
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.ImmutableSet.Builder;
-
-/**
- * A CTF trace reader. Reads the events of a trace.
- *
- * @version 1.0
- * @author Matthew Khouzam
- * @author Alexandre Montplaisir
- */
-public class CTFTraceReader implements AutoCloseable {
-
- private static final int MIN_PRIO_SIZE = 16;
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- /**
- * The trace to read from.
- */
- private final CTFTrace fTrace;
-
- /**
- * Vector of all the trace file readers.
- */
- private final List<CTFStreamInputReader> fStreamInputReaders = new ArrayList<>();
-
- /**
- * Priority queue to order the trace file readers by timestamp.
- */
- private PriorityQueue<CTFStreamInputReader> fPrio;
-
- /**
- * Array to count the number of event per trace file.
- */
- private long[] fEventCountPerTraceFile;
-
- /**
- * Timestamp of the first event in the trace
- */
- private long fStartTime;
-
- /**
- * Timestamp of the last event read so far
- */
- private long fEndTime;
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Constructs a TraceReader to read a trace.
- *
- * @param trace
- * The trace to read from.
- * @throws CTFReaderException
- * if an error occurs
- */
- public CTFTraceReader(CTFTrace trace) throws CTFReaderException {
- fTrace = trace;
- fStreamInputReaders.clear();
-
- /**
- * Create the trace file readers.
- */
- createStreamInputReaders();
-
- /**
- * Populate the timestamp-based priority queue.
- */
- populateStreamInputReaderHeap();
-
- /**
- * Get the start Time of this trace bear in mind that the trace could be
- * empty.
- */
- fStartTime = 0;
- if (hasMoreEvents()) {
- fStartTime = getTopStream().getCurrentEvent().getTimestamp();
- setEndTime(fStartTime);
- }
- }
-
- /**
- * Copy constructor
- *
- * @return The new CTFTraceReader
- * @throws CTFReaderException
- * if an error occurs
- */
- public CTFTraceReader copyFrom() throws CTFReaderException {
- CTFTraceReader newReader = null;
-
- newReader = new CTFTraceReader(fTrace);
- newReader.fStartTime = fStartTime;
- newReader.setEndTime(fEndTime);
- return newReader;
- }
-
- /**
- * Dispose the CTFTraceReader
- *
- * @since 3.0
- */
- @Override
- public void close() {
- for (CTFStreamInputReader reader : fStreamInputReaders) {
- if (reader != null) {
- try {
- reader.close();
- } catch (IOException e) {
- Activator.logError(e.getMessage(), e);
- }
- }
- }
- fStreamInputReaders.clear();
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- /**
- * Return the start time of this trace (== timestamp of the first event)
- *
- * @return the trace start time
- */
- public long getStartTime() {
- return fStartTime;
- }
-
- /**
- * Set the trace's end time
- *
- * @param endTime
- * The end time to use
- */
- protected final void setEndTime(long endTime) {
- fEndTime = endTime;
- }
-
- /**
- * Get the priority queue of this trace reader.
- *
- * @return The priority queue of input readers
- * @since 2.0
- */
- protected PriorityQueue<CTFStreamInputReader> getPrio() {
- return fPrio;
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- /**
- * Creates one trace file reader per trace file contained in the trace.
- *
- * @throws CTFReaderException
- * if an error occurs
- */
- private void createStreamInputReaders() throws CTFReaderException {
- /*
- * For each stream.
- */
- for (CTFStream stream : fTrace.getStreams()) {
- Set<CTFStreamInput> streamInputs = stream.getStreamInputs();
-
- /*
- * For each trace file of the stream.
- */
- for (CTFStreamInput streamInput : streamInputs) {
-
- /*
- * Create a reader and add it to the group.
- */
- fStreamInputReaders.add(new CTFStreamInputReader(streamInput));
- }
- }
-
- /*
- * Create the array to count the number of event per trace file.
- */
- fEventCountPerTraceFile = new long[fStreamInputReaders.size()];
- }
-
- /**
- * Update the priority queue to make it match the parent trace
- *
- * @throws CTFReaderException
- * An error occured
- *
- * @since 3.0
- */
- public void update() throws CTFReaderException {
- Set<CTFStreamInputReader> readers = new HashSet<>();
- for (CTFStream stream : fTrace.getStreams()) {
- Set<CTFStreamInput> streamInputs = stream.getStreamInputs();
- for (CTFStreamInput streamInput : streamInputs) {
- /*
- * Create a reader.
- */
- CTFStreamInputReader streamInputReader = new CTFStreamInputReader(
- streamInput);
-
- /*
- * Add it to the group.
- */
- if (!fStreamInputReaders.contains(streamInputReader)) {
- streamInputReader.readNextEvent();
- fStreamInputReaders.add(streamInputReader);
- readers.add(streamInputReader);
- }
- }
- }
- long[] temp = fEventCountPerTraceFile;
- fEventCountPerTraceFile = new long[readers.size() + temp.length];
- for (CTFStreamInputReader reader : readers) {
- fPrio.add(reader);
- }
- for (int i = 0; i < temp.length; i++) {
- fEventCountPerTraceFile[i] = temp[i];
- }
- }
-
- /**
- * Gets an iterable of the stream input readers, useful for foreaches
- *
- * @return the iterable of the stream input readers
- * @since 3.0
- */
- public Iterable<IEventDeclaration> getEventDeclarations() {
- ImmutableSet.Builder<IEventDeclaration> builder = new Builder<>();
- for (CTFStreamInputReader sir : fStreamInputReaders) {
- builder.addAll(sir.getEventDeclarations());
- }
- return builder.build();
- }
-
- /**
- * Initializes the priority queue used to choose the trace file with the
- * lower next event timestamp.
- *
- * @throws CTFReaderException
- * if an error occurs
- */
- private void populateStreamInputReaderHeap() throws CTFReaderException {
- if (fStreamInputReaders.isEmpty()) {
- fPrio = new PriorityQueue<>(MIN_PRIO_SIZE,
- new StreamInputReaderTimestampComparator());
- return;
- }
-
- /*
- * Create the priority queue with a size twice as bigger as the number
- * of reader in order to avoid constant resizing.
- */
- fPrio = new PriorityQueue<>(
- Math.max(fStreamInputReaders.size() * 2, MIN_PRIO_SIZE),
- new StreamInputReaderTimestampComparator());
-
- int pos = 0;
-
- for (CTFStreamInputReader reader : fStreamInputReaders) {
- /*
- * Add each trace file reader in the priority queue, if we are able
- * to read an event from it.
- */
- reader.setParent(this);
- CTFResponse readNextEvent = reader.readNextEvent();
- if (readNextEvent == CTFResponse.OK || readNextEvent == CTFResponse.WAIT) {
- fPrio.add(reader);
-
- fEventCountPerTraceFile[pos] = 0;
- reader.setName(pos);
-
- pos++;
- }
- }
- }
-
- /**
- * Get the current event, which is the current event of the trace file
- * reader with the lowest timestamp.
- *
- * @return An event definition, or null of the trace reader reached the end
- * of the trace.
- */
- public EventDefinition getCurrentEventDef() {
- CTFStreamInputReader top = getTopStream();
- return (top != null) ? top.getCurrentEvent() : null;
- }
-
- /**
- * Go to the next event.
- *
- * @return True if an event was read.
- * @throws CTFReaderException
- * if an error occurs
- */
- public boolean advance() throws CTFReaderException {
- /*
- * Remove the reader from the top of the priority queue.
- */
- CTFStreamInputReader top = fPrio.poll();
-
- /*
- * If the queue was empty.
- */
- if (top == null) {
- return false;
- }
- /*
- * Read the next event of this reader.
- */
- switch (top.readNextEvent()) {
- case OK: {
- /*
- * Add it back in the queue.
- */
- fPrio.add(top);
- final long topEnd = fTrace.timestampCyclesToNanos(top.getCurrentEvent().getTimestamp());
- setEndTime(Math.max(topEnd, getEndTime()));
- fEventCountPerTraceFile[top.getName()]++;
-
- if (top.getCurrentEvent() != null) {
- fEndTime = Math.max(top.getCurrentEvent().getTimestamp(),
- fEndTime);
- }
- break;
- }
- case WAIT: {
- fPrio.add(top);
- break;
- }
- case FINISH:
- break;
- case ERROR:
- default:
- // something bad happend
- }
- /*
- * If there is no reader in the queue, it means the trace reader reached
- * the end of the trace.
- */
- return hasMoreEvents();
- }
-
- /**
- * Go to the last event in the trace.
- *
- * @throws CTFReaderException
- * if an error occurs
- */
- public void goToLastEvent() throws CTFReaderException {
- seek(getEndTime());
- while (fPrio.size() > 1) {
- advance();
- }
- }
-
- /**
- * Seeks to a given timestamp. It will seek to the nearest event greater or
- * equal to timestamp. If a trace is [10 20 30 40] and you are looking for
- * 19, it will give you 20. If you want 20, you will get 20, if you want 21,
- * you will get 30. The value -inf will seek to the first element and the
- * value +inf will seek to the end of the file (past the last event).
- *
- * @param timestamp
- * the timestamp to seek to
- * @return true if there are events above or equal the seek timestamp, false
- * if seek at the end of the trace (no valid event).
- * @throws CTFReaderException
- * if an error occurs
- */
- public boolean seek(long timestamp) throws CTFReaderException {
- /*
- * Remove all the trace readers from the priority queue
- */
- fPrio.clear();
- for (CTFStreamInputReader streamInputReader : fStreamInputReaders) {
- /*
- * Seek the trace reader.
- */
- streamInputReader.seek(timestamp);
-
- /*
- * Add it to the priority queue if there is a current event.
- */
- if (streamInputReader.getCurrentEvent() != null) {
- fPrio.add(streamInputReader);
- }
- }
- return hasMoreEvents();
- }
-
- /**
- * Gets the stream with the oldest event
- *
- * @return the stream with the oldest event
- * @since 3.0
- */
- public CTFStreamInputReader getTopStream() {
- return fPrio.peek();
- }
-
- /**
- * Does the trace have more events?
- *
- * @return true if yes.
- */
- public final boolean hasMoreEvents() {
- return fPrio.size() > 0;
- }
-
- /**
- * Prints the event count stats.
- */
- public void printStats() {
- printStats(60);
- }
-
- /**
- * Prints the event count stats.
- *
- * @param width
- * Width of the display.
- */
- public void printStats(int width) {
- int numEvents = 0;
- if (width == 0) {
- return;
- }
-
- for (long i : fEventCountPerTraceFile) {
- numEvents += i;
- }
-
- for (int j = 0; j < fEventCountPerTraceFile.length; j++) {
- CTFStreamInputReader se = fStreamInputReaders.get(j);
-
- long len = (width * fEventCountPerTraceFile[se.getName()])
- / numEvents;
-
- StringBuilder sb = new StringBuilder(se.getFilename());
- sb.append("\t["); //$NON-NLS-1$
-
- for (int i = 0; i < len; i++) {
- sb.append('+');
- }
-
- for (long i = len; i < width; i++) {
- sb.append(' ');
- }
-
- sb.append("]\t" + fEventCountPerTraceFile[se.getName()] + " Events"); //$NON-NLS-1$//$NON-NLS-2$
- Activator.log(sb.toString());
- }
- }
-
- /**
- * Gets the last event timestamp that was read. This is NOT necessarily the
- * last event in a trace, just the last one read so far.
- *
- * @return the last event
- */
- public long getEndTime() {
- return fEndTime;
- }
-
- /**
- * Sets a trace to be live or not
- *
- * @param live
- * whether the trace is live
- * @since 3.0
- */
- public void setLive(boolean live) {
- for (CTFStreamInputReader s : fPrio) {
- s.setLive(live);
- }
- }
-
- /**
- * Get if the trace is to read live or not
- *
- * @return whether the trace is live or not
- * @since 3.0
- *
- */
- public boolean isLive() {
- return getTopStream().isLive();
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = (prime * result) + (int) (fStartTime ^ (fStartTime >>> 32));
- result = (prime * result) + fStreamInputReaders.hashCode();
- result = (prime * result) + ((fTrace == null) ? 0 : fTrace.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (!(obj instanceof CTFTraceReader)) {
- return false;
- }
- CTFTraceReader other = (CTFTraceReader) obj;
- if (!fStreamInputReaders.equals(other.fStreamInputReaders)) {
- return false;
- }
- if (fTrace == null) {
- if (other.fTrace != null) {
- return false;
- }
- } else if (!fTrace.equals(other.fTrace)) {
- return false;
- }
- return true;
- }
-
- @Override
- public String toString() {
- /* Only for debugging, shouldn't be externalized */
- return "CTFTraceReader [trace=" + fTrace + ']'; //$NON-NLS-1$
- }
-
- /**
- * Gets the parent trace
- *
- * @return the parent trace
- */
- public CTFTrace getTrace() {
- return fTrace;
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- * Simon Marchi - Initial API and implementation
- * Matthew Khouzam - Update for live trace reading support
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.trace;
-
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.Reader;
-import java.io.StringReader;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.nio.channels.FileChannel;
-import java.util.UUID;
-
-import org.antlr.runtime.ANTLRReaderStream;
-import org.antlr.runtime.CommonTokenStream;
-import org.antlr.runtime.RecognitionException;
-import org.antlr.runtime.tree.CommonTree;
-import org.antlr.runtime.tree.RewriteCardinalityException;
-import org.eclipse.linuxtools.ctf.parser.CTFLexer;
-import org.eclipse.linuxtools.ctf.parser.CTFParser;
-import org.eclipse.linuxtools.ctf.parser.CTFParser.parse_return;
-import org.eclipse.linuxtools.internal.ctf.core.event.metadata.IOStructGen;
-import org.eclipse.linuxtools.internal.ctf.core.event.metadata.exceptions.CtfAntlrException;
-import org.eclipse.linuxtools.internal.ctf.core.event.metadata.exceptions.ParseException;
-
-/**
- * The CTF trace metadata TSDL file
- *
- * @version 1.0
- * @author Matthew Khouzam
- * @author Simon Marchi
- */
-public class Metadata {
-
- // ------------------------------------------------------------------------
- // Constants
- // ------------------------------------------------------------------------
-
- /**
- * Name of the metadata file in the trace directory
- */
- private static final String METADATA_FILENAME = "metadata"; //$NON-NLS-1$
-
- /**
- * Size of the metadata packet header, in bytes, computed by hand.
- */
- private static final int METADATA_PACKET_HEADER_SIZE = 37;
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- /**
- * Byte order as detected when reading the TSDL magic number.
- */
- private ByteOrder detectedByteOrder = null;
-
- /**
- * The trace file to which belongs this metadata file.
- */
- private final CTFTrace trace;
-
- private IOStructGen fTreeParser;
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Constructs a Metadata object.
- *
- * @param trace
- * The trace to which belongs this metadata file.
- */
- public Metadata(CTFTrace trace) {
- this.trace = trace;
- }
-
- /**
- * For network streaming
- *
- * @since 3.0
- */
- public Metadata() {
- trace = new CTFTrace();
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- /**
- * Returns the ByteOrder that was detected while parsing the metadata.
- *
- * @return The byte order.
- */
- public ByteOrder getDetectedByteOrder() {
- return detectedByteOrder;
- }
-
- /**
- * Gets the parent trace
- *
- * @return the parent trace
- * @since 3.0
- */
- public CTFTrace getTrace() {
- return trace;
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- /**
- * Parse the metadata file.
- *
- * @throws CTFReaderException
- * If there was a problem parsing the metadata
- * @since 3.0
- */
- public void parseFile() throws CTFReaderException {
-
- /*
- * Reader. It will contain a StringReader if we are using packet-based
- * metadata and it will contain a FileReader if we have text-based
- * metadata.
- */
-
- try (FileInputStream fis = new FileInputStream(getMetadataPath());
- FileChannel metadataFileChannel = fis.getChannel();
- /* Check if metadata is packet-based, if not it is text based */
- Reader metadataTextInput =
- (isPacketBased(metadataFileChannel) ?
- readBinaryMetaData(metadataFileChannel) :
- new FileReader(getMetadataPath()));) {
-
- readMetaDataText(metadataTextInput);
-
- } catch (FileNotFoundException e) {
- throw new CTFReaderException("Cannot find metadata file!"); //$NON-NLS-1$
- } catch (IOException | ParseException e) {
- throw new CTFReaderException(e);
- } catch (RecognitionException | RewriteCardinalityException e) {
- throw new CtfAntlrException(e);
- }
- }
-
- private Reader readBinaryMetaData(FileChannel metadataFileChannel) throws CTFReaderException {
- /* Create StringBuffer to receive metadata text */
- StringBuffer metadataText = new StringBuffer();
-
- /*
- * Read metadata packet one by one, appending the text to the
- * StringBuffer
- */
- MetadataPacketHeader packetHeader = readMetadataPacket(
- metadataFileChannel, metadataText);
- while (packetHeader != null) {
- packetHeader = readMetadataPacket(metadataFileChannel,
- metadataText);
- }
-
- /* Wrap the metadata string with a StringReader */
- return new StringReader(metadataText.toString());
- }
-
- /**
- * Read the metadata from a formatted TSDL string
- *
- * @param data
- * the data to read
- * @throws CTFReaderException
- * this exception wraps a ParseException, IOException or
- * CtfAntlrException, three exceptions that can be obtained from
- * parsing a TSDL file
- * @since 3.0
- */
- public void parseText(String data) throws CTFReaderException {
- Reader metadataTextInput = new StringReader(data);
- try {
- readMetaDataText(metadataTextInput);
- } catch (IOException | ParseException e) {
- throw new CTFReaderException(e);
- } catch (RecognitionException | RewriteCardinalityException e) {
- throw new CtfAntlrException(e);
- }
-
- }
-
- private void readMetaDataText(Reader metadataTextInput) throws IOException, RecognitionException, ParseException {
- CommonTree tree = createAST(metadataTextInput);
-
- /* Generate IO structures (declarations) */
- fTreeParser = new IOStructGen(tree, trace);
- fTreeParser.generate();
- }
-
- /**
- * Read a metadata fragment from a formatted TSDL string
- *
- * @param dataFragment
- * the data to read
- * @throws CTFReaderException
- * this exception wraps a ParseException, IOException or
- * CtfAntlrException, three exceptions that can be obtained from
- * parsing a TSDL file
- * @since 3.0
- */
- public void parseTextFragment(String dataFragment) throws CTFReaderException {
- Reader metadataTextInput = new StringReader(dataFragment);
- try {
- readMetaDataTextFragment(metadataTextInput);
- } catch (IOException | ParseException e) {
- throw new CTFReaderException(e);
- } catch (RecognitionException | RewriteCardinalityException e) {
- throw new CtfAntlrException(e);
- }
- }
-
- private void readMetaDataTextFragment(Reader metadataTextInput) throws IOException, RecognitionException, ParseException {
- CommonTree tree = createAST(metadataTextInput);
- fTreeParser.setTree(tree);
- fTreeParser.generateFragment();
- }
-
- private static CommonTree createAST(Reader metadataTextInput) throws IOException,
- RecognitionException {
- /* Create an ANTLR reader */
- ANTLRReaderStream antlrStream;
- antlrStream = new ANTLRReaderStream(metadataTextInput);
-
- /* Parse the metadata text and get the AST */
- CTFLexer ctfLexer = new CTFLexer(antlrStream);
- CommonTokenStream tokens = new CommonTokenStream(ctfLexer);
- CTFParser ctfParser = new CTFParser(tokens, false);
-
- parse_return pr = ctfParser.parse();
- return pr.getTree();
- }
-
- /**
- * Determines whether the metadata file is packet-based by looking at the
- * TSDL magic number. If it is packet-based, it also gives information about
- * the endianness of the trace using the detectedByteOrder attribute.
- *
- * @param metadataFileChannel
- * FileChannel of the metadata file.
- * @return True if the metadata is packet-based.
- * @throws CTFReaderException
- */
- private boolean isPacketBased(FileChannel metadataFileChannel)
- throws CTFReaderException {
- /*
- * Create a ByteBuffer to read the TSDL magic number (default is
- * big-endian)
- */
- ByteBuffer magicByteBuffer = ByteBuffer.allocate(Utils.TSDL_MAGIC_LEN);
-
- /* Read without changing file position */
- try {
- metadataFileChannel.read(magicByteBuffer, 0);
- } catch (IOException e) {
- throw new CTFReaderException("Unable to read metadata file channel.", e); //$NON-NLS-1$
- }
-
- /* Get the first int from the file */
- int magic = magicByteBuffer.getInt(0);
-
- /* Check if it matches */
- if (Utils.TSDL_MAGIC == magic) {
- detectedByteOrder = ByteOrder.BIG_ENDIAN;
- return true;
- }
-
- /* Try the same thing, but with little-endian */
- magicByteBuffer.order(ByteOrder.LITTLE_ENDIAN);
- magic = magicByteBuffer.getInt(0);
-
- if (Utils.TSDL_MAGIC == magic) {
- detectedByteOrder = ByteOrder.LITTLE_ENDIAN;
- return true;
- }
-
- return false;
- }
-
- private String getMetadataPath() {
- /* Path of metadata file = trace directory path + metadata filename */
- if (trace.getTraceDirectory() == null) {
- return new String();
- }
- return trace.getTraceDirectory().getPath()
- + Utils.SEPARATOR + METADATA_FILENAME;
- }
-
- /**
- * Reads a metadata packet from the given metadata FileChannel, do some
- * basic validation and append the text to the StringBuffer.
- *
- * @param metadataFileChannel
- * Metadata FileChannel
- * @param metadataText
- * StringBuffer to which the metadata text will be appended.
- * @return A structure describing the header of the metadata packet, or null
- * if the end of the file is reached.
- * @throws CTFReaderException
- */
- private MetadataPacketHeader readMetadataPacket(
- FileChannel metadataFileChannel, StringBuffer metadataText)
- throws CTFReaderException {
- /* Allocate a ByteBuffer for the header */
- ByteBuffer headerByteBuffer = ByteBuffer.allocate(METADATA_PACKET_HEADER_SIZE);
-
- /* Read the header */
- try {
- int nbBytesRead = metadataFileChannel.read(headerByteBuffer);
-
- /* Return null if EOF */
- if (nbBytesRead < 0) {
- return null;
- }
-
- if (nbBytesRead != METADATA_PACKET_HEADER_SIZE) {
- throw new CTFReaderException("Error reading the metadata header."); //$NON-NLS-1$
- }
-
- } catch (IOException e) {
- throw new CTFReaderException("Error reading the metadata header.", e); //$NON-NLS-1$
- }
-
- /* Set ByteBuffer's position to 0 */
- headerByteBuffer.position(0);
-
- /* Use byte order that was detected with the magic number */
- headerByteBuffer.order(detectedByteOrder);
-
- MetadataPacketHeader header = new MetadataPacketHeader(headerByteBuffer);
-
- /* Check TSDL magic number */
- if (!header.isMagicValid()) {
- throw new CTFReaderException("TSDL magic number does not match"); //$NON-NLS-1$
- }
-
- /* Check UUID */
- if (!trace.uuidIsSet()) {
- trace.setUUID(header.getUuid());
- } else if (!trace.getUUID().equals(header.getUuid())) {
- throw new CTFReaderException("UUID mismatch"); //$NON-NLS-1$
- }
-
- /* Extract the text from the packet */
- int payloadSize = ((header.getContentSize() / 8) - METADATA_PACKET_HEADER_SIZE);
- if (payloadSize < 0) {
- throw new CTFReaderException("Invalid metadata packet payload size."); //$NON-NLS-1$
- }
- int skipSize = (header.getPacketSize() - header.getContentSize()) / 8;
-
- /* Read the payload + the padding in a ByteBuffer */
- ByteBuffer payloadByteBuffer = ByteBuffer.allocateDirect(payloadSize
- + skipSize);
- try {
- metadataFileChannel.read(payloadByteBuffer);
- } catch (IOException e) {
- throw new CTFReaderException("Error reading metadata packet payload.", e); //$NON-NLS-1$
- }
- payloadByteBuffer.rewind();
-
- /* Read only the payload from the ByteBuffer into a byte array */
- byte payloadByteArray[] = new byte[payloadByteBuffer.remaining()];
- payloadByteBuffer.get(payloadByteArray, 0, payloadSize);
-
- /* Convert the byte array to a String */
- String str = new String(payloadByteArray, 0, payloadSize);
-
- /* Append it to the existing metadata */
- metadataText.append(str);
-
- return header;
- }
-
- private static class MetadataPacketHeader {
-
- private final int fMagic;
- private final UUID fUuid;
- private final int fChecksum;
- private final int fContentSize;
- private final int fPacketSize;
- private final byte fCompressionScheme;
- private final byte fEncryptionScheme;
- private final byte fChecksumScheme;
- private final byte fCtfMajorVersion;
- private final byte fCtfMinorVersion;
-
- public MetadataPacketHeader(ByteBuffer headerByteBuffer) {
- /* Read from the ByteBuffer */
- fMagic = headerByteBuffer.getInt();
- byte[] uuidBytes = new byte[16];
- headerByteBuffer.get(uuidBytes);
- fUuid = Utils.makeUUID(uuidBytes);
- fChecksum = headerByteBuffer.getInt();
- fContentSize = headerByteBuffer.getInt();
- fPacketSize = headerByteBuffer.getInt();
- fCompressionScheme = headerByteBuffer.get();
- fEncryptionScheme = headerByteBuffer.get();
- fChecksumScheme = headerByteBuffer.get();
- fCtfMajorVersion = headerByteBuffer.get();
- fCtfMinorVersion = headerByteBuffer.get();
- }
-
- public boolean isMagicValid() {
- return fMagic == Utils.TSDL_MAGIC;
- }
-
- public UUID getUuid() {
- return fUuid;
- }
-
- public int getContentSize() {
- return fContentSize;
- }
-
- public int getPacketSize() {
- return fPacketSize;
- }
-
- @Override
- public String toString() {
- /* Only for debugging, shouldn't be externalized */
- /* Therefore it cannot be covered by test cases */
- return "MetadataPacketHeader [magic=0x" //$NON-NLS-1$
- + Integer.toHexString(fMagic) + ", uuid=" //$NON-NLS-1$
- + fUuid.toString() + ", checksum=" + fChecksum //$NON-NLS-1$
- + ", contentSize=" + fContentSize + ", packetSize=" //$NON-NLS-1$ //$NON-NLS-2$
- + fPacketSize + ", compressionScheme=" + fCompressionScheme //$NON-NLS-1$
- + ", encryptionScheme=" + fEncryptionScheme //$NON-NLS-1$
- + ", checksumScheme=" + fChecksumScheme //$NON-NLS-1$
- + ", ctfMajorVersion=" + fCtfMajorVersion //$NON-NLS-1$
- + ", ctfMinorVersion=" + fCtfMinorVersion + ']'; //$NON-NLS-1$
- }
-
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.core.trace;
-
-import java.util.UUID;
-
-import org.eclipse.linuxtools.ctf.core.event.types.AbstractArrayDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.CompoundDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDefinition;
-
-/**
- * Various utilities.
- *
- * @version 1.0
- * @author Matthew Khouzam
- * @author Simon Marchi
- */
-public final class Utils {
-
- private Utils() {
- }
-
- // ------------------------------------------------------------------------
- // Constants
- // ------------------------------------------------------------------------
-
- /**
- * CTF magic number. (sort of looks like CTF CTF CT)
- */
- public static final int CTF_MAGIC = 0xC1FC1FC1;
-
- /**
- * TSDL magic number. (sort of looks like TSDL LSDT)
- */
- public static final int TSDL_MAGIC = 0x75D11D57;
-
- /**
- * TSDL magic number length in bytes.
- */
- public static final int TSDL_MAGIC_LEN = 4;
-
- /**
- * Directory separator on the current platform.
- */
- public static final String SEPARATOR = System.getProperty("file.separator"); //$NON-NLS-1$
-
- /**
- * Length in bytes of a UUID value.
- */
- public static final int UUID_LEN = 16;
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- /**
- * Performs an unsigned long comparison on two unsigned long numbers.
- *
- * <strong> As Java does not support unsigned types and arithmetic,
- * parameters are received encoded as a signed long (two-complement) but the
- * operation is an unsigned comparator.</strong>
- *
- * @param left
- * Left operand of the comparator.
- * @param right
- * Right operand of the comparator.
- * @return -1 if left < right, 1 if left > right, 0 if left == right.
- */
- public static int unsignedCompare(long left, long right) {
- /*
- * This method assumes that the arithmetic overflow on signed integer
- * wrap on a circular domain (modulo arithmetic in two-complement),
- * which is the defined behavior in Java.
- *
- * This idea is to rotate the domain by the length of the negative
- * space, and then use the signed operator.
- */
- final long a = left + Long.MIN_VALUE;
- final long b = right + Long.MIN_VALUE;
- if (a < b) {
- return -1;
- } else if (a > b) {
- return 1;
- }
- return 0;
- }
-
- /**
- * Gets a UUID from an array defintion
- *
- * @param uuidDef
- * the array defintions, must contain integer bytes
- * @return the UUID
- * @throws CTFReaderException
- * if the definition contains less than 16 elements
- * @since 3.1
- */
- public static UUID getUUIDfromDefinition(AbstractArrayDefinition uuidDef) throws CTFReaderException {
- byte[] uuidArray = new byte[16];
- IDeclaration declaration = uuidDef.getDeclaration();
- if (!(declaration instanceof CompoundDeclaration)) {
- throw new CTFReaderException("UUID must be a sequence of unsigned bytes"); //$NON-NLS-1$
- }
- CompoundDeclaration uuidDec = (CompoundDeclaration) declaration;
-
- IDeclaration uuidElem = uuidDec.getElementType();
- if (!(uuidElem instanceof IntegerDeclaration)) {
- throw new CTFReaderException("UUID must be a sequence of unsigned bytes"); //$NON-NLS-1$
- }
- IntegerDeclaration intUuidElem = (IntegerDeclaration) uuidElem;
- if (!intUuidElem.isUnsignedByte()) {
- throw new CTFReaderException("UUID must be a sequence of unsigned bytes"); //$NON-NLS-1$
- }
- return getUUID(uuidDef, uuidArray);
- }
-
- private static UUID getUUID(AbstractArrayDefinition uuidDef, byte[] uuidArray) throws CTFReaderException {
- for (int i = 0; i < uuidArray.length; i++) {
- IntegerDefinition uuidByteDef = (IntegerDefinition) uuidDef.getDefinitions().get(i);
- if (uuidByteDef == null) {
- throw new CTFReaderException("UUID incomplete, only " + i + " bytes available"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- uuidArray[i] = (byte) uuidByteDef.getValue();
- }
-
- UUID uuid = Utils.makeUUID(uuidArray);
- return uuid;
- }
-
- /**
- * Gets a UUID from an array defintion
- *
- * @param uuidDef
- * the array defintions, must contain integer bytes
- * @return the UUID
- * @throws CTFReaderException
- * if the definition contains less than 16 elements
- * @since 3.1
- * @deprecated use
- * {@link Utils#getUUIDfromDefinition(AbstractArrayDefinition uuidDef)}
- */
- @Deprecated
- public static UUID getUUIDfromDefinition(org.eclipse.linuxtools.ctf.core.event.types.ArrayDefinition uuidDef) throws CTFReaderException {
- byte[] uuidArray = new byte[16];
- return getUUID(uuidDef, uuidArray);
- }
-
- /**
- * Creates a UUID object from an array of 16 bytes.
- *
- * @param bytes
- * Array of 16 bytes.
- * @return A UUID object.
- */
- public static UUID makeUUID(byte bytes[]) {
- long high = 0;
- long low = 0;
-
- assert (bytes.length == Utils.UUID_LEN);
-
- for (int i = 0; i < 8; i++) {
- low = (low << 8) | (bytes[i + 8] & 0xFF);
- high = (high << 8) | (bytes[i] & 0xFF);
- }
-
- UUID uuid = new UUID(high, low);
-
- return uuid;
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are
- * made available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Francois Chouinard - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.internal.ctf.core;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Plugin;
-import org.eclipse.core.runtime.Status;
-import org.osgi.framework.BundleContext;
-
-/**
- * <b><u>Activator</u></b>
- * <p>
- * The activator class controls the plug-in life cycle.
- */
-public class Activator extends Plugin {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- /**
- * The plug-in ID
- */
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.ctf"; //$NON-NLS-1$
-
- /**
- * The shared instance
- */
- private static Activator fPlugin;
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Constructor
- */
- public Activator() {
- setDefault(this);
- }
-
- // ------------------------------------------------------------------------
- // Accessors
- // ------------------------------------------------------------------------
-
- /**
- * Get the default activator
- * @return the default activator
- */
- public static Activator getDefault() {
- return fPlugin;
- }
-
- /**
- * Sets the default activator
- *
- * @param plugin the default activator
- */
- private static void setDefault(Activator plugin) {
- fPlugin = plugin;
- }
-
- // ------------------------------------------------------------------------
- // Plugin
- // ------------------------------------------------------------------------
-
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
- setDefault(this);
- }
-
- @Override
- public void stop(BundleContext context) throws Exception {
- setDefault(null);
- super.stop(context);
- }
-
- // ------------------------------------------------------------------------
- // Logging
- // ------------------------------------------------------------------------
-
- /**
- * Log a message
- *
- * @param msg
- * The message to log
- */
- public static void log(String msg) {
- log(msg, null);
- }
-
- /**
- * Log a message with an exception
- *
- * @param msg
- * The message
- * @param e
- * The exception
- */
- public static void log(String msg, Exception e) {
- getDefault().getLog().log(new Status(IStatus.INFO, PLUGIN_ID, IStatus.OK, msg, e));
- }
-
- /**
- * Log an error, with an associated exception
- *
- * @param msg
- * The error message
- * @param e
- * The cause
- */
- public static void logError(String msg, Exception e) {
- getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.OK, msg, e));
- }
-
- /**
- * Log a message
- *
- * @param severity
- * Desired severity of the message in the log, one of
- * {@link IStatus#INFO}, {@link IStatus#WARNING} or
- * {@link IStatus#ERROR}
- * @param msg
- * The message to log
- */
- public static void log(int severity, String msg) {
- getDefault().getLog().log(new Status(severity, PLUGIN_ID, msg));
- }
-
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Marc-Andre Laperle - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.internal.ctf.core;
-
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.nio.channels.FileChannel;
-
-/**
- * A common utility for mapping a ByteBuffer safely to work around a bug on
- * Windows which prevents deleting a file after it was mapped. On Windows, the
- * ByteBuffer will be allocated and the file will be read instead of being
- * mapped.
- *
- * http://bugs.java.com/view_bug.do?bug_id=4715154
- */
-public class SafeMappedByteBuffer {
-
- private static final boolean IS_WIN32 = System.getProperty("os.name").startsWith("Windows"); //$NON-NLS-1$//$NON-NLS-2$
-
- /**
- * Maps a region of this channel's file directly into memory. On Windows,
- * this will allocate a new ByteBuffer and read the file.
- *
- * @param fc
- * the file channel
- * @param mode
- * the mapping mode
- * @param position
- * the position within the file
- * @param size
- * the size of the region to be mapped (or read)
- * @return the mapped ByteBuffer
- * @throws IOException
- * on FileChannel operations failures
- */
- public static ByteBuffer map(FileChannel fc, FileChannel.MapMode mode, long position, long size) throws IOException {
- ByteBuffer byteBuffer;
- if (IS_WIN32) {
- byteBuffer = ByteBuffer.allocate((int) size);
- fc.read(byteBuffer, position);
- } else {
- byteBuffer = fc.map(mode, position, size);
- }
-
- return byteBuffer;
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Simon Delisle - Initial implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.internal.ctf.core.event;
-
-import java.util.Comparator;
-
-import org.eclipse.linuxtools.ctf.core.event.CTFCallsite;
-
-/**
- * Comparator for CTFCallsite
- *
- * @author Simon Delisle
- * @since 3.0
- *
- */
-public class CTFCallsiteComparator implements Comparator<CTFCallsite> {
-
- private static final long MASK32 = 0x00000000ffffffffL;
-
- /*
- * The callsites will be sorted by calling addresses. To do this we take IPs
- * (instruction pointers) and compare them. Java only supports signed
- * operation and since memory addresses are unsigned, we will convert the
- * longs into integers that contain the high and low bytes and compare them.
- */
- @Override
- public int compare(CTFCallsite o1, CTFCallsite o2) {
- /*
- * mask32 is 32 zeros followed by 32 ones, when we bitwise and this it
- * will return the lower 32 bits
- */
-
- long other = o2.getIp();
- /*
- * To get a high int: we downshift by 32 and bitwise and with the mask
- * to get rid of the sign
- *
- * To get the low int: we bitwise and with the mask.
- */
- long otherHigh = (other >> 32) & MASK32;
- long otherLow = other & MASK32;
- long ownHigh = (o1.getIp() >> 32) & MASK32;
- long ownLow = o1.getIp() & MASK32;
- /* are the high values different, if so ignore the lower values */
- if (ownHigh > otherHigh) {
- return 1;
- }
- if (ownHigh < otherHigh ) {
- return -1;
- }
- /* the high values are the same, compare the lower values */
- if (ownLow > otherLow) {
- return 1;
- }
- if (ownLow < otherLow) {
- return -1;
- }
- /* the values are identical */
- return 0;
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.internal.ctf.core.event;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.CTFStrings;
-import org.eclipse.linuxtools.ctf.core.event.EventDefinition;
-import org.eclipse.linuxtools.ctf.core.event.IEventDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.scope.LexicalScope;
-import org.eclipse.linuxtools.ctf.core.event.types.Declaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDefinition;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.ctf.core.trace.CTFStream;
-import org.eclipse.linuxtools.ctf.core.trace.CTFStreamInputReader;
-
-/**
- * Representation of one type of event. A bit like "int" or "long" but for trace
- * events.
- */
-public class EventDeclaration implements IEventDeclaration {
-
- /** Id of lost events */
- public static final long LOST_EVENT_ID = -1L;
-
- /** Id of events when not set */
- public static final long UNSET_EVENT_ID = -2L;
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- /**
- * Name of the event
- */
- private String fName;
-
- /**
- * Event context structure declaration
- */
- private StructDeclaration fContext = null;
-
- /**
- * Event fields structure declaration
- */
- private StructDeclaration fFields = null;
-
- /**
- * Stream to which belongs this event.
- */
- private CTFStream fStream = null;
-
- /**
- * Loglevel of an event
- */
- private long fLogLevel;
-
- /** Map of this event type's custom CTF attributes */
- private final Map<String, String> fCustomAttributes = new HashMap<>();
-
- private int fId = (int) UNSET_EVENT_ID;
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Default constructor. Use the setters afterwards to set the fields
- * accordingly.
- */
- public EventDeclaration() {
- }
-
- @Override
- public EventDefinition createDefinition(CTFStreamInputReader streamInputReader, @NonNull BitBuffer input, long timestamp) throws CTFReaderException {
- StructDeclaration streamEventContextDecl = streamInputReader.getStreamEventContextDecl();
- StructDefinition streamEventContext = streamEventContextDecl != null ? streamEventContextDecl.createDefinition(fStream.getTrace(), LexicalScope.STREAM_EVENT_CONTEXT, input) : null;
- StructDefinition packetContext = streamInputReader.getPacketReader().getCurrentPacketEventHeader();
- StructDefinition eventContext = fContext != null ? fContext.createDefinition(fStream.getTrace(), LexicalScope.CONTEXT, input) : null;
- StructDefinition eventPayload = fFields != null ? fFields.createDefinition(fStream.getTrace(), LexicalScope.FIELDS, input) : null;
-
- // a bit lttng specific
- // CTF doesn't require a timestamp,
- // but it's passed to us
- return new EventDefinition(
- this,
- streamInputReader,
- timestamp,
- streamEventContext,
- eventContext,
- packetContext,
- eventPayload);
- }
-
- /**
- * Creates a "lost" event. This is a synthetic event that is there to show
- * that there should be something there.
- *
- * @return the lost event
- */
- public static synchronized EventDeclaration getLostEventDeclaration() {
- EventDeclaration lostEvent = new EventDeclaration();
- String[] fieldNames = new String[] { CTFStrings.LOST_EVENTS_FIELD, CTFStrings.LOST_EVENTS_DURATION };
- Declaration[] fieldDeclarations = new Declaration[] { IntegerDeclaration.UINT_32B_DECL, IntegerDeclaration.UINT_64B_DECL };
- lostEvent.fFields = new StructDeclaration(fieldNames, fieldDeclarations);
- lostEvent.fId = (int) LOST_EVENT_ID;
- lostEvent.fName = CTFStrings.LOST_EVENT_NAME;
- return lostEvent;
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- /**
- * Sets a name for an event Declaration
- *
- * @param name
- * the name
- */
- public void setName(String name) {
- fName = name;
- }
-
- @Override
- public String getName() {
- return fName;
- }
-
- /**
- * Sets the context for an event declaration (see CTF specification)
- *
- * @param context
- * the context in structdeclaration format
- */
- public void setContext(StructDeclaration context) {
- fContext = context;
- }
-
- /**
- * Sets the fields of an event declaration
- *
- * @param fields
- * the fields in structdeclaration format
- */
- public void setFields(StructDeclaration fields) {
- fFields = fields;
- }
-
- @Override
- public StructDeclaration getFields() {
- return fFields;
- }
-
- @Override
- public StructDeclaration getContext() {
- return fContext;
- }
-
- /**
- * Sets the id of an event declaration
- *
- * @param id
- * the id
- */
- public void setId(long id) {
- if (id < 0 || id > Integer.MAX_VALUE) {
- throw new IllegalArgumentException("id out of range"); //$NON-NLS-1$
- }
- fId = (int) id;
- }
-
- @Override
- public Long getId() {
- return Long.valueOf(fId);
- }
-
- /**
- * Faster get id assuming you have less than a billion event types
- *
- * @return the event id
- */
- public int id() {
- return fId;
- }
-
- /**
- * Sets the stream of an event declaration
- *
- * @param stream
- * the stream
- * @since 2.0
- */
- public void setStream(CTFStream stream) {
- fStream = stream;
- }
-
- @Override
- public CTFStream getStream() {
- return fStream;
- }
-
- /**
- * Is the name of the event declaration set
- *
- * @return is the name set?
- */
- public boolean nameIsSet() {
- return fName != null;
- }
-
- /**
- * Is the context set
- *
- * @return is the context set
- */
- public boolean contextIsSet() {
- return fContext != null;
- }
-
- /**
- * Is a field set?
- *
- * @return Is the field set?
- */
- public boolean fieldsIsSet() {
- return fFields != null;
- }
-
- /**
- * Is the id set?
- *
- * @return is the id set?
- */
- public boolean idIsSet() {
- return (fId != UNSET_EVENT_ID);
- }
-
- /**
- * Is the stream set?
- *
- * @return is the stream set?
- */
- public boolean streamIsSet() {
- return fStream != null;
- }
-
- @Override
- public long getLogLevel() {
- return fLogLevel;
- }
-
- /**
- * Sets the log level
- *
- * @param level
- * the log level
- */
- public void setLogLevel(long level) {
- fLogLevel = level;
- }
-
- @Override
- public Set<String> getCustomAttributes() {
- return fCustomAttributes.keySet();
- }
-
- @Override
- public String getCustomAttribute(String key) {
- return fCustomAttributes.get(key);
- }
-
- /**
- * Sets a custom attribute value.
- *
- * @param key
- * the key of the attribute
- * @param value
- * the value of the attribute
- * @since 2.0
- */
- public void setCustomAttribute(String key, String value) {
- fCustomAttributes.put(key, value);
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (!(obj instanceof EventDeclaration)) {
- return false;
- }
- EventDeclaration other = (EventDeclaration) obj;
- if (fContext == null) {
- if (other.fContext != null) {
- return false;
- }
- } else if (!fContext.equals(other.fContext)) {
- return false;
- }
- if (fFields == null) {
- if (other.fFields != null) {
- return false;
- }
- } else if (!fFields.equals(other.fFields)) {
- return false;
- }
- if (fId != (other.fId)) {
- return false;
- }
- if (fName == null) {
- if (other.fName != null) {
- return false;
- }
- } else if (!fName.equals(other.fName)) {
- return false;
- }
- if (fStream == null) {
- if (other.fStream != null) {
- return false;
- }
- } else if (!fStream.equals(other.fStream)) {
- return false;
- }
- if (!fCustomAttributes.equals(other.fCustomAttributes)) {
- return false;
- }
- return true;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = (prime * result)
- + ((fContext == null) ? 0 : fContext.hashCode());
- result = (prime * result) + ((fFields == null) ? 0 : fFields.hashCode());
- result = (prime * result) + fId;
- result = (prime * result) + ((fName == null) ? 0 : fName.hashCode());
- result = (prime * result) + ((fStream == null) ? 0 : fStream.hashCode());
- result = (prime * result) + fCustomAttributes.hashCode();
- return result;
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial Design and Grammar
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.internal.ctf.core.event.metadata;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.linuxtools.ctf.core.event.types.EnumDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.VariantDeclaration;
-import org.eclipse.linuxtools.internal.ctf.core.event.metadata.exceptions.ParseException;
-
-/**
- * <b><u>DeclarationScope</u></b>
- * <p>
- * A DeclarationScope keeps track of the various CTF declarations for a given
- * scope.
- *
- * TODO: The notion of "symbols" and the notion of "scope" are misused in this
- * parser, which leads to inefficient tree management. It should be cleaned up.
- *
- * @author Matthew Khouzam
- * @author Simon Marchi
- *
- */
-class DeclarationScope {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- private DeclarationScope fParentScope = null;
-
- private final Map<String, StructDeclaration> fStructs = new HashMap<>();
- private final Map<String, EnumDeclaration> fEnums = new HashMap<>();
- private final Map<String, VariantDeclaration> fVariants = new HashMap<>();
- private final Map<String, IDeclaration> fTypes = new HashMap<>();
- private final Map<String, IDeclaration> fIdentifiers = new HashMap<>();
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Creates a declaration scope with no parent.
- */
- public DeclarationScope() {
- }
-
- /**
- * Creates a declaration scope with the specified parent.
- *
- * @param parentScope
- * The parent of the newly created scope.
- */
- public DeclarationScope(DeclarationScope parentScope) {
- fParentScope = parentScope;
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- /**
- * Returns the parent of the current scope.
- *
- * @return The parent scope.
- */
- public DeclarationScope getParentScope() {
- return fParentScope;
- }
-
- // ------------------------------------------------------------------------
- // Registration operations
- // ------------------------------------------------------------------------
-
- /**
- * Registers a type declaration.
- *
- * @param name
- * The name of the type.
- * @param declaration
- * The type declaration.
- * @throws ParseException
- * if a type with the same name has already been defined.
- */
- public void registerType(String name, IDeclaration declaration)
- throws ParseException {
- /* Check if the type has been defined in the current scope */
- if (fTypes.containsKey(name)) {
- throw new ParseException("Type has already been defined:" + name); //$NON-NLS-1$
- }
-
- /* Add it to the register. */
- fTypes.put(name, declaration);
- }
-
- /**
- * Registers an identifier declaration.
- *
- * @param name
- * name of the identifier
- * @param declaration
- * the identfier's declaration
- * @throws ParseException
- * if an identifier with the same name has already been defined.
- */
- public void registerIdentifier(String name, IDeclaration declaration) throws ParseException {
- /* Check if the type has been defined in the current scope */
- if (fIdentifiers.containsKey(name)) {
- throw new ParseException("Identifier has already been defined:" + name); //$NON-NLS-1$
- }
-
- /* Add it to the register. */
- fIdentifiers.put(name, declaration);
- }
-
- /**
- * Registers a struct declaration.
- *
- * @param name
- * The name of the struct.
- * @param declaration
- * The declaration of the struct.
- * @throws ParseException
- * if a struct with the same name has already been registered.
- */
- public void registerStruct(String name, StructDeclaration declaration)
- throws ParseException {
- /* Check if the struct has been defined in the current scope. */
- if (fStructs.containsKey(name)) {
- throw new ParseException("Struct has already been defined:" + name); //$NON-NLS-1$
- }
-
- /* Add it to the register. */
- fStructs.put(name, declaration);
-
- /* It also defined a new type, so add it to the type declarations. */
- String structPrefix = "struct "; //$NON-NLS-1$
- registerType(structPrefix + name, declaration);
- }
-
- /**
- * Registers an enum declaration.
- *
- * @param name
- * The name of the enum.
- * @param declaration
- * The declaration of the enum.
- * @throws ParseException
- * if an enum with the same name has already been registered.
- */
- public void registerEnum(String name, EnumDeclaration declaration)
- throws ParseException {
- /* Check if the enum has been defined in the current scope. */
- if (lookupEnum(name) != null) {
- throw new ParseException("Enum has already been defined:" + name); //$NON-NLS-1$
- }
-
- /* Add it to the register. */
- fEnums.put(name, declaration);
-
- /* It also defined a new type, so add it to the type declarations. */
- String enumPrefix = "enum "; //$NON-NLS-1$
- registerType(enumPrefix + name, declaration);
- }
-
- /**
- * Registers a variant declaration.
- *
- * @param name
- * The name of the variant.
- * @param declaration
- * The declaration of the variant.
- * @throws ParseException
- * if a variant with the same name has already been registered.
- */
- public void registerVariant(String name, VariantDeclaration declaration)
- throws ParseException {
- /* Check if the variant has been defined in the current scope. */
- if (lookupVariant(name) != null) {
- throw new ParseException("Variant has already been defined:" + name); //$NON-NLS-1$
- }
-
- /* Add it to the register. */
- fVariants.put(name, declaration);
-
- /* It also defined a new type, so add it to the type declarations. */
- String variantPrefix = "variant "; //$NON-NLS-1$
- registerType(variantPrefix + name, declaration);
- }
-
- // ------------------------------------------------------------------------
- // Lookup operations
- // ------------------------------------------------------------------------
-
- /**
- * Looks up a type declaration in the current scope.
- *
- * @param name
- * The name of the type to search for.
- * @return The type declaration, or null if no type with that name has been
- * defined.
- */
- public IDeclaration lookupType(String name) {
- return fTypes.get(name);
- }
-
- /**
- * Looks up a type declaration in the current scope and recursively in the
- * parent scopes.
- *
- * @param name
- * The name of the type to search for.
- * @return The type declaration, or null if no type with that name has been
- * defined.
- */
- public IDeclaration lookupTypeRecursive(String name) {
- IDeclaration declaration = lookupType(name);
- if (declaration != null) {
- return declaration;
- } else if (fParentScope != null) {
- return fParentScope.lookupTypeRecursive(name);
- } else {
- return null;
- }
- }
-
- /**
- * Looks up a struct declaration.
- *
- * @param name
- * The name of the struct to search for.
- * @return The struct declaration, or null if no struct with that name has
- * been defined.
- */
- public StructDeclaration lookupStruct(String name) {
- return fStructs.get(name);
- }
-
- /**
- * Looks up a struct declaration in the current scope and recursively in the
- * parent scopes.
- *
- * @param name
- * The name of the struct to search for.
- * @return The struct declaration, or null if no struct with that name has
- * been defined.
- */
- public StructDeclaration lookupStructRecursive(String name) {
- StructDeclaration declaration = lookupStruct(name);
- if (declaration != null) {
- return declaration;
- } else if (fParentScope != null) {
- return fParentScope.lookupStructRecursive(name);
- } else {
- return null;
- }
- }
-
- /**
- * Looks up an enum declaration.
- *
- * @param name
- * The name of the enum to search for.
- * @return The enum declaration, or null if no enum with that name has been
- * defined.
- */
- public EnumDeclaration lookupEnum(String name) {
- return fEnums.get(name);
- }
-
- /**
- * Looks up an enum declaration in the current scope and recursively in the
- * parent scopes.
- *
- * @param name
- * The name of the enum to search for.
- * @return The enum declaration, or null if no enum with that name has been
- * defined.
- */
- public EnumDeclaration lookupEnumRecursive(String name) {
- EnumDeclaration declaration = lookupEnum(name);
- if (declaration != null) {
- return declaration;
- } else if (fParentScope != null) {
- return fParentScope.lookupEnumRecursive(name);
- } else {
- return null;
- }
- }
-
- /**
- * Looks up a variant declaration.
- *
- * @param name
- * The name of the variant to search for.
- * @return The variant declaration, or null if no variant with that name has
- * been defined.
- */
- public VariantDeclaration lookupVariant(String name) {
- return fVariants.get(name);
- }
-
- /**
- * Looks up a variant declaration in the current scope and recursively in
- * the parent scopes.
- *
- * @param name
- * The name of the variant to search for.
- * @return The variant declaration, or null if no variant with that name has
- * been defined.
- */
- public VariantDeclaration lookupVariantRecursive(String name) {
- VariantDeclaration declaration = lookupVariant(name);
- if (declaration != null) {
- return declaration;
- } else if (fParentScope != null) {
- return fParentScope.lookupVariantRecursive(name);
- } else {
- return null;
- }
- }
-
- /**
- * Lookup query for an identifier in this scope.
- *
- * @param identifier
- * the name of the identifier to search for. In the case of int
- * x; it would be "x"
- * @return the declaration of the type associated to that identifier
- */
- public IDeclaration lookupIdentifier(String identifier) {
- return fIdentifiers.get(identifier);
- }
-
- /**
- * Lookup query for an identifier through this scope and its ancestors.
- * An ancestor scope is a scope in which this scope is nested.
- *
- * @param identifier
- * the name of the identifier to search for. In the case of int
- * x; it would be "x"
- * @return the declaration of the type associated to that identifier
- */
- public IDeclaration lookupIdentifierRecursive(String identifier) {
- IDeclaration declaration = lookupIdentifier(identifier);
- if (declaration != null) {
- return declaration;
- } else if (fParentScope != null) {
- return fParentScope.lookupIdentifierRecursive(identifier);
- }
- return null;
- }
-
- /**
- * Get all the type names of this scope.
- *
- * @return The type names
- */
- public Set<String> getTypeNames() {
- return fTypes.keySet();
- }
-
- /**
- * Replace a type with a new one.
- *
- * @param name
- * The name of the type
- * @param newType
- * The type
- * @throws ParseException
- * If the type does not exist.
- */
- public void replaceType(String name, IDeclaration newType) throws ParseException {
- if (fTypes.containsKey(name)) {
- fTypes.put(name, newType);
- } else {
- throw new ParseException("Trace does not contain type:" + name); //$NON-NLS-1$
- }
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial Design and Grammar
- * Francis Giraldeau - Initial API and implementation
- * Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.internal.ctf.core.event.metadata;
-
-import java.math.BigInteger;
-import java.nio.ByteOrder;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Set;
-import java.util.UUID;
-
-import org.antlr.runtime.tree.CommonTree;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.CTFClock;
-import org.eclipse.linuxtools.ctf.core.event.types.Encoding;
-import org.eclipse.linuxtools.ctf.core.event.types.EnumDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.FloatDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IEventHeaderDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StringDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.VariantDeclaration;
-import org.eclipse.linuxtools.ctf.core.trace.CTFStream;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTrace;
-import org.eclipse.linuxtools.ctf.parser.CTFParser;
-import org.eclipse.linuxtools.internal.ctf.core.Activator;
-import org.eclipse.linuxtools.internal.ctf.core.event.EventDeclaration;
-import org.eclipse.linuxtools.internal.ctf.core.event.metadata.exceptions.ParseException;
-import org.eclipse.linuxtools.internal.ctf.core.event.types.ArrayDeclaration;
-import org.eclipse.linuxtools.internal.ctf.core.event.types.SequenceDeclaration;
-import org.eclipse.linuxtools.internal.ctf.core.event.types.StructDeclarationFlattener;
-import org.eclipse.linuxtools.internal.ctf.core.event.types.composite.EventHeaderCompactDeclaration;
-import org.eclipse.linuxtools.internal.ctf.core.event.types.composite.EventHeaderLargeDeclaration;
-
-/**
- * IOStructGen
- */
-public class IOStructGen {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- private static final @NonNull String MAP = "map"; //$NON-NLS-1$
- private static final @NonNull String ENCODING = "encoding"; //$NON-NLS-1$
- private static final @NonNull String BASE = "base"; //$NON-NLS-1$
- private static final @NonNull String SIZE = "size"; //$NON-NLS-1$
- private static final @NonNull String SIGNED = "signed"; //$NON-NLS-1$
- private static final @NonNull String LINE = "line"; //$NON-NLS-1$
- private static final @NonNull String FILE = "file"; //$NON-NLS-1$
- private static final @NonNull String IP = "ip"; //$NON-NLS-1$
- private static final @NonNull String FUNC = "func"; //$NON-NLS-1$
- private static final @NonNull String NAME = "name"; //$NON-NLS-1$
- private static final @NonNull String EMPTY_STRING = ""; //$NON-NLS-1$
- private static final int INTEGER_BASE_16 = 16;
- private static final int INTEGER_BASE_10 = 10;
- private static final int INTEGER_BASE_8 = 8;
- private static final int INTEGER_BASE_2 = 2;
- private static final long DEFAULT_ALIGNMENT = 8;
- private static final int DEFAULT_FLOAT_EXPONENT = 8;
- private static final int DEFAULT_FLOAT_MANTISSA = 24;
- private static final int DEFAULT_INT_BASE = 10;
- /**
- * The trace
- */
- private final CTFTrace fTrace;
- private CommonTree fTree;
-
- /**
- * The current declaration scope.
- */
- private DeclarationScope fScope = null;
-
- /**
- * Data helpers needed for streaming
- */
-
- private boolean fHasBeenParsed = false;
-
- // ------------------------------------------------------------------------
- // Constructor
- // ------------------------------------------------------------------------
-
- /**
- * Constructor
- *
- * @param tree
- * the tree (ANTLR generated) with the parsed TSDL data.
- * @param trace
- * the trace containing the places to put all the read metadata
- */
- public IOStructGen(CommonTree tree, CTFTrace trace) {
- fTrace = trace;
- fTree = tree;
-
- }
-
- /**
- * Parse the tree and populate the trace defined in the constructor.
- *
- * @throws ParseException
- * If there was a problem parsing the metadata
- */
- public void generate() throws ParseException {
- parseRoot(fTree);
- }
-
- /**
- * Parse a partial tree and populate the trace defined in the constructor.
- * Does not check for a "trace" block as there is only one in the trace and
- * thus
- *
- * @throws ParseException
- * If there was a problem parsing the metadata
- */
- public void generateFragment() throws ParseException {
- parseIncompleteRoot(fTree);
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- /**
- * Sets a new tree to parse
- *
- * @param newTree
- * the new tree to parse
- */
- public void setTree(CommonTree newTree) {
- fTree = newTree;
- }
-
- /**
- * Parse the root node.
- *
- * @param root
- * A ROOT node.
- * @throws ParseException
- */
- private void parseRoot(CommonTree root) throws ParseException {
-
- List<CommonTree> children = root.getChildren();
-
- CommonTree traceNode = null;
- List<CommonTree> streams = new ArrayList<>();
- List<CommonTree> events = new ArrayList<>();
- List<CommonTree> declarations = new ArrayList<>();
- List<CommonTree> environments = new ArrayList<>();
- List<CommonTree> clocks = new ArrayList<>();
- List<CommonTree> callsites = new ArrayList<>();
-
- /* Create a new declaration scope with no parent. */
- pushScope();
-
- for (CommonTree child : children) {
- final int type = child.getType();
- switch (type) {
- case CTFParser.DECLARATION:
- declarations.add(child);
- break;
- case CTFParser.TRACE:
- if (traceNode != null) {
- throw new ParseException("Only one trace block is allowed"); //$NON-NLS-1$
- }
- traceNode = child;
- break;
- case CTFParser.STREAM:
- streams.add(child);
- break;
- case CTFParser.EVENT:
- events.add(child);
- break;
- case CTFParser.CLOCK:
- clocks.add(child);
- break;
- case CTFParser.ENV:
- environments.add(child);
- break;
- case CTFParser.CALLSITE:
- callsites.add(child);
- break;
- default:
- childTypeError(child);
- }
- }
- for (CommonTree decl : declarations) {
- parseRootDeclaration(decl);
- }
- if (traceNode == null) {
- throw new ParseException("Missing trace block"); //$NON-NLS-1$
- }
-
- parseTrace(traceNode);
-
- for (CommonTree environment : environments) {
- parseEnvironment(environment);
- }
- for (CommonTree clock : clocks) {
- parseClock(clock);
- }
- for (CommonTree callsite : callsites) {
- parseCallsite(callsite);
- }
-
- if (!streams.isEmpty()) {
- for (CommonTree stream : streams) {
- parseStream(stream);
- }
- } else {
- /* Add an empty stream that will have a null id */
- fTrace.addStream(new CTFStream(fTrace));
- }
-
- for (CommonTree event : events) {
- parseEvent(event);
- }
- popScope();
- fHasBeenParsed = true;
- }
-
- private void parseIncompleteRoot(CommonTree root) throws ParseException {
- List<CommonTree> children = root.getChildren();
-
- if (!fHasBeenParsed) {
- throw new ParseException("You need to run generate first"); //$NON-NLS-1$
- }
- List<CommonTree> streams = new ArrayList<>();
- List<CommonTree> events = new ArrayList<>();
- List<CommonTree> declarations = new ArrayList<>();
- List<CommonTree> environments = new ArrayList<>();
- List<CommonTree> clocks = new ArrayList<>();
- List<CommonTree> callsites = new ArrayList<>();
- /* Create a new declaration scope with no parent. */
- pushScope();
-
- for (CommonTree child : children) {
- final int type = child.getType();
- switch (type) {
- case CTFParser.DECLARATION:
- declarations.add(child);
- break;
- case CTFParser.TRACE:
- throw new ParseException("Trace block defined here, please use generate and not generateFragment to parse this fragment"); //$NON-NLS-1$
- case CTFParser.STREAM:
- streams.add(child);
- break;
- case CTFParser.EVENT:
- events.add(child);
- break;
- case CTFParser.CLOCK:
- clocks.add(child);
- break;
- case CTFParser.ENV:
- environments.add(child);
- break;
- case CTFParser.CALLSITE:
- callsites.add(child);
- break;
- default:
- childTypeError(child);
- }
- }
- for (CommonTree decl : declarations) {
- parseRootDeclaration(decl);
- }
-
- for (CommonTree environment : environments) {
- parseEnvironment(environment);
- }
- for (CommonTree clock : clocks) {
- parseClock(clock);
- }
- for (CommonTree callsite : callsites) {
- parseCallsite(callsite);
- }
-
- for (CommonTree stream : streams) {
- parseStream(stream);
- }
-
- for (CommonTree event : events) {
- parseEvent(event);
- }
- popScope();
- }
-
- private void parseCallsite(CommonTree callsite) {
-
- List<CommonTree> children = callsite.getChildren();
- String name = null;
- String funcName = null;
- long lineNumber = -1;
- long ip = -1;
- String fileName = null;
-
- for (CommonTree child : children) {
- String left;
- /* this is a regex to find the leading and trailing quotes */
- final String regex = "^\"|\"$"; //$NON-NLS-1$
- /*
- * this is to replace the previous quotes with nothing...
- * effectively deleting them
- */
- final String nullString = EMPTY_STRING;
- left = child.getChild(0).getChild(0).getChild(0).getText();
- if (left.equals(NAME)) {
- name = child.getChild(1).getChild(0).getChild(0).getText().replaceAll(regex, nullString);
- } else if (left.equals(FUNC)) {
- funcName = child.getChild(1).getChild(0).getChild(0).getText().replaceAll(regex, nullString);
- } else if (left.equals(IP)) {
- ip = Long.decode(child.getChild(1).getChild(0).getChild(0).getText());
- } else if (left.equals(FILE)) {
- fileName = child.getChild(1).getChild(0).getChild(0).getText().replaceAll(regex, nullString);
- } else if (left.equals(LINE)) {
- lineNumber = Long.parseLong(child.getChild(1).getChild(0).getChild(0).getText());
- }
- }
- fTrace.addCallsite(name, funcName, ip, fileName, lineNumber);
- }
-
- private void parseEnvironment(CommonTree environment) {
- List<CommonTree> children = environment.getChildren();
- for (CommonTree child : children) {
- String left;
- String right;
- left = child.getChild(0).getChild(0).getChild(0).getText();
- right = child.getChild(1).getChild(0).getChild(0).getText();
- fTrace.addEnvironmentVar(left, right);
- }
- }
-
- private void parseClock(CommonTree clock) throws ParseException {
- List<CommonTree> children = clock.getChildren();
- CTFClock ctfClock = new CTFClock();
- for (CommonTree child : children) {
- final String key = child.getChild(0).getChild(0).getChild(0).getText();
- final CommonTree value = (CommonTree) child.getChild(1).getChild(0).getChild(0);
- final int type = value.getType();
- final String text = value.getText();
- switch (type) {
- case CTFParser.INTEGER:
- case CTFParser.DECIMAL_LITERAL:
- /*
- * Not a pretty hack, this is to make sure that there is no
- * number overflow due to 63 bit integers. The offset should
- * only really be an issue in the year 2262. the tracer in C/ASM
- * can write an offset in an unsigned 64 bit long. In java, the
- * last bit, being set to 1 will be read as a negative number,
- * but since it is too big a positive it will throw an
- * exception. this will happen in 2^63 ns from 1970. Therefore
- * 293 years from 1970
- */
- Long numValue;
- try {
- numValue = Long.parseLong(text);
- } catch (NumberFormatException e) {
- throw new ParseException("Number conversion issue with " + text, e); //$NON-NLS-1$
- }
- ctfClock.addAttribute(key, numValue);
- break;
- default:
- ctfClock.addAttribute(key, text);
- }
-
- }
- String nameValue = ctfClock.getName();
- fTrace.addClock(nameValue, ctfClock);
- }
-
- private void parseTrace(CommonTree traceNode) throws ParseException {
-
- List<CommonTree> children = traceNode.getChildren();
- if (children == null) {
- throw new ParseException("Trace block is empty"); //$NON-NLS-1$
- }
-
- pushScope();
-
- for (CommonTree child : children) {
- switch (child.getType()) {
- case CTFParser.TYPEALIAS:
- parseTypealias(child);
- break;
- case CTFParser.TYPEDEF:
- parseTypedef(child);
- break;
- case CTFParser.CTF_EXPRESSION_TYPE:
- case CTFParser.CTF_EXPRESSION_VAL:
- parseTraceDeclaration(child);
- break;
- default:
- childTypeError(child);
- break;
- }
- }
-
- /*
- * If trace byte order was not specified and not using packet based
- * metadata
- */
- if (fTrace.getByteOrder() == null) {
- throw new ParseException("Trace byte order not set"); //$NON-NLS-1$
- }
-
- popScope();
- }
-
- private void parseTraceDeclaration(CommonTree traceDecl)
- throws ParseException {
-
- /* There should be a left and right */
-
- CommonTree leftNode = (CommonTree) traceDecl.getChild(0);
- CommonTree rightNode = (CommonTree) traceDecl.getChild(1);
-
- List<CommonTree> leftStrings = leftNode.getChildren();
-
- if (!isAnyUnaryString(leftStrings.get(0))) {
- throw new ParseException("Left side of CTF assignment must be a string"); //$NON-NLS-1$
- }
-
- String left = concatenateUnaryStrings(leftStrings);
-
- if (left.equals(MetadataStrings.MAJOR)) {
- if (fTrace.majorIsSet()) {
- throw new ParseException("major is already set"); //$NON-NLS-1$
- }
-
- fTrace.setMajor(getMajorOrMinor(rightNode));
- } else if (left.equals(MetadataStrings.MINOR)) {
- if (fTrace.minorIsSet()) {
- throw new ParseException("minor is already set"); //$NON-NLS-1$
- }
-
- fTrace.setMinor(getMajorOrMinor(rightNode));
- } else if (left.equals(MetadataStrings.UUID_STRING)) {
- UUID uuid = getUUID(rightNode);
-
- /*
- * If uuid was already set by a metadata packet, compare it to see
- * if it matches
- */
- if (fTrace.uuidIsSet()) {
- if (fTrace.getUUID().compareTo(uuid) != 0) {
- throw new ParseException("UUID mismatch. Packet says " //$NON-NLS-1$
- + fTrace.getUUID() + " but metadata says " + uuid); //$NON-NLS-1$
- }
- } else {
- fTrace.setUUID(uuid);
- }
-
- } else if (left.equals(MetadataStrings.BYTE_ORDER)) {
- ByteOrder byteOrder = getByteOrder(rightNode);
-
- /*
- * If byte order was already set by a metadata packet, compare it to
- * see if it matches
- */
- if (fTrace.getByteOrder() != null) {
- if (fTrace.getByteOrder() != byteOrder) {
- throw new ParseException(
- "Endianness mismatch. Magic number says " //$NON-NLS-1$
- + fTrace.getByteOrder()
- + " but metadata says " + byteOrder); //$NON-NLS-1$
- }
- } else {
- fTrace.setByteOrder(byteOrder);
- final DeclarationScope parentScope = fScope.getParentScope();
-
- for (String type : parentScope.getTypeNames()) {
- IDeclaration d = parentScope.lookupType(type);
- if (d instanceof IntegerDeclaration) {
- addByteOrder(byteOrder, parentScope, type, (IntegerDeclaration) d);
- } else if (d instanceof StructDeclaration) {
- setAlign(parentScope, (StructDeclaration) d, byteOrder);
- }
- }
- }
- } else if (left.equals(MetadataStrings.PACKET_HEADER)) {
- if (fTrace.packetHeaderIsSet()) {
- throw new ParseException("packet.header already defined"); //$NON-NLS-1$
- }
-
- CommonTree typeSpecifier = (CommonTree) rightNode.getChild(0);
-
- if (typeSpecifier.getType() != CTFParser.TYPE_SPECIFIER_LIST) {
- throw new ParseException("packet.header expects a type specifier"); //$NON-NLS-1$
- }
-
- IDeclaration packetHeaderDecl = parseTypeSpecifierList(
- typeSpecifier, null);
-
- if (!(packetHeaderDecl instanceof StructDeclaration)) {
- throw new ParseException("packet.header expects a struct"); //$NON-NLS-1$
- }
-
- fTrace.setPacketHeader((StructDeclaration) packetHeaderDecl);
- } else {
- Activator.log(IStatus.WARNING, Messages.IOStructGen_UnknownTraceAttributeWarning + " " + left); //$NON-NLS-1$
- }
- }
-
- private static void addByteOrder(ByteOrder byteOrder,
- final DeclarationScope parentScope, String name,
- IntegerDeclaration decl) throws ParseException {
-
- if (decl.getByteOrder() != byteOrder) {
- IntegerDeclaration newI;
- newI = IntegerDeclaration.createDeclaration(decl.getLength(), decl.isSigned(),
- decl.getBase(), byteOrder, decl.getEncoding(),
- decl.getClock(), decl.getAlignment());
- parentScope.replaceType(name, newI);
- }
- }
-
- private void setAlign(DeclarationScope parentScope, StructDeclaration sd,
- ByteOrder byteOrder) throws ParseException {
-
- for (String s : sd.getFieldsList()) {
- IDeclaration d = sd.getField(s);
-
- if (d instanceof StructDeclaration) {
- setAlign(parentScope, (StructDeclaration) d, byteOrder);
-
- } else if (d instanceof VariantDeclaration) {
- setAlign(parentScope, (VariantDeclaration) d, byteOrder);
- } else if (d instanceof IntegerDeclaration) {
- IntegerDeclaration decl = (IntegerDeclaration) d;
- if (decl.getByteOrder() != byteOrder) {
- IntegerDeclaration newI;
- newI = IntegerDeclaration.createDeclaration(decl.getLength(),
- decl.isSigned(), decl.getBase(), byteOrder,
- decl.getEncoding(), decl.getClock(),
- decl.getAlignment());
- sd.getFields().put(s, newI);
- }
- }
- }
- }
-
- private void setAlign(DeclarationScope parentScope, VariantDeclaration vd,
- ByteOrder byteOrder) throws ParseException {
-
- for (String s : vd.getFields().keySet()) {
- IDeclaration d = vd.getFields().get(s);
-
- if (d instanceof StructDeclaration) {
- setAlign(parentScope, (StructDeclaration) d, byteOrder);
-
- } else if (d instanceof IntegerDeclaration) {
- IntegerDeclaration decl = (IntegerDeclaration) d;
- IntegerDeclaration newI;
- newI = IntegerDeclaration.createDeclaration(decl.getLength(),
- decl.isSigned(), decl.getBase(), byteOrder,
- decl.getEncoding(), decl.getClock(),
- decl.getAlignment());
- vd.getFields().put(s, newI);
- }
- }
- }
-
- private void parseStream(CommonTree streamNode) throws ParseException {
-
- CTFStream stream = new CTFStream(fTrace);
-
- List<CommonTree> children = streamNode.getChildren();
- if (children == null) {
- throw new ParseException("Empty stream block"); //$NON-NLS-1$
- }
-
- pushScope();
-
- for (CommonTree child : children) {
- switch (child.getType()) {
- case CTFParser.TYPEALIAS:
- parseTypealias(child);
- break;
- case CTFParser.TYPEDEF:
- parseTypedef(child);
- break;
- case CTFParser.CTF_EXPRESSION_TYPE:
- case CTFParser.CTF_EXPRESSION_VAL:
- parseStreamDeclaration(child, stream);
- break;
- default:
- childTypeError(child);
- break;
- }
- }
-
- if (stream.isIdSet() &&
- (!fTrace.packetHeaderIsSet() || !fTrace.getPacketHeader().hasField(MetadataStrings.STREAM_ID))) {
- throw new ParseException("Stream has an ID, but there is no stream_id field in packet header."); //$NON-NLS-1$
- }
-
- fTrace.addStream(stream);
-
- popScope();
- }
-
- private void parseStreamDeclaration(CommonTree streamDecl, CTFStream stream)
- throws ParseException {
-
- /* There should be a left and right */
-
- CommonTree leftNode = (CommonTree) streamDecl.getChild(0);
- CommonTree rightNode = (CommonTree) streamDecl.getChild(1);
-
- List<CommonTree> leftStrings = leftNode.getChildren();
-
- if (!isAnyUnaryString(leftStrings.get(0))) {
- throw new ParseException("Left side of CTF assignment must be a string"); //$NON-NLS-1$
- }
-
- String left = concatenateUnaryStrings(leftStrings);
-
- if (left.equals(MetadataStrings.ID)) {
- if (stream.isIdSet()) {
- throw new ParseException("stream id already defined"); //$NON-NLS-1$
- }
-
- long streamID = getStreamID(rightNode);
-
- stream.setId(streamID);
- } else if (left.equals(MetadataStrings.EVENT_HEADER)) {
- if (stream.isEventHeaderSet()) {
- throw new ParseException("event.header already defined"); //$NON-NLS-1$
- }
-
- CommonTree typeSpecifier = (CommonTree) rightNode.getChild(0);
-
- if (typeSpecifier.getType() != CTFParser.TYPE_SPECIFIER_LIST) {
- throw new ParseException("event.header expects a type specifier"); //$NON-NLS-1$
- }
-
- IDeclaration eventHeaderDecl = parseTypeSpecifierList(
- typeSpecifier, null);
-
- if (eventHeaderDecl instanceof StructDeclaration) {
- stream.setEventHeader((StructDeclaration) eventHeaderDecl);
- } else if (eventHeaderDecl instanceof IEventHeaderDeclaration) {
- stream.setEventHeader((IEventHeaderDeclaration) eventHeaderDecl);
- } else {
- throw new ParseException("event.header expects a struct"); //$NON-NLS-1$
- }
-
- } else if (left.equals(MetadataStrings.EVENT_CONTEXT)) {
- if (stream.isEventContextSet()) {
- throw new ParseException("event.context already defined"); //$NON-NLS-1$
- }
-
- CommonTree typeSpecifier = (CommonTree) rightNode.getChild(0);
-
- if (typeSpecifier.getType() != CTFParser.TYPE_SPECIFIER_LIST) {
- throw new ParseException("event.context expects a type specifier"); //$NON-NLS-1$
- }
-
- IDeclaration eventContextDecl = parseTypeSpecifierList(
- typeSpecifier, null);
-
- if (!(eventContextDecl instanceof StructDeclaration)) {
- throw new ParseException("event.context expects a struct"); //$NON-NLS-1$
- }
-
- stream.setEventContext((StructDeclaration) eventContextDecl);
- } else if (left.equals(MetadataStrings.PACKET_CONTEXT)) {
- if (stream.isPacketContextSet()) {
- throw new ParseException("packet.context already defined"); //$NON-NLS-1$
- }
-
- CommonTree typeSpecifier = (CommonTree) rightNode.getChild(0);
-
- if (typeSpecifier.getType() != CTFParser.TYPE_SPECIFIER_LIST) {
- throw new ParseException("packet.context expects a type specifier"); //$NON-NLS-1$
- }
-
- IDeclaration packetContextDecl = parseTypeSpecifierList(
- typeSpecifier, null);
-
- if (!(packetContextDecl instanceof StructDeclaration)) {
- throw new ParseException("packet.context expects a struct"); //$NON-NLS-1$
- }
-
- stream.setPacketContext((StructDeclaration) packetContextDecl);
- } else {
- Activator.log(IStatus.WARNING, Messages.IOStructGen_UnknownStreamAttributeWarning + " " + left); //$NON-NLS-1$
- }
- }
-
- private void parseEvent(CommonTree eventNode) throws ParseException {
-
- List<CommonTree> children = eventNode.getChildren();
- if (children == null) {
- throw new ParseException("Empty event block"); //$NON-NLS-1$
- }
-
- EventDeclaration event = new EventDeclaration();
-
- pushScope();
-
- for (CommonTree child : children) {
- switch (child.getType()) {
- case CTFParser.TYPEALIAS:
- parseTypealias(child);
- break;
- case CTFParser.TYPEDEF:
- parseTypedef(child);
- break;
- case CTFParser.CTF_EXPRESSION_TYPE:
- case CTFParser.CTF_EXPRESSION_VAL:
- parseEventDeclaration(child, event);
- break;
- default:
- childTypeError(child);
- break;
- }
- }
-
- if (!event.nameIsSet()) {
- throw new ParseException("Event name not set"); //$NON-NLS-1$
- }
-
- /*
- * If the event did not specify a stream, then the trace must be single
- * stream
- */
- if (!event.streamIsSet()) {
- if (fTrace.nbStreams() > 1) {
- throw new ParseException("Event without stream_id with more than one stream"); //$NON-NLS-1$
- }
-
- /*
- * If the event did not specify a stream, the only existing stream
- * must not have an id. Note: That behavior could be changed, it
- * could be possible to just get the only existing stream, whatever
- * is its id.
- */
- CTFStream stream = fTrace.getStream(null);
-
- if (stream != null) {
- event.setStream(stream);
- } else {
- throw new ParseException("Event without stream_id, but there is no stream without id"); //$NON-NLS-1$
- }
- }
-
- /*
- * Add the event to the stream.
- */
- event.getStream().addEvent(event);
-
- popScope();
- }
-
- private void parseEventDeclaration(CommonTree eventDecl,
- EventDeclaration event) throws ParseException {
-
- /* There should be a left and right */
-
- CommonTree leftNode = (CommonTree) eventDecl.getChild(0);
- CommonTree rightNode = (CommonTree) eventDecl.getChild(1);
-
- List<CommonTree> leftStrings = leftNode.getChildren();
-
- if (!isAnyUnaryString(leftStrings.get(0))) {
- throw new ParseException("Left side of CTF assignment must be a string"); //$NON-NLS-1$
- }
-
- String left = concatenateUnaryStrings(leftStrings);
-
- if (left.equals(MetadataStrings.NAME2)) {
- if (event.nameIsSet()) {
- throw new ParseException("name already defined"); //$NON-NLS-1$
- }
-
- String name = getEventName(rightNode);
-
- event.setName(name);
- } else if (left.equals(MetadataStrings.ID)) {
- if (event.idIsSet()) {
- throw new ParseException("id already defined"); //$NON-NLS-1$
- }
-
- long id = getEventID(rightNode);
- if (id > Integer.MAX_VALUE) {
- throw new ParseException("id is greater than int.maxvalue, unsupported. id : " + id); //$NON-NLS-1$
- }
- if (id < 0) {
- throw new ParseException("negative id, unsupported. id : " + id); //$NON-NLS-1$
- }
- event.setId((int) id);
- } else if (left.equals(MetadataStrings.STREAM_ID)) {
- if (event.streamIsSet()) {
- throw new ParseException("stream id already defined"); //$NON-NLS-1$
- }
-
- long streamId = getStreamID(rightNode);
-
- CTFStream stream = fTrace.getStream(streamId);
-
- if (stream == null) {
- throw new ParseException("Stream " + streamId + " not found"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- event.setStream(stream);
- } else if (left.equals(MetadataStrings.CONTEXT)) {
- if (event.contextIsSet()) {
- throw new ParseException("context already defined"); //$NON-NLS-1$
- }
-
- CommonTree typeSpecifier = (CommonTree) rightNode.getChild(0);
-
- if (typeSpecifier.getType() != CTFParser.TYPE_SPECIFIER_LIST) {
- throw new ParseException("context expects a type specifier"); //$NON-NLS-1$
- }
-
- IDeclaration contextDecl = parseTypeSpecifierList(typeSpecifier,
- null);
-
- if (!(contextDecl instanceof StructDeclaration)) {
- throw new ParseException("context expects a struct"); //$NON-NLS-1$
- }
-
- event.setContext((StructDeclaration) contextDecl);
- } else if (left.equals(MetadataStrings.FIELDS_STRING)) {
- if (event.fieldsIsSet()) {
- throw new ParseException("fields already defined"); //$NON-NLS-1$
- }
-
- CommonTree typeSpecifier = (CommonTree) rightNode.getChild(0);
-
- if (typeSpecifier.getType() != CTFParser.TYPE_SPECIFIER_LIST) {
- throw new ParseException("fields expects a type specifier"); //$NON-NLS-1$
- }
-
- IDeclaration fieldsDecl;
- fieldsDecl = parseTypeSpecifierList(typeSpecifier, null);
-
- if (!(fieldsDecl instanceof StructDeclaration)) {
- throw new ParseException("fields expects a struct"); //$NON-NLS-1$
- }
- /*
- * The underscores in the event names. These underscores were added
- * by the LTTng tracer.
- */
- final StructDeclaration fields = (StructDeclaration) fieldsDecl;
- event.setFields(fields);
- } else if (left.equals(MetadataStrings.LOGLEVEL2)) {
- long logLevel = parseUnaryInteger((CommonTree) rightNode.getChild(0));
- event.setLogLevel(logLevel);
- } else {
- /* Custom event attribute, we'll add it to the attributes map */
- String right = parseUnaryString((CommonTree) rightNode.getChild(0));
- event.setCustomAttribute(left, right);
- }
- }
-
- /**
- * Parses a declaration at the root level.
- *
- * @param declaration
- * The declaration subtree.
- * @throws ParseException
- */
- private void parseRootDeclaration(CommonTree declaration)
- throws ParseException {
-
- List<CommonTree> children = declaration.getChildren();
-
- for (CommonTree child : children) {
- switch (child.getType()) {
- case CTFParser.TYPEDEF:
- parseTypedef(child);
- break;
- case CTFParser.TYPEALIAS:
- parseTypealias(child);
- break;
- case CTFParser.TYPE_SPECIFIER_LIST:
- parseTypeSpecifierList(child, null);
- break;
- default:
- childTypeError(child);
- }
- }
- }
-
- /**
- * Parses a typealias node. It parses the target, the alias, and registers
- * the type in the current scope.
- *
- * @param typealias
- * A TYPEALIAS node.
- * @throws ParseException
- */
- private void parseTypealias(CommonTree typealias) throws ParseException {
-
- List<CommonTree> children = typealias.getChildren();
-
- CommonTree target = null;
- CommonTree alias = null;
-
- for (CommonTree child : children) {
- switch (child.getType()) {
- case CTFParser.TYPEALIAS_TARGET:
- target = child;
- break;
- case CTFParser.TYPEALIAS_ALIAS:
- alias = child;
- break;
- default:
- childTypeError(child);
- break;
- }
- }
-
- IDeclaration targetDeclaration = parseTypealiasTarget(target);
-
- if ((targetDeclaration instanceof VariantDeclaration)
- && ((VariantDeclaration) targetDeclaration).isTagged()) {
- throw new ParseException("Typealias of untagged variant is not permitted"); //$NON-NLS-1$
- }
-
- String aliasString = parseTypealiasAlias(alias);
-
- getCurrentScope().registerType(aliasString, targetDeclaration);
- }
-
- /**
- * Parses the target part of a typealias and gets the corresponding
- * declaration.
- *
- * @param target
- * A TYPEALIAS_TARGET node.
- * @return The corresponding declaration.
- * @throws ParseException
- */
- private IDeclaration parseTypealiasTarget(CommonTree target)
- throws ParseException {
-
- List<CommonTree> children = target.getChildren();
-
- CommonTree typeSpecifierList = null;
- CommonTree typeDeclaratorList = null;
- CommonTree typeDeclarator = null;
- StringBuilder identifierSB = new StringBuilder();
-
- for (CommonTree child : children) {
- switch (child.getType()) {
- case CTFParser.TYPE_SPECIFIER_LIST:
- typeSpecifierList = child;
- break;
- case CTFParser.TYPE_DECLARATOR_LIST:
- typeDeclaratorList = child;
- break;
- default:
- childTypeError(child);
- break;
- }
- }
-
- if (typeDeclaratorList != null) {
- /*
- * Only allow one declarator
- *
- * eg: "typealias uint8_t *, ** := puint8_t;" is not permitted,
- * otherwise the new type puint8_t would maps to two different
- * types.
- */
- if (typeDeclaratorList.getChildCount() != 1) {
- throw new ParseException("Only one type declarator is allowed in the typealias target"); //$NON-NLS-1$
- }
-
- typeDeclarator = (CommonTree) typeDeclaratorList.getChild(0);
- }
-
- /* Parse the target type and get the declaration */
- IDeclaration targetDeclaration = parseTypeDeclarator(typeDeclarator,
- typeSpecifierList, identifierSB);
-
- /*
- * We don't allow identifier in the target
- *
- * eg: "typealias uint8_t* hello := puint8_t;", the "hello" is not
- * permitted
- */
- if (identifierSB.length() > 0) {
- throw new ParseException("Identifier (" + identifierSB.toString() //$NON-NLS-1$
- + ") not expected in the typealias target"); //$NON-NLS-1$
- }
-
- return targetDeclaration;
- }
-
- /**
- * Parses the alias part of a typealias. It parses the underlying specifier
- * list and declarator and creates the string representation that will be
- * used to register the type.
- *
- * @param alias
- * A TYPEALIAS_ALIAS node.
- * @return The string representation of the alias.
- * @throws ParseException
- */
- private static String parseTypealiasAlias(CommonTree alias)
- throws ParseException {
-
- List<CommonTree> children = alias.getChildren();
-
- CommonTree typeSpecifierList = null;
- CommonTree typeDeclaratorList = null;
- CommonTree typeDeclarator = null;
- List<CommonTree> pointers = new LinkedList<>();
-
- for (CommonTree child : children) {
- switch (child.getType()) {
- case CTFParser.TYPE_SPECIFIER_LIST:
- typeSpecifierList = child;
- break;
- case CTFParser.TYPE_DECLARATOR_LIST:
- typeDeclaratorList = child;
- break;
- default:
- childTypeError(child);
- break;
- }
- }
-
- /* If there is a type declarator list, extract the pointers */
- if (typeDeclaratorList != null) {
- /*
- * Only allow one declarator
- *
- * eg: "typealias uint8_t := puint8_t *, **;" is not permitted.
- */
- if (typeDeclaratorList.getChildCount() != 1) {
- throw new ParseException("Only one type declarator is allowed in the typealias alias"); //$NON-NLS-1$
- }
-
- typeDeclarator = (CommonTree) typeDeclaratorList.getChild(0);
-
- List<CommonTree> typeDeclaratorChildren = typeDeclarator.getChildren();
-
- for (CommonTree child : typeDeclaratorChildren) {
- switch (child.getType()) {
- case CTFParser.POINTER:
- pointers.add(child);
- break;
- case CTFParser.IDENTIFIER:
- throw new ParseException("Identifier (" + child.getText() //$NON-NLS-1$
- + ") not expected in the typealias target"); //$NON-NLS-1$
- default:
- childTypeError(child);
- break;
- }
- }
- }
-
- return createTypeDeclarationString(typeSpecifierList, pointers);
- }
-
- /**
- * Parses a typedef node. This creates and registers a new declaration for
- * each declarator found in the typedef.
- *
- * @param typedef
- * A TYPEDEF node.
- * @throws ParseException
- * If there is an error creating the declaration.
- */
- private void parseTypedef(CommonTree typedef) throws ParseException {
-
- CommonTree typeDeclaratorListNode = (CommonTree) typedef.getFirstChildWithType(CTFParser.TYPE_DECLARATOR_LIST);
-
- CommonTree typeSpecifierListNode = (CommonTree) typedef.getFirstChildWithType(CTFParser.TYPE_SPECIFIER_LIST);
-
- List<CommonTree> typeDeclaratorList = typeDeclaratorListNode.getChildren();
-
- for (CommonTree typeDeclaratorNode : typeDeclaratorList) {
- StringBuilder identifierSB = new StringBuilder();
-
- IDeclaration typeDeclaration = parseTypeDeclarator(
- typeDeclaratorNode, typeSpecifierListNode, identifierSB);
-
- if ((typeDeclaration instanceof VariantDeclaration)
- && ((VariantDeclaration) typeDeclaration).isTagged()) {
- throw new ParseException("Typealias of untagged variant is not permitted"); //$NON-NLS-1$
- }
-
- getCurrentScope().registerType(identifierSB.toString(),
- typeDeclaration);
- }
- }
-
- /**
- * Parses a pair type declarator / type specifier list and returns the
- * corresponding declaration. If it is present, it also writes the
- * identifier of the declarator in the given {@link StringBuilder}.
- *
- * @param typeDeclarator
- * A TYPE_DECLARATOR node.
- * @param typeSpecifierList
- * A TYPE_SPECIFIER_LIST node.
- * @param identifierSB
- * A StringBuilder that will receive the identifier found in the
- * declarator.
- * @return The corresponding declaration.
- * @throws ParseException
- * If there is an error finding or creating the declaration.
- */
- private IDeclaration parseTypeDeclarator(CommonTree typeDeclarator,
- CommonTree typeSpecifierList, StringBuilder identifierSB)
- throws ParseException {
-
- IDeclaration declaration = null;
- List<CommonTree> children = null;
- List<CommonTree> pointers = new LinkedList<>();
- List<CommonTree> lengths = new LinkedList<>();
- CommonTree identifier = null;
-
- /* Separate the tokens by type */
- if (typeDeclarator != null) {
- children = typeDeclarator.getChildren();
- for (CommonTree child : children) {
-
- switch (child.getType()) {
- case CTFParser.POINTER:
- pointers.add(child);
- break;
- case CTFParser.IDENTIFIER:
- identifier = child;
- break;
- case CTFParser.LENGTH:
- lengths.add(child);
- break;
- default:
- childTypeError(child);
- break;
- }
- }
-
- }
-
- /*
- * Parse the type specifier list, which is the "base" type. For example,
- * it would be int in int a[3][len].
- */
- declaration = parseTypeSpecifierList(typeSpecifierList, pointers);
-
- /*
- * Each length subscript means that we must create a nested array or
- * sequence. For example, int a[3][len] means that we have an array of 3
- * (sequences of length 'len' of (int)).
- */
- if (!lengths.isEmpty()) {
- /* We begin at the end */
- Collections.reverse(lengths);
-
- for (CommonTree length : lengths) {
- /*
- * By looking at the first expression, we can determine whether
- * it is an array or a sequence.
- */
- List<CommonTree> lengthChildren = length.getChildren();
-
- CommonTree first = lengthChildren.get(0);
- if (isUnaryInteger(first)) {
- /* Array */
- int arrayLength = (int) parseUnaryInteger(first);
-
- if (arrayLength < 1) {
- throw new ParseException("Array length is negative"); //$NON-NLS-1$
- }
-
- /* Create the array declaration. */
- declaration = new ArrayDeclaration(arrayLength, declaration);
- } else if (isAnyUnaryString(first)) {
- /* Sequence */
- String lengthName = concatenateUnaryStrings(lengthChildren);
-
- /* check that lengthName was declared */
- if (isSignedIntegerField(lengthName)) {
- throw new ParseException("Sequence declared with length that is not an unsigned integer"); //$NON-NLS-1$
- }
- /* Create the sequence declaration. */
- declaration = new SequenceDeclaration(lengthName,
- declaration);
- } else {
- childTypeError(first);
- }
- }
- }
-
- if (identifier != null) {
- identifierSB.append(identifier.getText());
- }
-
- return declaration;
- }
-
- private boolean isSignedIntegerField(String lengthName) throws ParseException {
- IDeclaration decl = getCurrentScope().lookupIdentifierRecursive(lengthName);
- if (decl instanceof IntegerDeclaration) {
- return ((IntegerDeclaration) decl).isSigned();
- }
- throw new ParseException("Is not an integer: " + lengthName); //$NON-NLS-1$
-
- }
-
- /**
- * Parses a type specifier list and returns the corresponding declaration.
- *
- * @param typeSpecifierList
- * A TYPE_SPECIFIER_LIST node.
- * @param pointerList
- * A list of POINTER nodes that apply to the specified type.
- * @return The corresponding declaration.
- * @throws ParseException
- * If the type has not been defined or if there is an error
- * creating the declaration.
- */
- private IDeclaration parseTypeSpecifierList(CommonTree typeSpecifierList,
- List<CommonTree> pointerList) throws ParseException {
- IDeclaration declaration = null;
-
- /*
- * By looking at the first element of the type specifier list, we can
- * determine which type it belongs to.
- */
- CommonTree firstChild = (CommonTree) typeSpecifierList.getChild(0);
-
- switch (firstChild.getType()) {
- case CTFParser.FLOATING_POINT:
- declaration = parseFloat(firstChild);
- break;
- case CTFParser.INTEGER:
- declaration = parseInteger(firstChild);
- break;
- case CTFParser.STRING:
- declaration = parseString(firstChild);
- break;
- case CTFParser.STRUCT:
- declaration = parseStruct(firstChild);
- StructDeclaration structDeclaration = (StructDeclaration) declaration;
- IDeclaration idEnumDecl = structDeclaration.getFields().get("id"); //$NON-NLS-1$
- if (EventHeaderCompactDeclaration.isCompactEventHeader(structDeclaration)) {
- ByteOrder bo = ((EnumDeclaration) idEnumDecl).getContainerType().getByteOrder();
- declaration = new EventHeaderCompactDeclaration(bo);
- } else if (EventHeaderLargeDeclaration.isLargeEventHeader(structDeclaration)) {
- ByteOrder bo = ((EnumDeclaration) idEnumDecl).getContainerType().getByteOrder();
- declaration = new EventHeaderLargeDeclaration(bo);
- }
- break;
- case CTFParser.VARIANT:
- declaration = parseVariant(firstChild);
- break;
- case CTFParser.ENUM:
- declaration = parseEnum(firstChild);
- break;
- case CTFParser.IDENTIFIER:
- case CTFParser.FLOATTOK:
- case CTFParser.INTTOK:
- case CTFParser.LONGTOK:
- case CTFParser.SHORTTOK:
- case CTFParser.SIGNEDTOK:
- case CTFParser.UNSIGNEDTOK:
- case CTFParser.CHARTOK:
- case CTFParser.DOUBLETOK:
- case CTFParser.VOIDTOK:
- case CTFParser.BOOLTOK:
- case CTFParser.COMPLEXTOK:
- case CTFParser.IMAGINARYTOK:
- declaration = parseTypeDeclaration(typeSpecifierList, pointerList);
- break;
- default:
- childTypeError(firstChild);
- }
-
- return declaration;
- }
-
- private IDeclaration parseFloat(CommonTree floatingPoint)
- throws ParseException {
-
- List<CommonTree> children = floatingPoint.getChildren();
-
- /*
- * If the integer has no attributes, then it is missing the size
- * attribute which is required
- */
- if (children == null) {
- throw new ParseException("float: missing size attribute"); //$NON-NLS-1$
- }
-
- /* The return value */
- FloatDeclaration floatDeclaration = null;
- ByteOrder byteOrder = fTrace.getByteOrder();
- long alignment = 0;
-
- int exponent = DEFAULT_FLOAT_EXPONENT;
- int mantissa = DEFAULT_FLOAT_MANTISSA;
-
- /* Iterate on all integer children */
- for (CommonTree child : children) {
- switch (child.getType()) {
- case CTFParser.CTF_EXPRESSION_VAL:
- /*
- * An assignment expression must have 2 children, left and right
- */
-
- CommonTree leftNode = (CommonTree) child.getChild(0);
- CommonTree rightNode = (CommonTree) child.getChild(1);
-
- List<CommonTree> leftStrings = leftNode.getChildren();
-
- if (!isAnyUnaryString(leftStrings.get(0))) {
- throw new ParseException("Left side of ctf expression must be a string"); //$NON-NLS-1$
- }
- String left = concatenateUnaryStrings(leftStrings);
-
- if (left.equals(MetadataStrings.EXP_DIG)) {
- exponent = (int) parseUnaryInteger((CommonTree) rightNode.getChild(0));
- } else if (left.equals(MetadataStrings.BYTE_ORDER)) {
- byteOrder = getByteOrder(rightNode);
- } else if (left.equals(MetadataStrings.MANT_DIG)) {
- mantissa = (int) parseUnaryInteger((CommonTree) rightNode.getChild(0));
- } else if (left.equals(MetadataStrings.ALIGN)) {
- alignment = getAlignment(rightNode);
- } else {
- throw new ParseException("Float: unknown attribute " + left); //$NON-NLS-1$
- }
-
- break;
- default:
- childTypeError(child);
- break;
- }
- }
- int size = mantissa + exponent;
- if (size == 0) {
- throw new ParseException("Float missing size attribute"); //$NON-NLS-1$
- }
-
- if (alignment == 0) {
- alignment = ((size % DEFAULT_ALIGNMENT) == 0) ? 1 : DEFAULT_ALIGNMENT;
- }
-
- floatDeclaration = new FloatDeclaration(exponent, mantissa, byteOrder, alignment);
-
- return floatDeclaration;
-
- }
-
- /**
- * Parses a type specifier list as a user-declared type.
- *
- * @param typeSpecifierList
- * A TYPE_SPECIFIER_LIST node containing a user-declared type.
- * @param pointerList
- * A list of POINTER nodes that apply to the type specified in
- * typeSpecifierList.
- * @return The corresponding declaration.
- * @throws ParseException
- * If the type does not exist (has not been found).
- */
- private IDeclaration parseTypeDeclaration(CommonTree typeSpecifierList,
- List<CommonTree> pointerList) throws ParseException {
- /* Create the string representation of the type declaration */
- String typeStringRepresentation = createTypeDeclarationString(
- typeSpecifierList, pointerList);
-
- /* Use the string representation to search the type in the current scope */
- IDeclaration decl = getCurrentScope().lookupTypeRecursive(
- typeStringRepresentation);
-
- if (decl == null) {
- throw new ParseException("Type " + typeStringRepresentation //$NON-NLS-1$
- + " has not been defined."); //$NON-NLS-1$
- }
-
- return decl;
- }
-
- /**
- * Parses an integer declaration node.
- *
- * @param integer
- * An INTEGER node.
- * @return The corresponding integer declaration.
- * @throws ParseException
- */
- private IntegerDeclaration parseInteger(CommonTree integer)
- throws ParseException {
-
- List<CommonTree> children = integer.getChildren();
-
- /*
- * If the integer has no attributes, then it is missing the size
- * attribute which is required
- */
- if (children == null) {
- throw new ParseException("integer: missing size attribute"); //$NON-NLS-1$
- }
-
- /* The return value */
- IntegerDeclaration integerDeclaration = null;
- boolean signed = false;
- ByteOrder byteOrder = fTrace.getByteOrder();
- long size = 0;
- long alignment = 0;
- int base = DEFAULT_INT_BASE;
- @NonNull
- String clock = EMPTY_STRING;
-
- Encoding encoding = Encoding.NONE;
-
- /* Iterate on all integer children */
- for (CommonTree child : children) {
- switch (child.getType()) {
- case CTFParser.CTF_EXPRESSION_VAL:
- /*
- * An assignment expression must have 2 children, left and right
- */
-
- CommonTree leftNode = (CommonTree) child.getChild(0);
- CommonTree rightNode = (CommonTree) child.getChild(1);
-
- List<CommonTree> leftStrings = leftNode.getChildren();
-
- if (!isAnyUnaryString(leftStrings.get(0))) {
- throw new ParseException("Left side of ctf expression must be a string"); //$NON-NLS-1$
- }
- String left = concatenateUnaryStrings(leftStrings);
-
- if (left.equals(SIGNED)) {
- signed = getSigned(rightNode);
- } else if (left.equals(MetadataStrings.BYTE_ORDER)) {
- byteOrder = getByteOrder(rightNode);
- } else if (left.equals(SIZE)) {
- size = getSize(rightNode);
- } else if (left.equals(MetadataStrings.ALIGN)) {
- alignment = getAlignment(rightNode);
- } else if (left.equals(BASE)) {
- base = getBase(rightNode);
- } else if (left.equals(ENCODING)) {
- encoding = getEncoding(rightNode);
- } else if (left.equals(MAP)) {
- clock = getClock(rightNode);
- } else {
- Activator.log(IStatus.WARNING, Messages.IOStructGen_UnknownIntegerAttributeWarning + " " + left); //$NON-NLS-1$
- }
-
- break;
- default:
- childTypeError(child);
- break;
- }
- }
-
- if (size == 0) {
- throw new ParseException("Integer missing size attribute"); //$NON-NLS-1$
- }
-
- if (alignment == 0) {
- alignment = ((size % DEFAULT_ALIGNMENT) == 0) ? 1 : DEFAULT_ALIGNMENT;
- }
-
- integerDeclaration = IntegerDeclaration.createDeclaration((int) size, signed, base,
- byteOrder, encoding, clock, alignment);
-
- return integerDeclaration;
- }
-
- @NonNull
- private static String getClock(CommonTree rightNode) {
- String clock = rightNode.getChild(1).getChild(0).getChild(0).getText();
- return clock == null ? EMPTY_STRING : clock;
- }
-
- private static StringDeclaration parseString(CommonTree string)
- throws ParseException {
-
- List<CommonTree> children = string.getChildren();
- StringDeclaration stringDeclaration = null;
-
- if (children == null) {
- stringDeclaration = new StringDeclaration();
- } else {
- Encoding encoding = Encoding.UTF8;
- for (CommonTree child : children) {
- switch (child.getType()) {
- case CTFParser.CTF_EXPRESSION_VAL:
- /*
- * An assignment expression must have 2 children, left and
- * right
- */
-
- CommonTree leftNode = (CommonTree) child.getChild(0);
- CommonTree rightNode = (CommonTree) child.getChild(1);
-
- List<CommonTree> leftStrings = leftNode.getChildren();
-
- if (!isAnyUnaryString(leftStrings.get(0))) {
- throw new ParseException("Left side of ctf expression must be a string"); //$NON-NLS-1$
- }
- String left = concatenateUnaryStrings(leftStrings);
-
- if (left.equals(ENCODING)) {
- encoding = getEncoding(rightNode);
- } else {
- throw new ParseException("String: unknown attribute " //$NON-NLS-1$
- + left);
- }
-
- break;
- default:
- childTypeError(child);
- break;
- }
- }
-
- stringDeclaration = new StringDeclaration(encoding);
- }
-
- return stringDeclaration;
- }
-
- /**
- * Parses a struct declaration and returns the corresponding declaration.
- *
- * @param struct
- * An STRUCT node.
- * @return The corresponding struct declaration.
- * @throws ParseException
- */
- private StructDeclaration parseStruct(CommonTree struct)
- throws ParseException {
-
- List<CommonTree> children = struct.getChildren();
-
- /* The return value */
- StructDeclaration structDeclaration = null;
-
- /* Name */
- String structName = null;
- boolean hasName = false;
-
- /* Body */
- CommonTree structBody = null;
- boolean hasBody = false;
-
- /* Align */
- long structAlign = 0;
-
- /* Loop on all children and identify what we have to work with. */
- for (CommonTree child : children) {
- switch (child.getType()) {
- case CTFParser.STRUCT_NAME: {
- hasName = true;
-
- CommonTree structNameIdentifier = (CommonTree) child.getChild(0);
-
- structName = structNameIdentifier.getText();
-
- break;
- }
- case CTFParser.STRUCT_BODY: {
- hasBody = true;
-
- structBody = child;
-
- break;
- }
- case CTFParser.ALIGN: {
- CommonTree structAlignExpression = (CommonTree) child.getChild(0);
-
- structAlign = getAlignment(structAlignExpression);
-
- break;
- }
- default:
- childTypeError(child);
-
- break;
- }
- }
-
- /*
- * If a struct has just a body and no name (just like the song,
- * "A Struct With No Name" by America (sorry for that...)), it's a
- * definition of a new type, so we create the type declaration and
- * return it. We can't add it to the declaration scope since there is no
- * name, but that's what we want because it won't be possible to use it
- * again to declare another field.
- *
- * If it has just a name, we look it up in the declaration scope and
- * return the associated declaration. If it is not found in the
- * declaration scope, it means that a struct with that name has not been
- * declared, which is an error.
- *
- * If it has both, then we create the type declaration and register it
- * to the current scope.
- *
- * If it has none, then what are we doing here ?
- */
- if (hasBody) {
- /*
- * If struct has a name, check if already defined in the current
- * scope.
- */
- if (hasName && (getCurrentScope().lookupStruct(structName) != null)) {
- throw new ParseException("struct " + structName //$NON-NLS-1$
- + " already defined."); //$NON-NLS-1$
- }
- /* Create the declaration */
- structDeclaration = new StructDeclaration(structAlign);
-
- /* Parse the body */
- parseStructBody(structBody, structDeclaration);
-
- /* If struct has name, add it to the current scope. */
- if (hasName) {
- getCurrentScope().registerStruct(structName, structDeclaration);
- }
- } else /* !hasBody */{
- if (hasName) {
- /* Name and !body */
-
- /* Lookup the name in the current scope. */
- structDeclaration = getCurrentScope().lookupStructRecursive(structName);
-
- /*
- * If not found, it means that a struct with such name has not
- * been defined
- */
- if (structDeclaration == null) {
- throw new ParseException("struct " + structName //$NON-NLS-1$
- + " is not defined"); //$NON-NLS-1$
- }
- } else {
- /* !Name and !body */
-
- /* We can't do anything with that. */
- throw new ParseException("struct with no name and no body"); //$NON-NLS-1$
- }
- }
- return StructDeclarationFlattener.tryFlattenStruct(structDeclaration);
- }
-
- /**
- * Parses a struct body, adding the fields to specified structure
- * declaration.
- *
- * @param structBody
- * A STRUCT_BODY node.
- * @param structDeclaration
- * The struct declaration.
- * @throws ParseException
- */
- private void parseStructBody(CommonTree structBody,
- StructDeclaration structDeclaration) throws ParseException {
-
- List<CommonTree> structDeclarations = structBody.getChildren();
-
- /*
- * If structDeclaration is null, structBody has no children and the
- * struct body is empty.
- */
- if (structDeclarations != null) {
- pushScope();
-
- for (CommonTree declarationNode : structDeclarations) {
- switch (declarationNode.getType()) {
- case CTFParser.TYPEALIAS:
- parseTypealias(declarationNode);
- break;
- case CTFParser.TYPEDEF:
- parseTypedef(declarationNode);
- break;
- case CTFParser.SV_DECLARATION:
- parseStructDeclaration(declarationNode, structDeclaration);
- break;
- default:
- childTypeError(declarationNode);
- break;
- }
- }
- popScope();
- }
- }
-
- /**
- * Parses a declaration found in a struct.
- *
- * @param declaration
- * A SV_DECLARATION node.
- * @param struct
- * A struct declaration. (I know, little name clash here...)
- * @throws ParseException
- */
- private void parseStructDeclaration(CommonTree declaration,
- StructDeclaration struct) throws ParseException {
-
- /* Get the type specifier list node */
- CommonTree typeSpecifierListNode = (CommonTree) declaration.getFirstChildWithType(CTFParser.TYPE_SPECIFIER_LIST);
-
- /* Get the type declarator list node */
- CommonTree typeDeclaratorListNode = (CommonTree) declaration.getFirstChildWithType(CTFParser.TYPE_DECLARATOR_LIST);
-
- /* Get the type declarator list */
- List<CommonTree> typeDeclaratorList = typeDeclaratorListNode.getChildren();
-
- /*
- * For each type declarator, parse the declaration and add a field to
- * the struct
- */
- for (CommonTree typeDeclaratorNode : typeDeclaratorList) {
-
- StringBuilder identifierSB = new StringBuilder();
-
- IDeclaration decl = parseTypeDeclarator(typeDeclaratorNode,
- typeSpecifierListNode, identifierSB);
- String fieldName = identifierSB.toString();
- getCurrentScope().registerIdentifier(fieldName, decl);
-
- if (struct.hasField(fieldName)) {
- throw new ParseException("struct: duplicate field " //$NON-NLS-1$
- + fieldName);
- }
-
- struct.addField(fieldName, decl);
-
- }
- }
-
- /**
- * Parses an enum declaration and returns the corresponding declaration.
- *
- * @param theEnum
- * An ENUM node.
- * @return The corresponding enum declaration.
- * @throws ParseException
- */
- private EnumDeclaration parseEnum(CommonTree theEnum) throws ParseException {
-
- List<CommonTree> children = theEnum.getChildren();
-
- /* The return value */
- EnumDeclaration enumDeclaration = null;
-
- /* Name */
- String enumName = null;
-
- /* Body */
- CommonTree enumBody = null;
-
- /* Container type */
- IntegerDeclaration containerTypeDeclaration = null;
-
- /* Loop on all children and identify what we have to work with. */
- for (CommonTree child : children) {
- switch (child.getType()) {
- case CTFParser.ENUM_NAME: {
- CommonTree enumNameIdentifier = (CommonTree) child.getChild(0);
- enumName = enumNameIdentifier.getText();
- break;
- }
- case CTFParser.ENUM_BODY: {
- enumBody = child;
- break;
- }
- case CTFParser.ENUM_CONTAINER_TYPE: {
- containerTypeDeclaration = parseEnumContainerType(child);
- break;
- }
- default:
- childTypeError(child);
- break;
- }
- }
-
- /*
- * If the container type has not been defined explicitly, we assume it
- * is "int".
- */
- if (containerTypeDeclaration == null) {
- IDeclaration enumDecl;
- /*
- * it could be because the enum was already declared.
- */
- if (enumName != null) {
- enumDecl = getCurrentScope().lookupEnumRecursive(enumName);
- if (enumDecl != null) {
- return (EnumDeclaration) enumDecl;
- }
- }
-
- IDeclaration decl = getCurrentScope().lookupTypeRecursive("int"); //$NON-NLS-1$
-
- if (decl == null) {
- throw new ParseException("enum container type implicit and type int not defined"); //$NON-NLS-1$
- } else if (!(decl instanceof IntegerDeclaration)) {
- throw new ParseException("enum container type implicit and type int not an integer"); //$NON-NLS-1$
- }
-
- containerTypeDeclaration = (IntegerDeclaration) decl;
- }
-
- /*
- * If it has a body, it's a new declaration, otherwise it's a reference
- * to an existing declaration. Same logic as struct.
- */
- if (enumBody != null) {
- /*
- * If enum has a name, check if already defined in the current
- * scope.
- */
- if ((enumName != null)
- && (getCurrentScope().lookupEnum(enumName) != null)) {
- throw new ParseException("enum " + enumName //$NON-NLS-1$
- + " already defined"); //$NON-NLS-1$
- }
-
- /* Create the declaration */
- enumDeclaration = new EnumDeclaration(containerTypeDeclaration);
-
- /* Parse the body */
- parseEnumBody(enumBody, enumDeclaration);
-
- /* If the enum has name, add it to the current scope. */
- if (enumName != null) {
- getCurrentScope().registerEnum(enumName, enumDeclaration);
- }
- } else {
- if (enumName != null) {
- /* Name and !body */
-
- /* Lookup the name in the current scope. */
- enumDeclaration = getCurrentScope().lookupEnumRecursive(enumName);
-
- /*
- * If not found, it means that an enum with such name has not
- * been defined
- */
- if (enumDeclaration == null) {
- throw new ParseException("enum " + enumName //$NON-NLS-1$
- + " is not defined"); //$NON-NLS-1$
- }
- } else {
- /* !Name and !body */
- throw new ParseException("enum with no name and no body"); //$NON-NLS-1$
- }
- }
-
- return enumDeclaration;
-
- }
-
- /**
- * Parses an enum body, adding the enumerators to the specified enum
- * declaration.
- *
- * @param enumBody
- * An ENUM_BODY node.
- * @param enumDeclaration
- * The enum declaration.
- * @throws ParseException
- */
- private void parseEnumBody(CommonTree enumBody,
- EnumDeclaration enumDeclaration) throws ParseException {
-
- List<CommonTree> enumerators = enumBody.getChildren();
- /* enum body can't be empty (unlike struct). */
-
- pushScope();
-
- /*
- * Start at -1, so that if the first enumrator has no explicit value, it
- * will choose 0
- */
- long lastHigh = -1;
-
- for (CommonTree enumerator : enumerators) {
- lastHigh = parseEnumEnumerator(enumerator, enumDeclaration,
- lastHigh);
- }
-
- popScope();
-
- }
-
- /**
- * Parses an enumerator node and adds an enumerator declaration to an
- * enumeration declaration.
- *
- * The high value of the range of the last enumerator is needed in case the
- * current enumerator does not specify its value.
- *
- * @param enumerator
- * An ENUM_ENUMERATOR node.
- * @param enumDeclaration
- * en enumeration declaration to which will be added the
- * enumerator.
- * @param lastHigh
- * The high value of the range of the last enumerator
- * @return The high value of the value range of the current enumerator.
- * @throws ParseException
- */
- private static long parseEnumEnumerator(CommonTree enumerator,
- EnumDeclaration enumDeclaration, long lastHigh)
- throws ParseException {
-
- List<CommonTree> children = enumerator.getChildren();
-
- long low = 0, high = 0;
- boolean valueSpecified = false;
- String label = null;
-
- for (CommonTree child : children) {
- if (isAnyUnaryString(child)) {
- label = parseUnaryString(child);
- } else if (child.getType() == CTFParser.ENUM_VALUE) {
-
- valueSpecified = true;
-
- low = parseUnaryInteger((CommonTree) child.getChild(0));
- high = low;
- } else if (child.getType() == CTFParser.ENUM_VALUE_RANGE) {
-
- valueSpecified = true;
-
- low = parseUnaryInteger((CommonTree) child.getChild(0));
- high = parseUnaryInteger((CommonTree) child.getChild(1));
- } else {
- childTypeError(child);
- }
- }
-
- if (!valueSpecified) {
- low = lastHigh + 1;
- high = low;
- }
-
- if (low > high) {
- throw new ParseException("enum low value greater than high value"); //$NON-NLS-1$
- }
-
- if (!enumDeclaration.add(low, high, label)) {
- throw new ParseException("enum declarator values overlap."); //$NON-NLS-1$
- }
-
- if (valueSpecified && (BigInteger.valueOf(low).compareTo(enumDeclaration.getContainerType().getMinValue()) == -1 ||
- BigInteger.valueOf(high).compareTo(enumDeclaration.getContainerType().getMaxValue()) == 1)) {
- throw new ParseException("enum value is not in range"); //$NON-NLS-1$
- }
-
- return high;
- }
-
- /**
- * Parses an enum container type node and returns the corresponding integer
- * type.
- *
- * @param enumContainerType
- * An ENUM_CONTAINER_TYPE node.
- * @return An integer declaration corresponding to the container type.
- * @throws ParseException
- * If the type does not parse correctly or if it is not an
- * integer type.
- */
- private IntegerDeclaration parseEnumContainerType(
- CommonTree enumContainerType) throws ParseException {
-
- /* Get the child, which should be a type specifier list */
- CommonTree typeSpecifierList = (CommonTree) enumContainerType.getChild(0);
-
- /* Parse it and get the corresponding declaration */
- IDeclaration decl = parseTypeSpecifierList(typeSpecifierList, null);
-
- /* If is is an integer, return it, else throw an error */
- if (decl instanceof IntegerDeclaration) {
- return (IntegerDeclaration) decl;
- }
- throw new ParseException("enum container type must be an integer"); //$NON-NLS-1$
- }
-
- private VariantDeclaration parseVariant(CommonTree variant)
- throws ParseException {
-
- List<CommonTree> children = variant.getChildren();
- VariantDeclaration variantDeclaration = null;
-
- boolean hasName = false;
- String variantName = null;
-
- boolean hasBody = false;
- CommonTree variantBody = null;
-
- boolean hasTag = false;
- String variantTag = null;
-
- for (CommonTree child : children) {
- switch (child.getType()) {
- case CTFParser.VARIANT_NAME:
-
- hasName = true;
-
- CommonTree variantNameIdentifier = (CommonTree) child.getChild(0);
-
- variantName = variantNameIdentifier.getText();
-
- break;
- case CTFParser.VARIANT_TAG:
-
- hasTag = true;
-
- CommonTree variantTagIdentifier = (CommonTree) child.getChild(0);
-
- variantTag = variantTagIdentifier.getText();
-
- break;
- case CTFParser.VARIANT_BODY:
-
- hasBody = true;
-
- variantBody = child;
-
- break;
- default:
- childTypeError(child);
- break;
- }
- }
-
- if (hasBody) {
- /*
- * If variant has a name, check if already defined in the current
- * scope.
- */
- if (hasName
- && (getCurrentScope().lookupVariant(variantName) != null)) {
- throw new ParseException("variant " + variantName //$NON-NLS-1$
- + " already defined."); //$NON-NLS-1$
- }
-
- /* Create the declaration */
- variantDeclaration = new VariantDeclaration();
-
- /* Parse the body */
- parseVariantBody(variantBody, variantDeclaration);
-
- /* If variant has name, add it to the current scope. */
- if (hasName) {
- getCurrentScope().registerVariant(variantName,
- variantDeclaration);
- }
- } else /* !hasBody */{
- if (hasName) {
- /* Name and !body */
-
- /* Lookup the name in the current scope. */
- variantDeclaration = getCurrentScope().lookupVariantRecursive(
- variantName);
-
- /*
- * If not found, it means that a struct with such name has not
- * been defined
- */
- if (variantDeclaration == null) {
- throw new ParseException("variant " + variantName //$NON-NLS-1$
- + " is not defined"); //$NON-NLS-1$
- }
- } else {
- /* !Name and !body */
-
- /* We can't do anything with that. */
- throw new ParseException("variant with no name and no body"); //$NON-NLS-1$
- }
- }
-
- if (hasTag) {
- variantDeclaration.setTag(variantTag);
-
- IDeclaration decl = getCurrentScope().lookupIdentifierRecursive(variantTag);
- if (decl == null) {
- throw new ParseException("Variant tag not found: " + variantTag); //$NON-NLS-1$
- }
- if (!(decl instanceof EnumDeclaration)) {
- throw new ParseException("Variant tag must be an enum: " + variantTag); //$NON-NLS-1$
- }
- EnumDeclaration tagDecl = (EnumDeclaration) decl;
- Set<String> intersection = new HashSet<>(tagDecl.getLabels());
- intersection.retainAll(variantDeclaration.getFields().keySet());
- if (intersection.isEmpty()) {
- throw new ParseException("Variant contains no values of the tag, impossible to use: " + variantName); //$NON-NLS-1$
- }
- }
-
- return variantDeclaration;
- }
-
- private void parseVariantBody(CommonTree variantBody,
- VariantDeclaration variantDeclaration) throws ParseException {
-
- List<CommonTree> variantDeclarations = variantBody.getChildren();
-
- pushScope();
-
- for (CommonTree declarationNode : variantDeclarations) {
- switch (declarationNode.getType()) {
- case CTFParser.TYPEALIAS:
- parseTypealias(declarationNode);
- break;
- case CTFParser.TYPEDEF:
- parseTypedef(declarationNode);
- break;
- case CTFParser.SV_DECLARATION:
- parseVariantDeclaration(declarationNode, variantDeclaration);
- break;
- default:
- childTypeError(declarationNode);
- break;
- }
- }
-
- popScope();
- }
-
- private void parseVariantDeclaration(CommonTree declaration,
- VariantDeclaration variant) throws ParseException {
-
- /* Get the type specifier list node */
- CommonTree typeSpecifierListNode = (CommonTree) declaration.getFirstChildWithType(CTFParser.TYPE_SPECIFIER_LIST);
-
- /* Get the type declarator list node */
- CommonTree typeDeclaratorListNode = (CommonTree) declaration.getFirstChildWithType(CTFParser.TYPE_DECLARATOR_LIST);
-
- /* Get the type declarator list */
- List<CommonTree> typeDeclaratorList = typeDeclaratorListNode.getChildren();
-
- /*
- * For each type declarator, parse the declaration and add a field to
- * the variant
- */
- for (CommonTree typeDeclaratorNode : typeDeclaratorList) {
-
- StringBuilder identifierSB = new StringBuilder();
-
- IDeclaration decl = parseTypeDeclarator(typeDeclaratorNode,
- typeSpecifierListNode, identifierSB);
-
- String name = identifierSB.toString();
-
- if (variant.hasField(name)) {
- throw new ParseException("variant: duplicate field " //$NON-NLS-1$
- + name);
- }
-
- getCurrentScope().registerIdentifier(name, decl);
-
- variant.addField(name, decl);
- }
- }
-
- /**
- * Creates the string representation of a type declaration (type specifier
- * list + pointers).
- *
- * @param typeSpecifierList
- * A TYPE_SPECIFIER_LIST node.
- * @param pointers
- * A list of POINTER nodes.
- * @return The string representation.
- * @throws ParseException
- */
- private static String createTypeDeclarationString(
- CommonTree typeSpecifierList, List<CommonTree> pointers)
- throws ParseException {
- StringBuilder sb = new StringBuilder();
-
- createTypeSpecifierListString(typeSpecifierList, sb);
- createPointerListString(pointers, sb);
-
- return sb.toString();
- }
-
- /**
- * Creates the string representation of a list of type specifiers.
- *
- * @param typeSpecifierList
- * A TYPE_SPECIFIER_LIST node.
- * @param sb
- * A StringBuilder to which will be appended the string.
- * @throws ParseException
- */
- private static void createTypeSpecifierListString(
- CommonTree typeSpecifierList, StringBuilder sb)
- throws ParseException {
-
- List<CommonTree> children = typeSpecifierList.getChildren();
-
- boolean firstItem = true;
-
- for (CommonTree child : children) {
- if (!firstItem) {
- sb.append(' ');
-
- }
-
- firstItem = false;
-
- /* Append the string that represents this type specifier. */
- createTypeSpecifierString(child, sb);
- }
- }
-
- /**
- * Creates the string representation of a type specifier.
- *
- * @param typeSpecifier
- * A TYPE_SPECIFIER node.
- * @param sb
- * A StringBuilder to which will be appended the string.
- * @throws ParseException
- */
- private static void createTypeSpecifierString(CommonTree typeSpecifier,
- StringBuilder sb) throws ParseException {
- switch (typeSpecifier.getType()) {
- case CTFParser.FLOATTOK:
- case CTFParser.INTTOK:
- case CTFParser.LONGTOK:
- case CTFParser.SHORTTOK:
- case CTFParser.SIGNEDTOK:
- case CTFParser.UNSIGNEDTOK:
- case CTFParser.CHARTOK:
- case CTFParser.DOUBLETOK:
- case CTFParser.VOIDTOK:
- case CTFParser.BOOLTOK:
- case CTFParser.COMPLEXTOK:
- case CTFParser.IMAGINARYTOK:
- case CTFParser.CONSTTOK:
- case CTFParser.IDENTIFIER:
- sb.append(typeSpecifier.getText());
- break;
- case CTFParser.STRUCT: {
- CommonTree structName = (CommonTree) typeSpecifier.getFirstChildWithType(CTFParser.STRUCT_NAME);
- if (structName == null) {
- throw new ParseException("nameless struct found in createTypeSpecifierString"); //$NON-NLS-1$
- }
-
- CommonTree structNameIdentifier = (CommonTree) structName.getChild(0);
-
- sb.append(structNameIdentifier.getText());
- break;
- }
- case CTFParser.VARIANT: {
- CommonTree variantName = (CommonTree) typeSpecifier.getFirstChildWithType(CTFParser.VARIANT_NAME);
- if (variantName == null) {
- throw new ParseException("nameless variant found in createTypeSpecifierString"); //$NON-NLS-1$
- }
-
- CommonTree variantNameIdentifier = (CommonTree) variantName.getChild(0);
-
- sb.append(variantNameIdentifier.getText());
- break;
- }
- case CTFParser.ENUM: {
- CommonTree enumName = (CommonTree) typeSpecifier.getFirstChildWithType(CTFParser.ENUM_NAME);
- if (enumName == null) {
- throw new ParseException("nameless enum found in createTypeSpecifierString"); //$NON-NLS-1$
- }
-
- CommonTree enumNameIdentifier = (CommonTree) enumName.getChild(0);
-
- sb.append(enumNameIdentifier.getText());
- break;
- }
- case CTFParser.FLOATING_POINT:
- case CTFParser.INTEGER:
- case CTFParser.STRING:
- throw new ParseException("CTF type found in createTypeSpecifierString"); //$NON-NLS-1$
- default:
- childTypeError(typeSpecifier);
- break;
- }
- }
-
- /**
- * Creates the string representation of a list of pointers.
- *
- * @param pointerList
- * A list of pointer nodes. If pointerList is null, this function
- * does nothing.
- * @param sb
- * A stringbuilder to which will be appended the string.
- */
- private static void createPointerListString(List<CommonTree> pointerList,
- StringBuilder sb) {
- if (pointerList == null) {
- return;
- }
-
- for (CommonTree pointer : pointerList) {
-
- sb.append(" *"); //$NON-NLS-1$
- if (pointer.getChildCount() > 0) {
-
- sb.append(" const"); //$NON-NLS-1$
- }
- }
- }
-
- /**
- * @param node
- * The node to check.
- * @return True if the given node is an unary string.
- */
- private static boolean isUnaryString(CommonTree node) {
- return ((node.getType() == CTFParser.UNARY_EXPRESSION_STRING));
- }
-
- /**
- * @param node
- * The node to check.
- * @return True if the given node is any type of unary string (no quotes,
- * quotes, etc).
- */
- private static boolean isAnyUnaryString(CommonTree node) {
- return ((node.getType() == CTFParser.UNARY_EXPRESSION_STRING) || (node.getType() == CTFParser.UNARY_EXPRESSION_STRING_QUOTES));
- }
-
- /**
- * @param node
- * The node to check.
- * @return True if the given node is an unary integer.
- */
- private static boolean isUnaryInteger(CommonTree node) {
- return ((node.getType() == CTFParser.UNARY_EXPRESSION_DEC) ||
- (node.getType() == CTFParser.UNARY_EXPRESSION_HEX) || (node.getType() == CTFParser.UNARY_EXPRESSION_OCT));
- }
-
- /**
- * Parses a unary string node and return the string value.
- *
- * @param unaryString
- * The unary string node to parse (type UNARY_EXPRESSION_STRING
- * or UNARY_EXPRESSION_STRING_QUOTES).
- * @return The string value.
- */
- /*
- * It would be really nice to remove the quotes earlier, such as in the
- * parser.
- */
- private static String parseUnaryString(CommonTree unaryString) {
-
- CommonTree value = (CommonTree) unaryString.getChild(0);
- String strval = value.getText();
-
- /* Remove quotes */
- if (unaryString.getType() == CTFParser.UNARY_EXPRESSION_STRING_QUOTES) {
- strval = strval.substring(1, strval.length() - 1);
- }
-
- return strval;
- }
-
- /**
- * Parses an unary integer (dec, hex or oct).
- *
- * @param unaryInteger
- * An unary integer node.
- * @return The integer value.
- * @throws ParseException
- * on an invalid integer format ("bob" for example)
- */
- private static long parseUnaryInteger(CommonTree unaryInteger) throws ParseException {
-
- List<CommonTree> children = unaryInteger.getChildren();
- CommonTree value = children.get(0);
- String strval = value.getText();
-
- long intval;
- try {
- intval = Long.decode(strval);
- } catch (NumberFormatException e) {
- throw new ParseException("Invalid integer format: " + strval, e); //$NON-NLS-1$
- }
-
- /* The rest of children are sign */
- if ((children.size() % 2) == 0) {
- return -intval;
- }
- return intval;
- }
-
- private static long getMajorOrMinor(CommonTree rightNode)
- throws ParseException {
-
- CommonTree firstChild = (CommonTree) rightNode.getChild(0);
-
- if (isUnaryInteger(firstChild)) {
- if (rightNode.getChildCount() > 1) {
- throw new ParseException("Invalid value for major/minor"); //$NON-NLS-1$
- }
-
- long m = parseUnaryInteger(firstChild);
-
- if (m < 0) {
- throw new ParseException("Invalid value for major/minor"); //$NON-NLS-1$
- }
-
- return m;
- }
- throw new ParseException("Invalid value for major/minor"); //$NON-NLS-1$
- }
-
- private static UUID getUUID(CommonTree rightNode) throws ParseException {
-
- CommonTree firstChild = (CommonTree) rightNode.getChild(0);
-
- if (isAnyUnaryString(firstChild)) {
- if (rightNode.getChildCount() > 1) {
- throw new ParseException("Invalid value for UUID"); //$NON-NLS-1$
- }
-
- String uuidstr = parseUnaryString(firstChild);
-
- try {
- return UUID.fromString(uuidstr);
- } catch (IllegalArgumentException e) {
- throw new ParseException("Invalid format for UUID", e); //$NON-NLS-1$
- }
- }
- throw new ParseException("Invalid value for UUID"); //$NON-NLS-1$
- }
-
- /**
- * Gets the value of a "signed" integer attribute.
- *
- * @param rightNode
- * A CTF_RIGHT node.
- * @return The "signed" value as a boolean.
- * @throws ParseException
- */
- private static boolean getSigned(CommonTree rightNode)
- throws ParseException {
-
- boolean ret = false;
- CommonTree firstChild = (CommonTree) rightNode.getChild(0);
-
- if (isUnaryString(firstChild)) {
- String strval = concatenateUnaryStrings(rightNode.getChildren());
-
- if (strval.equals(MetadataStrings.TRUE)
- || strval.equals(MetadataStrings.TRUE2)) {
- ret = true;
- } else if (strval.equals(MetadataStrings.FALSE)
- || strval.equals(MetadataStrings.FALSE2)) {
- ret = false;
- } else {
- throw new ParseException("Invalid boolean value " //$NON-NLS-1$
- + firstChild.getChild(0).getText());
- }
- } else if (isUnaryInteger(firstChild)) {
- /* Happens if the value is something like "1234.hello" */
- if (rightNode.getChildCount() > 1) {
- throw new ParseException("Invalid boolean value"); //$NON-NLS-1$
- }
-
- long intval = parseUnaryInteger(firstChild);
-
- if (intval == 1) {
- ret = true;
- } else if (intval == 0) {
- ret = false;
- } else {
- throw new ParseException("Invalid boolean value " //$NON-NLS-1$
- + firstChild.getChild(0).getText());
- }
- } else {
- throw new ParseException();
- }
-
- return ret;
- }
-
- /**
- * Gets the value of a "byte_order" integer attribute.
- *
- * @param rightNode
- * A CTF_RIGHT node.
- * @return The "byte_order" value.
- * @throws ParseException
- */
- private ByteOrder getByteOrder(CommonTree rightNode) throws ParseException {
-
- CommonTree firstChild = (CommonTree) rightNode.getChild(0);
-
- if (isUnaryString(firstChild)) {
- String strval = concatenateUnaryStrings(rightNode.getChildren());
-
- if (strval.equals(MetadataStrings.LE)) {
- return ByteOrder.LITTLE_ENDIAN;
- } else if (strval.equals(MetadataStrings.BE)
- || strval.equals(MetadataStrings.NETWORK)) {
- return ByteOrder.BIG_ENDIAN;
- } else if (strval.equals(MetadataStrings.NATIVE)) {
- return fTrace.getByteOrder();
- } else {
- throw new ParseException("Invalid value for byte order"); //$NON-NLS-1$
- }
- }
- throw new ParseException("Invalid value for byte order"); //$NON-NLS-1$
- }
-
- /**
- * Determines if the given value is a valid alignment value.
- *
- * @param alignment
- * The value to check.
- * @return True if it is valid.
- */
- private static boolean isValidAlignment(long alignment) {
- return !((alignment <= 0) || ((alignment & (alignment - 1)) != 0));
- }
-
- /**
- * Gets the value of a "size" integer attribute.
- *
- * @param rightNode
- * A CTF_RIGHT node.
- * @return The "size" value.
- * @throws ParseException
- */
- private static long getSize(CommonTree rightNode) throws ParseException {
-
- CommonTree firstChild = (CommonTree) rightNode.getChild(0);
-
- if (isUnaryInteger(firstChild)) {
- if (rightNode.getChildCount() > 1) {
- throw new ParseException("Invalid value for size"); //$NON-NLS-1$
- }
-
- long size = parseUnaryInteger(firstChild);
-
- if (size < 1) {
- throw new ParseException("Invalid value for size"); //$NON-NLS-1$
- }
-
- return size;
- }
- throw new ParseException("Invalid value for size"); //$NON-NLS-1$
- }
-
- /**
- * Gets the value of a "align" integer or struct attribute.
- *
- * @param node
- * A CTF_RIGHT node or directly an unary integer.
- * @return The align value.
- * @throws ParseException
- */
- private static long getAlignment(CommonTree node) throws ParseException {
-
- /*
- * If a CTF_RIGHT node was passed, call getAlignment with the first
- * child
- */
- if (node.getType() == CTFParser.CTF_RIGHT) {
- if (node.getChildCount() > 1) {
- throw new ParseException("Invalid alignment value"); //$NON-NLS-1$
- }
-
- return getAlignment((CommonTree) node.getChild(0));
- } else if (isUnaryInteger(node)) {
- long alignment = parseUnaryInteger(node);
-
- if (!isValidAlignment(alignment)) {
- throw new ParseException("Invalid value for alignment : " //$NON-NLS-1$
- + alignment);
- }
-
- return alignment;
- }
- throw new ParseException("Invalid value for alignment"); //$NON-NLS-1$
- }
-
- /**
- * Gets the value of a "base" integer attribute.
- *
- * @param rightNode
- * An CTF_RIGHT node.
- * @return The "base" value.
- * @throws ParseException
- */
- private static int getBase(CommonTree rightNode) throws ParseException {
-
- CommonTree firstChild = (CommonTree) rightNode.getChild(0);
-
- if (isUnaryInteger(firstChild)) {
- if (rightNode.getChildCount() > 1) {
- throw new ParseException("invalid base value"); //$NON-NLS-1$
- }
-
- long intval = parseUnaryInteger(firstChild);
- if ((intval == INTEGER_BASE_2) || (intval == INTEGER_BASE_8) || (intval == INTEGER_BASE_10)
- || (intval == INTEGER_BASE_16)) {
- return (int) intval;
- }
- throw new ParseException("Invalid value for base"); //$NON-NLS-1$
- } else if (isUnaryString(firstChild)) {
- String strval = concatenateUnaryStrings(rightNode.getChildren());
-
- if (strval.equals(MetadataStrings.DECIMAL)
- || strval.equals(MetadataStrings.DEC)
- || strval.equals(MetadataStrings.DEC_CTE)
- || strval.equals(MetadataStrings.INT_MOD)
- || strval.equals(MetadataStrings.UNSIGNED_CTE)) {
- return INTEGER_BASE_10;
- } else if (strval.equals(MetadataStrings.HEXADECIMAL)
- || strval.equals(MetadataStrings.HEX)
- || strval.equals(MetadataStrings.X)
- || strval.equals(MetadataStrings.X2)
- || strval.equals(MetadataStrings.POINTER)) {
- return INTEGER_BASE_16;
- } else if (strval.equals(MetadataStrings.OCTAL)
- || strval.equals(MetadataStrings.OCT)
- || strval.equals(MetadataStrings.OCTAL_CTE)) {
- return INTEGER_BASE_8;
- } else if (strval.equals(MetadataStrings.BINARY)
- || strval.equals(MetadataStrings.BIN)) {
- return INTEGER_BASE_2;
- } else {
- throw new ParseException("Invalid value for base"); //$NON-NLS-1$
- }
- } else {
- throw new ParseException("invalid value for base"); //$NON-NLS-1$
- }
- }
-
- /**
- * Gets the value of an "encoding" integer attribute.
- *
- * @param rightNode
- * A CTF_RIGHT node.
- * @return The "encoding" value.
- * @throws ParseException
- */
- @NonNull
- private static Encoding getEncoding(CommonTree rightNode)
- throws ParseException {
-
- CommonTree firstChild = (CommonTree) rightNode.getChild(0);
-
- if (isUnaryString(firstChild)) {
- String strval = concatenateUnaryStrings(rightNode.getChildren());
-
- if (strval.equals(MetadataStrings.UTF8)) {
- return Encoding.UTF8;
- } else if (strval.equals(MetadataStrings.ASCII)) {
- return Encoding.ASCII;
- } else if (strval.equals(MetadataStrings.NONE)) {
- return Encoding.NONE;
- } else {
- throw new ParseException("Invalid value for encoding"); //$NON-NLS-1$
- }
- }
- throw new ParseException("Invalid value for encoding"); //$NON-NLS-1$
- }
-
- private static long getStreamID(CommonTree rightNode) throws ParseException {
-
- CommonTree firstChild = (CommonTree) rightNode.getChild(0);
-
- if (isUnaryInteger(firstChild)) {
- if (rightNode.getChildCount() > 1) {
- throw new ParseException("invalid value for stream id"); //$NON-NLS-1$
- }
-
- long intval = parseUnaryInteger(firstChild);
-
- return intval;
- }
- throw new ParseException("invalid value for stream id"); //$NON-NLS-1$
- }
-
- private static String getEventName(CommonTree rightNode)
- throws ParseException {
-
- CommonTree firstChild = (CommonTree) rightNode.getChild(0);
-
- if (isAnyUnaryString(firstChild)) {
- String str = concatenateUnaryStrings(rightNode.getChildren());
-
- return str;
- }
- throw new ParseException("invalid value for event name"); //$NON-NLS-1$
- }
-
- private static long getEventID(CommonTree rightNode) throws ParseException {
-
- CommonTree firstChild = (CommonTree) rightNode.getChild(0);
-
- if (isUnaryInteger(firstChild)) {
- if (rightNode.getChildCount() > 1) {
- throw new ParseException("invalid value for event id"); //$NON-NLS-1$
- }
-
- long intval = parseUnaryInteger(firstChild);
- if (intval > Integer.MAX_VALUE) {
- throw new ParseException("Event id larger than int.maxvalue, something is amiss"); //$NON-NLS-1$
- }
- return intval;
- }
- throw new ParseException("invalid value for event id"); //$NON-NLS-1$
- }
-
- /**
- * Concatenates a list of unary strings separated by arrows (->) or dots.
- *
- * @param strings
- * A list, first element being an unary string, subsequent
- * elements being ARROW or DOT nodes with unary strings as child.
- * @return The string representation of the unary string chain.
- */
- private static String concatenateUnaryStrings(List<CommonTree> strings) {
-
- StringBuilder sb = new StringBuilder();
-
- CommonTree first = strings.get(0);
- sb.append(parseUnaryString(first));
-
- boolean isFirst = true;
-
- for (CommonTree ref : strings) {
- if (isFirst) {
- isFirst = false;
- continue;
- }
-
- CommonTree id = (CommonTree) ref.getChild(0);
-
- if (ref.getType() == CTFParser.ARROW) {
- sb.append("->"); //$NON-NLS-1$
- } else { /* DOT */
- sb.append('.');
- }
-
- sb.append(parseUnaryString(id));
- }
-
- return sb.toString();
- }
-
- /**
- * Throws a ParseException stating that the parent-child relation between
- * the given node and its parent is not valid. It means that the shape of
- * the AST is unexpected.
- *
- * @param child
- * The invalid child node.
- * @throws ParseException
- */
- private static void childTypeError(CommonTree child) throws ParseException {
- CommonTree parent = (CommonTree) child.getParent();
- String error = "Parent " + CTFParser.tokenNames[parent.getType()] //$NON-NLS-1$
- + " can't have a child of type " //$NON-NLS-1$
- + CTFParser.tokenNames[child.getType()] + "."; //$NON-NLS-1$
-
- throw new ParseException(error);
- }
-
- // ------------------------------------------------------------------------
- // Scope management
- // ------------------------------------------------------------------------
-
- /**
- * Adds a new declaration scope on the top of the scope stack.
- */
- private void pushScope() {
- fScope = new DeclarationScope(fScope);
- }
-
- /**
- * Removes the top declaration scope from the scope stack.
- */
- private void popScope() {
- fScope = fScope.getParentScope();
- }
-
- /**
- * Returns the current declaration scope.
- *
- * @return The current declaration scope.
- */
- private DeclarationScope getCurrentScope() {
- return fScope;
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Marc-Andre Laperle - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.internal.ctf.core.event.metadata;
-
-import org.eclipse.osgi.util.NLS;
-
-@SuppressWarnings("javadoc")
-public class Messages extends NLS {
-
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.ctf.core.event.metadata.messages"; //$NON-NLS-1$
-
- public static String IOStructGen_UnknownTraceAttributeWarning;
- public static String IOStructGen_UnknownStreamAttributeWarning;
- public static String IOStructGen_UnknownIntegerAttributeWarning;
-
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
-
- private Messages() {
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.internal.ctf.core.event.metadata;
-
-/**
- * Strings generated from the TSDL grammar. Note that they are static final so
- * they get quarked. See CTF specs for more details
- *
- * @author Matthew Khouzam and All
- */
-@SuppressWarnings("nls")
-public interface MetadataStrings {
-
- /** None */
-
- static final String NONE = "none";
- /** Ascii */
- static final String ASCII = "ASCII";
- /** UTF8 */
- static final String UTF8 = "UTF8";
- /** b (for binary like b11010010 */
- static final String BIN = "b";
- /** Binary */
- static final String BINARY = "binary";
- /** Octal like o177 */
- static final String OCTAL_CTE = "o";
- /** Octal like oct177 */
- static final String OCT = "oct";
- /** Octal like octal177 */
- static final String OCTAL = "octal";
- /** Pointer (memory address for all the hardcore Java gurus out there)*/
- static final String POINTER = "p";
- /** X for hex */
- static final String X2 = "X";
- /** x for hex */
- static final String X = "x";
- /** hex */
- static final String HEX = "hex";
- /** Hexadecimal */
- static final String HEXADECIMAL = "hexadecimal";
- /** unsigned like in 10000ul */
- static final String UNSIGNED_CTE = "u";
- /** Decimal */
- static final String DEC_CTE = "d";
- /** Integer like 1000i */
- static final String INT_MOD = "i";
- /** Decimal */
- static final String DEC = "dec";
- /** Decimal */
- static final String DECIMAL = "decimal";
- /** native for byteorders*/
- static final String NATIVE = "native";
- /** network for byteorders*/
- static final String NETWORK = "network";
- /** Big endian */
- static final String BE = "be";
- /** Little endian */
- static final String LE = "le";
- /** Alignment of a field */
- static final String ALIGN = "align";
- /** Mantissa digits */
- static final String MANT_DIG = "mant_dig";
- /** Exponent digits */
- static final String EXP_DIG = "exp_dig";
- /** Loglevel */
- static final String LOGLEVEL2 = "loglevel";
- /** Name */
- static final String NAME2 = "name";
- /** Event context */
- static final String EVENT_CONTEXT = "event.context";
- /** Fields */
- static final String FIELDS_STRING = "fields";
- /** context */
- static final String CONTEXT = "context";
- /** Stream ID */
- static final String STREAM_ID = "stream_id";
- /** Packet context */
- static final String PACKET_CONTEXT = "packet.context";
- /** ID */
- static final String ID = "id";
- /** Packet Header */
- static final String PACKET_HEADER = "packet.header";
- /** Event Header */
- static final String EVENT_HEADER = "event.header";
- /** Byte order */
- static final String BYTE_ORDER = "byte_order";
- /** UUID */
- static final String UUID_STRING = "uuid";
- /** False */
- static final String FALSE2 = "FALSE";
- /** False */
- static final String FALSE = "false";
- /** True */
- static final String TRUE2 = "TRUE";
- /** True */
- static final String TRUE = "true";
- /** Minor (Version)*/
- static final String MINOR = "minor";
- /** Major (Version)*/
- static final String MAJOR = "major";
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013, 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Alexandre Montplaisir - Initial API and implementation
- * Matthew Khouzam - Addition to have more descriptive errors
- *******************************************************************************/
-
-package org.eclipse.linuxtools.internal.ctf.core.event.metadata.exceptions;
-
-import java.lang.reflect.Field;
-
-import org.antlr.runtime.MismatchedTokenException;
-import org.antlr.runtime.RecognitionException;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.ctf.parser.CTFLexer;
-
-/**
- * CTF Reader exception but dealing with Antlr-specific parsing problems.
- *
- * It is separated from the main {@link CTFReaderException} - and is not part of
- * the API - to isolate the Antlr-specific classes and avoid pushing that
- * dependency to the users of this plugin.
- *
- * @author Matthew Khouzam
- */
-public class CtfAntlrException extends CTFReaderException {
-
- private static final long serialVersionUID = -7078624493350073777L;
-
- private int fErrorLine = -1;
- private String fFile = ""; //$NON-NLS-1$
- private String fExpectingName = ""; //$NON-NLS-1$
- private int fExpectedValue = -1;
- private String fActualName = ""; //$NON-NLS-1$
- private int fActualValue = -1;
-
- /**
- * Re-throw the exception but read its data
- *
- * @param e
- * the previous recognition exception (Antlr specific)
- */
- public CtfAntlrException(RecognitionException e) {
- super(e);
- this.fErrorLine = e.line;
- this.fFile = "metadata"; //$NON-NLS-1$ // we're in CTF, the only thing using antlr is metadata
- }
-
- /**
- * Re-throw the exception but read its data
- *
- * @param e
- * the previous recognition exception (Antlr specific)
- */
- public CtfAntlrException(MismatchedTokenException e) {
- super(e);
- this.fErrorLine = e.line;
- this.fFile = "metadata"; //$NON-NLS-1$ // we're in CTF, the only thing using antlr is metadata
- parseMismatchedException(e);
- }
-
- /**
- * Re-throw the exception but read its data
- *
- * @param e
- * the previous rewrite exception (Antlr specific)
- */
- public CtfAntlrException(Exception e) {
- super(e);
- this.fErrorLine = -1;
- this.fFile = "metadata"; //$NON-NLS-1$ // we're in CTF, the only thing using antlr is metadata
- }
-
- private void parseMismatchedException(MismatchedTokenException m) {
- // Iterate through the tokens that are hidden in the CTFLexer
- // They are private static final int fields.
- for (Field f : CTFLexer.class.getDeclaredFields()) {
- f.setAccessible(true);
- String name;
- int value;
- try {
- name = f.getName();
- final boolean isInt = (f.getType().isPrimitive());
- if (isInt) {
- value = ((Integer) f.get(null)).intValue();
- if (value == m.expecting) {
- this.fExpectingName = name;
- this.fExpectedValue = value;
- }
- if (value == m.c) {
- this.fActualName = name;
- this.fActualValue = value;
- }
- }
- } catch (NullPointerException e1) {
- // Pokemon, gotta catch em all!
- // actually useful since f may not have a
- // value
- } catch (IllegalArgumentException e1) {
- // Catch these exceptions (reflexion)
- } catch (IllegalAccessException e1) {
- // Catch these exceptions (reflexion)
- }
- if (!this.fExpectingName.isEmpty() && !this.fActualName.isEmpty()) {
- return;
- }
- }
- }
-
- @Override
- public String getMessage() {
- final String message = super.getMessage();
- if (fErrorLine == -1) {
- return message;
- }
- String expected = "" + this.fExpectedValue; //$NON-NLS-1$
- String actual = "" + this.fActualValue; //$NON-NLS-1$
- String newMessage = message.replaceAll(expected, this.fExpectingName);
- newMessage = newMessage.replaceAll(actual, this.fActualName);
- return newMessage + " at " + fFile + ":" + fErrorLine; //$NON-NLS-1$ //$NON-NLS-2$
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.internal.ctf.core.event.metadata.exceptions;
-
-
-/**
- * <b><u>ParseException</u></b>
- */
-public class ParseException extends Exception {
-
- private static final long serialVersionUID = 7901917601459652080L;
-
- /**
- * Empty constructor
- */
- public ParseException() {
- super();
- }
-
- /**
- * Constructor
- *
- * @param message to be sent to logs
- */
- public ParseException(String message) {
- super(message);
- }
-
- /**
- * Copy constructor
- * @param e the exception to throw
- */
- public ParseException(Exception e) {
- super(e);
- }
-
- /**
- * Constructs a new exception with the specified detail message and
- * cause. <p>Note that the detail message associated with
- * {@code cause} is <i>not</i> automatically incorporated in
- * this exception's detail message.
- *
- * @param message the detail message (which is saved for later retrieval
- * by the {@link #getMessage()} method).
- * @param cause the cause (which is saved for later retrieval by the
- * {@link #getCause()} method). (A <tt>null</tt> value is
- * permitted, and indicates that the cause is nonexistent or
- * unknown.)
- */
- public ParseException(String message, Exception cause) {
- super(message, cause);
- }
-}
+++ /dev/null
-###############################################################################
-# Copyright (c) 2013 Ericsson
-#
-# All rights reserved. This program and the accompanying materials
-# are made available under the terms of the Eclipse Public License v1.0
-# which accompanies this distribution, and is available at
-# http://www.eclipse.org/legal/epl-v10.html
-#
-# Contributors:
-# Marc-Andre Laperle - Initial API and implementation
-# Alexandre Montplaisir - Added strings from DeclarationScope
-###############################################################################
-
-#IOStructGen
-IOStructGen_UnknownTraceAttributeWarning=Unknown trace attribute:
-IOStructGen_UnknownStreamAttributeWarning=Unknown stream attribute:
-IOStructGen_UnknownIntegerAttributeWarning=Unknown integer attribute:
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.internal.ctf.core.event.types;
-
-import java.util.List;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.event.types.AbstractArrayDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.CompoundDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.Definition;
-import org.eclipse.linuxtools.ctf.core.event.types.IDeclaration;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-
-import com.google.common.collect.ArrayListMultimap;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableList.Builder;
-
-/**
- * A CTF array declaration
- *
- * Arrays are fixed-length. Their length is declared in the type declaration
- * within the meta-data. They contain an array of "inner type" elements, which
- * can refer to any type not containing the type of the array being declared (no
- * circular dependency). The length is the number of elements in an array.
- *
- * @author Matthew Khouzam
- * @since 3.1
- */
-public final class ArrayDeclaration extends CompoundDeclaration {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- private final int fLength;
- private final IDeclaration fElemType;
-
- /**
- * <pre>
- * Cache where we can pre-generate the children names
- * Key: parent name
- * Value: children names
- * ex: field → {field[0], field[1], … field[n]}
- * </pre>
- *
- * TODO: investigate performance
- */
- private final ArrayListMultimap<String, String> fChildrenNames = ArrayListMultimap.create();
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Constructor
- *
- * @param length
- * how many elements in the array
- * @param elemType
- * what type of element is in the array
- */
- public ArrayDeclaration(int length, IDeclaration elemType) {
- fLength = length;
- fElemType = elemType;
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- @Override
- public IDeclaration getElementType() {
- return fElemType;
- }
-
- /**
- * Get the length of the array
- *
- * @return the length of the array
- */
- public int getLength() {
- return fLength;
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- @Override
- public AbstractArrayDefinition createDefinition(IDefinitionScope definitionScope,
- @NonNull String fieldName, BitBuffer input) throws CTFReaderException {
- alignRead(input);
- if (isString()) {
- byte[] data = new byte[fLength];
- input.get(data);
- return new ByteArrayDefinition(this, definitionScope, fieldName, data);
- }
- List<Definition> definitions = read(input, definitionScope, fieldName);
- return new ArrayDefinition(this, definitionScope, fieldName, definitions);
- }
-
- @Override
- public String toString() {
- /* Only used for debugging */
- return "[declaration] array[" + Integer.toHexString(hashCode()) + ']'; //$NON-NLS-1$
- }
-
- @NonNull
- private List<Definition> read(@NonNull BitBuffer input, IDefinitionScope definitionScope, String fieldName) throws CTFReaderException {
- Builder<Definition> definitions = new ImmutableList.Builder<>();
- if (!fChildrenNames.containsKey(fieldName)) {
- for (int i = 0; i < fLength; i++) {
- fChildrenNames.put(fieldName, fieldName + '[' + i + ']');
- }
- }
- List<String> elemNames = fChildrenNames.get(fieldName);
- for (int i = 0; i < fLength; i++) {
- String name = elemNames.get(i);
- if (name == null) {
- throw new IllegalStateException();
- }
- definitions.add(fElemType.createDefinition(definitionScope, name, input));
- }
- @SuppressWarnings("null")
- @NonNull ImmutableList<Definition> ret = definitions.build();
- return ret;
- }
-
- @Override
- public int getMaximumSize() {
- long val = (long) fLength * fElemType.getMaximumSize();
- return (int) Math.min(Integer.MAX_VALUE, val);
- }
-
-}
\ No newline at end of file
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.internal.ctf.core.event.types;
-
-import java.util.List;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.jdt.annotation.NonNullByDefault;
-import org.eclipse.jdt.annotation.Nullable;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.event.types.AbstractArrayDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.CompoundDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.Definition;
-
-import com.google.common.base.Joiner;
-import com.google.common.collect.ImmutableList;
-
-/**
- * A CTF array definition
- *
- * Arrays are fixed-length. Their length is declared in the type declaration
- * within the meta-data. They contain an array of "inner type" elements, which
- * can refer to any type not containing the type of the array being declared (no
- * circular dependency). The length is the number of elements in an array.
- *
- * @version 1.0
- * @author Matthew Khouzam
- * @since 3.1
- */
-@NonNullByDefault
-public final class ArrayDefinition extends AbstractArrayDefinition {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- private final ImmutableList<Definition> fDefinitions;
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Constructor
- *
- * @param declaration
- * the parent declaration
- * @param definitionScope
- * the parent scope
- * @param fieldName
- * the field name
- * @param definitions
- * the content of the array
- */
- public ArrayDefinition(CompoundDeclaration declaration,
- @Nullable IDefinitionScope definitionScope,
- String fieldName,
- List<Definition> definitions) {
- super(declaration, definitionScope, fieldName);
- @SuppressWarnings("null")
- @NonNull ImmutableList<Definition> list = ImmutableList.copyOf(definitions);
- fDefinitions = list;
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- @Override
- public List<Definition> getDefinitions() {
- return fDefinitions;
- }
-
- /**
- * Get the the number of elements in the array
- *
- * @return how many elements in the array
- */
- public int getLength() {
- return fDefinitions.size();
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- @Override
- public String toString() {
- StringBuilder b = new StringBuilder();
- b.append('[');
- Joiner joiner = Joiner.on(", ").skipNulls(); //$NON-NLS-1$
- b.append(joiner.join(fDefinitions));
- b.append(']');
- @SuppressWarnings("null")
- @NonNull String ret = b.toString();
- return ret;
- }
-}
\ No newline at end of file
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.internal.ctf.core.event.types;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.jdt.annotation.NonNullByDefault;
-import org.eclipse.jdt.annotation.Nullable;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.event.types.AbstractArrayDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.CompoundDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.Definition;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDefinition;
-
-import com.google.common.collect.ImmutableList;
-
-/**
- * A fixed length string definition
- *
- * @author Matthew Khouzam
- * @since 3.1
- */
-@NonNullByDefault
-public final class ByteArrayDefinition extends AbstractArrayDefinition {
-
- private final byte[] fContent;
- private transient @Nullable List<Definition> fDefs;
-
- /**
- * An fixed length string declaration, it's created by sequence or array
- * defintions
- *
- * @param declaration
- * the declaration
- * @param definitionScope
- * the definition scope
- * @param fieldName
- * the field name
- * @param content
- * the string content
- */
- public ByteArrayDefinition(CompoundDeclaration declaration,
- @Nullable IDefinitionScope definitionScope,
- String fieldName,
- byte[] content) {
- super(declaration, definitionScope, fieldName);
- fContent = content;
-
- }
-
- @Override
- public synchronized List<Definition> getDefinitions() {
- List<Definition> defs = fDefs;
- if (defs == null) {
- ImmutableList.Builder<Definition> builder = new ImmutableList.Builder<>();
- for (int i = 0; i < fContent.length; i++) {
- IntegerDeclaration charDecl = IntegerDeclaration.UINT_8_DECL;
- String fieldName = getFieldName() + '[' + i + ']';
- byte fieldValue = fContent[i];
- builder.add(new IntegerDefinition(charDecl, getDefinitionScope(), fieldName, fieldValue));
- }
- @SuppressWarnings("null")
- @NonNull List<Definition> ret = builder.build();
- fDefs = ret;
- return ret;
- }
-
- return defs;
- }
-
- @Override
- public String toString() {
- /*
- * the string is a byte array and may contain more than the string plus
- * a null char, this will truncate it back to a null char
- */
- int pos = -1;
- for (int i = 0; i < fContent.length; i++) {
- if (fContent[i] == 0) {
- pos = i;
- break;
- }
- }
- byte[] bytes = (pos != -1) ? (Arrays.copyOf(fContent, pos)) : fContent;
- return new String(bytes);
- }
-}
\ No newline at end of file
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.internal.ctf.core.event.types;
-
-import java.util.Collection;
-import java.util.List;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.event.types.AbstractArrayDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.CompoundDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.Definition;
-import org.eclipse.linuxtools.ctf.core.event.types.IDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDefinition;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-
-import com.google.common.collect.ArrayListMultimap;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableList.Builder;
-import com.google.common.collect.Multimap;
-
-/**
- * A CTF sequence declaration.
- *
- * An array where the size is fixed but declared in the trace, unlike array
- * where it is declared with a literal
- *
- * @author Matthew Khouzam
- * @since 3.1
- */
-public class SequenceDeclaration extends CompoundDeclaration {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- private final IDeclaration fElemType;
- private final String fLengthName;
- private final Multimap<String, String> fPaths = ArrayListMultimap.create();
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Constructor
- *
- * @param lengthName
- * the name of the field describing the length
- * @param elemType
- * The element type
- */
- public SequenceDeclaration(String lengthName, IDeclaration elemType) {
- fElemType = elemType;
- fLengthName = lengthName;
- }
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- @Override
- public IDeclaration getElementType() {
- return fElemType;
- }
-
- /**
- * Gets the name of the length field
- *
- * @return the name of the length field
- */
- public String getLengthName() {
- return fLengthName;
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- @Override
- public AbstractArrayDefinition createDefinition(
- IDefinitionScope definitionScope, String fieldName, BitBuffer input) throws CTFReaderException {
- IDefinition lenDef = null;
-
- if (definitionScope != null) {
- lenDef = definitionScope.lookupDefinition(getLengthName());
- }
-
- if (lenDef == null) {
- throw new CTFReaderException("Sequence length field not found"); //$NON-NLS-1$
- }
-
- if (!(lenDef instanceof IntegerDefinition)) {
- throw new CTFReaderException("Sequence length field not integer"); //$NON-NLS-1$
- }
-
- IntegerDefinition lengthDefinition = (IntegerDefinition) lenDef;
-
- if (lengthDefinition.getDeclaration().isSigned()) {
- throw new CTFReaderException("Sequence length must not be signed"); //$NON-NLS-1$
- }
-
- long length = lengthDefinition.getValue();
- if ((length > Integer.MAX_VALUE) || (!input.canRead((int) length * fElemType.getMaximumSize()))) {
- throw new CTFReaderException("Sequence length too long " + length); //$NON-NLS-1$
- }
-
- if (isString()) {
- // Don't create "useless" definitions
- byte[] data = new byte[(int) length];
- input.get(data);
- return new ByteArrayDefinition(this, definitionScope, fieldName, data);
- }
- Collection<String> collection = fPaths.get(fieldName);
- while (collection.size() < length) {
- fPaths.put(fieldName, fieldName + '[' + collection.size() + ']');
- }
- List<String> paths = (List<String>) fPaths.get(fieldName);
- Builder<Definition> definitions = new ImmutableList.Builder<>();
- for (int i = 0; i < length; i++) {
- @SuppressWarnings("null")
- @NonNull String elemName = paths.get(i);
- definitions.add(fElemType.createDefinition(definitionScope, elemName, input));
- }
- @SuppressWarnings("null")
- @NonNull ImmutableList<Definition> build = definitions.build();
- return new ArrayDefinition(this, definitionScope, fieldName, build);
- }
-
- @Override
- public String toString() {
- /* Only used for debugging */
- return "[declaration] sequence[" + Integer.toHexString(hashCode()) + ']'; //$NON-NLS-1$
- }
-
- @Override
- public int getMaximumSize() {
- return Integer.MAX_VALUE;
- }
-
-}
\ No newline at end of file
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.internal.ctf.core.event.types;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.types.IDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.ISimpleDatatypeDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-
-/**
- * A fixed size struct declaration is a declaration of a structure that has no
- * variant or sequence fields. This will accelerate reading of the trace.
- *
- * @author Matthew Khouzam
- * @since 3.0
- */
-public final class StructDeclarationFlattener {
-
- private StructDeclarationFlattener() {}
-
- /**
- * Flatten a {@link StructDeclaration}, if it can be (which means if it
- * contains only fixed-size elements).
- *
- * This does not modify the declaration passed in parameter, you need to use
- * the return value.
- *
- * @param sd
- * The initial StructDeclaration
- * @return The flattened struct. Or if it couldn't be flattened, the 'sd'
- * struct itself
- */
- public static StructDeclaration tryFlattenStruct(@NonNull StructDeclaration sd) {
- if (canBeFlattened(sd)) {
- return newFlattenedStruct(sd);
- }
- return sd;
- }
-
- /**
- * Check if this struct is fixed size
- *
- * @param sd
- * the struct
- * @return if the struct is of fixed size
- */
- private static boolean canBeFlattened(@NonNull StructDeclaration sd) {
- for (String field : sd.getFieldsList()) {
- IDeclaration dec = sd.getField(field);
- if (!isFixedSize(dec)) {
- return false;
- }
- }
- return true;
- }
-
- private static boolean isFixedSize(IDeclaration dec) {
- if (dec instanceof ISimpleDatatypeDeclaration) {
- return true;
- }
- if (dec instanceof ArrayDeclaration) {
- return isFixedSize(((ArrayDeclaration) dec).getElementType());
- }
- if (dec instanceof StructDeclaration) {
- StructDeclaration sDec = ((StructDeclaration) dec);
- return canBeFlattened(sDec);
- }
- return false;
- }
-
- private static StructDeclaration newFlattenedStruct(@NonNull StructDeclaration sd) {
- StructDeclaration flatStruct = new StructDeclaration(sd.getAlignment());
- for (String name : sd.getFieldsList()) {
- depthFirstAdd(name, flatStruct, sd.getField(name));
- }
- return flatStruct;
- }
-
- private static void depthFirstAdd(String path, StructDeclaration flatStruct, IDeclaration dec) {
- if (dec instanceof ISimpleDatatypeDeclaration) {
- flatStruct.addField(path, dec);
- } else if (dec instanceof ArrayDeclaration) {
- ArrayDeclaration ad = (ArrayDeclaration) dec;
- int lastIndexOf = path.lastIndexOf('.');
-
- String name = (lastIndexOf > 0) ? path.substring(lastIndexOf) : path;
- if (((ArrayDeclaration) dec).isString()) {
- flatStruct.addField(path, dec);
- } else {
- for (int i = 0; i < ad.getLength(); i++) {
- depthFirstAdd(path + '.' + name + '[' + i + ']', flatStruct, ad.getElementType());
- }
- }
- } else if (dec instanceof StructDeclaration) {
- StructDeclaration sDec = ((StructDeclaration) dec);
- for (String name : sDec.getFieldsList()) {
- depthFirstAdd(path + '.' + name, flatStruct, sDec.getField(name));
- }
- }
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.internal.ctf.core.event.types.composite;
-
-import java.nio.ByteOrder;
-
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.event.types.Declaration;
-import org.eclipse.linuxtools.ctf.core.event.types.EnumDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IEventHeaderDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.VariantDeclaration;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-
-/**
- * An event header declaration is a declaration of a structure defined in the
- * CTF spec examples section 6.1.1 . It is used in LTTng traces. This will
- * accelerate reading of the trace.
- *
- * Reminder
- *
- * <pre>
- * struct event_header_compact {
- * enum : uint5_t { compact = 0 ... 30, extended = 31 } id;
- * variant <id> {
- * struct {
- * uint27_clock_monotonic_t timestamp;
- * } compact;
- * struct {
- * uint32_t id;
- * uint64_clock_monotonic_t timestamp;
- * } extended;
- * } v;
- * } align(8);
- * </pre>
- *
- * @author Matthew Khouzam
- */
-public class EventHeaderCompactDeclaration extends Declaration implements IEventHeaderDeclaration {
-
- private static final int COMPACT_SIZE = 1;
- private static final int VARIANT_SIZE = 2;
- private static final int EXTENDED_FIELD_SIZE = 2;
- /**
- * The id is 5 bits
- */
- private static final int COMPACT_ID = 5;
- private static final int EXTENDED_VALUE = 31;
- /**
- * Full sized id is 32 bits
- */
- private static final int ID_SIZE = 32;
- /**
- * Full sized timestamp is 64 bits
- */
- private static final int FULL_TS = 64;
- /**
- * Compact timestamp is 27 bits,
- */
- private static final int COMPACT_TS = 27;
- /**
- * Maximum size = largest this header can be
- */
- private static final int MAX_SIZE = 104;
- /**
- * Byte aligned
- */
- private static final int ALIGN = 8;
- /**
- * Name of the variant according to the spec
- */
- private static final String V = "v"; //$NON-NLS-1$
-
- private final ByteOrder fByteOrder;
-
- /**
- * Event Header Declaration
- *
- * @param byteOrder
- * the byteorder
- */
- public EventHeaderCompactDeclaration(ByteOrder byteOrder) {
- fByteOrder = byteOrder;
- }
-
- @Override
- public EventHeaderDefinition createDefinition(IDefinitionScope definitionScope, String fieldName, BitBuffer input) throws CTFReaderException {
- alignRead(input);
- ByteOrder bo = input.getByteOrder();
- input.setByteOrder(fByteOrder);
- int enumId = (int) input.get(COMPACT_ID, false);
- if (enumId != EXTENDED_VALUE) {
- long timestamp2 = input.get(COMPACT_TS, false);
- input.setByteOrder(bo);
- return new EventHeaderDefinition(this, enumId, timestamp2, COMPACT_TS);
- }
- // needed since we read 5 bits
- input.position(input.position() + 3);
- long id = input.get(ID_SIZE, false);
- if (id > Integer.MAX_VALUE) {
- throw new CTFReaderException("ID " + id + " larger than " + Integer.MAX_VALUE + " is currently unsupported by the parser"); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
- }
- long timestampLong = input.get(FULL_TS, false);
- input.setByteOrder(bo);
- return new EventHeaderDefinition(this, (int) id, timestampLong, FULL_TS);
-
- }
-
- @Override
- public long getAlignment() {
- return ALIGN;
- }
-
- @Override
- public int getMaximumSize() {
- return MAX_SIZE;
- }
-
- /**
- * Check if a given struct declaration is an event header
- *
- * @param declaration
- * the declaration
- * @return true if the struct is a compact event header
- */
- public static boolean isCompactEventHeader(StructDeclaration declaration) {
-
- IDeclaration iDeclaration = declaration.getFields().get(ID);
- if (!(iDeclaration instanceof EnumDeclaration)) {
- return false;
- }
- EnumDeclaration eId = (EnumDeclaration) iDeclaration;
- if (eId.getContainerType().getLength() != COMPACT_ID) {
- return false;
- }
- iDeclaration = declaration.getFields().get(V);
-
- if (!(iDeclaration instanceof VariantDeclaration)) {
- return false;
- }
- VariantDeclaration vDec = (VariantDeclaration) iDeclaration;
- if (!vDec.hasField(COMPACT) || !vDec.hasField(EXTENDED)) {
- return false;
- }
- if (vDec.getFields().size() != VARIANT_SIZE) {
- return false;
- }
- iDeclaration = vDec.getFields().get(COMPACT);
- if (!(iDeclaration instanceof StructDeclaration)) {
- return false;
- }
- StructDeclaration compactDec = (StructDeclaration) iDeclaration;
- if (compactDec.getFields().size() != COMPACT_SIZE) {
- return false;
- }
- if (!compactDec.hasField(TIMESTAMP)) {
- return false;
- }
- iDeclaration = compactDec.getFields().get(TIMESTAMP);
- if (!(iDeclaration instanceof IntegerDeclaration)) {
- return false;
- }
- IntegerDeclaration tsDec = (IntegerDeclaration) iDeclaration;
- if (tsDec.getLength() != COMPACT_TS || tsDec.isSigned()) {
- return false;
- }
- iDeclaration = vDec.getFields().get(EXTENDED);
- if (!(iDeclaration instanceof StructDeclaration)) {
- return false;
- }
- StructDeclaration extendedDec = (StructDeclaration) iDeclaration;
- if (!extendedDec.hasField(TIMESTAMP)) {
- return false;
- }
- if (extendedDec.getFields().size() != EXTENDED_FIELD_SIZE) {
- return false;
- }
- iDeclaration = extendedDec.getFields().get(TIMESTAMP);
- if (!(iDeclaration instanceof IntegerDeclaration)) {
- return false;
- }
- tsDec = (IntegerDeclaration) iDeclaration;
- if (tsDec.getLength() != FULL_TS || tsDec.isSigned()) {
- return false;
- }
- iDeclaration = extendedDec.getFields().get(ID);
- if (!(iDeclaration instanceof IntegerDeclaration)) {
- return false;
- }
- IntegerDeclaration iId = (IntegerDeclaration) iDeclaration;
- if (iId.getLength() != ID_SIZE || iId.isSigned()) {
- return false;
- }
- return true;
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.internal.ctf.core.event.types.composite;
-
-import java.util.List;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.scope.LexicalScope;
-import org.eclipse.linuxtools.ctf.core.event.types.Declaration;
-import org.eclipse.linuxtools.ctf.core.event.types.Definition;
-import org.eclipse.linuxtools.ctf.core.event.types.ICompositeDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.IEventHeaderDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDefinition;
-
-import com.google.common.collect.ImmutableList;
-
-/**
- * An event header definition, as shown in the example of the CTF spec examples
- * section 6.1.1
- *
- * @author Matthew Khouzam
- */
-public final class EventHeaderDefinition extends Definition implements ICompositeDefinition {
-
- private static final List<String> FIELD_NAMES = ImmutableList.of(
- IEventHeaderDeclaration.ID,
- IEventHeaderDeclaration.TIMESTAMP
- );
-
- private final int fId;
- private final long fTimestamp;
- private final int fTimestampLength;
-
- /**
- * Event header defintion
- *
- * @param id
- * the event id
- * @param timestamp
- * the timestamp
- * @param eventHeaderDecl
- * The declaration of this defintion
- * @param timestampLength
- * the number of bits valid in the timestamp
- */
- public EventHeaderDefinition(@NonNull Declaration eventHeaderDecl, int id, long timestamp, int timestampLength) {
- super(eventHeaderDecl, null, LexicalScope.EVENT_HEADER.toString(), LexicalScope.EVENT_HEADER);
- fId = id;
- fTimestamp = timestamp;
- fTimestampLength = timestampLength;
- }
-
- /**
- * Gets the timestamp declaration
- *
- * @return the timestamp declaration
- */
- public int getTimestampLength() {
- return fTimestampLength;
- }
-
- /**
- * Get the event id
- *
- * @return the event id
- */
- public int getId() {
- return fId;
- }
-
- /**
- * Get the timestamp
- *
- * @return the timestamp
- */
- public long getTimestamp() {
- return fTimestamp;
- }
-
- @Override
- public Definition getDefinition(String fieldName) {
- if (fieldName.equals(IEventHeaderDeclaration.ID)) {
- return new IntegerDefinition(IntegerDeclaration.INT_32B_DECL, null, IEventHeaderDeclaration.ID, getId());
- } else if (fieldName.equals(IEventHeaderDeclaration.TIMESTAMP)) {
- return new IntegerDefinition(IntegerDeclaration.INT_64B_DECL, null, IEventHeaderDeclaration.TIMESTAMP, getTimestamp());
- }
- return null;
- }
-
- @Override
- public List<String> getFieldNames() {
- return FIELD_NAMES;
- }
-}
\ No newline at end of file
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2014 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Matthew Khouzam - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.internal.ctf.core.event.types.composite;
-
-import java.nio.ByteOrder;
-
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.scope.IDefinitionScope;
-import org.eclipse.linuxtools.ctf.core.event.types.Declaration;
-import org.eclipse.linuxtools.ctf.core.event.types.EnumDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IEventHeaderDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.VariantDeclaration;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-
-/**
- * An event header declaration is a declaration of a structure defined in the
- * CTF spec examples section 6.1.1 . It is used in LTTng traces. This will
- * accelerate reading of the trace.
- *
- * Reminder
- *
- * <pre>
- * struct event_header_large {
- * enum : uint16_t { compact = 0 ... 65534, extended = 65535 } id;
- * variant <id> {
- * struct {
- * uint32_clock_monotonic_t timestamp;
- * } compact;
- * struct {
- * uint32_t id;
- * uint64_clock_monotonic_t timestamp;
- * } extended;
- * } v;
- * } align(8);
- * </pre>
- *
- * @author Matthew Khouzam
- */
-public class EventHeaderLargeDeclaration extends Declaration implements IEventHeaderDeclaration {
-
- /**
- * The id is 16 bits
- */
- private static final int COMPACT_ID = 16;
- private static final int EXTENDED_VALUE = 65535;
- /**
- * Full sized id is 32 bits
- */
- private static final int ID_SIZE = 32;
- /**
- * Full sized timestamp is 64 bits
- */
- private static final int FULL_TS = 64;
- /**
- * Compact timestamp is 32 bits,
- */
- private static final int COMPACT_TS = 32;
- /**
- * Maximum size = largest this header can be
- */
- private static final int MAX_SIZE = 112;
- /**
- * Byte aligned
- */
- private static final int ALIGN = 8;
- /**
- * Name of the variant according to the spec
- */
- private static final String V = "v"; //$NON-NLS-1$
- private static final int VARIANT_SIZE = 2;
- private static final int COMPACT_SIZE = 1;
- private static final int EXTENDED_FIELD_SIZE = 2;
-
- private final ByteOrder fByteOrder;
-
- /**
- * Event Header Declaration
- *
- * @param byteOrder
- * the byteorder
- */
- public EventHeaderLargeDeclaration(ByteOrder byteOrder) {
- fByteOrder = byteOrder;
- }
-
- @Override
- public EventHeaderDefinition createDefinition(IDefinitionScope definitionScope, String fieldName, BitBuffer input) throws CTFReaderException {
- alignRead(input);
- ByteOrder bo = input.getByteOrder();
- input.setByteOrder(fByteOrder);
- int first = (int) input.get(COMPACT_ID, false);
- long second = input.get(COMPACT_TS, false);
- if (first != EXTENDED_VALUE) {
- input.setByteOrder(bo);
- return new EventHeaderDefinition(this, first, second, COMPACT_TS);
- }
- long timestampLong = input.get(FULL_TS, false);
- input.setByteOrder(bo);
- if (second > Integer.MAX_VALUE) {
- throw new CTFReaderException("ID " + second + " larger than " + Integer.MAX_VALUE + " is currently unsupported by the parser"); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
- }
- return new EventHeaderDefinition(this, (int) second, timestampLong, FULL_TS);
- }
-
- @Override
- public long getAlignment() {
- return ALIGN;
- }
-
- @Override
- public int getMaximumSize() {
- return MAX_SIZE;
- }
-
- /**
- * Check if a given struct declaration is an event header
- *
- * @param declaration
- * the declaration
- * @return true if the event is a large event header
- */
- public static boolean isLargeEventHeader(StructDeclaration declaration) {
-
- IDeclaration iDeclaration = declaration.getFields().get(ID);
- if (!(iDeclaration instanceof EnumDeclaration)) {
- return false;
- }
- EnumDeclaration eId = (EnumDeclaration) iDeclaration;
- if (eId.getContainerType().getLength() != COMPACT_ID) {
- return false;
- }
- iDeclaration = declaration.getFields().get(V);
-
- if (!(iDeclaration instanceof VariantDeclaration)) {
- return false;
- }
- VariantDeclaration vDec = (VariantDeclaration) iDeclaration;
- if (!vDec.hasField(COMPACT) || !vDec.hasField(EXTENDED)) {
- return false;
- }
- if (vDec.getFields().size() != VARIANT_SIZE) {
- return false;
- }
- iDeclaration = vDec.getFields().get(COMPACT);
- if (!(iDeclaration instanceof StructDeclaration)) {
- return false;
- }
- StructDeclaration compactDec = (StructDeclaration) iDeclaration;
- if (compactDec.getFields().size() != COMPACT_SIZE) {
- return false;
- }
- if (!compactDec.hasField(TIMESTAMP)) {
- return false;
- }
- iDeclaration = compactDec.getFields().get(TIMESTAMP);
- if (!(iDeclaration instanceof IntegerDeclaration)) {
- return false;
- }
- IntegerDeclaration tsDec = (IntegerDeclaration) iDeclaration;
- if (tsDec.getLength() != COMPACT_TS || tsDec.isSigned()) {
- return false;
- }
- iDeclaration = vDec.getFields().get(EXTENDED);
- if (!(iDeclaration instanceof StructDeclaration)) {
- return false;
- }
- StructDeclaration extendedDec = (StructDeclaration) iDeclaration;
- if (!extendedDec.hasField(TIMESTAMP)) {
- return false;
- }
- if (extendedDec.getFields().size() != EXTENDED_FIELD_SIZE) {
- return false;
- }
- iDeclaration = extendedDec.getFields().get(TIMESTAMP);
- if (!(iDeclaration instanceof IntegerDeclaration)) {
- return false;
- }
- tsDec = (IntegerDeclaration) iDeclaration;
- if (tsDec.getLength() != FULL_TS || tsDec.isSigned()) {
- return false;
- }
- iDeclaration = extendedDec.getFields().get(ID);
- if (!(iDeclaration instanceof IntegerDeclaration)) {
- return false;
- }
- IntegerDeclaration iId = (IntegerDeclaration) iDeclaration;
- if (iId.getLength() != ID_SIZE || iId.isSigned()) {
- return false;
- }
- return true;
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- * Contributors: Etienne Bergeron <etienne.bergeron@gmail.com>
- * Contributors: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
- *******************************************************************************/
-
-package org.eclipse.linuxtools.internal.ctf.core.trace;
-
-import java.util.ListIterator;
-import java.util.Vector;
-
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-
-/**
- * <b><u>StreamInputPacketIndex</u></b>
- * <p>
- * TODO Implement me. Please.
- */
-public class StreamInputPacketIndex {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- /**
- * Entries of the index. They are sorted by increasing begin timestamp.
- * index builder.
- */
- private final Vector<StreamInputPacketIndexEntry> entries = new Vector<>();
-
- // ------------------------------------------------------------------------
- // Getters/Setters/Predicates
- // ------------------------------------------------------------------------
-
- /**
- * Gets the entries
- *
- * @return the entries
- */
- public Vector<StreamInputPacketIndexEntry> getEntries() {
- return this.entries;
- }
-
- /**
- * Gets an iterator to the entries
- *
- * @return an iterator to the entries
- */
- public ListIterator<StreamInputPacketIndexEntry> listIterator() {
- return this.entries.listIterator();
- }
-
- /**
- * Gets an iterator to the entries at a given position
- *
- * @param n
- * the position to get
- * @return the iterator
- */
- public ListIterator<StreamInputPacketIndexEntry> listIterator(int n) {
- return this.entries.listIterator(n);
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- /**
- * Adds an entry to the index.
- *
- * @param entry
- * The entry to add
- * @throws CTFReaderException
- * If there was a problem reading the entry
- */
- public void addEntry(StreamInputPacketIndexEntry entry)
- throws CTFReaderException {
- assert (entry.getContentSizeBits() != 0);
-
- /* Validate consistent entry. */
- if (entry.getTimestampBegin() > entry.getTimestampEnd()) {
- throw new CTFReaderException("Packet begin timestamp is after end timestamp"); //$NON-NLS-1$
- }
-
- /* Validate entries are inserted in monotonic increasing timestamp order. */
- if (!this.entries.isEmpty()) {
- if (entry.getTimestampBegin() < this.entries.lastElement()
- .getTimestampBegin()) {
- throw new CTFReaderException("Packets begin timestamp decreasing"); //$NON-NLS-1$
- }
- }
- this.entries.add(entry);
- }
-
- /**
- * Returns the first PacketIndexEntry that could include the timestamp,
- * that is the last packet with a begin timestamp smaller than the given timestamp.
- *
- * @param timestamp
- * The timestamp to look for.
- * @return The StreamInputPacketEntry that corresponds to the packet that
- * includes the given timestamp.
- */
- public ListIterator<StreamInputPacketIndexEntry> search(final long timestamp) {
- /*
- * Start with min and max covering all the elements.
- */
- int max = this.entries.size() - 1;
- int min = 0;
-
- int guessI;
- StreamInputPacketIndexEntry guessEntry = null;
-
- /*
- * If the index is empty, return the iterator at the very beginning.
- */
- if (this.getEntries().isEmpty()) {
- return this.getEntries().listIterator();
- }
-
- if (timestamp < 0) {
- throw new IllegalArgumentException("timestamp is negative"); //$NON-NLS-1$
- }
-
- /* Binary search */
- for (;;) {
- /*
- * Guess in the middle of min and max.
- */
- guessI = min + ((max - min) / 2);
- guessEntry = this.entries.get(guessI);
-
- /*
- * If we reached the point where we focus on a single packet, our
- * search is done.
- */
- if (min == max) {
- break;
- }
-
- if (timestamp <= guessEntry.getTimestampEnd()) {
- /*
- * If the timestamp is lower or equal to the end of the guess packet,
- * then the guess packet becomes the new inclusive max.
- */
- max = guessI;
- } else {
- /*
- * If the timestamp is greater than the end of the guess packet, then
- * the new inclusive min is the packet after the guess packet.
- */
- min = guessI + 1;
- }
- }
-
- return this.entries.listIterator(guessI);
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.internal.ctf.core.trace;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * <b><u>StreamInputPacketIndexEntry</u></b>
- * <p>
- * Represents an entry in the index of event packets.
- */
-public class StreamInputPacketIndexEntry {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- /**
- * Offset of the packet in the file, in bytes
- */
- final private long fOffsetBytes;
-
- /**
- * Offset of the data in the packet, in bits
- */
- private long fDataOffsetBits = 0;
-
- /**
- * Packet size, in bits
- */
- private long fPacketSizeBits = 0;
-
- /**
- * Content size, in bits
- */
- private long fContentSizeBits = 0;
-
- /**
- * Begin timestamp
- */
- private long fTimestampBegin = 0;
-
- /**
- * End timestamp
- */
- private long fTimestampEnd = 0;
-
- /**
- * How many lost events are there?
- */
- private long fLostEvents = 0;
-
- /**
- * Which target is being traced
- */
- private String fTarget ;
- private long fTargetID;
-
- /**
- * Attributes of this index entry
- */
- private final Map<String, Object> fAttributes = new HashMap<>();
-
-
- // ------------------------------------------------------------------------
- // Constructors
- // ------------------------------------------------------------------------
-
- /**
- * Constructs an index entry.
- *
- * @param offset
- * The offset of the packet in the file, in bytes.
- */
-
- public StreamInputPacketIndexEntry(long offset) {
- fOffsetBytes = offset;
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- /**
- * Returns whether the packet includes (inclusively) the given timestamp in
- * the begin-end timestamp range.
- *
- * @param ts
- * The timestamp to check.
- * @return True if the packet includes the timestamp.
- */
- boolean includes(long ts) {
- return (ts >= fTimestampBegin) && (ts <= fTimestampEnd);
- }
-
- @Override
- public String toString() {
- return "StreamInputPacketIndexEntry [offsetBytes=" + fOffsetBytes //$NON-NLS-1$
- + ", timestampBegin=" + fTimestampBegin + ", timestampEnd=" //$NON-NLS-1$ //$NON-NLS-2$
- + fTimestampEnd + "]"; //$NON-NLS-1$
- }
-
- // ------------------------------------------------------------------------
- // Getters and Setters
- // ------------------------------------------------------------------------
-
- /**
- * @return the offsetBytes
- */
- public long getOffsetBytes() {
- return fOffsetBytes;
- }
-
- /**
- * @return the dataOffsetBits
- */
- public long getDataOffsetBits() {
- return fDataOffsetBits;
- }
-
- /**
- * @param dataOffsetBits
- * the dataOffsetBits to set
- */
- public void setDataOffsetBits(long dataOffsetBits) {
- fDataOffsetBits = dataOffsetBits;
- }
-
- /**
- * @return the packetSizeBits
- */
- public long getPacketSizeBits() {
- return fPacketSizeBits;
- }
-
- /**
- * @param packetSizeBits
- * the packetSizeBits to set
- */
- public void setPacketSizeBits(long packetSizeBits) {
- fPacketSizeBits = packetSizeBits;
- }
-
- /**
- * @return the contentSizeBits
- */
- public long getContentSizeBits() {
- return fContentSizeBits;
- }
-
- /**
- * @param contentSizeBits
- * the contentSizeBits to set
- */
- public void setContentSizeBits(long contentSizeBits) {
- fContentSizeBits = contentSizeBits;
- }
-
- /**
- * @return the timestampBegin
- */
- public long getTimestampBegin() {
- return fTimestampBegin;
- }
-
- /**
- * @param timestampBegin
- * the timestampBegin to set
- */
- public void setTimestampBegin(long timestampBegin) {
- fTimestampBegin = timestampBegin;
- }
-
- /**
- * @return the timestampEnd
- */
- public long getTimestampEnd() {
- return fTimestampEnd;
- }
-
- /**
- * @param timestampEnd
- * the timestampEnd to set
- */
- public void setTimestampEnd(long timestampEnd) {
- fTimestampEnd = timestampEnd;
- }
-
- /**
- * @return the lostEvents in this packet
- */
- public long getLostEvents() {
- return fLostEvents;
- }
-
- /**
- * @param lostEvents the lostEvents to set
- */
- public void setLostEvents(long lostEvents) {
- fLostEvents = lostEvents;
- }
-
- /**
- * Add an attribute to this index entry
- *
- * @param field
- * The name of the attribute
- * @param value
- * The value to insert
- */
- public void addAttribute(String field, Object value) {
- fAttributes.put(field, value);
- }
-
- /**
- * Retrieve the value of an existing attribute
- *
- * @param field
- * The name of the attribute
- * @return The value that was stored, or null if it wasn't found
- */
- public Object lookupAttribute(String field){
- return fAttributes.get(field);
- }
-
- /**
- * @return The target that is being traced
- */
- public String getTarget() {
- return fTarget;
- }
-
- /**
- * Assign a target to this index entry
- *
- * @param target
- * The target to assign
- */
- public void setTarget(String target) {
- fTarget = target;
- fTargetID = Integer.parseInt(target.replaceAll("[\\D]", "")); //$NON-NLS-1$ //$NON-NLS-2$ // slow
- }
-
- /**
- * @return The ID of the target
- */
- public long getTargetId(){
- return fTargetID;
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
- *
- * All rights reserved. This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Matthew Khouzam - Initial API and implementation
- * Contributors: Simon Marchi - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.internal.ctf.core.trace;
-
-import java.io.Serializable;
-import java.util.Comparator;
-
-import org.eclipse.linuxtools.ctf.core.event.EventDefinition;
-import org.eclipse.linuxtools.ctf.core.trace.CTFStreamInputReader;
-import org.eclipse.linuxtools.ctf.core.trace.Utils;
-
-/**
- * <b><u>StreamInputReaderTimestampComparator</u></b>
- * <p>
- * Compares two StreamInputReader by their timestamp (smaller comes before).
- */
-public class StreamInputReaderTimestampComparator implements
- Comparator<CTFStreamInputReader>, Serializable {
-
- // ------------------------------------------------------------------------
- // Constants
- // ------------------------------------------------------------------------
-
- private static final long serialVersionUID = 1066434959451875045L;
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- /**
- * @throws NullPointerException
- * If any {@link CTFStreamInputReader} parameter is null, of if any
- * of them does not contain a current event.
- */
- @Override
- public int compare(CTFStreamInputReader a, CTFStreamInputReader b) {
- EventDefinition event_a = a.getCurrentEvent();
- EventDefinition event_b = b.getCurrentEvent();
-
- long ta = event_a.getTimestamp();
- long tb = event_b.getTimestamp();
- return Utils.unsignedCompare(ta, tb);
- }
-
-}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Alexandre Montplaisir - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core;
+
+import org.eclipse.jdt.annotation.NonNullByDefault;
+
+/**
+ * Non-externalized strings for use with the CTF plugin (event names, field
+ * names, etc.)
+ *
+ * @author Alexandre Montplaisir
+ * @since 2.2
+ */
+@SuppressWarnings("nls")
+@NonNullByDefault
+public interface CTFStrings {
+
+ /** Event name for lost events */
+ static final String LOST_EVENT_NAME = "Lost event";
+
+ /**
+ * Name of the field in lost events indicating how many actual events were
+ * lost
+ */
+ static final String LOST_EVENTS_FIELD = "Lost events";
+
+ /**
+ * Name of the field in lost events indicating the time range
+ */
+ static final String LOST_EVENTS_DURATION = "duration";
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2012, 2013 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event;
+
+/**
+ * Callsite information to help with cdt integration
+ *
+ * @author Matthew Khouzam
+ *
+ * @since 1.2
+ */
+public class CTFCallsite implements Comparable<CTFCallsite> {
+
+ private static final long MASK32 = 0x00000000ffffffffL;
+
+ /**
+ * The event name
+ */
+ private final String fEventName;
+
+ /**
+ * the file name of the callsite
+ */
+ private final String fFileName;
+
+ /**
+ * the instruction pointer
+ */
+ private final long fIp;
+
+ /**
+ * the function name
+ */
+ private final String fFunctionName;
+
+ /**
+ * the line number of the callsite
+ */
+ private final long fLineNumber;
+
+ /**
+ * The callsite constructor
+ *
+ * @param en
+ * The event name
+ * @param func
+ * the function name
+ * @param ip
+ * the instruction pointer of the callsite
+ * @param fn
+ * the file name of the callsite
+ * @param line
+ * the line number of the callsite
+ */
+ public CTFCallsite(String en, String func, long ip, String fn, long line) {
+ fEventName = en;
+ fFileName = fn;
+ fFunctionName = func;
+ fIp = ip;
+ fLineNumber = line;
+ }
+
+ /**
+ * @return the eventName
+ */
+ public String getEventName() {
+ return fEventName;
+ }
+
+ /**
+ * @return the fileName
+ */
+ public String getFileName() {
+ return fFileName;
+ }
+
+ /**
+ * @return the ip
+ */
+ public long getIp() {
+ return fIp;
+ }
+
+ /**
+ * @return the functionName
+ */
+ public String getFunctionName() {
+ return fFunctionName;
+ }
+
+ /**
+ * @return the lineNumber
+ */
+ public long getLineNumber() {
+ return fLineNumber;
+ }
+
+ /*
+ * The callsites will be sorted by calling addresses. To do this we take IPs
+ * (instruction pointers) and compare them. Java only supports signed
+ * operation and since memory addresses are unsigned, we will convert the
+ * longs into integers that contain the high and low bytes and compare them.
+ */
+ @Override
+ public int compareTo(CTFCallsite o) {
+ /*
+ * mask32 is 32 zeros followed by 32 ones, when we bitwise and this it
+ * will return the lower 32 bits
+ */
+
+ long other = o.fIp;
+ /*
+ * To get a high int: we downshift by 32 and bitwise and with the mask
+ * to get rid of the sign
+ *
+ * To get the low int: we bitwise and with the mask.
+ */
+ long otherHigh = (other >> 32) & MASK32;
+ long otherLow = other & MASK32;
+ long ownHigh = (fIp >> 32) & MASK32;
+ long ownLow = fIp & MASK32;
+ /* are the high values different, if so ignore the lower values */
+ if (ownHigh > otherHigh) {
+ return 1;
+ }
+ if (ownHigh < otherHigh ) {
+ return -1;
+ }
+ /* the high values are the same, compare the lower values */
+ if (ownLow > otherLow) {
+ return 1;
+ }
+ if (ownLow < otherLow) {
+ return -1;
+ }
+ /* the values are identical */
+ return 0;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((fEventName == null) ? 0 : fEventName.hashCode());
+ result = prime * result + ((fFileName == null) ? 0 : fFileName.hashCode());
+ result = prime * result + ((fFunctionName == null) ? 0 : fFunctionName.hashCode());
+ result = prime * result + (int) (fIp ^ (fIp >>> 32));
+ result = prime * result + (int) (fLineNumber ^ (fLineNumber >>> 32));
+ return result;
+ }
+
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ CTFCallsite other = (CTFCallsite) obj;
+ if (fEventName == null) {
+ if (other.fEventName != null) {
+ return false;
+ }
+ } else if (!fEventName.equals(other.fEventName)) {
+ return false;
+ }
+ if (fFileName == null) {
+ if (other.fFileName != null) {
+ return false;
+ }
+ } else if (!fFileName.equals(other.fFileName)) {
+ return false;
+ }
+ if (fFunctionName == null) {
+ if (other.fFunctionName != null) {
+ return false;
+ }
+ } else if (!fFunctionName.equals(other.fFunctionName)) {
+ return false;
+ }
+ if (fIp != other.fIp) {
+ return false;
+ }
+ if (fLineNumber != other.fLineNumber) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ return fFileName + "/" + fFunctionName + ":" + fLineNumber; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Clock description used in CTF traces
+ */
+public class CTFClock {
+
+ private static final long ONE_BILLION_L = 1000000000L;
+ private static final double ONE_BILLION_D = 1000000000.0;
+
+ private static final String NAME = "name"; //$NON-NLS-1$
+ private static final String FREQ = "freq"; //$NON-NLS-1$
+ private static final String OFFSET = "offset"; //$NON-NLS-1$
+
+ private long fClockOffset = 0;
+ private double fClockScale = 1.0;
+ private double fClockAntiScale = 1.0;
+
+ /**
+ * Field properties.
+ */
+ private final Map<String, Object> fProperties = new HashMap<>();
+ /**
+ * Field name.
+ */
+ private String fName;
+ private boolean fIsScaled = false;
+
+ /**
+ * Default constructor
+ */
+ public CTFClock() {
+ }
+
+ /**
+ * Method addAttribute.
+ *
+ * @param key
+ * String
+ * @param value
+ * Object
+ */
+ public void addAttribute(String key, Object value) {
+ fProperties.put(key, value);
+ if (key.equals(NAME)) {
+ fName = (String) value;
+ }
+ if (key.equals(FREQ)) {
+ /*
+ * Long is converted to a double. the double is then dividing
+ * another double that double is saved. this is precise as long as
+ * the long is under 53 bits long. this is ok as long as we don't
+ * have a system with a frequency of > 1 600 000 000 GHz with
+ * 200 ppm precision
+ */
+ fIsScaled = !((Long) getProperty(FREQ)).equals(ONE_BILLION_L);
+ fClockScale = ONE_BILLION_D / ((Long) getProperty(FREQ)).doubleValue();
+ fClockAntiScale = 1.0 / fClockScale;
+
+ }
+ if (key.equals(OFFSET)) {
+ fClockOffset = (Long) getProperty(OFFSET);
+ }
+ }
+
+ /**
+ * Method getName.
+ *
+ * @return String
+ */
+ public String getName() {
+ return fName;
+ }
+
+ /**
+ * Method getProperty.
+ *
+ * @param key
+ * String
+ * @return Object
+ */
+ public Object getProperty(String key) {
+ return fProperties.get(key);
+ }
+
+ /**
+ * @return the clockOffset
+ * @since 2.0
+ */
+ public long getClockOffset() {
+ return fClockOffset;
+ }
+
+ /**
+ * @return the clockScale
+ * @since 2.0
+ */
+ public double getClockScale() {
+ return fClockScale;
+ }
+
+ /**
+ * @return the clockAntiScale
+ * @since 2.0
+ */
+ public double getClockAntiScale() {
+ return fClockAntiScale;
+ }
+
+ /**
+ * @return is the clock in ns or cycles?
+ * @since 2.0
+ */
+ public boolean isClockScaled() {
+ return fIsScaled;
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011-2013 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.event.scope.LexicalScope;
+import org.eclipse.tracecompass.ctf.core.event.types.Definition;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDefinition;
+import org.eclipse.tracecompass.ctf.core.trace.CTFStreamInputReader;
+import org.eclipse.tracecompass.internal.ctf.core.event.EventDeclaration;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableList.Builder;
+
+/**
+ * Representation of a particular instance of an event.
+ */
+public final class EventDefinition implements IDefinitionScope {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ /**
+ * A null event, can be used for testing or poison pilling
+ *
+ * @since 3.0
+ */
+ @NonNull
+ public static final EventDefinition NULL_EVENT = new EventDefinition(new EventDeclaration(), null, -1L, null, null, null, null);
+
+ /**
+ * The corresponding event declaration.
+ */
+ private final IEventDeclaration fDeclaration;
+
+ /**
+ * The timestamp of the current event.
+ */
+ private final long fTimestamp;
+
+ /**
+ * The event context structure definition.
+ */
+ private final StructDefinition fEventContext;
+
+ private final StructDefinition fStreamContext;
+
+ private final StructDefinition fPacketContext;
+
+ /**
+ * The event fields structure definition.
+ */
+ private final StructDefinition fFields;
+
+ /**
+ * The StreamInputReader that reads this event definition.
+ */
+ private final CTFStreamInputReader fStreamInputReader;
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructs an event definition.
+ *
+ * @param declaration
+ * The corresponding event declaration
+ * @param streamInputReader
+ * The SIR from where this EventDef was read
+ * @param timestamp
+ * event timestamp
+ * @param eventContext
+ * The event context
+ * @param packetContext
+ * the packet context
+ * @param streamContext
+ * the stream context
+ * @param fields
+ * The event fields
+ * @since 3.0
+ */
+ public EventDefinition(IEventDeclaration declaration,
+ CTFStreamInputReader streamInputReader,
+ long timestamp,
+ StructDefinition streamContext,
+ StructDefinition eventContext,
+ StructDefinition packetContext,
+ StructDefinition fields) {
+ fDeclaration = declaration;
+ fStreamInputReader = streamInputReader;
+ fTimestamp = timestamp;
+ fFields = fields;
+ fEventContext = eventContext;
+ fPacketContext = packetContext;
+ fStreamContext = streamContext;
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ /**
+ * @since 3.0
+ */
+ @Override
+ public LexicalScope getScopePath() {
+ String eventName = fDeclaration.getName();
+ if (eventName == null) {
+ return null;
+ }
+ LexicalScope myScope = LexicalScope.EVENT.getChild(eventName);
+ if (myScope == null) {
+ myScope = new LexicalScope(LexicalScope.EVENT, eventName);
+ }
+ return myScope;
+ }
+
+ /**
+ * Gets the declaration (the form) of the data
+ *
+ * @return the event declaration
+ * @since 2.0
+ */
+ public IEventDeclaration getDeclaration() {
+ return fDeclaration;
+ }
+
+ /**
+ * Gets the fields of a definition
+ *
+ * @return the fields of a definition in struct form. Can be null.
+ */
+ public StructDefinition getFields() {
+ return fFields;
+ }
+
+ /**
+ * Gets the context of this event without the context of the stream
+ *
+ * @return the context in struct form
+ * @since 1.2
+ */
+ public StructDefinition getEventContext() {
+ return fEventContext;
+ }
+
+ /**
+ * Gets the context of this event within a stream
+ *
+ * @return the context in struct form
+ */
+ public StructDefinition getContext() {
+
+ /* Most common case so far */
+ if (fStreamContext == null) {
+ return fEventContext;
+ }
+
+ /* streamContext is not null, but the context of the event is null */
+ if (fEventContext == null) {
+ return fStreamContext;
+ }
+
+ // TODO: cache if this is a performance issue
+
+ /* The stream context and event context are assigned. */
+ StructDeclaration mergedDeclaration = new StructDeclaration(1);
+
+ Builder<String> builder = ImmutableList.<String> builder();
+ List<Definition> fieldValues = new ArrayList<>();
+
+ /* Add fields from the stream */
+ for (String fieldName : fStreamContext.getFieldNames()) {
+ Definition definition = fStreamContext.getDefinition(fieldName);
+ mergedDeclaration.addField(fieldName, definition.getDeclaration());
+ builder.add(fieldName);
+ fieldValues.add(definition);
+ }
+
+ ImmutableList<String> fieldNames = builder.build();
+ /*
+ * Add fields from the event context, overwrite the stream ones if
+ * needed.
+ */
+ for (String fieldName : fEventContext.getFieldNames()) {
+ Definition definition = fEventContext.getDefinition(fieldName);
+ mergedDeclaration.addField(fieldName, definition.getDeclaration());
+ if (fieldNames.contains(fieldName)) {
+ fieldValues.set((fieldNames.indexOf(fieldName)), definition);
+ } else {
+ builder.add(fieldName);
+ fieldValues.add(definition);
+ }
+ }
+ fieldNames = builder.build();
+ StructDefinition mergedContext = new StructDefinition(mergedDeclaration, this, "context", //$NON-NLS-1$
+ fieldNames,
+ fieldValues.toArray(new Definition[fieldValues.size()]));
+ return mergedContext;
+ }
+
+ /**
+ * Gets the stream input reader that this event was made by
+ *
+ * @return the parent
+ * @since 3.0
+ */
+ public CTFStreamInputReader getStreamInputReader() {
+ return fStreamInputReader;
+ }
+
+ /**
+ * Gets the context of packet the event is in.
+ *
+ * @return the packet context
+ */
+ public StructDefinition getPacketContext() {
+ return fPacketContext;
+ }
+
+ /**
+ * gets the CPU the event was generated by. Slightly LTTng specific
+ *
+ * @return The CPU the event was generated by
+ */
+ public int getCPU() {
+ return fStreamInputReader.getCPU();
+ }
+
+ /**
+ * @return the timestamp
+ */
+ public long getTimestamp() {
+ return fTimestamp;
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ @Override
+ public Definition lookupDefinition(String lookupPath) {
+ if (lookupPath.equals("context")) { //$NON-NLS-1$
+ return fEventContext;
+ } else if (lookupPath.equals("fields")) { //$NON-NLS-1$
+ return fFields;
+ } else {
+ return null;
+ }
+ }
+
+ @Override
+ public String toString() {
+ Iterable<String> list;
+ StringBuilder retString = new StringBuilder();
+ final String cr = System.getProperty("line.separator");//$NON-NLS-1$
+
+ retString.append("Event type: " + fDeclaration.getName() + cr); //$NON-NLS-1$
+ retString.append("Timestamp: " + Long.toString(fTimestamp) + cr); //$NON-NLS-1$
+
+ if (fEventContext != null) {
+ list = fEventContext.getDeclaration().getFieldsList();
+
+ for (String field : list) {
+ retString.append(field
+ + " : " + fEventContext.getDefinition(field).toString() + cr); //$NON-NLS-1$
+ }
+ }
+
+ if (fFields != null) {
+ list = fFields.getDeclaration().getFieldsList();
+
+ for (String field : list) {
+ retString.append(field
+ + " : " + fFields.getDefinition(field).toString() + cr); //$NON-NLS-1$
+ }
+ }
+
+ return retString.toString();
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011-2013 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event;
+
+import java.util.Set;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.ctf.core.trace.CTFStream;
+import org.eclipse.tracecompass.ctf.core.trace.CTFStreamInputReader;
+
+/**
+ * Representation of one type of event. A bit like "int" or "long" but for trace
+ * events.
+ *
+ * @author Matthew Khouzam
+ * @since 2.0
+ */
+public interface IEventDeclaration {
+
+ /**
+ * Creates an instance of EventDefinition corresponding to this declaration.
+ *
+ * @param streamInputReader
+ * The StreamInputReader for which this definition is created.
+ * @param input
+ * the bitbuffer input source
+ * @param timestamp
+ * The timestamp when the event was taken
+ * @return A new EventDefinition.
+ * @throws CTFReaderException
+ * As a bitbuffer is used to read, it could have wrapped
+ * IOExceptions.
+ * @since 3.0
+ */
+ EventDefinition createDefinition(CTFStreamInputReader streamInputReader, @NonNull BitBuffer input, long timestamp) throws CTFReaderException;
+
+ /**
+ * Gets the name of an event declaration
+ *
+ * @return the name
+ */
+ String getName();
+
+ /**
+ * Gets the fields of an event declaration
+ *
+ * @return fields the fields in {@link StructDeclaration} format
+ */
+ StructDeclaration getFields();
+
+ /**
+ * Gets the context of an event declaration
+ *
+ * @return context the fields in {@link StructDeclaration} format
+ */
+ StructDeclaration getContext();
+
+ /**
+ * Gets the id of an event declaration
+ *
+ * @return The EventDeclaration ID
+ */
+ Long getId();
+
+ /**
+ * Gets the {@link CTFStream} of an event declaration
+ *
+ * @return the stream
+ * @since 3.0
+ */
+ CTFStream getStream();
+
+ /**
+ * What is the log level of this event?
+ *
+ * @return the log level.
+ * @since 2.0
+ */
+ long getLogLevel();
+
+ /**
+ * Get the {@link Set} of names of the custom CTF attributes.
+ *
+ * @return The set of custom attributes
+ * @since 2.0
+ */
+ Set<String> getCustomAttributes();
+
+ /**
+ * Get the value of a given CTF attribute.
+ *
+ * @param key
+ * The CTF attribute name
+ * @return the CTF attribute
+ * @since 2.0
+ */
+ String getCustomAttribute(String key);
+
+}
--- /dev/null
+/*******************************************************************************.
+ * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial Design and implementation + overhaul
+ * Francis Giraldeau - Initial API and implementation
+ * Philippe Proulx - Some refinement and optimization
+ * Etienne Bergeron <Etienne.Bergeron@gmail.com> - fix zero size read + cleanup
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.io;
+
+import java.nio.BufferUnderflowException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+
+/**
+ * <b><u>BitBuffer</u></b>
+ * <p>
+ * A bitwise buffer capable of accessing fields with bit offsets.
+ *
+ * @since 2.0
+ */
+public final class BitBuffer {
+
+ // ------------------------------------------------------------------------
+ // Constants
+ // ------------------------------------------------------------------------
+
+ /* default bit width */
+ /** 8 bits to a char */
+ public static final int BIT_CHAR = 8;
+ /** 16 bits to a short */
+ public static final int BIT_SHORT = 16;
+ /** 32 bits to an int */
+ public static final int BIT_INT = 32;
+ /** 32 bits to a float */
+ public static final int BIT_FLOAT = 32;
+ /** 64 bits to a long */
+ public static final int BIT_LONG = 64;
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ private final @NonNull ByteBuffer fBuffer;
+ private final long fBitCapacity;
+
+ /**
+ * Bit-buffer's position, maximum value = Integer.MAX_VALUE * 8
+ */
+ private long fPosition;
+ private ByteOrder fByteOrder;
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+ /**
+ * Default constructor, makes a big-endian buffer
+ */
+ @SuppressWarnings("null")
+ public BitBuffer() {
+ this(ByteBuffer.allocateDirect(0), ByteOrder.BIG_ENDIAN);
+ }
+
+ /**
+ * Constructor, makes a big-endian buffer
+ *
+ * @param buf
+ * the bytebuffer to read
+ */
+ public BitBuffer(@NonNull ByteBuffer buf) {
+ this(buf, ByteOrder.BIG_ENDIAN);
+ }
+
+ /**
+ * Constructor that is fully parameterizable
+ *
+ * @param buf
+ * the buffer to read
+ * @param order
+ * the byte order (big-endian, little-endian, network?)
+ */
+ public BitBuffer(@NonNull ByteBuffer buf, ByteOrder order) {
+ fBuffer = buf;
+ setByteOrder(order);
+ resetPosition();
+ fBitCapacity = fBuffer.capacity() * BIT_CHAR;
+ }
+
+ private void resetPosition() {
+ fPosition = 0;
+ }
+
+ // ------------------------------------------------------------------------
+ // 'Get' operations on buffer
+ // ------------------------------------------------------------------------
+
+ /**
+ * Relative <i>get</i> method for reading 32-bit integer.
+ *
+ * Reads next four bytes from the current bit position according to current
+ * byte order.
+ *
+ * @return The int value (signed) read from the buffer
+ * @throws CTFReaderException
+ * An error occurred reading the long. This exception can be
+ * raised if the buffer tries to read out of bounds
+ */
+ public int getInt() throws CTFReaderException {
+ return getInt(BIT_INT, true);
+ }
+
+ /**
+ * Relative <i>get</i> method for reading 64-bit integer.
+ *
+ * Reads next eight bytes from the current bit position according to current
+ * byte order.
+ *
+ * @return The long value (signed) read from the buffer
+ * @throws CTFReaderException
+ * An error occurred reading the long. This exception can be
+ * raised if the buffer tries to read out of bounds
+ * @since 3.0
+ */
+ public long getLong() throws CTFReaderException {
+ return get(BIT_LONG, true);
+ }
+
+ /**
+ * Relative <i>get</i> method for reading long of <i>length</i> bits.
+ *
+ * Reads <i>length</i> bits starting at the current position. The result is
+ * signed extended if <i>signed</i> is true. The current position is
+ * increased of <i>length</i> bits.
+ *
+ * @param length
+ * The length in bits of this integer
+ * @param signed
+ * The sign extended flag
+ * @return The long value read from the buffer
+ * @throws CTFReaderException
+ * An error occurred reading the data. If more than 64 bits at a
+ * time are read, or the buffer is read beyond its end, this
+ * exception will be raised.
+ * @since 3.0
+ */
+ public long get(int length, boolean signed) throws CTFReaderException {
+ if (length > BIT_LONG) {
+ throw new CTFReaderException("Cannot read a long longer than 64 bits. Rquested: " + length); //$NON-NLS-1$
+ }
+ if (length > BIT_INT) {
+ final int highShift = length - BIT_INT;
+ long a = getInt();
+ long b = getInt(highShift, false);
+ long retVal;
+ /* Cast the signed-extended int into a unsigned int. */
+ a &= 0xFFFFFFFFL;
+ b &= (1L << highShift) - 1L;
+
+ retVal = (fByteOrder == ByteOrder.BIG_ENDIAN) ? ((a << highShift) | b) : ((b << BIT_INT) | a);
+ /* sign extend */
+ if (signed) {
+ int signExtendBits = BIT_LONG - length;
+ retVal = (retVal << signExtendBits) >> signExtendBits;
+ }
+ return retVal;
+ }
+ long retVal = getInt(length, signed);
+ return (signed ? retVal : (retVal & 0xFFFFFFFFL));
+ }
+
+ /**
+ * Relative bulk <i>get</i> method.
+ *
+ * <p>
+ * This method transfers <strong>bytes</strong> from this buffer into the
+ * given destination array. This method currently only supports reads
+ * aligned to 8 bytes. It is up to the developer to shift the bits in
+ * post-processing to do unaligned reads.
+ *
+ * @param dst
+ * the bytes to write to
+ * @throws BufferUnderflowException
+ * - If there are fewer than length bytes remaining in this
+ * buffer
+ * @since 3.1
+ */
+ public void get(@NonNull byte[] dst) {
+ fBuffer.position((int) (fPosition / 8));
+ fBuffer.get(dst);
+ fPosition += dst.length * 8;
+ }
+
+ /**
+ * Relative <i>get</i> method for reading integer of <i>length</i> bits.
+ *
+ * Reads <i>length</i> bits starting at the current position. The result is
+ * signed extended if <i>signed</i> is true. The current position is
+ * increased of <i>length</i> bits.
+ *
+ * @param length
+ * The length in bits of this integer
+ * @param signed
+ * The sign extended flag
+ * @return The int value read from the buffer
+ * @throws CTFReaderException
+ * An error occurred reading the data. When the buffer is read
+ * beyond its end, this exception will be raised.
+ */
+ private int getInt(int length, boolean signed) throws CTFReaderException {
+
+ /* Nothing to read. */
+ if (length == 0) {
+ return 0;
+ }
+
+ /* Validate that the buffer has enough bits. */
+ if (!canRead(length)) {
+ throw new CTFReaderException("Cannot read the integer, " + //$NON-NLS-1$
+ "the buffer does not have enough remaining space. " + //$NON-NLS-1$
+ "Requested:" + length); //$NON-NLS-1$
+ }
+
+ /* Get the value from the byte buffer. */
+ int val = 0;
+ boolean gotIt = false;
+
+ /*
+ * Try a fast read when the position is byte-aligned by using
+ * java.nio.ByteBuffer's native methods
+ */
+ /*
+ * A faster alignment detection as the compiler cannot guaranty that pos
+ * is always positive.
+ */
+ if ((fPosition & (BitBuffer.BIT_CHAR - 1)) == 0) {
+ switch (length) {
+ case BitBuffer.BIT_CHAR:
+ // Byte
+ val = fBuffer.get((int) (fPosition / 8));
+ if (!signed) {
+ val = val & 0xff;
+ }
+ gotIt = true;
+ break;
+
+ case BitBuffer.BIT_SHORT:
+ // Word
+ val = fBuffer.getShort((int) (fPosition / 8));
+ if (!signed) {
+ val = val & 0xffff;
+ }
+ gotIt = true;
+ break;
+
+ case BitBuffer.BIT_INT:
+ // Double word
+ val = fBuffer.getInt((int) (fPosition / 8));
+ gotIt = true;
+ break;
+
+ default:
+ break;
+ }
+ }
+
+ /* When not byte-aligned, fall-back to a general decoder. */
+ if (!gotIt) {
+ // Nothing read yet: use longer methods
+ if (fByteOrder == ByteOrder.LITTLE_ENDIAN) {
+ val = getIntLE(fPosition, length, signed);
+ } else {
+ val = getIntBE(fPosition, length, signed);
+ }
+ }
+ fPosition += length;
+
+ return val;
+ }
+
+ private int getIntBE(long index, int length, boolean signed) {
+ if ((length <= 0) || (length > BIT_INT)) {
+ throw new IllegalArgumentException("Length must be between 1-32 bits"); //$NON-NLS-1$
+ }
+ long end = index + length;
+ int startByte = (int) (index / BIT_CHAR);
+ int endByte = (int) ((end + (BIT_CHAR - 1)) / BIT_CHAR);
+ int currByte, lshift, cshift, mask, cmask, cache;
+ int value = 0;
+
+ currByte = startByte;
+ cache = fBuffer.get(currByte) & 0xFF;
+ boolean isNeg = (cache & (1 << (BIT_CHAR - (index % BIT_CHAR) - 1))) != 0;
+ if (signed && isNeg) {
+ value = ~0;
+ }
+ if (startByte == (endByte - 1)) {
+ cmask = cache >>> ((BIT_CHAR - (end % BIT_CHAR)) % BIT_CHAR);
+ if (((length) % BIT_CHAR) > 0) {
+ mask = ~((~0) << length);
+ cmask &= mask;
+ }
+ value <<= length;
+ value |= cmask;
+ return value;
+ }
+ cshift = (int) (index % BIT_CHAR);
+ if (cshift > 0) {
+ mask = ~((~0) << (BIT_CHAR - cshift));
+ cmask = cache & mask;
+ lshift = BIT_CHAR - cshift;
+ value <<= lshift;
+ value |= cmask;
+ currByte++;
+ }
+ for (; currByte < (endByte - 1); currByte++) {
+ value <<= BIT_CHAR;
+ value |= fBuffer.get(currByte) & 0xFF;
+ }
+ lshift = (int) (end % BIT_CHAR);
+ if (lshift > 0) {
+ mask = ~((~0) << lshift);
+ cmask = fBuffer.get(currByte) & 0xFF;
+ cmask >>>= BIT_CHAR - lshift;
+ cmask &= mask;
+ value <<= lshift;
+ value |= cmask;
+ } else {
+ value <<= BIT_CHAR;
+ value |= fBuffer.get(currByte) & 0xFF;
+ }
+ return value;
+ }
+
+ private int getIntLE(long index, int length, boolean signed) {
+ if ((length <= 0) || (length > BIT_INT)) {
+ throw new IllegalArgumentException("Length must be between 1-32 bits"); //$NON-NLS-1$
+ }
+ long end = index + length;
+ int startByte = (int) (index / BIT_CHAR);
+ int endByte = (int) ((end + (BIT_CHAR - 1)) / BIT_CHAR);
+ int currByte, lshift, cshift, mask, cmask, cache, mod;
+ int value = 0;
+
+ currByte = endByte - 1;
+ cache = fBuffer.get(currByte) & 0xFF;
+ mod = (int) (end % BIT_CHAR);
+ lshift = (mod > 0) ? mod : BIT_CHAR;
+ boolean isNeg = (cache & (1 << (lshift - 1))) != 0;
+ if (signed && isNeg) {
+ value = ~0;
+ }
+ if (startByte == (endByte - 1)) {
+ cmask = cache >>> (index % BIT_CHAR);
+ if (((length) % BIT_CHAR) > 0) {
+ mask = ~((~0) << length);
+ cmask &= mask;
+ }
+ value <<= length;
+ value |= cmask;
+ return value;
+ }
+ cshift = (int) (end % BIT_CHAR);
+ if (cshift > 0) {
+ mask = ~((~0) << cshift);
+ cmask = cache & mask;
+ value <<= cshift;
+ value |= cmask;
+ currByte--;
+ }
+ for (; currByte >= (startByte + 1); currByte--) {
+ value <<= BIT_CHAR;
+ value |= fBuffer.get(currByte) & 0xFF;
+ }
+ lshift = (int) (index % BIT_CHAR);
+ if (lshift > 0) {
+ mask = ~((~0) << (BIT_CHAR - lshift));
+ cmask = fBuffer.get(currByte) & 0xFF;
+ cmask >>>= lshift;
+ cmask &= mask;
+ value <<= (BIT_CHAR - lshift);
+ value |= cmask;
+ } else {
+ value <<= BIT_CHAR;
+ value |= fBuffer.get(currByte) & 0xFF;
+ }
+ return value;
+ }
+
+ // ------------------------------------------------------------------------
+ // 'Put' operations on buffer
+ // ------------------------------------------------------------------------
+
+ /**
+ * Relative <i>put</i> method to write signed 32-bit integer.
+ *
+ * Write four bytes starting from current bit position in the buffer
+ * according to the current byte order. The current position is increased of
+ * <i>length</i> bits.
+ *
+ * @param value
+ * The int value to write
+ * @throws CTFReaderException
+ * An error occurred writing the data. If the buffer is written
+ * beyond its end, this exception will be raised.
+ */
+ public void putInt(int value) throws CTFReaderException {
+ putInt(BIT_INT, value);
+ }
+
+ /**
+ * Relative <i>put</i> method to write <i>length</i> bits integer.
+ *
+ * Writes <i>length</i> lower-order bits from the provided <i>value</i>,
+ * starting from current bit position in the buffer. Sequential bytes are
+ * written according to the current byte order. The sign bit is carried to
+ * the MSB if signed is true. The sign bit is included in <i>length</i>. The
+ * current position is increased of <i>length</i>.
+ *
+ * @param length
+ * The number of bits to write
+ * @param value
+ * The value to write
+ * @throws CTFReaderException
+ * An error occurred writing the data. If the buffer is written
+ * beyond its end, this exception will be raised.
+ */
+ public void putInt(int length, int value) throws CTFReaderException {
+ final long curPos = fPosition;
+
+ if (!canRead(length)) {
+ throw new CTFReaderException("Cannot write to bitbuffer, " //$NON-NLS-1$
+ + "insufficient space. Requested: " + length); //$NON-NLS-1$
+ }
+ if (length == 0) {
+ return;
+ }
+ if (fByteOrder == ByteOrder.LITTLE_ENDIAN) {
+ putIntLE(curPos, length, value);
+ } else {
+ putIntBE(curPos, length, value);
+ }
+ fPosition += length;
+ }
+
+ private void putIntBE(long index, int length, int value) {
+ if ((length <= 0) || (length > BIT_INT)) {
+ throw new IllegalArgumentException("Length must be between 1-32 bits"); //$NON-NLS-1$
+ }
+ long end = index + length;
+ int startByte = (int) (index / BIT_CHAR);
+ int endByte = (int) ((end + (BIT_CHAR - 1)) / BIT_CHAR);
+ int currByte, lshift, cshift, mask, cmask;
+ int correctedValue = value;
+
+ /*
+ * mask v high bits. Works for unsigned and two complement signed
+ * numbers which value do not overflow on length bits.
+ */
+
+ if (length < BIT_INT) {
+ correctedValue &= ~(~0 << length);
+ }
+
+ /* sub byte */
+ if (startByte == (endByte - 1)) {
+ lshift = (int) ((BIT_CHAR - (end % BIT_CHAR)) % BIT_CHAR);
+ mask = ~((~0) << lshift);
+ if ((index % BIT_CHAR) > 0) {
+ mask |= (~(0)) << (BIT_CHAR - (index % BIT_CHAR));
+ }
+ cmask = correctedValue << lshift;
+ /*
+ * low bits are cleared because of left-shift and high bits are
+ * already cleared
+ */
+ cmask &= ~mask;
+ int b = fBuffer.get(startByte) & 0xFF;
+ fBuffer.put(startByte, (byte) ((b & mask) | cmask));
+ return;
+ }
+
+ /* head byte contains MSB */
+ currByte = endByte - 1;
+ cshift = (int) (end % BIT_CHAR);
+ if (cshift > 0) {
+ lshift = BIT_CHAR - cshift;
+ mask = ~((~0) << lshift);
+ cmask = correctedValue << lshift;
+ cmask &= ~mask;
+ int b = fBuffer.get(currByte) & 0xFF;
+ fBuffer.put(currByte, (byte) ((b & mask) | cmask));
+ correctedValue >>>= cshift;
+ currByte--;
+ }
+
+ /* middle byte(s) */
+ for (; currByte >= (startByte + 1); currByte--) {
+ fBuffer.put(currByte, (byte) correctedValue);
+ correctedValue >>>= BIT_CHAR;
+ }
+ /* end byte contains LSB */
+ if ((index % BIT_CHAR) > 0) {
+ mask = (~0) << (BIT_CHAR - (index % BIT_CHAR));
+ cmask = correctedValue & ~mask;
+ int b = fBuffer.get(currByte) & 0xFF;
+ fBuffer.put(currByte, (byte) ((b & mask) | cmask));
+ } else {
+ fBuffer.put(currByte, (byte) correctedValue);
+ }
+ }
+
+ private void putIntLE(long index, int length, int value) {
+ if ((length <= 0) || (length > BIT_INT)) {
+ throw new IllegalArgumentException("Length must be between 1-32 bits"); //$NON-NLS-1$
+ }
+ long end = index + length;
+ int startByte = (int) (index / BIT_CHAR);
+ int endByte = (int) ((end + (BIT_CHAR - 1)) / BIT_CHAR);
+ int currByte, lshift, cshift, mask, cmask;
+ int correctedValue = value;
+
+ /*
+ * mask v high bits. Works for unsigned and two complement signed
+ * numbers which value do not overflow on length bits.
+ */
+
+ if (length < BIT_INT) {
+ correctedValue &= ~(~0 << length);
+ }
+
+ /* sub byte */
+ if (startByte == (endByte - 1)) {
+ lshift = (int) (index % BIT_CHAR);
+ mask = ~((~0) << lshift);
+ if ((end % BIT_CHAR) > 0) {
+ mask |= (~(0)) << (end % BIT_CHAR);
+ }
+ cmask = correctedValue << lshift;
+ /*
+ * low bits are cleared because of left-shift and high bits are
+ * already cleared
+ */
+ cmask &= ~mask;
+ int b = fBuffer.get(startByte) & 0xFF;
+ fBuffer.put(startByte, (byte) ((b & mask) | cmask));
+ return;
+ }
+
+ /* head byte */
+ currByte = startByte;
+ cshift = (int) (index % BIT_CHAR);
+ if (cshift > 0) {
+ mask = ~((~0) << cshift);
+ cmask = correctedValue << cshift;
+ cmask &= ~mask;
+ int b = fBuffer.get(currByte) & 0xFF;
+ fBuffer.put(currByte, (byte) ((b & mask) | cmask));
+ correctedValue >>>= BIT_CHAR - cshift;
+ currByte++;
+ }
+
+ /* middle byte(s) */
+ for (; currByte < (endByte - 1); currByte++) {
+ fBuffer.put(currByte, (byte) correctedValue);
+ correctedValue >>>= BIT_CHAR;
+ }
+ /* end byte */
+ if ((end % BIT_CHAR) > 0) {
+ mask = (~0) << (end % BIT_CHAR);
+ cmask = correctedValue & ~mask;
+ int b = fBuffer.get(currByte) & 0xFF;
+ fBuffer.put(currByte, (byte) ((b & mask) | cmask));
+ } else {
+ fBuffer.put(currByte, (byte) correctedValue);
+ }
+ }
+
+ // ------------------------------------------------------------------------
+ // Buffer attributes handling
+ // ------------------------------------------------------------------------
+
+ /**
+ * Can this buffer be read for thus amount of bits?
+ *
+ * @param length
+ * the length in bits to read
+ * @return does the buffer have enough room to read the next "length"
+ */
+ public boolean canRead(int length) {
+ return ((fPosition + length) <= fBitCapacity);
+ }
+
+ /**
+ * Sets the order of the buffer.
+ *
+ * @param order
+ * The order of the buffer.
+ */
+ public void setByteOrder(ByteOrder order) {
+ fByteOrder = order;
+ fBuffer.order(order);
+ }
+
+ /**
+ * Sets the order of the buffer.
+ *
+ * @return The order of the buffer.
+ */
+ public ByteOrder getByteOrder() {
+ return fByteOrder;
+ }
+
+ /**
+ * Sets the position in the buffer.
+ *
+ * @param newPosition
+ * The new position of the buffer.
+ * @throws CTFReaderException
+ * Thrown on out of bounds exceptions
+ * @since 3.0
+ */
+ public void position(long newPosition) throws CTFReaderException {
+
+
+ if (newPosition > fBitCapacity) {
+ throw new CTFReaderException("Out of bounds exception on a position move, attempting to access position: " + newPosition); //$NON-NLS-1$
+ }
+ fPosition = newPosition;
+ }
+
+ /**
+ *
+ * Sets the position in the buffer.
+ *
+ * @return order The position of the buffer.
+ * @since 3.0
+ */
+ public long position() {
+ return fPosition;
+ }
+
+ /**
+ * Sets the byte buffer
+ *
+ * @param buf
+ * the byte buffer
+ */
+ @Deprecated
+ public void setByteBuffer(ByteBuffer buf) {
+ /*
+ * to avoid "The method setByteBuffer(ByteBuffer) from the type
+ * BitBuffer can be declared as static"
+ */
+ long data = fPosition;
+ fPosition = data;
+ throw new UnsupportedOperationException("Bytebuffers are now final"); //$NON-NLS-1$
+
+ }
+
+ /**
+ * Gets the byte buffer
+ *
+ * @return The byte buffer
+ */
+ public ByteBuffer getByteBuffer() {
+ return fBuffer;
+ }
+
+ /**
+ * Resets the bitbuffer.
+ */
+ public void clear() {
+ resetPosition();
+ fBuffer.clear();
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.scope;
+
+import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
+
+/**
+ * A lttng specific speedup node (the packet header with ID and V) of a lexical
+ * scope
+ *
+ * @author Matthew Khouzam
+ * @since 3.1
+ */
+@NonNullByDefault
+public class EventHeaderScope extends LexicalScope {
+
+ /**
+ * Event header id string
+ */
+ public static final LexicalScope EVENT_HEADER_ID = new LexicalScope(EVENT_HEADER, "id"); //$NON-NLS-1$
+
+ /**
+ * Event header v as in variant string
+ */
+ public static final LexicalScope EVENT_HEADER_V = new EventHeaderVScope(EVENT_HEADER, "v"); //$NON-NLS-1$
+
+ /**
+ * The scope constructor
+ *
+ * @param parent
+ * The parent node, can be null, but shouldn't
+ * @param name
+ * the name of the field
+ */
+ public EventHeaderScope(LexicalScope parent, String name) {
+ super(parent, name);
+ }
+
+ @Override
+ @Nullable
+ public LexicalScope getChild(String name) {
+ if (name.equals(EVENT_HEADER_ID.getName())) {
+ return EVENT_HEADER_ID;
+ }
+ if (name.equals(EVENT_HEADER_V.getName())) {
+ return EVENT_HEADER_V;
+ }
+ return super.getChild(name);
+ }
+
+ @Override
+ public String toString() {
+ return "event.header"; //$NON-NLS-1$
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.scope;
+
+import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
+
+/**
+ * A lttng specific speedup node (v variant for event headers) of a lexical
+ * scope they normally contain a timestamp
+ *
+ * @author Matthew Khouzam
+ * @since 3.1
+ */
+@NonNullByDefault
+public class EventHeaderVScope extends LexicalScope {
+
+ /**
+ * Packet header v id string
+ */
+ public static final LexicalScope PACKET_HEADER_V_ID = new LexicalScope(PACKET_HEADER, "id"); //$NON-NLS-1$
+ /**
+ * Packet header v timestamp string
+ */
+ public static final LexicalScope PACKET_HEADER_V_TIMESTAMP = new LexicalScope(PACKET_HEADER, "timestamp"); //$NON-NLS-1$
+
+ /**
+ * The scope constructor
+ *
+ * @param parent
+ * The parent node, can be null, but shouldn't
+ * @param name
+ * the name of the field
+ */
+ public EventHeaderVScope(LexicalScope parent, String name) {
+ super(parent, name);
+ }
+
+ @Override
+ @Nullable
+ public LexicalScope getChild(String name) {
+ if (name.equals(PACKET_HEADER_V_TIMESTAMP.getName())) {
+ return PACKET_HEADER_V_TIMESTAMP;
+ }
+ if (name.equals(PACKET_HEADER_V_ID.getName())) {
+ return PACKET_HEADER_V_ID;
+ }
+ return super.getChild(name);
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.scope;
+
+import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
+
+/**
+ * A lttng specific speedup node field scope of a lexical scope
+ *
+ * @author Matthew Khouzam
+ * @since 3.1
+ */
+@NonNullByDefault
+public class FieldsScope extends LexicalScope {
+
+ /**
+ * ret field
+ */
+ public static final LexicalScope FIELDS_RET = new LexicalScope(FIELDS, "_ret"); //$NON-NLS-1$
+
+ /**
+ * tid field
+ */
+ public static final LexicalScope FIELDS_TID = new LexicalScope(FIELDS, "_tid"); //$NON-NLS-1$
+
+ /**
+ * The scope constructor
+ *
+ * @param parent
+ * The parent node, can be null, but shouldn't
+ * @param name
+ * the name of the field
+ */
+ public FieldsScope(LexicalScope parent, String name) {
+ super(parent, name);
+ }
+
+ @Override
+ @Nullable
+ public LexicalScope getChild(String name) {
+ if (name.equals(FIELDS_RET.getName())) {
+ return FIELDS_RET;
+ }
+ if (name.equals(FIELDS_TID.getName())) {
+ return FIELDS_TID;
+ }
+ return super.getChild(name);
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.scope;
+
+import org.eclipse.tracecompass.ctf.core.event.types.Definition;
+
+/**
+ * The scope of a CTF definition. Used for compound types.
+ *
+ * @version 1.0
+ * @author Matthew Khouzam
+ * @author Simon Marchi
+ * @since 3.0
+ */
+public interface IDefinitionScope {
+
+ /**
+ * Gets the path in a C style for the scope.
+ *
+ * @return the path
+ * @since 3.0
+ */
+ LexicalScope getScopePath();
+
+ /**
+ * Looks up in this definition scope.
+ *
+ * @param lookupPath
+ * The path to look up
+ * @return The Definition that was read
+ */
+ // TODO: change to IDefintion
+ Definition lookupDefinition(String lookupPath);
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.scope;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
+
+import com.google.common.base.Joiner;
+
+/**
+ * A node of a lexical scope
+ *
+ * @author Matthew Khouzam
+ * @since 3.0
+ */
+@NonNullByDefault
+public class LexicalScope implements Comparable<LexicalScope> {
+ /**
+ * Empty string
+ *
+ * @since 3.0
+ */
+ public static final LexicalScope ROOT = new RootScope();
+
+ /**
+ * Trace string
+ *
+ * @since 3.0
+ */
+ public static final LexicalScope TRACE = new LexicalScope(ROOT, "trace"); //$NON-NLS-1$
+
+ /**
+ * Env string
+ *
+ * @since 3.0
+ */
+ public static final LexicalScope ENV = new LexicalScope(ROOT, "env"); //$NON-NLS-1$
+
+ /**
+ * Stream string
+ *
+ * @since 3.0
+ */
+ public static final LexicalScope STREAM = new LexicalScope(ROOT, "stream"); //$NON-NLS-1$
+
+ /**
+ * Event string
+ *
+ * @since 3.0
+ */
+ public static final LexicalScope EVENT = new LexicalScope(ROOT, "event"); //$NON-NLS-1$
+
+ /**
+ * Variant string
+ *
+ * @since 3.0
+ */
+ public static final LexicalScope VARIANT = new LexicalScope(ROOT, "variant"); //$NON-NLS-1$
+
+ /**
+ * packet string
+ *
+ * @since 3.0
+ */
+ public static final LexicalScope PACKET = new LexicalScope(ROOT, "packet"); //$NON-NLS-1$
+
+ /**
+ * Packet header string
+ *
+ * @since 3.0
+ *
+ */
+ public static final LexicalScope PACKET_HEADER = new PacketHeaderScope();
+
+ /**
+ * Stream packet scope
+ *
+ * @since 3.0
+ */
+ public static final LexicalScope STREAM_PACKET = new LexicalScope(STREAM, "packet"); //$NON-NLS-1$
+
+ /**
+ * Stream Packet header string
+ *
+ * @since 3.0
+ */
+ public static final LexicalScope STREAM_PACKET_CONTEXT = new LexicalScope(STREAM_PACKET, "context"); //$NON-NLS-1$
+
+ /**
+ * Trace packet scope
+ *
+ * @since 3.0
+ */
+ public static final LexicalScope TRACE_PACKET = new LexicalScope(TRACE, "packet"); //$NON-NLS-1$
+
+ /**
+ * Stream event scope
+ *
+ * @since 3.0
+ */
+ public static final LexicalScope STREAM_EVENT = new LexicalScope(STREAM, "event"); //$NON-NLS-1$
+
+ /**
+ * Trace packet header string
+ *
+ * @since 3.0
+ */
+ public static final LexicalScope TRACE_PACKET_HEADER = new LexicalScope(TRACE_PACKET, "header"); //$NON-NLS-1$
+
+ /**
+ * Stream event context
+ *
+ * @since 3.0
+ */
+ public static final LexicalScope STREAM_EVENT_CONTEXT = new LexicalScope(STREAM_EVENT, "context"); //$NON-NLS-1$
+
+ /**
+ * Stream event header
+ *
+ * @since 3.0
+ */
+ public static final LexicalScope STREAM_EVENT_HEADER = new LexicalScope(STREAM_EVENT, "header"); //$NON-NLS-1$
+
+ /**
+ * Event header
+ *
+ * @since 3.1
+ */
+ public static final LexicalScope EVENT_HEADER = new EventHeaderScope(EVENT, "header"); //$NON-NLS-1$
+
+ /**
+ * Fields in an event
+ *
+ * @since 3.0
+ */
+ public static final LexicalScope FIELDS = new FieldsScope(ROOT, "fields"); //$NON-NLS-1$
+
+ /**
+ * Context of an event
+ *
+ * @since 3.0
+ */
+ public static final LexicalScope CONTEXT = new LexicalScope(ROOT, "context"); //$NON-NLS-1$
+
+ /**
+ * Sorted list of parent paths
+ *
+ * @since 3.0
+ */
+ public static final LexicalScope[] PARENT_PATHS = {
+ ROOT,
+ CONTEXT,
+ FIELDS,
+ PACKET_HEADER,
+ STREAM_EVENT_CONTEXT,
+ STREAM_EVENT_HEADER,
+ STREAM_PACKET_CONTEXT,
+ TRACE_PACKET_HEADER
+ };
+
+ private int hash = 0;
+ private final String fName;
+ private final String fPath;
+ private final Map<String, LexicalScope> fChildren;
+
+ /**
+ * The scope constructor
+ *
+ * @param parent
+ * The parent node, can be null, but shouldn't
+ * @param name
+ * the name of the field
+ */
+ @SuppressWarnings("null")
+ public LexicalScope(@Nullable LexicalScope parent, String name) {
+ fName = name;
+ if (parent != null) {
+ String pathString = Joiner.on('.').skipNulls().join(parent.fPath, parent.getName());
+ /*
+ * if joiner return null, we get an NPE... so we won't assign fPath
+ * to null
+ */
+ if (pathString.startsWith(".")) { //$NON-NLS-1$
+ /*
+ * substring throws an exception or returns a string, it won't
+ * return null
+ */
+ pathString = pathString.substring(1);
+ }
+ fPath = pathString;
+ parent.addChild(fName, this);
+ } else {
+ fPath = ""; //$NON-NLS-1$
+ }
+ @NonNull
+ Map<String, LexicalScope> children =
+ Collections.synchronizedMap(new HashMap<String, LexicalScope>());
+ fChildren = children;
+ }
+
+ /**
+ * Adds a child lexical scope
+ *
+ * @param name
+ * the name of the child
+ * @param child
+ * the child
+ */
+ private void addChild(String name, LexicalScope child) {
+ fChildren.put(name, child);
+ }
+
+ /**
+ * Get the name
+ *
+ * @return the name
+ */
+ public String getName() {
+ return fName;
+ }
+
+ /**
+ * Gets a child of a given name
+ *
+ * @param name
+ * the child
+ * @return the scope, can be null
+ */
+ @Nullable
+ public LexicalScope getChild(String name) {
+ return fChildren.get(name);
+ }
+
+ @Override
+ public String toString() {
+ return (fPath.isEmpty() ? fName : fPath + '.' + fName);
+ }
+
+ @Override
+ public int compareTo(@Nullable LexicalScope other) {
+ if (other == null) {
+ throw new IllegalArgumentException();
+ }
+ int comp = fPath.compareTo(other.fPath);
+ if (comp == 0) {
+ return fName.compareTo(other.fName);
+ }
+ return comp;
+ }
+
+ @Override
+ public synchronized int hashCode() {
+ if (hash == 0) {
+ final int prime = 31;
+ hash = prime * (prime + fName.hashCode()) + fPath.hashCode();
+ }
+ return hash;
+ }
+
+ @Override
+ public boolean equals(@Nullable Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ LexicalScope other = (LexicalScope) obj;
+ if (!fName.equals(other.fName)) {
+ return false;
+ }
+ return fPath.equals(other.fPath);
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.scope;
+
+import org.eclipse.jdt.annotation.NonNullByDefault;
+
+/**
+ * A lttng specific speedup node (the packet header with magic, uuid and stream
+ * id ) of a lexical scope the sole reason to have this is to accelerate tostring()
+ *
+ * @author Matthew Khouzam
+ * @since 3.1
+ */
+@NonNullByDefault
+public class PacketHeaderScope extends LexicalScope {
+
+ /**
+ * Constructor
+ */
+ public PacketHeaderScope() {
+ super(PACKET, "header"); //$NON-NLS-1$
+ }
+
+ @Override
+ public String toString() {
+ return "packet.header"; //$NON-NLS-1$
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.scope;
+
+import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
+
+/**
+ * A lttng specific speedup node a root with accelerated returns for some scopes
+ * of a lexical scope
+ *
+ * @author Matthew Khouzam
+ * @since 3.1
+ */
+@NonNullByDefault
+public class RootScope extends LexicalScope {
+
+ /**
+ * The scope constructor
+ */
+ public RootScope() {
+ super(null, ""); //$NON-NLS-1$
+ }
+
+ @Override
+ @Nullable
+ public LexicalScope getChild(String name) {
+ /*
+ * This happens ~40 % of the time
+ */
+ if (name.equals(EVENT_HEADER.toString())) {
+ return EVENT_HEADER;
+ }
+ /*
+ * This happens ~30 % of the time
+ */
+ if (name.equals(FIELDS.toString())) {
+ return FIELDS;
+ }
+ /*
+ * This happens ~30 % of the time
+ */
+ if (name.equals(CONTEXT.toString())) {
+ return CONTEXT;
+ }
+ /*
+ * This happens ~1 % of the time
+ */
+ if (name.equals(PACKET_HEADER.toString())) {
+ return PACKET_HEADER;
+ }
+ return super.getChild(name);
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+import java.util.List;
+
+import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+
+/**
+ * Array definition, used for compound definitions and fixed length strings
+ *
+ * @author Matthew Khouzam
+ * @since 3.1
+ */
+@NonNullByDefault
+public abstract class AbstractArrayDefinition extends Definition {
+
+ /**
+ * Constructor
+ *
+ * @param declaration
+ * the event declaration
+ *
+ * @param definitionScope
+ * the definition is in a scope, (normally a struct) what is it?
+ * @param fieldName
+ * the name of the definition. (it is a field in the parent
+ * scope)
+ */
+ public AbstractArrayDefinition(IDeclaration declaration, @Nullable IDefinitionScope definitionScope, String fieldName) {
+ super(declaration, definitionScope, fieldName);
+ }
+
+ /**
+ * Get the defintions, an array is a collection of definitions
+ *
+ * @return the definitions
+ */
+ public abstract List<Definition> getDefinitions();
+
+}
\ No newline at end of file
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+import java.util.List;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+
+import com.google.common.collect.ArrayListMultimap;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableList.Builder;
+import com.google.common.collect.Multimap;
+
+/**
+ * A CTF array declaration
+ *
+ * Arrays are fixed-length. Their length is declared in the type declaration
+ * within the meta-data. They contain an array of "inner type" elements, which
+ * can refer to any type not containing the type of the array being declared (no
+ * circular dependency). The length is the number of elements in an array.
+ *
+ * @deprecated use
+ * {@link org.eclipse.tracecompass.internal.ctf.core.event.types.ArrayDeclaration}
+ * @version 1.0
+ * @author Matthew Khouzam
+ * @author Simon Marchi
+ */
+@Deprecated
+public class ArrayDeclaration extends CompoundDeclaration {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ private final int fLength;
+ private final IDeclaration fElemType;
+
+ /**
+ * <pre>
+ * Cache where we can pre-generate the children names
+ * Key: parent name
+ * Value: children names
+ * ex: field → {field[0], field[1], … field[n]}
+ * </pre>
+ *
+ * TODO: investigate performance
+ */
+ private final Multimap<String, String> fChildrenNames = ArrayListMultimap.<String, String> create();
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructor
+ *
+ * @param length
+ * how many elements in the array
+ * @param elemType
+ * what type of element is in the array
+ */
+ public ArrayDeclaration(int length, IDeclaration elemType) {
+ fLength = length;
+ fElemType = elemType;
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ @Override
+ public IDeclaration getElementType() {
+ return fElemType;
+ }
+
+ /**
+ *
+ * @return how many elements in the array
+ */
+ public int getLength() {
+ return fLength;
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ /**
+ * @since 3.0
+ */
+ @Deprecated
+ @Override
+ public ArrayDefinition createDefinition(IDefinitionScope definitionScope,
+ @NonNull String fieldName, BitBuffer input) throws CTFReaderException {
+ alignRead(input);
+ List<Definition> definitions = read(input, definitionScope, fieldName);
+ return new ArrayDefinition(this, definitionScope, fieldName, definitions);
+ }
+
+ @Override
+ public String toString() {
+ /* Only used for debugging */
+ return "[declaration] array[" + Integer.toHexString(hashCode()) + ']'; //$NON-NLS-1$
+ }
+
+ @NonNull
+ private List<Definition> read(@NonNull BitBuffer input, IDefinitionScope definitionScope, String fieldName) throws CTFReaderException {
+ Builder<Definition> definitions = new ImmutableList.Builder<>();
+ if (!fChildrenNames.containsKey(fieldName)) {
+ for (int i = 0; i < fLength; i++) {
+ fChildrenNames.put(fieldName, fieldName + '[' + i + ']');
+ }
+ }
+ List<String> elemNames = (List<String>) fChildrenNames.get(fieldName);
+ for (int i = 0; i < fLength; i++) {
+ String name = elemNames.get(i);
+ if (name == null) {
+ throw new IllegalStateException();
+ }
+ definitions.add(fElemType.createDefinition(definitionScope, name, input));
+ }
+ @SuppressWarnings("null")
+ @NonNull ImmutableList<Definition> ret = definitions.build();
+ return ret;
+ }
+
+ /**
+ * @since 3.0
+ */
+ @Override
+ public int getMaximumSize() {
+ long val = (long) fLength * fElemType.getMaximumSize();
+ return (int) Math.min(Integer.MAX_VALUE, val);
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+import java.util.List;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+
+import com.google.common.base.Joiner;
+import com.google.common.collect.ImmutableList;
+
+/**
+ * A CTF array definition
+ *
+ * Arrays are fixed-length. Their length is declared in the type declaration
+ * within the meta-data. They contain an array of "inner type" elements, which
+ * can refer to any type not containing the type of the array being declared (no
+ * circular dependency). The length is the number of elements in an array.
+ *
+ * @deprecated use {@link AbstractArrayDefinition}
+ * @version 1.0
+ * @author Matthew Khouzam
+ * @author Simon Marchi
+ */
+@NonNullByDefault
+@Deprecated
+public final class ArrayDefinition extends AbstractArrayDefinition{
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ private final ImmutableList<Definition> fDefinitions;
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructor
+ *
+ * @param declaration
+ * the parent declaration
+ * @param definitionScope
+ * the parent scope
+ * @param fieldName
+ * the field name
+ * @param definitions
+ * the content of the array
+ * @since 3.0
+ */
+ public ArrayDefinition(ArrayDeclaration declaration,
+ @Nullable IDefinitionScope definitionScope,
+ String fieldName,
+ List<Definition> definitions) {
+ super(declaration, definitionScope, fieldName);
+ @SuppressWarnings("null")
+ @NonNull ImmutableList<Definition> list = ImmutableList.copyOf(definitions);
+ fDefinitions = list;
+
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ @Override
+ public List<Definition> getDefinitions() {
+ return fDefinitions;
+ }
+
+ /**
+ * Get the element at i
+ *
+ * @param i the index (cannot be negative)
+ * @return The element at I, if I > length, null, if I < 0, the method throws an out of bounds exception
+ */
+ @Nullable
+ public Definition getElem(int i) {
+ if (i > fDefinitions.size()) {
+ return null;
+ }
+
+ return fDefinitions.get(i);
+ }
+
+ @Override
+ public ArrayDeclaration getDeclaration() {
+ return (ArrayDeclaration) super.getDeclaration();
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ @Override
+ public String toString() {
+ StringBuilder b = new StringBuilder();
+
+ if (getDeclaration().isString()) {
+ for (Definition def : fDefinitions) {
+ IntegerDefinition character = (IntegerDefinition) def;
+
+ if (character.getValue() == 0) {
+ break;
+ }
+
+ b.append(character.toString());
+ }
+ } else {
+ b.append('[');
+ Joiner joiner = Joiner.on(", ").skipNulls(); //$NON-NLS-1$
+ b.append(joiner.join(fDefinitions));
+ b.append(']');
+ }
+
+ @SuppressWarnings("null")
+ @NonNull String ret = b.toString();
+ return ret;
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+
+/**
+ * Parent of sequences and arrays
+ *
+ * @author Matthew Khouzam
+ * @since 3.1
+ */
+public abstract class CompoundDeclaration extends Declaration {
+
+ /**
+ * Get the element type
+ *
+ * @return the type of element in the array
+ */
+ public abstract IDeclaration getElementType();
+
+ @Override
+ public long getAlignment() {
+ return getElementType().getAlignment();
+ }
+
+ /**
+ * Sometimes, strings are encoded as an array of 1-byte integers (each one
+ * being an UTF-8 byte).
+ *
+ * @return true if this array is in fact an UTF-8 string. false if it's a
+ * "normal" array of generic Definition's.
+ */
+ public boolean isString(){
+ IDeclaration elementType = getElementType();
+ if (elementType instanceof IntegerDeclaration) {
+ IntegerDeclaration elemInt = (IntegerDeclaration) elementType;
+ return elemInt.isCharacter();
+ }
+ return false;
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.event.scope.LexicalScope;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+
+/**
+ * Declaration base, it helps for basic functionality that is often called, so
+ * performance is often a high priority in this class
+ *
+ * @author Matthew Khouzam
+ * @since 3.0
+ */
+public abstract class Declaration implements IDeclaration {
+
+ @Override
+ public LexicalScope getPath(IDefinitionScope definitionScope, @NonNull String fieldName) {
+ if (definitionScope != null) {
+ final LexicalScope parentPath = definitionScope.getScopePath();
+ if (parentPath != null) {
+ LexicalScope myScope = parentPath.getChild(fieldName);
+ if (myScope == null) {
+ myScope = new LexicalScope(parentPath, fieldName);
+ }
+ return myScope;
+ }
+ }
+ LexicalScope child = LexicalScope.ROOT.getChild(fieldName);
+ if (child != null) {
+ return child;
+ }
+ return new LexicalScope(LexicalScope.ROOT, fieldName);
+ }
+
+ /**
+ * Offset the buffer position wrt the current alignment.
+ *
+ * @param input
+ * The bitbuffer that is being read
+ * @throws CTFReaderException
+ * Happens when there is an out of bounds exception
+ * @since 3.0
+ */
+ protected final void alignRead(BitBuffer input) throws CTFReaderException {
+ long mask = getAlignment() - 1;
+ /*
+ * The alignment is a power of 2
+ */
+ long pos = input.position();
+ if ((pos & mask) == 0) {
+ return;
+ }
+ pos = (pos + mask) & ~mask;
+ input.position(pos);
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.event.scope.LexicalScope;
+
+/**
+ * A CTF definition
+ *
+ * A definition is like an object of a declaration class. It fills the
+ * declaration with values. <br>
+ * An example: <br>
+ * int i = 0; <br>
+ * <b>int</b> is the declaration.<br>
+ * <b>i</b> is the definition.<br>
+ * <b>0</b> is the value assigned to the definition, not the declaration.<br>
+ *
+ * @version 1.0
+ * @author Matthew Khouzam
+ * @author Simon Marchi
+ */
+public abstract class Definition implements IDefinition {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ private final String fFieldName;
+
+ /** The complete path of this field */
+ private final @NonNull LexicalScope fPath;
+
+ private final IDefinitionScope fDefinitionScope;
+
+ @NonNull
+ private final IDeclaration fDeclaration;
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructor
+ *
+ * @param declaration
+ * the event declaration
+ * @param definitionScope
+ * the definition is in a scope, (normally a struct) what is it?
+ * @param fieldName
+ * the name of the definition. (it is a field in the parent
+ * scope)
+ * @since 3.0
+ */
+ public Definition(@NonNull IDeclaration declaration, IDefinitionScope definitionScope, @NonNull String fieldName) {
+ this(declaration, definitionScope, fieldName, declaration.getPath(definitionScope, fieldName));
+ }
+
+ /**
+ * Constructor This one takes the scope and thus speeds up definition
+ * creation
+ *
+ *
+ * @param declaration
+ * the event declaration
+ *
+ * @param definitionScope
+ * the definition is in a scope, (normally a struct) what is it?
+ *
+ * @param fieldName
+ * the name of the defintions. it is a field in the parent scope.
+ *
+ * @param scope
+ * the scope
+ * @since 3.1
+ */
+ public Definition(@NonNull IDeclaration declaration, IDefinitionScope definitionScope, @NonNull String fieldName, @NonNull LexicalScope scope) {
+ fDeclaration = declaration;
+ fDefinitionScope = definitionScope;
+ fFieldName = fieldName;
+ fPath = scope;
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters
+ // ------------------------------------------------------------------------
+
+ /**
+ * Get the field name in its container.
+ *
+ * @return The field name
+ * @since 2.0
+ */
+ protected String getFieldName() {
+ return fFieldName;
+ }
+
+ @Override
+ public LexicalScope getScopePath() {
+ return fPath;
+ }
+
+ /**
+ * Get the definition scope in which this definition is found.
+ *
+ * The complete path of a definition is thus the path of the definition
+ * scope DOT the name of the definition (name of the field in its container)
+ *
+ * @return The definition scope
+ * @since 3.0
+ */
+ protected IDefinitionScope getDefinitionScope() {
+ return fDefinitionScope;
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ @Override
+ public IDeclaration getDeclaration() {
+ return fDeclaration;
+ }
+
+ @Override
+ public String toString() {
+ return fPath.toString() + '[' + Integer.toHexString(hashCode()) + ']';
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011-2012 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+import org.eclipse.jdt.annotation.NonNullByDefault;
+
+/**
+ * CTF encoding types
+ *
+ * @version 1.0
+ * @author Matthew Khouzam
+ * @author Simon Marchi
+ */
+@NonNullByDefault
+public enum Encoding {
+ /** UTF-8 encoding */
+ UTF8,
+ /** Ascii encoding */
+ ASCII,
+ /** No encoding, maybe not even text */
+ NONE
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
+
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+
+/**
+ * A CTF enum declaration.
+ *
+ * The definition of a enum point basic data type. It will take the data from a
+ * trace and store it (and make it fit) as an integer and a string.
+ *
+ * @version 1.0
+ * @author Matthew Khouzam
+ * @author Simon Marchi
+ */
+public final class EnumDeclaration extends Declaration implements ISimpleDatatypeDeclaration {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ private final EnumTable fTable = new EnumTable();
+ private final IntegerDeclaration fContainerType;
+ private final Set<String> fLabels = new HashSet<>();
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * constructor
+ *
+ * @param containerType
+ * the enum is an int, this is the type that the data is
+ * contained in. If you have 1000 possible values, you need at
+ * least a 10 bit enum. If you store 2 values in a 128 bit int,
+ * you are wasting space.
+ */
+ public EnumDeclaration(IntegerDeclaration containerType) {
+ fContainerType = containerType;
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ /**
+ *
+ * @return The container type
+ */
+ public IntegerDeclaration getContainerType() {
+ return fContainerType;
+ }
+
+ @Override
+ public long getAlignment() {
+ return this.getContainerType().getAlignment();
+ }
+
+ /**
+ * @since 3.0
+ */
+ @Override
+ public int getMaximumSize() {
+ return fContainerType.getMaximumSize();
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ /**
+ * @since 3.0
+ */
+ @Override
+ public EnumDefinition createDefinition(IDefinitionScope definitionScope, String fieldName, BitBuffer input) throws CTFReaderException {
+ alignRead(input);
+ IntegerDefinition value = getContainerType().createDefinition(definitionScope, fieldName, input);
+ return new EnumDefinition(this, definitionScope, fieldName, value);
+ }
+
+ /**
+ * Add a value. Do not overlap, this is <em><strong>not</strong></em> an
+ * interval tree.
+ *
+ * @param low
+ * lowest value that this int can be to have label as a return
+ * string
+ * @param high
+ * highest value that this int can be to have label as a return
+ * string
+ * @param label
+ * the name of the value.
+ * @return was the value be added? true == success
+ */
+ public boolean add(long low, long high, String label) {
+ fLabels.add(label);
+ return fTable.add(low, high, label);
+ }
+
+ /**
+ * Check if the label for a value (enum a{day=0,night=1} would return "day"
+ * for query(0)
+ *
+ * @param value
+ * the value to lookup
+ * @return the label of that value, can be null
+ */
+ public String query(long value) {
+ return fTable.query(value);
+ }
+
+ /**
+ * Gets a set of labels of the enum
+ *
+ * @return A set of labels of the enum, can be empty but not null
+ * @since 3.0
+ */
+ public Set<String> getLabels() {
+ return Collections.unmodifiableSet(fLabels);
+ }
+
+ /*
+ * Maps integer range -> string. A simple list for now, but feel free to
+ * optimize it. Babeltrace suggests an interval tree.
+ */
+ private class EnumTable {
+
+ private final List<LabelAndRange> ranges = new LinkedList<>();
+
+ public EnumTable() {
+ }
+
+ public boolean add(long low, long high, String label) {
+ LabelAndRange newRange = new LabelAndRange(low, high, label);
+
+ for (LabelAndRange r : ranges) {
+ if (r.intersects(newRange)) {
+ return false;
+ }
+ }
+
+ ranges.add(newRange);
+
+ return true;
+ }
+
+ /**
+ * Return the first label that matches a value
+ *
+ * @param value
+ * the value to query
+ * @return the label corresponding to that value
+ */
+ public String query(long value) {
+ for (LabelAndRange r : ranges) {
+ if (r.intersects(value)) {
+ return r.getLabel();
+ }
+ }
+ return null;
+ }
+
+ }
+
+ private static class LabelAndRange {
+
+ private final long low, high;
+ private final String fLabel;
+
+ /**
+ * Get the label
+ *
+ * @return the label
+ */
+ public String getLabel() {
+ return fLabel;
+ }
+
+ public LabelAndRange(long low, long high, String str) {
+ this.low = low;
+ this.high = high;
+ this.fLabel = str;
+ }
+
+ public boolean intersects(long i) {
+ return (i >= this.low) && (i <= this.high);
+ }
+
+ public boolean intersects(LabelAndRange other) {
+ return this.intersects(other.low)
+ || this.intersects(other.high);
+ }
+ }
+
+ @Override
+ public String toString() {
+ /* Only used for debugging */
+ return "[declaration] enum[" + Integer.toHexString(hashCode()) + ']'; //$NON-NLS-1$
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+
+/**
+ * A CTF enum definition.
+ *
+ * The definition of a enum point basic data type. It will take the data from a
+ * trace and store it (and make it fit) as an integer and a string.
+ *
+ * @version 1.0
+ * @author Matthew Khouzam
+ * @author Simon Marchi
+ */
+public final class EnumDefinition extends SimpleDatatypeDefinition {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ private final long fIntegerValue;
+
+ private final String fValue;
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructor
+ *
+ * @param declaration
+ * the parent declaration
+ * @param definitionScope
+ * the parent scope
+ * @param fieldName
+ * the field name
+ * @param intValue
+ * the value of the enum
+ * @since 3.0
+ */
+ public EnumDefinition(@NonNull EnumDeclaration declaration,
+ IDefinitionScope definitionScope, @NonNull String fieldName, IntegerDefinition intValue) {
+ super(declaration, definitionScope, fieldName);
+
+ fIntegerValue = intValue.getValue();
+ fValue = declaration.query(fIntegerValue);
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ /**
+ * Gets the value of the enum in string format so
+ * "Enum a{DAY="0", NIGHT="1"}; will return "DAY"
+ *
+ * @return the value of the enum.
+ */
+ public String getValue() {
+ return fValue;
+ }
+
+ @Override
+ public String getStringValue() {
+ return getValue();
+ }
+
+ /**
+ * Gets the value of the enum in string format so
+ * "Enum a{DAY="0", NIGHT="1"}; will return 0
+ *
+ * @return the value of the enum.
+ */
+ @Override
+ public Long getIntegerValue() {
+ return fIntegerValue;
+ }
+
+ @Override
+ public EnumDeclaration getDeclaration() {
+ return (EnumDeclaration) super.getDeclaration();
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ @Override
+ public String toString() {
+ return "{ value = " + getValue() + //$NON-NLS-1$
+ ", container = " + fIntegerValue + //$NON-NLS-1$
+ " }"; //$NON-NLS-1$
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+import java.nio.ByteOrder;
+
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+
+/**
+ * A CTF float declaration.
+ *
+ * The declaration of a floating point basic data type.
+ *
+ * @version 1.0
+ * @author Matthew Khouzam
+ */
+public final class FloatDeclaration extends Declaration implements ISimpleDatatypeDeclaration {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ private final int fMantissa;
+ private final int fExponent;
+ private final ByteOrder fByteOrder;
+ private final long fAlignement;
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructor
+ *
+ * @param exponent
+ * The exponent size in bits
+ * @param mantissa
+ * The mantissa size in bits (+1 for sign) (see CTF spec)
+ * @param byteOrder
+ * The byte order
+ * @param alignment
+ * The alignment. Should be ≥ 1
+ */
+ public FloatDeclaration(int exponent, int mantissa, ByteOrder byteOrder,
+ long alignment) {
+ fMantissa = mantissa;
+ fExponent = exponent;
+ fByteOrder = byteOrder;
+ fAlignement = Math.max(alignment, 1);
+
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ /**
+ * @return the mant
+ */
+ public int getMantissa() {
+ return fMantissa;
+ }
+
+ /**
+ * @return the exp
+ */
+ public int getExponent() {
+ return fExponent;
+ }
+
+ /**
+ * @return the byteOrder
+ */
+ public ByteOrder getByteOrder() {
+ return fByteOrder;
+ }
+
+ @Override
+ public long getAlignment() {
+ return fAlignement;
+ }
+
+ /**
+ * @since 3.0
+ */
+ @Override
+ public int getMaximumSize() {
+ return fMantissa + fExponent + 1;
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ /**
+ * @since 3.0
+ */
+ @Override
+ public FloatDefinition createDefinition(IDefinitionScope definitionScope,
+ String fieldName, BitBuffer input) throws CTFReaderException {
+ ByteOrder byteOrder = input.getByteOrder();
+ input.setByteOrder(fByteOrder);
+ double value = read(input);
+ input.setByteOrder(byteOrder);
+ return new FloatDefinition(this, definitionScope, fieldName, value);
+ }
+
+ @Override
+ public String toString() {
+ /* Only used for debugging */
+ return "[declaration] float[" + Integer.toHexString(hashCode()) + ']'; //$NON-NLS-1$
+ }
+
+ private double read(BitBuffer input) throws CTFReaderException {
+ /* Offset the buffer position wrt the current alignment */
+ alignRead(input);
+ final int exp = getExponent();
+ final int mant = getMantissa();
+ double value = Double.NaN;
+ if ((exp + mant) == 32) {
+ value = readRawFloat32(input, mant, exp);
+ } else if ((exp + mant) == 64) {
+ value = readRawFloat64(input, mant, exp);
+ }
+ return value;
+ }
+
+ private static double readRawFloat32(BitBuffer input, final int manBits,
+ final int expBits) throws CTFReaderException {
+ long temp = input.get(32, false);
+ return createFloat(temp, manBits - 1, expBits);
+ }
+
+ private static double readRawFloat64(BitBuffer input, final int manBits,
+ final int expBits) throws CTFReaderException {
+ long temp = input.get(64, false);
+ return createFloat(temp, manBits - 1, expBits);
+ }
+
+ /**
+ * Create a float from the raw value, Mathematicians beware.
+ *
+ * @param rawValue
+ * The raw value( up to 64 bits)
+ * @param manBits
+ * number of bits in the mantissa
+ * @param expBits
+ * number of bits in the exponent
+ */
+ private static double createFloat(long rawValue, final int manBits,
+ final int expBits) {
+ long manShift = 1L << (manBits);
+ long manMask = manShift - 1;
+ long expMask = (1L << expBits) - 1;
+
+ int exp = (int) ((rawValue >> (manBits)) & expMask) + 1;
+ long man = (rawValue & manMask);
+ final int offsetExponent = exp - (1 << (expBits - 1));
+ double expPow = Math.pow(2.0, offsetExponent);
+ double ret = man * 1.0f;
+ ret /= manShift;
+ ret += 1.0;
+ ret *= expPow;
+ return ret;
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+
+/**
+ * A CTF float definition.
+ *
+ * The definition of a floating point basic data type. It will take the data
+ * from a trace and store it (and make it fit) as a double.
+ *
+ * @version 1.0
+ * @author Matthew Khouzam
+ * @author Simon Marchi
+ */
+public final class FloatDefinition extends Definition {
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ private final double fValue;
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructor
+ *
+ * @param declaration
+ * the parent declaration
+ * @param definitionScope
+ * the parent scope
+ * @param fieldName
+ * the field name
+ * @param value
+ * field value
+ * @since 3.0
+ */
+ public FloatDefinition(@NonNull FloatDeclaration declaration,
+ IDefinitionScope definitionScope, @NonNull String fieldName, double value) {
+ super(declaration, definitionScope, fieldName);
+ fValue = value;
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ /**
+ * The value of a float stored, fit into a double. This should be extended
+ * for exotic floats if this is necessary.
+ *
+ * @return the value of the float field fit into a double.
+ */
+ public double getValue() {
+ return fValue;
+ }
+
+ @Override
+ public FloatDeclaration getDeclaration() {
+ return (FloatDeclaration) super.getDeclaration();
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ @Override
+ public String toString() {
+ return String.valueOf(fValue);
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+import java.util.List;
+
+/**
+ * Interface for data definitions containing heterogenous definitions
+ * (subfields)
+ *
+ * @author Matthew Khouzam
+ * @since 3.1
+ */
+public interface ICompositeDefinition extends IDefinition {
+
+ /**
+ * Gets the definition of the field
+ *
+ * @param fieldName
+ * the fieldname
+ * @return The definitions of all the fields
+ */
+ Definition getDefinition(String fieldName);
+
+ /**
+ * Gets an array of the field names
+ *
+ * @return the field names array
+ */
+ List<String> getFieldNames();
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.event.scope.LexicalScope;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+
+/**
+ * A CTF data type declaration.
+ *
+ * An example: <br>
+ * int i = 0; <br>
+ * <b>int</b> is the declaration.<br>
+ * <b>i</b> is the definition.<br>
+ * <b>0</b> is the value assigned to the definition, not the declaration.<br>
+ *
+ * @version 1.0
+ * @author Matthew Khouzam
+ * @author Simon Marchi
+ */
+public interface IDeclaration {
+
+ /**
+ * Create a definition from this declaration
+ *
+ * @param definitionScope
+ * the definition scope, the parent where the definition will be
+ * placed
+ * @param fieldName
+ * the name of the definition
+ * @param input
+ * a bitbuffer to read from
+ * @return a reference to the definition
+ * @throws CTFReaderException
+ * error in reading
+ * @since 3.0
+ */
+ Definition createDefinition(IDefinitionScope definitionScope, @NonNull String fieldName, @NonNull BitBuffer input) throws CTFReaderException;
+
+ /**
+ * Get the path of a definition
+ *
+ * @param definitionScope
+ * the scope of the definition
+ * @param fieldName
+ * the name of the definition
+ * @return the path of the definition
+ * @since 3.0
+ */
+ public @NonNull LexicalScope getPath(IDefinitionScope definitionScope, @NonNull String fieldName);
+
+ /**
+ * The minimum alignment. if the field is 32 bits, the definition will pad
+ * all the data up to (position%32==0)
+ *
+ * @return the alignment in bits
+ */
+ long getAlignment();
+
+ /**
+ * The MAXIMUM size of this declaration
+ *
+ * @return the maximum size
+ * @since 3.0
+ */
+ int getMaximumSize();
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.tracecompass.ctf.core.event.scope.LexicalScope;
+
+/**
+ * Interface for data definitions. A definition is when a value is given to a
+ * declaration
+ *
+ * @author Matthew Khouzam
+ * @since 3.1
+ */
+@NonNullByDefault
+public interface IDefinition {
+
+ /**
+ * Get the complete path of this field.
+ *
+ * @return The path
+ */
+ LexicalScope getScopePath();
+
+ /**
+ * Get the declaration of this definition
+ *
+ * @return the declaration of a datatype
+ */
+ IDeclaration getDeclaration();
+
+}
\ No newline at end of file
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+import org.eclipse.jdt.annotation.NonNullByDefault;
+
+/**
+ * Event header declaration abstract class
+ *
+ * @author Matthew Khouzam
+ * @since 3.1
+ */
+@NonNullByDefault
+public interface IEventHeaderDeclaration extends IDeclaration {
+ /**
+ * The id of an event
+ */
+ String ID = "id"; //$NON-NLS-1$
+ /**
+ * The name of a timestamp field
+ */
+ String TIMESTAMP = "timestamp"; //$NON-NLS-1$
+ /**
+ * Extended header
+ */
+ String EXTENDED = "extended"; //$NON-NLS-1$
+ /**
+ * Compact header (not to be confused with compact vs large)
+ */
+ String COMPACT = "compact"; //$NON-NLS-1$
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+/**
+ * Common interface for simple CTF data types (which do not contain sub-fields).
+ *
+ * @author Matthew Khouzam
+ * @since 3.1
+ */
+public interface ISimpleDatatypeDeclaration {
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ * Simon Marchi - Initial API and implementation
+ * Marc-Andre Laperle - Add min/maximum for validation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+import java.math.BigInteger;
+import java.nio.ByteOrder;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+
+/**
+ * A CTF integer declaration.
+ *
+ * The declaration of a integer basic data type.
+ *
+ * @version 1.0
+ * @author Matthew Khouzam
+ * @author Simon Marchi
+ */
+@NonNullByDefault
+public class IntegerDeclaration extends Declaration implements ISimpleDatatypeDeclaration {
+
+ // ------------------------------------------------------------------------
+ // Helpers
+ // ------------------------------------------------------------------------
+
+ /**
+ * unsigned int 32 bits big endian
+ *
+ * @since 3.0
+ */
+ public static final IntegerDeclaration UINT_32B_DECL = new IntegerDeclaration(32, false, ByteOrder.BIG_ENDIAN);
+ /**
+ * unsigned int 32 bits little endian
+ *
+ * @since 3.0
+ */
+ public static final IntegerDeclaration UINT_32L_DECL = new IntegerDeclaration(32, false, ByteOrder.LITTLE_ENDIAN);
+ /**
+ * signed int 32 bits big endian
+ *
+ * @since 3.0
+ */
+ public static final IntegerDeclaration INT_32B_DECL = new IntegerDeclaration(32, true, ByteOrder.BIG_ENDIAN);
+ /**
+ * signed int 32 bits little endian
+ *
+ * @since 3.0
+ */
+ public static final IntegerDeclaration INT_32L_DECL = new IntegerDeclaration(32, true, ByteOrder.LITTLE_ENDIAN);
+ /**
+ * unsigned int 32 bits big endian
+ *
+ * @since 3.0
+ */
+ public static final IntegerDeclaration UINT_64B_DECL = new IntegerDeclaration(64, false, ByteOrder.BIG_ENDIAN);
+ /**
+ * unsigned int 64 bits little endian
+ *
+ * @since 3.0
+ */
+ public static final IntegerDeclaration UINT_64L_DECL = new IntegerDeclaration(64, false, ByteOrder.LITTLE_ENDIAN);
+ /**
+ * signed int 64 bits big endian
+ *
+ * @since 3.0
+ */
+ public static final IntegerDeclaration INT_64B_DECL = new IntegerDeclaration(64, true, ByteOrder.BIG_ENDIAN);
+ /**
+ * signed int 64 bits little endian
+ *
+ * @since 3.0
+ */
+ public static final IntegerDeclaration INT_64L_DECL = new IntegerDeclaration(64, true, ByteOrder.LITTLE_ENDIAN);
+ /**
+ * unsigned 8 bit int endianness doesn't matter since it's 8 bits (byte)
+ *
+ * @since 3.0
+ */
+ public static final IntegerDeclaration UINT_8_DECL = new IntegerDeclaration(8, false, ByteOrder.BIG_ENDIAN);
+ /**
+ * signed 8 bit int endianness doesn't matter since it's 8 bits (char)
+ *
+ * @since 3.0
+ */
+ public static final IntegerDeclaration INT_8_DECL = new IntegerDeclaration(8, true, ByteOrder.BIG_ENDIAN);
+ /**
+ * Unsigned 5 bit int, used for event headers
+ *
+ * @since 3.1
+ */
+ public static final IntegerDeclaration UINT_5B_DECL = new IntegerDeclaration(5, false, ByteOrder.BIG_ENDIAN);
+ /**
+ * Unsigned 5 bit int, used for event headers
+ *
+ * @since 3.1
+ */
+ public static final IntegerDeclaration UINT_5L_DECL = new IntegerDeclaration(5, false, ByteOrder.LITTLE_ENDIAN);
+ /**
+ * Unsigned 5 bit int, used for event headers
+ *
+ * @since 3.1
+ */
+ public static final IntegerDeclaration UINT_27B_DECL = new IntegerDeclaration(27, false, ByteOrder.BIG_ENDIAN);
+ /**
+ * Unsigned 5 bit int, used for event headers
+ *
+ * @since 3.1
+ */
+ public static final IntegerDeclaration UINT_27L_DECL = new IntegerDeclaration(27, false, ByteOrder.LITTLE_ENDIAN);
+ /**
+ * Unsigned 16 bit int, used for event headers
+ *
+ * @since 3.1
+ */
+ public static final IntegerDeclaration UINT_16B_DECL = new IntegerDeclaration(16, false, ByteOrder.BIG_ENDIAN);
+ /**
+ * Unsigned 16 bit int, used for event headers
+ *
+ * @since 3.1
+ */
+ public static final IntegerDeclaration UINT_16L_DECL = new IntegerDeclaration(16, false, ByteOrder.LITTLE_ENDIAN);
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ private final int fLength;
+ private final boolean fSigned;
+ private final int fBase;
+ private final ByteOrder fByteOrder;
+ private final Encoding fEncoding;
+ private final long fAlignment;
+ private final String fClock;
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Factory, some common types cached
+ *
+ * @param len
+ * The length in bits
+ * @param signed
+ * Is the integer signed? false == unsigned
+ * @param base
+ * The base (10-16 are most common)
+ * @param byteOrder
+ * Big-endian little-endian or other
+ * @param encoding
+ * ascii, utf8 or none.
+ * @param clock
+ * The clock path, can be null
+ * @param alignment
+ * The minimum alignment. Should be >= 1
+ * @return the integer declaration
+ * @since 3.0
+ */
+ public static IntegerDeclaration createDeclaration(int len, boolean signed, int base,
+ @Nullable ByteOrder byteOrder, Encoding encoding, String clock, long alignment) {
+ if (encoding.equals(Encoding.NONE) && (alignment == 8) && (clock.equals("")) && base == 10) { //$NON-NLS-1$
+ switch (len) {
+ case 5:
+ if (!signed) {
+ if (byteOrder != null && byteOrder.equals(ByteOrder.BIG_ENDIAN)) {
+ return UINT_5B_DECL;
+ }
+ return UINT_5L_DECL;
+ }
+ break;
+ case 8:
+ return signed ? INT_8_DECL : UINT_8_DECL;
+ case 16:
+ if (!signed) {
+ if (byteOrder != null && byteOrder.equals(ByteOrder.BIG_ENDIAN)) {
+ return UINT_16B_DECL;
+ }
+ return UINT_16L_DECL;
+ }
+ break;
+ case 27:
+ if (!signed) {
+ if (byteOrder != null && byteOrder.equals(ByteOrder.BIG_ENDIAN)) {
+ return UINT_27B_DECL;
+ }
+ return UINT_27L_DECL;
+ }
+ break;
+ case 32:
+ if (signed) {
+ if (byteOrder != null && byteOrder.equals(ByteOrder.BIG_ENDIAN)) {
+ return INT_32B_DECL;
+ }
+ return INT_32L_DECL;
+ }
+ if (byteOrder != null && byteOrder.equals(ByteOrder.BIG_ENDIAN)) {
+ return UINT_32B_DECL;
+ }
+ return UINT_32L_DECL;
+ case 64:
+ if (signed) {
+ if (byteOrder != null && byteOrder.equals(ByteOrder.BIG_ENDIAN)) {
+ return INT_64B_DECL;
+ }
+ return INT_64L_DECL;
+ }
+ if (byteOrder != null && byteOrder.equals(ByteOrder.BIG_ENDIAN)) {
+ return UINT_64B_DECL;
+ }
+ return UINT_64L_DECL;
+ default:
+ }
+ }
+ return new IntegerDeclaration(len, signed, base, byteOrder, encoding, clock, alignment);
+ }
+
+ /**
+ * Constructor
+ *
+ * @param len
+ * The length in bits
+ * @param signed
+ * Is the integer signed? false == unsigned
+ * @param base
+ * The base (10-16 are most common)
+ * @param byteOrder
+ * Big-endian little-endian or other
+ * @param encoding
+ * ascii, utf8 or none.
+ * @param clock
+ * The clock path, can be null
+ * @param alignment
+ * The minimum alignment. Should be ≥ 1
+ */
+ private IntegerDeclaration(int len, boolean signed, int base,
+ @Nullable ByteOrder byteOrder, Encoding encoding, String clock, long alignment) {
+ if (len <= 0 || len == 1 && signed) {
+ throw new IllegalArgumentException();
+ }
+
+ fLength = len;
+ fSigned = signed;
+ fBase = base;
+
+ @SuppressWarnings("null")
+ @NonNull
+ ByteOrder actualByteOrder = (byteOrder == null ? ByteOrder.nativeOrder() : byteOrder);
+ fByteOrder = actualByteOrder;
+
+ fEncoding = encoding;
+ fClock = clock;
+ fAlignment = Math.max(alignment, 1);
+ }
+
+ private IntegerDeclaration(int len, boolean signed, @Nullable ByteOrder byteOrder) {
+ this(len, signed, 10, byteOrder, Encoding.NONE, "", 8); //$NON-NLS-1$
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ /**
+ * Is the integer signed?
+ *
+ * @return the is the integer signed
+ */
+ public boolean isSigned() {
+ return fSigned;
+ }
+
+ /**
+ * Get the integer base commonly decimal or hex
+ *
+ * @return the integer base
+ */
+ public int getBase() {
+ return fBase;
+ }
+
+ /**
+ * Get the byte order
+ *
+ * @return the byte order
+ */
+ public ByteOrder getByteOrder() {
+ return fByteOrder;
+ }
+
+ /**
+ * Get encoding, chars are 8 bit ints
+ *
+ * @return the encoding
+ */
+ public Encoding getEncoding() {
+ return fEncoding;
+ }
+
+ /**
+ * Is the integer a character (8 bits and encoded?)
+ *
+ * @return is the integer a char
+ */
+ public boolean isCharacter() {
+ return (fLength == 8) && (fEncoding != Encoding.NONE);
+ }
+
+ /**
+ * Is the integer an unsigned byte (8 bits and no sign)?
+ *
+ * @return is the integer an unsigned byte
+ * @since 3.1
+ */
+ public boolean isUnsignedByte() {
+ return (fLength == 8) && (!fSigned);
+ }
+
+ /**
+ * Get the length in bits for this integer
+ *
+ * @return the length of the integer
+ */
+ public int getLength() {
+ return fLength;
+ }
+
+ @Override
+ public long getAlignment() {
+ return fAlignment;
+ }
+
+ /**
+ * The integer's clock, since timestamps are stored in ints
+ *
+ * @return the integer's clock, can be null. (most often it is)
+ */
+ public String getClock() {
+ return fClock;
+ }
+
+ /**
+ * @since 3.0
+ */
+ @Override
+ public int getMaximumSize() {
+ return fLength;
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ /**
+ * @since 3.0
+ */
+ @Override
+ public IntegerDefinition createDefinition(@Nullable IDefinitionScope definitionScope,
+ String fieldName, BitBuffer input) throws CTFReaderException {
+ ByteOrder byteOrder = input.getByteOrder();
+ input.setByteOrder(fByteOrder);
+ long value = read(input);
+ input.setByteOrder(byteOrder);
+ return new IntegerDefinition(this, definitionScope, fieldName, value);
+ }
+
+ @Override
+ public String toString() {
+ /* Only used for debugging */
+ return "[declaration] integer[" + Integer.toHexString(hashCode()) + ']'; //$NON-NLS-1$
+ }
+
+ /**
+ * Get the maximum value for this integer declaration.
+ *
+ * @return The maximum value for this integer declaration
+ * @since 2.0
+ */
+ public BigInteger getMaxValue() {
+ /*
+ * Compute the number of bits able to represent an unsigned number,
+ * ignoring sign bit.
+ */
+ int significantBits = fLength - (fSigned ? 1 : 0);
+ /*
+ * For a given N significant bits, compute the maximal value which is (1
+ * << N) - 1.
+ */
+
+ @SuppressWarnings("null")
+ @NonNull
+ BigInteger ret = BigInteger.ONE.shiftLeft(significantBits).subtract(BigInteger.ONE);
+ return ret;
+ }
+
+ /**
+ * Get the minimum value for this integer declaration.
+ *
+ * @return The minimum value for this integer declaration
+ * @since 2.0
+ */
+ public BigInteger getMinValue() {
+ if (!fSigned) {
+ @SuppressWarnings("null")
+ @NonNull
+ BigInteger ret = BigInteger.ZERO;
+ return ret;
+ }
+
+ /*
+ * Compute the number of bits able to represent an unsigned number,
+ * without the sign bit.
+ */
+ int significantBits = fLength - 1;
+ /*
+ * For a given N significant bits, compute the minimal value which is -
+ * (1 << N).
+ */
+ @SuppressWarnings("null")
+ @NonNull
+ BigInteger ret = BigInteger.ONE.shiftLeft(significantBits).negate();
+ return ret;
+ }
+
+ private long read(BitBuffer input) throws CTFReaderException {
+ /* Offset the buffer position wrt the current alignment */
+ alignRead(input);
+
+ boolean signed = isSigned();
+ int length = getLength();
+ long bits = 0;
+
+ /*
+ * Is the endianness of this field the same as the endianness of the
+ * input buffer? If not, then temporarily set the buffer's endianness to
+ * this field's just to read the data
+ */
+ ByteOrder previousByteOrder = input.getByteOrder();
+ if ((getByteOrder() != input.getByteOrder())) {
+ input.setByteOrder(getByteOrder());
+ }
+
+ if (length > 64) {
+ throw new CTFReaderException("Cannot read an integer with over 64 bits. Length given: " + length); //$NON-NLS-1$
+ }
+
+ bits = input.get(length, signed);
+
+ /*
+ * Put the input buffer's endianness back to original if it was changed
+ */
+ if (previousByteOrder != input.getByteOrder()) {
+ input.setByteOrder(previousByteOrder);
+ }
+
+ return bits;
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+import java.math.BigInteger;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+
+/**
+ * A CTF integer definition.
+ *
+ * The definition of a integer basic data type. It will take the data from a
+ * trace and store it (and make it fit) as a long.
+ *
+ * @version 1.0
+ * @author Matthew Khouzam
+ * @author Simon Marchi
+ */
+public final class IntegerDefinition extends SimpleDatatypeDefinition {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ private final long fValue;
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructor
+ *
+ * @param declaration
+ * the parent declaration
+ * @param definitionScope
+ * the parent scope
+ * @param fieldName
+ * the field name
+ * @param value
+ * integer value
+ * @since 3.0
+ */
+ public IntegerDefinition(@NonNull IntegerDeclaration declaration,
+ IDefinitionScope definitionScope, @NonNull String fieldName, long value) {
+ super(declaration, definitionScope, fieldName);
+ fValue = value;
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ /**
+ * Gets the value of the integer
+ *
+ * @return the value of the integer (in long)
+ */
+ public long getValue() {
+ return fValue;
+ }
+
+ @Override
+ public IntegerDeclaration getDeclaration() {
+ return (IntegerDeclaration) super.getDeclaration();
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ @Override
+ public Long getIntegerValue() {
+ return getValue();
+ }
+
+ @Override
+ public String getStringValue() {
+ return this.toString();
+ }
+
+ @Override
+ public String toString() {
+ if (getDeclaration().isCharacter()) {
+ char c = (char) fValue;
+ return Character.toString(c);
+ }
+ return formatNumber(fValue, getDeclaration().getBase(), getDeclaration().isSigned());
+ }
+
+ /**
+ * Print a numeric value as a string in a given base
+ *
+ * @param value
+ * The value to print as string
+ * @param base
+ * The base for this value
+ * @param signed
+ * Is the value signed or not
+ * @return formatted number string
+ * @since 3.0
+ */
+ public static final String formatNumber(long value, int base, boolean signed) {
+ String s;
+ /* Format the number correctly according to the integer's base */
+ switch (base) {
+ case 2:
+ s = "0b" + Long.toBinaryString(value); //$NON-NLS-1$
+ break;
+ case 8:
+ s = "0" + Long.toOctalString(value); //$NON-NLS-1$
+ break;
+ case 16:
+ s = "0x" + Long.toHexString(value); //$NON-NLS-1$
+ break;
+ case 10:
+ default:
+ /* For non-standard base, we'll just print it as a decimal number */
+ if (!signed && value < 0) {
+ /*
+ * Since there are no 'unsigned long', handle this case with
+ * BigInteger
+ */
+ BigInteger bigInteger = BigInteger.valueOf(value);
+ /*
+ * we add 2^64 to the negative number to get the real unsigned
+ * value
+ */
+ bigInteger = bigInteger.add(BigInteger.valueOf(1).shiftLeft(64));
+ s = bigInteger.toString();
+ } else {
+ s = Long.toString(value);
+ }
+ break;
+ }
+ return s;
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.event.scope.LexicalScope;
+
+/**
+ * Scoped defintion. a defintion where you can lookup various datatypes
+ *
+ * TODO: replace by default methods and an interface when java 8 is upon us
+ *
+ * @author Matthew Khouzam
+ * @since 3.1
+ */
+@NonNullByDefault
+public abstract class ScopedDefinition extends Definition implements IDefinitionScope {
+
+ /**
+ * Constructor
+ *
+ * @param declaration
+ * the event declaration
+ * @param definitionScope
+ * the definition is in a scope, (normally a struct) what is it?
+ * @param fieldName
+ * the name of the definition. (it is a field in the parent
+ * scope)
+ */
+ public ScopedDefinition(IDeclaration declaration, @Nullable IDefinitionScope definitionScope, String fieldName) {
+ super(declaration, definitionScope, fieldName);
+ }
+
+ /**
+ * Constructor This one takes the scope and thus speeds up definition
+ * creation
+ *
+ * @param declaration
+ * the parent declaration
+ * @param definitionScope
+ * the parent scope
+ * @param fieldName
+ * the field name
+ * @param scope
+ * the lexical scope
+ * @since 3.1
+ */
+ public ScopedDefinition(StructDeclaration declaration, @Nullable IDefinitionScope definitionScope, String fieldName, LexicalScope scope) {
+ super(declaration, definitionScope, fieldName, scope);
+ }
+
+ /**
+ * Lookup an array in a struct. If the name returns a non-array (like an
+ * int) then the method returns null
+ *
+ * @param name
+ * the name of the array
+ * @return the array or null.
+ */
+ public @Nullable AbstractArrayDefinition lookupArrayDefinition(String name) {
+ Definition def = lookupDefinition(name);
+ return (AbstractArrayDefinition) ((def instanceof AbstractArrayDefinition) ? def : null);
+ }
+
+ /**
+ * Lookup an array in a struct. If the name returns a non-array (like an
+ * int) then the method returns null
+ *
+ * @param name
+ * the name of the array
+ * @return the array or null.
+ * @deprecated use {@link ScopedDefinition#lookupArrayDefinition(String)}
+ */
+ @Deprecated
+ @Nullable
+ public ArrayDefinition lookupArray(String name) {
+ Definition def = lookupDefinition(name);
+ return (ArrayDefinition) ((def instanceof ArrayDefinition) ? def : null);
+ }
+
+ /**
+ * Lookup an enum in a struct. If the name returns a non-enum (like an int)
+ * then the method returns null
+ *
+ * @param name
+ * the name of the enum
+ * @return the enum or null if a definition is not found or it does not
+ * match the desired datatype.
+ */
+ @Nullable
+ public EnumDefinition lookupEnum(String name) {
+ Definition def = lookupDefinition(name);
+ return (EnumDefinition) ((def instanceof EnumDefinition) ? def : null);
+ }
+
+ /**
+ * Lookup an integer in a struct. If the name returns a non-integer (like an
+ * float) then the method returns null
+ *
+ * @param name
+ * the name of the integer
+ * @return the integer or null if a definition is not found or it does not
+ * match the desired datatype.
+ */
+ @Nullable
+ public IntegerDefinition lookupInteger(String name) {
+ Definition def = lookupDefinition(name);
+ return (IntegerDefinition) ((def instanceof IntegerDefinition) ? def : null);
+ }
+
+ /**
+ * Lookup a sequence in a struct. If the name returns a non-sequence (like
+ * an int) then the method returns null
+ *
+ * @param name
+ * the name of the sequence
+ * @return the sequence or null if a definition is not found or it does not
+ * match the desired datatype.
+ * @since 3.0
+ * @deprecated use {@link ScopedDefinition#lookupArrayDefinition(String)}
+ */
+ @Deprecated
+ @Nullable
+ public SequenceDefinition lookupSequence(String name) {
+ Definition def = lookupDefinition(name);
+ return (SequenceDefinition) ((def instanceof SequenceDefinition) ? def : null);
+ }
+
+ /**
+ * Lookup a string in a struct. If the name returns a non-string (like an
+ * int) then the method returns null
+ *
+ * @param name
+ * the name of the string
+ * @return the string or null if a definition is not found or it does not
+ * match the desired datatype.
+ */
+ @Nullable
+ public StringDefinition lookupString(String name) {
+ Definition def = lookupDefinition(name);
+ return (StringDefinition) ((def instanceof StringDefinition) ? def : null);
+ }
+
+ /**
+ * Lookup a struct in a struct. If the name returns a non-struct (like an
+ * int) then the method returns null
+ *
+ * @param name
+ * the name of the struct
+ * @return the struct or null if a definition is not found or it does not
+ * match the desired datatype.
+ */
+ @Nullable
+ public StructDefinition lookupStruct(String name) {
+ Definition def = lookupDefinition(name);
+ return (StructDefinition) ((def instanceof StructDefinition) ? def : null);
+ }
+
+ /**
+ * Lookup a variant in a struct. If the name returns a non-variant (like an
+ * int) then the method returns null
+ *
+ * @param name
+ * the name of the variant
+ * @return the variant or null if a definition is not found or it does not
+ * match the desired datatype.
+ */
+ @Nullable
+ public VariantDefinition lookupVariant(String name) {
+ Definition def = lookupDefinition(name);
+ return (VariantDefinition) ((def instanceof VariantDefinition) ? def : null);
+ }
+}
\ No newline at end of file
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011-2012 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+import java.util.Collection;
+import java.util.List;
+
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+
+import com.google.common.collect.ArrayListMultimap;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableList.Builder;
+import com.google.common.collect.Multimap;
+
+/**
+ * A CTF sequence declaration.
+ *
+ * An array where the size is fixed but declared in the trace, unlike array
+ * where it is declared with a literal
+ * @deprecated use {@link org.eclipse.tracecompass.internal.ctf.core.event.types.SequenceDeclaration}
+ * @version 1.0
+ * @author Matthew Khouzam
+ * @author Simon Marchi
+ */
+@Deprecated
+public class SequenceDeclaration extends CompoundDeclaration {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ private final IDeclaration fElemType;
+ private final String fLengthName;
+ private final Multimap<String, String> fPaths = ArrayListMultimap.<String, String>create();
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructor
+ *
+ * @param lengthName
+ * the name of the field describing the length
+ * @param elemType
+ * The element type
+ */
+ public SequenceDeclaration(String lengthName, IDeclaration elemType) {
+ fElemType = elemType;
+ fLengthName = lengthName;
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ @Override
+ public IDeclaration getElementType() {
+ return fElemType;
+ }
+
+ /**
+ * Gets the name of the length field
+ *
+ * @return the name of the length field
+ */
+ public String getLengthName() {
+ return fLengthName;
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ /**
+ * @since 3.0
+ */
+ @SuppressWarnings("null") // immutablelist
+ @Override
+ public SequenceDefinition createDefinition(
+ IDefinitionScope definitionScope, String fieldName, BitBuffer input) throws CTFReaderException {
+ IDefinition lenDef = null;
+
+ if (definitionScope != null) {
+ lenDef = definitionScope.lookupDefinition(getLengthName());
+ }
+
+ if (lenDef == null) {
+ throw new CTFReaderException("Sequence length field not found"); //$NON-NLS-1$
+ }
+
+ if (!(lenDef instanceof IntegerDefinition)) {
+ throw new CTFReaderException("Sequence length field not integer"); //$NON-NLS-1$
+ }
+
+ IntegerDefinition lengthDefinition = (IntegerDefinition) lenDef;
+
+ if (lengthDefinition.getDeclaration().isSigned()) {
+ throw new CTFReaderException("Sequence length must not be signed"); //$NON-NLS-1$
+ }
+
+ long length = lengthDefinition.getValue();
+ if ((length > Integer.MAX_VALUE) || (!input.canRead((int) length * fElemType.getMaximumSize()))) {
+ throw new CTFReaderException("Sequence length too long " + length); //$NON-NLS-1$
+ }
+
+ Collection<String> collection = fPaths.get(fieldName);
+ while (collection.size() < length) {
+ fPaths.put(fieldName, fieldName + '[' + collection.size() + ']');
+ }
+ List<String> paths = (List<String>) fPaths.get(fieldName);
+ Builder<Definition> definitions = new ImmutableList.Builder<>();
+ for (int i = 0; i < length; i++) {
+ definitions.add(fElemType.createDefinition(definitionScope, paths.get(i), input));
+ }
+ return new SequenceDefinition(this, definitionScope, fieldName, definitions.build());
+ }
+
+ @Override
+ public String toString() {
+ /* Only used for debugging */
+ return "[declaration] sequence[" + Integer.toHexString(hashCode()) + ']'; //$NON-NLS-1$
+ }
+
+ /**
+ * @since 3.0
+ */
+ @Override
+ public int getMaximumSize() {
+ return Integer.MAX_VALUE;
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+import java.util.List;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+
+import com.google.common.base.Joiner;
+import com.google.common.collect.ImmutableList;
+
+/**
+ * A CTF sequence definition (a fixed-size array).
+ *
+ * An array where the size is fixed but declared in the trace, unlike array
+ * where it is declared with a literal
+ *
+ * @deprecated use {@link AbstractArrayDefinition}
+ * @version 1.0
+ * @author Matthew Khouzam
+ * @author Simon Marchi
+ */
+@Deprecated
+public final class SequenceDefinition extends Definition {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ private final ImmutableList<Definition> fDefinitions;
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructor
+ *
+ * @param declaration
+ * the parent declaration
+ * @param definitionScope
+ * the parent scope
+ * @param fieldName
+ * the field name
+ * @param definitions
+ * Definitions
+ * @since 3.0
+ */
+ public SequenceDefinition(@NonNull SequenceDeclaration declaration, IDefinitionScope definitionScope, @NonNull String fieldName, List<Definition> definitions) {
+ super(declaration, definitionScope, fieldName);
+ fDefinitions = ImmutableList.copyOf(definitions);
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ @Override
+ public SequenceDeclaration getDeclaration() {
+ return (SequenceDeclaration) super.getDeclaration();
+ }
+
+ /**
+ * The length of the sequence in number of elements so a sequence of 5
+ * GIANT_rediculous_long_ints is the same as a sequence of 5 bits. (5)
+ *
+ * @return the length of the sequence
+ */
+ public int getLength() {
+ return fDefinitions.size();
+ }
+
+ /**
+ * Get the element at i
+ *
+ * @param i
+ * the index (cannot be negative)
+ * @return The element at I, if I > length, null, if I < 0, the method
+ * throws an out of bounds exception
+ */
+ public Definition getElem(int i) {
+ if (i > fDefinitions.size()) {
+ return null;
+ }
+ return fDefinitions.get(i);
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ @Override
+ public String toString() {
+ StringBuilder b = new StringBuilder();
+
+ if (getDeclaration().isString()) {
+ for (Definition def : fDefinitions) {
+ IntegerDefinition character = (IntegerDefinition) def;
+
+ if (character.getValue() == 0) {
+ break;
+ }
+
+ b.append(character.toString());
+ }
+ } else {
+ b.append('[');
+ Joiner joiner = Joiner.on(", ").skipNulls(); //$NON-NLS-1$
+ b.append(joiner.join(fDefinitions));
+ b.append(']');
+ }
+
+ return b.toString();
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+
+/**
+ * Simple Datatype definition is a datatype that allows the addition of
+ * getIntegerValue and getStringValue to a class.
+ *
+ * @author Matthew Khouzam
+ * @since 1.2
+ */
+public abstract class SimpleDatatypeDefinition extends Definition {
+
+ /**
+ * Create a new SimpleDatatypeDefinition
+ *
+ * @param declaration
+ * definition's declaration
+ * @param definitionScope
+ * The scope of this definition
+ * @param fieldName
+ * The name of the field matching this definition in the parent
+ * scope
+ * @since 3.0
+ */
+ public SimpleDatatypeDefinition(@NonNull IDeclaration declaration, IDefinitionScope definitionScope,
+ @NonNull String fieldName) {
+ super(declaration, definitionScope, fieldName);
+ }
+
+ /**
+ * Gets the value in integer form
+ *
+ * @return the integer in a Long, can be null
+ */
+ public Long getIntegerValue() {
+ return null;
+ }
+
+ /**
+ * Gets the value in string form
+ *
+ * @return the integer in a String, can be null
+ */
+ public String getStringValue() {
+ return null;
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+
+/**
+ * A CTF string declaration.
+ *
+ * Strings are an array of bytes of variable size and are terminated by a '\0'
+ * "NULL" character. Their encoding is described in the TSDL meta-data. In
+ * absence of encoding attribute information, the default encoding is UTF-8.
+ *
+ * @version 1.0
+ * @author Matthew Khouzam
+ * @author Simon Marchi
+ */
+public class StringDeclaration extends Declaration {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ private final Encoding fEncoding;
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Generate a UTF8 string declaration
+ */
+ public StringDeclaration() {
+ fEncoding = Encoding.UTF8;
+ }
+
+ /**
+ * Generate an encoded string declaration
+ * @param encoding the encoding, utf8 or ascii
+ */
+ public StringDeclaration(Encoding encoding) {
+ fEncoding = encoding;
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ /**
+ *
+ * @return the character encoding.
+ */
+ public Encoding getEncoding() {
+ return fEncoding;
+ }
+
+ @Override
+ public long getAlignment() {
+ // See ctf 4.2.5: Strings are always aligned on byte size.
+ return 8;
+ }
+
+ /**
+ * @since 3.0
+ */
+ @Override
+ public int getMaximumSize() {
+ return Integer.MAX_VALUE;
+ }
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ /**
+ * @since 3.0
+ */
+ @Override
+ public StringDefinition createDefinition(IDefinitionScope definitionScope,
+ String fieldName, BitBuffer input) throws CTFReaderException {
+ String value = read(input);
+ return new StringDefinition(this, definitionScope, fieldName, value);
+ }
+
+ private String read(BitBuffer input) throws CTFReaderException {
+ /* Offset the buffer position wrt the current alignment */
+ alignRead(input);
+
+ StringBuilder sb = new StringBuilder();
+ char c = (char) input.get(8, false);
+ while (c != 0) {
+ sb.append(c);
+ c = (char) input.get(8, false);
+ }
+ return sb.toString();
+ }
+ @Override
+ public String toString() {
+ /* Only used for debugging */
+ return "[declaration] string[" + Integer.toHexString(hashCode()) + ']'; //$NON-NLS-1$
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+
+/**
+ * A CTF string definition (similar to a C null-terminated byte array).
+ *
+ * Strings are an array of bytes of variable size and are terminated by a '\0'
+ * "NULL" character. Their encoding is described in the TSDL meta-data. In
+ * absence of encoding attribute information, the default encoding is UTF-8.
+ *
+ * @version 1.0
+ * @author Matthew Khouzam
+ * @author Simon Marchi
+ */
+public final class StringDefinition extends Definition {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ private final String fString;
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructor
+ *
+ * @param declaration
+ * the parent declaration
+ * @param definitionScope
+ * the parent scope
+ * @param fieldName
+ * the field name
+ * @param value
+ * The String value
+ * @since 3.0
+ */
+ public StringDefinition(@NonNull StringDeclaration declaration,
+ IDefinitionScope definitionScope, @NonNull String fieldName, String value) {
+ super(declaration, definitionScope, fieldName);
+ fString = value;
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ @Override
+ public StringDeclaration getDeclaration() {
+ return (StringDeclaration) super.getDeclaration();
+ }
+
+ /**
+ * Gets the string (value)
+ *
+ * @return the string
+ */
+ public String getValue() {
+ return fString;
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ @Override
+ public String toString() {
+ return '\"' + getValue() + '\"';
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.Nullable;
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.event.scope.LexicalScope;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+
+/**
+ * A CTF structure declaration.
+ *
+ * A structure is similar to a C structure, it is a compound data type that
+ * contains other datatypes in fields. they are stored in an hashmap and indexed
+ * by names which are strings.
+ *
+ * @version 1.0
+ * @author Matthew Khouzam
+ * @author Simon Marchi
+ */
+public class StructDeclaration extends Declaration {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ /** linked list of field names. So fieldName->fieldValue */
+ private final @NonNull Map<String, IDeclaration> fFieldMap = new LinkedHashMap<>();
+
+ /** maximum bit alignment */
+ private long fMaxAlign;
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * The struct declaration, add fields later
+ *
+ * @param align
+ * the minimum alignment of the struct. (if a struct is 8bit
+ * aligned and has a 32 bit aligned field, the struct becomes 32
+ * bit aligned.
+ */
+ public StructDeclaration(long align) {
+ fMaxAlign = Math.max(align, 1);
+ }
+
+ /**
+ * Struct declaration constructor
+ *
+ * @param names
+ * the names of all the fields
+ * @param declarations
+ * all the fields
+ * @since 3.0
+ */
+ public StructDeclaration(String[] names, Declaration[] declarations) {
+ fMaxAlign = 1;
+
+ for (int i = 0; i < names.length; i++) {
+ addField(names[i], declarations[i]);
+ }
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ /**
+ * Get current alignment
+ *
+ * @return the alignment of the struct and all its fields
+ */
+ public long getMaxAlign() {
+ return fMaxAlign;
+ }
+
+ /**
+ * Query if the struct has a given field
+ *
+ * @param name
+ * the name of the field, scopeless please
+ * @return does the field exist?
+ */
+ public boolean hasField(String name) {
+ return fFieldMap.containsKey(name);
+ }
+
+ /**
+ * Get the fields of the struct as a map.
+ *
+ * @return a Map of the fields (key is the name)
+ * @since 2.0
+ */
+ public Map<String, IDeclaration> getFields() {
+ return fFieldMap;
+ }
+
+ /**
+ * Get the field declaration corresponding to a field name.
+ *
+ * @param fieldName
+ * The field name
+ * @return The declaration of the field, or null if there is no such field.
+ * @since 3.1
+ */
+ @Nullable
+ public IDeclaration getField(String fieldName) {
+ return fFieldMap.get(fieldName);
+ }
+
+ /**
+ * Gets the field list. Very important since the map of fields does not
+ * retain the order of the fields.
+ *
+ * @return the field list.
+ * @since 3.0
+ */
+ public Iterable<String> getFieldsList() {
+ return fFieldMap.keySet();
+ }
+
+ @Override
+ public long getAlignment() {
+ return this.fMaxAlign;
+ }
+
+ /**
+ * @since 3.0
+ */
+ @Override
+ public int getMaximumSize() {
+ int maxSize = 0;
+ for (IDeclaration field : fFieldMap.values()) {
+ maxSize += field.getMaximumSize();
+ }
+ return Math.min(maxSize, Integer.MAX_VALUE);
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ /**
+ * @since 3.0
+ */
+ @Override
+ public StructDefinition createDefinition(IDefinitionScope definitionScope,
+ String fieldName, BitBuffer input) throws CTFReaderException {
+ alignRead(input);
+ final Definition[] myFields = new Definition[fFieldMap.size()];
+ StructDefinition structDefinition = new StructDefinition(this, definitionScope, fieldName, fFieldMap.keySet(), myFields);
+ fillStruct(input, myFields, structDefinition);
+ return structDefinition;
+ }
+
+ /**
+ * Create a definition from this declaration. This is a faster constructor
+ * as it has a lexical scope and this does not need to look it up.
+ *
+ * @param definitionScope
+ * the definition scope, the parent where the definition will be
+ * placed
+ * @param fieldScope
+ * the scope of the definition
+ * @param input
+ * a bitbuffer to read from
+ * @return a reference to the definition
+ * @throws CTFReaderException
+ * error in reading
+ * @since 3.1
+ */
+ public StructDefinition createDefinition(IDefinitionScope definitionScope,
+ LexicalScope fieldScope, @NonNull BitBuffer input) throws CTFReaderException {
+ alignRead(input);
+ final Definition[] myFields = new Definition[fFieldMap.size()];
+ /*
+ * Key set is NOT null
+ */
+ @SuppressWarnings("null")
+ StructDefinition structDefinition = new StructDefinition(this, definitionScope, fieldScope, fieldScope.getName(), fFieldMap.keySet(), myFields);
+ fillStruct(input, myFields, structDefinition);
+ return structDefinition;
+ }
+
+ /**
+ * Add a field to the struct
+ *
+ * @param name
+ * the name of the field, scopeless
+ * @param declaration
+ * the declaration of the field
+ */
+ public void addField(String name, IDeclaration declaration) {
+ fFieldMap.put(name, declaration);
+ fMaxAlign = Math.max(fMaxAlign, declaration.getAlignment());
+ }
+
+ @SuppressWarnings("null")
+ private void fillStruct(@NonNull BitBuffer input, final Definition[] myFields, StructDefinition structDefinition) throws CTFReaderException {
+ Iterator<Map.Entry<String, IDeclaration>> iter = fFieldMap.entrySet().iterator();
+ for (int i = 0; i < fFieldMap.size(); i++) {
+ Map.Entry<String, IDeclaration> entry = iter.next();
+ myFields[i] = entry.getValue().createDefinition(structDefinition, entry.getKey(), input);
+ }
+ }
+
+ @Override
+ public String toString() {
+ /* Only used for debugging */
+ return "[declaration] struct[" + Integer.toHexString(hashCode()) + ']'; //$NON-NLS-1$
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = (prime * result) + fFieldMap.entrySet().hashCode();
+ result = (prime * result) + (int) (fMaxAlign ^ (fMaxAlign >>> 32));
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (!(obj instanceof StructDeclaration)) {
+ return false;
+ }
+ StructDeclaration other = (StructDeclaration) obj;
+ if (!fFieldMap.entrySet().equals(other.fFieldMap.entrySet())) {
+ return false;
+ }
+ if (fMaxAlign != other.fMaxAlign) {
+ return false;
+ }
+ return true;
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.event.scope.LexicalScope;
+
+import com.google.common.base.Joiner;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableMap.Builder;
+
+/**
+ * A CTF structure definition (similar to a C structure).
+ *
+ * A structure is similar to a C structure, it is a compound data type that
+ * contains other datatypes in fields. they are stored in an hashmap and indexed
+ * by names which are strings.
+ *
+ * TODO: move me to internal
+ *
+ * @version 1.0
+ * @author Matthew Khouzam
+ * @author Simon Marchi
+ */
+public final class StructDefinition extends ScopedDefinition implements ICompositeDefinition {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ private final ImmutableList<String> fFieldNames;
+ private final Definition[] fDefinitions;
+ private Map<String, Definition> fDefinitionsMap = null;
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * *DEPRECATED* TODO: To remove once we break the API...
+ *
+ * Not marked with the annotation to not annoy callers using a List, which
+ * is still as valid with the new constructor. But the compiler gives an
+ * error even though a Iterable is a List too...
+ *
+ * @param declaration
+ * the parent declaration
+ * @param definitionScope
+ * the parent scope
+ * @param structFieldName
+ * the field name
+ * @param fieldNames
+ * the list of fields
+ * @param definitions
+ * the definitions
+ * @since 3.1
+ */
+ public StructDefinition(@NonNull StructDeclaration declaration,
+ IDefinitionScope definitionScope,
+ @NonNull String structFieldName,
+ List<String> fieldNames,
+ Definition[] definitions) {
+ this(declaration, definitionScope, structFieldName, (Iterable<String>) fieldNames, definitions);
+ }
+
+ /**
+ * Constructor
+ *
+ * @param declaration
+ * the parent declaration
+ * @param definitionScope
+ * the parent scope
+ * @param structFieldName
+ * the field name
+ * @param fieldNames
+ * the list of fields
+ * @param definitions
+ * the definitions
+ * @since 3.1
+ */
+ public StructDefinition(@NonNull StructDeclaration declaration,
+ IDefinitionScope definitionScope,
+ @NonNull String structFieldName,
+ Iterable<String> fieldNames,
+ Definition[] definitions) {
+ super(declaration, definitionScope, structFieldName);
+ fFieldNames = ImmutableList.copyOf(fieldNames);
+ fDefinitions = definitions;
+ if (fFieldNames.isEmpty()) {
+ fDefinitionsMap = Collections.EMPTY_MAP;
+ }
+ }
+
+ /**
+ * Constructor This one takes the scope and thus speeds up definition
+ * creation
+ *
+ * @param declaration
+ * the parent declaration
+ * @param definitionScope
+ * the parent scope
+ * @param scope
+ * the scope of this variable
+ * @param structFieldName
+ * the field name
+ * @param fieldNames
+ * the list of fields
+ * @param definitions
+ * the definitions
+ * @since 3.1
+ */
+ public StructDefinition(@NonNull StructDeclaration declaration,
+ IDefinitionScope definitionScope, @NonNull LexicalScope scope,
+ @NonNull String structFieldName, @NonNull Iterable<String> fieldNames, Definition[] definitions) {
+ super(declaration, definitionScope, structFieldName, scope);
+ fFieldNames = ImmutableList.copyOf(fieldNames);
+ fDefinitions = definitions;
+ if (fFieldNames.isEmpty()) {
+ fDefinitionsMap = Collections.EMPTY_MAP;
+ }
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ @Override
+ public Definition getDefinition(String fieldName) {
+ if (fDefinitionsMap == null) {
+ /* Build the definitions map */
+ Builder<String, Definition> mapBuilder = new ImmutableMap.Builder<>();
+ for (int i = 0; i < fFieldNames.size(); i++) {
+ if (fDefinitions[i] != null) {
+ mapBuilder.put(fFieldNames.get(i), fDefinitions[i]);
+ }
+ }
+ fDefinitionsMap = mapBuilder.build();
+ }
+ return fDefinitionsMap.get(fieldName);
+ }
+
+ @Override
+ public List<String> getFieldNames() {
+ return fFieldNames;
+ }
+
+ @Override
+ public StructDeclaration getDeclaration() {
+ return (StructDeclaration) super.getDeclaration();
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ @Override
+ public Definition lookupDefinition(String lookupPath) {
+ /*
+ * The fields are created in order of appearance, so if a variant or
+ * sequence refers to a field that is after it, the field's definition
+ * will not be there yet in the hashmap.
+ */
+ int val = fFieldNames.indexOf(lookupPath);
+ if (val != -1) {
+ return fDefinitions[val];
+ }
+ String lookupUnderscored = "_" + lookupPath; //$NON-NLS-1$
+ val = fFieldNames.indexOf(lookupUnderscored);
+ if (val != -1) {
+ return fDefinitions[val];
+ }
+ return null;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+
+ builder.append("{ "); //$NON-NLS-1$
+
+ if (fFieldNames != null) {
+ List<String> fields = new LinkedList<>();
+ for (String field : fFieldNames) {
+ String appendee = field + " = " + lookupDefinition(field).toString(); //$NON-NLS-1$
+ fields.add(appendee);
+ }
+ Joiner joiner = Joiner.on(", ").skipNulls(); //$NON-NLS-1$
+ builder.append(joiner.join(fields));
+ }
+
+ builder.append(" }"); //$NON-NLS-1$
+
+ return builder.toString();
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+
+/**
+ * A CTFC variant declaration.
+ *
+ * A variant is similar to a C union, only taking the minimum size of the types,
+ * it is a compound data type that contains other datatypes in fields. they are
+ * stored in an hashmap and indexed by names which are strings.
+ *
+ * @version 1.0
+ * @author Matthew Khouzam
+ * @author Simon Marchi
+ */
+public class VariantDeclaration extends Declaration {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ private String fTag = null;
+ private static final long ALIGNMENT = 1;
+ private final Map<String, IDeclaration> fFields = Collections.synchronizedMap(new HashMap<String, IDeclaration>());
+ private EnumDefinition fTagDef;
+ private IDeclaration fDeclarationToPopulate;
+ private IDefinitionScope fPrevDefinitionScope;
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructor
+ */
+ public VariantDeclaration() {
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ /**
+ * @return Does the variant have a tag
+ */
+ public boolean isTagged() {
+ return fTag != null;
+ }
+
+ /**
+ * Lookup if a field exists in the variant
+ *
+ * @param fieldTag
+ * the field tag name
+ * @return true = field tag exists
+ */
+ public boolean hasField(String fieldTag) {
+ return fFields.containsKey(fieldTag);
+ }
+
+ /**
+ * Sets the tag in a variant
+ *
+ * @param tag
+ * the tag
+ */
+ public void setTag(String tag) {
+ fTag = tag;
+ fTagDef = null;
+ }
+
+ /**
+ * Gets current variant tag
+ *
+ * @return the variant tag.
+ */
+ public String getTag() {
+ return fTag;
+ }
+
+ /**
+ * Gets the fields of the variant
+ *
+ * @return the fields of the variant
+ * @since 2.0
+ */
+ public Map<String, IDeclaration> getFields() {
+ return this.fFields;
+ }
+
+ @Override
+ public long getAlignment() {
+ return ALIGNMENT;
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ /**
+ * @since 3.0
+ */
+ @Override
+ public VariantDefinition createDefinition(IDefinitionScope definitionScope,
+ String fieldName, BitBuffer input) throws CTFReaderException {
+ alignRead(input);
+ if (fPrevDefinitionScope != definitionScope) {
+ fTagDef = null;
+ fPrevDefinitionScope = definitionScope;
+ }
+ EnumDefinition tagDef = fTagDef;
+ if (tagDef == null) {
+ Definition def = definitionScope.lookupDefinition(fTag);
+ tagDef = (EnumDefinition) ((def instanceof EnumDefinition) ? def : null);
+ }
+ if (tagDef == null) {
+ throw new CTFReaderException("Tag is not defined " + fTag); //$NON-NLS-1$
+ }
+ String varFieldName = tagDef.getStringValue();
+ fDeclarationToPopulate = fFields.get(varFieldName);
+ if (fDeclarationToPopulate == null) {
+ throw new CTFReaderException("Unknown enum selector for variant " + //$NON-NLS-1$
+ definitionScope.getScopePath().toString());
+ }
+ Definition fieldValue = fDeclarationToPopulate.createDefinition(definitionScope, fieldName, input);
+ return new VariantDefinition(this, definitionScope, varFieldName, fieldName, fieldValue);
+ }
+
+ /**
+ * Add a field to this CTF Variant
+ *
+ * @param fieldTag
+ * The tag of the new field
+ * @param declaration
+ * The Declaration of this new field
+ */
+ public void addField(String fieldTag, IDeclaration declaration) {
+ fFields.put(fieldTag, declaration);
+ }
+
+ /**
+ * gets the tag definition
+ *
+ * @return the fTagDef
+ * @since 3.0
+ */
+ public EnumDefinition getTagDef() {
+ return fTagDef;
+ }
+
+ /**
+ * @since 3.0
+ */
+ @Override
+ public int getMaximumSize() {
+ Collection<IDeclaration> values = fFields.values();
+ int maxSize = 0;
+ for (IDeclaration field : values) {
+ maxSize = Math.max(maxSize, field.getMaximumSize());
+ }
+ return maxSize;
+ }
+
+ @Override
+ public String toString() {
+ /* Only used for debugging */
+ return "[declaration] variant[" + Integer.toHexString(hashCode()) + ']'; //$NON-NLS-1$
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.event.types;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+
+/**
+ * A CTF variant definition (similar to a C union).
+ *
+ * A variant is similar to a C union, only taking the minimum size of the types,
+ * it is a compound data type that contains other datatypes in fields. they are
+ * stored in an hashmap and indexed by names which are strings.
+ *
+ * @version 1.0
+ * @author Matthew Khouzam
+ * @author Simon Marchi
+ */
+public final class VariantDefinition extends ScopedDefinition {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ private final Definition fDefinition;
+ private final String fCurrentField;
+ private final String fFieldName;
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructor
+ *
+ * @param declaration
+ * the parent declaration
+ * @param definitionScope
+ * the parent scope
+ * @param selectedField
+ * the selected field
+ * @param fieldName
+ * the field name
+ * @param fieldValue
+ * the field value
+ * @since 3.0
+ */
+ public VariantDefinition(@NonNull VariantDeclaration declaration,
+ IDefinitionScope definitionScope, String selectedField, @NonNull String fieldName, Definition fieldValue) {
+ super(declaration, definitionScope, fieldName);
+
+ fFieldName = fieldName;
+ fCurrentField = selectedField;
+ fDefinition = fieldValue;
+
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ @Override
+ public VariantDeclaration getDeclaration() {
+ return (VariantDeclaration) super.getDeclaration();
+ }
+
+ /**
+ * Get the current field name
+ *
+ * @return the current field name
+ */
+ public String getCurrentFieldName() {
+ return fCurrentField;
+ }
+
+ /**
+ * Get the current field
+ *
+ * @return the current field
+ */
+ public Definition getCurrentField() {
+ return fDefinition;
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ @Override
+ public Definition lookupDefinition(String lookupPath) {
+ if (lookupPath == null) {
+ return null;
+ }
+ if (lookupPath.equals(fFieldName)) {
+ return fDefinition;
+ }
+ return getDefinitionScope().lookupDefinition(lookupPath);
+ }
+
+ @Override
+ public String toString() {
+ return "{ " + getCurrentFieldName() + //$NON-NLS-1$
+ " = " + getCurrentField() + //$NON-NLS-1$
+ " }"; //$NON-NLS-1$
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Alexandre Montplaisir - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.trace;
+
+/**
+ * General exception that is thrown when there is a problem somewhere with the
+ * CTF trace reader.
+ *
+ * @version 1.0
+ * @author Alexandre Montplaisir
+ */
+public class CTFReaderException extends Exception {
+
+ private static final long serialVersionUID = 2065258365219777672L;
+
+ /**
+ * Default constructor with no message.
+ */
+ public CTFReaderException() {
+ super();
+ }
+
+ /**
+ * Constructor with an attached message.
+ *
+ * @param message
+ * The message attached to this exception
+ */
+ public CTFReaderException(String message) {
+ super(message);
+ }
+
+ /**
+ * Re-throw an exception into this type.
+ *
+ * @param e
+ * The previous Exception we caught
+ */
+ public CTFReaderException(Exception e) {
+ super(e);
+ }
+
+ /**
+ * Constructor with an attached message and re-throw an exception into this type.
+ *
+ * @param message
+ * The message attached to this exception
+ * @param exception
+ * The previous Exception caught
+ * @since 2.0
+ */
+ public CTFReaderException(String message, Throwable exception) {
+ super(message, exception);
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+package org.eclipse.tracecompass.ctf.core.trace;
+
+/**
+ * A response to a request
+ *
+ * @author Matthew Khouzam
+ * @since 3.0
+ *
+ */
+public enum CTFResponse {
+ /**
+ * The operation was successful
+ */
+ OK,
+ /**
+ * The operation cannot be yet completed
+ */
+ WAIT,
+ /**
+ * The operation was finished
+ */
+ FINISH,
+ /**
+ * The operation failed
+ */
+ ERROR
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.trace;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.Nullable;
+import org.eclipse.tracecompass.ctf.core.event.IEventDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IEventHeaderDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+import org.eclipse.tracecompass.internal.ctf.core.event.EventDeclaration;
+import org.eclipse.tracecompass.internal.ctf.core.event.metadata.exceptions.ParseException;
+
+/**
+ * <b><u>Stream</u></b>
+ * <p>
+ * Represents a stream in a trace.
+ *
+ * @since 3.0
+ */
+public class CTFStream {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ /**
+ * The numerical ID of the stream
+ */
+ private Long fId = null;
+
+ /**
+ * Declarations of the stream-specific structures
+ */
+ private StructDeclaration fPacketContextDecl = null;
+ private IDeclaration fEventHeaderDecl = null;
+ private StructDeclaration fEventContextDecl = null;
+
+ /**
+ * The trace to which the stream belongs
+ */
+ private CTFTrace fTrace = null;
+
+ /**
+ * Maps event ids to events
+ */
+ private final ArrayList<IEventDeclaration> fEvents = new ArrayList<>();
+
+ private boolean fEventUnsetId = false;
+
+ /**
+ * The inputs associated to this stream
+ */
+ private final Set<CTFStreamInput> fInputs = new HashSet<>();
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructs a Stream that belongs to a Trace
+ *
+ * @param trace
+ * The trace to which belongs this stream.
+ */
+ public CTFStream(CTFTrace trace) {
+ fTrace = trace;
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ /**
+ * Sets the id of a stream
+ *
+ * @param id
+ * the id of a stream
+ */
+ public void setId(long id) {
+ fId = id;
+ }
+
+ /**
+ * Gets the id of a stream
+ *
+ * @return id the id of a stream
+ */
+ public Long getId() {
+ return fId;
+ }
+
+ /**
+ * Is the id of a stream set
+ *
+ * @return If the ID is set or not
+ */
+ public boolean isIdSet() {
+ return fId != null;
+ }
+
+ /**
+ *
+ * @return is the event header set (timestamp and stuff) (see Ctf Spec)
+ */
+ public boolean isEventHeaderSet() {
+ return fEventHeaderDecl != null;
+ }
+
+ /**
+ *
+ * @return is the event context set (pid and stuff) (see Ctf Spec)
+ */
+ public boolean isEventContextSet() {
+ return fEventContextDecl != null;
+ }
+
+ /**
+ *
+ * @return Is the packet context set (see Ctf Spec)
+ */
+ public boolean isPacketContextSet() {
+ return fPacketContextDecl != null;
+ }
+
+ /**
+ * Sets the event header
+ *
+ * @param eventHeader
+ * the current event header for all events in this stream
+ */
+ public void setEventHeader(StructDeclaration eventHeader) {
+ fEventHeaderDecl = eventHeader;
+ }
+
+ /**
+ * Sets the event header, this typically has the id and the timestamp
+ *
+ * @param eventHeader
+ * the current event header for all events in this stream
+ * @since 3.1
+ */
+ public void setEventHeader(IEventHeaderDeclaration eventHeader) {
+ fEventHeaderDecl = eventHeader;
+ }
+
+ /**
+ *
+ * @param eventContext
+ * the context for all events in this stream
+ */
+ public void setEventContext(StructDeclaration eventContext) {
+ fEventContextDecl = eventContext;
+ }
+
+ /**
+ *
+ * @param packetContext
+ * the packet context for all packets in this stream
+ */
+ public void setPacketContext(StructDeclaration packetContext) {
+ fPacketContextDecl = packetContext;
+ }
+
+ /**
+ *
+ * @return the event header declaration in structdeclaration form
+ * @deprecated use {@link CTFStream#getEventHeaderDeclaration()}
+ */
+ @Deprecated
+ public StructDeclaration getEventHeaderDecl() {
+ return (StructDeclaration) ((fEventHeaderDecl instanceof StructDeclaration) ? fEventHeaderDecl : null);
+ }
+
+ /**
+ * Gets the event header declaration
+ *
+ * @return the event header declaration in declaration form
+ * @since 3.1
+ */
+ public IDeclaration getEventHeaderDeclaration() {
+ return fEventHeaderDecl;
+ }
+
+ /**
+ *
+ * @return the event context declaration in structdeclaration form
+ */
+ public StructDeclaration getEventContextDecl() {
+ return fEventContextDecl;
+ }
+
+ /**
+ *
+ * @return the packet context declaration in structdeclaration form
+ */
+ public StructDeclaration getPacketContextDecl() {
+ return fPacketContextDecl;
+ }
+
+ /**
+ *
+ * @return the set of all stream inputs for this stream
+ */
+ public Set<CTFStreamInput> getStreamInputs() {
+ return fInputs;
+ }
+
+ /**
+ *
+ * @return the parent trace
+ */
+ public CTFTrace getTrace() {
+ return fTrace;
+ }
+
+ /**
+ *
+ * @return all the event declarations for this stream, using the id as a key
+ * for the hashmap.
+ * @deprecated use {@link CTFStream#getEventDeclarations()}
+ */
+ @Deprecated
+ public Map<Long, IEventDeclaration> getEvents() {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * Get all the event declarations in this stream.
+ *
+ * @return The event declarations for this stream
+ * @since 3.2
+ */
+ public @NonNull Collection<IEventDeclaration> getEventDeclarations() {
+ List<IEventDeclaration> retVal = new ArrayList<>(fEvents);
+ retVal.removeAll(Collections.<IEventDeclaration> singletonList(null));
+ return retVal;
+ }
+
+ /**
+ * Get the event declaration for a given ID.
+ *
+ * @param eventId
+ * The ID, can be {@link EventDeclaration#UNSET_EVENT_ID}, or any
+ * positive value
+ * @return The event declaration with the given ID for this stream, or
+ * 'null' if there are no declaration with this ID
+ * @throws IllegalArgumentException
+ * If the passed ID is invalid
+ * @since 3.2
+ */
+ public @Nullable IEventDeclaration getEventDeclaration(int eventId) {
+ int eventIndex = (eventId == EventDeclaration.UNSET_EVENT_ID) ? 0 : eventId;
+ if (eventIndex < 0) {
+ /* Any negative value other than UNSET_EVENT_ID is invalid */
+ throw new IllegalArgumentException("Event ID cannot be negative."); //$NON-NLS-1$
+ }
+ if (eventIndex >= fEvents.size()) {
+ /* This ID could be valid, but there are no declarations with it */
+ return null;
+ }
+ return fEvents.get(eventIndex);
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ /**
+ * Adds an event to the event list.
+ *
+ * An event in a stream can omit its id if it is the only event in this
+ * stream. An event for which no id has been specified has a null id. It is
+ * thus not possible to add an event with the null key if the map is not
+ * empty. It is also not possible to add an event to the map if the null key
+ * is present in the map.
+ *
+ * @param event
+ * The event to add
+ * @throws ParseException
+ * If there was a problem reading the event or adding it to the
+ * stream
+ */
+ public void addEvent(IEventDeclaration event) throws ParseException {
+ if (fEventUnsetId) {
+ throw new ParseException("Event without id with multiple events in a stream"); //$NON-NLS-1$
+ }
+ int id = ((EventDeclaration) event).id();
+
+ /*
+ * If there is an event without id (the null key), it must be the only
+ * one
+ */
+ if (id == EventDeclaration.UNSET_EVENT_ID) {
+ if (!fEvents.isEmpty()) {
+ throw new ParseException("Event without id with multiple events in a stream"); //$NON-NLS-1$
+ }
+ fEventUnsetId = true;
+ fEvents.add(event);
+ } else {
+ /* Check if an event with the same ID already exists */
+ if (fEvents.size() > id && fEvents.get(id) != null) {
+ throw new ParseException("Event id already exists"); //$NON-NLS-1$
+ }
+ ensureSize(fEvents, id);
+ /* Put the event in the list */
+ fEvents.set(id, event);
+ }
+ }
+
+ /**
+ * Add a list of event declarations to this stream. There must be no overlap
+ * between the two lists of event declarations. This will merge the two
+ * lists and preserve the indexes of both lists.
+ *
+ * @param events
+ * list of the events to add
+ * @throws CTFReaderException
+ * if the list already contains data
+ * @since 3.2
+ */
+ public void addEvents(Collection<IEventDeclaration> events) throws CTFReaderException {
+ if (fEventUnsetId) {
+ throw new CTFReaderException("Cannot add to a stream with an unidentified event"); //$NON-NLS-1$
+ }
+ if (fEvents.isEmpty()) {
+ fEvents.addAll(events);
+ return;
+ }
+ for (IEventDeclaration event : events) {
+ if (event != null) {
+ int index = event.getId().intValue();
+ ensureSize(fEvents, index);
+ if (fEvents.get(index) != null) {
+ throw new CTFReaderException("Both lists have an event defined at position " + index); //$NON-NLS-1$
+ }
+ fEvents.set(index, event);
+ }
+ }
+ }
+
+ private static void ensureSize(ArrayList<? extends Object> list, int index) {
+ list.ensureCapacity(index);
+ while (list.size() <= index) {
+ list.add(null);
+ }
+ }
+
+ /**
+ * Add an input to this Stream
+ *
+ * @param input
+ * The StreamInput to add.
+ */
+ public void addInput(CTFStreamInput input) {
+ fInputs.add(input);
+ }
+
+ @Override
+ public String toString() {
+ return "Stream [id=" + fId + ", packetContextDecl=" + fPacketContextDecl //$NON-NLS-1$ //$NON-NLS-2$
+ + ", eventHeaderDecl=" + fEventHeaderDecl //$NON-NLS-1$
+ + ", eventContextDecl=" + fEventContextDecl + ", trace=" + fTrace //$NON-NLS-1$ //$NON-NLS-2$
+ + ", events=" + fEvents + ", inputs=" + fInputs + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.trace;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.channels.FileChannel.MapMode;
+import java.nio.file.StandardOpenOption;
+import java.util.UUID;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.event.scope.LexicalScope;
+import org.eclipse.tracecompass.ctf.core.event.types.Definition;
+import org.eclipse.tracecompass.ctf.core.event.types.EnumDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.FloatDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.IDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.StringDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDefinition;
+import org.eclipse.tracecompass.internal.ctf.core.SafeMappedByteBuffer;
+import org.eclipse.tracecompass.internal.ctf.core.event.types.ArrayDefinition;
+import org.eclipse.tracecompass.internal.ctf.core.trace.StreamInputPacketIndex;
+import org.eclipse.tracecompass.internal.ctf.core.trace.StreamInputPacketIndexEntry;
+
+/**
+ * <b><u>StreamInput</u></b>
+ * <p>
+ * Represents a trace file that belongs to a certain stream.
+ *
+ * @since 3.0
+ */
+// TODO: remove AutoCloseable
+public class CTFStreamInput implements IDefinitionScope, AutoCloseable {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ /**
+ * The associated Stream
+ */
+ private final CTFStream fStream;
+
+ /**
+ * Information on the file (used for debugging)
+ */
+ @NonNull
+ private final File fFile;
+
+ /**
+ * The packet index of this input
+ */
+ private final StreamInputPacketIndex fIndex;
+
+ private long fTimestampEnd;
+
+ /**
+ * Definition of trace packet header
+ */
+ private StructDeclaration fTracePacketHeaderDecl = null;
+
+ /**
+ * Definition of trace stream packet context
+ */
+ private StructDeclaration fStreamPacketContextDecl = null;
+
+ /**
+ * Total number of lost events in this stream
+ */
+ private long fLostSoFar = 0;
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructs a StreamInput.
+ *
+ * @param stream
+ * The stream to which this StreamInput belongs to.
+ * @param file
+ * Information about the trace file (for debugging purposes).
+ */
+ public CTFStreamInput(CTFStream stream, @NonNull File file) {
+ fStream = stream;
+ fFile = file;
+ fIndex = new StreamInputPacketIndex();
+ }
+
+ @Override
+ public void close() throws IOException {
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ /**
+ * Gets the stream the streamInput wrapper is wrapping
+ *
+ * @return the stream the streamInput wrapper is wrapping
+ */
+ public CTFStream getStream() {
+ return fStream;
+ }
+
+ /**
+ * The common streamInput Index
+ *
+ * @return the stream input Index
+ */
+ StreamInputPacketIndex getIndex() {
+ return fIndex;
+ }
+
+ /**
+ * Gets the filename of the streamInput file.
+ *
+ * @return the filename of the streaminput file.
+ */
+ public String getFilename() {
+ return fFile.getName();
+ }
+
+ /**
+ * Gets the last read timestamp of a stream. (this is not necessarily the
+ * last time in the stream.)
+ *
+ * @return the last read timestamp
+ */
+ public long getTimestampEnd() {
+ return fTimestampEnd;
+ }
+
+ /**
+ * Sets the last read timestamp of a stream. (this is not necessarily the
+ * last time in the stream.)
+ *
+ * @param timestampEnd
+ * the last read timestamp
+ */
+ public void setTimestampEnd(long timestampEnd) {
+ fTimestampEnd = timestampEnd;
+ }
+
+ /**
+ * Useless for streaminputs
+ */
+ @Override
+ public LexicalScope getScopePath() {
+ return LexicalScope.STREAM;
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ @Override
+ public Definition lookupDefinition(String lookupPath) {
+ /* TODO: lookup in different dynamic scopes is not supported yet. */
+ return null;
+ }
+
+ /**
+ * Create the index for this trace file.
+ */
+ public void setupIndex() {
+
+ /*
+ * The BitBuffer to extract data from the StreamInput
+ */
+ BitBuffer bitBuffer = new BitBuffer();
+ bitBuffer.setByteOrder(getStream().getTrace().getByteOrder());
+
+ /*
+ * Create the definitions we need to read the packet headers + contexts
+ */
+ if (getStream().getTrace().getPacketHeader() != null) {
+ fTracePacketHeaderDecl = getStream().getTrace().getPacketHeader();
+ }
+
+ if (getStream().getPacketContextDecl() != null) {
+ fStreamPacketContextDecl = getStream().getPacketContextDecl();
+ }
+
+ }
+
+ /**
+ * Adds the next packet header index entry to the index of a stream input.
+ *
+ * <strong>This method is slow and can corrupt data if not used
+ * properly</strong>
+ *
+ * @return true if there are more packets to add
+ * @throws CTFReaderException
+ * If there was a problem reading the packed header
+ */
+ public boolean addPacketHeaderIndex() throws CTFReaderException {
+ long currentPos = 0L;
+ if (!fIndex.getEntries().isEmpty()) {
+ StreamInputPacketIndexEntry pos = fIndex.getEntries().lastElement();
+ currentPos = computeNextOffset(pos);
+ }
+ long fileSize = getStreamSize();
+ if (currentPos < fileSize) {
+
+ StreamInputPacketIndexEntry packetIndex = new StreamInputPacketIndexEntry(
+ currentPos);
+ createPacketIndexEntry(fileSize, currentPos, packetIndex);
+ fIndex.addEntry(packetIndex);
+ return true;
+ }
+ return false;
+ }
+
+ private long getStreamSize() {
+ return fFile.length();
+ }
+
+ private long createPacketIndexEntry(long fileSizeBytes, long packetOffsetBytes, StreamInputPacketIndexEntry packetIndex)
+ throws CTFReaderException {
+
+ long pos = readPacketHeader(fileSizeBytes, packetOffsetBytes, packetIndex);
+
+ /* Basic validation */
+ if (packetIndex.getContentSizeBits() > packetIndex.getPacketSizeBits()) {
+ throw new CTFReaderException("Content size > packet size"); //$NON-NLS-1$
+ }
+
+ if (packetIndex.getPacketSizeBits() > ((fileSizeBytes - packetIndex
+ .getOffsetBytes()) * 8)) {
+ throw new CTFReaderException("Not enough data remaining in the file for the size of this packet"); //$NON-NLS-1$
+ }
+
+ /*
+ * Offset in the file, in bits
+ */
+ packetIndex.setDataOffsetBits(pos);
+
+ /*
+ * Update the counting packet offset
+ */
+ return computeNextOffset(packetIndex);
+ }
+
+ /**
+ * @param packetIndex
+ * @return
+ */
+ private static long computeNextOffset(
+ StreamInputPacketIndexEntry packetIndex) {
+ return packetIndex.getOffsetBytes()
+ + ((packetIndex.getPacketSizeBits() + 7) / 8);
+ }
+
+ private long readPacketHeader(long fileSizeBytes,
+ long packetOffsetBytes, StreamInputPacketIndexEntry packetIndex) throws CTFReaderException {
+ long position = -1;
+ /*
+ * Initial size, it should map at least the packet header + context
+ * size.
+ *
+ * TODO: use a less arbitrary size.
+ */
+ long mapSize = 4096;
+ /*
+ * If there is less data remaining than what we want to map, reduce the
+ * map size.
+ */
+ if ((fileSizeBytes - packetIndex.getOffsetBytes()) < mapSize) {
+ mapSize = fileSizeBytes - packetIndex.getOffsetBytes();
+ }
+
+ /*
+ * Map the packet.
+ */
+ try (FileChannel fc = FileChannel.open(fFile.toPath(), StandardOpenOption.READ)) {
+ ByteBuffer map = SafeMappedByteBuffer.map(fc, MapMode.READ_ONLY, packetOffsetBytes, mapSize);
+ if (map == null) {
+ throw new CTFReaderException("Failed to allocate mapped byte buffer"); //$NON-NLS-1$
+ }
+ /*
+ * create a packet bit buffer to read the packet header
+ */
+ BitBuffer bitBuffer = new BitBuffer(map);
+ bitBuffer.setByteOrder(getStream().getTrace().getByteOrder());
+ /*
+ * Read the trace packet header if it exists.
+ */
+ if (fTracePacketHeaderDecl != null) {
+ parseTracePacketHeader(fTracePacketHeaderDecl, bitBuffer);
+ }
+
+ /*
+ * Read the stream packet context if it exists.
+ */
+ if (fStreamPacketContextDecl != null) {
+ parsePacketContext(fileSizeBytes, fStreamPacketContextDecl,
+ bitBuffer, packetIndex);
+ } else {
+ setPacketContextNull(fileSizeBytes, packetIndex);
+ }
+
+ position = bitBuffer.position();
+ } catch (IOException e) {
+ throw new CTFReaderException(e);
+ }
+ return position;
+ }
+
+ private void parseTracePacketHeader(StructDeclaration tracePacketHeaderDecl,
+ @NonNull BitBuffer bitBuffer) throws CTFReaderException {
+ StructDefinition tracePacketHeaderDef = tracePacketHeaderDecl.createDefinition(fStream.getTrace(), LexicalScope.TRACE_PACKET_HEADER, bitBuffer);
+
+ /*
+ * Check the CTF magic number
+ */
+ IntegerDefinition magicDef = (IntegerDefinition) tracePacketHeaderDef
+ .lookupDefinition("magic"); //$NON-NLS-1$
+ if (magicDef != null) {
+ int magic = (int) magicDef.getValue();
+ if (magic != Utils.CTF_MAGIC) {
+ throw new CTFReaderException(
+ "CTF magic mismatch " + Integer.toHexString(magic) + " vs " + Integer.toHexString(Utils.CTF_MAGIC)); //$NON-NLS-1$//$NON-NLS-2$
+ }
+ }
+
+ /*
+ * Check the trace UUID
+ */
+ ArrayDefinition uuidDef =
+ (ArrayDefinition) tracePacketHeaderDef.lookupDefinition("uuid"); //$NON-NLS-1$
+ if (uuidDef != null) {
+ UUID uuid = Utils.getUUIDfromDefinition(uuidDef);
+
+ if (!getStream().getTrace().getUUID().equals(uuid)) {
+ throw new CTFReaderException("UUID mismatch"); //$NON-NLS-1$
+ }
+ }
+
+ /*
+ * Check that the stream id did not change
+ */
+ IntegerDefinition streamIDDef = (IntegerDefinition) tracePacketHeaderDef
+ .lookupDefinition("stream_id"); //$NON-NLS-1$
+ if (streamIDDef != null) {
+ long streamID = streamIDDef.getValue();
+
+ if (streamID != getStream().getId()) {
+ throw new CTFReaderException("Stream ID changing within a StreamInput"); //$NON-NLS-1$
+ }
+ }
+ }
+
+ /**
+ * Gets the wrapped file
+ *
+ * @return the file
+ */
+ @NonNull
+ File getFile() {
+ return fFile;
+ }
+
+ private static void setPacketContextNull(long fileSizeBytes,
+ StreamInputPacketIndexEntry packetIndex) {
+ /*
+ * If there is no packet context, infer the content and packet size from
+ * the file size (assume that there is only one packet and no padding)
+ */
+ packetIndex.setContentSizeBits(fileSizeBytes * 8);
+ packetIndex.setPacketSizeBits(fileSizeBytes * 8);
+ }
+
+ private void parsePacketContext(long fileSizeBytes,
+ StructDeclaration streamPacketContextDecl, @NonNull BitBuffer bitBuffer,
+ StreamInputPacketIndexEntry packetIndex) throws CTFReaderException {
+ StructDefinition streamPacketContextDef = streamPacketContextDecl.createDefinition(this, LexicalScope.STREAM_PACKET_CONTEXT, bitBuffer);
+
+ for (String field : streamPacketContextDef.getDeclaration()
+ .getFieldsList()) {
+ IDefinition id = streamPacketContextDef.lookupDefinition(field);
+ if (id instanceof IntegerDefinition) {
+ packetIndex.addAttribute(field,
+ ((IntegerDefinition) id).getValue());
+ } else if (id instanceof FloatDefinition) {
+ packetIndex.addAttribute(field,
+ ((FloatDefinition) id).getValue());
+ } else if (id instanceof EnumDefinition) {
+ packetIndex.addAttribute(field,
+ ((EnumDefinition) id).getValue());
+ } else if (id instanceof StringDefinition) {
+ packetIndex.addAttribute(field,
+ ((StringDefinition) id).getValue());
+ }
+ }
+
+ Long contentSize = (Long) packetIndex.lookupAttribute("content_size"); //$NON-NLS-1$
+ Long packetSize = (Long) packetIndex.lookupAttribute("packet_size"); //$NON-NLS-1$
+ Long tsBegin = (Long) packetIndex.lookupAttribute("timestamp_begin"); //$NON-NLS-1$
+ Long tsEnd = (Long) packetIndex.lookupAttribute("timestamp_end"); //$NON-NLS-1$
+ String device = (String) packetIndex.lookupAttribute("device"); //$NON-NLS-1$
+ // LTTng Specific
+ Long cpuId = (Long) packetIndex.lookupAttribute("cpu_id"); //$NON-NLS-1$
+ Long lostEvents = (Long) packetIndex.lookupAttribute("events_discarded"); //$NON-NLS-1$
+
+ /* Read the content size in bits */
+ if (contentSize != null) {
+ packetIndex.setContentSizeBits(contentSize.intValue());
+ } else if (packetSize != null) {
+ packetIndex.setContentSizeBits(packetSize.longValue());
+ } else {
+ packetIndex.setContentSizeBits((int) (fileSizeBytes * 8));
+ }
+
+ /* Read the packet size in bits */
+ if (packetSize != null) {
+ packetIndex.setPacketSizeBits(packetSize.intValue());
+ } else if (packetIndex.getContentSizeBits() != 0) {
+ packetIndex.setPacketSizeBits(packetIndex.getContentSizeBits());
+ } else {
+ packetIndex.setPacketSizeBits((int) (fileSizeBytes * 8));
+ }
+
+ /* Read the begin timestamp */
+ if (tsBegin != null) {
+ packetIndex.setTimestampBegin(tsBegin.longValue());
+ }
+
+ /* Read the end timestamp */
+ if (tsEnd != null) {
+ if (tsEnd == -1) {
+ tsEnd = Long.MAX_VALUE;
+ }
+ packetIndex.setTimestampEnd(tsEnd.longValue());
+ setTimestampEnd(packetIndex.getTimestampEnd());
+ }
+
+ if (device != null) {
+ packetIndex.setTarget(device);
+ }
+
+ if (cpuId != null) {
+ packetIndex.setTarget("CPU" + cpuId.toString()); //$NON-NLS-1$
+ }
+
+ if (lostEvents != null) {
+ packetIndex.setLostEvents(lostEvents - fLostSoFar);
+ fLostSoFar = lostEvents;
+ }
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = (prime * result) + fFile.hashCode();
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (!(obj instanceof CTFStreamInput)) {
+ return false;
+ }
+ CTFStreamInput other = (CTFStreamInput) obj;
+ if (!fFile.equals(other.fFile)) {
+ return false;
+ }
+ return true;
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+package org.eclipse.tracecompass.ctf.core.trace;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel.MapMode;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.Nullable;
+import org.eclipse.tracecompass.ctf.core.CTFStrings;
+import org.eclipse.tracecompass.ctf.core.event.EventDefinition;
+import org.eclipse.tracecompass.ctf.core.event.IEventDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.event.scope.LexicalScope;
+import org.eclipse.tracecompass.ctf.core.event.types.Definition;
+import org.eclipse.tracecompass.ctf.core.event.types.ICompositeDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.IDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.IEventHeaderDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.SimpleDatatypeDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.VariantDefinition;
+import org.eclipse.tracecompass.internal.ctf.core.SafeMappedByteBuffer;
+import org.eclipse.tracecompass.internal.ctf.core.event.EventDeclaration;
+import org.eclipse.tracecompass.internal.ctf.core.event.types.composite.EventHeaderDefinition;
+import org.eclipse.tracecompass.internal.ctf.core.trace.StreamInputPacketIndexEntry;
+
+import com.google.common.collect.ImmutableList;
+
+/**
+ * CTF trace packet reader. Reads the events of a packet of a trace file.
+ *
+ * @author Matthew Khouzam
+ * @author Simon Marchi
+ * @since 3.0
+ */
+public class CTFStreamInputPacketReader implements IDefinitionScope, AutoCloseable {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ /** BitBuffer used to read the trace file. */
+ @Nullable
+ private BitBuffer fBitBuffer;
+
+ /** StreamInputReader that uses this StreamInputPacketReader. */
+ private final CTFStreamInputReader fStreamInputReader;
+
+ /** Trace packet header. */
+ private final StructDeclaration fTracePacketHeaderDecl;
+
+ /** Stream packet context definition. */
+ private final StructDeclaration fStreamPacketContextDecl;
+
+ /** Stream event header definition. */
+ private final IDeclaration fStreamEventHeaderDecl;
+
+ /** Stream event context definition. */
+ private final StructDeclaration fStreamEventContextDecl;
+
+ private ICompositeDefinition fCurrentTracePacketHeaderDef;
+ private ICompositeDefinition fCurrentStreamEventHeaderDef;
+ private ICompositeDefinition fCurrentStreamPacketContextDef;
+ /** Reference to the index entry of the current packet. */
+ private StreamInputPacketIndexEntry fCurrentPacket = null;
+
+ /**
+ * Last timestamp recorded.
+ *
+ * Needed to calculate the complete timestamp values for the events with
+ * compact headers.
+ */
+ private long fLastTimestamp = 0;
+
+ /** CPU id of current packet. */
+ private int fCurrentCpu = 0;
+
+ private int fLostEventsInThisPacket;
+
+ private long fLostEventsDuration;
+
+ private boolean fHasLost = false;
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructs a StreamInputPacketReader.
+ *
+ * @param streamInputReader
+ * The StreamInputReader to which this packet reader belongs to.
+ */
+ public CTFStreamInputPacketReader(CTFStreamInputReader streamInputReader) {
+ fStreamInputReader = streamInputReader;
+
+ /* Set the BitBuffer's byte order. */
+ ByteBuffer allocateDirect = ByteBuffer.allocateDirect(0);
+ if (allocateDirect == null) {
+ throw new IllegalStateException("Unable to allocate 0 bytes!"); //$NON-NLS-1$
+ }
+ fBitBuffer = new BitBuffer(allocateDirect);
+
+ final CTFStream currentStream = streamInputReader.getStreamInput().getStream();
+ fTracePacketHeaderDecl = currentStream.getTrace().getPacketHeader();
+ fStreamPacketContextDecl = currentStream.getPacketContextDecl();
+ fStreamEventHeaderDecl = currentStream.getEventHeaderDeclaration();
+ fStreamEventContextDecl = currentStream.getEventContextDecl();
+ }
+
+ /**
+ * Get the event context defintiion
+ *
+ * @param input
+ * the bitbuffer to read from
+ * @return an context definition, can be null
+ * @throws CTFReaderException
+ * out of bounds exception or such
+ */
+ public StructDefinition getEventContextDefinition(@NonNull BitBuffer input) throws CTFReaderException {
+ return fStreamEventContextDecl.createDefinition(fStreamInputReader.getStreamInput(), LexicalScope.STREAM_EVENT_CONTEXT, input);
+ }
+
+ /**
+ * Get the stream context defintiion
+ *
+ * @param input
+ * the bitbuffer to read from
+ * @return an context definition, can be null
+ * @throws CTFReaderException
+ * out of bounds exception or such
+ * @deprecated it was not used
+ */
+ @Deprecated
+ public StructDefinition getStreamEventHeaderDefinition(@NonNull BitBuffer input) throws CTFReaderException {
+ if (!(fStreamEventHeaderDecl instanceof StructDeclaration)) {
+ throw new IllegalStateException("Definition is not a struct definition, this is a deprecated method that doesn't work so well, stop using it."); //$NON-NLS-1$
+ }
+ return ((StructDeclaration) fStreamEventHeaderDecl).createDefinition(this, LexicalScope.STREAM_EVENT_HEADER, input);
+ }
+
+ /**
+ * Get the packet context defintiion
+ *
+ * @param input
+ * the bitbuffer to read from
+ * @return an context definition, can be null
+ * @throws CTFReaderException
+ * out of bounds exception or such
+ */
+ public StructDefinition getStreamPacketContextDefinition(@NonNull BitBuffer input) throws CTFReaderException {
+ return fStreamPacketContextDecl.createDefinition(fStreamInputReader.getStreamInput(), LexicalScope.STREAM_PACKET_CONTEXT, input);
+ }
+
+ /**
+ * Get the event header defintiion
+ *
+ * @param input
+ * the bitbuffer to read from
+ * @return an header definition, can be null
+ * @throws CTFReaderException
+ * out of bounds exception or such
+ */
+ public StructDefinition getTracePacketHeaderDefinition(@NonNull BitBuffer input) throws CTFReaderException {
+ return fTracePacketHeaderDecl.createDefinition(fStreamInputReader.getStreamInput().getStream().getTrace(), LexicalScope.TRACE_PACKET_HEADER, input);
+ }
+
+ /**
+ * Dispose the StreamInputPacketReader
+ */
+ @Override
+ public void close() {
+ fBitBuffer = null;
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ /**
+ * Gets the current packet
+ *
+ * @return the current packet
+ */
+ StreamInputPacketIndexEntry getCurrentPacket() {
+ return fCurrentPacket;
+ }
+
+ /**
+ * Gets the CPU (core) number
+ *
+ * @return the CPU (core) number
+ */
+ public int getCPU() {
+ return fCurrentCpu;
+ }
+
+ @Override
+ public LexicalScope getScopePath() {
+ return LexicalScope.PACKET;
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ @NonNull
+ private ByteBuffer getByteBufferAt(long position, long size) throws CTFReaderException, IOException {
+ ByteBuffer map = SafeMappedByteBuffer.map(fStreamInputReader.getFc(), MapMode.READ_ONLY, position, size);
+ if (map == null) {
+ throw new CTFReaderException("Failed to allocate mapped byte buffer"); //$NON-NLS-1$
+ }
+ return map;
+ }
+ /**
+ * Changes the current packet to the given one.
+ *
+ * @param currentPacket
+ * The index entry of the packet to switch to.
+ * @throws CTFReaderException
+ * If we get an error reading the packet
+ */
+ void setCurrentPacket(StreamInputPacketIndexEntry currentPacket) throws CTFReaderException {
+ StreamInputPacketIndexEntry prevPacket = null;
+ fCurrentPacket = currentPacket;
+
+ if (fCurrentPacket != null) {
+ /*
+ * Change the map of the BitBuffer.
+ */
+ ByteBuffer bb = null;
+ try {
+ bb = getByteBufferAt(
+ fCurrentPacket.getOffsetBytes(),
+ (fCurrentPacket.getPacketSizeBits() + 7) / 8);
+ } catch (IOException e) {
+ throw new CTFReaderException(e.getMessage(), e);
+ }
+
+ BitBuffer bitBuffer = new BitBuffer(bb);
+ fBitBuffer = bitBuffer;
+ /*
+ * Read trace packet header.
+ */
+ if (fTracePacketHeaderDecl != null) {
+ fCurrentTracePacketHeaderDef = getTracePacketHeaderDefinition(bitBuffer);
+ }
+
+ /*
+ * Read stream packet context.
+ */
+ if (fStreamPacketContextDecl != null) {
+ fCurrentStreamPacketContextDef = getStreamPacketContextDefinition(bitBuffer);
+
+ /* Read CPU ID */
+ if (getCurrentPacket().getTarget() != null) {
+ fCurrentCpu = (int) getCurrentPacket().getTargetId();
+ }
+
+ /* Read number of lost events */
+ fLostEventsInThisPacket = (int) getCurrentPacket().getLostEvents();
+ if (fLostEventsInThisPacket != 0) {
+ fHasLost = true;
+ /*
+ * Compute the duration of the lost event time range. If the
+ * current packet is the first packet, duration will be set
+ * to 1.
+ */
+ long lostEventsStartTime;
+ int index = fStreamInputReader.getStreamInput().getIndex().getEntries().indexOf(currentPacket);
+ if (index == 0) {
+ lostEventsStartTime = currentPacket.getTimestampBegin() + 1;
+ } else {
+ prevPacket = fStreamInputReader.getStreamInput().getIndex().getEntries().get(index - 1);
+ lostEventsStartTime = prevPacket.getTimestampEnd();
+ }
+ fLostEventsDuration = Math.abs(lostEventsStartTime - currentPacket.getTimestampBegin());
+ }
+ }
+
+ /*
+ * Use the timestamp begin of the packet as the reference for the
+ * timestamp reconstitution.
+ */
+ fLastTimestamp = currentPacket.getTimestampBegin();
+ } else {
+ fBitBuffer = null;
+ fLastTimestamp = 0;
+ }
+ }
+
+ /**
+ * Returns whether it is possible to read any more events from this packet.
+ *
+ * @return True if it is possible to read any more events from this packet.
+ */
+ public boolean hasMoreEvents() {
+ BitBuffer bitBuffer = fBitBuffer;
+ StreamInputPacketIndexEntry currentPacket = fCurrentPacket;
+ if (currentPacket != null && bitBuffer != null) {
+ return fHasLost || (bitBuffer.position() < currentPacket.getContentSizeBits());
+ }
+ return false;
+ }
+
+ /**
+ * Reads the next event of the packet into the right event definition.
+ *
+ * @return The event definition containing the event data that was just
+ * read.
+ * @throws CTFReaderException
+ * If there was a problem reading the trace
+ */
+ public EventDefinition readNextEvent() throws CTFReaderException {
+ /* Default values for those fields */
+ // compromise since we cannot have 64 bit addressing of arrays yet.
+ int eventID = (int) EventDeclaration.UNSET_EVENT_ID;
+ long timestamp = 0;
+ if (fHasLost) {
+ fHasLost = false;
+ EventDeclaration lostEventDeclaration = EventDeclaration.getLostEventDeclaration();
+ StructDeclaration lostFields = lostEventDeclaration.getFields();
+ // this is a hard coded map, we know it's not null
+ IntegerDeclaration lostFieldsDecl = (IntegerDeclaration) lostFields.getField(CTFStrings.LOST_EVENTS_FIELD);
+ if (lostFieldsDecl == null)
+ {
+ throw new IllegalStateException("Lost events count not declared!"); //$NON-NLS-1$
+ }
+ IntegerDeclaration lostEventsDurationDecl = (IntegerDeclaration) lostFields.getField(CTFStrings.LOST_EVENTS_DURATION);
+ if (lostEventsDurationDecl == null) {
+ throw new IllegalStateException("Lost events duration not declared!"); //$NON-NLS-1$
+ }
+ IntegerDefinition lostDurationDef = new IntegerDefinition(lostFieldsDecl, null, CTFStrings.LOST_EVENTS_DURATION, fLostEventsDuration);
+ IntegerDefinition lostCountDef = new IntegerDefinition(lostEventsDurationDecl, null, CTFStrings.LOST_EVENTS_FIELD, fLostEventsInThisPacket);
+ IntegerDefinition[] fields = new IntegerDefinition[] { lostCountDef, lostDurationDef };
+ /* this is weird notation, but it's the java notation */
+ final ImmutableList<String> fieldNameList = ImmutableList.<String> builder().add(CTFStrings.LOST_EVENTS_FIELD).add(CTFStrings.LOST_EVENTS_DURATION).build();
+ return new EventDefinition(
+ lostEventDeclaration,
+ fStreamInputReader,
+ fLastTimestamp,
+ null,
+ null,
+ null,
+ new StructDefinition(
+ lostFields,
+ this, "fields", //$NON-NLS-1$
+ fieldNameList,
+ fields
+ ));
+
+ }
+
+ final BitBuffer currentBitBuffer = fBitBuffer;
+ if (currentBitBuffer == null) {
+ return null;
+ }
+ final long posStart = currentBitBuffer.position();
+ /* Read the stream event header. */
+ if (fStreamEventHeaderDecl != null) {
+ if (fStreamEventHeaderDecl instanceof IEventHeaderDeclaration) {
+ fCurrentStreamEventHeaderDef = (ICompositeDefinition) fStreamEventHeaderDecl.createDefinition(null, "", currentBitBuffer); //$NON-NLS-1$
+ EventHeaderDefinition ehd = (EventHeaderDefinition) fCurrentStreamEventHeaderDef;
+ eventID = ehd.getId();
+ timestamp = calculateTimestamp(ehd.getTimestamp(), ehd.getTimestampLength());
+ } else {
+ fCurrentStreamEventHeaderDef = ((StructDeclaration) fStreamEventHeaderDecl).createDefinition(null, LexicalScope.EVENT_HEADER, currentBitBuffer);
+ StructDefinition StructEventHeaderDef = (StructDefinition) fCurrentStreamEventHeaderDef;
+ /* Check for the event id. */
+ IDefinition idDef = StructEventHeaderDef.lookupDefinition("id"); //$NON-NLS-1$
+ SimpleDatatypeDefinition simpleIdDef = null;
+ if (idDef instanceof SimpleDatatypeDefinition) {
+ simpleIdDef = ((SimpleDatatypeDefinition) idDef);
+ } else if (idDef != null) {
+ throw new CTFReaderException("Id defintion not an integer, enum or float definiton in event header."); //$NON-NLS-1$
+ }
+
+ /*
+ * Get the timestamp from the event header (may be overridden
+ * later on)
+ */
+ IntegerDefinition timestampDef = StructEventHeaderDef.lookupInteger("timestamp"); //$NON-NLS-1$
+
+ /* Check for the variant v. */
+ IDefinition variantDef = StructEventHeaderDef.lookupDefinition("v"); //$NON-NLS-1$
+ if (variantDef instanceof VariantDefinition) {
+
+ /* Get the variant current field */
+ StructDefinition variantCurrentField = (StructDefinition) ((VariantDefinition) variantDef).getCurrentField();
+
+ /*
+ * Try to get the id field in the current field of the
+ * variant. If it is present, it overrides the previously
+ * read event id.
+ */
+ IDefinition vIdDef = variantCurrentField.lookupDefinition("id"); //$NON-NLS-1$
+ if (vIdDef instanceof IntegerDefinition) {
+ simpleIdDef = (SimpleDatatypeDefinition) vIdDef;
+ }
+
+ /*
+ * Get the timestamp. This would overwrite any previous
+ * timestamp definition
+ */
+ timestampDef = variantCurrentField.lookupInteger("timestamp"); //$NON-NLS-1$
+ }
+ if (simpleIdDef != null) {
+ eventID = simpleIdDef.getIntegerValue().intValue();
+ }
+ if (timestampDef != null) {
+ timestamp = calculateTimestamp(timestampDef);
+ } // else timestamp remains 0
+ }
+ }
+ /* Get the right event definition using the event id. */
+ IEventDeclaration eventDeclaration = fStreamInputReader.getStreamInput().getStream().getEventDeclaration(eventID);
+ if (eventDeclaration == null) {
+ throw new CTFReaderException("Incorrect event id : " + eventID); //$NON-NLS-1$
+ }
+ EventDefinition eventDef = eventDeclaration.createDefinition(fStreamInputReader, currentBitBuffer, timestamp);
+
+ /*
+ * Set the event timestamp using the timestamp calculated by
+ * updateTimestamp.
+ */
+
+ if (posStart == currentBitBuffer.position()) {
+ throw new CTFReaderException("Empty event not allowed, event: " + eventDef.getDeclaration().getName()); //$NON-NLS-1$
+ }
+
+ return eventDef;
+ }
+
+ /**
+ * Calculates the timestamp value of the event, possibly using the timestamp
+ * from the last event.
+ *
+ * @param timestampDef
+ * Integer definition of the timestamp.
+ * @return The calculated timestamp value.
+ */
+ private long calculateTimestamp(IntegerDefinition timestampDef) {
+ int len = timestampDef.getDeclaration().getLength();
+ final long value = timestampDef.getValue();
+
+ return calculateTimestamp(value, len);
+ }
+
+ private long calculateTimestamp(final long value, int len) {
+ long newval;
+ long majorasbitmask;
+ /*
+ * If the timestamp length is 64 bits, it is a full timestamp.
+ */
+ if (len == 64) {
+ fLastTimestamp = value;
+ return fLastTimestamp;
+ }
+
+ /*
+ * Bit mask to keep / remove all old / new bits.
+ */
+ majorasbitmask = (1L << len) - 1;
+
+ /*
+ * If the new value is smaller than the corresponding bits of the last
+ * timestamp, we assume an overflow of the compact representation.
+ */
+ newval = value;
+ if (newval < (fLastTimestamp & majorasbitmask)) {
+ newval = newval + (1L << len);
+ }
+
+ /* Keep only the high bits of the old value */
+ fLastTimestamp = fLastTimestamp & ~majorasbitmask;
+
+ /* Then add the low bits of the new value */
+ fLastTimestamp = fLastTimestamp + newval;
+
+ return fLastTimestamp;
+ }
+
+ @Override
+ public Definition lookupDefinition(String lookupPath) {
+ if (lookupPath.equals(LexicalScope.STREAM_PACKET_CONTEXT.toString())) {
+ return (Definition) fCurrentStreamPacketContextDef;
+ }
+ if (lookupPath.equals(LexicalScope.TRACE_PACKET_HEADER.toString())) {
+ return (Definition) fCurrentTracePacketHeaderDef;
+ }
+ return null;
+ }
+
+ /**
+ * Get stream event header
+ *
+ * @return the stream event header
+ * @deprecated use
+ * {@link CTFStreamInputPacketReader#getStreamEventHeaderDefinition()}
+ */
+ @Deprecated
+ public StructDefinition getCurrentStreamEventHeader() {
+ return (StructDefinition) ((fCurrentStreamEventHeaderDef instanceof StructDefinition) ? fCurrentStreamEventHeaderDef : null);
+ }
+
+ /**
+ * Get stream event header
+ *
+ * @return the stream event header
+ * @since 3.1
+ */
+ public ICompositeDefinition getStreamEventHeaderDefinition() {
+ return fCurrentStreamEventHeaderDef;
+ }
+
+ /**
+ * Get the current packet event header
+ *
+ * @return the current packet event header
+ */
+ public StructDefinition getCurrentPacketEventHeader() {
+ if (fCurrentTracePacketHeaderDef instanceof StructDefinition) {
+ return (StructDefinition) fCurrentTracePacketHeaderDef;
+ }
+ return null;
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.trace;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.ByteOrder;
+import java.nio.channels.FileChannel;
+import java.nio.file.StandardOpenOption;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.EventDefinition;
+import org.eclipse.tracecompass.ctf.core.event.IEventDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+import org.eclipse.tracecompass.internal.ctf.core.Activator;
+import org.eclipse.tracecompass.internal.ctf.core.trace.StreamInputPacketIndexEntry;
+
+import com.google.common.collect.ImmutableList;
+
+/**
+ * A CTF trace event reader. Reads the events of a trace file.
+ *
+ * @author Matthew Khouzam
+ * @author Simon Marchi
+ * @since 3.0
+ */
+public class CTFStreamInputReader implements AutoCloseable {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ /**
+ * The StreamInput we are reading.
+ */
+ private final @NonNull File fFile;
+
+ private final @NonNull CTFStreamInput fStreamInput;
+
+ private final FileChannel fFileChannel;
+
+ /**
+ * The packet reader used to read packets from this trace file.
+ */
+ private final CTFStreamInputPacketReader fPacketReader;
+
+ /**
+ * Iterator on the packet index
+ */
+ private int fPacketIndex;
+
+ /**
+ * Reference to the current event of this trace file (iow, the last on that
+ * was read, the next one to be returned)
+ */
+ private EventDefinition fCurrentEvent = null;
+
+ private int fId;
+
+ private CTFTraceReader fParent;
+
+ /**
+ * Live trace reading
+ */
+ private boolean fLive = false;
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+ /**
+ * Constructs a StreamInputReader that reads a StreamInput.
+ *
+ * @param streamInput
+ * The StreamInput to read.
+ * @throws CTFReaderException
+ * If the file cannot be opened
+ */
+ public CTFStreamInputReader(CTFStreamInput streamInput) throws CTFReaderException {
+ if (streamInput == null) {
+ throw new IllegalArgumentException("stream cannot be null"); //$NON-NLS-1$
+ }
+ fStreamInput = streamInput;
+ fFile = fStreamInput.getFile();
+ try {
+ fFileChannel = FileChannel.open(fFile.toPath(), StandardOpenOption.READ);
+ } catch (IOException e) {
+ throw new CTFReaderException(e);
+ }
+ fPacketReader = new CTFStreamInputPacketReader(this);
+ /*
+ * Get the iterator on the packet index.
+ */
+ fPacketIndex = 0;
+ /*
+ * Make first packet the current one.
+ */
+ goToNextPacket();
+ }
+
+ /**
+ * Dispose the StreamInputReader, closes the file channel and its packet
+ * reader
+ *
+ * @throws IOException
+ * If an I/O error occurs
+ */
+ @Override
+ public void close() throws IOException {
+ fFileChannel.close();
+ fPacketReader.close();
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ /**
+ * Gets the current event in this stream
+ *
+ * @return the current event in the stream, null if the stream is
+ * finished/empty/malformed
+ */
+ public EventDefinition getCurrentEvent() {
+ return fCurrentEvent;
+ }
+
+ /**
+ * Gets the byte order for a trace
+ *
+ * @return the trace byte order
+ */
+ public ByteOrder getByteOrder() {
+ return fStreamInput.getStream().getTrace().getByteOrder();
+ }
+
+ /**
+ * Gets the name of the stream (it's an id and a number)
+ *
+ * @return gets the stream name (it's a number)
+ */
+ public int getName() {
+ return fId;
+ }
+
+ /**
+ * Sets the name of the stream
+ *
+ * @param name
+ * the name of the stream, (it's a number)
+ */
+ public void setName(int name) {
+ fId = name;
+ }
+
+ /**
+ * Gets the CPU of a stream. It's the same as the one in /proc or running
+ * the asm CPUID instruction
+ *
+ * @return The CPU id (a number)
+ */
+ public int getCPU() {
+ return fPacketReader.getCPU();
+ }
+
+ /**
+ * Gets the filename of the stream being read
+ *
+ * @return The filename of the stream being read
+ */
+ public String getFilename() {
+ return fStreamInput.getFilename();
+ }
+
+ /*
+ * for internal use only
+ */
+ CTFStreamInput getStreamInput() {
+ return fStreamInput;
+ }
+
+ /**
+ * Gets the event definition set for this StreamInput
+ *
+ * @return Unmodifiable set with the event definitions
+ */
+ public Iterable<IEventDeclaration> getEventDeclarations() {
+ return ImmutableList.copyOf(fStreamInput.getStream().getEventDeclarations());
+ }
+
+ /**
+ * Set the trace to live mode
+ *
+ * @param live
+ * whether the trace is read live or not
+ */
+ public void setLive(boolean live) {
+ fLive = live;
+ }
+
+ /**
+ * Get if the trace is to read live or not
+ *
+ * @return whether the trace is live or not
+ */
+ public boolean isLive() {
+ return fLive;
+ }
+
+ /**
+ * Get the event context of the stream
+ *
+ * @return the event context declaration of the stream
+ */
+ public StructDeclaration getStreamEventContextDecl() {
+ return getStreamInput().getStream().getEventContextDecl();
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+ /**
+ * Reads the next event in the current event variable.
+ *
+ * @return If an event has been successfully read.
+ * @throws CTFReaderException
+ * if an error occurs
+ */
+ public CTFResponse readNextEvent() throws CTFReaderException {
+
+ /*
+ * Change packet if needed
+ */
+ if (!fPacketReader.hasMoreEvents()) {
+ final StreamInputPacketIndexEntry prevPacket = fPacketReader
+ .getCurrentPacket();
+ if (prevPacket != null || fLive) {
+ goToNextPacket();
+ }
+
+ }
+
+ /*
+ * If an event is available, read it.
+ */
+ if (fPacketReader.hasMoreEvents()) {
+ setCurrentEvent(fPacketReader.readNextEvent());
+ return CTFResponse.OK;
+ }
+ this.setCurrentEvent(null);
+ return fLive ? CTFResponse.WAIT : CTFResponse.FINISH;
+ }
+
+ /**
+ * Change the current packet of the packet reader to the next one.
+ *
+ * @throws CTFReaderException
+ * if an error occurs
+ */
+ private void goToNextPacket() throws CTFReaderException {
+ fPacketIndex++;
+ // did we already index the packet?
+ if (getPacketSize() >= (fPacketIndex + 1)) {
+ fPacketReader.setCurrentPacket(getPacket());
+ } else {
+ // go to the next packet if there is one, index it at the same time
+ if (fStreamInput.addPacketHeaderIndex()) {
+ fPacketIndex = getPacketSize() - 1;
+ fPacketReader.setCurrentPacket(getPacket());
+ } else {
+ // out of packets
+ fPacketReader.setCurrentPacket(null);
+ }
+ }
+ }
+
+ /**
+ * @return
+ */
+ private int getPacketSize() {
+ return fStreamInput.getIndex().getEntries().size();
+ }
+
+ /**
+ * Changes the location of the trace file reader so that the current event
+ * is the first event with a timestamp greater or equal the given timestamp.
+ *
+ * @param timestamp
+ * The timestamp to seek to.
+ * @return The offset compared to the current position
+ * @throws CTFReaderException
+ * if an error occurs
+ */
+ public long seek(long timestamp) throws CTFReaderException {
+ long offset = 0;
+
+ gotoPacket(timestamp);
+
+ /*
+ * index up to the desired timestamp.
+ */
+ while ((fPacketReader.getCurrentPacket() != null)
+ && (fPacketReader.getCurrentPacket().getTimestampEnd() < timestamp)) {
+ try {
+ fStreamInput.addPacketHeaderIndex();
+ goToNextPacket();
+ } catch (CTFReaderException e) {
+ // do nothing here
+ Activator.log(e.getMessage());
+ }
+ }
+ if (fPacketReader.getCurrentPacket() == null) {
+ gotoPacket(timestamp);
+ }
+
+ /*
+ * Advance until either of these conditions are met:
+ *
+ * - reached the end of the trace file (the given timestamp is after the
+ * last event)
+ *
+ * - found the first event with a timestamp greater or equal the given
+ * timestamp.
+ */
+ readNextEvent();
+ boolean done = (this.getCurrentEvent() == null);
+ while (!done && (this.getCurrentEvent().getTimestamp() < timestamp)) {
+ readNextEvent();
+ done = (this.getCurrentEvent() == null);
+ offset++;
+ }
+ return offset;
+ }
+
+ /**
+ * @param timestamp
+ * the time to seek
+ * @throws CTFReaderException
+ * if an error occurs
+ */
+ private void gotoPacket(long timestamp) throws CTFReaderException {
+ fPacketIndex = fStreamInput.getIndex().search(timestamp)
+ .previousIndex();
+ /*
+ * Switch to this packet.
+ */
+ goToNextPacket();
+ }
+
+ /**
+ * Seeks the last event of a stream and returns it.
+ *
+ * @throws CTFReaderException
+ * if an error occurs
+ */
+ public void goToLastEvent() throws CTFReaderException {
+ /*
+ * Search in the index for the packet to search in.
+ */
+ final int len = fStreamInput.getIndex().getEntries().size();
+
+ /*
+ * Go to beginning of trace.
+ */
+ seek(0);
+ /*
+ * if the trace is empty.
+ */
+ if ((len == 0) || (fPacketReader.hasMoreEvents() == false)) {
+ /*
+ * This means the trace is empty. abort.
+ */
+ return;
+ }
+ /*
+ * Go to the last packet that contains events.
+ */
+ for (int pos = len - 1; pos > 0; pos--) {
+ fPacketIndex = pos;
+ fPacketReader.setCurrentPacket(getPacket());
+ if (fPacketReader.hasMoreEvents()) {
+ break;
+ }
+ }
+
+ /*
+ * Go until the end of that packet
+ */
+ EventDefinition prevEvent = null;
+ while (fCurrentEvent != null) {
+ prevEvent = fCurrentEvent;
+ this.readNextEvent();
+ }
+ /*
+ * Go back to the previous event
+ */
+ this.setCurrentEvent(prevEvent);
+ }
+
+ /**
+ * @return the parent
+ */
+ public CTFTraceReader getParent() {
+ return fParent;
+ }
+
+ /**
+ * @param parent
+ * the parent to set
+ */
+ public void setParent(CTFTraceReader parent) {
+ fParent = parent;
+ }
+
+ /**
+ * Sets the current event in a stream input reader
+ *
+ * @param currentEvent
+ * the event to set
+ */
+ public void setCurrentEvent(EventDefinition currentEvent) {
+ fCurrentEvent = currentEvent;
+ }
+
+ /**
+ * @return the packetIndexIt
+ */
+ private int getPacketIndex() {
+ return fPacketIndex;
+ }
+
+ private StreamInputPacketIndexEntry getPacket() {
+ return fStreamInput.getIndex().getEntries().get(getPacketIndex());
+ }
+
+ /**
+ * Get the file channel wrapped by this reader
+ *
+ * @return the file channel
+ */
+ FileChannel getFc() {
+ return fFileChannel;
+ }
+
+ /**
+ * @return the packetReader
+ */
+ public CTFStreamInputPacketReader getPacketReader() {
+ return fPacketReader;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = (prime * result) + fId;
+ result = (prime * result)
+ + fFile.hashCode();
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (!(obj instanceof CTFStreamInputReader)) {
+ return false;
+ }
+ CTFStreamInputReader other = (CTFStreamInputReader) obj;
+ if (fId != other.fId) {
+ return false;
+ }
+ return fFile.equals(other.fFile);
+ }
+
+ @Override
+ public String toString() {
+ // this helps debugging
+ return fId + ' ' + fCurrentEvent.toString();
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ * Alexandre Montplaisir - Initial API and implementation
+ * Simon Delisle - Replace LinkedList by TreeSet in callsitesByName attribute
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.trace;
+
+import java.io.File;
+import java.io.FileFilter;
+import java.io.IOException;
+import java.io.Serializable;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.channels.FileChannel;
+import java.nio.channels.FileChannel.MapMode;
+import java.nio.file.StandardOpenOption;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.UUID;
+
+import org.eclipse.tracecompass.ctf.core.event.CTFCallsite;
+import org.eclipse.tracecompass.ctf.core.event.CTFClock;
+import org.eclipse.tracecompass.ctf.core.event.IEventDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.event.scope.LexicalScope;
+import org.eclipse.tracecompass.ctf.core.event.types.Definition;
+import org.eclipse.tracecompass.ctf.core.event.types.IDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDefinition;
+import org.eclipse.tracecompass.internal.ctf.core.SafeMappedByteBuffer;
+import org.eclipse.tracecompass.internal.ctf.core.event.CTFCallsiteComparator;
+import org.eclipse.tracecompass.internal.ctf.core.event.metadata.exceptions.ParseException;
+import org.eclipse.tracecompass.internal.ctf.core.event.types.ArrayDefinition;
+
+/**
+ * A CTF trace on the file system.
+ *
+ * Represents a trace on the filesystem. It is responsible of parsing the
+ * metadata, creating declarations data structures, indexing the event packets
+ * (in other words, all the work that can be shared between readers), but the
+ * actual reading of events is left to TraceReader.
+ *
+ * @author Matthew Khouzam
+ * @version $Revision: 1.0 $
+ */
+public class CTFTrace implements IDefinitionScope, AutoCloseable {
+
+ @Override
+ public String toString() {
+ /* Only for debugging, shouldn't be externalized */
+ return "CTFTrace [path=" + fPath + ", major=" + fMajor + ", minor=" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ + fMinor + ", uuid=" + fUuid + "]"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /**
+ * The trace directory on the filesystem.
+ */
+ private final File fPath;
+
+ /**
+ * Major CTF version number
+ */
+ private Long fMajor;
+
+ /**
+ * Minor CTF version number
+ */
+ private Long fMinor;
+
+ /**
+ * Trace UUID
+ */
+ private UUID fUuid;
+
+ /**
+ * Trace byte order
+ */
+ private ByteOrder fByteOrder;
+
+ /**
+ * Packet header structure declaration
+ */
+ private StructDeclaration fPacketHeaderDecl = null;
+
+ /**
+ * The clock of the trace
+ */
+ private CTFClock fSingleClock = null;
+
+ /**
+ * Packet header structure definition
+ *
+ * This is only used when opening the trace files, to read the first packet
+ * header and see if they are valid trace files.
+ */
+ private StructDefinition fPacketHeaderDef;
+
+ /**
+ * Collection of streams contained in the trace.
+ */
+ private final Map<Long, CTFStream> fStreams = new HashMap<>();
+
+ /**
+ * Collection of environment variables set by the tracer
+ */
+ private final Map<String, String> fEnvironment = new HashMap<>();
+
+ /**
+ * Collection of all the clocks in a system.
+ */
+ private final Map<String, CTFClock> fClocks = new HashMap<>();
+
+ /** Handlers for the metadata files */
+ private static final FileFilter METADATA_FILE_FILTER = new MetadataFileFilter();
+ private static final Comparator<File> METADATA_COMPARATOR = new MetadataComparator();
+
+ /** Callsite helpers */
+ private CTFCallsiteComparator fCtfCallsiteComparator = new CTFCallsiteComparator();
+
+ private Map<String, TreeSet<CTFCallsite>> fCallsitesByName = new HashMap<>();
+
+ /** Callsite helpers */
+ private TreeSet<CTFCallsite> fCallsitesByIP = new TreeSet<>();
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Trace constructor.
+ *
+ * @param path
+ * Filesystem path of the trace directory
+ * @throws CTFReaderException
+ * If no CTF trace was found at the path
+ */
+ public CTFTrace(String path) throws CTFReaderException {
+ this(new File(path));
+
+ }
+
+ /**
+ * Trace constructor.
+ *
+ * @param path
+ * Filesystem path of the trace directory.
+ * @throws CTFReaderException
+ * If no CTF trace was found at the path
+ */
+ public CTFTrace(File path) throws CTFReaderException {
+ fPath = path;
+ final Metadata metadata = new Metadata(this);
+
+ /* Set up the internal containers for this trace */
+ if (!fPath.exists()) {
+ throw new CTFReaderException("Trace (" + path.getPath() + ") doesn't exist. Deleted or moved?"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ if (!fPath.isDirectory()) {
+ throw new CTFReaderException("Path must be a valid directory"); //$NON-NLS-1$
+ }
+
+ /* Open and parse the metadata file */
+ metadata.parseFile();
+
+ init(path);
+ }
+
+ /**
+ * Streamed constructor
+ *
+ * @since 3.0
+ */
+ public CTFTrace() {
+ fPath = null;
+ }
+
+ private void init(File path) throws CTFReaderException {
+
+ /* Open all the trace files */
+
+ /* List files not called metadata and not hidden. */
+ File[] files = path.listFiles(METADATA_FILE_FILTER);
+ Arrays.sort(files, METADATA_COMPARATOR);
+
+ /* Try to open each file */
+ for (File streamFile : files) {
+ openStreamInput(streamFile);
+ }
+
+ /* Create their index */
+ for (CTFStream stream : getStreams()) {
+ Set<CTFStreamInput> inputs = stream.getStreamInputs();
+ for (CTFStreamInput s : inputs) {
+ addStream(s);
+ }
+ }
+ }
+
+ /**
+ * Dispose the trace
+ *
+ * FIXME Not needed anymore, class doesn't need to be AutoCloseable.
+ *
+ * @since 3.0
+ */
+ @Override
+ public void close() {
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ /**
+ * Gets an event declaration hash map for a given streamID
+ *
+ * @param streamId
+ * The ID of the stream from which to read
+ * @return The Hash map with the event declarations
+ * @since 2.0
+ * @deprecated use {@link CTFTrace#getEventDeclarations(Long)}
+ */
+ @Deprecated
+ public Map<Long, IEventDeclaration> getEvents(Long streamId) {
+ return fStreams.get(streamId).getEvents();
+ }
+
+ /**
+ * Gets an event declaration list for a given streamID
+ *
+ * @param streamId
+ * The ID of the stream from which to read
+ * @return The list of event declarations
+ * @since 3.2
+ */
+ public Collection<IEventDeclaration> getEventDeclarations(Long streamId) {
+ return fStreams.get(streamId).getEventDeclarations();
+ }
+
+ /**
+ * Get an event by it's ID
+ *
+ * @param streamId
+ * The ID of the stream from which to read
+ * @param id
+ * the ID of the event
+ * @return the event declaration
+ * @since 2.0
+ * @deprecated use {@link CTFTrace#getEventType(long, int)} instead
+ */
+ @Deprecated
+ public IEventDeclaration getEventType(long streamId, long id) {
+ return getStream(streamId).getEventDeclaration((int) id);
+ }
+
+ /**
+ * Get an event by it's ID
+ *
+ * @param streamId
+ * The ID of the stream from which to read
+ * @param id
+ * the ID of the event
+ * @return the event declaration
+ * @since 3.2
+ */
+ public IEventDeclaration getEventType(long streamId, int id) {
+ return getEvents(streamId).get(id);
+ }
+
+ /**
+ * Method getStream gets the stream for a given id
+ *
+ * @param id
+ * Long the id of the stream
+ * @return Stream the stream that we need
+ * @since 3.0
+ */
+ public CTFStream getStream(Long id) {
+ return fStreams.get(id);
+ }
+
+ /**
+ * Method nbStreams gets the number of available streams
+ *
+ * @return int the number of streams
+ */
+ public int nbStreams() {
+ return fStreams.size();
+ }
+
+ /**
+ * Method setMajor sets the major version of the trace (DO NOT USE)
+ *
+ * @param major
+ * long the major version
+ */
+ public void setMajor(long major) {
+ fMajor = major;
+ }
+
+ /**
+ * Method setMinor sets the minor version of the trace (DO NOT USE)
+ *
+ * @param minor
+ * long the minor version
+ */
+ public void setMinor(long minor) {
+ fMinor = minor;
+ }
+
+ /**
+ * Method setUUID sets the UUID of a trace
+ *
+ * @param uuid
+ * UUID
+ */
+ public void setUUID(UUID uuid) {
+ fUuid = uuid;
+ }
+
+ /**
+ * Method setByteOrder sets the byte order
+ *
+ * @param byteOrder
+ * ByteOrder of the trace, can be little-endian or big-endian
+ */
+ public void setByteOrder(ByteOrder byteOrder) {
+ fByteOrder = byteOrder;
+ }
+
+ /**
+ * Method setPacketHeader sets the packet header of a trace (DO NOT USE)
+ *
+ * @param packetHeader
+ * StructDeclaration the header in structdeclaration form
+ */
+ public void setPacketHeader(StructDeclaration packetHeader) {
+ fPacketHeaderDecl = packetHeader;
+ }
+
+ /**
+ * Method majorIsSet is the major version number set?
+ *
+ * @return boolean is the major set?
+ * @since 3.0
+ */
+ public boolean majorIsSet() {
+ return fMajor != null;
+ }
+
+ /**
+ * Method minorIsSet. is the minor version number set?
+ *
+ * @return boolean is the minor set?
+ */
+ public boolean minorIsSet() {
+ return fMinor != null;
+ }
+
+ /**
+ * Method UUIDIsSet is the UUID set?
+ *
+ * @return boolean is the UUID set?
+ * @since 2.0
+ */
+ public boolean uuidIsSet() {
+ return fUuid != null;
+ }
+
+ /**
+ * Method byteOrderIsSet is the byteorder set?
+ *
+ * @return boolean is the byteorder set?
+ */
+ public boolean byteOrderIsSet() {
+ return fByteOrder != null;
+ }
+
+ /**
+ * Method packetHeaderIsSet is the packet header set?
+ *
+ * @return boolean is the packet header set?
+ */
+ public boolean packetHeaderIsSet() {
+ return fPacketHeaderDecl != null;
+ }
+
+ /**
+ * Method getUUID gets the trace UUID
+ *
+ * @return UUID gets the trace UUID
+ */
+ public UUID getUUID() {
+ return fUuid;
+ }
+
+ /**
+ * Method getMajor gets the trace major version
+ *
+ * @return long gets the trace major version
+ */
+ public long getMajor() {
+ return fMajor;
+ }
+
+ /**
+ * Method getMinor gets the trace minor version
+ *
+ * @return long gets the trace minor version
+ */
+ public long getMinor() {
+ return fMinor;
+ }
+
+ /**
+ * Method getByteOrder gets the trace byte order
+ *
+ * @return ByteOrder gets the trace byte order
+ */
+ public final ByteOrder getByteOrder() {
+ return fByteOrder;
+ }
+
+ /**
+ * Method getPacketHeader gets the trace packet header
+ *
+ * @return StructDeclaration gets the trace packet header
+ */
+ public StructDeclaration getPacketHeader() {
+ return fPacketHeaderDecl;
+ }
+
+ /**
+ * Method getTraceDirectory gets the trace directory
+ *
+ * @return File the path in "File" format.
+ */
+ public File getTraceDirectory() {
+ return fPath;
+ }
+
+ /**
+ * Get all the streams as an iterable.
+ *
+ * @return Iterable<Stream> an iterable over streams.
+ * @since 3.0
+ */
+ public Iterable<CTFStream> getStreams() {
+ return fStreams.values();
+ }
+
+ /**
+ * Method getPath gets the path of the trace directory
+ *
+ * @return String the path of the trace directory, in string format.
+ * @see java.io.File#getPath()
+ */
+ public String getPath() {
+ return (fPath != null) ? fPath.getPath() : ""; //$NON-NLS-1$
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ private void addStream(CTFStreamInput s) {
+
+ /*
+ * add the stream
+ */
+ CTFStream stream = s.getStream();
+ fStreams.put(stream.getId(), stream);
+
+ /*
+ * index the trace
+ */
+ s.setupIndex();
+ }
+
+ /**
+ * Tries to open the given file, reads the first packet header of the file
+ * and check its validity. This will add a file to a stream as a streaminput
+ *
+ * @param streamFile
+ * A trace file in the trace directory.
+ * @param index
+ * Which index in the class' streamFileChannel array this file
+ * must use
+ * @throws CTFReaderException
+ * if there is a file error
+ */
+ private CTFStream openStreamInput(File streamFile) throws CTFReaderException {
+ ByteBuffer byteBuffer;
+ BitBuffer streamBitBuffer;
+ CTFStream stream;
+
+ if (!streamFile.canRead()) {
+ throw new CTFReaderException("Unreadable file : " //$NON-NLS-1$
+ + streamFile.getPath());
+ }
+
+ try (FileChannel fc = FileChannel.open(streamFile.toPath(), StandardOpenOption.READ)) {
+ /* Map one memory page of 4 kiB */
+ byteBuffer = SafeMappedByteBuffer.map(fc, MapMode.READ_ONLY, 0, (int) Math.min(fc.size(), 4096L));
+ if (byteBuffer == null) {
+ throw new IllegalStateException("Failed to allocate memory"); //$NON-NLS-1$
+ }
+ /* Create a BitBuffer with this mapping and the trace byte order */
+ streamBitBuffer = new BitBuffer(byteBuffer, this.getByteOrder());
+
+ if (fPacketHeaderDecl != null) {
+ /* Read the packet header */
+ fPacketHeaderDef = fPacketHeaderDecl.createDefinition(this, LexicalScope.PACKET_HEADER, streamBitBuffer);
+ }
+ } catch (IOException e) {
+ /* Shouldn't happen at this stage if every other check passed */
+ throw new CTFReaderException(e);
+ }
+ if (fPacketHeaderDef != null) {
+ validateMagicNumber(fPacketHeaderDef);
+
+ validateUUID(fPacketHeaderDef);
+
+ /* Read the stream ID */
+ IDefinition streamIDDef = fPacketHeaderDef.lookupDefinition("stream_id"); //$NON-NLS-1$
+
+ if (streamIDDef instanceof IntegerDefinition) {
+ /* This doubles as a null check */
+ long streamID = ((IntegerDefinition) streamIDDef).getValue();
+ stream = fStreams.get(streamID);
+ } else {
+ /* No stream_id in the packet header */
+ stream = fStreams.get(null);
+ }
+
+ } else {
+ /* No packet header, we suppose there is only one stream */
+ stream = fStreams.get(null);
+ }
+
+ if (stream == null) {
+ throw new CTFReaderException("Unexpected end of stream"); //$NON-NLS-1$
+ }
+
+ /*
+ * Create the stream input and add a reference to the streamInput in the
+ * stream.
+ */
+ stream.addInput(new CTFStreamInput(stream, streamFile));
+ return stream;
+ }
+
+ private void validateUUID(StructDefinition packetHeaderDef) throws CTFReaderException {
+ IDefinition lookupDefinition = packetHeaderDef.lookupDefinition("uuid"); //$NON-NLS-1$
+ ArrayDefinition uuidDef = (ArrayDefinition) lookupDefinition;
+ if (uuidDef != null) {
+ UUID otheruuid = Utils.getUUIDfromDefinition(uuidDef);
+ if (!fUuid.equals(otheruuid)) {
+ throw new CTFReaderException("UUID mismatch"); //$NON-NLS-1$
+ }
+ }
+ }
+
+ private static void validateMagicNumber(StructDefinition packetHeaderDef) throws CTFReaderException {
+ IntegerDefinition magicDef = (IntegerDefinition) packetHeaderDef.lookupDefinition("magic"); //$NON-NLS-1$
+ int magic = (int) magicDef.getValue();
+ if (magic != Utils.CTF_MAGIC) {
+ throw new CTFReaderException("CTF magic mismatch"); //$NON-NLS-1$
+ }
+ }
+
+ // ------------------------------------------------------------------------
+ // IDefinitionScope
+ // ------------------------------------------------------------------------
+
+ /**
+ * @since 3.0
+ */
+ @Override
+ public LexicalScope getScopePath() {
+ return LexicalScope.TRACE;
+ }
+
+ /**
+ * Looks up a definition from packet
+ *
+ * @param lookupPath
+ * String
+ * @return Definition
+ * @see org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope#lookupDefinition(String)
+ */
+ @Override
+ public Definition lookupDefinition(String lookupPath) {
+ if (lookupPath.equals(LexicalScope.TRACE_PACKET_HEADER.toString())) {
+ return fPacketHeaderDef;
+ }
+ return null;
+ }
+
+ // ------------------------------------------------------------------------
+ // Live trace reading
+ // ------------------------------------------------------------------------
+
+ /**
+ * Add a new stream file to support new streams while the trace is being
+ * read.
+ *
+ * @param streamFile
+ * the file of the stream
+ * @throws CTFReaderException
+ * A stream had an issue being read
+ * @since 3.0
+ */
+ public void addStreamFile(File streamFile) throws CTFReaderException {
+ openStreamInput(streamFile);
+ }
+
+ /**
+ * Registers a new stream to the trace.
+ *
+ * @param stream
+ * A stream object.
+ * @throws ParseException
+ * If there was some problem reading the metadata
+ * @since 3.0
+ */
+ public void addStream(CTFStream stream) throws ParseException {
+ /*
+ * If there is already a stream without id (the null key), it must be
+ * the only one
+ */
+ if (fStreams.get(null) != null) {
+ throw new ParseException("Stream without id with multiple streams"); //$NON-NLS-1$
+ }
+
+ /*
+ * If the stream we try to add has the null key, it must be the only
+ * one. Thus, if the streams container is not empty, it is not valid.
+ */
+ if ((stream.getId() == null) && (fStreams.size() != 0)) {
+ throw new ParseException("Stream without id with multiple streams"); //$NON-NLS-1$
+ }
+
+ /*
+ * If a stream with the same ID already exists, it is not valid.
+ */
+ CTFStream existingStream = fStreams.get(stream.getId());
+ if (existingStream != null) {
+ throw new ParseException("Stream id already exists"); //$NON-NLS-1$
+ }
+
+ /* This stream is valid and has a unique id. */
+ fStreams.put(stream.getId(), stream);
+ }
+
+ /**
+ * Gets the Environment variables from the trace metadata (See CTF spec)
+ *
+ * @return The environment variables in the form of an unmodifiable map
+ * (key, value)
+ * @since 2.0
+ */
+ public Map<String, String> getEnvironment() {
+ return Collections.unmodifiableMap(fEnvironment);
+ }
+
+ /**
+ * Add a variable to the environment variables
+ *
+ * @param varName
+ * the name of the variable
+ * @param varValue
+ * the value of the variable
+ */
+ public void addEnvironmentVar(String varName, String varValue) {
+ fEnvironment.put(varName, varValue);
+ }
+
+ /**
+ * Add a clock to the clock list
+ *
+ * @param nameValue
+ * the name of the clock (full name with scope)
+ * @param ctfClock
+ * the clock
+ */
+ public void addClock(String nameValue, CTFClock ctfClock) {
+ fClocks.put(nameValue, ctfClock);
+ }
+
+ /**
+ * gets the clock with a specific name
+ *
+ * @param name
+ * the name of the clock.
+ * @return the clock
+ */
+ public CTFClock getClock(String name) {
+ return fClocks.get(name);
+ }
+
+ /**
+ * gets the clock if there is only one. (this is 100% of the use cases as of
+ * June 2012)
+ *
+ * @return the clock
+ */
+ public final CTFClock getClock() {
+ if (fSingleClock != null && fClocks.size() == 1) {
+ return fSingleClock;
+ }
+ if (fClocks.size() == 1) {
+ fSingleClock = fClocks.get(fClocks.keySet().iterator().next());
+ return fSingleClock;
+ }
+ return null;
+ }
+
+ /**
+ * gets the time offset of a clock with respect to UTC in nanoseconds
+ *
+ * @return the time offset of a clock with respect to UTC in nanoseconds
+ */
+ public final long getOffset() {
+ if (getClock() == null) {
+ return 0;
+ }
+ return fSingleClock.getClockOffset();
+ }
+
+ /**
+ * gets the time offset of a clock with respect to UTC in nanoseconds
+ *
+ * @return the time offset of a clock with respect to UTC in nanoseconds
+ */
+ private double getTimeScale() {
+ if (getClock() == null) {
+ return 1.0;
+ }
+ return fSingleClock.getClockScale();
+ }
+
+ /**
+ * Gets the current first packet start time
+ *
+ * @return the current start time
+ * @since 3.0
+ */
+ public long getCurrentStartTime() {
+ long currentStart = Long.MAX_VALUE;
+ for (CTFStream stream : fStreams.values()) {
+ for (CTFStreamInput si : stream.getStreamInputs()) {
+ currentStart = Math.min(currentStart, si.getIndex().getEntries().get(0).getTimestampBegin());
+ }
+ }
+ return timestampCyclesToNanos(currentStart);
+ }
+
+ /**
+ * Gets the current last packet end time
+ *
+ * @return the current end time
+ * @since 3.0
+ */
+ public long getCurrentEndTime() {
+ long currentEnd = Long.MIN_VALUE;
+ for (CTFStream stream : fStreams.values()) {
+ for (CTFStreamInput si : stream.getStreamInputs()) {
+ currentEnd = Math.max(currentEnd, si.getTimestampEnd());
+ }
+ }
+ return timestampCyclesToNanos(currentEnd);
+ }
+
+ /**
+ * Does the trace need to time scale?
+ *
+ * @return if the trace is in ns or cycles.
+ */
+ private boolean clockNeedsScale() {
+ if (getClock() == null) {
+ return false;
+ }
+ return fSingleClock.isClockScaled();
+ }
+
+ /**
+ * the inverse clock for returning to a scale.
+ *
+ * @return 1.0 / scale
+ */
+ private double getInverseTimeScale() {
+ if (getClock() == null) {
+ return 1.0;
+ }
+ return fSingleClock.getClockAntiScale();
+ }
+
+ /**
+ * @param cycles
+ * clock cycles since boot
+ * @return time in nanoseconds UTC offset
+ * @since 2.0
+ */
+ public long timestampCyclesToNanos(long cycles) {
+ long retVal = cycles + getOffset();
+ /*
+ * this fix is since quite often the offset will be > than 53 bits and
+ * therefore the conversion will be lossy
+ */
+ if (clockNeedsScale()) {
+ retVal = (long) (retVal * getTimeScale());
+ }
+ return retVal;
+ }
+
+ /**
+ * @param nanos
+ * time in nanoseconds UTC offset
+ * @return clock cycles since boot.
+ * @since 2.0
+ */
+ public long timestampNanoToCycles(long nanos) {
+ long retVal;
+ /*
+ * this fix is since quite often the offset will be > than 53 bits and
+ * therefore the conversion will be lossy
+ */
+ if (clockNeedsScale()) {
+ retVal = (long) (nanos * getInverseTimeScale());
+ } else {
+ retVal = nanos;
+ }
+ return retVal - getOffset();
+ }
+
+ /**
+ * Adds a callsite
+ *
+ * @param eventName
+ * the event name of the callsite
+ * @param funcName
+ * the name of the callsite function
+ * @param ip
+ * the ip of the callsite
+ * @param fileName
+ * the filename of the callsite
+ * @param lineNumber
+ * the line number of the callsite
+ */
+ public void addCallsite(String eventName, String funcName, long ip,
+ String fileName, long lineNumber) {
+ final CTFCallsite cs = new CTFCallsite(eventName, funcName, ip,
+ fileName, lineNumber);
+ TreeSet<CTFCallsite> csl = fCallsitesByName.get(eventName);
+ if (csl == null) {
+ csl = new TreeSet<>(fCtfCallsiteComparator);
+ fCallsitesByName.put(eventName, csl);
+ }
+
+ csl.add(cs);
+
+ fCallsitesByIP.add(cs);
+ }
+
+ /**
+ * Gets the set of callsites associated to an event name. O(1)
+ *
+ * @param eventName
+ * the event name
+ * @return the callsite set can be empty
+ * @since 3.0
+ */
+ public TreeSet<CTFCallsite> getCallsiteCandidates(String eventName) {
+ TreeSet<CTFCallsite> retVal = fCallsitesByName.get(eventName);
+ if (retVal == null) {
+ retVal = new TreeSet<>(fCtfCallsiteComparator);
+ }
+ return retVal;
+ }
+
+ /**
+ * The I'm feeling lucky of getCallsiteCandidates O(1)
+ *
+ * @param eventName
+ * the event name
+ * @return the first callsite that has that event name, can be null
+ * @since 1.2
+ */
+ public CTFCallsite getCallsite(String eventName) {
+ TreeSet<CTFCallsite> callsites = fCallsitesByName.get(eventName);
+ if (callsites != null) {
+ return callsites.first();
+ }
+ return null;
+ }
+
+ /**
+ * Gets a callsite from the instruction pointer O(log(n))
+ *
+ * @param ip
+ * the instruction pointer to lookup
+ * @return the callsite just before that IP in the list remember the IP is
+ * backwards on X86, can be null if no callsite is before the IP.
+ * @since 1.2
+ */
+ public CTFCallsite getCallsite(long ip) {
+ CTFCallsite cs = new CTFCallsite(null, null, ip, null, 0L);
+ return fCallsitesByIP.ceiling(cs);
+ }
+
+ /**
+ * Gets a callsite using the event name and instruction pointer O(log(n))
+ *
+ * @param eventName
+ * the name of the event
+ * @param ip
+ * the instruction pointer
+ * @return the closest matching callsite, can be null
+ */
+ public CTFCallsite getCallsite(String eventName, long ip) {
+ final TreeSet<CTFCallsite> candidates = fCallsitesByName.get(eventName);
+ if (candidates == null) {
+ return null;
+ }
+ final CTFCallsite dummyCs = new CTFCallsite(null, null, ip, null, -1);
+ final CTFCallsite callsite = candidates.ceiling(dummyCs);
+ if (callsite == null) {
+ return candidates.floor(dummyCs);
+ }
+ return callsite;
+ }
+
+ /**
+ * Add a new stream
+ *
+ * @param id
+ * the ID of the stream
+ * @param streamFile
+ * new file in the stream
+ * @throws CTFReaderException
+ * The file must exist
+ * @since 3.0
+ */
+ // TODO: remove suppress warning
+ @SuppressWarnings("resource")
+ public void addStream(long id, File streamFile) throws CTFReaderException {
+ CTFStream stream = null;
+ final File file = streamFile;
+ if (file == null) {
+ throw new CTFReaderException("cannot create a stream with no file"); //$NON-NLS-1$
+ }
+ if (fStreams.containsKey(id)) {
+ stream = fStreams.get(id);
+ } else {
+ stream = new CTFStream(this);
+ fStreams.put(id, stream);
+ }
+ stream.addInput(new CTFStreamInput(stream, file));
+ }
+}
+
+class MetadataFileFilter implements FileFilter {
+
+ @Override
+ public boolean accept(File pathname) {
+ if (pathname.isDirectory()) {
+ return false;
+ }
+ if (pathname.isHidden()) {
+ return false;
+ }
+ if (pathname.getName().equals("metadata")) { //$NON-NLS-1$
+ return false;
+ }
+ return true;
+ }
+
+}
+
+class MetadataComparator implements Comparator<File>, Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public int compare(File o1, File o2) {
+ return o1.getName().compareTo(o2.getName());
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ * Alexandre Montplaisir - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.trace;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.PriorityQueue;
+import java.util.Set;
+
+import org.eclipse.tracecompass.ctf.core.event.EventDefinition;
+import org.eclipse.tracecompass.ctf.core.event.IEventDeclaration;
+import org.eclipse.tracecompass.internal.ctf.core.Activator;
+import org.eclipse.tracecompass.internal.ctf.core.trace.StreamInputReaderTimestampComparator;
+
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSet.Builder;
+
+/**
+ * A CTF trace reader. Reads the events of a trace.
+ *
+ * @version 1.0
+ * @author Matthew Khouzam
+ * @author Alexandre Montplaisir
+ */
+public class CTFTraceReader implements AutoCloseable {
+
+ private static final int MIN_PRIO_SIZE = 16;
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ /**
+ * The trace to read from.
+ */
+ private final CTFTrace fTrace;
+
+ /**
+ * Vector of all the trace file readers.
+ */
+ private final List<CTFStreamInputReader> fStreamInputReaders = new ArrayList<>();
+
+ /**
+ * Priority queue to order the trace file readers by timestamp.
+ */
+ private PriorityQueue<CTFStreamInputReader> fPrio;
+
+ /**
+ * Array to count the number of event per trace file.
+ */
+ private long[] fEventCountPerTraceFile;
+
+ /**
+ * Timestamp of the first event in the trace
+ */
+ private long fStartTime;
+
+ /**
+ * Timestamp of the last event read so far
+ */
+ private long fEndTime;
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructs a TraceReader to read a trace.
+ *
+ * @param trace
+ * The trace to read from.
+ * @throws CTFReaderException
+ * if an error occurs
+ */
+ public CTFTraceReader(CTFTrace trace) throws CTFReaderException {
+ fTrace = trace;
+ fStreamInputReaders.clear();
+
+ /**
+ * Create the trace file readers.
+ */
+ createStreamInputReaders();
+
+ /**
+ * Populate the timestamp-based priority queue.
+ */
+ populateStreamInputReaderHeap();
+
+ /**
+ * Get the start Time of this trace bear in mind that the trace could be
+ * empty.
+ */
+ fStartTime = 0;
+ if (hasMoreEvents()) {
+ fStartTime = getTopStream().getCurrentEvent().getTimestamp();
+ setEndTime(fStartTime);
+ }
+ }
+
+ /**
+ * Copy constructor
+ *
+ * @return The new CTFTraceReader
+ * @throws CTFReaderException
+ * if an error occurs
+ */
+ public CTFTraceReader copyFrom() throws CTFReaderException {
+ CTFTraceReader newReader = null;
+
+ newReader = new CTFTraceReader(fTrace);
+ newReader.fStartTime = fStartTime;
+ newReader.setEndTime(fEndTime);
+ return newReader;
+ }
+
+ /**
+ * Dispose the CTFTraceReader
+ *
+ * @since 3.0
+ */
+ @Override
+ public void close() {
+ for (CTFStreamInputReader reader : fStreamInputReaders) {
+ if (reader != null) {
+ try {
+ reader.close();
+ } catch (IOException e) {
+ Activator.logError(e.getMessage(), e);
+ }
+ }
+ }
+ fStreamInputReaders.clear();
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ /**
+ * Return the start time of this trace (== timestamp of the first event)
+ *
+ * @return the trace start time
+ */
+ public long getStartTime() {
+ return fStartTime;
+ }
+
+ /**
+ * Set the trace's end time
+ *
+ * @param endTime
+ * The end time to use
+ */
+ protected final void setEndTime(long endTime) {
+ fEndTime = endTime;
+ }
+
+ /**
+ * Get the priority queue of this trace reader.
+ *
+ * @return The priority queue of input readers
+ * @since 2.0
+ */
+ protected PriorityQueue<CTFStreamInputReader> getPrio() {
+ return fPrio;
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ /**
+ * Creates one trace file reader per trace file contained in the trace.
+ *
+ * @throws CTFReaderException
+ * if an error occurs
+ */
+ private void createStreamInputReaders() throws CTFReaderException {
+ /*
+ * For each stream.
+ */
+ for (CTFStream stream : fTrace.getStreams()) {
+ Set<CTFStreamInput> streamInputs = stream.getStreamInputs();
+
+ /*
+ * For each trace file of the stream.
+ */
+ for (CTFStreamInput streamInput : streamInputs) {
+
+ /*
+ * Create a reader and add it to the group.
+ */
+ fStreamInputReaders.add(new CTFStreamInputReader(streamInput));
+ }
+ }
+
+ /*
+ * Create the array to count the number of event per trace file.
+ */
+ fEventCountPerTraceFile = new long[fStreamInputReaders.size()];
+ }
+
+ /**
+ * Update the priority queue to make it match the parent trace
+ *
+ * @throws CTFReaderException
+ * An error occured
+ *
+ * @since 3.0
+ */
+ public void update() throws CTFReaderException {
+ Set<CTFStreamInputReader> readers = new HashSet<>();
+ for (CTFStream stream : fTrace.getStreams()) {
+ Set<CTFStreamInput> streamInputs = stream.getStreamInputs();
+ for (CTFStreamInput streamInput : streamInputs) {
+ /*
+ * Create a reader.
+ */
+ CTFStreamInputReader streamInputReader = new CTFStreamInputReader(
+ streamInput);
+
+ /*
+ * Add it to the group.
+ */
+ if (!fStreamInputReaders.contains(streamInputReader)) {
+ streamInputReader.readNextEvent();
+ fStreamInputReaders.add(streamInputReader);
+ readers.add(streamInputReader);
+ }
+ }
+ }
+ long[] temp = fEventCountPerTraceFile;
+ fEventCountPerTraceFile = new long[readers.size() + temp.length];
+ for (CTFStreamInputReader reader : readers) {
+ fPrio.add(reader);
+ }
+ for (int i = 0; i < temp.length; i++) {
+ fEventCountPerTraceFile[i] = temp[i];
+ }
+ }
+
+ /**
+ * Gets an iterable of the stream input readers, useful for foreaches
+ *
+ * @return the iterable of the stream input readers
+ * @since 3.0
+ */
+ public Iterable<IEventDeclaration> getEventDeclarations() {
+ ImmutableSet.Builder<IEventDeclaration> builder = new Builder<>();
+ for (CTFStreamInputReader sir : fStreamInputReaders) {
+ builder.addAll(sir.getEventDeclarations());
+ }
+ return builder.build();
+ }
+
+ /**
+ * Initializes the priority queue used to choose the trace file with the
+ * lower next event timestamp.
+ *
+ * @throws CTFReaderException
+ * if an error occurs
+ */
+ private void populateStreamInputReaderHeap() throws CTFReaderException {
+ if (fStreamInputReaders.isEmpty()) {
+ fPrio = new PriorityQueue<>(MIN_PRIO_SIZE,
+ new StreamInputReaderTimestampComparator());
+ return;
+ }
+
+ /*
+ * Create the priority queue with a size twice as bigger as the number
+ * of reader in order to avoid constant resizing.
+ */
+ fPrio = new PriorityQueue<>(
+ Math.max(fStreamInputReaders.size() * 2, MIN_PRIO_SIZE),
+ new StreamInputReaderTimestampComparator());
+
+ int pos = 0;
+
+ for (CTFStreamInputReader reader : fStreamInputReaders) {
+ /*
+ * Add each trace file reader in the priority queue, if we are able
+ * to read an event from it.
+ */
+ reader.setParent(this);
+ CTFResponse readNextEvent = reader.readNextEvent();
+ if (readNextEvent == CTFResponse.OK || readNextEvent == CTFResponse.WAIT) {
+ fPrio.add(reader);
+
+ fEventCountPerTraceFile[pos] = 0;
+ reader.setName(pos);
+
+ pos++;
+ }
+ }
+ }
+
+ /**
+ * Get the current event, which is the current event of the trace file
+ * reader with the lowest timestamp.
+ *
+ * @return An event definition, or null of the trace reader reached the end
+ * of the trace.
+ */
+ public EventDefinition getCurrentEventDef() {
+ CTFStreamInputReader top = getTopStream();
+ return (top != null) ? top.getCurrentEvent() : null;
+ }
+
+ /**
+ * Go to the next event.
+ *
+ * @return True if an event was read.
+ * @throws CTFReaderException
+ * if an error occurs
+ */
+ public boolean advance() throws CTFReaderException {
+ /*
+ * Remove the reader from the top of the priority queue.
+ */
+ CTFStreamInputReader top = fPrio.poll();
+
+ /*
+ * If the queue was empty.
+ */
+ if (top == null) {
+ return false;
+ }
+ /*
+ * Read the next event of this reader.
+ */
+ switch (top.readNextEvent()) {
+ case OK: {
+ /*
+ * Add it back in the queue.
+ */
+ fPrio.add(top);
+ final long topEnd = fTrace.timestampCyclesToNanos(top.getCurrentEvent().getTimestamp());
+ setEndTime(Math.max(topEnd, getEndTime()));
+ fEventCountPerTraceFile[top.getName()]++;
+
+ if (top.getCurrentEvent() != null) {
+ fEndTime = Math.max(top.getCurrentEvent().getTimestamp(),
+ fEndTime);
+ }
+ break;
+ }
+ case WAIT: {
+ fPrio.add(top);
+ break;
+ }
+ case FINISH:
+ break;
+ case ERROR:
+ default:
+ // something bad happend
+ }
+ /*
+ * If there is no reader in the queue, it means the trace reader reached
+ * the end of the trace.
+ */
+ return hasMoreEvents();
+ }
+
+ /**
+ * Go to the last event in the trace.
+ *
+ * @throws CTFReaderException
+ * if an error occurs
+ */
+ public void goToLastEvent() throws CTFReaderException {
+ seek(getEndTime());
+ while (fPrio.size() > 1) {
+ advance();
+ }
+ }
+
+ /**
+ * Seeks to a given timestamp. It will seek to the nearest event greater or
+ * equal to timestamp. If a trace is [10 20 30 40] and you are looking for
+ * 19, it will give you 20. If you want 20, you will get 20, if you want 21,
+ * you will get 30. The value -inf will seek to the first element and the
+ * value +inf will seek to the end of the file (past the last event).
+ *
+ * @param timestamp
+ * the timestamp to seek to
+ * @return true if there are events above or equal the seek timestamp, false
+ * if seek at the end of the trace (no valid event).
+ * @throws CTFReaderException
+ * if an error occurs
+ */
+ public boolean seek(long timestamp) throws CTFReaderException {
+ /*
+ * Remove all the trace readers from the priority queue
+ */
+ fPrio.clear();
+ for (CTFStreamInputReader streamInputReader : fStreamInputReaders) {
+ /*
+ * Seek the trace reader.
+ */
+ streamInputReader.seek(timestamp);
+
+ /*
+ * Add it to the priority queue if there is a current event.
+ */
+ if (streamInputReader.getCurrentEvent() != null) {
+ fPrio.add(streamInputReader);
+ }
+ }
+ return hasMoreEvents();
+ }
+
+ /**
+ * Gets the stream with the oldest event
+ *
+ * @return the stream with the oldest event
+ * @since 3.0
+ */
+ public CTFStreamInputReader getTopStream() {
+ return fPrio.peek();
+ }
+
+ /**
+ * Does the trace have more events?
+ *
+ * @return true if yes.
+ */
+ public final boolean hasMoreEvents() {
+ return fPrio.size() > 0;
+ }
+
+ /**
+ * Prints the event count stats.
+ */
+ public void printStats() {
+ printStats(60);
+ }
+
+ /**
+ * Prints the event count stats.
+ *
+ * @param width
+ * Width of the display.
+ */
+ public void printStats(int width) {
+ int numEvents = 0;
+ if (width == 0) {
+ return;
+ }
+
+ for (long i : fEventCountPerTraceFile) {
+ numEvents += i;
+ }
+
+ for (int j = 0; j < fEventCountPerTraceFile.length; j++) {
+ CTFStreamInputReader se = fStreamInputReaders.get(j);
+
+ long len = (width * fEventCountPerTraceFile[se.getName()])
+ / numEvents;
+
+ StringBuilder sb = new StringBuilder(se.getFilename());
+ sb.append("\t["); //$NON-NLS-1$
+
+ for (int i = 0; i < len; i++) {
+ sb.append('+');
+ }
+
+ for (long i = len; i < width; i++) {
+ sb.append(' ');
+ }
+
+ sb.append("]\t" + fEventCountPerTraceFile[se.getName()] + " Events"); //$NON-NLS-1$//$NON-NLS-2$
+ Activator.log(sb.toString());
+ }
+ }
+
+ /**
+ * Gets the last event timestamp that was read. This is NOT necessarily the
+ * last event in a trace, just the last one read so far.
+ *
+ * @return the last event
+ */
+ public long getEndTime() {
+ return fEndTime;
+ }
+
+ /**
+ * Sets a trace to be live or not
+ *
+ * @param live
+ * whether the trace is live
+ * @since 3.0
+ */
+ public void setLive(boolean live) {
+ for (CTFStreamInputReader s : fPrio) {
+ s.setLive(live);
+ }
+ }
+
+ /**
+ * Get if the trace is to read live or not
+ *
+ * @return whether the trace is live or not
+ * @since 3.0
+ *
+ */
+ public boolean isLive() {
+ return getTopStream().isLive();
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = (prime * result) + (int) (fStartTime ^ (fStartTime >>> 32));
+ result = (prime * result) + fStreamInputReaders.hashCode();
+ result = (prime * result) + ((fTrace == null) ? 0 : fTrace.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (!(obj instanceof CTFTraceReader)) {
+ return false;
+ }
+ CTFTraceReader other = (CTFTraceReader) obj;
+ if (!fStreamInputReaders.equals(other.fStreamInputReaders)) {
+ return false;
+ }
+ if (fTrace == null) {
+ if (other.fTrace != null) {
+ return false;
+ }
+ } else if (!fTrace.equals(other.fTrace)) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ /* Only for debugging, shouldn't be externalized */
+ return "CTFTraceReader [trace=" + fTrace + ']'; //$NON-NLS-1$
+ }
+
+ /**
+ * Gets the parent trace
+ *
+ * @return the parent trace
+ */
+ public CTFTrace getTrace() {
+ return fTrace;
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ * Simon Marchi - Initial API and implementation
+ * Matthew Khouzam - Update for live trace reading support
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.trace;
+
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.channels.FileChannel;
+import java.util.UUID;
+
+import org.antlr.runtime.ANTLRReaderStream;
+import org.antlr.runtime.CommonTokenStream;
+import org.antlr.runtime.RecognitionException;
+import org.antlr.runtime.tree.CommonTree;
+import org.antlr.runtime.tree.RewriteCardinalityException;
+import org.eclipse.tracecompass.ctf.parser.CTFLexer;
+import org.eclipse.tracecompass.ctf.parser.CTFParser;
+import org.eclipse.tracecompass.ctf.parser.CTFParser.parse_return;
+import org.eclipse.tracecompass.internal.ctf.core.event.metadata.IOStructGen;
+import org.eclipse.tracecompass.internal.ctf.core.event.metadata.exceptions.CtfAntlrException;
+import org.eclipse.tracecompass.internal.ctf.core.event.metadata.exceptions.ParseException;
+
+/**
+ * The CTF trace metadata TSDL file
+ *
+ * @version 1.0
+ * @author Matthew Khouzam
+ * @author Simon Marchi
+ */
+public class Metadata {
+
+ // ------------------------------------------------------------------------
+ // Constants
+ // ------------------------------------------------------------------------
+
+ /**
+ * Name of the metadata file in the trace directory
+ */
+ private static final String METADATA_FILENAME = "metadata"; //$NON-NLS-1$
+
+ /**
+ * Size of the metadata packet header, in bytes, computed by hand.
+ */
+ private static final int METADATA_PACKET_HEADER_SIZE = 37;
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ /**
+ * Byte order as detected when reading the TSDL magic number.
+ */
+ private ByteOrder detectedByteOrder = null;
+
+ /**
+ * The trace file to which belongs this metadata file.
+ */
+ private final CTFTrace trace;
+
+ private IOStructGen fTreeParser;
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructs a Metadata object.
+ *
+ * @param trace
+ * The trace to which belongs this metadata file.
+ */
+ public Metadata(CTFTrace trace) {
+ this.trace = trace;
+ }
+
+ /**
+ * For network streaming
+ *
+ * @since 3.0
+ */
+ public Metadata() {
+ trace = new CTFTrace();
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ /**
+ * Returns the ByteOrder that was detected while parsing the metadata.
+ *
+ * @return The byte order.
+ */
+ public ByteOrder getDetectedByteOrder() {
+ return detectedByteOrder;
+ }
+
+ /**
+ * Gets the parent trace
+ *
+ * @return the parent trace
+ * @since 3.0
+ */
+ public CTFTrace getTrace() {
+ return trace;
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ /**
+ * Parse the metadata file.
+ *
+ * @throws CTFReaderException
+ * If there was a problem parsing the metadata
+ * @since 3.0
+ */
+ public void parseFile() throws CTFReaderException {
+
+ /*
+ * Reader. It will contain a StringReader if we are using packet-based
+ * metadata and it will contain a FileReader if we have text-based
+ * metadata.
+ */
+
+ try (FileInputStream fis = new FileInputStream(getMetadataPath());
+ FileChannel metadataFileChannel = fis.getChannel();
+ /* Check if metadata is packet-based, if not it is text based */
+ Reader metadataTextInput =
+ (isPacketBased(metadataFileChannel) ?
+ readBinaryMetaData(metadataFileChannel) :
+ new FileReader(getMetadataPath()));) {
+
+ readMetaDataText(metadataTextInput);
+
+ } catch (FileNotFoundException e) {
+ throw new CTFReaderException("Cannot find metadata file!"); //$NON-NLS-1$
+ } catch (IOException | ParseException e) {
+ throw new CTFReaderException(e);
+ } catch (RecognitionException | RewriteCardinalityException e) {
+ throw new CtfAntlrException(e);
+ }
+ }
+
+ private Reader readBinaryMetaData(FileChannel metadataFileChannel) throws CTFReaderException {
+ /* Create StringBuffer to receive metadata text */
+ StringBuffer metadataText = new StringBuffer();
+
+ /*
+ * Read metadata packet one by one, appending the text to the
+ * StringBuffer
+ */
+ MetadataPacketHeader packetHeader = readMetadataPacket(
+ metadataFileChannel, metadataText);
+ while (packetHeader != null) {
+ packetHeader = readMetadataPacket(metadataFileChannel,
+ metadataText);
+ }
+
+ /* Wrap the metadata string with a StringReader */
+ return new StringReader(metadataText.toString());
+ }
+
+ /**
+ * Read the metadata from a formatted TSDL string
+ *
+ * @param data
+ * the data to read
+ * @throws CTFReaderException
+ * this exception wraps a ParseException, IOException or
+ * CtfAntlrException, three exceptions that can be obtained from
+ * parsing a TSDL file
+ * @since 3.0
+ */
+ public void parseText(String data) throws CTFReaderException {
+ Reader metadataTextInput = new StringReader(data);
+ try {
+ readMetaDataText(metadataTextInput);
+ } catch (IOException | ParseException e) {
+ throw new CTFReaderException(e);
+ } catch (RecognitionException | RewriteCardinalityException e) {
+ throw new CtfAntlrException(e);
+ }
+
+ }
+
+ private void readMetaDataText(Reader metadataTextInput) throws IOException, RecognitionException, ParseException {
+ CommonTree tree = createAST(metadataTextInput);
+
+ /* Generate IO structures (declarations) */
+ fTreeParser = new IOStructGen(tree, trace);
+ fTreeParser.generate();
+ }
+
+ /**
+ * Read a metadata fragment from a formatted TSDL string
+ *
+ * @param dataFragment
+ * the data to read
+ * @throws CTFReaderException
+ * this exception wraps a ParseException, IOException or
+ * CtfAntlrException, three exceptions that can be obtained from
+ * parsing a TSDL file
+ * @since 3.0
+ */
+ public void parseTextFragment(String dataFragment) throws CTFReaderException {
+ Reader metadataTextInput = new StringReader(dataFragment);
+ try {
+ readMetaDataTextFragment(metadataTextInput);
+ } catch (IOException | ParseException e) {
+ throw new CTFReaderException(e);
+ } catch (RecognitionException | RewriteCardinalityException e) {
+ throw new CtfAntlrException(e);
+ }
+ }
+
+ private void readMetaDataTextFragment(Reader metadataTextInput) throws IOException, RecognitionException, ParseException {
+ CommonTree tree = createAST(metadataTextInput);
+ fTreeParser.setTree(tree);
+ fTreeParser.generateFragment();
+ }
+
+ private static CommonTree createAST(Reader metadataTextInput) throws IOException,
+ RecognitionException {
+ /* Create an ANTLR reader */
+ ANTLRReaderStream antlrStream;
+ antlrStream = new ANTLRReaderStream(metadataTextInput);
+
+ /* Parse the metadata text and get the AST */
+ CTFLexer ctfLexer = new CTFLexer(antlrStream);
+ CommonTokenStream tokens = new CommonTokenStream(ctfLexer);
+ CTFParser ctfParser = new CTFParser(tokens, false);
+
+ parse_return pr = ctfParser.parse();
+ return pr.getTree();
+ }
+
+ /**
+ * Determines whether the metadata file is packet-based by looking at the
+ * TSDL magic number. If it is packet-based, it also gives information about
+ * the endianness of the trace using the detectedByteOrder attribute.
+ *
+ * @param metadataFileChannel
+ * FileChannel of the metadata file.
+ * @return True if the metadata is packet-based.
+ * @throws CTFReaderException
+ */
+ private boolean isPacketBased(FileChannel metadataFileChannel)
+ throws CTFReaderException {
+ /*
+ * Create a ByteBuffer to read the TSDL magic number (default is
+ * big-endian)
+ */
+ ByteBuffer magicByteBuffer = ByteBuffer.allocate(Utils.TSDL_MAGIC_LEN);
+
+ /* Read without changing file position */
+ try {
+ metadataFileChannel.read(magicByteBuffer, 0);
+ } catch (IOException e) {
+ throw new CTFReaderException("Unable to read metadata file channel.", e); //$NON-NLS-1$
+ }
+
+ /* Get the first int from the file */
+ int magic = magicByteBuffer.getInt(0);
+
+ /* Check if it matches */
+ if (Utils.TSDL_MAGIC == magic) {
+ detectedByteOrder = ByteOrder.BIG_ENDIAN;
+ return true;
+ }
+
+ /* Try the same thing, but with little-endian */
+ magicByteBuffer.order(ByteOrder.LITTLE_ENDIAN);
+ magic = magicByteBuffer.getInt(0);
+
+ if (Utils.TSDL_MAGIC == magic) {
+ detectedByteOrder = ByteOrder.LITTLE_ENDIAN;
+ return true;
+ }
+
+ return false;
+ }
+
+ private String getMetadataPath() {
+ /* Path of metadata file = trace directory path + metadata filename */
+ if (trace.getTraceDirectory() == null) {
+ return new String();
+ }
+ return trace.getTraceDirectory().getPath()
+ + Utils.SEPARATOR + METADATA_FILENAME;
+ }
+
+ /**
+ * Reads a metadata packet from the given metadata FileChannel, do some
+ * basic validation and append the text to the StringBuffer.
+ *
+ * @param metadataFileChannel
+ * Metadata FileChannel
+ * @param metadataText
+ * StringBuffer to which the metadata text will be appended.
+ * @return A structure describing the header of the metadata packet, or null
+ * if the end of the file is reached.
+ * @throws CTFReaderException
+ */
+ private MetadataPacketHeader readMetadataPacket(
+ FileChannel metadataFileChannel, StringBuffer metadataText)
+ throws CTFReaderException {
+ /* Allocate a ByteBuffer for the header */
+ ByteBuffer headerByteBuffer = ByteBuffer.allocate(METADATA_PACKET_HEADER_SIZE);
+
+ /* Read the header */
+ try {
+ int nbBytesRead = metadataFileChannel.read(headerByteBuffer);
+
+ /* Return null if EOF */
+ if (nbBytesRead < 0) {
+ return null;
+ }
+
+ if (nbBytesRead != METADATA_PACKET_HEADER_SIZE) {
+ throw new CTFReaderException("Error reading the metadata header."); //$NON-NLS-1$
+ }
+
+ } catch (IOException e) {
+ throw new CTFReaderException("Error reading the metadata header.", e); //$NON-NLS-1$
+ }
+
+ /* Set ByteBuffer's position to 0 */
+ headerByteBuffer.position(0);
+
+ /* Use byte order that was detected with the magic number */
+ headerByteBuffer.order(detectedByteOrder);
+
+ MetadataPacketHeader header = new MetadataPacketHeader(headerByteBuffer);
+
+ /* Check TSDL magic number */
+ if (!header.isMagicValid()) {
+ throw new CTFReaderException("TSDL magic number does not match"); //$NON-NLS-1$
+ }
+
+ /* Check UUID */
+ if (!trace.uuidIsSet()) {
+ trace.setUUID(header.getUuid());
+ } else if (!trace.getUUID().equals(header.getUuid())) {
+ throw new CTFReaderException("UUID mismatch"); //$NON-NLS-1$
+ }
+
+ /* Extract the text from the packet */
+ int payloadSize = ((header.getContentSize() / 8) - METADATA_PACKET_HEADER_SIZE);
+ if (payloadSize < 0) {
+ throw new CTFReaderException("Invalid metadata packet payload size."); //$NON-NLS-1$
+ }
+ int skipSize = (header.getPacketSize() - header.getContentSize()) / 8;
+
+ /* Read the payload + the padding in a ByteBuffer */
+ ByteBuffer payloadByteBuffer = ByteBuffer.allocateDirect(payloadSize
+ + skipSize);
+ try {
+ metadataFileChannel.read(payloadByteBuffer);
+ } catch (IOException e) {
+ throw new CTFReaderException("Error reading metadata packet payload.", e); //$NON-NLS-1$
+ }
+ payloadByteBuffer.rewind();
+
+ /* Read only the payload from the ByteBuffer into a byte array */
+ byte payloadByteArray[] = new byte[payloadByteBuffer.remaining()];
+ payloadByteBuffer.get(payloadByteArray, 0, payloadSize);
+
+ /* Convert the byte array to a String */
+ String str = new String(payloadByteArray, 0, payloadSize);
+
+ /* Append it to the existing metadata */
+ metadataText.append(str);
+
+ return header;
+ }
+
+ private static class MetadataPacketHeader {
+
+ private final int fMagic;
+ private final UUID fUuid;
+ private final int fChecksum;
+ private final int fContentSize;
+ private final int fPacketSize;
+ private final byte fCompressionScheme;
+ private final byte fEncryptionScheme;
+ private final byte fChecksumScheme;
+ private final byte fCtfMajorVersion;
+ private final byte fCtfMinorVersion;
+
+ public MetadataPacketHeader(ByteBuffer headerByteBuffer) {
+ /* Read from the ByteBuffer */
+ fMagic = headerByteBuffer.getInt();
+ byte[] uuidBytes = new byte[16];
+ headerByteBuffer.get(uuidBytes);
+ fUuid = Utils.makeUUID(uuidBytes);
+ fChecksum = headerByteBuffer.getInt();
+ fContentSize = headerByteBuffer.getInt();
+ fPacketSize = headerByteBuffer.getInt();
+ fCompressionScheme = headerByteBuffer.get();
+ fEncryptionScheme = headerByteBuffer.get();
+ fChecksumScheme = headerByteBuffer.get();
+ fCtfMajorVersion = headerByteBuffer.get();
+ fCtfMinorVersion = headerByteBuffer.get();
+ }
+
+ public boolean isMagicValid() {
+ return fMagic == Utils.TSDL_MAGIC;
+ }
+
+ public UUID getUuid() {
+ return fUuid;
+ }
+
+ public int getContentSize() {
+ return fContentSize;
+ }
+
+ public int getPacketSize() {
+ return fPacketSize;
+ }
+
+ @Override
+ public String toString() {
+ /* Only for debugging, shouldn't be externalized */
+ /* Therefore it cannot be covered by test cases */
+ return "MetadataPacketHeader [magic=0x" //$NON-NLS-1$
+ + Integer.toHexString(fMagic) + ", uuid=" //$NON-NLS-1$
+ + fUuid.toString() + ", checksum=" + fChecksum //$NON-NLS-1$
+ + ", contentSize=" + fContentSize + ", packetSize=" //$NON-NLS-1$ //$NON-NLS-2$
+ + fPacketSize + ", compressionScheme=" + fCompressionScheme //$NON-NLS-1$
+ + ", encryptionScheme=" + fEncryptionScheme //$NON-NLS-1$
+ + ", checksumScheme=" + fChecksumScheme //$NON-NLS-1$
+ + ", ctfMajorVersion=" + fCtfMajorVersion //$NON-NLS-1$
+ + ", ctfMinorVersion=" + fCtfMinorVersion + ']'; //$NON-NLS-1$
+ }
+
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.core.trace;
+
+import java.util.UUID;
+
+import org.eclipse.tracecompass.ctf.core.event.types.AbstractArrayDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.CompoundDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDefinition;
+
+/**
+ * Various utilities.
+ *
+ * @version 1.0
+ * @author Matthew Khouzam
+ * @author Simon Marchi
+ */
+public final class Utils {
+
+ private Utils() {
+ }
+
+ // ------------------------------------------------------------------------
+ // Constants
+ // ------------------------------------------------------------------------
+
+ /**
+ * CTF magic number. (sort of looks like CTF CTF CT)
+ */
+ public static final int CTF_MAGIC = 0xC1FC1FC1;
+
+ /**
+ * TSDL magic number. (sort of looks like TSDL LSDT)
+ */
+ public static final int TSDL_MAGIC = 0x75D11D57;
+
+ /**
+ * TSDL magic number length in bytes.
+ */
+ public static final int TSDL_MAGIC_LEN = 4;
+
+ /**
+ * Directory separator on the current platform.
+ */
+ public static final String SEPARATOR = System.getProperty("file.separator"); //$NON-NLS-1$
+
+ /**
+ * Length in bytes of a UUID value.
+ */
+ public static final int UUID_LEN = 16;
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ /**
+ * Performs an unsigned long comparison on two unsigned long numbers.
+ *
+ * <strong> As Java does not support unsigned types and arithmetic,
+ * parameters are received encoded as a signed long (two-complement) but the
+ * operation is an unsigned comparator.</strong>
+ *
+ * @param left
+ * Left operand of the comparator.
+ * @param right
+ * Right operand of the comparator.
+ * @return -1 if left < right, 1 if left > right, 0 if left == right.
+ */
+ public static int unsignedCompare(long left, long right) {
+ /*
+ * This method assumes that the arithmetic overflow on signed integer
+ * wrap on a circular domain (modulo arithmetic in two-complement),
+ * which is the defined behavior in Java.
+ *
+ * This idea is to rotate the domain by the length of the negative
+ * space, and then use the signed operator.
+ */
+ final long a = left + Long.MIN_VALUE;
+ final long b = right + Long.MIN_VALUE;
+ if (a < b) {
+ return -1;
+ } else if (a > b) {
+ return 1;
+ }
+ return 0;
+ }
+
+ /**
+ * Gets a UUID from an array defintion
+ *
+ * @param uuidDef
+ * the array defintions, must contain integer bytes
+ * @return the UUID
+ * @throws CTFReaderException
+ * if the definition contains less than 16 elements
+ * @since 3.1
+ */
+ public static UUID getUUIDfromDefinition(AbstractArrayDefinition uuidDef) throws CTFReaderException {
+ byte[] uuidArray = new byte[16];
+ IDeclaration declaration = uuidDef.getDeclaration();
+ if (!(declaration instanceof CompoundDeclaration)) {
+ throw new CTFReaderException("UUID must be a sequence of unsigned bytes"); //$NON-NLS-1$
+ }
+ CompoundDeclaration uuidDec = (CompoundDeclaration) declaration;
+
+ IDeclaration uuidElem = uuidDec.getElementType();
+ if (!(uuidElem instanceof IntegerDeclaration)) {
+ throw new CTFReaderException("UUID must be a sequence of unsigned bytes"); //$NON-NLS-1$
+ }
+ IntegerDeclaration intUuidElem = (IntegerDeclaration) uuidElem;
+ if (!intUuidElem.isUnsignedByte()) {
+ throw new CTFReaderException("UUID must be a sequence of unsigned bytes"); //$NON-NLS-1$
+ }
+ return getUUID(uuidDef, uuidArray);
+ }
+
+ private static UUID getUUID(AbstractArrayDefinition uuidDef, byte[] uuidArray) throws CTFReaderException {
+ for (int i = 0; i < uuidArray.length; i++) {
+ IntegerDefinition uuidByteDef = (IntegerDefinition) uuidDef.getDefinitions().get(i);
+ if (uuidByteDef == null) {
+ throw new CTFReaderException("UUID incomplete, only " + i + " bytes available"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ uuidArray[i] = (byte) uuidByteDef.getValue();
+ }
+
+ UUID uuid = Utils.makeUUID(uuidArray);
+ return uuid;
+ }
+
+ /**
+ * Gets a UUID from an array defintion
+ *
+ * @param uuidDef
+ * the array defintions, must contain integer bytes
+ * @return the UUID
+ * @throws CTFReaderException
+ * if the definition contains less than 16 elements
+ * @since 3.1
+ * @deprecated use
+ * {@link Utils#getUUIDfromDefinition(AbstractArrayDefinition uuidDef)}
+ */
+ @Deprecated
+ public static UUID getUUIDfromDefinition(org.eclipse.tracecompass.ctf.core.event.types.ArrayDefinition uuidDef) throws CTFReaderException {
+ byte[] uuidArray = new byte[16];
+ return getUUID(uuidDef, uuidArray);
+ }
+
+ /**
+ * Creates a UUID object from an array of 16 bytes.
+ *
+ * @param bytes
+ * Array of 16 bytes.
+ * @return A UUID object.
+ */
+ public static UUID makeUUID(byte bytes[]) {
+ long high = 0;
+ long low = 0;
+
+ assert (bytes.length == Utils.UUID_LEN);
+
+ for (int i = 0; i < 8; i++) {
+ low = (low << 8) | (bytes[i + 8] & 0xFF);
+ high = (high << 8) | (bytes[i] & 0xFF);
+ }
+
+ UUID uuid = new UUID(high, low);
+
+ return uuid;
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are
+ * made available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Francois Chouinard - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.internal.ctf.core;
+
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Plugin;
+import org.eclipse.core.runtime.Status;
+import org.osgi.framework.BundleContext;
+
+/**
+ * <b><u>Activator</u></b>
+ * <p>
+ * The activator class controls the plug-in life cycle.
+ */
+public class Activator extends Plugin {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ /**
+ * The plug-in ID
+ */
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.ctf"; //$NON-NLS-1$
+
+ /**
+ * The shared instance
+ */
+ private static Activator fPlugin;
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructor
+ */
+ public Activator() {
+ setDefault(this);
+ }
+
+ // ------------------------------------------------------------------------
+ // Accessors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Get the default activator
+ * @return the default activator
+ */
+ public static Activator getDefault() {
+ return fPlugin;
+ }
+
+ /**
+ * Sets the default activator
+ *
+ * @param plugin the default activator
+ */
+ private static void setDefault(Activator plugin) {
+ fPlugin = plugin;
+ }
+
+ // ------------------------------------------------------------------------
+ // Plugin
+ // ------------------------------------------------------------------------
+
+ @Override
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ setDefault(this);
+ }
+
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ setDefault(null);
+ super.stop(context);
+ }
+
+ // ------------------------------------------------------------------------
+ // Logging
+ // ------------------------------------------------------------------------
+
+ /**
+ * Log a message
+ *
+ * @param msg
+ * The message to log
+ */
+ public static void log(String msg) {
+ log(msg, null);
+ }
+
+ /**
+ * Log a message with an exception
+ *
+ * @param msg
+ * The message
+ * @param e
+ * The exception
+ */
+ public static void log(String msg, Exception e) {
+ getDefault().getLog().log(new Status(IStatus.INFO, PLUGIN_ID, IStatus.OK, msg, e));
+ }
+
+ /**
+ * Log an error, with an associated exception
+ *
+ * @param msg
+ * The error message
+ * @param e
+ * The cause
+ */
+ public static void logError(String msg, Exception e) {
+ getDefault().getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.OK, msg, e));
+ }
+
+ /**
+ * Log a message
+ *
+ * @param severity
+ * Desired severity of the message in the log, one of
+ * {@link IStatus#INFO}, {@link IStatus#WARNING} or
+ * {@link IStatus#ERROR}
+ * @param msg
+ * The message to log
+ */
+ public static void log(int severity, String msg) {
+ getDefault().getLog().log(new Status(severity, PLUGIN_ID, msg));
+ }
+
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Marc-Andre Laperle - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.internal.ctf.core;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+
+/**
+ * A common utility for mapping a ByteBuffer safely to work around a bug on
+ * Windows which prevents deleting a file after it was mapped. On Windows, the
+ * ByteBuffer will be allocated and the file will be read instead of being
+ * mapped.
+ *
+ * http://bugs.java.com/view_bug.do?bug_id=4715154
+ */
+public class SafeMappedByteBuffer {
+
+ private static final boolean IS_WIN32 = System.getProperty("os.name").startsWith("Windows"); //$NON-NLS-1$//$NON-NLS-2$
+
+ /**
+ * Maps a region of this channel's file directly into memory. On Windows,
+ * this will allocate a new ByteBuffer and read the file.
+ *
+ * @param fc
+ * the file channel
+ * @param mode
+ * the mapping mode
+ * @param position
+ * the position within the file
+ * @param size
+ * the size of the region to be mapped (or read)
+ * @return the mapped ByteBuffer
+ * @throws IOException
+ * on FileChannel operations failures
+ */
+ public static ByteBuffer map(FileChannel fc, FileChannel.MapMode mode, long position, long size) throws IOException {
+ ByteBuffer byteBuffer;
+ if (IS_WIN32) {
+ byteBuffer = ByteBuffer.allocate((int) size);
+ fc.read(byteBuffer, position);
+ } else {
+ byteBuffer = fc.map(mode, position, size);
+ }
+
+ return byteBuffer;
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Simon Delisle - Initial implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.internal.ctf.core.event;
+
+import java.util.Comparator;
+
+import org.eclipse.tracecompass.ctf.core.event.CTFCallsite;
+
+/**
+ * Comparator for CTFCallsite
+ *
+ * @author Simon Delisle
+ * @since 3.0
+ *
+ */
+public class CTFCallsiteComparator implements Comparator<CTFCallsite> {
+
+ private static final long MASK32 = 0x00000000ffffffffL;
+
+ /*
+ * The callsites will be sorted by calling addresses. To do this we take IPs
+ * (instruction pointers) and compare them. Java only supports signed
+ * operation and since memory addresses are unsigned, we will convert the
+ * longs into integers that contain the high and low bytes and compare them.
+ */
+ @Override
+ public int compare(CTFCallsite o1, CTFCallsite o2) {
+ /*
+ * mask32 is 32 zeros followed by 32 ones, when we bitwise and this it
+ * will return the lower 32 bits
+ */
+
+ long other = o2.getIp();
+ /*
+ * To get a high int: we downshift by 32 and bitwise and with the mask
+ * to get rid of the sign
+ *
+ * To get the low int: we bitwise and with the mask.
+ */
+ long otherHigh = (other >> 32) & MASK32;
+ long otherLow = other & MASK32;
+ long ownHigh = (o1.getIp() >> 32) & MASK32;
+ long ownLow = o1.getIp() & MASK32;
+ /* are the high values different, if so ignore the lower values */
+ if (ownHigh > otherHigh) {
+ return 1;
+ }
+ if (ownHigh < otherHigh ) {
+ return -1;
+ }
+ /* the high values are the same, compare the lower values */
+ if (ownLow > otherLow) {
+ return 1;
+ }
+ if (ownLow < otherLow) {
+ return -1;
+ }
+ /* the values are identical */
+ return 0;
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.internal.ctf.core.event;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.CTFStrings;
+import org.eclipse.tracecompass.ctf.core.event.EventDefinition;
+import org.eclipse.tracecompass.ctf.core.event.IEventDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.scope.LexicalScope;
+import org.eclipse.tracecompass.ctf.core.event.types.Declaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDefinition;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.ctf.core.trace.CTFStream;
+import org.eclipse.tracecompass.ctf.core.trace.CTFStreamInputReader;
+
+/**
+ * Representation of one type of event. A bit like "int" or "long" but for trace
+ * events.
+ */
+public class EventDeclaration implements IEventDeclaration {
+
+ /** Id of lost events */
+ public static final long LOST_EVENT_ID = -1L;
+
+ /** Id of events when not set */
+ public static final long UNSET_EVENT_ID = -2L;
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ /**
+ * Name of the event
+ */
+ private String fName;
+
+ /**
+ * Event context structure declaration
+ */
+ private StructDeclaration fContext = null;
+
+ /**
+ * Event fields structure declaration
+ */
+ private StructDeclaration fFields = null;
+
+ /**
+ * Stream to which belongs this event.
+ */
+ private CTFStream fStream = null;
+
+ /**
+ * Loglevel of an event
+ */
+ private long fLogLevel;
+
+ /** Map of this event type's custom CTF attributes */
+ private final Map<String, String> fCustomAttributes = new HashMap<>();
+
+ private int fId = (int) UNSET_EVENT_ID;
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Default constructor. Use the setters afterwards to set the fields
+ * accordingly.
+ */
+ public EventDeclaration() {
+ }
+
+ @Override
+ public EventDefinition createDefinition(CTFStreamInputReader streamInputReader, @NonNull BitBuffer input, long timestamp) throws CTFReaderException {
+ StructDeclaration streamEventContextDecl = streamInputReader.getStreamEventContextDecl();
+ StructDefinition streamEventContext = streamEventContextDecl != null ? streamEventContextDecl.createDefinition(fStream.getTrace(), LexicalScope.STREAM_EVENT_CONTEXT, input) : null;
+ StructDefinition packetContext = streamInputReader.getPacketReader().getCurrentPacketEventHeader();
+ StructDefinition eventContext = fContext != null ? fContext.createDefinition(fStream.getTrace(), LexicalScope.CONTEXT, input) : null;
+ StructDefinition eventPayload = fFields != null ? fFields.createDefinition(fStream.getTrace(), LexicalScope.FIELDS, input) : null;
+
+ // a bit lttng specific
+ // CTF doesn't require a timestamp,
+ // but it's passed to us
+ return new EventDefinition(
+ this,
+ streamInputReader,
+ timestamp,
+ streamEventContext,
+ eventContext,
+ packetContext,
+ eventPayload);
+ }
+
+ /**
+ * Creates a "lost" event. This is a synthetic event that is there to show
+ * that there should be something there.
+ *
+ * @return the lost event
+ */
+ public static synchronized EventDeclaration getLostEventDeclaration() {
+ EventDeclaration lostEvent = new EventDeclaration();
+ String[] fieldNames = new String[] { CTFStrings.LOST_EVENTS_FIELD, CTFStrings.LOST_EVENTS_DURATION };
+ Declaration[] fieldDeclarations = new Declaration[] { IntegerDeclaration.UINT_32B_DECL, IntegerDeclaration.UINT_64B_DECL };
+ lostEvent.fFields = new StructDeclaration(fieldNames, fieldDeclarations);
+ lostEvent.fId = (int) LOST_EVENT_ID;
+ lostEvent.fName = CTFStrings.LOST_EVENT_NAME;
+ return lostEvent;
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ /**
+ * Sets a name for an event Declaration
+ *
+ * @param name
+ * the name
+ */
+ public void setName(String name) {
+ fName = name;
+ }
+
+ @Override
+ public String getName() {
+ return fName;
+ }
+
+ /**
+ * Sets the context for an event declaration (see CTF specification)
+ *
+ * @param context
+ * the context in structdeclaration format
+ */
+ public void setContext(StructDeclaration context) {
+ fContext = context;
+ }
+
+ /**
+ * Sets the fields of an event declaration
+ *
+ * @param fields
+ * the fields in structdeclaration format
+ */
+ public void setFields(StructDeclaration fields) {
+ fFields = fields;
+ }
+
+ @Override
+ public StructDeclaration getFields() {
+ return fFields;
+ }
+
+ @Override
+ public StructDeclaration getContext() {
+ return fContext;
+ }
+
+ /**
+ * Sets the id of an event declaration
+ *
+ * @param id
+ * the id
+ */
+ public void setId(long id) {
+ if (id < 0 || id > Integer.MAX_VALUE) {
+ throw new IllegalArgumentException("id out of range"); //$NON-NLS-1$
+ }
+ fId = (int) id;
+ }
+
+ @Override
+ public Long getId() {
+ return Long.valueOf(fId);
+ }
+
+ /**
+ * Faster get id assuming you have less than a billion event types
+ *
+ * @return the event id
+ */
+ public int id() {
+ return fId;
+ }
+
+ /**
+ * Sets the stream of an event declaration
+ *
+ * @param stream
+ * the stream
+ * @since 2.0
+ */
+ public void setStream(CTFStream stream) {
+ fStream = stream;
+ }
+
+ @Override
+ public CTFStream getStream() {
+ return fStream;
+ }
+
+ /**
+ * Is the name of the event declaration set
+ *
+ * @return is the name set?
+ */
+ public boolean nameIsSet() {
+ return fName != null;
+ }
+
+ /**
+ * Is the context set
+ *
+ * @return is the context set
+ */
+ public boolean contextIsSet() {
+ return fContext != null;
+ }
+
+ /**
+ * Is a field set?
+ *
+ * @return Is the field set?
+ */
+ public boolean fieldsIsSet() {
+ return fFields != null;
+ }
+
+ /**
+ * Is the id set?
+ *
+ * @return is the id set?
+ */
+ public boolean idIsSet() {
+ return (fId != UNSET_EVENT_ID);
+ }
+
+ /**
+ * Is the stream set?
+ *
+ * @return is the stream set?
+ */
+ public boolean streamIsSet() {
+ return fStream != null;
+ }
+
+ @Override
+ public long getLogLevel() {
+ return fLogLevel;
+ }
+
+ /**
+ * Sets the log level
+ *
+ * @param level
+ * the log level
+ */
+ public void setLogLevel(long level) {
+ fLogLevel = level;
+ }
+
+ @Override
+ public Set<String> getCustomAttributes() {
+ return fCustomAttributes.keySet();
+ }
+
+ @Override
+ public String getCustomAttribute(String key) {
+ return fCustomAttributes.get(key);
+ }
+
+ /**
+ * Sets a custom attribute value.
+ *
+ * @param key
+ * the key of the attribute
+ * @param value
+ * the value of the attribute
+ * @since 2.0
+ */
+ public void setCustomAttribute(String key, String value) {
+ fCustomAttributes.put(key, value);
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (!(obj instanceof EventDeclaration)) {
+ return false;
+ }
+ EventDeclaration other = (EventDeclaration) obj;
+ if (fContext == null) {
+ if (other.fContext != null) {
+ return false;
+ }
+ } else if (!fContext.equals(other.fContext)) {
+ return false;
+ }
+ if (fFields == null) {
+ if (other.fFields != null) {
+ return false;
+ }
+ } else if (!fFields.equals(other.fFields)) {
+ return false;
+ }
+ if (fId != (other.fId)) {
+ return false;
+ }
+ if (fName == null) {
+ if (other.fName != null) {
+ return false;
+ }
+ } else if (!fName.equals(other.fName)) {
+ return false;
+ }
+ if (fStream == null) {
+ if (other.fStream != null) {
+ return false;
+ }
+ } else if (!fStream.equals(other.fStream)) {
+ return false;
+ }
+ if (!fCustomAttributes.equals(other.fCustomAttributes)) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = (prime * result)
+ + ((fContext == null) ? 0 : fContext.hashCode());
+ result = (prime * result) + ((fFields == null) ? 0 : fFields.hashCode());
+ result = (prime * result) + fId;
+ result = (prime * result) + ((fName == null) ? 0 : fName.hashCode());
+ result = (prime * result) + ((fStream == null) ? 0 : fStream.hashCode());
+ result = (prime * result) + fCustomAttributes.hashCode();
+ return result;
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial Design and Grammar
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.internal.ctf.core.event.metadata;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+import org.eclipse.tracecompass.ctf.core.event.types.EnumDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.VariantDeclaration;
+import org.eclipse.tracecompass.internal.ctf.core.event.metadata.exceptions.ParseException;
+
+/**
+ * <b><u>DeclarationScope</u></b>
+ * <p>
+ * A DeclarationScope keeps track of the various CTF declarations for a given
+ * scope.
+ *
+ * TODO: The notion of "symbols" and the notion of "scope" are misused in this
+ * parser, which leads to inefficient tree management. It should be cleaned up.
+ *
+ * @author Matthew Khouzam
+ * @author Simon Marchi
+ *
+ */
+class DeclarationScope {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ private DeclarationScope fParentScope = null;
+
+ private final Map<String, StructDeclaration> fStructs = new HashMap<>();
+ private final Map<String, EnumDeclaration> fEnums = new HashMap<>();
+ private final Map<String, VariantDeclaration> fVariants = new HashMap<>();
+ private final Map<String, IDeclaration> fTypes = new HashMap<>();
+ private final Map<String, IDeclaration> fIdentifiers = new HashMap<>();
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Creates a declaration scope with no parent.
+ */
+ public DeclarationScope() {
+ }
+
+ /**
+ * Creates a declaration scope with the specified parent.
+ *
+ * @param parentScope
+ * The parent of the newly created scope.
+ */
+ public DeclarationScope(DeclarationScope parentScope) {
+ fParentScope = parentScope;
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ /**
+ * Returns the parent of the current scope.
+ *
+ * @return The parent scope.
+ */
+ public DeclarationScope getParentScope() {
+ return fParentScope;
+ }
+
+ // ------------------------------------------------------------------------
+ // Registration operations
+ // ------------------------------------------------------------------------
+
+ /**
+ * Registers a type declaration.
+ *
+ * @param name
+ * The name of the type.
+ * @param declaration
+ * The type declaration.
+ * @throws ParseException
+ * if a type with the same name has already been defined.
+ */
+ public void registerType(String name, IDeclaration declaration)
+ throws ParseException {
+ /* Check if the type has been defined in the current scope */
+ if (fTypes.containsKey(name)) {
+ throw new ParseException("Type has already been defined:" + name); //$NON-NLS-1$
+ }
+
+ /* Add it to the register. */
+ fTypes.put(name, declaration);
+ }
+
+ /**
+ * Registers an identifier declaration.
+ *
+ * @param name
+ * name of the identifier
+ * @param declaration
+ * the identfier's declaration
+ * @throws ParseException
+ * if an identifier with the same name has already been defined.
+ */
+ public void registerIdentifier(String name, IDeclaration declaration) throws ParseException {
+ /* Check if the type has been defined in the current scope */
+ if (fIdentifiers.containsKey(name)) {
+ throw new ParseException("Identifier has already been defined:" + name); //$NON-NLS-1$
+ }
+
+ /* Add it to the register. */
+ fIdentifiers.put(name, declaration);
+ }
+
+ /**
+ * Registers a struct declaration.
+ *
+ * @param name
+ * The name of the struct.
+ * @param declaration
+ * The declaration of the struct.
+ * @throws ParseException
+ * if a struct with the same name has already been registered.
+ */
+ public void registerStruct(String name, StructDeclaration declaration)
+ throws ParseException {
+ /* Check if the struct has been defined in the current scope. */
+ if (fStructs.containsKey(name)) {
+ throw new ParseException("Struct has already been defined:" + name); //$NON-NLS-1$
+ }
+
+ /* Add it to the register. */
+ fStructs.put(name, declaration);
+
+ /* It also defined a new type, so add it to the type declarations. */
+ String structPrefix = "struct "; //$NON-NLS-1$
+ registerType(structPrefix + name, declaration);
+ }
+
+ /**
+ * Registers an enum declaration.
+ *
+ * @param name
+ * The name of the enum.
+ * @param declaration
+ * The declaration of the enum.
+ * @throws ParseException
+ * if an enum with the same name has already been registered.
+ */
+ public void registerEnum(String name, EnumDeclaration declaration)
+ throws ParseException {
+ /* Check if the enum has been defined in the current scope. */
+ if (lookupEnum(name) != null) {
+ throw new ParseException("Enum has already been defined:" + name); //$NON-NLS-1$
+ }
+
+ /* Add it to the register. */
+ fEnums.put(name, declaration);
+
+ /* It also defined a new type, so add it to the type declarations. */
+ String enumPrefix = "enum "; //$NON-NLS-1$
+ registerType(enumPrefix + name, declaration);
+ }
+
+ /**
+ * Registers a variant declaration.
+ *
+ * @param name
+ * The name of the variant.
+ * @param declaration
+ * The declaration of the variant.
+ * @throws ParseException
+ * if a variant with the same name has already been registered.
+ */
+ public void registerVariant(String name, VariantDeclaration declaration)
+ throws ParseException {
+ /* Check if the variant has been defined in the current scope. */
+ if (lookupVariant(name) != null) {
+ throw new ParseException("Variant has already been defined:" + name); //$NON-NLS-1$
+ }
+
+ /* Add it to the register. */
+ fVariants.put(name, declaration);
+
+ /* It also defined a new type, so add it to the type declarations. */
+ String variantPrefix = "variant "; //$NON-NLS-1$
+ registerType(variantPrefix + name, declaration);
+ }
+
+ // ------------------------------------------------------------------------
+ // Lookup operations
+ // ------------------------------------------------------------------------
+
+ /**
+ * Looks up a type declaration in the current scope.
+ *
+ * @param name
+ * The name of the type to search for.
+ * @return The type declaration, or null if no type with that name has been
+ * defined.
+ */
+ public IDeclaration lookupType(String name) {
+ return fTypes.get(name);
+ }
+
+ /**
+ * Looks up a type declaration in the current scope and recursively in the
+ * parent scopes.
+ *
+ * @param name
+ * The name of the type to search for.
+ * @return The type declaration, or null if no type with that name has been
+ * defined.
+ */
+ public IDeclaration lookupTypeRecursive(String name) {
+ IDeclaration declaration = lookupType(name);
+ if (declaration != null) {
+ return declaration;
+ } else if (fParentScope != null) {
+ return fParentScope.lookupTypeRecursive(name);
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Looks up a struct declaration.
+ *
+ * @param name
+ * The name of the struct to search for.
+ * @return The struct declaration, or null if no struct with that name has
+ * been defined.
+ */
+ public StructDeclaration lookupStruct(String name) {
+ return fStructs.get(name);
+ }
+
+ /**
+ * Looks up a struct declaration in the current scope and recursively in the
+ * parent scopes.
+ *
+ * @param name
+ * The name of the struct to search for.
+ * @return The struct declaration, or null if no struct with that name has
+ * been defined.
+ */
+ public StructDeclaration lookupStructRecursive(String name) {
+ StructDeclaration declaration = lookupStruct(name);
+ if (declaration != null) {
+ return declaration;
+ } else if (fParentScope != null) {
+ return fParentScope.lookupStructRecursive(name);
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Looks up an enum declaration.
+ *
+ * @param name
+ * The name of the enum to search for.
+ * @return The enum declaration, or null if no enum with that name has been
+ * defined.
+ */
+ public EnumDeclaration lookupEnum(String name) {
+ return fEnums.get(name);
+ }
+
+ /**
+ * Looks up an enum declaration in the current scope and recursively in the
+ * parent scopes.
+ *
+ * @param name
+ * The name of the enum to search for.
+ * @return The enum declaration, or null if no enum with that name has been
+ * defined.
+ */
+ public EnumDeclaration lookupEnumRecursive(String name) {
+ EnumDeclaration declaration = lookupEnum(name);
+ if (declaration != null) {
+ return declaration;
+ } else if (fParentScope != null) {
+ return fParentScope.lookupEnumRecursive(name);
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Looks up a variant declaration.
+ *
+ * @param name
+ * The name of the variant to search for.
+ * @return The variant declaration, or null if no variant with that name has
+ * been defined.
+ */
+ public VariantDeclaration lookupVariant(String name) {
+ return fVariants.get(name);
+ }
+
+ /**
+ * Looks up a variant declaration in the current scope and recursively in
+ * the parent scopes.
+ *
+ * @param name
+ * The name of the variant to search for.
+ * @return The variant declaration, or null if no variant with that name has
+ * been defined.
+ */
+ public VariantDeclaration lookupVariantRecursive(String name) {
+ VariantDeclaration declaration = lookupVariant(name);
+ if (declaration != null) {
+ return declaration;
+ } else if (fParentScope != null) {
+ return fParentScope.lookupVariantRecursive(name);
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Lookup query for an identifier in this scope.
+ *
+ * @param identifier
+ * the name of the identifier to search for. In the case of int
+ * x; it would be "x"
+ * @return the declaration of the type associated to that identifier
+ */
+ public IDeclaration lookupIdentifier(String identifier) {
+ return fIdentifiers.get(identifier);
+ }
+
+ /**
+ * Lookup query for an identifier through this scope and its ancestors.
+ * An ancestor scope is a scope in which this scope is nested.
+ *
+ * @param identifier
+ * the name of the identifier to search for. In the case of int
+ * x; it would be "x"
+ * @return the declaration of the type associated to that identifier
+ */
+ public IDeclaration lookupIdentifierRecursive(String identifier) {
+ IDeclaration declaration = lookupIdentifier(identifier);
+ if (declaration != null) {
+ return declaration;
+ } else if (fParentScope != null) {
+ return fParentScope.lookupIdentifierRecursive(identifier);
+ }
+ return null;
+ }
+
+ /**
+ * Get all the type names of this scope.
+ *
+ * @return The type names
+ */
+ public Set<String> getTypeNames() {
+ return fTypes.keySet();
+ }
+
+ /**
+ * Replace a type with a new one.
+ *
+ * @param name
+ * The name of the type
+ * @param newType
+ * The type
+ * @throws ParseException
+ * If the type does not exist.
+ */
+ public void replaceType(String name, IDeclaration newType) throws ParseException {
+ if (fTypes.containsKey(name)) {
+ fTypes.put(name, newType);
+ } else {
+ throw new ParseException("Trace does not contain type:" + name); //$NON-NLS-1$
+ }
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial Design and Grammar
+ * Francis Giraldeau - Initial API and implementation
+ * Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.internal.ctf.core.event.metadata;
+
+import java.math.BigInteger;
+import java.nio.ByteOrder;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+
+import org.antlr.runtime.tree.CommonTree;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.CTFClock;
+import org.eclipse.tracecompass.ctf.core.event.types.Encoding;
+import org.eclipse.tracecompass.ctf.core.event.types.EnumDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.FloatDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IEventHeaderDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StringDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.VariantDeclaration;
+import org.eclipse.tracecompass.ctf.core.trace.CTFStream;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTrace;
+import org.eclipse.tracecompass.ctf.parser.CTFParser;
+import org.eclipse.tracecompass.internal.ctf.core.Activator;
+import org.eclipse.tracecompass.internal.ctf.core.event.EventDeclaration;
+import org.eclipse.tracecompass.internal.ctf.core.event.metadata.exceptions.ParseException;
+import org.eclipse.tracecompass.internal.ctf.core.event.types.ArrayDeclaration;
+import org.eclipse.tracecompass.internal.ctf.core.event.types.SequenceDeclaration;
+import org.eclipse.tracecompass.internal.ctf.core.event.types.StructDeclarationFlattener;
+import org.eclipse.tracecompass.internal.ctf.core.event.types.composite.EventHeaderCompactDeclaration;
+import org.eclipse.tracecompass.internal.ctf.core.event.types.composite.EventHeaderLargeDeclaration;
+
+/**
+ * IOStructGen
+ */
+public class IOStructGen {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ private static final @NonNull String MAP = "map"; //$NON-NLS-1$
+ private static final @NonNull String ENCODING = "encoding"; //$NON-NLS-1$
+ private static final @NonNull String BASE = "base"; //$NON-NLS-1$
+ private static final @NonNull String SIZE = "size"; //$NON-NLS-1$
+ private static final @NonNull String SIGNED = "signed"; //$NON-NLS-1$
+ private static final @NonNull String LINE = "line"; //$NON-NLS-1$
+ private static final @NonNull String FILE = "file"; //$NON-NLS-1$
+ private static final @NonNull String IP = "ip"; //$NON-NLS-1$
+ private static final @NonNull String FUNC = "func"; //$NON-NLS-1$
+ private static final @NonNull String NAME = "name"; //$NON-NLS-1$
+ private static final @NonNull String EMPTY_STRING = ""; //$NON-NLS-1$
+ private static final int INTEGER_BASE_16 = 16;
+ private static final int INTEGER_BASE_10 = 10;
+ private static final int INTEGER_BASE_8 = 8;
+ private static final int INTEGER_BASE_2 = 2;
+ private static final long DEFAULT_ALIGNMENT = 8;
+ private static final int DEFAULT_FLOAT_EXPONENT = 8;
+ private static final int DEFAULT_FLOAT_MANTISSA = 24;
+ private static final int DEFAULT_INT_BASE = 10;
+ /**
+ * The trace
+ */
+ private final CTFTrace fTrace;
+ private CommonTree fTree;
+
+ /**
+ * The current declaration scope.
+ */
+ private DeclarationScope fScope = null;
+
+ /**
+ * Data helpers needed for streaming
+ */
+
+ private boolean fHasBeenParsed = false;
+
+ // ------------------------------------------------------------------------
+ // Constructor
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructor
+ *
+ * @param tree
+ * the tree (ANTLR generated) with the parsed TSDL data.
+ * @param trace
+ * the trace containing the places to put all the read metadata
+ */
+ public IOStructGen(CommonTree tree, CTFTrace trace) {
+ fTrace = trace;
+ fTree = tree;
+
+ }
+
+ /**
+ * Parse the tree and populate the trace defined in the constructor.
+ *
+ * @throws ParseException
+ * If there was a problem parsing the metadata
+ */
+ public void generate() throws ParseException {
+ parseRoot(fTree);
+ }
+
+ /**
+ * Parse a partial tree and populate the trace defined in the constructor.
+ * Does not check for a "trace" block as there is only one in the trace and
+ * thus
+ *
+ * @throws ParseException
+ * If there was a problem parsing the metadata
+ */
+ public void generateFragment() throws ParseException {
+ parseIncompleteRoot(fTree);
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ /**
+ * Sets a new tree to parse
+ *
+ * @param newTree
+ * the new tree to parse
+ */
+ public void setTree(CommonTree newTree) {
+ fTree = newTree;
+ }
+
+ /**
+ * Parse the root node.
+ *
+ * @param root
+ * A ROOT node.
+ * @throws ParseException
+ */
+ private void parseRoot(CommonTree root) throws ParseException {
+
+ List<CommonTree> children = root.getChildren();
+
+ CommonTree traceNode = null;
+ List<CommonTree> streams = new ArrayList<>();
+ List<CommonTree> events = new ArrayList<>();
+ List<CommonTree> declarations = new ArrayList<>();
+ List<CommonTree> environments = new ArrayList<>();
+ List<CommonTree> clocks = new ArrayList<>();
+ List<CommonTree> callsites = new ArrayList<>();
+
+ /* Create a new declaration scope with no parent. */
+ pushScope();
+
+ for (CommonTree child : children) {
+ final int type = child.getType();
+ switch (type) {
+ case CTFParser.DECLARATION:
+ declarations.add(child);
+ break;
+ case CTFParser.TRACE:
+ if (traceNode != null) {
+ throw new ParseException("Only one trace block is allowed"); //$NON-NLS-1$
+ }
+ traceNode = child;
+ break;
+ case CTFParser.STREAM:
+ streams.add(child);
+ break;
+ case CTFParser.EVENT:
+ events.add(child);
+ break;
+ case CTFParser.CLOCK:
+ clocks.add(child);
+ break;
+ case CTFParser.ENV:
+ environments.add(child);
+ break;
+ case CTFParser.CALLSITE:
+ callsites.add(child);
+ break;
+ default:
+ childTypeError(child);
+ }
+ }
+ for (CommonTree decl : declarations) {
+ parseRootDeclaration(decl);
+ }
+ if (traceNode == null) {
+ throw new ParseException("Missing trace block"); //$NON-NLS-1$
+ }
+
+ parseTrace(traceNode);
+
+ for (CommonTree environment : environments) {
+ parseEnvironment(environment);
+ }
+ for (CommonTree clock : clocks) {
+ parseClock(clock);
+ }
+ for (CommonTree callsite : callsites) {
+ parseCallsite(callsite);
+ }
+
+ if (!streams.isEmpty()) {
+ for (CommonTree stream : streams) {
+ parseStream(stream);
+ }
+ } else {
+ /* Add an empty stream that will have a null id */
+ fTrace.addStream(new CTFStream(fTrace));
+ }
+
+ for (CommonTree event : events) {
+ parseEvent(event);
+ }
+ popScope();
+ fHasBeenParsed = true;
+ }
+
+ private void parseIncompleteRoot(CommonTree root) throws ParseException {
+ List<CommonTree> children = root.getChildren();
+
+ if (!fHasBeenParsed) {
+ throw new ParseException("You need to run generate first"); //$NON-NLS-1$
+ }
+ List<CommonTree> streams = new ArrayList<>();
+ List<CommonTree> events = new ArrayList<>();
+ List<CommonTree> declarations = new ArrayList<>();
+ List<CommonTree> environments = new ArrayList<>();
+ List<CommonTree> clocks = new ArrayList<>();
+ List<CommonTree> callsites = new ArrayList<>();
+ /* Create a new declaration scope with no parent. */
+ pushScope();
+
+ for (CommonTree child : children) {
+ final int type = child.getType();
+ switch (type) {
+ case CTFParser.DECLARATION:
+ declarations.add(child);
+ break;
+ case CTFParser.TRACE:
+ throw new ParseException("Trace block defined here, please use generate and not generateFragment to parse this fragment"); //$NON-NLS-1$
+ case CTFParser.STREAM:
+ streams.add(child);
+ break;
+ case CTFParser.EVENT:
+ events.add(child);
+ break;
+ case CTFParser.CLOCK:
+ clocks.add(child);
+ break;
+ case CTFParser.ENV:
+ environments.add(child);
+ break;
+ case CTFParser.CALLSITE:
+ callsites.add(child);
+ break;
+ default:
+ childTypeError(child);
+ }
+ }
+ for (CommonTree decl : declarations) {
+ parseRootDeclaration(decl);
+ }
+
+ for (CommonTree environment : environments) {
+ parseEnvironment(environment);
+ }
+ for (CommonTree clock : clocks) {
+ parseClock(clock);
+ }
+ for (CommonTree callsite : callsites) {
+ parseCallsite(callsite);
+ }
+
+ for (CommonTree stream : streams) {
+ parseStream(stream);
+ }
+
+ for (CommonTree event : events) {
+ parseEvent(event);
+ }
+ popScope();
+ }
+
+ private void parseCallsite(CommonTree callsite) {
+
+ List<CommonTree> children = callsite.getChildren();
+ String name = null;
+ String funcName = null;
+ long lineNumber = -1;
+ long ip = -1;
+ String fileName = null;
+
+ for (CommonTree child : children) {
+ String left;
+ /* this is a regex to find the leading and trailing quotes */
+ final String regex = "^\"|\"$"; //$NON-NLS-1$
+ /*
+ * this is to replace the previous quotes with nothing...
+ * effectively deleting them
+ */
+ final String nullString = EMPTY_STRING;
+ left = child.getChild(0).getChild(0).getChild(0).getText();
+ if (left.equals(NAME)) {
+ name = child.getChild(1).getChild(0).getChild(0).getText().replaceAll(regex, nullString);
+ } else if (left.equals(FUNC)) {
+ funcName = child.getChild(1).getChild(0).getChild(0).getText().replaceAll(regex, nullString);
+ } else if (left.equals(IP)) {
+ ip = Long.decode(child.getChild(1).getChild(0).getChild(0).getText());
+ } else if (left.equals(FILE)) {
+ fileName = child.getChild(1).getChild(0).getChild(0).getText().replaceAll(regex, nullString);
+ } else if (left.equals(LINE)) {
+ lineNumber = Long.parseLong(child.getChild(1).getChild(0).getChild(0).getText());
+ }
+ }
+ fTrace.addCallsite(name, funcName, ip, fileName, lineNumber);
+ }
+
+ private void parseEnvironment(CommonTree environment) {
+ List<CommonTree> children = environment.getChildren();
+ for (CommonTree child : children) {
+ String left;
+ String right;
+ left = child.getChild(0).getChild(0).getChild(0).getText();
+ right = child.getChild(1).getChild(0).getChild(0).getText();
+ fTrace.addEnvironmentVar(left, right);
+ }
+ }
+
+ private void parseClock(CommonTree clock) throws ParseException {
+ List<CommonTree> children = clock.getChildren();
+ CTFClock ctfClock = new CTFClock();
+ for (CommonTree child : children) {
+ final String key = child.getChild(0).getChild(0).getChild(0).getText();
+ final CommonTree value = (CommonTree) child.getChild(1).getChild(0).getChild(0);
+ final int type = value.getType();
+ final String text = value.getText();
+ switch (type) {
+ case CTFParser.INTEGER:
+ case CTFParser.DECIMAL_LITERAL:
+ /*
+ * Not a pretty hack, this is to make sure that there is no
+ * number overflow due to 63 bit integers. The offset should
+ * only really be an issue in the year 2262. the tracer in C/ASM
+ * can write an offset in an unsigned 64 bit long. In java, the
+ * last bit, being set to 1 will be read as a negative number,
+ * but since it is too big a positive it will throw an
+ * exception. this will happen in 2^63 ns from 1970. Therefore
+ * 293 years from 1970
+ */
+ Long numValue;
+ try {
+ numValue = Long.parseLong(text);
+ } catch (NumberFormatException e) {
+ throw new ParseException("Number conversion issue with " + text, e); //$NON-NLS-1$
+ }
+ ctfClock.addAttribute(key, numValue);
+ break;
+ default:
+ ctfClock.addAttribute(key, text);
+ }
+
+ }
+ String nameValue = ctfClock.getName();
+ fTrace.addClock(nameValue, ctfClock);
+ }
+
+ private void parseTrace(CommonTree traceNode) throws ParseException {
+
+ List<CommonTree> children = traceNode.getChildren();
+ if (children == null) {
+ throw new ParseException("Trace block is empty"); //$NON-NLS-1$
+ }
+
+ pushScope();
+
+ for (CommonTree child : children) {
+ switch (child.getType()) {
+ case CTFParser.TYPEALIAS:
+ parseTypealias(child);
+ break;
+ case CTFParser.TYPEDEF:
+ parseTypedef(child);
+ break;
+ case CTFParser.CTF_EXPRESSION_TYPE:
+ case CTFParser.CTF_EXPRESSION_VAL:
+ parseTraceDeclaration(child);
+ break;
+ default:
+ childTypeError(child);
+ break;
+ }
+ }
+
+ /*
+ * If trace byte order was not specified and not using packet based
+ * metadata
+ */
+ if (fTrace.getByteOrder() == null) {
+ throw new ParseException("Trace byte order not set"); //$NON-NLS-1$
+ }
+
+ popScope();
+ }
+
+ private void parseTraceDeclaration(CommonTree traceDecl)
+ throws ParseException {
+
+ /* There should be a left and right */
+
+ CommonTree leftNode = (CommonTree) traceDecl.getChild(0);
+ CommonTree rightNode = (CommonTree) traceDecl.getChild(1);
+
+ List<CommonTree> leftStrings = leftNode.getChildren();
+
+ if (!isAnyUnaryString(leftStrings.get(0))) {
+ throw new ParseException("Left side of CTF assignment must be a string"); //$NON-NLS-1$
+ }
+
+ String left = concatenateUnaryStrings(leftStrings);
+
+ if (left.equals(MetadataStrings.MAJOR)) {
+ if (fTrace.majorIsSet()) {
+ throw new ParseException("major is already set"); //$NON-NLS-1$
+ }
+
+ fTrace.setMajor(getMajorOrMinor(rightNode));
+ } else if (left.equals(MetadataStrings.MINOR)) {
+ if (fTrace.minorIsSet()) {
+ throw new ParseException("minor is already set"); //$NON-NLS-1$
+ }
+
+ fTrace.setMinor(getMajorOrMinor(rightNode));
+ } else if (left.equals(MetadataStrings.UUID_STRING)) {
+ UUID uuid = getUUID(rightNode);
+
+ /*
+ * If uuid was already set by a metadata packet, compare it to see
+ * if it matches
+ */
+ if (fTrace.uuidIsSet()) {
+ if (fTrace.getUUID().compareTo(uuid) != 0) {
+ throw new ParseException("UUID mismatch. Packet says " //$NON-NLS-1$
+ + fTrace.getUUID() + " but metadata says " + uuid); //$NON-NLS-1$
+ }
+ } else {
+ fTrace.setUUID(uuid);
+ }
+
+ } else if (left.equals(MetadataStrings.BYTE_ORDER)) {
+ ByteOrder byteOrder = getByteOrder(rightNode);
+
+ /*
+ * If byte order was already set by a metadata packet, compare it to
+ * see if it matches
+ */
+ if (fTrace.getByteOrder() != null) {
+ if (fTrace.getByteOrder() != byteOrder) {
+ throw new ParseException(
+ "Endianness mismatch. Magic number says " //$NON-NLS-1$
+ + fTrace.getByteOrder()
+ + " but metadata says " + byteOrder); //$NON-NLS-1$
+ }
+ } else {
+ fTrace.setByteOrder(byteOrder);
+ final DeclarationScope parentScope = fScope.getParentScope();
+
+ for (String type : parentScope.getTypeNames()) {
+ IDeclaration d = parentScope.lookupType(type);
+ if (d instanceof IntegerDeclaration) {
+ addByteOrder(byteOrder, parentScope, type, (IntegerDeclaration) d);
+ } else if (d instanceof StructDeclaration) {
+ setAlign(parentScope, (StructDeclaration) d, byteOrder);
+ }
+ }
+ }
+ } else if (left.equals(MetadataStrings.PACKET_HEADER)) {
+ if (fTrace.packetHeaderIsSet()) {
+ throw new ParseException("packet.header already defined"); //$NON-NLS-1$
+ }
+
+ CommonTree typeSpecifier = (CommonTree) rightNode.getChild(0);
+
+ if (typeSpecifier.getType() != CTFParser.TYPE_SPECIFIER_LIST) {
+ throw new ParseException("packet.header expects a type specifier"); //$NON-NLS-1$
+ }
+
+ IDeclaration packetHeaderDecl = parseTypeSpecifierList(
+ typeSpecifier, null);
+
+ if (!(packetHeaderDecl instanceof StructDeclaration)) {
+ throw new ParseException("packet.header expects a struct"); //$NON-NLS-1$
+ }
+
+ fTrace.setPacketHeader((StructDeclaration) packetHeaderDecl);
+ } else {
+ Activator.log(IStatus.WARNING, Messages.IOStructGen_UnknownTraceAttributeWarning + " " + left); //$NON-NLS-1$
+ }
+ }
+
+ private static void addByteOrder(ByteOrder byteOrder,
+ final DeclarationScope parentScope, String name,
+ IntegerDeclaration decl) throws ParseException {
+
+ if (decl.getByteOrder() != byteOrder) {
+ IntegerDeclaration newI;
+ newI = IntegerDeclaration.createDeclaration(decl.getLength(), decl.isSigned(),
+ decl.getBase(), byteOrder, decl.getEncoding(),
+ decl.getClock(), decl.getAlignment());
+ parentScope.replaceType(name, newI);
+ }
+ }
+
+ private void setAlign(DeclarationScope parentScope, StructDeclaration sd,
+ ByteOrder byteOrder) throws ParseException {
+
+ for (String s : sd.getFieldsList()) {
+ IDeclaration d = sd.getField(s);
+
+ if (d instanceof StructDeclaration) {
+ setAlign(parentScope, (StructDeclaration) d, byteOrder);
+
+ } else if (d instanceof VariantDeclaration) {
+ setAlign(parentScope, (VariantDeclaration) d, byteOrder);
+ } else if (d instanceof IntegerDeclaration) {
+ IntegerDeclaration decl = (IntegerDeclaration) d;
+ if (decl.getByteOrder() != byteOrder) {
+ IntegerDeclaration newI;
+ newI = IntegerDeclaration.createDeclaration(decl.getLength(),
+ decl.isSigned(), decl.getBase(), byteOrder,
+ decl.getEncoding(), decl.getClock(),
+ decl.getAlignment());
+ sd.getFields().put(s, newI);
+ }
+ }
+ }
+ }
+
+ private void setAlign(DeclarationScope parentScope, VariantDeclaration vd,
+ ByteOrder byteOrder) throws ParseException {
+
+ for (String s : vd.getFields().keySet()) {
+ IDeclaration d = vd.getFields().get(s);
+
+ if (d instanceof StructDeclaration) {
+ setAlign(parentScope, (StructDeclaration) d, byteOrder);
+
+ } else if (d instanceof IntegerDeclaration) {
+ IntegerDeclaration decl = (IntegerDeclaration) d;
+ IntegerDeclaration newI;
+ newI = IntegerDeclaration.createDeclaration(decl.getLength(),
+ decl.isSigned(), decl.getBase(), byteOrder,
+ decl.getEncoding(), decl.getClock(),
+ decl.getAlignment());
+ vd.getFields().put(s, newI);
+ }
+ }
+ }
+
+ private void parseStream(CommonTree streamNode) throws ParseException {
+
+ CTFStream stream = new CTFStream(fTrace);
+
+ List<CommonTree> children = streamNode.getChildren();
+ if (children == null) {
+ throw new ParseException("Empty stream block"); //$NON-NLS-1$
+ }
+
+ pushScope();
+
+ for (CommonTree child : children) {
+ switch (child.getType()) {
+ case CTFParser.TYPEALIAS:
+ parseTypealias(child);
+ break;
+ case CTFParser.TYPEDEF:
+ parseTypedef(child);
+ break;
+ case CTFParser.CTF_EXPRESSION_TYPE:
+ case CTFParser.CTF_EXPRESSION_VAL:
+ parseStreamDeclaration(child, stream);
+ break;
+ default:
+ childTypeError(child);
+ break;
+ }
+ }
+
+ if (stream.isIdSet() &&
+ (!fTrace.packetHeaderIsSet() || !fTrace.getPacketHeader().hasField(MetadataStrings.STREAM_ID))) {
+ throw new ParseException("Stream has an ID, but there is no stream_id field in packet header."); //$NON-NLS-1$
+ }
+
+ fTrace.addStream(stream);
+
+ popScope();
+ }
+
+ private void parseStreamDeclaration(CommonTree streamDecl, CTFStream stream)
+ throws ParseException {
+
+ /* There should be a left and right */
+
+ CommonTree leftNode = (CommonTree) streamDecl.getChild(0);
+ CommonTree rightNode = (CommonTree) streamDecl.getChild(1);
+
+ List<CommonTree> leftStrings = leftNode.getChildren();
+
+ if (!isAnyUnaryString(leftStrings.get(0))) {
+ throw new ParseException("Left side of CTF assignment must be a string"); //$NON-NLS-1$
+ }
+
+ String left = concatenateUnaryStrings(leftStrings);
+
+ if (left.equals(MetadataStrings.ID)) {
+ if (stream.isIdSet()) {
+ throw new ParseException("stream id already defined"); //$NON-NLS-1$
+ }
+
+ long streamID = getStreamID(rightNode);
+
+ stream.setId(streamID);
+ } else if (left.equals(MetadataStrings.EVENT_HEADER)) {
+ if (stream.isEventHeaderSet()) {
+ throw new ParseException("event.header already defined"); //$NON-NLS-1$
+ }
+
+ CommonTree typeSpecifier = (CommonTree) rightNode.getChild(0);
+
+ if (typeSpecifier.getType() != CTFParser.TYPE_SPECIFIER_LIST) {
+ throw new ParseException("event.header expects a type specifier"); //$NON-NLS-1$
+ }
+
+ IDeclaration eventHeaderDecl = parseTypeSpecifierList(
+ typeSpecifier, null);
+
+ if (eventHeaderDecl instanceof StructDeclaration) {
+ stream.setEventHeader((StructDeclaration) eventHeaderDecl);
+ } else if (eventHeaderDecl instanceof IEventHeaderDeclaration) {
+ stream.setEventHeader((IEventHeaderDeclaration) eventHeaderDecl);
+ } else {
+ throw new ParseException("event.header expects a struct"); //$NON-NLS-1$
+ }
+
+ } else if (left.equals(MetadataStrings.EVENT_CONTEXT)) {
+ if (stream.isEventContextSet()) {
+ throw new ParseException("event.context already defined"); //$NON-NLS-1$
+ }
+
+ CommonTree typeSpecifier = (CommonTree) rightNode.getChild(0);
+
+ if (typeSpecifier.getType() != CTFParser.TYPE_SPECIFIER_LIST) {
+ throw new ParseException("event.context expects a type specifier"); //$NON-NLS-1$
+ }
+
+ IDeclaration eventContextDecl = parseTypeSpecifierList(
+ typeSpecifier, null);
+
+ if (!(eventContextDecl instanceof StructDeclaration)) {
+ throw new ParseException("event.context expects a struct"); //$NON-NLS-1$
+ }
+
+ stream.setEventContext((StructDeclaration) eventContextDecl);
+ } else if (left.equals(MetadataStrings.PACKET_CONTEXT)) {
+ if (stream.isPacketContextSet()) {
+ throw new ParseException("packet.context already defined"); //$NON-NLS-1$
+ }
+
+ CommonTree typeSpecifier = (CommonTree) rightNode.getChild(0);
+
+ if (typeSpecifier.getType() != CTFParser.TYPE_SPECIFIER_LIST) {
+ throw new ParseException("packet.context expects a type specifier"); //$NON-NLS-1$
+ }
+
+ IDeclaration packetContextDecl = parseTypeSpecifierList(
+ typeSpecifier, null);
+
+ if (!(packetContextDecl instanceof StructDeclaration)) {
+ throw new ParseException("packet.context expects a struct"); //$NON-NLS-1$
+ }
+
+ stream.setPacketContext((StructDeclaration) packetContextDecl);
+ } else {
+ Activator.log(IStatus.WARNING, Messages.IOStructGen_UnknownStreamAttributeWarning + " " + left); //$NON-NLS-1$
+ }
+ }
+
+ private void parseEvent(CommonTree eventNode) throws ParseException {
+
+ List<CommonTree> children = eventNode.getChildren();
+ if (children == null) {
+ throw new ParseException("Empty event block"); //$NON-NLS-1$
+ }
+
+ EventDeclaration event = new EventDeclaration();
+
+ pushScope();
+
+ for (CommonTree child : children) {
+ switch (child.getType()) {
+ case CTFParser.TYPEALIAS:
+ parseTypealias(child);
+ break;
+ case CTFParser.TYPEDEF:
+ parseTypedef(child);
+ break;
+ case CTFParser.CTF_EXPRESSION_TYPE:
+ case CTFParser.CTF_EXPRESSION_VAL:
+ parseEventDeclaration(child, event);
+ break;
+ default:
+ childTypeError(child);
+ break;
+ }
+ }
+
+ if (!event.nameIsSet()) {
+ throw new ParseException("Event name not set"); //$NON-NLS-1$
+ }
+
+ /*
+ * If the event did not specify a stream, then the trace must be single
+ * stream
+ */
+ if (!event.streamIsSet()) {
+ if (fTrace.nbStreams() > 1) {
+ throw new ParseException("Event without stream_id with more than one stream"); //$NON-NLS-1$
+ }
+
+ /*
+ * If the event did not specify a stream, the only existing stream
+ * must not have an id. Note: That behavior could be changed, it
+ * could be possible to just get the only existing stream, whatever
+ * is its id.
+ */
+ CTFStream stream = fTrace.getStream(null);
+
+ if (stream != null) {
+ event.setStream(stream);
+ } else {
+ throw new ParseException("Event without stream_id, but there is no stream without id"); //$NON-NLS-1$
+ }
+ }
+
+ /*
+ * Add the event to the stream.
+ */
+ event.getStream().addEvent(event);
+
+ popScope();
+ }
+
+ private void parseEventDeclaration(CommonTree eventDecl,
+ EventDeclaration event) throws ParseException {
+
+ /* There should be a left and right */
+
+ CommonTree leftNode = (CommonTree) eventDecl.getChild(0);
+ CommonTree rightNode = (CommonTree) eventDecl.getChild(1);
+
+ List<CommonTree> leftStrings = leftNode.getChildren();
+
+ if (!isAnyUnaryString(leftStrings.get(0))) {
+ throw new ParseException("Left side of CTF assignment must be a string"); //$NON-NLS-1$
+ }
+
+ String left = concatenateUnaryStrings(leftStrings);
+
+ if (left.equals(MetadataStrings.NAME2)) {
+ if (event.nameIsSet()) {
+ throw new ParseException("name already defined"); //$NON-NLS-1$
+ }
+
+ String name = getEventName(rightNode);
+
+ event.setName(name);
+ } else if (left.equals(MetadataStrings.ID)) {
+ if (event.idIsSet()) {
+ throw new ParseException("id already defined"); //$NON-NLS-1$
+ }
+
+ long id = getEventID(rightNode);
+ if (id > Integer.MAX_VALUE) {
+ throw new ParseException("id is greater than int.maxvalue, unsupported. id : " + id); //$NON-NLS-1$
+ }
+ if (id < 0) {
+ throw new ParseException("negative id, unsupported. id : " + id); //$NON-NLS-1$
+ }
+ event.setId((int) id);
+ } else if (left.equals(MetadataStrings.STREAM_ID)) {
+ if (event.streamIsSet()) {
+ throw new ParseException("stream id already defined"); //$NON-NLS-1$
+ }
+
+ long streamId = getStreamID(rightNode);
+
+ CTFStream stream = fTrace.getStream(streamId);
+
+ if (stream == null) {
+ throw new ParseException("Stream " + streamId + " not found"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ event.setStream(stream);
+ } else if (left.equals(MetadataStrings.CONTEXT)) {
+ if (event.contextIsSet()) {
+ throw new ParseException("context already defined"); //$NON-NLS-1$
+ }
+
+ CommonTree typeSpecifier = (CommonTree) rightNode.getChild(0);
+
+ if (typeSpecifier.getType() != CTFParser.TYPE_SPECIFIER_LIST) {
+ throw new ParseException("context expects a type specifier"); //$NON-NLS-1$
+ }
+
+ IDeclaration contextDecl = parseTypeSpecifierList(typeSpecifier,
+ null);
+
+ if (!(contextDecl instanceof StructDeclaration)) {
+ throw new ParseException("context expects a struct"); //$NON-NLS-1$
+ }
+
+ event.setContext((StructDeclaration) contextDecl);
+ } else if (left.equals(MetadataStrings.FIELDS_STRING)) {
+ if (event.fieldsIsSet()) {
+ throw new ParseException("fields already defined"); //$NON-NLS-1$
+ }
+
+ CommonTree typeSpecifier = (CommonTree) rightNode.getChild(0);
+
+ if (typeSpecifier.getType() != CTFParser.TYPE_SPECIFIER_LIST) {
+ throw new ParseException("fields expects a type specifier"); //$NON-NLS-1$
+ }
+
+ IDeclaration fieldsDecl;
+ fieldsDecl = parseTypeSpecifierList(typeSpecifier, null);
+
+ if (!(fieldsDecl instanceof StructDeclaration)) {
+ throw new ParseException("fields expects a struct"); //$NON-NLS-1$
+ }
+ /*
+ * The underscores in the event names. These underscores were added
+ * by the LTTng tracer.
+ */
+ final StructDeclaration fields = (StructDeclaration) fieldsDecl;
+ event.setFields(fields);
+ } else if (left.equals(MetadataStrings.LOGLEVEL2)) {
+ long logLevel = parseUnaryInteger((CommonTree) rightNode.getChild(0));
+ event.setLogLevel(logLevel);
+ } else {
+ /* Custom event attribute, we'll add it to the attributes map */
+ String right = parseUnaryString((CommonTree) rightNode.getChild(0));
+ event.setCustomAttribute(left, right);
+ }
+ }
+
+ /**
+ * Parses a declaration at the root level.
+ *
+ * @param declaration
+ * The declaration subtree.
+ * @throws ParseException
+ */
+ private void parseRootDeclaration(CommonTree declaration)
+ throws ParseException {
+
+ List<CommonTree> children = declaration.getChildren();
+
+ for (CommonTree child : children) {
+ switch (child.getType()) {
+ case CTFParser.TYPEDEF:
+ parseTypedef(child);
+ break;
+ case CTFParser.TYPEALIAS:
+ parseTypealias(child);
+ break;
+ case CTFParser.TYPE_SPECIFIER_LIST:
+ parseTypeSpecifierList(child, null);
+ break;
+ default:
+ childTypeError(child);
+ }
+ }
+ }
+
+ /**
+ * Parses a typealias node. It parses the target, the alias, and registers
+ * the type in the current scope.
+ *
+ * @param typealias
+ * A TYPEALIAS node.
+ * @throws ParseException
+ */
+ private void parseTypealias(CommonTree typealias) throws ParseException {
+
+ List<CommonTree> children = typealias.getChildren();
+
+ CommonTree target = null;
+ CommonTree alias = null;
+
+ for (CommonTree child : children) {
+ switch (child.getType()) {
+ case CTFParser.TYPEALIAS_TARGET:
+ target = child;
+ break;
+ case CTFParser.TYPEALIAS_ALIAS:
+ alias = child;
+ break;
+ default:
+ childTypeError(child);
+ break;
+ }
+ }
+
+ IDeclaration targetDeclaration = parseTypealiasTarget(target);
+
+ if ((targetDeclaration instanceof VariantDeclaration)
+ && ((VariantDeclaration) targetDeclaration).isTagged()) {
+ throw new ParseException("Typealias of untagged variant is not permitted"); //$NON-NLS-1$
+ }
+
+ String aliasString = parseTypealiasAlias(alias);
+
+ getCurrentScope().registerType(aliasString, targetDeclaration);
+ }
+
+ /**
+ * Parses the target part of a typealias and gets the corresponding
+ * declaration.
+ *
+ * @param target
+ * A TYPEALIAS_TARGET node.
+ * @return The corresponding declaration.
+ * @throws ParseException
+ */
+ private IDeclaration parseTypealiasTarget(CommonTree target)
+ throws ParseException {
+
+ List<CommonTree> children = target.getChildren();
+
+ CommonTree typeSpecifierList = null;
+ CommonTree typeDeclaratorList = null;
+ CommonTree typeDeclarator = null;
+ StringBuilder identifierSB = new StringBuilder();
+
+ for (CommonTree child : children) {
+ switch (child.getType()) {
+ case CTFParser.TYPE_SPECIFIER_LIST:
+ typeSpecifierList = child;
+ break;
+ case CTFParser.TYPE_DECLARATOR_LIST:
+ typeDeclaratorList = child;
+ break;
+ default:
+ childTypeError(child);
+ break;
+ }
+ }
+
+ if (typeDeclaratorList != null) {
+ /*
+ * Only allow one declarator
+ *
+ * eg: "typealias uint8_t *, ** := puint8_t;" is not permitted,
+ * otherwise the new type puint8_t would maps to two different
+ * types.
+ */
+ if (typeDeclaratorList.getChildCount() != 1) {
+ throw new ParseException("Only one type declarator is allowed in the typealias target"); //$NON-NLS-1$
+ }
+
+ typeDeclarator = (CommonTree) typeDeclaratorList.getChild(0);
+ }
+
+ /* Parse the target type and get the declaration */
+ IDeclaration targetDeclaration = parseTypeDeclarator(typeDeclarator,
+ typeSpecifierList, identifierSB);
+
+ /*
+ * We don't allow identifier in the target
+ *
+ * eg: "typealias uint8_t* hello := puint8_t;", the "hello" is not
+ * permitted
+ */
+ if (identifierSB.length() > 0) {
+ throw new ParseException("Identifier (" + identifierSB.toString() //$NON-NLS-1$
+ + ") not expected in the typealias target"); //$NON-NLS-1$
+ }
+
+ return targetDeclaration;
+ }
+
+ /**
+ * Parses the alias part of a typealias. It parses the underlying specifier
+ * list and declarator and creates the string representation that will be
+ * used to register the type.
+ *
+ * @param alias
+ * A TYPEALIAS_ALIAS node.
+ * @return The string representation of the alias.
+ * @throws ParseException
+ */
+ private static String parseTypealiasAlias(CommonTree alias)
+ throws ParseException {
+
+ List<CommonTree> children = alias.getChildren();
+
+ CommonTree typeSpecifierList = null;
+ CommonTree typeDeclaratorList = null;
+ CommonTree typeDeclarator = null;
+ List<CommonTree> pointers = new LinkedList<>();
+
+ for (CommonTree child : children) {
+ switch (child.getType()) {
+ case CTFParser.TYPE_SPECIFIER_LIST:
+ typeSpecifierList = child;
+ break;
+ case CTFParser.TYPE_DECLARATOR_LIST:
+ typeDeclaratorList = child;
+ break;
+ default:
+ childTypeError(child);
+ break;
+ }
+ }
+
+ /* If there is a type declarator list, extract the pointers */
+ if (typeDeclaratorList != null) {
+ /*
+ * Only allow one declarator
+ *
+ * eg: "typealias uint8_t := puint8_t *, **;" is not permitted.
+ */
+ if (typeDeclaratorList.getChildCount() != 1) {
+ throw new ParseException("Only one type declarator is allowed in the typealias alias"); //$NON-NLS-1$
+ }
+
+ typeDeclarator = (CommonTree) typeDeclaratorList.getChild(0);
+
+ List<CommonTree> typeDeclaratorChildren = typeDeclarator.getChildren();
+
+ for (CommonTree child : typeDeclaratorChildren) {
+ switch (child.getType()) {
+ case CTFParser.POINTER:
+ pointers.add(child);
+ break;
+ case CTFParser.IDENTIFIER:
+ throw new ParseException("Identifier (" + child.getText() //$NON-NLS-1$
+ + ") not expected in the typealias target"); //$NON-NLS-1$
+ default:
+ childTypeError(child);
+ break;
+ }
+ }
+ }
+
+ return createTypeDeclarationString(typeSpecifierList, pointers);
+ }
+
+ /**
+ * Parses a typedef node. This creates and registers a new declaration for
+ * each declarator found in the typedef.
+ *
+ * @param typedef
+ * A TYPEDEF node.
+ * @throws ParseException
+ * If there is an error creating the declaration.
+ */
+ private void parseTypedef(CommonTree typedef) throws ParseException {
+
+ CommonTree typeDeclaratorListNode = (CommonTree) typedef.getFirstChildWithType(CTFParser.TYPE_DECLARATOR_LIST);
+
+ CommonTree typeSpecifierListNode = (CommonTree) typedef.getFirstChildWithType(CTFParser.TYPE_SPECIFIER_LIST);
+
+ List<CommonTree> typeDeclaratorList = typeDeclaratorListNode.getChildren();
+
+ for (CommonTree typeDeclaratorNode : typeDeclaratorList) {
+ StringBuilder identifierSB = new StringBuilder();
+
+ IDeclaration typeDeclaration = parseTypeDeclarator(
+ typeDeclaratorNode, typeSpecifierListNode, identifierSB);
+
+ if ((typeDeclaration instanceof VariantDeclaration)
+ && ((VariantDeclaration) typeDeclaration).isTagged()) {
+ throw new ParseException("Typealias of untagged variant is not permitted"); //$NON-NLS-1$
+ }
+
+ getCurrentScope().registerType(identifierSB.toString(),
+ typeDeclaration);
+ }
+ }
+
+ /**
+ * Parses a pair type declarator / type specifier list and returns the
+ * corresponding declaration. If it is present, it also writes the
+ * identifier of the declarator in the given {@link StringBuilder}.
+ *
+ * @param typeDeclarator
+ * A TYPE_DECLARATOR node.
+ * @param typeSpecifierList
+ * A TYPE_SPECIFIER_LIST node.
+ * @param identifierSB
+ * A StringBuilder that will receive the identifier found in the
+ * declarator.
+ * @return The corresponding declaration.
+ * @throws ParseException
+ * If there is an error finding or creating the declaration.
+ */
+ private IDeclaration parseTypeDeclarator(CommonTree typeDeclarator,
+ CommonTree typeSpecifierList, StringBuilder identifierSB)
+ throws ParseException {
+
+ IDeclaration declaration = null;
+ List<CommonTree> children = null;
+ List<CommonTree> pointers = new LinkedList<>();
+ List<CommonTree> lengths = new LinkedList<>();
+ CommonTree identifier = null;
+
+ /* Separate the tokens by type */
+ if (typeDeclarator != null) {
+ children = typeDeclarator.getChildren();
+ for (CommonTree child : children) {
+
+ switch (child.getType()) {
+ case CTFParser.POINTER:
+ pointers.add(child);
+ break;
+ case CTFParser.IDENTIFIER:
+ identifier = child;
+ break;
+ case CTFParser.LENGTH:
+ lengths.add(child);
+ break;
+ default:
+ childTypeError(child);
+ break;
+ }
+ }
+
+ }
+
+ /*
+ * Parse the type specifier list, which is the "base" type. For example,
+ * it would be int in int a[3][len].
+ */
+ declaration = parseTypeSpecifierList(typeSpecifierList, pointers);
+
+ /*
+ * Each length subscript means that we must create a nested array or
+ * sequence. For example, int a[3][len] means that we have an array of 3
+ * (sequences of length 'len' of (int)).
+ */
+ if (!lengths.isEmpty()) {
+ /* We begin at the end */
+ Collections.reverse(lengths);
+
+ for (CommonTree length : lengths) {
+ /*
+ * By looking at the first expression, we can determine whether
+ * it is an array or a sequence.
+ */
+ List<CommonTree> lengthChildren = length.getChildren();
+
+ CommonTree first = lengthChildren.get(0);
+ if (isUnaryInteger(first)) {
+ /* Array */
+ int arrayLength = (int) parseUnaryInteger(first);
+
+ if (arrayLength < 1) {
+ throw new ParseException("Array length is negative"); //$NON-NLS-1$
+ }
+
+ /* Create the array declaration. */
+ declaration = new ArrayDeclaration(arrayLength, declaration);
+ } else if (isAnyUnaryString(first)) {
+ /* Sequence */
+ String lengthName = concatenateUnaryStrings(lengthChildren);
+
+ /* check that lengthName was declared */
+ if (isSignedIntegerField(lengthName)) {
+ throw new ParseException("Sequence declared with length that is not an unsigned integer"); //$NON-NLS-1$
+ }
+ /* Create the sequence declaration. */
+ declaration = new SequenceDeclaration(lengthName,
+ declaration);
+ } else {
+ childTypeError(first);
+ }
+ }
+ }
+
+ if (identifier != null) {
+ identifierSB.append(identifier.getText());
+ }
+
+ return declaration;
+ }
+
+ private boolean isSignedIntegerField(String lengthName) throws ParseException {
+ IDeclaration decl = getCurrentScope().lookupIdentifierRecursive(lengthName);
+ if (decl instanceof IntegerDeclaration) {
+ return ((IntegerDeclaration) decl).isSigned();
+ }
+ throw new ParseException("Is not an integer: " + lengthName); //$NON-NLS-1$
+
+ }
+
+ /**
+ * Parses a type specifier list and returns the corresponding declaration.
+ *
+ * @param typeSpecifierList
+ * A TYPE_SPECIFIER_LIST node.
+ * @param pointerList
+ * A list of POINTER nodes that apply to the specified type.
+ * @return The corresponding declaration.
+ * @throws ParseException
+ * If the type has not been defined or if there is an error
+ * creating the declaration.
+ */
+ private IDeclaration parseTypeSpecifierList(CommonTree typeSpecifierList,
+ List<CommonTree> pointerList) throws ParseException {
+ IDeclaration declaration = null;
+
+ /*
+ * By looking at the first element of the type specifier list, we can
+ * determine which type it belongs to.
+ */
+ CommonTree firstChild = (CommonTree) typeSpecifierList.getChild(0);
+
+ switch (firstChild.getType()) {
+ case CTFParser.FLOATING_POINT:
+ declaration = parseFloat(firstChild);
+ break;
+ case CTFParser.INTEGER:
+ declaration = parseInteger(firstChild);
+ break;
+ case CTFParser.STRING:
+ declaration = parseString(firstChild);
+ break;
+ case CTFParser.STRUCT:
+ declaration = parseStruct(firstChild);
+ StructDeclaration structDeclaration = (StructDeclaration) declaration;
+ IDeclaration idEnumDecl = structDeclaration.getFields().get("id"); //$NON-NLS-1$
+ if (EventHeaderCompactDeclaration.isCompactEventHeader(structDeclaration)) {
+ ByteOrder bo = ((EnumDeclaration) idEnumDecl).getContainerType().getByteOrder();
+ declaration = new EventHeaderCompactDeclaration(bo);
+ } else if (EventHeaderLargeDeclaration.isLargeEventHeader(structDeclaration)) {
+ ByteOrder bo = ((EnumDeclaration) idEnumDecl).getContainerType().getByteOrder();
+ declaration = new EventHeaderLargeDeclaration(bo);
+ }
+ break;
+ case CTFParser.VARIANT:
+ declaration = parseVariant(firstChild);
+ break;
+ case CTFParser.ENUM:
+ declaration = parseEnum(firstChild);
+ break;
+ case CTFParser.IDENTIFIER:
+ case CTFParser.FLOATTOK:
+ case CTFParser.INTTOK:
+ case CTFParser.LONGTOK:
+ case CTFParser.SHORTTOK:
+ case CTFParser.SIGNEDTOK:
+ case CTFParser.UNSIGNEDTOK:
+ case CTFParser.CHARTOK:
+ case CTFParser.DOUBLETOK:
+ case CTFParser.VOIDTOK:
+ case CTFParser.BOOLTOK:
+ case CTFParser.COMPLEXTOK:
+ case CTFParser.IMAGINARYTOK:
+ declaration = parseTypeDeclaration(typeSpecifierList, pointerList);
+ break;
+ default:
+ childTypeError(firstChild);
+ }
+
+ return declaration;
+ }
+
+ private IDeclaration parseFloat(CommonTree floatingPoint)
+ throws ParseException {
+
+ List<CommonTree> children = floatingPoint.getChildren();
+
+ /*
+ * If the integer has no attributes, then it is missing the size
+ * attribute which is required
+ */
+ if (children == null) {
+ throw new ParseException("float: missing size attribute"); //$NON-NLS-1$
+ }
+
+ /* The return value */
+ FloatDeclaration floatDeclaration = null;
+ ByteOrder byteOrder = fTrace.getByteOrder();
+ long alignment = 0;
+
+ int exponent = DEFAULT_FLOAT_EXPONENT;
+ int mantissa = DEFAULT_FLOAT_MANTISSA;
+
+ /* Iterate on all integer children */
+ for (CommonTree child : children) {
+ switch (child.getType()) {
+ case CTFParser.CTF_EXPRESSION_VAL:
+ /*
+ * An assignment expression must have 2 children, left and right
+ */
+
+ CommonTree leftNode = (CommonTree) child.getChild(0);
+ CommonTree rightNode = (CommonTree) child.getChild(1);
+
+ List<CommonTree> leftStrings = leftNode.getChildren();
+
+ if (!isAnyUnaryString(leftStrings.get(0))) {
+ throw new ParseException("Left side of ctf expression must be a string"); //$NON-NLS-1$
+ }
+ String left = concatenateUnaryStrings(leftStrings);
+
+ if (left.equals(MetadataStrings.EXP_DIG)) {
+ exponent = (int) parseUnaryInteger((CommonTree) rightNode.getChild(0));
+ } else if (left.equals(MetadataStrings.BYTE_ORDER)) {
+ byteOrder = getByteOrder(rightNode);
+ } else if (left.equals(MetadataStrings.MANT_DIG)) {
+ mantissa = (int) parseUnaryInteger((CommonTree) rightNode.getChild(0));
+ } else if (left.equals(MetadataStrings.ALIGN)) {
+ alignment = getAlignment(rightNode);
+ } else {
+ throw new ParseException("Float: unknown attribute " + left); //$NON-NLS-1$
+ }
+
+ break;
+ default:
+ childTypeError(child);
+ break;
+ }
+ }
+ int size = mantissa + exponent;
+ if (size == 0) {
+ throw new ParseException("Float missing size attribute"); //$NON-NLS-1$
+ }
+
+ if (alignment == 0) {
+ alignment = ((size % DEFAULT_ALIGNMENT) == 0) ? 1 : DEFAULT_ALIGNMENT;
+ }
+
+ floatDeclaration = new FloatDeclaration(exponent, mantissa, byteOrder, alignment);
+
+ return floatDeclaration;
+
+ }
+
+ /**
+ * Parses a type specifier list as a user-declared type.
+ *
+ * @param typeSpecifierList
+ * A TYPE_SPECIFIER_LIST node containing a user-declared type.
+ * @param pointerList
+ * A list of POINTER nodes that apply to the type specified in
+ * typeSpecifierList.
+ * @return The corresponding declaration.
+ * @throws ParseException
+ * If the type does not exist (has not been found).
+ */
+ private IDeclaration parseTypeDeclaration(CommonTree typeSpecifierList,
+ List<CommonTree> pointerList) throws ParseException {
+ /* Create the string representation of the type declaration */
+ String typeStringRepresentation = createTypeDeclarationString(
+ typeSpecifierList, pointerList);
+
+ /* Use the string representation to search the type in the current scope */
+ IDeclaration decl = getCurrentScope().lookupTypeRecursive(
+ typeStringRepresentation);
+
+ if (decl == null) {
+ throw new ParseException("Type " + typeStringRepresentation //$NON-NLS-1$
+ + " has not been defined."); //$NON-NLS-1$
+ }
+
+ return decl;
+ }
+
+ /**
+ * Parses an integer declaration node.
+ *
+ * @param integer
+ * An INTEGER node.
+ * @return The corresponding integer declaration.
+ * @throws ParseException
+ */
+ private IntegerDeclaration parseInteger(CommonTree integer)
+ throws ParseException {
+
+ List<CommonTree> children = integer.getChildren();
+
+ /*
+ * If the integer has no attributes, then it is missing the size
+ * attribute which is required
+ */
+ if (children == null) {
+ throw new ParseException("integer: missing size attribute"); //$NON-NLS-1$
+ }
+
+ /* The return value */
+ IntegerDeclaration integerDeclaration = null;
+ boolean signed = false;
+ ByteOrder byteOrder = fTrace.getByteOrder();
+ long size = 0;
+ long alignment = 0;
+ int base = DEFAULT_INT_BASE;
+ @NonNull
+ String clock = EMPTY_STRING;
+
+ Encoding encoding = Encoding.NONE;
+
+ /* Iterate on all integer children */
+ for (CommonTree child : children) {
+ switch (child.getType()) {
+ case CTFParser.CTF_EXPRESSION_VAL:
+ /*
+ * An assignment expression must have 2 children, left and right
+ */
+
+ CommonTree leftNode = (CommonTree) child.getChild(0);
+ CommonTree rightNode = (CommonTree) child.getChild(1);
+
+ List<CommonTree> leftStrings = leftNode.getChildren();
+
+ if (!isAnyUnaryString(leftStrings.get(0))) {
+ throw new ParseException("Left side of ctf expression must be a string"); //$NON-NLS-1$
+ }
+ String left = concatenateUnaryStrings(leftStrings);
+
+ if (left.equals(SIGNED)) {
+ signed = getSigned(rightNode);
+ } else if (left.equals(MetadataStrings.BYTE_ORDER)) {
+ byteOrder = getByteOrder(rightNode);
+ } else if (left.equals(SIZE)) {
+ size = getSize(rightNode);
+ } else if (left.equals(MetadataStrings.ALIGN)) {
+ alignment = getAlignment(rightNode);
+ } else if (left.equals(BASE)) {
+ base = getBase(rightNode);
+ } else if (left.equals(ENCODING)) {
+ encoding = getEncoding(rightNode);
+ } else if (left.equals(MAP)) {
+ clock = getClock(rightNode);
+ } else {
+ Activator.log(IStatus.WARNING, Messages.IOStructGen_UnknownIntegerAttributeWarning + " " + left); //$NON-NLS-1$
+ }
+
+ break;
+ default:
+ childTypeError(child);
+ break;
+ }
+ }
+
+ if (size == 0) {
+ throw new ParseException("Integer missing size attribute"); //$NON-NLS-1$
+ }
+
+ if (alignment == 0) {
+ alignment = ((size % DEFAULT_ALIGNMENT) == 0) ? 1 : DEFAULT_ALIGNMENT;
+ }
+
+ integerDeclaration = IntegerDeclaration.createDeclaration((int) size, signed, base,
+ byteOrder, encoding, clock, alignment);
+
+ return integerDeclaration;
+ }
+
+ @NonNull
+ private static String getClock(CommonTree rightNode) {
+ String clock = rightNode.getChild(1).getChild(0).getChild(0).getText();
+ return clock == null ? EMPTY_STRING : clock;
+ }
+
+ private static StringDeclaration parseString(CommonTree string)
+ throws ParseException {
+
+ List<CommonTree> children = string.getChildren();
+ StringDeclaration stringDeclaration = null;
+
+ if (children == null) {
+ stringDeclaration = new StringDeclaration();
+ } else {
+ Encoding encoding = Encoding.UTF8;
+ for (CommonTree child : children) {
+ switch (child.getType()) {
+ case CTFParser.CTF_EXPRESSION_VAL:
+ /*
+ * An assignment expression must have 2 children, left and
+ * right
+ */
+
+ CommonTree leftNode = (CommonTree) child.getChild(0);
+ CommonTree rightNode = (CommonTree) child.getChild(1);
+
+ List<CommonTree> leftStrings = leftNode.getChildren();
+
+ if (!isAnyUnaryString(leftStrings.get(0))) {
+ throw new ParseException("Left side of ctf expression must be a string"); //$NON-NLS-1$
+ }
+ String left = concatenateUnaryStrings(leftStrings);
+
+ if (left.equals(ENCODING)) {
+ encoding = getEncoding(rightNode);
+ } else {
+ throw new ParseException("String: unknown attribute " //$NON-NLS-1$
+ + left);
+ }
+
+ break;
+ default:
+ childTypeError(child);
+ break;
+ }
+ }
+
+ stringDeclaration = new StringDeclaration(encoding);
+ }
+
+ return stringDeclaration;
+ }
+
+ /**
+ * Parses a struct declaration and returns the corresponding declaration.
+ *
+ * @param struct
+ * An STRUCT node.
+ * @return The corresponding struct declaration.
+ * @throws ParseException
+ */
+ private StructDeclaration parseStruct(CommonTree struct)
+ throws ParseException {
+
+ List<CommonTree> children = struct.getChildren();
+
+ /* The return value */
+ StructDeclaration structDeclaration = null;
+
+ /* Name */
+ String structName = null;
+ boolean hasName = false;
+
+ /* Body */
+ CommonTree structBody = null;
+ boolean hasBody = false;
+
+ /* Align */
+ long structAlign = 0;
+
+ /* Loop on all children and identify what we have to work with. */
+ for (CommonTree child : children) {
+ switch (child.getType()) {
+ case CTFParser.STRUCT_NAME: {
+ hasName = true;
+
+ CommonTree structNameIdentifier = (CommonTree) child.getChild(0);
+
+ structName = structNameIdentifier.getText();
+
+ break;
+ }
+ case CTFParser.STRUCT_BODY: {
+ hasBody = true;
+
+ structBody = child;
+
+ break;
+ }
+ case CTFParser.ALIGN: {
+ CommonTree structAlignExpression = (CommonTree) child.getChild(0);
+
+ structAlign = getAlignment(structAlignExpression);
+
+ break;
+ }
+ default:
+ childTypeError(child);
+
+ break;
+ }
+ }
+
+ /*
+ * If a struct has just a body and no name (just like the song,
+ * "A Struct With No Name" by America (sorry for that...)), it's a
+ * definition of a new type, so we create the type declaration and
+ * return it. We can't add it to the declaration scope since there is no
+ * name, but that's what we want because it won't be possible to use it
+ * again to declare another field.
+ *
+ * If it has just a name, we look it up in the declaration scope and
+ * return the associated declaration. If it is not found in the
+ * declaration scope, it means that a struct with that name has not been
+ * declared, which is an error.
+ *
+ * If it has both, then we create the type declaration and register it
+ * to the current scope.
+ *
+ * If it has none, then what are we doing here ?
+ */
+ if (hasBody) {
+ /*
+ * If struct has a name, check if already defined in the current
+ * scope.
+ */
+ if (hasName && (getCurrentScope().lookupStruct(structName) != null)) {
+ throw new ParseException("struct " + structName //$NON-NLS-1$
+ + " already defined."); //$NON-NLS-1$
+ }
+ /* Create the declaration */
+ structDeclaration = new StructDeclaration(structAlign);
+
+ /* Parse the body */
+ parseStructBody(structBody, structDeclaration);
+
+ /* If struct has name, add it to the current scope. */
+ if (hasName) {
+ getCurrentScope().registerStruct(structName, structDeclaration);
+ }
+ } else /* !hasBody */{
+ if (hasName) {
+ /* Name and !body */
+
+ /* Lookup the name in the current scope. */
+ structDeclaration = getCurrentScope().lookupStructRecursive(structName);
+
+ /*
+ * If not found, it means that a struct with such name has not
+ * been defined
+ */
+ if (structDeclaration == null) {
+ throw new ParseException("struct " + structName //$NON-NLS-1$
+ + " is not defined"); //$NON-NLS-1$
+ }
+ } else {
+ /* !Name and !body */
+
+ /* We can't do anything with that. */
+ throw new ParseException("struct with no name and no body"); //$NON-NLS-1$
+ }
+ }
+ return StructDeclarationFlattener.tryFlattenStruct(structDeclaration);
+ }
+
+ /**
+ * Parses a struct body, adding the fields to specified structure
+ * declaration.
+ *
+ * @param structBody
+ * A STRUCT_BODY node.
+ * @param structDeclaration
+ * The struct declaration.
+ * @throws ParseException
+ */
+ private void parseStructBody(CommonTree structBody,
+ StructDeclaration structDeclaration) throws ParseException {
+
+ List<CommonTree> structDeclarations = structBody.getChildren();
+
+ /*
+ * If structDeclaration is null, structBody has no children and the
+ * struct body is empty.
+ */
+ if (structDeclarations != null) {
+ pushScope();
+
+ for (CommonTree declarationNode : structDeclarations) {
+ switch (declarationNode.getType()) {
+ case CTFParser.TYPEALIAS:
+ parseTypealias(declarationNode);
+ break;
+ case CTFParser.TYPEDEF:
+ parseTypedef(declarationNode);
+ break;
+ case CTFParser.SV_DECLARATION:
+ parseStructDeclaration(declarationNode, structDeclaration);
+ break;
+ default:
+ childTypeError(declarationNode);
+ break;
+ }
+ }
+ popScope();
+ }
+ }
+
+ /**
+ * Parses a declaration found in a struct.
+ *
+ * @param declaration
+ * A SV_DECLARATION node.
+ * @param struct
+ * A struct declaration. (I know, little name clash here...)
+ * @throws ParseException
+ */
+ private void parseStructDeclaration(CommonTree declaration,
+ StructDeclaration struct) throws ParseException {
+
+ /* Get the type specifier list node */
+ CommonTree typeSpecifierListNode = (CommonTree) declaration.getFirstChildWithType(CTFParser.TYPE_SPECIFIER_LIST);
+
+ /* Get the type declarator list node */
+ CommonTree typeDeclaratorListNode = (CommonTree) declaration.getFirstChildWithType(CTFParser.TYPE_DECLARATOR_LIST);
+
+ /* Get the type declarator list */
+ List<CommonTree> typeDeclaratorList = typeDeclaratorListNode.getChildren();
+
+ /*
+ * For each type declarator, parse the declaration and add a field to
+ * the struct
+ */
+ for (CommonTree typeDeclaratorNode : typeDeclaratorList) {
+
+ StringBuilder identifierSB = new StringBuilder();
+
+ IDeclaration decl = parseTypeDeclarator(typeDeclaratorNode,
+ typeSpecifierListNode, identifierSB);
+ String fieldName = identifierSB.toString();
+ getCurrentScope().registerIdentifier(fieldName, decl);
+
+ if (struct.hasField(fieldName)) {
+ throw new ParseException("struct: duplicate field " //$NON-NLS-1$
+ + fieldName);
+ }
+
+ struct.addField(fieldName, decl);
+
+ }
+ }
+
+ /**
+ * Parses an enum declaration and returns the corresponding declaration.
+ *
+ * @param theEnum
+ * An ENUM node.
+ * @return The corresponding enum declaration.
+ * @throws ParseException
+ */
+ private EnumDeclaration parseEnum(CommonTree theEnum) throws ParseException {
+
+ List<CommonTree> children = theEnum.getChildren();
+
+ /* The return value */
+ EnumDeclaration enumDeclaration = null;
+
+ /* Name */
+ String enumName = null;
+
+ /* Body */
+ CommonTree enumBody = null;
+
+ /* Container type */
+ IntegerDeclaration containerTypeDeclaration = null;
+
+ /* Loop on all children and identify what we have to work with. */
+ for (CommonTree child : children) {
+ switch (child.getType()) {
+ case CTFParser.ENUM_NAME: {
+ CommonTree enumNameIdentifier = (CommonTree) child.getChild(0);
+ enumName = enumNameIdentifier.getText();
+ break;
+ }
+ case CTFParser.ENUM_BODY: {
+ enumBody = child;
+ break;
+ }
+ case CTFParser.ENUM_CONTAINER_TYPE: {
+ containerTypeDeclaration = parseEnumContainerType(child);
+ break;
+ }
+ default:
+ childTypeError(child);
+ break;
+ }
+ }
+
+ /*
+ * If the container type has not been defined explicitly, we assume it
+ * is "int".
+ */
+ if (containerTypeDeclaration == null) {
+ IDeclaration enumDecl;
+ /*
+ * it could be because the enum was already declared.
+ */
+ if (enumName != null) {
+ enumDecl = getCurrentScope().lookupEnumRecursive(enumName);
+ if (enumDecl != null) {
+ return (EnumDeclaration) enumDecl;
+ }
+ }
+
+ IDeclaration decl = getCurrentScope().lookupTypeRecursive("int"); //$NON-NLS-1$
+
+ if (decl == null) {
+ throw new ParseException("enum container type implicit and type int not defined"); //$NON-NLS-1$
+ } else if (!(decl instanceof IntegerDeclaration)) {
+ throw new ParseException("enum container type implicit and type int not an integer"); //$NON-NLS-1$
+ }
+
+ containerTypeDeclaration = (IntegerDeclaration) decl;
+ }
+
+ /*
+ * If it has a body, it's a new declaration, otherwise it's a reference
+ * to an existing declaration. Same logic as struct.
+ */
+ if (enumBody != null) {
+ /*
+ * If enum has a name, check if already defined in the current
+ * scope.
+ */
+ if ((enumName != null)
+ && (getCurrentScope().lookupEnum(enumName) != null)) {
+ throw new ParseException("enum " + enumName //$NON-NLS-1$
+ + " already defined"); //$NON-NLS-1$
+ }
+
+ /* Create the declaration */
+ enumDeclaration = new EnumDeclaration(containerTypeDeclaration);
+
+ /* Parse the body */
+ parseEnumBody(enumBody, enumDeclaration);
+
+ /* If the enum has name, add it to the current scope. */
+ if (enumName != null) {
+ getCurrentScope().registerEnum(enumName, enumDeclaration);
+ }
+ } else {
+ if (enumName != null) {
+ /* Name and !body */
+
+ /* Lookup the name in the current scope. */
+ enumDeclaration = getCurrentScope().lookupEnumRecursive(enumName);
+
+ /*
+ * If not found, it means that an enum with such name has not
+ * been defined
+ */
+ if (enumDeclaration == null) {
+ throw new ParseException("enum " + enumName //$NON-NLS-1$
+ + " is not defined"); //$NON-NLS-1$
+ }
+ } else {
+ /* !Name and !body */
+ throw new ParseException("enum with no name and no body"); //$NON-NLS-1$
+ }
+ }
+
+ return enumDeclaration;
+
+ }
+
+ /**
+ * Parses an enum body, adding the enumerators to the specified enum
+ * declaration.
+ *
+ * @param enumBody
+ * An ENUM_BODY node.
+ * @param enumDeclaration
+ * The enum declaration.
+ * @throws ParseException
+ */
+ private void parseEnumBody(CommonTree enumBody,
+ EnumDeclaration enumDeclaration) throws ParseException {
+
+ List<CommonTree> enumerators = enumBody.getChildren();
+ /* enum body can't be empty (unlike struct). */
+
+ pushScope();
+
+ /*
+ * Start at -1, so that if the first enumrator has no explicit value, it
+ * will choose 0
+ */
+ long lastHigh = -1;
+
+ for (CommonTree enumerator : enumerators) {
+ lastHigh = parseEnumEnumerator(enumerator, enumDeclaration,
+ lastHigh);
+ }
+
+ popScope();
+
+ }
+
+ /**
+ * Parses an enumerator node and adds an enumerator declaration to an
+ * enumeration declaration.
+ *
+ * The high value of the range of the last enumerator is needed in case the
+ * current enumerator does not specify its value.
+ *
+ * @param enumerator
+ * An ENUM_ENUMERATOR node.
+ * @param enumDeclaration
+ * en enumeration declaration to which will be added the
+ * enumerator.
+ * @param lastHigh
+ * The high value of the range of the last enumerator
+ * @return The high value of the value range of the current enumerator.
+ * @throws ParseException
+ */
+ private static long parseEnumEnumerator(CommonTree enumerator,
+ EnumDeclaration enumDeclaration, long lastHigh)
+ throws ParseException {
+
+ List<CommonTree> children = enumerator.getChildren();
+
+ long low = 0, high = 0;
+ boolean valueSpecified = false;
+ String label = null;
+
+ for (CommonTree child : children) {
+ if (isAnyUnaryString(child)) {
+ label = parseUnaryString(child);
+ } else if (child.getType() == CTFParser.ENUM_VALUE) {
+
+ valueSpecified = true;
+
+ low = parseUnaryInteger((CommonTree) child.getChild(0));
+ high = low;
+ } else if (child.getType() == CTFParser.ENUM_VALUE_RANGE) {
+
+ valueSpecified = true;
+
+ low = parseUnaryInteger((CommonTree) child.getChild(0));
+ high = parseUnaryInteger((CommonTree) child.getChild(1));
+ } else {
+ childTypeError(child);
+ }
+ }
+
+ if (!valueSpecified) {
+ low = lastHigh + 1;
+ high = low;
+ }
+
+ if (low > high) {
+ throw new ParseException("enum low value greater than high value"); //$NON-NLS-1$
+ }
+
+ if (!enumDeclaration.add(low, high, label)) {
+ throw new ParseException("enum declarator values overlap."); //$NON-NLS-1$
+ }
+
+ if (valueSpecified && (BigInteger.valueOf(low).compareTo(enumDeclaration.getContainerType().getMinValue()) == -1 ||
+ BigInteger.valueOf(high).compareTo(enumDeclaration.getContainerType().getMaxValue()) == 1)) {
+ throw new ParseException("enum value is not in range"); //$NON-NLS-1$
+ }
+
+ return high;
+ }
+
+ /**
+ * Parses an enum container type node and returns the corresponding integer
+ * type.
+ *
+ * @param enumContainerType
+ * An ENUM_CONTAINER_TYPE node.
+ * @return An integer declaration corresponding to the container type.
+ * @throws ParseException
+ * If the type does not parse correctly or if it is not an
+ * integer type.
+ */
+ private IntegerDeclaration parseEnumContainerType(
+ CommonTree enumContainerType) throws ParseException {
+
+ /* Get the child, which should be a type specifier list */
+ CommonTree typeSpecifierList = (CommonTree) enumContainerType.getChild(0);
+
+ /* Parse it and get the corresponding declaration */
+ IDeclaration decl = parseTypeSpecifierList(typeSpecifierList, null);
+
+ /* If is is an integer, return it, else throw an error */
+ if (decl instanceof IntegerDeclaration) {
+ return (IntegerDeclaration) decl;
+ }
+ throw new ParseException("enum container type must be an integer"); //$NON-NLS-1$
+ }
+
+ private VariantDeclaration parseVariant(CommonTree variant)
+ throws ParseException {
+
+ List<CommonTree> children = variant.getChildren();
+ VariantDeclaration variantDeclaration = null;
+
+ boolean hasName = false;
+ String variantName = null;
+
+ boolean hasBody = false;
+ CommonTree variantBody = null;
+
+ boolean hasTag = false;
+ String variantTag = null;
+
+ for (CommonTree child : children) {
+ switch (child.getType()) {
+ case CTFParser.VARIANT_NAME:
+
+ hasName = true;
+
+ CommonTree variantNameIdentifier = (CommonTree) child.getChild(0);
+
+ variantName = variantNameIdentifier.getText();
+
+ break;
+ case CTFParser.VARIANT_TAG:
+
+ hasTag = true;
+
+ CommonTree variantTagIdentifier = (CommonTree) child.getChild(0);
+
+ variantTag = variantTagIdentifier.getText();
+
+ break;
+ case CTFParser.VARIANT_BODY:
+
+ hasBody = true;
+
+ variantBody = child;
+
+ break;
+ default:
+ childTypeError(child);
+ break;
+ }
+ }
+
+ if (hasBody) {
+ /*
+ * If variant has a name, check if already defined in the current
+ * scope.
+ */
+ if (hasName
+ && (getCurrentScope().lookupVariant(variantName) != null)) {
+ throw new ParseException("variant " + variantName //$NON-NLS-1$
+ + " already defined."); //$NON-NLS-1$
+ }
+
+ /* Create the declaration */
+ variantDeclaration = new VariantDeclaration();
+
+ /* Parse the body */
+ parseVariantBody(variantBody, variantDeclaration);
+
+ /* If variant has name, add it to the current scope. */
+ if (hasName) {
+ getCurrentScope().registerVariant(variantName,
+ variantDeclaration);
+ }
+ } else /* !hasBody */{
+ if (hasName) {
+ /* Name and !body */
+
+ /* Lookup the name in the current scope. */
+ variantDeclaration = getCurrentScope().lookupVariantRecursive(
+ variantName);
+
+ /*
+ * If not found, it means that a struct with such name has not
+ * been defined
+ */
+ if (variantDeclaration == null) {
+ throw new ParseException("variant " + variantName //$NON-NLS-1$
+ + " is not defined"); //$NON-NLS-1$
+ }
+ } else {
+ /* !Name and !body */
+
+ /* We can't do anything with that. */
+ throw new ParseException("variant with no name and no body"); //$NON-NLS-1$
+ }
+ }
+
+ if (hasTag) {
+ variantDeclaration.setTag(variantTag);
+
+ IDeclaration decl = getCurrentScope().lookupIdentifierRecursive(variantTag);
+ if (decl == null) {
+ throw new ParseException("Variant tag not found: " + variantTag); //$NON-NLS-1$
+ }
+ if (!(decl instanceof EnumDeclaration)) {
+ throw new ParseException("Variant tag must be an enum: " + variantTag); //$NON-NLS-1$
+ }
+ EnumDeclaration tagDecl = (EnumDeclaration) decl;
+ Set<String> intersection = new HashSet<>(tagDecl.getLabels());
+ intersection.retainAll(variantDeclaration.getFields().keySet());
+ if (intersection.isEmpty()) {
+ throw new ParseException("Variant contains no values of the tag, impossible to use: " + variantName); //$NON-NLS-1$
+ }
+ }
+
+ return variantDeclaration;
+ }
+
+ private void parseVariantBody(CommonTree variantBody,
+ VariantDeclaration variantDeclaration) throws ParseException {
+
+ List<CommonTree> variantDeclarations = variantBody.getChildren();
+
+ pushScope();
+
+ for (CommonTree declarationNode : variantDeclarations) {
+ switch (declarationNode.getType()) {
+ case CTFParser.TYPEALIAS:
+ parseTypealias(declarationNode);
+ break;
+ case CTFParser.TYPEDEF:
+ parseTypedef(declarationNode);
+ break;
+ case CTFParser.SV_DECLARATION:
+ parseVariantDeclaration(declarationNode, variantDeclaration);
+ break;
+ default:
+ childTypeError(declarationNode);
+ break;
+ }
+ }
+
+ popScope();
+ }
+
+ private void parseVariantDeclaration(CommonTree declaration,
+ VariantDeclaration variant) throws ParseException {
+
+ /* Get the type specifier list node */
+ CommonTree typeSpecifierListNode = (CommonTree) declaration.getFirstChildWithType(CTFParser.TYPE_SPECIFIER_LIST);
+
+ /* Get the type declarator list node */
+ CommonTree typeDeclaratorListNode = (CommonTree) declaration.getFirstChildWithType(CTFParser.TYPE_DECLARATOR_LIST);
+
+ /* Get the type declarator list */
+ List<CommonTree> typeDeclaratorList = typeDeclaratorListNode.getChildren();
+
+ /*
+ * For each type declarator, parse the declaration and add a field to
+ * the variant
+ */
+ for (CommonTree typeDeclaratorNode : typeDeclaratorList) {
+
+ StringBuilder identifierSB = new StringBuilder();
+
+ IDeclaration decl = parseTypeDeclarator(typeDeclaratorNode,
+ typeSpecifierListNode, identifierSB);
+
+ String name = identifierSB.toString();
+
+ if (variant.hasField(name)) {
+ throw new ParseException("variant: duplicate field " //$NON-NLS-1$
+ + name);
+ }
+
+ getCurrentScope().registerIdentifier(name, decl);
+
+ variant.addField(name, decl);
+ }
+ }
+
+ /**
+ * Creates the string representation of a type declaration (type specifier
+ * list + pointers).
+ *
+ * @param typeSpecifierList
+ * A TYPE_SPECIFIER_LIST node.
+ * @param pointers
+ * A list of POINTER nodes.
+ * @return The string representation.
+ * @throws ParseException
+ */
+ private static String createTypeDeclarationString(
+ CommonTree typeSpecifierList, List<CommonTree> pointers)
+ throws ParseException {
+ StringBuilder sb = new StringBuilder();
+
+ createTypeSpecifierListString(typeSpecifierList, sb);
+ createPointerListString(pointers, sb);
+
+ return sb.toString();
+ }
+
+ /**
+ * Creates the string representation of a list of type specifiers.
+ *
+ * @param typeSpecifierList
+ * A TYPE_SPECIFIER_LIST node.
+ * @param sb
+ * A StringBuilder to which will be appended the string.
+ * @throws ParseException
+ */
+ private static void createTypeSpecifierListString(
+ CommonTree typeSpecifierList, StringBuilder sb)
+ throws ParseException {
+
+ List<CommonTree> children = typeSpecifierList.getChildren();
+
+ boolean firstItem = true;
+
+ for (CommonTree child : children) {
+ if (!firstItem) {
+ sb.append(' ');
+
+ }
+
+ firstItem = false;
+
+ /* Append the string that represents this type specifier. */
+ createTypeSpecifierString(child, sb);
+ }
+ }
+
+ /**
+ * Creates the string representation of a type specifier.
+ *
+ * @param typeSpecifier
+ * A TYPE_SPECIFIER node.
+ * @param sb
+ * A StringBuilder to which will be appended the string.
+ * @throws ParseException
+ */
+ private static void createTypeSpecifierString(CommonTree typeSpecifier,
+ StringBuilder sb) throws ParseException {
+ switch (typeSpecifier.getType()) {
+ case CTFParser.FLOATTOK:
+ case CTFParser.INTTOK:
+ case CTFParser.LONGTOK:
+ case CTFParser.SHORTTOK:
+ case CTFParser.SIGNEDTOK:
+ case CTFParser.UNSIGNEDTOK:
+ case CTFParser.CHARTOK:
+ case CTFParser.DOUBLETOK:
+ case CTFParser.VOIDTOK:
+ case CTFParser.BOOLTOK:
+ case CTFParser.COMPLEXTOK:
+ case CTFParser.IMAGINARYTOK:
+ case CTFParser.CONSTTOK:
+ case CTFParser.IDENTIFIER:
+ sb.append(typeSpecifier.getText());
+ break;
+ case CTFParser.STRUCT: {
+ CommonTree structName = (CommonTree) typeSpecifier.getFirstChildWithType(CTFParser.STRUCT_NAME);
+ if (structName == null) {
+ throw new ParseException("nameless struct found in createTypeSpecifierString"); //$NON-NLS-1$
+ }
+
+ CommonTree structNameIdentifier = (CommonTree) structName.getChild(0);
+
+ sb.append(structNameIdentifier.getText());
+ break;
+ }
+ case CTFParser.VARIANT: {
+ CommonTree variantName = (CommonTree) typeSpecifier.getFirstChildWithType(CTFParser.VARIANT_NAME);
+ if (variantName == null) {
+ throw new ParseException("nameless variant found in createTypeSpecifierString"); //$NON-NLS-1$
+ }
+
+ CommonTree variantNameIdentifier = (CommonTree) variantName.getChild(0);
+
+ sb.append(variantNameIdentifier.getText());
+ break;
+ }
+ case CTFParser.ENUM: {
+ CommonTree enumName = (CommonTree) typeSpecifier.getFirstChildWithType(CTFParser.ENUM_NAME);
+ if (enumName == null) {
+ throw new ParseException("nameless enum found in createTypeSpecifierString"); //$NON-NLS-1$
+ }
+
+ CommonTree enumNameIdentifier = (CommonTree) enumName.getChild(0);
+
+ sb.append(enumNameIdentifier.getText());
+ break;
+ }
+ case CTFParser.FLOATING_POINT:
+ case CTFParser.INTEGER:
+ case CTFParser.STRING:
+ throw new ParseException("CTF type found in createTypeSpecifierString"); //$NON-NLS-1$
+ default:
+ childTypeError(typeSpecifier);
+ break;
+ }
+ }
+
+ /**
+ * Creates the string representation of a list of pointers.
+ *
+ * @param pointerList
+ * A list of pointer nodes. If pointerList is null, this function
+ * does nothing.
+ * @param sb
+ * A stringbuilder to which will be appended the string.
+ */
+ private static void createPointerListString(List<CommonTree> pointerList,
+ StringBuilder sb) {
+ if (pointerList == null) {
+ return;
+ }
+
+ for (CommonTree pointer : pointerList) {
+
+ sb.append(" *"); //$NON-NLS-1$
+ if (pointer.getChildCount() > 0) {
+
+ sb.append(" const"); //$NON-NLS-1$
+ }
+ }
+ }
+
+ /**
+ * @param node
+ * The node to check.
+ * @return True if the given node is an unary string.
+ */
+ private static boolean isUnaryString(CommonTree node) {
+ return ((node.getType() == CTFParser.UNARY_EXPRESSION_STRING));
+ }
+
+ /**
+ * @param node
+ * The node to check.
+ * @return True if the given node is any type of unary string (no quotes,
+ * quotes, etc).
+ */
+ private static boolean isAnyUnaryString(CommonTree node) {
+ return ((node.getType() == CTFParser.UNARY_EXPRESSION_STRING) || (node.getType() == CTFParser.UNARY_EXPRESSION_STRING_QUOTES));
+ }
+
+ /**
+ * @param node
+ * The node to check.
+ * @return True if the given node is an unary integer.
+ */
+ private static boolean isUnaryInteger(CommonTree node) {
+ return ((node.getType() == CTFParser.UNARY_EXPRESSION_DEC) ||
+ (node.getType() == CTFParser.UNARY_EXPRESSION_HEX) || (node.getType() == CTFParser.UNARY_EXPRESSION_OCT));
+ }
+
+ /**
+ * Parses a unary string node and return the string value.
+ *
+ * @param unaryString
+ * The unary string node to parse (type UNARY_EXPRESSION_STRING
+ * or UNARY_EXPRESSION_STRING_QUOTES).
+ * @return The string value.
+ */
+ /*
+ * It would be really nice to remove the quotes earlier, such as in the
+ * parser.
+ */
+ private static String parseUnaryString(CommonTree unaryString) {
+
+ CommonTree value = (CommonTree) unaryString.getChild(0);
+ String strval = value.getText();
+
+ /* Remove quotes */
+ if (unaryString.getType() == CTFParser.UNARY_EXPRESSION_STRING_QUOTES) {
+ strval = strval.substring(1, strval.length() - 1);
+ }
+
+ return strval;
+ }
+
+ /**
+ * Parses an unary integer (dec, hex or oct).
+ *
+ * @param unaryInteger
+ * An unary integer node.
+ * @return The integer value.
+ * @throws ParseException
+ * on an invalid integer format ("bob" for example)
+ */
+ private static long parseUnaryInteger(CommonTree unaryInteger) throws ParseException {
+
+ List<CommonTree> children = unaryInteger.getChildren();
+ CommonTree value = children.get(0);
+ String strval = value.getText();
+
+ long intval;
+ try {
+ intval = Long.decode(strval);
+ } catch (NumberFormatException e) {
+ throw new ParseException("Invalid integer format: " + strval, e); //$NON-NLS-1$
+ }
+
+ /* The rest of children are sign */
+ if ((children.size() % 2) == 0) {
+ return -intval;
+ }
+ return intval;
+ }
+
+ private static long getMajorOrMinor(CommonTree rightNode)
+ throws ParseException {
+
+ CommonTree firstChild = (CommonTree) rightNode.getChild(0);
+
+ if (isUnaryInteger(firstChild)) {
+ if (rightNode.getChildCount() > 1) {
+ throw new ParseException("Invalid value for major/minor"); //$NON-NLS-1$
+ }
+
+ long m = parseUnaryInteger(firstChild);
+
+ if (m < 0) {
+ throw new ParseException("Invalid value for major/minor"); //$NON-NLS-1$
+ }
+
+ return m;
+ }
+ throw new ParseException("Invalid value for major/minor"); //$NON-NLS-1$
+ }
+
+ private static UUID getUUID(CommonTree rightNode) throws ParseException {
+
+ CommonTree firstChild = (CommonTree) rightNode.getChild(0);
+
+ if (isAnyUnaryString(firstChild)) {
+ if (rightNode.getChildCount() > 1) {
+ throw new ParseException("Invalid value for UUID"); //$NON-NLS-1$
+ }
+
+ String uuidstr = parseUnaryString(firstChild);
+
+ try {
+ return UUID.fromString(uuidstr);
+ } catch (IllegalArgumentException e) {
+ throw new ParseException("Invalid format for UUID", e); //$NON-NLS-1$
+ }
+ }
+ throw new ParseException("Invalid value for UUID"); //$NON-NLS-1$
+ }
+
+ /**
+ * Gets the value of a "signed" integer attribute.
+ *
+ * @param rightNode
+ * A CTF_RIGHT node.
+ * @return The "signed" value as a boolean.
+ * @throws ParseException
+ */
+ private static boolean getSigned(CommonTree rightNode)
+ throws ParseException {
+
+ boolean ret = false;
+ CommonTree firstChild = (CommonTree) rightNode.getChild(0);
+
+ if (isUnaryString(firstChild)) {
+ String strval = concatenateUnaryStrings(rightNode.getChildren());
+
+ if (strval.equals(MetadataStrings.TRUE)
+ || strval.equals(MetadataStrings.TRUE2)) {
+ ret = true;
+ } else if (strval.equals(MetadataStrings.FALSE)
+ || strval.equals(MetadataStrings.FALSE2)) {
+ ret = false;
+ } else {
+ throw new ParseException("Invalid boolean value " //$NON-NLS-1$
+ + firstChild.getChild(0).getText());
+ }
+ } else if (isUnaryInteger(firstChild)) {
+ /* Happens if the value is something like "1234.hello" */
+ if (rightNode.getChildCount() > 1) {
+ throw new ParseException("Invalid boolean value"); //$NON-NLS-1$
+ }
+
+ long intval = parseUnaryInteger(firstChild);
+
+ if (intval == 1) {
+ ret = true;
+ } else if (intval == 0) {
+ ret = false;
+ } else {
+ throw new ParseException("Invalid boolean value " //$NON-NLS-1$
+ + firstChild.getChild(0).getText());
+ }
+ } else {
+ throw new ParseException();
+ }
+
+ return ret;
+ }
+
+ /**
+ * Gets the value of a "byte_order" integer attribute.
+ *
+ * @param rightNode
+ * A CTF_RIGHT node.
+ * @return The "byte_order" value.
+ * @throws ParseException
+ */
+ private ByteOrder getByteOrder(CommonTree rightNode) throws ParseException {
+
+ CommonTree firstChild = (CommonTree) rightNode.getChild(0);
+
+ if (isUnaryString(firstChild)) {
+ String strval = concatenateUnaryStrings(rightNode.getChildren());
+
+ if (strval.equals(MetadataStrings.LE)) {
+ return ByteOrder.LITTLE_ENDIAN;
+ } else if (strval.equals(MetadataStrings.BE)
+ || strval.equals(MetadataStrings.NETWORK)) {
+ return ByteOrder.BIG_ENDIAN;
+ } else if (strval.equals(MetadataStrings.NATIVE)) {
+ return fTrace.getByteOrder();
+ } else {
+ throw new ParseException("Invalid value for byte order"); //$NON-NLS-1$
+ }
+ }
+ throw new ParseException("Invalid value for byte order"); //$NON-NLS-1$
+ }
+
+ /**
+ * Determines if the given value is a valid alignment value.
+ *
+ * @param alignment
+ * The value to check.
+ * @return True if it is valid.
+ */
+ private static boolean isValidAlignment(long alignment) {
+ return !((alignment <= 0) || ((alignment & (alignment - 1)) != 0));
+ }
+
+ /**
+ * Gets the value of a "size" integer attribute.
+ *
+ * @param rightNode
+ * A CTF_RIGHT node.
+ * @return The "size" value.
+ * @throws ParseException
+ */
+ private static long getSize(CommonTree rightNode) throws ParseException {
+
+ CommonTree firstChild = (CommonTree) rightNode.getChild(0);
+
+ if (isUnaryInteger(firstChild)) {
+ if (rightNode.getChildCount() > 1) {
+ throw new ParseException("Invalid value for size"); //$NON-NLS-1$
+ }
+
+ long size = parseUnaryInteger(firstChild);
+
+ if (size < 1) {
+ throw new ParseException("Invalid value for size"); //$NON-NLS-1$
+ }
+
+ return size;
+ }
+ throw new ParseException("Invalid value for size"); //$NON-NLS-1$
+ }
+
+ /**
+ * Gets the value of a "align" integer or struct attribute.
+ *
+ * @param node
+ * A CTF_RIGHT node or directly an unary integer.
+ * @return The align value.
+ * @throws ParseException
+ */
+ private static long getAlignment(CommonTree node) throws ParseException {
+
+ /*
+ * If a CTF_RIGHT node was passed, call getAlignment with the first
+ * child
+ */
+ if (node.getType() == CTFParser.CTF_RIGHT) {
+ if (node.getChildCount() > 1) {
+ throw new ParseException("Invalid alignment value"); //$NON-NLS-1$
+ }
+
+ return getAlignment((CommonTree) node.getChild(0));
+ } else if (isUnaryInteger(node)) {
+ long alignment = parseUnaryInteger(node);
+
+ if (!isValidAlignment(alignment)) {
+ throw new ParseException("Invalid value for alignment : " //$NON-NLS-1$
+ + alignment);
+ }
+
+ return alignment;
+ }
+ throw new ParseException("Invalid value for alignment"); //$NON-NLS-1$
+ }
+
+ /**
+ * Gets the value of a "base" integer attribute.
+ *
+ * @param rightNode
+ * An CTF_RIGHT node.
+ * @return The "base" value.
+ * @throws ParseException
+ */
+ private static int getBase(CommonTree rightNode) throws ParseException {
+
+ CommonTree firstChild = (CommonTree) rightNode.getChild(0);
+
+ if (isUnaryInteger(firstChild)) {
+ if (rightNode.getChildCount() > 1) {
+ throw new ParseException("invalid base value"); //$NON-NLS-1$
+ }
+
+ long intval = parseUnaryInteger(firstChild);
+ if ((intval == INTEGER_BASE_2) || (intval == INTEGER_BASE_8) || (intval == INTEGER_BASE_10)
+ || (intval == INTEGER_BASE_16)) {
+ return (int) intval;
+ }
+ throw new ParseException("Invalid value for base"); //$NON-NLS-1$
+ } else if (isUnaryString(firstChild)) {
+ String strval = concatenateUnaryStrings(rightNode.getChildren());
+
+ if (strval.equals(MetadataStrings.DECIMAL)
+ || strval.equals(MetadataStrings.DEC)
+ || strval.equals(MetadataStrings.DEC_CTE)
+ || strval.equals(MetadataStrings.INT_MOD)
+ || strval.equals(MetadataStrings.UNSIGNED_CTE)) {
+ return INTEGER_BASE_10;
+ } else if (strval.equals(MetadataStrings.HEXADECIMAL)
+ || strval.equals(MetadataStrings.HEX)
+ || strval.equals(MetadataStrings.X)
+ || strval.equals(MetadataStrings.X2)
+ || strval.equals(MetadataStrings.POINTER)) {
+ return INTEGER_BASE_16;
+ } else if (strval.equals(MetadataStrings.OCTAL)
+ || strval.equals(MetadataStrings.OCT)
+ || strval.equals(MetadataStrings.OCTAL_CTE)) {
+ return INTEGER_BASE_8;
+ } else if (strval.equals(MetadataStrings.BINARY)
+ || strval.equals(MetadataStrings.BIN)) {
+ return INTEGER_BASE_2;
+ } else {
+ throw new ParseException("Invalid value for base"); //$NON-NLS-1$
+ }
+ } else {
+ throw new ParseException("invalid value for base"); //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * Gets the value of an "encoding" integer attribute.
+ *
+ * @param rightNode
+ * A CTF_RIGHT node.
+ * @return The "encoding" value.
+ * @throws ParseException
+ */
+ @NonNull
+ private static Encoding getEncoding(CommonTree rightNode)
+ throws ParseException {
+
+ CommonTree firstChild = (CommonTree) rightNode.getChild(0);
+
+ if (isUnaryString(firstChild)) {
+ String strval = concatenateUnaryStrings(rightNode.getChildren());
+
+ if (strval.equals(MetadataStrings.UTF8)) {
+ return Encoding.UTF8;
+ } else if (strval.equals(MetadataStrings.ASCII)) {
+ return Encoding.ASCII;
+ } else if (strval.equals(MetadataStrings.NONE)) {
+ return Encoding.NONE;
+ } else {
+ throw new ParseException("Invalid value for encoding"); //$NON-NLS-1$
+ }
+ }
+ throw new ParseException("Invalid value for encoding"); //$NON-NLS-1$
+ }
+
+ private static long getStreamID(CommonTree rightNode) throws ParseException {
+
+ CommonTree firstChild = (CommonTree) rightNode.getChild(0);
+
+ if (isUnaryInteger(firstChild)) {
+ if (rightNode.getChildCount() > 1) {
+ throw new ParseException("invalid value for stream id"); //$NON-NLS-1$
+ }
+
+ long intval = parseUnaryInteger(firstChild);
+
+ return intval;
+ }
+ throw new ParseException("invalid value for stream id"); //$NON-NLS-1$
+ }
+
+ private static String getEventName(CommonTree rightNode)
+ throws ParseException {
+
+ CommonTree firstChild = (CommonTree) rightNode.getChild(0);
+
+ if (isAnyUnaryString(firstChild)) {
+ String str = concatenateUnaryStrings(rightNode.getChildren());
+
+ return str;
+ }
+ throw new ParseException("invalid value for event name"); //$NON-NLS-1$
+ }
+
+ private static long getEventID(CommonTree rightNode) throws ParseException {
+
+ CommonTree firstChild = (CommonTree) rightNode.getChild(0);
+
+ if (isUnaryInteger(firstChild)) {
+ if (rightNode.getChildCount() > 1) {
+ throw new ParseException("invalid value for event id"); //$NON-NLS-1$
+ }
+
+ long intval = parseUnaryInteger(firstChild);
+ if (intval > Integer.MAX_VALUE) {
+ throw new ParseException("Event id larger than int.maxvalue, something is amiss"); //$NON-NLS-1$
+ }
+ return intval;
+ }
+ throw new ParseException("invalid value for event id"); //$NON-NLS-1$
+ }
+
+ /**
+ * Concatenates a list of unary strings separated by arrows (->) or dots.
+ *
+ * @param strings
+ * A list, first element being an unary string, subsequent
+ * elements being ARROW or DOT nodes with unary strings as child.
+ * @return The string representation of the unary string chain.
+ */
+ private static String concatenateUnaryStrings(List<CommonTree> strings) {
+
+ StringBuilder sb = new StringBuilder();
+
+ CommonTree first = strings.get(0);
+ sb.append(parseUnaryString(first));
+
+ boolean isFirst = true;
+
+ for (CommonTree ref : strings) {
+ if (isFirst) {
+ isFirst = false;
+ continue;
+ }
+
+ CommonTree id = (CommonTree) ref.getChild(0);
+
+ if (ref.getType() == CTFParser.ARROW) {
+ sb.append("->"); //$NON-NLS-1$
+ } else { /* DOT */
+ sb.append('.');
+ }
+
+ sb.append(parseUnaryString(id));
+ }
+
+ return sb.toString();
+ }
+
+ /**
+ * Throws a ParseException stating that the parent-child relation between
+ * the given node and its parent is not valid. It means that the shape of
+ * the AST is unexpected.
+ *
+ * @param child
+ * The invalid child node.
+ * @throws ParseException
+ */
+ private static void childTypeError(CommonTree child) throws ParseException {
+ CommonTree parent = (CommonTree) child.getParent();
+ String error = "Parent " + CTFParser.tokenNames[parent.getType()] //$NON-NLS-1$
+ + " can't have a child of type " //$NON-NLS-1$
+ + CTFParser.tokenNames[child.getType()] + "."; //$NON-NLS-1$
+
+ throw new ParseException(error);
+ }
+
+ // ------------------------------------------------------------------------
+ // Scope management
+ // ------------------------------------------------------------------------
+
+ /**
+ * Adds a new declaration scope on the top of the scope stack.
+ */
+ private void pushScope() {
+ fScope = new DeclarationScope(fScope);
+ }
+
+ /**
+ * Removes the top declaration scope from the scope stack.
+ */
+ private void popScope() {
+ fScope = fScope.getParentScope();
+ }
+
+ /**
+ * Returns the current declaration scope.
+ *
+ * @return The current declaration scope.
+ */
+ private DeclarationScope getCurrentScope() {
+ return fScope;
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Marc-Andre Laperle - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.internal.ctf.core.event.metadata;
+
+import org.eclipse.osgi.util.NLS;
+
+@SuppressWarnings("javadoc")
+public class Messages extends NLS {
+
+ private static final String BUNDLE_NAME = "org.eclipse.tracecompass.internal.ctf.core.event.metadata.messages"; //$NON-NLS-1$
+
+ public static String IOStructGen_UnknownTraceAttributeWarning;
+ public static String IOStructGen_UnknownStreamAttributeWarning;
+ public static String IOStructGen_UnknownIntegerAttributeWarning;
+
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
+
+ private Messages() {
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.internal.ctf.core.event.metadata;
+
+/**
+ * Strings generated from the TSDL grammar. Note that they are static final so
+ * they get quarked. See CTF specs for more details
+ *
+ * @author Matthew Khouzam and All
+ */
+@SuppressWarnings("nls")
+public interface MetadataStrings {
+
+ /** None */
+
+ static final String NONE = "none";
+ /** Ascii */
+ static final String ASCII = "ASCII";
+ /** UTF8 */
+ static final String UTF8 = "UTF8";
+ /** b (for binary like b11010010 */
+ static final String BIN = "b";
+ /** Binary */
+ static final String BINARY = "binary";
+ /** Octal like o177 */
+ static final String OCTAL_CTE = "o";
+ /** Octal like oct177 */
+ static final String OCT = "oct";
+ /** Octal like octal177 */
+ static final String OCTAL = "octal";
+ /** Pointer (memory address for all the hardcore Java gurus out there)*/
+ static final String POINTER = "p";
+ /** X for hex */
+ static final String X2 = "X";
+ /** x for hex */
+ static final String X = "x";
+ /** hex */
+ static final String HEX = "hex";
+ /** Hexadecimal */
+ static final String HEXADECIMAL = "hexadecimal";
+ /** unsigned like in 10000ul */
+ static final String UNSIGNED_CTE = "u";
+ /** Decimal */
+ static final String DEC_CTE = "d";
+ /** Integer like 1000i */
+ static final String INT_MOD = "i";
+ /** Decimal */
+ static final String DEC = "dec";
+ /** Decimal */
+ static final String DECIMAL = "decimal";
+ /** native for byteorders*/
+ static final String NATIVE = "native";
+ /** network for byteorders*/
+ static final String NETWORK = "network";
+ /** Big endian */
+ static final String BE = "be";
+ /** Little endian */
+ static final String LE = "le";
+ /** Alignment of a field */
+ static final String ALIGN = "align";
+ /** Mantissa digits */
+ static final String MANT_DIG = "mant_dig";
+ /** Exponent digits */
+ static final String EXP_DIG = "exp_dig";
+ /** Loglevel */
+ static final String LOGLEVEL2 = "loglevel";
+ /** Name */
+ static final String NAME2 = "name";
+ /** Event context */
+ static final String EVENT_CONTEXT = "event.context";
+ /** Fields */
+ static final String FIELDS_STRING = "fields";
+ /** context */
+ static final String CONTEXT = "context";
+ /** Stream ID */
+ static final String STREAM_ID = "stream_id";
+ /** Packet context */
+ static final String PACKET_CONTEXT = "packet.context";
+ /** ID */
+ static final String ID = "id";
+ /** Packet Header */
+ static final String PACKET_HEADER = "packet.header";
+ /** Event Header */
+ static final String EVENT_HEADER = "event.header";
+ /** Byte order */
+ static final String BYTE_ORDER = "byte_order";
+ /** UUID */
+ static final String UUID_STRING = "uuid";
+ /** False */
+ static final String FALSE2 = "FALSE";
+ /** False */
+ static final String FALSE = "false";
+ /** True */
+ static final String TRUE2 = "TRUE";
+ /** True */
+ static final String TRUE = "true";
+ /** Minor (Version)*/
+ static final String MINOR = "minor";
+ /** Major (Version)*/
+ static final String MAJOR = "major";
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013, 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Alexandre Montplaisir - Initial API and implementation
+ * Matthew Khouzam - Addition to have more descriptive errors
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.internal.ctf.core.event.metadata.exceptions;
+
+import java.lang.reflect.Field;
+
+import org.antlr.runtime.MismatchedTokenException;
+import org.antlr.runtime.RecognitionException;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.ctf.parser.CTFLexer;
+
+/**
+ * CTF Reader exception but dealing with Antlr-specific parsing problems.
+ *
+ * It is separated from the main {@link CTFReaderException} - and is not part of
+ * the API - to isolate the Antlr-specific classes and avoid pushing that
+ * dependency to the users of this plugin.
+ *
+ * @author Matthew Khouzam
+ */
+public class CtfAntlrException extends CTFReaderException {
+
+ private static final long serialVersionUID = -7078624493350073777L;
+
+ private int fErrorLine = -1;
+ private String fFile = ""; //$NON-NLS-1$
+ private String fExpectingName = ""; //$NON-NLS-1$
+ private int fExpectedValue = -1;
+ private String fActualName = ""; //$NON-NLS-1$
+ private int fActualValue = -1;
+
+ /**
+ * Re-throw the exception but read its data
+ *
+ * @param e
+ * the previous recognition exception (Antlr specific)
+ */
+ public CtfAntlrException(RecognitionException e) {
+ super(e);
+ this.fErrorLine = e.line;
+ this.fFile = "metadata"; //$NON-NLS-1$ // we're in CTF, the only thing using antlr is metadata
+ }
+
+ /**
+ * Re-throw the exception but read its data
+ *
+ * @param e
+ * the previous recognition exception (Antlr specific)
+ */
+ public CtfAntlrException(MismatchedTokenException e) {
+ super(e);
+ this.fErrorLine = e.line;
+ this.fFile = "metadata"; //$NON-NLS-1$ // we're in CTF, the only thing using antlr is metadata
+ parseMismatchedException(e);
+ }
+
+ /**
+ * Re-throw the exception but read its data
+ *
+ * @param e
+ * the previous rewrite exception (Antlr specific)
+ */
+ public CtfAntlrException(Exception e) {
+ super(e);
+ this.fErrorLine = -1;
+ this.fFile = "metadata"; //$NON-NLS-1$ // we're in CTF, the only thing using antlr is metadata
+ }
+
+ private void parseMismatchedException(MismatchedTokenException m) {
+ // Iterate through the tokens that are hidden in the CTFLexer
+ // They are private static final int fields.
+ for (Field f : CTFLexer.class.getDeclaredFields()) {
+ f.setAccessible(true);
+ String name;
+ int value;
+ try {
+ name = f.getName();
+ final boolean isInt = (f.getType().isPrimitive());
+ if (isInt) {
+ value = ((Integer) f.get(null)).intValue();
+ if (value == m.expecting) {
+ this.fExpectingName = name;
+ this.fExpectedValue = value;
+ }
+ if (value == m.c) {
+ this.fActualName = name;
+ this.fActualValue = value;
+ }
+ }
+ } catch (NullPointerException e1) {
+ // Pokemon, gotta catch em all!
+ // actually useful since f may not have a
+ // value
+ } catch (IllegalArgumentException e1) {
+ // Catch these exceptions (reflexion)
+ } catch (IllegalAccessException e1) {
+ // Catch these exceptions (reflexion)
+ }
+ if (!this.fExpectingName.isEmpty() && !this.fActualName.isEmpty()) {
+ return;
+ }
+ }
+ }
+
+ @Override
+ public String getMessage() {
+ final String message = super.getMessage();
+ if (fErrorLine == -1) {
+ return message;
+ }
+ String expected = "" + this.fExpectedValue; //$NON-NLS-1$
+ String actual = "" + this.fActualValue; //$NON-NLS-1$
+ String newMessage = message.replaceAll(expected, this.fExpectingName);
+ newMessage = newMessage.replaceAll(actual, this.fActualName);
+ return newMessage + " at " + fFile + ":" + fErrorLine; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.internal.ctf.core.event.metadata.exceptions;
+
+
+/**
+ * <b><u>ParseException</u></b>
+ */
+public class ParseException extends Exception {
+
+ private static final long serialVersionUID = 7901917601459652080L;
+
+ /**
+ * Empty constructor
+ */
+ public ParseException() {
+ super();
+ }
+
+ /**
+ * Constructor
+ *
+ * @param message to be sent to logs
+ */
+ public ParseException(String message) {
+ super(message);
+ }
+
+ /**
+ * Copy constructor
+ * @param e the exception to throw
+ */
+ public ParseException(Exception e) {
+ super(e);
+ }
+
+ /**
+ * Constructs a new exception with the specified detail message and
+ * cause. <p>Note that the detail message associated with
+ * {@code cause} is <i>not</i> automatically incorporated in
+ * this exception's detail message.
+ *
+ * @param message the detail message (which is saved for later retrieval
+ * by the {@link #getMessage()} method).
+ * @param cause the cause (which is saved for later retrieval by the
+ * {@link #getCause()} method). (A <tt>null</tt> value is
+ * permitted, and indicates that the cause is nonexistent or
+ * unknown.)
+ */
+ public ParseException(String message, Exception cause) {
+ super(message, cause);
+ }
+}
--- /dev/null
+###############################################################################
+# Copyright (c) 2013 Ericsson
+#
+# All rights reserved. This program and the accompanying materials
+# are made available under the terms of the Eclipse Public License v1.0
+# which accompanies this distribution, and is available at
+# http://www.eclipse.org/legal/epl-v10.html
+#
+# Contributors:
+# Marc-Andre Laperle - Initial API and implementation
+# Alexandre Montplaisir - Added strings from DeclarationScope
+###############################################################################
+
+#IOStructGen
+IOStructGen_UnknownTraceAttributeWarning=Unknown trace attribute:
+IOStructGen_UnknownStreamAttributeWarning=Unknown stream attribute:
+IOStructGen_UnknownIntegerAttributeWarning=Unknown integer attribute:
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.internal.ctf.core.event.types;
+
+import java.util.List;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.event.types.AbstractArrayDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.CompoundDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.Definition;
+import org.eclipse.tracecompass.ctf.core.event.types.IDeclaration;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+
+import com.google.common.collect.ArrayListMultimap;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableList.Builder;
+
+/**
+ * A CTF array declaration
+ *
+ * Arrays are fixed-length. Their length is declared in the type declaration
+ * within the meta-data. They contain an array of "inner type" elements, which
+ * can refer to any type not containing the type of the array being declared (no
+ * circular dependency). The length is the number of elements in an array.
+ *
+ * @author Matthew Khouzam
+ * @since 3.1
+ */
+public final class ArrayDeclaration extends CompoundDeclaration {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ private final int fLength;
+ private final IDeclaration fElemType;
+
+ /**
+ * <pre>
+ * Cache where we can pre-generate the children names
+ * Key: parent name
+ * Value: children names
+ * ex: field → {field[0], field[1], … field[n]}
+ * </pre>
+ *
+ * TODO: investigate performance
+ */
+ private final ArrayListMultimap<String, String> fChildrenNames = ArrayListMultimap.create();
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructor
+ *
+ * @param length
+ * how many elements in the array
+ * @param elemType
+ * what type of element is in the array
+ */
+ public ArrayDeclaration(int length, IDeclaration elemType) {
+ fLength = length;
+ fElemType = elemType;
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ @Override
+ public IDeclaration getElementType() {
+ return fElemType;
+ }
+
+ /**
+ * Get the length of the array
+ *
+ * @return the length of the array
+ */
+ public int getLength() {
+ return fLength;
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ @Override
+ public AbstractArrayDefinition createDefinition(IDefinitionScope definitionScope,
+ @NonNull String fieldName, BitBuffer input) throws CTFReaderException {
+ alignRead(input);
+ if (isString()) {
+ byte[] data = new byte[fLength];
+ input.get(data);
+ return new ByteArrayDefinition(this, definitionScope, fieldName, data);
+ }
+ List<Definition> definitions = read(input, definitionScope, fieldName);
+ return new ArrayDefinition(this, definitionScope, fieldName, definitions);
+ }
+
+ @Override
+ public String toString() {
+ /* Only used for debugging */
+ return "[declaration] array[" + Integer.toHexString(hashCode()) + ']'; //$NON-NLS-1$
+ }
+
+ @NonNull
+ private List<Definition> read(@NonNull BitBuffer input, IDefinitionScope definitionScope, String fieldName) throws CTFReaderException {
+ Builder<Definition> definitions = new ImmutableList.Builder<>();
+ if (!fChildrenNames.containsKey(fieldName)) {
+ for (int i = 0; i < fLength; i++) {
+ fChildrenNames.put(fieldName, fieldName + '[' + i + ']');
+ }
+ }
+ List<String> elemNames = fChildrenNames.get(fieldName);
+ for (int i = 0; i < fLength; i++) {
+ String name = elemNames.get(i);
+ if (name == null) {
+ throw new IllegalStateException();
+ }
+ definitions.add(fElemType.createDefinition(definitionScope, name, input));
+ }
+ @SuppressWarnings("null")
+ @NonNull ImmutableList<Definition> ret = definitions.build();
+ return ret;
+ }
+
+ @Override
+ public int getMaximumSize() {
+ long val = (long) fLength * fElemType.getMaximumSize();
+ return (int) Math.min(Integer.MAX_VALUE, val);
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.internal.ctf.core.event.types;
+
+import java.util.List;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.event.types.AbstractArrayDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.CompoundDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.Definition;
+
+import com.google.common.base.Joiner;
+import com.google.common.collect.ImmutableList;
+
+/**
+ * A CTF array definition
+ *
+ * Arrays are fixed-length. Their length is declared in the type declaration
+ * within the meta-data. They contain an array of "inner type" elements, which
+ * can refer to any type not containing the type of the array being declared (no
+ * circular dependency). The length is the number of elements in an array.
+ *
+ * @version 1.0
+ * @author Matthew Khouzam
+ * @since 3.1
+ */
+@NonNullByDefault
+public final class ArrayDefinition extends AbstractArrayDefinition {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ private final ImmutableList<Definition> fDefinitions;
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructor
+ *
+ * @param declaration
+ * the parent declaration
+ * @param definitionScope
+ * the parent scope
+ * @param fieldName
+ * the field name
+ * @param definitions
+ * the content of the array
+ */
+ public ArrayDefinition(CompoundDeclaration declaration,
+ @Nullable IDefinitionScope definitionScope,
+ String fieldName,
+ List<Definition> definitions) {
+ super(declaration, definitionScope, fieldName);
+ @SuppressWarnings("null")
+ @NonNull ImmutableList<Definition> list = ImmutableList.copyOf(definitions);
+ fDefinitions = list;
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ @Override
+ public List<Definition> getDefinitions() {
+ return fDefinitions;
+ }
+
+ /**
+ * Get the the number of elements in the array
+ *
+ * @return how many elements in the array
+ */
+ public int getLength() {
+ return fDefinitions.size();
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ @Override
+ public String toString() {
+ StringBuilder b = new StringBuilder();
+ b.append('[');
+ Joiner joiner = Joiner.on(", ").skipNulls(); //$NON-NLS-1$
+ b.append(joiner.join(fDefinitions));
+ b.append(']');
+ @SuppressWarnings("null")
+ @NonNull String ret = b.toString();
+ return ret;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.internal.ctf.core.event.types;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.event.types.AbstractArrayDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.CompoundDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.Definition;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDefinition;
+
+import com.google.common.collect.ImmutableList;
+
+/**
+ * A fixed length string definition
+ *
+ * @author Matthew Khouzam
+ * @since 3.1
+ */
+@NonNullByDefault
+public final class ByteArrayDefinition extends AbstractArrayDefinition {
+
+ private final byte[] fContent;
+ private transient @Nullable List<Definition> fDefs;
+
+ /**
+ * An fixed length string declaration, it's created by sequence or array
+ * defintions
+ *
+ * @param declaration
+ * the declaration
+ * @param definitionScope
+ * the definition scope
+ * @param fieldName
+ * the field name
+ * @param content
+ * the string content
+ */
+ public ByteArrayDefinition(CompoundDeclaration declaration,
+ @Nullable IDefinitionScope definitionScope,
+ String fieldName,
+ byte[] content) {
+ super(declaration, definitionScope, fieldName);
+ fContent = content;
+
+ }
+
+ @Override
+ public synchronized List<Definition> getDefinitions() {
+ List<Definition> defs = fDefs;
+ if (defs == null) {
+ ImmutableList.Builder<Definition> builder = new ImmutableList.Builder<>();
+ for (int i = 0; i < fContent.length; i++) {
+ IntegerDeclaration charDecl = IntegerDeclaration.UINT_8_DECL;
+ String fieldName = getFieldName() + '[' + i + ']';
+ byte fieldValue = fContent[i];
+ builder.add(new IntegerDefinition(charDecl, getDefinitionScope(), fieldName, fieldValue));
+ }
+ @SuppressWarnings("null")
+ @NonNull List<Definition> ret = builder.build();
+ fDefs = ret;
+ return ret;
+ }
+
+ return defs;
+ }
+
+ @Override
+ public String toString() {
+ /*
+ * the string is a byte array and may contain more than the string plus
+ * a null char, this will truncate it back to a null char
+ */
+ int pos = -1;
+ for (int i = 0; i < fContent.length; i++) {
+ if (fContent[i] == 0) {
+ pos = i;
+ break;
+ }
+ }
+ byte[] bytes = (pos != -1) ? (Arrays.copyOf(fContent, pos)) : fContent;
+ return new String(bytes);
+ }
+}
\ No newline at end of file
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.internal.ctf.core.event.types;
+
+import java.util.Collection;
+import java.util.List;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.event.types.AbstractArrayDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.CompoundDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.Definition;
+import org.eclipse.tracecompass.ctf.core.event.types.IDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDefinition;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+
+import com.google.common.collect.ArrayListMultimap;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableList.Builder;
+import com.google.common.collect.Multimap;
+
+/**
+ * A CTF sequence declaration.
+ *
+ * An array where the size is fixed but declared in the trace, unlike array
+ * where it is declared with a literal
+ *
+ * @author Matthew Khouzam
+ * @since 3.1
+ */
+public class SequenceDeclaration extends CompoundDeclaration {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ private final IDeclaration fElemType;
+ private final String fLengthName;
+ private final Multimap<String, String> fPaths = ArrayListMultimap.create();
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructor
+ *
+ * @param lengthName
+ * the name of the field describing the length
+ * @param elemType
+ * The element type
+ */
+ public SequenceDeclaration(String lengthName, IDeclaration elemType) {
+ fElemType = elemType;
+ fLengthName = lengthName;
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ @Override
+ public IDeclaration getElementType() {
+ return fElemType;
+ }
+
+ /**
+ * Gets the name of the length field
+ *
+ * @return the name of the length field
+ */
+ public String getLengthName() {
+ return fLengthName;
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ @Override
+ public AbstractArrayDefinition createDefinition(
+ IDefinitionScope definitionScope, String fieldName, BitBuffer input) throws CTFReaderException {
+ IDefinition lenDef = null;
+
+ if (definitionScope != null) {
+ lenDef = definitionScope.lookupDefinition(getLengthName());
+ }
+
+ if (lenDef == null) {
+ throw new CTFReaderException("Sequence length field not found"); //$NON-NLS-1$
+ }
+
+ if (!(lenDef instanceof IntegerDefinition)) {
+ throw new CTFReaderException("Sequence length field not integer"); //$NON-NLS-1$
+ }
+
+ IntegerDefinition lengthDefinition = (IntegerDefinition) lenDef;
+
+ if (lengthDefinition.getDeclaration().isSigned()) {
+ throw new CTFReaderException("Sequence length must not be signed"); //$NON-NLS-1$
+ }
+
+ long length = lengthDefinition.getValue();
+ if ((length > Integer.MAX_VALUE) || (!input.canRead((int) length * fElemType.getMaximumSize()))) {
+ throw new CTFReaderException("Sequence length too long " + length); //$NON-NLS-1$
+ }
+
+ if (isString()) {
+ // Don't create "useless" definitions
+ byte[] data = new byte[(int) length];
+ input.get(data);
+ return new ByteArrayDefinition(this, definitionScope, fieldName, data);
+ }
+ Collection<String> collection = fPaths.get(fieldName);
+ while (collection.size() < length) {
+ fPaths.put(fieldName, fieldName + '[' + collection.size() + ']');
+ }
+ List<String> paths = (List<String>) fPaths.get(fieldName);
+ Builder<Definition> definitions = new ImmutableList.Builder<>();
+ for (int i = 0; i < length; i++) {
+ @SuppressWarnings("null")
+ @NonNull String elemName = paths.get(i);
+ definitions.add(fElemType.createDefinition(definitionScope, elemName, input));
+ }
+ @SuppressWarnings("null")
+ @NonNull ImmutableList<Definition> build = definitions.build();
+ return new ArrayDefinition(this, definitionScope, fieldName, build);
+ }
+
+ @Override
+ public String toString() {
+ /* Only used for debugging */
+ return "[declaration] sequence[" + Integer.toHexString(hashCode()) + ']'; //$NON-NLS-1$
+ }
+
+ @Override
+ public int getMaximumSize() {
+ return Integer.MAX_VALUE;
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.internal.ctf.core.event.types;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.types.IDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.ISimpleDatatypeDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+
+/**
+ * A fixed size struct declaration is a declaration of a structure that has no
+ * variant or sequence fields. This will accelerate reading of the trace.
+ *
+ * @author Matthew Khouzam
+ * @since 3.0
+ */
+public final class StructDeclarationFlattener {
+
+ private StructDeclarationFlattener() {}
+
+ /**
+ * Flatten a {@link StructDeclaration}, if it can be (which means if it
+ * contains only fixed-size elements).
+ *
+ * This does not modify the declaration passed in parameter, you need to use
+ * the return value.
+ *
+ * @param sd
+ * The initial StructDeclaration
+ * @return The flattened struct. Or if it couldn't be flattened, the 'sd'
+ * struct itself
+ */
+ public static StructDeclaration tryFlattenStruct(@NonNull StructDeclaration sd) {
+ if (canBeFlattened(sd)) {
+ return newFlattenedStruct(sd);
+ }
+ return sd;
+ }
+
+ /**
+ * Check if this struct is fixed size
+ *
+ * @param sd
+ * the struct
+ * @return if the struct is of fixed size
+ */
+ private static boolean canBeFlattened(@NonNull StructDeclaration sd) {
+ for (String field : sd.getFieldsList()) {
+ IDeclaration dec = sd.getField(field);
+ if (!isFixedSize(dec)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private static boolean isFixedSize(IDeclaration dec) {
+ if (dec instanceof ISimpleDatatypeDeclaration) {
+ return true;
+ }
+ if (dec instanceof ArrayDeclaration) {
+ return isFixedSize(((ArrayDeclaration) dec).getElementType());
+ }
+ if (dec instanceof StructDeclaration) {
+ StructDeclaration sDec = ((StructDeclaration) dec);
+ return canBeFlattened(sDec);
+ }
+ return false;
+ }
+
+ private static StructDeclaration newFlattenedStruct(@NonNull StructDeclaration sd) {
+ StructDeclaration flatStruct = new StructDeclaration(sd.getAlignment());
+ for (String name : sd.getFieldsList()) {
+ depthFirstAdd(name, flatStruct, sd.getField(name));
+ }
+ return flatStruct;
+ }
+
+ private static void depthFirstAdd(String path, StructDeclaration flatStruct, IDeclaration dec) {
+ if (dec instanceof ISimpleDatatypeDeclaration) {
+ flatStruct.addField(path, dec);
+ } else if (dec instanceof ArrayDeclaration) {
+ ArrayDeclaration ad = (ArrayDeclaration) dec;
+ int lastIndexOf = path.lastIndexOf('.');
+
+ String name = (lastIndexOf > 0) ? path.substring(lastIndexOf) : path;
+ if (((ArrayDeclaration) dec).isString()) {
+ flatStruct.addField(path, dec);
+ } else {
+ for (int i = 0; i < ad.getLength(); i++) {
+ depthFirstAdd(path + '.' + name + '[' + i + ']', flatStruct, ad.getElementType());
+ }
+ }
+ } else if (dec instanceof StructDeclaration) {
+ StructDeclaration sDec = ((StructDeclaration) dec);
+ for (String name : sDec.getFieldsList()) {
+ depthFirstAdd(path + '.' + name, flatStruct, sDec.getField(name));
+ }
+ }
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.internal.ctf.core.event.types.composite;
+
+import java.nio.ByteOrder;
+
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.event.types.Declaration;
+import org.eclipse.tracecompass.ctf.core.event.types.EnumDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IEventHeaderDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.VariantDeclaration;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+
+/**
+ * An event header declaration is a declaration of a structure defined in the
+ * CTF spec examples section 6.1.1 . It is used in LTTng traces. This will
+ * accelerate reading of the trace.
+ *
+ * Reminder
+ *
+ * <pre>
+ * struct event_header_compact {
+ * enum : uint5_t { compact = 0 ... 30, extended = 31 } id;
+ * variant <id> {
+ * struct {
+ * uint27_clock_monotonic_t timestamp;
+ * } compact;
+ * struct {
+ * uint32_t id;
+ * uint64_clock_monotonic_t timestamp;
+ * } extended;
+ * } v;
+ * } align(8);
+ * </pre>
+ *
+ * @author Matthew Khouzam
+ */
+public class EventHeaderCompactDeclaration extends Declaration implements IEventHeaderDeclaration {
+
+ private static final int COMPACT_SIZE = 1;
+ private static final int VARIANT_SIZE = 2;
+ private static final int EXTENDED_FIELD_SIZE = 2;
+ /**
+ * The id is 5 bits
+ */
+ private static final int COMPACT_ID = 5;
+ private static final int EXTENDED_VALUE = 31;
+ /**
+ * Full sized id is 32 bits
+ */
+ private static final int ID_SIZE = 32;
+ /**
+ * Full sized timestamp is 64 bits
+ */
+ private static final int FULL_TS = 64;
+ /**
+ * Compact timestamp is 27 bits,
+ */
+ private static final int COMPACT_TS = 27;
+ /**
+ * Maximum size = largest this header can be
+ */
+ private static final int MAX_SIZE = 104;
+ /**
+ * Byte aligned
+ */
+ private static final int ALIGN = 8;
+ /**
+ * Name of the variant according to the spec
+ */
+ private static final String V = "v"; //$NON-NLS-1$
+
+ private final ByteOrder fByteOrder;
+
+ /**
+ * Event Header Declaration
+ *
+ * @param byteOrder
+ * the byteorder
+ */
+ public EventHeaderCompactDeclaration(ByteOrder byteOrder) {
+ fByteOrder = byteOrder;
+ }
+
+ @Override
+ public EventHeaderDefinition createDefinition(IDefinitionScope definitionScope, String fieldName, BitBuffer input) throws CTFReaderException {
+ alignRead(input);
+ ByteOrder bo = input.getByteOrder();
+ input.setByteOrder(fByteOrder);
+ int enumId = (int) input.get(COMPACT_ID, false);
+ if (enumId != EXTENDED_VALUE) {
+ long timestamp2 = input.get(COMPACT_TS, false);
+ input.setByteOrder(bo);
+ return new EventHeaderDefinition(this, enumId, timestamp2, COMPACT_TS);
+ }
+ // needed since we read 5 bits
+ input.position(input.position() + 3);
+ long id = input.get(ID_SIZE, false);
+ if (id > Integer.MAX_VALUE) {
+ throw new CTFReaderException("ID " + id + " larger than " + Integer.MAX_VALUE + " is currently unsupported by the parser"); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
+ }
+ long timestampLong = input.get(FULL_TS, false);
+ input.setByteOrder(bo);
+ return new EventHeaderDefinition(this, (int) id, timestampLong, FULL_TS);
+
+ }
+
+ @Override
+ public long getAlignment() {
+ return ALIGN;
+ }
+
+ @Override
+ public int getMaximumSize() {
+ return MAX_SIZE;
+ }
+
+ /**
+ * Check if a given struct declaration is an event header
+ *
+ * @param declaration
+ * the declaration
+ * @return true if the struct is a compact event header
+ */
+ public static boolean isCompactEventHeader(StructDeclaration declaration) {
+
+ IDeclaration iDeclaration = declaration.getFields().get(ID);
+ if (!(iDeclaration instanceof EnumDeclaration)) {
+ return false;
+ }
+ EnumDeclaration eId = (EnumDeclaration) iDeclaration;
+ if (eId.getContainerType().getLength() != COMPACT_ID) {
+ return false;
+ }
+ iDeclaration = declaration.getFields().get(V);
+
+ if (!(iDeclaration instanceof VariantDeclaration)) {
+ return false;
+ }
+ VariantDeclaration vDec = (VariantDeclaration) iDeclaration;
+ if (!vDec.hasField(COMPACT) || !vDec.hasField(EXTENDED)) {
+ return false;
+ }
+ if (vDec.getFields().size() != VARIANT_SIZE) {
+ return false;
+ }
+ iDeclaration = vDec.getFields().get(COMPACT);
+ if (!(iDeclaration instanceof StructDeclaration)) {
+ return false;
+ }
+ StructDeclaration compactDec = (StructDeclaration) iDeclaration;
+ if (compactDec.getFields().size() != COMPACT_SIZE) {
+ return false;
+ }
+ if (!compactDec.hasField(TIMESTAMP)) {
+ return false;
+ }
+ iDeclaration = compactDec.getFields().get(TIMESTAMP);
+ if (!(iDeclaration instanceof IntegerDeclaration)) {
+ return false;
+ }
+ IntegerDeclaration tsDec = (IntegerDeclaration) iDeclaration;
+ if (tsDec.getLength() != COMPACT_TS || tsDec.isSigned()) {
+ return false;
+ }
+ iDeclaration = vDec.getFields().get(EXTENDED);
+ if (!(iDeclaration instanceof StructDeclaration)) {
+ return false;
+ }
+ StructDeclaration extendedDec = (StructDeclaration) iDeclaration;
+ if (!extendedDec.hasField(TIMESTAMP)) {
+ return false;
+ }
+ if (extendedDec.getFields().size() != EXTENDED_FIELD_SIZE) {
+ return false;
+ }
+ iDeclaration = extendedDec.getFields().get(TIMESTAMP);
+ if (!(iDeclaration instanceof IntegerDeclaration)) {
+ return false;
+ }
+ tsDec = (IntegerDeclaration) iDeclaration;
+ if (tsDec.getLength() != FULL_TS || tsDec.isSigned()) {
+ return false;
+ }
+ iDeclaration = extendedDec.getFields().get(ID);
+ if (!(iDeclaration instanceof IntegerDeclaration)) {
+ return false;
+ }
+ IntegerDeclaration iId = (IntegerDeclaration) iDeclaration;
+ if (iId.getLength() != ID_SIZE || iId.isSigned()) {
+ return false;
+ }
+ return true;
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.internal.ctf.core.event.types.composite;
+
+import java.util.List;
+
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.tracecompass.ctf.core.event.scope.LexicalScope;
+import org.eclipse.tracecompass.ctf.core.event.types.Declaration;
+import org.eclipse.tracecompass.ctf.core.event.types.Definition;
+import org.eclipse.tracecompass.ctf.core.event.types.ICompositeDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.IEventHeaderDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDefinition;
+
+import com.google.common.collect.ImmutableList;
+
+/**
+ * An event header definition, as shown in the example of the CTF spec examples
+ * section 6.1.1
+ *
+ * @author Matthew Khouzam
+ */
+public final class EventHeaderDefinition extends Definition implements ICompositeDefinition {
+
+ private static final List<String> FIELD_NAMES = ImmutableList.of(
+ IEventHeaderDeclaration.ID,
+ IEventHeaderDeclaration.TIMESTAMP
+ );
+
+ private final int fId;
+ private final long fTimestamp;
+ private final int fTimestampLength;
+
+ /**
+ * Event header defintion
+ *
+ * @param id
+ * the event id
+ * @param timestamp
+ * the timestamp
+ * @param eventHeaderDecl
+ * The declaration of this defintion
+ * @param timestampLength
+ * the number of bits valid in the timestamp
+ */
+ public EventHeaderDefinition(@NonNull Declaration eventHeaderDecl, int id, long timestamp, int timestampLength) {
+ super(eventHeaderDecl, null, LexicalScope.EVENT_HEADER.toString(), LexicalScope.EVENT_HEADER);
+ fId = id;
+ fTimestamp = timestamp;
+ fTimestampLength = timestampLength;
+ }
+
+ /**
+ * Gets the timestamp declaration
+ *
+ * @return the timestamp declaration
+ */
+ public int getTimestampLength() {
+ return fTimestampLength;
+ }
+
+ /**
+ * Get the event id
+ *
+ * @return the event id
+ */
+ public int getId() {
+ return fId;
+ }
+
+ /**
+ * Get the timestamp
+ *
+ * @return the timestamp
+ */
+ public long getTimestamp() {
+ return fTimestamp;
+ }
+
+ @Override
+ public Definition getDefinition(String fieldName) {
+ if (fieldName.equals(IEventHeaderDeclaration.ID)) {
+ return new IntegerDefinition(IntegerDeclaration.INT_32B_DECL, null, IEventHeaderDeclaration.ID, getId());
+ } else if (fieldName.equals(IEventHeaderDeclaration.TIMESTAMP)) {
+ return new IntegerDefinition(IntegerDeclaration.INT_64B_DECL, null, IEventHeaderDeclaration.TIMESTAMP, getTimestamp());
+ }
+ return null;
+ }
+
+ @Override
+ public List<String> getFieldNames() {
+ return FIELD_NAMES;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2014 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Matthew Khouzam - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.internal.ctf.core.event.types.composite;
+
+import java.nio.ByteOrder;
+
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
+import org.eclipse.tracecompass.ctf.core.event.types.Declaration;
+import org.eclipse.tracecompass.ctf.core.event.types.EnumDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IEventHeaderDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.VariantDeclaration;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+
+/**
+ * An event header declaration is a declaration of a structure defined in the
+ * CTF spec examples section 6.1.1 . It is used in LTTng traces. This will
+ * accelerate reading of the trace.
+ *
+ * Reminder
+ *
+ * <pre>
+ * struct event_header_large {
+ * enum : uint16_t { compact = 0 ... 65534, extended = 65535 } id;
+ * variant <id> {
+ * struct {
+ * uint32_clock_monotonic_t timestamp;
+ * } compact;
+ * struct {
+ * uint32_t id;
+ * uint64_clock_monotonic_t timestamp;
+ * } extended;
+ * } v;
+ * } align(8);
+ * </pre>
+ *
+ * @author Matthew Khouzam
+ */
+public class EventHeaderLargeDeclaration extends Declaration implements IEventHeaderDeclaration {
+
+ /**
+ * The id is 16 bits
+ */
+ private static final int COMPACT_ID = 16;
+ private static final int EXTENDED_VALUE = 65535;
+ /**
+ * Full sized id is 32 bits
+ */
+ private static final int ID_SIZE = 32;
+ /**
+ * Full sized timestamp is 64 bits
+ */
+ private static final int FULL_TS = 64;
+ /**
+ * Compact timestamp is 32 bits,
+ */
+ private static final int COMPACT_TS = 32;
+ /**
+ * Maximum size = largest this header can be
+ */
+ private static final int MAX_SIZE = 112;
+ /**
+ * Byte aligned
+ */
+ private static final int ALIGN = 8;
+ /**
+ * Name of the variant according to the spec
+ */
+ private static final String V = "v"; //$NON-NLS-1$
+ private static final int VARIANT_SIZE = 2;
+ private static final int COMPACT_SIZE = 1;
+ private static final int EXTENDED_FIELD_SIZE = 2;
+
+ private final ByteOrder fByteOrder;
+
+ /**
+ * Event Header Declaration
+ *
+ * @param byteOrder
+ * the byteorder
+ */
+ public EventHeaderLargeDeclaration(ByteOrder byteOrder) {
+ fByteOrder = byteOrder;
+ }
+
+ @Override
+ public EventHeaderDefinition createDefinition(IDefinitionScope definitionScope, String fieldName, BitBuffer input) throws CTFReaderException {
+ alignRead(input);
+ ByteOrder bo = input.getByteOrder();
+ input.setByteOrder(fByteOrder);
+ int first = (int) input.get(COMPACT_ID, false);
+ long second = input.get(COMPACT_TS, false);
+ if (first != EXTENDED_VALUE) {
+ input.setByteOrder(bo);
+ return new EventHeaderDefinition(this, first, second, COMPACT_TS);
+ }
+ long timestampLong = input.get(FULL_TS, false);
+ input.setByteOrder(bo);
+ if (second > Integer.MAX_VALUE) {
+ throw new CTFReaderException("ID " + second + " larger than " + Integer.MAX_VALUE + " is currently unsupported by the parser"); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
+ }
+ return new EventHeaderDefinition(this, (int) second, timestampLong, FULL_TS);
+ }
+
+ @Override
+ public long getAlignment() {
+ return ALIGN;
+ }
+
+ @Override
+ public int getMaximumSize() {
+ return MAX_SIZE;
+ }
+
+ /**
+ * Check if a given struct declaration is an event header
+ *
+ * @param declaration
+ * the declaration
+ * @return true if the event is a large event header
+ */
+ public static boolean isLargeEventHeader(StructDeclaration declaration) {
+
+ IDeclaration iDeclaration = declaration.getFields().get(ID);
+ if (!(iDeclaration instanceof EnumDeclaration)) {
+ return false;
+ }
+ EnumDeclaration eId = (EnumDeclaration) iDeclaration;
+ if (eId.getContainerType().getLength() != COMPACT_ID) {
+ return false;
+ }
+ iDeclaration = declaration.getFields().get(V);
+
+ if (!(iDeclaration instanceof VariantDeclaration)) {
+ return false;
+ }
+ VariantDeclaration vDec = (VariantDeclaration) iDeclaration;
+ if (!vDec.hasField(COMPACT) || !vDec.hasField(EXTENDED)) {
+ return false;
+ }
+ if (vDec.getFields().size() != VARIANT_SIZE) {
+ return false;
+ }
+ iDeclaration = vDec.getFields().get(COMPACT);
+ if (!(iDeclaration instanceof StructDeclaration)) {
+ return false;
+ }
+ StructDeclaration compactDec = (StructDeclaration) iDeclaration;
+ if (compactDec.getFields().size() != COMPACT_SIZE) {
+ return false;
+ }
+ if (!compactDec.hasField(TIMESTAMP)) {
+ return false;
+ }
+ iDeclaration = compactDec.getFields().get(TIMESTAMP);
+ if (!(iDeclaration instanceof IntegerDeclaration)) {
+ return false;
+ }
+ IntegerDeclaration tsDec = (IntegerDeclaration) iDeclaration;
+ if (tsDec.getLength() != COMPACT_TS || tsDec.isSigned()) {
+ return false;
+ }
+ iDeclaration = vDec.getFields().get(EXTENDED);
+ if (!(iDeclaration instanceof StructDeclaration)) {
+ return false;
+ }
+ StructDeclaration extendedDec = (StructDeclaration) iDeclaration;
+ if (!extendedDec.hasField(TIMESTAMP)) {
+ return false;
+ }
+ if (extendedDec.getFields().size() != EXTENDED_FIELD_SIZE) {
+ return false;
+ }
+ iDeclaration = extendedDec.getFields().get(TIMESTAMP);
+ if (!(iDeclaration instanceof IntegerDeclaration)) {
+ return false;
+ }
+ tsDec = (IntegerDeclaration) iDeclaration;
+ if (tsDec.getLength() != FULL_TS || tsDec.isSigned()) {
+ return false;
+ }
+ iDeclaration = extendedDec.getFields().get(ID);
+ if (!(iDeclaration instanceof IntegerDeclaration)) {
+ return false;
+ }
+ IntegerDeclaration iId = (IntegerDeclaration) iDeclaration;
+ if (iId.getLength() != ID_SIZE || iId.isSigned()) {
+ return false;
+ }
+ return true;
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ * Contributors: Etienne Bergeron <etienne.bergeron@gmail.com>
+ * Contributors: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.internal.ctf.core.trace;
+
+import java.util.ListIterator;
+import java.util.Vector;
+
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+
+/**
+ * <b><u>StreamInputPacketIndex</u></b>
+ * <p>
+ * TODO Implement me. Please.
+ */
+public class StreamInputPacketIndex {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ /**
+ * Entries of the index. They are sorted by increasing begin timestamp.
+ * index builder.
+ */
+ private final Vector<StreamInputPacketIndexEntry> entries = new Vector<>();
+
+ // ------------------------------------------------------------------------
+ // Getters/Setters/Predicates
+ // ------------------------------------------------------------------------
+
+ /**
+ * Gets the entries
+ *
+ * @return the entries
+ */
+ public Vector<StreamInputPacketIndexEntry> getEntries() {
+ return this.entries;
+ }
+
+ /**
+ * Gets an iterator to the entries
+ *
+ * @return an iterator to the entries
+ */
+ public ListIterator<StreamInputPacketIndexEntry> listIterator() {
+ return this.entries.listIterator();
+ }
+
+ /**
+ * Gets an iterator to the entries at a given position
+ *
+ * @param n
+ * the position to get
+ * @return the iterator
+ */
+ public ListIterator<StreamInputPacketIndexEntry> listIterator(int n) {
+ return this.entries.listIterator(n);
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ /**
+ * Adds an entry to the index.
+ *
+ * @param entry
+ * The entry to add
+ * @throws CTFReaderException
+ * If there was a problem reading the entry
+ */
+ public void addEntry(StreamInputPacketIndexEntry entry)
+ throws CTFReaderException {
+ assert (entry.getContentSizeBits() != 0);
+
+ /* Validate consistent entry. */
+ if (entry.getTimestampBegin() > entry.getTimestampEnd()) {
+ throw new CTFReaderException("Packet begin timestamp is after end timestamp"); //$NON-NLS-1$
+ }
+
+ /* Validate entries are inserted in monotonic increasing timestamp order. */
+ if (!this.entries.isEmpty()) {
+ if (entry.getTimestampBegin() < this.entries.lastElement()
+ .getTimestampBegin()) {
+ throw new CTFReaderException("Packets begin timestamp decreasing"); //$NON-NLS-1$
+ }
+ }
+ this.entries.add(entry);
+ }
+
+ /**
+ * Returns the first PacketIndexEntry that could include the timestamp,
+ * that is the last packet with a begin timestamp smaller than the given timestamp.
+ *
+ * @param timestamp
+ * The timestamp to look for.
+ * @return The StreamInputPacketEntry that corresponds to the packet that
+ * includes the given timestamp.
+ */
+ public ListIterator<StreamInputPacketIndexEntry> search(final long timestamp) {
+ /*
+ * Start with min and max covering all the elements.
+ */
+ int max = this.entries.size() - 1;
+ int min = 0;
+
+ int guessI;
+ StreamInputPacketIndexEntry guessEntry = null;
+
+ /*
+ * If the index is empty, return the iterator at the very beginning.
+ */
+ if (this.getEntries().isEmpty()) {
+ return this.getEntries().listIterator();
+ }
+
+ if (timestamp < 0) {
+ throw new IllegalArgumentException("timestamp is negative"); //$NON-NLS-1$
+ }
+
+ /* Binary search */
+ for (;;) {
+ /*
+ * Guess in the middle of min and max.
+ */
+ guessI = min + ((max - min) / 2);
+ guessEntry = this.entries.get(guessI);
+
+ /*
+ * If we reached the point where we focus on a single packet, our
+ * search is done.
+ */
+ if (min == max) {
+ break;
+ }
+
+ if (timestamp <= guessEntry.getTimestampEnd()) {
+ /*
+ * If the timestamp is lower or equal to the end of the guess packet,
+ * then the guess packet becomes the new inclusive max.
+ */
+ max = guessI;
+ } else {
+ /*
+ * If the timestamp is greater than the end of the guess packet, then
+ * the new inclusive min is the packet after the guess packet.
+ */
+ min = guessI + 1;
+ }
+ }
+
+ return this.entries.listIterator(guessI);
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.internal.ctf.core.trace;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * <b><u>StreamInputPacketIndexEntry</u></b>
+ * <p>
+ * Represents an entry in the index of event packets.
+ */
+public class StreamInputPacketIndexEntry {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ /**
+ * Offset of the packet in the file, in bytes
+ */
+ final private long fOffsetBytes;
+
+ /**
+ * Offset of the data in the packet, in bits
+ */
+ private long fDataOffsetBits = 0;
+
+ /**
+ * Packet size, in bits
+ */
+ private long fPacketSizeBits = 0;
+
+ /**
+ * Content size, in bits
+ */
+ private long fContentSizeBits = 0;
+
+ /**
+ * Begin timestamp
+ */
+ private long fTimestampBegin = 0;
+
+ /**
+ * End timestamp
+ */
+ private long fTimestampEnd = 0;
+
+ /**
+ * How many lost events are there?
+ */
+ private long fLostEvents = 0;
+
+ /**
+ * Which target is being traced
+ */
+ private String fTarget ;
+ private long fTargetID;
+
+ /**
+ * Attributes of this index entry
+ */
+ private final Map<String, Object> fAttributes = new HashMap<>();
+
+
+ // ------------------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructs an index entry.
+ *
+ * @param offset
+ * The offset of the packet in the file, in bytes.
+ */
+
+ public StreamInputPacketIndexEntry(long offset) {
+ fOffsetBytes = offset;
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ /**
+ * Returns whether the packet includes (inclusively) the given timestamp in
+ * the begin-end timestamp range.
+ *
+ * @param ts
+ * The timestamp to check.
+ * @return True if the packet includes the timestamp.
+ */
+ boolean includes(long ts) {
+ return (ts >= fTimestampBegin) && (ts <= fTimestampEnd);
+ }
+
+ @Override
+ public String toString() {
+ return "StreamInputPacketIndexEntry [offsetBytes=" + fOffsetBytes //$NON-NLS-1$
+ + ", timestampBegin=" + fTimestampBegin + ", timestampEnd=" //$NON-NLS-1$ //$NON-NLS-2$
+ + fTimestampEnd + "]"; //$NON-NLS-1$
+ }
+
+ // ------------------------------------------------------------------------
+ // Getters and Setters
+ // ------------------------------------------------------------------------
+
+ /**
+ * @return the offsetBytes
+ */
+ public long getOffsetBytes() {
+ return fOffsetBytes;
+ }
+
+ /**
+ * @return the dataOffsetBits
+ */
+ public long getDataOffsetBits() {
+ return fDataOffsetBits;
+ }
+
+ /**
+ * @param dataOffsetBits
+ * the dataOffsetBits to set
+ */
+ public void setDataOffsetBits(long dataOffsetBits) {
+ fDataOffsetBits = dataOffsetBits;
+ }
+
+ /**
+ * @return the packetSizeBits
+ */
+ public long getPacketSizeBits() {
+ return fPacketSizeBits;
+ }
+
+ /**
+ * @param packetSizeBits
+ * the packetSizeBits to set
+ */
+ public void setPacketSizeBits(long packetSizeBits) {
+ fPacketSizeBits = packetSizeBits;
+ }
+
+ /**
+ * @return the contentSizeBits
+ */
+ public long getContentSizeBits() {
+ return fContentSizeBits;
+ }
+
+ /**
+ * @param contentSizeBits
+ * the contentSizeBits to set
+ */
+ public void setContentSizeBits(long contentSizeBits) {
+ fContentSizeBits = contentSizeBits;
+ }
+
+ /**
+ * @return the timestampBegin
+ */
+ public long getTimestampBegin() {
+ return fTimestampBegin;
+ }
+
+ /**
+ * @param timestampBegin
+ * the timestampBegin to set
+ */
+ public void setTimestampBegin(long timestampBegin) {
+ fTimestampBegin = timestampBegin;
+ }
+
+ /**
+ * @return the timestampEnd
+ */
+ public long getTimestampEnd() {
+ return fTimestampEnd;
+ }
+
+ /**
+ * @param timestampEnd
+ * the timestampEnd to set
+ */
+ public void setTimestampEnd(long timestampEnd) {
+ fTimestampEnd = timestampEnd;
+ }
+
+ /**
+ * @return the lostEvents in this packet
+ */
+ public long getLostEvents() {
+ return fLostEvents;
+ }
+
+ /**
+ * @param lostEvents the lostEvents to set
+ */
+ public void setLostEvents(long lostEvents) {
+ fLostEvents = lostEvents;
+ }
+
+ /**
+ * Add an attribute to this index entry
+ *
+ * @param field
+ * The name of the attribute
+ * @param value
+ * The value to insert
+ */
+ public void addAttribute(String field, Object value) {
+ fAttributes.put(field, value);
+ }
+
+ /**
+ * Retrieve the value of an existing attribute
+ *
+ * @param field
+ * The name of the attribute
+ * @return The value that was stored, or null if it wasn't found
+ */
+ public Object lookupAttribute(String field){
+ return fAttributes.get(field);
+ }
+
+ /**
+ * @return The target that is being traced
+ */
+ public String getTarget() {
+ return fTarget;
+ }
+
+ /**
+ * Assign a target to this index entry
+ *
+ * @param target
+ * The target to assign
+ */
+ public void setTarget(String target) {
+ fTarget = target;
+ fTargetID = Integer.parseInt(target.replaceAll("[\\D]", "")); //$NON-NLS-1$ //$NON-NLS-2$ // slow
+ }
+
+ /**
+ * @return The ID of the target
+ */
+ public long getTargetId(){
+ return fTargetID;
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2011, 2013 Ericsson, Ecole Polytechnique de Montreal and others
+ *
+ * All rights reserved. This program and the accompanying materials are made
+ * available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors: Matthew Khouzam - Initial API and implementation
+ * Contributors: Simon Marchi - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.internal.ctf.core.trace;
+
+import java.io.Serializable;
+import java.util.Comparator;
+
+import org.eclipse.tracecompass.ctf.core.event.EventDefinition;
+import org.eclipse.tracecompass.ctf.core.trace.CTFStreamInputReader;
+import org.eclipse.tracecompass.ctf.core.trace.Utils;
+
+/**
+ * <b><u>StreamInputReaderTimestampComparator</u></b>
+ * <p>
+ * Compares two StreamInputReader by their timestamp (smaller comes before).
+ */
+public class StreamInputReaderTimestampComparator implements
+ Comparator<CTFStreamInputReader>, Serializable {
+
+ // ------------------------------------------------------------------------
+ // Constants
+ // ------------------------------------------------------------------------
+
+ private static final long serialVersionUID = 1066434959451875045L;
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ /**
+ * @throws NullPointerException
+ * If any {@link CTFStreamInputReader} parameter is null, of if any
+ * of them does not contain a current event.
+ */
+ @Override
+ public int compare(CTFStreamInputReader a, CTFStreamInputReader b) {
+ EventDefinition event_a = a.getCurrentEvent();
+ EventDefinition event_b = b.getCurrentEvent();
+
+ long ta = event_a.getTimestamp();
+ long tb = event_b.getTimestamp();
+ return Utils.unsignedCompare(ta, tb);
+ }
+
+}
Require-Bundle: org.junit;bundle-version="4.0.0",
org.eclipse.core.runtime,
org.eclipse.tracecompass.ctf.parser;bundle-version="3.1.0"
-Export-Package: org.eclipse.linuxtools.ctf.parser.tests
+Export-Package: org.eclipse.tracecompass.ctf.parser.tests
Import-Package: org.antlr.runtime;version="3.2.0",
org.antlr.runtime.tree;version="3.2.0"
<version>${tycho-version}</version>
<configuration>
<testSuite>org.eclipse.tracecompass.ctf.parser.tests</testSuite>
- <testClass>org.eclipse.linuxtools.ctf.parser.tests.AllCtfParserTests</testClass>
+ <testClass>org.eclipse.tracecompass.ctf.parser.tests.AllCtfParserTests</testClass>
<useUIHarness>false</useUIHarness>
<useUIThread>false</useUIThread>
<product>org.eclipse.platform.ide</product>
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Ericsson
- *
- * All rights reserved. This program and the accompanying materials are
- * made available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Etienne Bergeron - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.parser.tests;
-
-import org.junit.runner.RunWith;
-import org.junit.runners.Suite;
-
-/**
- * Master test suite for CTF parser.
- */
-@RunWith(Suite.class)
-@Suite.SuiteClasses({
- CtfLexerTest.class,
- CtfParserTest.class
-})
-
-public class AllCtfParserTests {
-
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013, 2014 Etienne Bergeron
- *
- * All rights reserved. This program and the accompanying materials are
- * made available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Etienne Bergeron - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.parser.tests;
-
-import static org.junit.Assert.fail;
-
-import java.util.LinkedList;
-import java.util.List;
-
-import org.antlr.runtime.ANTLRStringStream;
-import org.antlr.runtime.CharStream;
-import org.antlr.runtime.Token;
-import org.eclipse.linuxtools.ctf.parser.CTFLexer;
-import org.junit.Ignore;
-import org.junit.Test;
-
-/**
- * This test validates the CTF-Lexer implementation.
- *
- * The test splits a string into tokens with the compiled lexer and
- * validates the sequences of tokens produced by comparing their type
- * and content.
- *
- * @author Etienne Bergeron
- */
-public class CtfLexerTest {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- private final List<Token> tokens = new LinkedList<>();
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- private void tokenize(String content) {
- CharStream cs = new ANTLRStringStream(content);
- CTFLexer lexer = new CTFLexer(cs);
-
- tokens.clear();
- for (;;) {
- Token token = lexer.nextToken();
- if (token == Token.EOF_TOKEN) {
- return;
- }
- tokens.add(token);
- }
- }
-
- private void checkToken(int type, String content) {
- Token token = tokens.remove(0);
- if (token.getType() != type) {
- fail("Invalid type [value " + token.getType()
- + " but expect " + type + "]."
- + " Fail to tokenize:" + content);
- } else if (token.getText().compareTo(content) != 0) {
- fail("Invalid content [value " + token.getText()
- + " but expect " + content + "].");
- }
- }
-
- private void checkSingle(int type, String content) {
- tokenize(content);
- checkToken(type, content);
- }
-
- // ------------------------------------------------------------------------
- // Test cases
- // ------------------------------------------------------------------------
-
- /**
- * Validate the parsing of keywords
- */
- @Test
- public void testKeywords() {
- checkSingle(CTFLexer.ALIGNTOK, "align");
- checkSingle(CTFLexer.CONSTTOK, "const");
- checkSingle(CTFLexer.CHARTOK, "char");
- checkSingle(CTFLexer.DOUBLETOK, "double");
- checkSingle(CTFLexer.ENUMTOK, "enum");
- checkSingle(CTFLexer.EVENTTOK, "event");
- checkSingle(CTFLexer.FLOATINGPOINTTOK, "floating_point");
- checkSingle(CTFLexer.FLOATTOK, "float");
- checkSingle(CTFLexer.INTEGERTOK, "integer");
- checkSingle(CTFLexer.INTTOK, "int");
- checkSingle(CTFLexer.LONGTOK, "long");
- checkSingle(CTFLexer.SHORTTOK, "short");
- checkSingle(CTFLexer.SIGNEDTOK, "signed");
- checkSingle(CTFLexer.STREAMTOK, "stream");
- checkSingle(CTFLexer.STRINGTOK, "string");
- checkSingle(CTFLexer.STRUCTTOK, "struct");
- checkSingle(CTFLexer.TRACETOK, "trace");
- checkSingle(CTFLexer.TYPEALIASTOK, "typealias");
- checkSingle(CTFLexer.TYPEDEFTOK, "typedef");
- checkSingle(CTFLexer.UNSIGNEDTOK, "unsigned");
- checkSingle(CTFLexer.VARIANTTOK, "variant");
- checkSingle(CTFLexer.VOIDTOK, "void");
- checkSingle(CTFLexer.BOOLTOK, "_Bool");
- checkSingle(CTFLexer.COMPLEXTOK, "_Complex");
- checkSingle(CTFLexer.IMAGINARYTOK, "_Imaginary");
- checkSingle(CTFLexer.ENVTOK, "env");
- checkSingle(CTFLexer.CLOCKTOK, "clock");
- checkSingle(CTFLexer.CALLSITETOK, "callsite");
- checkSingle(CTFLexer.NANNUMBERTOK, "NaN");
- checkSingle(CTFLexer.INFINITYTOK, "+inf");
- checkSingle(CTFLexer.NINFINITYTOK, "-inf");
- }
-
- /**
- * Validate the parsing of symbols
- */
- @Test
- public void testSymbols() {
- tokenize(" , : ... ");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.SEPARATOR, ",");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.COLON, ":");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.ELIPSES, "...");
- checkToken(CTFLexer.WS, " ");
-
- tokenize(" = := = ");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.ASSIGNMENT, "=");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.TYPE_ASSIGNMENT, ":=");
- checkToken(CTFLexer.WS, " ");
-
- tokenize(" <<>> ");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.LT, "<");
- checkToken(CTFLexer.LT, "<");
- checkToken(CTFLexer.GT, ">");
- checkToken(CTFLexer.GT, ">");
- checkToken(CTFLexer.WS, " ");
-
- tokenize(" ({[]}) ");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.LPAREN, "(");
- checkToken(CTFLexer.LCURL, "{");
- checkToken(CTFLexer.OPENBRAC, "[");
- checkToken(CTFLexer.CLOSEBRAC, "]");
- checkToken(CTFLexer.RCURL, "}");
- checkToken(CTFLexer.RPAREN, ")");
- checkToken(CTFLexer.WS, " ");
-
- tokenize(";;");
- checkToken(CTFLexer.TERM, ";");
- checkToken(CTFLexer.TERM, ";");
-
- tokenize(" ++ -- ");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.SIGN, "+");
- checkToken(CTFLexer.SIGN, "+");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.SIGN, "-");
- checkToken(CTFLexer.SIGN, "-");
- checkToken(CTFLexer.WS, " ");
-
- tokenize("-> .*.");
- checkToken(CTFLexer.ARROW, "->");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.DOT, ".");
- checkToken(CTFLexer.POINTER, "*");
- checkToken(CTFLexer.DOT, ".");
- }
-
- /**
- * Validate the parsing of literals
- */
- @Test
- public void testLiterals() {
- tokenize("01 02 010");
- checkToken(CTFLexer.OCTAL_LITERAL, "01");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.OCTAL_LITERAL, "02");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.OCTAL_LITERAL, "010");
-
- tokenize("1 2 10 1024 ");
- checkToken(CTFLexer.DECIMAL_LITERAL, "1");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.DECIMAL_LITERAL, "2");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.DECIMAL_LITERAL, "10");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.DECIMAL_LITERAL, "1024");
- checkToken(CTFLexer.WS, " ");
-
- tokenize("0x01 0x02 0x0F0");
- checkToken(CTFLexer.HEX_LITERAL, "0x01");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.HEX_LITERAL, "0x02");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.HEX_LITERAL, "0x0F0");
- }
-
- /**
- * Validate the parsing of literals with hexa prefix
- */
- @Test
- public void testLiteralPrefixes() {
- checkSingle(CTFLexer.HEX_LITERAL, "0x1");
- checkSingle(CTFLexer.HEX_LITERAL, "0X1");
- }
-
- /**
- * Validate the parsing of literals with type suffix
- */
- @Test
- public void testLiteralSuffixes() {
- checkSingle(CTFLexer.DECIMAL_LITERAL, "0l");
- checkSingle(CTFLexer.DECIMAL_LITERAL, "0L");
- checkSingle(CTFLexer.DECIMAL_LITERAL, "0ll");
- checkSingle(CTFLexer.DECIMAL_LITERAL, "0LL");
- checkSingle(CTFLexer.DECIMAL_LITERAL, "0ul");
- checkSingle(CTFLexer.DECIMAL_LITERAL, "0uL");
- checkSingle(CTFLexer.DECIMAL_LITERAL, "0ull");
- checkSingle(CTFLexer.DECIMAL_LITERAL, "0uLL");
- checkSingle(CTFLexer.DECIMAL_LITERAL, "0Ul");
- checkSingle(CTFLexer.DECIMAL_LITERAL, "0UL");
- checkSingle(CTFLexer.DECIMAL_LITERAL, "0Ull");
- checkSingle(CTFLexer.DECIMAL_LITERAL, "0ULL");
- }
-
- /**
- * Validate the accepted characters in literals.
- */
- @Test
- public void testLiteralDigits() {
- checkSingle(CTFLexer.OCTAL_LITERAL, "001234567");
-
- checkSingle(CTFLexer.DECIMAL_LITERAL, "123456");
- checkSingle(CTFLexer.DECIMAL_LITERAL, "987654");
-
- checkSingle(CTFLexer.HEX_LITERAL, "0x012345");
- checkSingle(CTFLexer.HEX_LITERAL, "0x678990");
- checkSingle(CTFLexer.HEX_LITERAL, "0xABCDEF");
- checkSingle(CTFLexer.HEX_LITERAL, "0xabcdef");
- }
-
- /**
- * Validate zero literal to be the right token.
- */
- @Test
- public void testLiteralZero() {
- checkSingle(CTFLexer.OCTAL_LITERAL, "00");
- checkSingle(CTFLexer.DECIMAL_LITERAL, "0");
- checkSingle(CTFLexer.HEX_LITERAL, "0x0");
- }
-
- /**
- * Validate character literals
- */
- @Test
- public void testCharLiteral() {
- checkSingle(CTFLexer.CHARACTER_LITERAL, "'x'");
- checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\''");
- checkSingle(CTFLexer.CHARACTER_LITERAL, "' '");
- checkSingle(CTFLexer.CHARACTER_LITERAL, "L'1'");
- }
-
- /**
- * Validate escaped character literals
- */
- @Test
- public void testEscapeCharLiteral() {
- checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\a'");
- checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\b'");
- checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\f'");
- checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\n'");
- checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\r'");
- checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\t'");
- checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\v'");
- checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\''");
- checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\\"'");
- checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\\\'");
-
- checkSingle(CTFLexer.CHARACTER_LITERAL, "'\001'");
- checkSingle(CTFLexer.CHARACTER_LITERAL, "'\01'");
- checkSingle(CTFLexer.CHARACTER_LITERAL, "'\1'");
-
- checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\x1A'");
- checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\x1a'");
- checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\xa'");
- checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\x0'");
-
- checkSingle(CTFLexer.CHARACTER_LITERAL, "'\uABCD'");
- checkSingle(CTFLexer.CHARACTER_LITERAL, "'\u0123'");
- checkSingle(CTFLexer.CHARACTER_LITERAL, "'\u012345678'");
- checkSingle(CTFLexer.CHARACTER_LITERAL, "'\uFEDCBA987'");
- }
-
- /**
- * Validate string literals
- */
- @Test
- public void testStringLiteral() {
- checkSingle(CTFLexer.STRING_LITERAL, "\"\"");
- checkSingle(CTFLexer.STRING_LITERAL, "\"x\"");
- checkSingle(CTFLexer.STRING_LITERAL, "\"\\\"\"");
- checkSingle(CTFLexer.STRING_LITERAL, "\" \"");
- checkSingle(CTFLexer.STRING_LITERAL, "L\"1\"");
-
- checkSingle(CTFLexer.STRING_LITERAL, "\"This is \\n a multiline\\r\\n\"");
- checkSingle(CTFLexer.STRING_LITERAL, "L\"This is \\n a multiline\\r\\n\"");
- }
-
- /**
- * Validate string literals with escape sequence
- */
- @Test
- public void testEscapeStringLiteral() {
- checkSingle(CTFLexer.STRING_LITERAL, "\"\\a\"");
- checkSingle(CTFLexer.STRING_LITERAL, "\"\\b\"");
- checkSingle(CTFLexer.STRING_LITERAL, "\"\\f\"");
- checkSingle(CTFLexer.STRING_LITERAL, "\"\\n\"");
- checkSingle(CTFLexer.STRING_LITERAL, "\"\\r\"");
- checkSingle(CTFLexer.STRING_LITERAL, "\"\\t\"");
- checkSingle(CTFLexer.STRING_LITERAL, "\"\\v\"");
- checkSingle(CTFLexer.STRING_LITERAL, "\"\\'\"");
- checkSingle(CTFLexer.STRING_LITERAL, "\"\\\"\"");
- checkSingle(CTFLexer.STRING_LITERAL, "\"\\\\\"");
-
- checkSingle(CTFLexer.STRING_LITERAL, "\"\001\"");
- checkSingle(CTFLexer.STRING_LITERAL, "\"\01\"");
- checkSingle(CTFLexer.STRING_LITERAL, "\"\1\"");
-
- checkSingle(CTFLexer.STRING_LITERAL, "\"\\x1A\"");
- checkSingle(CTFLexer.STRING_LITERAL, "\"\\x1a\"");
- checkSingle(CTFLexer.STRING_LITERAL, "\"\\xa\"");
- checkSingle(CTFLexer.STRING_LITERAL, "\"\\x0\"");
-
- checkSingle(CTFLexer.STRING_LITERAL, "\"\uABCD\"");
- checkSingle(CTFLexer.STRING_LITERAL, "\"\u0123\"");
- checkSingle(CTFLexer.STRING_LITERAL, "\"\u012345678\"");
- checkSingle(CTFLexer.STRING_LITERAL, "\"\uFEDCBA987\"");
- }
-
- /**
- * Validate spaces parsing
- */
- @Test
- public void testWhitespaces() {
- tokenize(" \r\t\n\u000C ");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.WS, "\r");
- checkToken(CTFLexer.WS, "\t");
- checkToken(CTFLexer.WS, "\n");
- checkToken(CTFLexer.WS, "\u000C");
- checkToken(CTFLexer.WS, " ");
- }
-
- /**
- * Validate comments parsing
- */
- @Test
- public void testComment() {
- tokenize(" /* test */ ");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.COMMENT, "/* test */");
- checkToken(CTFLexer.WS, " ");
- }
-
- /**
- * Validate complex nested comments parsing
- */
- @Test
- public void testNestedComment() {
- tokenize(" /* /* */ ");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.COMMENT, "/* /* */");
- checkToken(CTFLexer.WS, " ");
-
- tokenize(" /* /* * ** / */ ");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.COMMENT, "/* /* * ** / */");
- checkToken(CTFLexer.WS, " ");
- }
-
- /**
- * Validate multi-lines comments
- */
- @Test
- public void testMultiLineComment() {
- tokenize(" /*\ntest\n*/ ");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.COMMENT, "/*\ntest\n*/");
- checkToken(CTFLexer.WS, " ");
- }
-
- /**
- * Validate single line comments
- */
- @Test
- public void testLineComment() {
- tokenize(" // asdad\r\n ");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.LINE_COMMENT, "// asdad\r\n");
- checkToken(CTFLexer.WS, " ");
- }
-
- /**
- * Validate incomplete comments parsing
- */
- @Ignore("Lexer must be fixed first")
- @Test
- public void testLineCommentWithEOF() {
- tokenize("//");
- checkToken(CTFLexer.LINE_COMMENT, "//");
- }
-
- /**
- * Validate parsing of mixed kind of comments
- */
- @Test
- public void testMixedComment() {
- tokenize(" // /*\n");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.LINE_COMMENT, "// /*\n");
-
- tokenize(" /*\n//\n*/ ");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.COMMENT, "/*\n//\n*/");
- checkToken(CTFLexer.WS, " ");
- }
-
- /**
- * Validate parsing identifiers
- */
- @Test
- public void testIdentifier() {
- tokenize("_ a a1 B ");
- checkToken(CTFLexer.IDENTIFIER, "_");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.IDENTIFIER, "a");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.IDENTIFIER, "a1");
- checkToken(CTFLexer.WS, " ");
- checkToken(CTFLexer.IDENTIFIER, "B");
- checkToken(CTFLexer.WS, " ");
- }
-
- /**
- * Validate accepted characters within an identifier
- */
- @Test
- public void testIdentifierLetters() {
- checkSingle(CTFLexer.IDENTIFIER, "ABCDEFGHI");
- checkSingle(CTFLexer.IDENTIFIER, "JKLMNOPQR");
- checkSingle(CTFLexer.IDENTIFIER, "STUVWXYZ");
- checkSingle(CTFLexer.IDENTIFIER, "abcdefghi");
- checkSingle(CTFLexer.IDENTIFIER, "jklmnopqr");
- checkSingle(CTFLexer.IDENTIFIER, "stuvwxyz");
- checkSingle(CTFLexer.IDENTIFIER, "_0123456789");
- }
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright (c) 2013 Etienne Bergeron
- *
- * All rights reserved. This program and the accompanying materials are
- * made available under the terms of the Eclipse Public License v1.0 which
- * accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Etienne Bergeron - Initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.linuxtools.ctf.parser.tests;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-
-import org.antlr.runtime.ANTLRStringStream;
-import org.antlr.runtime.CharStream;
-import org.antlr.runtime.CommonTokenStream;
-import org.antlr.runtime.RecognitionException;
-import org.antlr.runtime.tree.CommonTree;
-import org.eclipse.linuxtools.ctf.parser.CTFLexer;
-import org.eclipse.linuxtools.ctf.parser.CTFParser;
-import org.junit.Ignore;
-import org.junit.Test;
-
-/**
- * This test validates the CTF-Parser implementation.
- *
- * The goal of these tests is to validate syntactic rules and not the
- * CTF semantic. Each test parses a string with a given rule of the
- * compiled parser and validates the resulting tree by using match rules.
- *
- * @author Etienne Bergeron
- */
-public class CtfParserTest {
-
- // ------------------------------------------------------------------------
- // Attributes
- // ------------------------------------------------------------------------
-
- private CTFParser parser;
-
- // ------------------------------------------------------------------------
- // Matches - Helper class and functions to match a parsed tree.
- // ------------------------------------------------------------------------
-
- private class TreeMatcher {
- int fType;
- String fText;
- TreeMatcher[] fChild;
-
- TreeMatcher(int type, String text, TreeMatcher child[]) {
- fType = type;
- fText = text;
- fChild = child;
- }
-
- void matches(CommonTree tree) {
- if (fType == -1) {
- return;
- }
- if (tree.getType() != fType) {
- fail("Type mismatch!" +
- " expected:" + fType +
- " actual:" + tree.getType());
- }
-
- if (fText != null) {
- if (tree.getText().compareTo(fText) != 0) {
- fail("Text mismatch!" +
- " expected:" + fText +
- " actual:" + tree.getText());
- }
- }
-
- if (fChild != null) {
- int size = fChild.length;
- if (tree.getChildren() == null) {
- if (size != 0) {
- fail("Invalid children!"
- + "Expect: " + size + "child");
- }
- } else {
- if (tree.getChildren().size() != size) {
- fail("Invalid number of childs!"
- + " expected:" + size
- + " actual:" + tree.getChildren().size());
- }
-
- for (int i = 0; i < size; ++i) {
- fChild[i].matches((CommonTree) tree.getChild(i));
- }
- }
- }
- }
- }
-
- void Matches(TreeMatcher matcher, CommonTree tree) {
- if (tree == null) {
- fail("Parsing failed!");
- }
- matcher.matches(tree);
- }
-
- TreeMatcher All() {
- return new TreeMatcher(-1, null, null);
- }
-
- TreeMatcher Node(int type, TreeMatcher... child) {
- return new TreeMatcher(type, null, child);
- }
-
- TreeMatcher Node(int type, String text, TreeMatcher... child) {
- return new TreeMatcher(type, text, child);
- }
-
- TreeMatcher List(TreeMatcher... child) {
- return new TreeMatcher(0, null, child);
- }
-
- // ------------------------------------------------------------------------
- // Operations
- // ------------------------------------------------------------------------
-
- private void setInput(String content) {
- CharStream cs = new ANTLRStringStream(content);
- CTFLexer lexer = new CTFLexer(cs);
- CommonTokenStream tokens = new CommonTokenStream(lexer);
- parser = new CTFParser(tokens, false);
- }
-
- private CommonTree primaryExpression(String content) {
- try {
- setInput(content);
- return parser.primaryExpression().getTree();
- } catch (RecognitionException e) {
- return null;
- }
- }
-
- private CommonTree unaryExpression(String content) {
- try {
- setInput(content);
- return parser.unaryExpression().getTree();
- } catch (RecognitionException e) {
- return null;
- }
- }
-
- private CommonTree declaration(String content) {
- try {
- setInput(content);
- return parser.declaration().getTree();
- } catch (RecognitionException e) {
- return null;
- }
- }
-
- // ------------------------------------------------------------------------
- // Test cases
- // ------------------------------------------------------------------------
-
-
- /**
- * Validate that parsing of an empty expression is invalid.
- */
- @Test
- public void testPrimaryExpression() {
- CommonTree tree_empty = primaryExpression("");
- assertEquals(null, tree_empty);
- }
-
- /**
- * Validate parsing of literals through a primary expression
- */
- @Test
- public void testIntegerLiteralPrimaryExpression() {
- Matches(Node(CTFParser.UNARY_EXPRESSION_DEC,
- Node(CTFParser.DECIMAL_LITERAL, "123")),
- primaryExpression("123"));
-
- Matches(Node(CTFParser.UNARY_EXPRESSION_HEX,
- Node(CTFParser.HEX_LITERAL, "0x123")),
- primaryExpression("0x123"));
-
- Matches(Node(CTFParser.UNARY_EXPRESSION_OCT,
- Node(CTFParser.OCTAL_LITERAL, "0123")),
- primaryExpression("0123"));
-
- Matches(Node(CTFParser.UNARY_EXPRESSION_DEC,
- Node(CTFParser.DECIMAL_LITERAL, "123"),
- Node(CTFParser.SIGN, "-")),
- primaryExpression("-123"));
-
- Matches(Node(CTFParser.UNARY_EXPRESSION_DEC,
- Node(CTFParser.DECIMAL_LITERAL, "123"),
- Node(CTFParser.SIGN, "-")),
- primaryExpression(" - 123"));
-
- Matches(Node(CTFParser.UNARY_EXPRESSION_DEC,
- Node(CTFParser.DECIMAL_LITERAL, "123"),
- Node(CTFParser.SIGN, "-"),
- Node(CTFParser.SIGN, "-"),
- Node(CTFParser.SIGN, "+")),
- primaryExpression(" - - + 123"));
-
- Matches(Node(CTFParser.UNARY_EXPRESSION_HEX,
- Node(CTFParser.HEX_LITERAL, "0x123"),
- Node(CTFParser.SIGN, "+"),
- Node(CTFParser.SIGN, "-")),
- primaryExpression("+ - 0x123"));
-
- Matches(Node(CTFParser.UNARY_EXPRESSION_OCT,
- Node(CTFParser.OCTAL_LITERAL, "0123"),
- Node(CTFParser.SIGN, "+"),
- Node(CTFParser.SIGN, "-")),
- primaryExpression("+ - 0123"));
- }
-
- /**
- * Validate parsing of a character literals through a primary expression
- */
- @Test
- public void testCharacterLiteralPrimaryExpression() {
- Matches(Node(CTFParser.CHARACTER_LITERAL, "'a'"),
- primaryExpression("'a'"));
-
- Matches(Node(CTFParser.CHARACTER_LITERAL, "'\\n'"),
- primaryExpression("'\\n'"));
- }
-
- /**
- * Validate parsing of a string literals through a primary expression
- */
- @Test
- public void testStringLiteralPrimaryExpression() {
- Matches(Node(CTFParser.UNARY_EXPRESSION_STRING_QUOTES,
- Node(CTFParser.STRING_LITERAL, "\"aaa\"")),
- primaryExpression("\"aaa\""));
-
- Matches(Node(CTFParser.UNARY_EXPRESSION_STRING_QUOTES,
- Node(CTFParser.STRING_LITERAL, "L\"aaa\"")),
- primaryExpression("L\"aaa\""));
-
- Matches(Node(CTFParser.UNARY_EXPRESSION_STRING_QUOTES,
- Node(CTFParser.STRING_LITERAL, "\"aaa\\n\"")),
- primaryExpression("\"aaa\\n\""));
- }
-
- /**
- * Validate parsing of keywords through a primary expression
- */
- @Test
- public void testKeywordPrimaryExpression() {
- Matches(Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.SIGNEDTOK, "signed")),
- primaryExpression("signed"));
- Matches(Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.ALIGNTOK, "align")),
- primaryExpression("align"));
- }
-
- /**
- * Validate parsing of identifiers through a primary expression
- */
- @Test
- public void testIdentifierPrimaryExpression() {
- Matches(Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "x")),
- primaryExpression("x"));
- Matches(Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "_123")),
- primaryExpression("_123"));
- }
-
- /**
- * Validate that parsing of an empty unary expression is invalid.
- */
- @Test
- public void testUnaryExpression() {
- CommonTree tree_empty = unaryExpression("");
- assertEquals(null, tree_empty);
- }
-
- /**
- * Validate parsing primary expression through an unary expression
- */
- @Test
- public void testSimpleUnaryExpression() {
- Matches(Node(CTFParser.UNARY_EXPRESSION_DEC,
- Node(CTFParser.DECIMAL_LITERAL, "123")),
- unaryExpression("123"));
-
- Matches(Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "x")),
- unaryExpression("x"));
- }
-
- /**
- * Validate parsing array through an unary expression
- */
- @Test
- public void testArrayUnaryExpression() {
- Matches(List(Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "x")),
- Node(CTFParser.OPENBRAC),
- Node(CTFParser.UNARY_EXPRESSION_DEC,
- Node(CTFParser.DECIMAL_LITERAL, "1"))),
- unaryExpression("x[1]"));
-
- Matches(List(Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "x")),
- Node(CTFParser.OPENBRAC),
- Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "n"))),
- unaryExpression("x[n]"));
-
- Matches(List(Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "x")),
- Node(CTFParser.OPENBRAC),
- Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "n")),
- Node(CTFParser.OPENBRAC),
- Node(CTFParser.UNARY_EXPRESSION_DEC,
- Node(CTFParser.DECIMAL_LITERAL, "1"))),
- unaryExpression("x[n][1]"));
-
- Matches(List(Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "x")),
- Node(CTFParser.OPENBRAC),
- Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "n")),
- Node(CTFParser.OPENBRAC),
- Node(CTFParser.UNARY_EXPRESSION_DEC,
- Node(CTFParser.DECIMAL_LITERAL, "1"),
- Node(CTFParser.SIGN, "+"))),
- unaryExpression("x[n][+1]"));
- }
-
- /**
- * Validate parsing array with keywords through an unary expression
- */
- @Test
- public void testSpecialArrayUnaryExpression() {
- // Added for CTF-v1.8
- Matches(List(Node(CTFParser.TRACE),
- Node(CTFParser.OPENBRAC),
- Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "n"))),
- unaryExpression("trace[n]"));
-
- Matches(List(Node(CTFParser.CLOCK),
- Node(CTFParser.OPENBRAC),
- Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "n")),
- Node(CTFParser.OPENBRAC),
- Node(CTFParser.UNARY_EXPRESSION_DEC,
- Node(CTFParser.DECIMAL_LITERAL, "1"))),
- unaryExpression("clock[n][1]"));
- }
-
- /**
- * Validate parsing member expression through an unary expression
- */
- @Test
- public void testMemberUnaryExpression() {
- Matches(List(Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "x")),
- Node(CTFParser.DOT,
- Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "y")))),
- unaryExpression("x.y"));
-
- Matches(List(Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "x")),
- Node(CTFParser.DOT,
- Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "y"))),
- Node(CTFParser.DOT,
- Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "z")))),
- unaryExpression("x.y.z"));
- }
-
- /**
- * Validate parsing pointer expression through an unary expression
- */
- @Test
- public void testPointerUnaryExpression() {
- Matches(List(Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "x")),
- Node(CTFParser.ARROW,
- Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "y")))),
- unaryExpression("x->y"));
-
- Matches(List(Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "x")),
- Node(CTFParser.ARROW,
- Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "y"))),
- Node(CTFParser.ARROW,
- Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "z")))),
- unaryExpression("x->y->z"));
- }
-
- /**
- * Validate complex expressions through an unary expression
- */
- @Test
- public void testMixedUnaryExpression() {
- Matches(List(Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "x")),
- Node(CTFParser.OPENBRAC),
- Node(CTFParser.UNARY_EXPRESSION_DEC,
- Node(CTFParser.DECIMAL_LITERAL, "2")),
- Node(CTFParser.ARROW,
- Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "y"))),
- Node(CTFParser.DOT,
- Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "z"))),
- Node(CTFParser.OPENBRAC),
- Node(CTFParser.UNARY_EXPRESSION_DEC,
- Node(CTFParser.DECIMAL_LITERAL, "1"))),
- unaryExpression("x[2]->y.z[1]"));
- }
-
- /**
- * Validate that parsing of an empty declaration is invalid.
- */
- @Test
- public void testDeclaration() {
- CommonTree tree_empty = declaration("");
- assertEquals(null, tree_empty);
- }
-
- /**
- * Validate parsing of integer declaration
- */
- @Test
- public void testIntegerTypeAliasDeclaration() {
- // TODO: replace the "all" match with a better tree matcher.
- Matches(All(),
- declaration("typealias integer { } := int;"));
- Matches(All(),
- declaration("typealias integer { signed=true; } := int;"));
- }
-
- /**
- * Validate parsing of floating declaration
- */
- @Test
- public void testFloatingTypeAliasDeclaration() {
- // TODO: replace the "all" match with a better tree matcher.
- Matches(All(),
- declaration("typealias floating_point { } := float;"));
- Matches(All(),
- declaration("typealias floating_point { align = 32; } := float;"));
- }
-
- /**
- * Validate parsing of typedef declaration
- */
- @Ignore("This need a fix to the grammar to support a dummy initial scope. ")
- @Test
- public void testTypedefDeclaration() {
- // TODO: replace the "all" match with a better tree matcher.
- Matches(All(),
- declaration("typedef dummy int;"));
- Matches(All(),
- declaration("typedef integer { } int;"));
- }
-
- /**
- * Validate parsing of an enum declaration
- */
- @Test
- public void testEnumDeclaration() {
- Matches(Node(CTFParser.DECLARATION,
- Node(CTFParser.TYPE_SPECIFIER_LIST,
- Node(CTFParser.ENUM,
- Node(CTFParser.ENUM_NAME,
- Node(CTFParser.IDENTIFIER, "name")),
- Node(CTFParser.ENUM_BODY,
- Node(CTFParser.ENUM_ENUMERATOR,
- Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "A"))))))),
- declaration("enum name { A };"));
-
- Matches(Node(CTFParser.DECLARATION,
- Node(CTFParser.TYPE_SPECIFIER_LIST,
- Node(CTFParser.ENUM,
- Node(CTFParser.ENUM_NAME, All()),
- Node(CTFParser.ENUM_CONTAINER_TYPE,
- Node(CTFParser.TYPE_SPECIFIER_LIST,
- Node(CTFParser.INTTOK))),
- Node(CTFParser.ENUM_BODY, All())))),
- declaration("enum name : int { A };"));
-
- Matches(Node(CTFParser.DECLARATION,
- Node(CTFParser.TYPE_SPECIFIER_LIST,
- Node(CTFParser.ENUM,
- Node(CTFParser.ENUM_BODY, All())))),
- declaration("enum { A };"));
-
- Matches(Node(CTFParser.DECLARATION,
- Node(CTFParser.TYPE_SPECIFIER_LIST,
- Node(CTFParser.ENUM,
- Node(CTFParser.ENUM_CONTAINER_TYPE,
- Node(CTFParser.TYPE_SPECIFIER_LIST,
- Node(CTFParser.INTTOK))),
- Node(CTFParser.ENUM_BODY, All())))),
- declaration("enum : int { A };"));
- }
-
- /**
- * Validate parsing of an enumerator
- */
- @Ignore("The grammar needs to be fixed.")
- @Test
- public void testDeclaratorOfEnumDeclaration() {
- /* TODO: This test crash the parser. */
- Matches(All(),
- declaration("enum { };"));
-
- Matches(Node(CTFParser.DECLARATION,
- Node(CTFParser.TYPE_SPECIFIER_LIST,
- Node(CTFParser.ENUM,
- Node(CTFParser.ENUM_BODY,
- Node(CTFParser.ENUM_ENUMERATOR,
- Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "A"))),
- Node(CTFParser.ENUM_ENUMERATOR,
- Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "B")),
- Node(CTFParser.ENUM_VALUE,
- Node(CTFParser.UNARY_EXPRESSION_DEC,
- Node(CTFParser.DECIMAL_LITERAL, "2")))),
- Node(CTFParser.ENUM_ENUMERATOR,
- Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "C")),
- Node(CTFParser.ENUM_VALUE_RANGE,
- Node(CTFParser.UNARY_EXPRESSION_DEC,
- Node(CTFParser.DECIMAL_LITERAL, "3")),
- Node(CTFParser.UNARY_EXPRESSION_DEC,
- Node(CTFParser.DECIMAL_LITERAL, "5")))))))),
- declaration("enum { A, B=2, C=3...5 };"));
-
- Matches(Node(CTFParser.DECLARATION,
- Node(CTFParser.TYPE_SPECIFIER_LIST,
- Node(CTFParser.ENUM,
- Node(CTFParser.ENUM_BODY,
- Node(CTFParser.ENUM_ENUMERATOR,
- Node(CTFParser.UNARY_EXPRESSION_STRING_QUOTES,
- Node(CTFParser.STRING_LITERAL, "\"A\""))),
- Node(CTFParser.ENUM_ENUMERATOR,
- Node(CTFParser.UNARY_EXPRESSION_STRING_QUOTES,
- Node(CTFParser.STRING_LITERAL, "\"B\"")),
- All()))))),
- declaration("enum { \"A\", \"B\"=2 };"));
- }
-
- /**
- * Validate parsing of empty declaration
- */
- @Ignore("The grammar need to be fixed to support empty ctf-body.")
- @Test
- public void testEmptyDeclaration() {
- /* TODO: An exception is throw when building an common tree without
- * assignments in the ctf-body.
- */
- Matches(All(),
- declaration("env { };"));
- Matches(All(),
- declaration("trace { };"));
- Matches(All(),
- declaration("stream { };"));
- Matches(All(),
- declaration("event { };"));
- }
-
- /**
- * Validate parsing of an environment declaration
- */
- @Test
- public void testEnvDeclaration() {
- Matches(Node(CTFParser.ENV,
- Node(CTFParser.CTF_EXPRESSION_VAL,
- Node(CTFParser.CTF_LEFT,
- Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "pid"))),
- Node(CTFParser.CTF_RIGHT,
- Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "value"))))),
- declaration("env { pid = value; };"));
-
- Matches(Node(CTFParser.ENV,
- Node(CTFParser.CTF_EXPRESSION_VAL, All(), All()),
- Node(CTFParser.CTF_EXPRESSION_VAL, All(), All()),
- Node(CTFParser.CTF_EXPRESSION_VAL, All(), All())),
- declaration("env { pid = value; proc_name = \"name\"; x = y;};"));
- }
-
- /**
- * Validate parsing of a trace declaration
- */
- @Ignore("The grammar need to be fixed.")
- @Test
- public void testTraceDeclaration() {
- Matches(Node(CTFParser.TRACE,
- Node(CTFParser.CTF_EXPRESSION_VAL,
- Node(CTFParser.CTF_LEFT,
- Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "major"))),
- Node(CTFParser.CTF_RIGHT,
- Node(CTFParser.UNARY_EXPRESSION_DEC,
- Node(CTFParser.DECIMAL_LITERAL, "1"))))),
- declaration("trace { major = 1; };"));
-
- Matches(Node(CTFParser.TRACE,
- Node(CTFParser.CTF_EXPRESSION_TYPE,
- Node(CTFParser.CTF_LEFT,
- Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "packet")),
- Node(CTFParser.DOT,
- Node(CTFParser.UNARY_EXPRESSION_STRING,
- Node(CTFParser.IDENTIFIER, "header")))),
- Node(CTFParser.CTF_RIGHT,
- Node(CTFParser.TYPE_SPECIFIER_LIST,
- Node(CTFParser.STRUCT,
- Node(CTFParser.STRUCT_NAME,
- Node(CTFParser.IDENTIFIER, "dummy"))))))),
- declaration("trace { packet.header := struct dummy; };"));
-
- /* TODO: This test crash the parser. */
- Matches(Node(CTFParser.TRACE,
- All()),
- declaration("trace { typedef x y; };"));
-
- Matches(Node(CTFParser.TRACE,
- Node(CTFParser.CTF_EXPRESSION_VAL, All(), All()),
- Node(CTFParser.CTF_EXPRESSION_VAL, All(), All()),
- Node(CTFParser.CTF_EXPRESSION_TYPE, All(), All())),
- declaration("trace { major = 1; minor = 1;"
- + "packet.header := struct dummy; };"));
- }
-
-}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Ericsson
+ *
+ * All rights reserved. This program and the accompanying materials are
+ * made available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Etienne Bergeron - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.parser.tests;
+
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+
+/**
+ * Master test suite for CTF parser.
+ */
+@RunWith(Suite.class)
+@Suite.SuiteClasses({
+ CtfLexerTest.class,
+ CtfParserTest.class
+})
+
+public class AllCtfParserTests {
+
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013, 2014 Etienne Bergeron
+ *
+ * All rights reserved. This program and the accompanying materials are
+ * made available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Etienne Bergeron - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.parser.tests;
+
+import static org.junit.Assert.fail;
+
+import java.util.LinkedList;
+import java.util.List;
+
+import org.antlr.runtime.ANTLRStringStream;
+import org.antlr.runtime.CharStream;
+import org.antlr.runtime.Token;
+import org.eclipse.tracecompass.ctf.parser.CTFLexer;
+import org.junit.Ignore;
+import org.junit.Test;
+
+/**
+ * This test validates the CTF-Lexer implementation.
+ *
+ * The test splits a string into tokens with the compiled lexer and
+ * validates the sequences of tokens produced by comparing their type
+ * and content.
+ *
+ * @author Etienne Bergeron
+ */
+public class CtfLexerTest {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ private final List<Token> tokens = new LinkedList<>();
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ private void tokenize(String content) {
+ CharStream cs = new ANTLRStringStream(content);
+ CTFLexer lexer = new CTFLexer(cs);
+
+ tokens.clear();
+ for (;;) {
+ Token token = lexer.nextToken();
+ if (token == Token.EOF_TOKEN) {
+ return;
+ }
+ tokens.add(token);
+ }
+ }
+
+ private void checkToken(int type, String content) {
+ Token token = tokens.remove(0);
+ if (token.getType() != type) {
+ fail("Invalid type [value " + token.getType()
+ + " but expect " + type + "]."
+ + " Fail to tokenize:" + content);
+ } else if (token.getText().compareTo(content) != 0) {
+ fail("Invalid content [value " + token.getText()
+ + " but expect " + content + "].");
+ }
+ }
+
+ private void checkSingle(int type, String content) {
+ tokenize(content);
+ checkToken(type, content);
+ }
+
+ // ------------------------------------------------------------------------
+ // Test cases
+ // ------------------------------------------------------------------------
+
+ /**
+ * Validate the parsing of keywords
+ */
+ @Test
+ public void testKeywords() {
+ checkSingle(CTFLexer.ALIGNTOK, "align");
+ checkSingle(CTFLexer.CONSTTOK, "const");
+ checkSingle(CTFLexer.CHARTOK, "char");
+ checkSingle(CTFLexer.DOUBLETOK, "double");
+ checkSingle(CTFLexer.ENUMTOK, "enum");
+ checkSingle(CTFLexer.EVENTTOK, "event");
+ checkSingle(CTFLexer.FLOATINGPOINTTOK, "floating_point");
+ checkSingle(CTFLexer.FLOATTOK, "float");
+ checkSingle(CTFLexer.INTEGERTOK, "integer");
+ checkSingle(CTFLexer.INTTOK, "int");
+ checkSingle(CTFLexer.LONGTOK, "long");
+ checkSingle(CTFLexer.SHORTTOK, "short");
+ checkSingle(CTFLexer.SIGNEDTOK, "signed");
+ checkSingle(CTFLexer.STREAMTOK, "stream");
+ checkSingle(CTFLexer.STRINGTOK, "string");
+ checkSingle(CTFLexer.STRUCTTOK, "struct");
+ checkSingle(CTFLexer.TRACETOK, "trace");
+ checkSingle(CTFLexer.TYPEALIASTOK, "typealias");
+ checkSingle(CTFLexer.TYPEDEFTOK, "typedef");
+ checkSingle(CTFLexer.UNSIGNEDTOK, "unsigned");
+ checkSingle(CTFLexer.VARIANTTOK, "variant");
+ checkSingle(CTFLexer.VOIDTOK, "void");
+ checkSingle(CTFLexer.BOOLTOK, "_Bool");
+ checkSingle(CTFLexer.COMPLEXTOK, "_Complex");
+ checkSingle(CTFLexer.IMAGINARYTOK, "_Imaginary");
+ checkSingle(CTFLexer.ENVTOK, "env");
+ checkSingle(CTFLexer.CLOCKTOK, "clock");
+ checkSingle(CTFLexer.CALLSITETOK, "callsite");
+ checkSingle(CTFLexer.NANNUMBERTOK, "NaN");
+ checkSingle(CTFLexer.INFINITYTOK, "+inf");
+ checkSingle(CTFLexer.NINFINITYTOK, "-inf");
+ }
+
+ /**
+ * Validate the parsing of symbols
+ */
+ @Test
+ public void testSymbols() {
+ tokenize(" , : ... ");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.SEPARATOR, ",");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.COLON, ":");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.ELIPSES, "...");
+ checkToken(CTFLexer.WS, " ");
+
+ tokenize(" = := = ");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.ASSIGNMENT, "=");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.TYPE_ASSIGNMENT, ":=");
+ checkToken(CTFLexer.WS, " ");
+
+ tokenize(" <<>> ");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.LT, "<");
+ checkToken(CTFLexer.LT, "<");
+ checkToken(CTFLexer.GT, ">");
+ checkToken(CTFLexer.GT, ">");
+ checkToken(CTFLexer.WS, " ");
+
+ tokenize(" ({[]}) ");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.LPAREN, "(");
+ checkToken(CTFLexer.LCURL, "{");
+ checkToken(CTFLexer.OPENBRAC, "[");
+ checkToken(CTFLexer.CLOSEBRAC, "]");
+ checkToken(CTFLexer.RCURL, "}");
+ checkToken(CTFLexer.RPAREN, ")");
+ checkToken(CTFLexer.WS, " ");
+
+ tokenize(";;");
+ checkToken(CTFLexer.TERM, ";");
+ checkToken(CTFLexer.TERM, ";");
+
+ tokenize(" ++ -- ");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.SIGN, "+");
+ checkToken(CTFLexer.SIGN, "+");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.SIGN, "-");
+ checkToken(CTFLexer.SIGN, "-");
+ checkToken(CTFLexer.WS, " ");
+
+ tokenize("-> .*.");
+ checkToken(CTFLexer.ARROW, "->");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.DOT, ".");
+ checkToken(CTFLexer.POINTER, "*");
+ checkToken(CTFLexer.DOT, ".");
+ }
+
+ /**
+ * Validate the parsing of literals
+ */
+ @Test
+ public void testLiterals() {
+ tokenize("01 02 010");
+ checkToken(CTFLexer.OCTAL_LITERAL, "01");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.OCTAL_LITERAL, "02");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.OCTAL_LITERAL, "010");
+
+ tokenize("1 2 10 1024 ");
+ checkToken(CTFLexer.DECIMAL_LITERAL, "1");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.DECIMAL_LITERAL, "2");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.DECIMAL_LITERAL, "10");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.DECIMAL_LITERAL, "1024");
+ checkToken(CTFLexer.WS, " ");
+
+ tokenize("0x01 0x02 0x0F0");
+ checkToken(CTFLexer.HEX_LITERAL, "0x01");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.HEX_LITERAL, "0x02");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.HEX_LITERAL, "0x0F0");
+ }
+
+ /**
+ * Validate the parsing of literals with hexa prefix
+ */
+ @Test
+ public void testLiteralPrefixes() {
+ checkSingle(CTFLexer.HEX_LITERAL, "0x1");
+ checkSingle(CTFLexer.HEX_LITERAL, "0X1");
+ }
+
+ /**
+ * Validate the parsing of literals with type suffix
+ */
+ @Test
+ public void testLiteralSuffixes() {
+ checkSingle(CTFLexer.DECIMAL_LITERAL, "0l");
+ checkSingle(CTFLexer.DECIMAL_LITERAL, "0L");
+ checkSingle(CTFLexer.DECIMAL_LITERAL, "0ll");
+ checkSingle(CTFLexer.DECIMAL_LITERAL, "0LL");
+ checkSingle(CTFLexer.DECIMAL_LITERAL, "0ul");
+ checkSingle(CTFLexer.DECIMAL_LITERAL, "0uL");
+ checkSingle(CTFLexer.DECIMAL_LITERAL, "0ull");
+ checkSingle(CTFLexer.DECIMAL_LITERAL, "0uLL");
+ checkSingle(CTFLexer.DECIMAL_LITERAL, "0Ul");
+ checkSingle(CTFLexer.DECIMAL_LITERAL, "0UL");
+ checkSingle(CTFLexer.DECIMAL_LITERAL, "0Ull");
+ checkSingle(CTFLexer.DECIMAL_LITERAL, "0ULL");
+ }
+
+ /**
+ * Validate the accepted characters in literals.
+ */
+ @Test
+ public void testLiteralDigits() {
+ checkSingle(CTFLexer.OCTAL_LITERAL, "001234567");
+
+ checkSingle(CTFLexer.DECIMAL_LITERAL, "123456");
+ checkSingle(CTFLexer.DECIMAL_LITERAL, "987654");
+
+ checkSingle(CTFLexer.HEX_LITERAL, "0x012345");
+ checkSingle(CTFLexer.HEX_LITERAL, "0x678990");
+ checkSingle(CTFLexer.HEX_LITERAL, "0xABCDEF");
+ checkSingle(CTFLexer.HEX_LITERAL, "0xabcdef");
+ }
+
+ /**
+ * Validate zero literal to be the right token.
+ */
+ @Test
+ public void testLiteralZero() {
+ checkSingle(CTFLexer.OCTAL_LITERAL, "00");
+ checkSingle(CTFLexer.DECIMAL_LITERAL, "0");
+ checkSingle(CTFLexer.HEX_LITERAL, "0x0");
+ }
+
+ /**
+ * Validate character literals
+ */
+ @Test
+ public void testCharLiteral() {
+ checkSingle(CTFLexer.CHARACTER_LITERAL, "'x'");
+ checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\''");
+ checkSingle(CTFLexer.CHARACTER_LITERAL, "' '");
+ checkSingle(CTFLexer.CHARACTER_LITERAL, "L'1'");
+ }
+
+ /**
+ * Validate escaped character literals
+ */
+ @Test
+ public void testEscapeCharLiteral() {
+ checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\a'");
+ checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\b'");
+ checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\f'");
+ checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\n'");
+ checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\r'");
+ checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\t'");
+ checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\v'");
+ checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\''");
+ checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\\"'");
+ checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\\\'");
+
+ checkSingle(CTFLexer.CHARACTER_LITERAL, "'\001'");
+ checkSingle(CTFLexer.CHARACTER_LITERAL, "'\01'");
+ checkSingle(CTFLexer.CHARACTER_LITERAL, "'\1'");
+
+ checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\x1A'");
+ checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\x1a'");
+ checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\xa'");
+ checkSingle(CTFLexer.CHARACTER_LITERAL, "'\\x0'");
+
+ checkSingle(CTFLexer.CHARACTER_LITERAL, "'\uABCD'");
+ checkSingle(CTFLexer.CHARACTER_LITERAL, "'\u0123'");
+ checkSingle(CTFLexer.CHARACTER_LITERAL, "'\u012345678'");
+ checkSingle(CTFLexer.CHARACTER_LITERAL, "'\uFEDCBA987'");
+ }
+
+ /**
+ * Validate string literals
+ */
+ @Test
+ public void testStringLiteral() {
+ checkSingle(CTFLexer.STRING_LITERAL, "\"\"");
+ checkSingle(CTFLexer.STRING_LITERAL, "\"x\"");
+ checkSingle(CTFLexer.STRING_LITERAL, "\"\\\"\"");
+ checkSingle(CTFLexer.STRING_LITERAL, "\" \"");
+ checkSingle(CTFLexer.STRING_LITERAL, "L\"1\"");
+
+ checkSingle(CTFLexer.STRING_LITERAL, "\"This is \\n a multiline\\r\\n\"");
+ checkSingle(CTFLexer.STRING_LITERAL, "L\"This is \\n a multiline\\r\\n\"");
+ }
+
+ /**
+ * Validate string literals with escape sequence
+ */
+ @Test
+ public void testEscapeStringLiteral() {
+ checkSingle(CTFLexer.STRING_LITERAL, "\"\\a\"");
+ checkSingle(CTFLexer.STRING_LITERAL, "\"\\b\"");
+ checkSingle(CTFLexer.STRING_LITERAL, "\"\\f\"");
+ checkSingle(CTFLexer.STRING_LITERAL, "\"\\n\"");
+ checkSingle(CTFLexer.STRING_LITERAL, "\"\\r\"");
+ checkSingle(CTFLexer.STRING_LITERAL, "\"\\t\"");
+ checkSingle(CTFLexer.STRING_LITERAL, "\"\\v\"");
+ checkSingle(CTFLexer.STRING_LITERAL, "\"\\'\"");
+ checkSingle(CTFLexer.STRING_LITERAL, "\"\\\"\"");
+ checkSingle(CTFLexer.STRING_LITERAL, "\"\\\\\"");
+
+ checkSingle(CTFLexer.STRING_LITERAL, "\"\001\"");
+ checkSingle(CTFLexer.STRING_LITERAL, "\"\01\"");
+ checkSingle(CTFLexer.STRING_LITERAL, "\"\1\"");
+
+ checkSingle(CTFLexer.STRING_LITERAL, "\"\\x1A\"");
+ checkSingle(CTFLexer.STRING_LITERAL, "\"\\x1a\"");
+ checkSingle(CTFLexer.STRING_LITERAL, "\"\\xa\"");
+ checkSingle(CTFLexer.STRING_LITERAL, "\"\\x0\"");
+
+ checkSingle(CTFLexer.STRING_LITERAL, "\"\uABCD\"");
+ checkSingle(CTFLexer.STRING_LITERAL, "\"\u0123\"");
+ checkSingle(CTFLexer.STRING_LITERAL, "\"\u012345678\"");
+ checkSingle(CTFLexer.STRING_LITERAL, "\"\uFEDCBA987\"");
+ }
+
+ /**
+ * Validate spaces parsing
+ */
+ @Test
+ public void testWhitespaces() {
+ tokenize(" \r\t\n\u000C ");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.WS, "\r");
+ checkToken(CTFLexer.WS, "\t");
+ checkToken(CTFLexer.WS, "\n");
+ checkToken(CTFLexer.WS, "\u000C");
+ checkToken(CTFLexer.WS, " ");
+ }
+
+ /**
+ * Validate comments parsing
+ */
+ @Test
+ public void testComment() {
+ tokenize(" /* test */ ");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.COMMENT, "/* test */");
+ checkToken(CTFLexer.WS, " ");
+ }
+
+ /**
+ * Validate complex nested comments parsing
+ */
+ @Test
+ public void testNestedComment() {
+ tokenize(" /* /* */ ");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.COMMENT, "/* /* */");
+ checkToken(CTFLexer.WS, " ");
+
+ tokenize(" /* /* * ** / */ ");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.COMMENT, "/* /* * ** / */");
+ checkToken(CTFLexer.WS, " ");
+ }
+
+ /**
+ * Validate multi-lines comments
+ */
+ @Test
+ public void testMultiLineComment() {
+ tokenize(" /*\ntest\n*/ ");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.COMMENT, "/*\ntest\n*/");
+ checkToken(CTFLexer.WS, " ");
+ }
+
+ /**
+ * Validate single line comments
+ */
+ @Test
+ public void testLineComment() {
+ tokenize(" // asdad\r\n ");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.LINE_COMMENT, "// asdad\r\n");
+ checkToken(CTFLexer.WS, " ");
+ }
+
+ /**
+ * Validate incomplete comments parsing
+ */
+ @Ignore("Lexer must be fixed first")
+ @Test
+ public void testLineCommentWithEOF() {
+ tokenize("//");
+ checkToken(CTFLexer.LINE_COMMENT, "//");
+ }
+
+ /**
+ * Validate parsing of mixed kind of comments
+ */
+ @Test
+ public void testMixedComment() {
+ tokenize(" // /*\n");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.LINE_COMMENT, "// /*\n");
+
+ tokenize(" /*\n//\n*/ ");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.COMMENT, "/*\n//\n*/");
+ checkToken(CTFLexer.WS, " ");
+ }
+
+ /**
+ * Validate parsing identifiers
+ */
+ @Test
+ public void testIdentifier() {
+ tokenize("_ a a1 B ");
+ checkToken(CTFLexer.IDENTIFIER, "_");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.IDENTIFIER, "a");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.IDENTIFIER, "a1");
+ checkToken(CTFLexer.WS, " ");
+ checkToken(CTFLexer.IDENTIFIER, "B");
+ checkToken(CTFLexer.WS, " ");
+ }
+
+ /**
+ * Validate accepted characters within an identifier
+ */
+ @Test
+ public void testIdentifierLetters() {
+ checkSingle(CTFLexer.IDENTIFIER, "ABCDEFGHI");
+ checkSingle(CTFLexer.IDENTIFIER, "JKLMNOPQR");
+ checkSingle(CTFLexer.IDENTIFIER, "STUVWXYZ");
+ checkSingle(CTFLexer.IDENTIFIER, "abcdefghi");
+ checkSingle(CTFLexer.IDENTIFIER, "jklmnopqr");
+ checkSingle(CTFLexer.IDENTIFIER, "stuvwxyz");
+ checkSingle(CTFLexer.IDENTIFIER, "_0123456789");
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2013 Etienne Bergeron
+ *
+ * All rights reserved. This program and the accompanying materials are
+ * made available under the terms of the Eclipse Public License v1.0 which
+ * accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Etienne Bergeron - Initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.tracecompass.ctf.parser.tests;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import org.antlr.runtime.ANTLRStringStream;
+import org.antlr.runtime.CharStream;
+import org.antlr.runtime.CommonTokenStream;
+import org.antlr.runtime.RecognitionException;
+import org.antlr.runtime.tree.CommonTree;
+import org.eclipse.tracecompass.ctf.parser.CTFLexer;
+import org.eclipse.tracecompass.ctf.parser.CTFParser;
+import org.junit.Ignore;
+import org.junit.Test;
+
+/**
+ * This test validates the CTF-Parser implementation.
+ *
+ * The goal of these tests is to validate syntactic rules and not the
+ * CTF semantic. Each test parses a string with a given rule of the
+ * compiled parser and validates the resulting tree by using match rules.
+ *
+ * @author Etienne Bergeron
+ */
+public class CtfParserTest {
+
+ // ------------------------------------------------------------------------
+ // Attributes
+ // ------------------------------------------------------------------------
+
+ private CTFParser parser;
+
+ // ------------------------------------------------------------------------
+ // Matches - Helper class and functions to match a parsed tree.
+ // ------------------------------------------------------------------------
+
+ private class TreeMatcher {
+ int fType;
+ String fText;
+ TreeMatcher[] fChild;
+
+ TreeMatcher(int type, String text, TreeMatcher child[]) {
+ fType = type;
+ fText = text;
+ fChild = child;
+ }
+
+ void matches(CommonTree tree) {
+ if (fType == -1) {
+ return;
+ }
+ if (tree.getType() != fType) {
+ fail("Type mismatch!" +
+ " expected:" + fType +
+ " actual:" + tree.getType());
+ }
+
+ if (fText != null) {
+ if (tree.getText().compareTo(fText) != 0) {
+ fail("Text mismatch!" +
+ " expected:" + fText +
+ " actual:" + tree.getText());
+ }
+ }
+
+ if (fChild != null) {
+ int size = fChild.length;
+ if (tree.getChildren() == null) {
+ if (size != 0) {
+ fail("Invalid children!"
+ + "Expect: " + size + "child");
+ }
+ } else {
+ if (tree.getChildren().size() != size) {
+ fail("Invalid number of childs!"
+ + " expected:" + size
+ + " actual:" + tree.getChildren().size());
+ }
+
+ for (int i = 0; i < size; ++i) {
+ fChild[i].matches((CommonTree) tree.getChild(i));
+ }
+ }
+ }
+ }
+ }
+
+ void Matches(TreeMatcher matcher, CommonTree tree) {
+ if (tree == null) {
+ fail("Parsing failed!");
+ }
+ matcher.matches(tree);
+ }
+
+ TreeMatcher All() {
+ return new TreeMatcher(-1, null, null);
+ }
+
+ TreeMatcher Node(int type, TreeMatcher... child) {
+ return new TreeMatcher(type, null, child);
+ }
+
+ TreeMatcher Node(int type, String text, TreeMatcher... child) {
+ return new TreeMatcher(type, text, child);
+ }
+
+ TreeMatcher List(TreeMatcher... child) {
+ return new TreeMatcher(0, null, child);
+ }
+
+ // ------------------------------------------------------------------------
+ // Operations
+ // ------------------------------------------------------------------------
+
+ private void setInput(String content) {
+ CharStream cs = new ANTLRStringStream(content);
+ CTFLexer lexer = new CTFLexer(cs);
+ CommonTokenStream tokens = new CommonTokenStream(lexer);
+ parser = new CTFParser(tokens, false);
+ }
+
+ private CommonTree primaryExpression(String content) {
+ try {
+ setInput(content);
+ return parser.primaryExpression().getTree();
+ } catch (RecognitionException e) {
+ return null;
+ }
+ }
+
+ private CommonTree unaryExpression(String content) {
+ try {
+ setInput(content);
+ return parser.unaryExpression().getTree();
+ } catch (RecognitionException e) {
+ return null;
+ }
+ }
+
+ private CommonTree declaration(String content) {
+ try {
+ setInput(content);
+ return parser.declaration().getTree();
+ } catch (RecognitionException e) {
+ return null;
+ }
+ }
+
+ // ------------------------------------------------------------------------
+ // Test cases
+ // ------------------------------------------------------------------------
+
+
+ /**
+ * Validate that parsing of an empty expression is invalid.
+ */
+ @Test
+ public void testPrimaryExpression() {
+ CommonTree tree_empty = primaryExpression("");
+ assertEquals(null, tree_empty);
+ }
+
+ /**
+ * Validate parsing of literals through a primary expression
+ */
+ @Test
+ public void testIntegerLiteralPrimaryExpression() {
+ Matches(Node(CTFParser.UNARY_EXPRESSION_DEC,
+ Node(CTFParser.DECIMAL_LITERAL, "123")),
+ primaryExpression("123"));
+
+ Matches(Node(CTFParser.UNARY_EXPRESSION_HEX,
+ Node(CTFParser.HEX_LITERAL, "0x123")),
+ primaryExpression("0x123"));
+
+ Matches(Node(CTFParser.UNARY_EXPRESSION_OCT,
+ Node(CTFParser.OCTAL_LITERAL, "0123")),
+ primaryExpression("0123"));
+
+ Matches(Node(CTFParser.UNARY_EXPRESSION_DEC,
+ Node(CTFParser.DECIMAL_LITERAL, "123"),
+ Node(CTFParser.SIGN, "-")),
+ primaryExpression("-123"));
+
+ Matches(Node(CTFParser.UNARY_EXPRESSION_DEC,
+ Node(CTFParser.DECIMAL_LITERAL, "123"),
+ Node(CTFParser.SIGN, "-")),
+ primaryExpression(" - 123"));
+
+ Matches(Node(CTFParser.UNARY_EXPRESSION_DEC,
+ Node(CTFParser.DECIMAL_LITERAL, "123"),
+ Node(CTFParser.SIGN, "-"),
+ Node(CTFParser.SIGN, "-"),
+ Node(CTFParser.SIGN, "+")),
+ primaryExpression(" - - + 123"));
+
+ Matches(Node(CTFParser.UNARY_EXPRESSION_HEX,
+ Node(CTFParser.HEX_LITERAL, "0x123"),
+ Node(CTFParser.SIGN, "+"),
+ Node(CTFParser.SIGN, "-")),
+ primaryExpression("+ - 0x123"));
+
+ Matches(Node(CTFParser.UNARY_EXPRESSION_OCT,
+ Node(CTFParser.OCTAL_LITERAL, "0123"),
+ Node(CTFParser.SIGN, "+"),
+ Node(CTFParser.SIGN, "-")),
+ primaryExpression("+ - 0123"));
+ }
+
+ /**
+ * Validate parsing of a character literals through a primary expression
+ */
+ @Test
+ public void testCharacterLiteralPrimaryExpression() {
+ Matches(Node(CTFParser.CHARACTER_LITERAL, "'a'"),
+ primaryExpression("'a'"));
+
+ Matches(Node(CTFParser.CHARACTER_LITERAL, "'\\n'"),
+ primaryExpression("'\\n'"));
+ }
+
+ /**
+ * Validate parsing of a string literals through a primary expression
+ */
+ @Test
+ public void testStringLiteralPrimaryExpression() {
+ Matches(Node(CTFParser.UNARY_EXPRESSION_STRING_QUOTES,
+ Node(CTFParser.STRING_LITERAL, "\"aaa\"")),
+ primaryExpression("\"aaa\""));
+
+ Matches(Node(CTFParser.UNARY_EXPRESSION_STRING_QUOTES,
+ Node(CTFParser.STRING_LITERAL, "L\"aaa\"")),
+ primaryExpression("L\"aaa\""));
+
+ Matches(Node(CTFParser.UNARY_EXPRESSION_STRING_QUOTES,
+ Node(CTFParser.STRING_LITERAL, "\"aaa\\n\"")),
+ primaryExpression("\"aaa\\n\""));
+ }
+
+ /**
+ * Validate parsing of keywords through a primary expression
+ */
+ @Test
+ public void testKeywordPrimaryExpression() {
+ Matches(Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.SIGNEDTOK, "signed")),
+ primaryExpression("signed"));
+ Matches(Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.ALIGNTOK, "align")),
+ primaryExpression("align"));
+ }
+
+ /**
+ * Validate parsing of identifiers through a primary expression
+ */
+ @Test
+ public void testIdentifierPrimaryExpression() {
+ Matches(Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "x")),
+ primaryExpression("x"));
+ Matches(Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "_123")),
+ primaryExpression("_123"));
+ }
+
+ /**
+ * Validate that parsing of an empty unary expression is invalid.
+ */
+ @Test
+ public void testUnaryExpression() {
+ CommonTree tree_empty = unaryExpression("");
+ assertEquals(null, tree_empty);
+ }
+
+ /**
+ * Validate parsing primary expression through an unary expression
+ */
+ @Test
+ public void testSimpleUnaryExpression() {
+ Matches(Node(CTFParser.UNARY_EXPRESSION_DEC,
+ Node(CTFParser.DECIMAL_LITERAL, "123")),
+ unaryExpression("123"));
+
+ Matches(Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "x")),
+ unaryExpression("x"));
+ }
+
+ /**
+ * Validate parsing array through an unary expression
+ */
+ @Test
+ public void testArrayUnaryExpression() {
+ Matches(List(Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "x")),
+ Node(CTFParser.OPENBRAC),
+ Node(CTFParser.UNARY_EXPRESSION_DEC,
+ Node(CTFParser.DECIMAL_LITERAL, "1"))),
+ unaryExpression("x[1]"));
+
+ Matches(List(Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "x")),
+ Node(CTFParser.OPENBRAC),
+ Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "n"))),
+ unaryExpression("x[n]"));
+
+ Matches(List(Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "x")),
+ Node(CTFParser.OPENBRAC),
+ Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "n")),
+ Node(CTFParser.OPENBRAC),
+ Node(CTFParser.UNARY_EXPRESSION_DEC,
+ Node(CTFParser.DECIMAL_LITERAL, "1"))),
+ unaryExpression("x[n][1]"));
+
+ Matches(List(Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "x")),
+ Node(CTFParser.OPENBRAC),
+ Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "n")),
+ Node(CTFParser.OPENBRAC),
+ Node(CTFParser.UNARY_EXPRESSION_DEC,
+ Node(CTFParser.DECIMAL_LITERAL, "1"),
+ Node(CTFParser.SIGN, "+"))),
+ unaryExpression("x[n][+1]"));
+ }
+
+ /**
+ * Validate parsing array with keywords through an unary expression
+ */
+ @Test
+ public void testSpecialArrayUnaryExpression() {
+ // Added for CTF-v1.8
+ Matches(List(Node(CTFParser.TRACE),
+ Node(CTFParser.OPENBRAC),
+ Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "n"))),
+ unaryExpression("trace[n]"));
+
+ Matches(List(Node(CTFParser.CLOCK),
+ Node(CTFParser.OPENBRAC),
+ Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "n")),
+ Node(CTFParser.OPENBRAC),
+ Node(CTFParser.UNARY_EXPRESSION_DEC,
+ Node(CTFParser.DECIMAL_LITERAL, "1"))),
+ unaryExpression("clock[n][1]"));
+ }
+
+ /**
+ * Validate parsing member expression through an unary expression
+ */
+ @Test
+ public void testMemberUnaryExpression() {
+ Matches(List(Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "x")),
+ Node(CTFParser.DOT,
+ Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "y")))),
+ unaryExpression("x.y"));
+
+ Matches(List(Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "x")),
+ Node(CTFParser.DOT,
+ Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "y"))),
+ Node(CTFParser.DOT,
+ Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "z")))),
+ unaryExpression("x.y.z"));
+ }
+
+ /**
+ * Validate parsing pointer expression through an unary expression
+ */
+ @Test
+ public void testPointerUnaryExpression() {
+ Matches(List(Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "x")),
+ Node(CTFParser.ARROW,
+ Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "y")))),
+ unaryExpression("x->y"));
+
+ Matches(List(Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "x")),
+ Node(CTFParser.ARROW,
+ Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "y"))),
+ Node(CTFParser.ARROW,
+ Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "z")))),
+ unaryExpression("x->y->z"));
+ }
+
+ /**
+ * Validate complex expressions through an unary expression
+ */
+ @Test
+ public void testMixedUnaryExpression() {
+ Matches(List(Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "x")),
+ Node(CTFParser.OPENBRAC),
+ Node(CTFParser.UNARY_EXPRESSION_DEC,
+ Node(CTFParser.DECIMAL_LITERAL, "2")),
+ Node(CTFParser.ARROW,
+ Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "y"))),
+ Node(CTFParser.DOT,
+ Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "z"))),
+ Node(CTFParser.OPENBRAC),
+ Node(CTFParser.UNARY_EXPRESSION_DEC,
+ Node(CTFParser.DECIMAL_LITERAL, "1"))),
+ unaryExpression("x[2]->y.z[1]"));
+ }
+
+ /**
+ * Validate that parsing of an empty declaration is invalid.
+ */
+ @Test
+ public void testDeclaration() {
+ CommonTree tree_empty = declaration("");
+ assertEquals(null, tree_empty);
+ }
+
+ /**
+ * Validate parsing of integer declaration
+ */
+ @Test
+ public void testIntegerTypeAliasDeclaration() {
+ // TODO: replace the "all" match with a better tree matcher.
+ Matches(All(),
+ declaration("typealias integer { } := int;"));
+ Matches(All(),
+ declaration("typealias integer { signed=true; } := int;"));
+ }
+
+ /**
+ * Validate parsing of floating declaration
+ */
+ @Test
+ public void testFloatingTypeAliasDeclaration() {
+ // TODO: replace the "all" match with a better tree matcher.
+ Matches(All(),
+ declaration("typealias floating_point { } := float;"));
+ Matches(All(),
+ declaration("typealias floating_point { align = 32; } := float;"));
+ }
+
+ /**
+ * Validate parsing of typedef declaration
+ */
+ @Ignore("This need a fix to the grammar to support a dummy initial scope. ")
+ @Test
+ public void testTypedefDeclaration() {
+ // TODO: replace the "all" match with a better tree matcher.
+ Matches(All(),
+ declaration("typedef dummy int;"));
+ Matches(All(),
+ declaration("typedef integer { } int;"));
+ }
+
+ /**
+ * Validate parsing of an enum declaration
+ */
+ @Test
+ public void testEnumDeclaration() {
+ Matches(Node(CTFParser.DECLARATION,
+ Node(CTFParser.TYPE_SPECIFIER_LIST,
+ Node(CTFParser.ENUM,
+ Node(CTFParser.ENUM_NAME,
+ Node(CTFParser.IDENTIFIER, "name")),
+ Node(CTFParser.ENUM_BODY,
+ Node(CTFParser.ENUM_ENUMERATOR,
+ Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "A"))))))),
+ declaration("enum name { A };"));
+
+ Matches(Node(CTFParser.DECLARATION,
+ Node(CTFParser.TYPE_SPECIFIER_LIST,
+ Node(CTFParser.ENUM,
+ Node(CTFParser.ENUM_NAME, All()),
+ Node(CTFParser.ENUM_CONTAINER_TYPE,
+ Node(CTFParser.TYPE_SPECIFIER_LIST,
+ Node(CTFParser.INTTOK))),
+ Node(CTFParser.ENUM_BODY, All())))),
+ declaration("enum name : int { A };"));
+
+ Matches(Node(CTFParser.DECLARATION,
+ Node(CTFParser.TYPE_SPECIFIER_LIST,
+ Node(CTFParser.ENUM,
+ Node(CTFParser.ENUM_BODY, All())))),
+ declaration("enum { A };"));
+
+ Matches(Node(CTFParser.DECLARATION,
+ Node(CTFParser.TYPE_SPECIFIER_LIST,
+ Node(CTFParser.ENUM,
+ Node(CTFParser.ENUM_CONTAINER_TYPE,
+ Node(CTFParser.TYPE_SPECIFIER_LIST,
+ Node(CTFParser.INTTOK))),
+ Node(CTFParser.ENUM_BODY, All())))),
+ declaration("enum : int { A };"));
+ }
+
+ /**
+ * Validate parsing of an enumerator
+ */
+ @Ignore("The grammar needs to be fixed.")
+ @Test
+ public void testDeclaratorOfEnumDeclaration() {
+ /* TODO: This test crash the parser. */
+ Matches(All(),
+ declaration("enum { };"));
+
+ Matches(Node(CTFParser.DECLARATION,
+ Node(CTFParser.TYPE_SPECIFIER_LIST,
+ Node(CTFParser.ENUM,
+ Node(CTFParser.ENUM_BODY,
+ Node(CTFParser.ENUM_ENUMERATOR,
+ Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "A"))),
+ Node(CTFParser.ENUM_ENUMERATOR,
+ Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "B")),
+ Node(CTFParser.ENUM_VALUE,
+ Node(CTFParser.UNARY_EXPRESSION_DEC,
+ Node(CTFParser.DECIMAL_LITERAL, "2")))),
+ Node(CTFParser.ENUM_ENUMERATOR,
+ Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "C")),
+ Node(CTFParser.ENUM_VALUE_RANGE,
+ Node(CTFParser.UNARY_EXPRESSION_DEC,
+ Node(CTFParser.DECIMAL_LITERAL, "3")),
+ Node(CTFParser.UNARY_EXPRESSION_DEC,
+ Node(CTFParser.DECIMAL_LITERAL, "5")))))))),
+ declaration("enum { A, B=2, C=3...5 };"));
+
+ Matches(Node(CTFParser.DECLARATION,
+ Node(CTFParser.TYPE_SPECIFIER_LIST,
+ Node(CTFParser.ENUM,
+ Node(CTFParser.ENUM_BODY,
+ Node(CTFParser.ENUM_ENUMERATOR,
+ Node(CTFParser.UNARY_EXPRESSION_STRING_QUOTES,
+ Node(CTFParser.STRING_LITERAL, "\"A\""))),
+ Node(CTFParser.ENUM_ENUMERATOR,
+ Node(CTFParser.UNARY_EXPRESSION_STRING_QUOTES,
+ Node(CTFParser.STRING_LITERAL, "\"B\"")),
+ All()))))),
+ declaration("enum { \"A\", \"B\"=2 };"));
+ }
+
+ /**
+ * Validate parsing of empty declaration
+ */
+ @Ignore("The grammar need to be fixed to support empty ctf-body.")
+ @Test
+ public void testEmptyDeclaration() {
+ /* TODO: An exception is throw when building an common tree without
+ * assignments in the ctf-body.
+ */
+ Matches(All(),
+ declaration("env { };"));
+ Matches(All(),
+ declaration("trace { };"));
+ Matches(All(),
+ declaration("stream { };"));
+ Matches(All(),
+ declaration("event { };"));
+ }
+
+ /**
+ * Validate parsing of an environment declaration
+ */
+ @Test
+ public void testEnvDeclaration() {
+ Matches(Node(CTFParser.ENV,
+ Node(CTFParser.CTF_EXPRESSION_VAL,
+ Node(CTFParser.CTF_LEFT,
+ Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "pid"))),
+ Node(CTFParser.CTF_RIGHT,
+ Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "value"))))),
+ declaration("env { pid = value; };"));
+
+ Matches(Node(CTFParser.ENV,
+ Node(CTFParser.CTF_EXPRESSION_VAL, All(), All()),
+ Node(CTFParser.CTF_EXPRESSION_VAL, All(), All()),
+ Node(CTFParser.CTF_EXPRESSION_VAL, All(), All())),
+ declaration("env { pid = value; proc_name = \"name\"; x = y;};"));
+ }
+
+ /**
+ * Validate parsing of a trace declaration
+ */
+ @Ignore("The grammar need to be fixed.")
+ @Test
+ public void testTraceDeclaration() {
+ Matches(Node(CTFParser.TRACE,
+ Node(CTFParser.CTF_EXPRESSION_VAL,
+ Node(CTFParser.CTF_LEFT,
+ Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "major"))),
+ Node(CTFParser.CTF_RIGHT,
+ Node(CTFParser.UNARY_EXPRESSION_DEC,
+ Node(CTFParser.DECIMAL_LITERAL, "1"))))),
+ declaration("trace { major = 1; };"));
+
+ Matches(Node(CTFParser.TRACE,
+ Node(CTFParser.CTF_EXPRESSION_TYPE,
+ Node(CTFParser.CTF_LEFT,
+ Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "packet")),
+ Node(CTFParser.DOT,
+ Node(CTFParser.UNARY_EXPRESSION_STRING,
+ Node(CTFParser.IDENTIFIER, "header")))),
+ Node(CTFParser.CTF_RIGHT,
+ Node(CTFParser.TYPE_SPECIFIER_LIST,
+ Node(CTFParser.STRUCT,
+ Node(CTFParser.STRUCT_NAME,
+ Node(CTFParser.IDENTIFIER, "dummy"))))))),
+ declaration("trace { packet.header := struct dummy; };"));
+
+ /* TODO: This test crash the parser. */
+ Matches(Node(CTFParser.TRACE,
+ All()),
+ declaration("trace { typedef x y; };"));
+
+ Matches(Node(CTFParser.TRACE,
+ Node(CTFParser.CTF_EXPRESSION_VAL, All(), All()),
+ Node(CTFParser.CTF_EXPRESSION_VAL, All(), All()),
+ Node(CTFParser.CTF_EXPRESSION_TYPE, All(), All())),
+ declaration("trace { major = 1; minor = 1;"
+ + "packet.header := struct dummy; };"));
+ }
+
+}
Bundle-Localization: plugin
Bundle-SymbolicName: org.eclipse.tracecompass.ctf.parser
Bundle-RequiredExecutionEnvironment: JavaSE-1.7
-Export-Package: org.eclipse.linuxtools.ctf.parser;x-friends:="org.eclipse.tracecompass.ctf.core,org.eclipse.tracecompass.ctf.parser.tests"
+Export-Package: org.eclipse.tracecompass.ctf.parser;x-friends:="org.eclipse.tracecompass.ctf.core,org.eclipse.tracecompass.ctf.parser.tests"
Import-Package: org.antlr.runtime;version="3.2.0",
org.antlr.runtime.tree;version="3.2.0"
+++ /dev/null
-lexer grammar CTFLexer;
-
-options {
- language = Java;
-}
-
-@lexer::header {
- package org.eclipse.linuxtools.ctf.parser;
-}
-
-/*
- * Lexer tokens
- */
-
-/*
- * Keywords
- */
-ALIGNTOK : 'align' ;
-CONSTTOK : 'const' ;
-CHARTOK : 'char' ;
-DOUBLETOK : 'double' ;
-ENUMTOK : 'enum' ;
-EVENTTOK : 'event' ;
-FLOATINGPOINTTOK : 'floating_point' ;
-FLOATTOK : 'float' ;
-INTEGERTOK : 'integer' ;
-INTTOK : 'int' ;
-LONGTOK : 'long' ;
-SHORTTOK : 'short' ;
-SIGNEDTOK : 'signed' ;
-STREAMTOK : 'stream' ;
-STRINGTOK : 'string' ;
-STRUCTTOK : 'struct' ;
-TRACETOK : 'trace' ;
-TYPEALIASTOK : 'typealias' ;
-TYPEDEFTOK : 'typedef' ;
-UNSIGNEDTOK : 'unsigned' ;
-VARIANTTOK : 'variant' ;
-VOIDTOK : 'void' ;
-BOOLTOK : '_Bool' ;
-COMPLEXTOK : '_Complex' ;
-IMAGINARYTOK : '_Imaginary' ;
-ENVTOK : 'env' ;
-CLOCKTOK : 'clock' ;
-/*
- * Callsite tokens (CTF v1.9)
- */
-CALLSITETOK : 'callsite' ;
-
-
-/*
- * These tokens are not part of the CTF standard.
- * There are planned to be in CTF v1.9
- */
-NANNUMBERTOK : 'NaN' ;
-INFINITYTOK : '+inf' ;
-NINFINITYTOK : '-inf' ;
-
-/*
- * Symbols
- */
-SEPARATOR : ',' ;
-COLON : ':' ;
-ELIPSES : '...' ;
-ASSIGNMENT : '=' ;
-TYPE_ASSIGNMENT : ':=' ;
-LT : '<' ;
-GT : '>' ;
-OPENBRAC : '[' ;
-CLOSEBRAC : ']' ;
-LPAREN : '(' ;
-RPAREN : ')' ;
-LCURL : '{' ;
-RCURL : '}' ;
-TERM : ';' ;
-POINTER : '*' ;
-SIGN : '+' | '-' ;
-ARROW : '->' ;
-DOT : '.' ;
-fragment BACKSLASH : '\\' ;
-
-/* Helpers for integer literals */
-fragment DIGIT : '0'..'9' ;
-fragment OCT_DIGIT : '0'..'7' ;
-fragment OCT_PREFIX : '0' ;
-fragment NONZERO_DIGIT : '1'..'9' ;
-fragment HEX_DIGIT : DIGIT | ('a'..'f') | ('A'..'F') ;
-fragment HEX_PREFIX : '0' ('x' | 'X') ;
-
-/*
- * Integer literals
- */
-OCTAL_LITERAL : OCT_PREFIX (OCT_DIGIT)+ INTEGER_TYPES_SUFFIX? ;
-DECIMAL_LITERAL : DIGIT+ INTEGER_TYPES_SUFFIX? ;
-HEX_LITERAL : HEX_PREFIX HEX_DIGIT+ INTEGER_TYPES_SUFFIX? ;
-
-/**
- * Integer suffix for long, long long and unsigned.
- *
- * Matches all possible combination of L, LL and U.
- */
-fragment INTEGER_TYPES_SUFFIX
- : ('l' ('l')? | 'L' ('L')?) // l, ll
- | ('u' | 'U') // u
- | ('u' | 'U') ('l' ('l')? | 'L' ('L')?) // ul, ull
- | ('l' ('l')? | 'L' ('L')?) ('u'| 'U') // lu, llu
- ;
-
-/**
- * Escape sequences
- */
-fragment ESCAPE_SEQUENCE
- : BACKSLASH ('\'' | '"' | '?' | BACKSLASH | 'a' | 'b' | 'f' | 'n' | 'r' | 't' | 'v' )
- | OCTAL_ESCAPE
- | UNICODE_ESCAPE
- | HEXADECIMAL_ESCAPE
- ;
-
-/**
- * Octal escape sequence
- */
-fragment OCTAL_ESCAPE
- : BACKSLASH ('0'..'3') ('0'..'7') ('0'..'7')
- | BACKSLASH ('0'..'7') ('0'..'7')
- | BACKSLASH ('0'..'7')
- ;
-
-/**
- * Hexadecimal escape sequence
- */
-fragment HEXADECIMAL_ESCAPE : BACKSLASH 'x' HEX_DIGIT+ ;
-
-/**
- * Unicode escape sequence
- */
-fragment UNICODE_ESCAPE
- : BACKSLASH 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT
- | BACKSLASH 'U' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT
- ;
-
-
-/* Used in both character and string literal */
-fragment STRINGPREFIX : 'L';
-
-/*
- * Character literal
- */
-CHARACTER_LITERAL : STRINGPREFIX? SINGLEQUOTE CHAR_CONTENT+ SINGLEQUOTE ;
-fragment CHAR_CONTENT : (ESCAPE_SEQUENCE | ~(BACKSLASH | SINGLEQUOTE)) ;
-fragment SINGLEQUOTE : '\'';
-
-/*
- * String literal
- */
-STRING_LITERAL : STRINGPREFIX? DOUBLEQUOTE STRING_CONTENT* DOUBLEQUOTE ;
-fragment STRING_CONTENT : (ESCAPE_SEQUENCE | ~(BACKSLASH | DOUBLEQUOTE)) ;
-fragment DOUBLEQUOTE : '"' ;
-
-/**
- * Whitespaces
- */
-WS : (' ' | '\r' | '\t' | '\u000C' | '\n') { $channel = HIDDEN; } ;
-
-/**
- * Multiline comment
- */
-// About the greedy option: see page 100-101 of The Definitive ANTLR reference
-// COMMENT : '/*' ( options { greedy = false; } : . )* '*/' { $channel = HIDDEN; } ;
-COMMENT : COMMENT_OPEN .* COMMENT_CLOSE { $channel = HIDDEN; } ;
-fragment COMMENT_OPEN : '/*';
-fragment COMMENT_CLOSE : '*/';
-
-/**
- * Single line comment
- */
-LINE_COMMENT : '//' ~('\n')* '\n' { $channel = HIDDEN; } ;
-
-/**
- * Identifiers
- */
-IDENTIFIER : NONDIGIT (NONDIGIT | DIGIT)* ;
-fragment NONDIGIT : ('_') | ('A'..'Z') | ('a'..'z') ;
+++ /dev/null
-parser grammar CTFParser;
-
-options {
- language = Java;
- output = AST;
- ASTLabelType = CommonTree;
- tokenVocab = CTFLexer;
-}
-
-tokens {
- ROOT;
-
- EVENT;
- STREAM;
- TRACE;
- ENV;
- CLOCK;
- CALLSITE;
-
- DECLARATION;
- SV_DECLARATION;
- TYPE_SPECIFIER_LIST;
- TYPE_DECLARATOR_LIST;
- TYPE_DECLARATOR;
-
- STRUCT;
- STRUCT_NAME;
- STRUCT_BODY;
- ALIGN;
-
- CTF_EXPRESSION_TYPE;
- CTF_EXPRESSION_VAL;
- CTF_LEFT;
- CTF_RIGHT;
-
- UNARY_EXPRESSION_STRING;
- UNARY_EXPRESSION_STRING_QUOTES;
- UNARY_EXPRESSION_DEC;
- UNARY_EXPRESSION_HEX;
- UNARY_EXPRESSION_OCT;
- LENGTH;
-
- TYPEDEF;
-
- TYPEALIAS;
- TYPEALIAS_TARGET;
- TYPEALIAS_ALIAS;
-
- INTEGER;
- STRING;
- FLOATING_POINT;
-
- ENUM;
- ENUM_CONTAINER_TYPE;
- ENUM_ENUMERATOR;
- ENUM_NAME;
- ENUM_VALUE;
- ENUM_VALUE_RANGE;
- ENUM_BODY;
-
- VARIANT;
- VARIANT_NAME;
- VARIANT_TAG;
- VARIANT_BODY;
-
- DECLARATOR;
- LENGTH;
-}
-
-/*
- * Scope for the tracking of types.
- * For now we just track the names (it's a simple Set), but
- * later we will have to track the info about the target type.
- */
-scope Symbols {
- Set<String> types;
-}
-
-@header {
- package org.eclipse.linuxtools.ctf.parser;
- import java.util.Set;
- import java.util.HashSet;
-}
-
-@members {
- public CTFParser(TokenStream input, boolean verbose) {
- this(input);
- this.verbose = verbose;
- }
-
- /**
- * This method is overriden to disable automatic error recovery.
- * On a mismatched token, it simply re-throw an exception.
- */
- @Override
- protected Object recoverFromMismatchedToken(IntStream input, int ttype, BitSet follow) throws RecognitionException {
- throw new MismatchedTokenException(ttype, input);
- }
-
- /**
- * Checks if a given name has been defined has a type.
- * From: http://www.antlr.org/grammar/1153358328744/C.g
- *
- * @param name The name to check.
- * @return True if is is a type, false otherwise.
- */
- boolean isTypeName(String name) {
- for (int i = Symbols_stack.size() - 1; i >= 0; i--) {
- Symbols_scope scope = (Symbols_scope) Symbols_stack.get(i);
- if (scope.types.contains(name)) {
- return true;
- }
- }
- return false;
- }
-
- void addTypeName(String name) {
- $Symbols::types.add(name);
- if (verbose) {
- debug_print("New type: " + name);
- }
- }
-
- boolean _inTypedef = false;
-
- void typedefOn() {
- debug_print("typedefOn");
- _inTypedef = true;
- }
-
- void typedefOff() {
- debug_print("typedefOff");
- _inTypedef = false;
- }
-
- boolean inTypedef() {
- return _inTypedef;
- }
-
- boolean _inTypealiasAlias = false;
-
- void typealiasAliasOn() {
- debug_print("typealiasAliasOn");
- _inTypealiasAlias = true;
- }
-
- void typealiasAliasOff() {
- debug_print("typealiasAliasOff");
- _inTypealiasAlias = false;
- }
-
- boolean inTypealiasAlias() {
- return _inTypealiasAlias;
- }
-
- void debug_print(String str) {
- if (verbose) {
- System.out.println(str);
- }
- }
-
- /* Prints rule entry and exit while parsing */
- boolean verbose = false;
-}
-
- /*
- * Override the catch clause to disable automatic error recovery.
- * By default, the catch block of every rule simple rethrows the error.
- */
-@rulecatch {
- catch (RecognitionException e) {
- throw e;
- }
-}
-
-/* The top-level rule. */
-parse
-scope Symbols;
-@init {
- $Symbols::types = new HashSet<String>();
-}
- : declaration+ EOF -> ^(ROOT declaration+)
- ;
-
-numberLiteral
- : SIGN*
- ( HEX_LITERAL -> ^(UNARY_EXPRESSION_HEX HEX_LITERAL SIGN*)
- | DECIMAL_LITERAL -> ^(UNARY_EXPRESSION_DEC DECIMAL_LITERAL SIGN*)
- | OCTAL_LITERAL -> ^(UNARY_EXPRESSION_OCT OCTAL_LITERAL SIGN*)
- )
- ;
-
-primaryExpression
- : (IDENTIFIER) => IDENTIFIER
- -> ^(UNARY_EXPRESSION_STRING IDENTIFIER)
- | (ctfKeyword) => ctfKeyword -> ^(UNARY_EXPRESSION_STRING ctfKeyword)
- | (STRING_LITERAL) => STRING_LITERAL
- -> ^(UNARY_EXPRESSION_STRING_QUOTES STRING_LITERAL)
- /*| (LPAREN unaryExpression RPAREN)*/ // Not supported yet
- | numberLiteral
- | enumConstant
- | CHARACTER_LITERAL
- ;
-
-postfixExpressionSuffix
- : OPENBRAC unaryExpression CLOSEBRAC!
- | (ref=DOT | ref=ARROW) IDENTIFIER
- -> ^($ref ^(UNARY_EXPRESSION_STRING IDENTIFIER))
- ;
-
-postfixExpression
- : primaryExpression postfixExpressionSuffix*
- | ctfSpecifierHead postfixExpressionSuffix+ // added for ctf-v1.8
- ;
-
-unaryExpression
- : postfixExpression
- /* | ((SIGN postfixExpression[true]) | postfixExpression[false]) */
- ;
-
-enumConstant
- : STRING_LITERAL -> ^(UNARY_EXPRESSION_STRING_QUOTES STRING_LITERAL)
- | IDENTIFIER -> ^(UNARY_EXPRESSION_STRING IDENTIFIER)
- | ctfKeyword -> ^(UNARY_EXPRESSION_STRING ctfKeyword)
- ;
-
-// 2.2
-
-declaration
-@after {
- if (inTypedef()) {
- typedefOff();
- }
-}
- : declarationSpecifiers declaratorList? TERM
- // When the declaration is completely parsed and was a typedef,
- // we add the declarators to the symbol table.
- -> {inTypedef()}?
- ^(DECLARATION ^(TYPEDEF declaratorList declarationSpecifiers))
- -> ^(DECLARATION declarationSpecifiers declaratorList?)
- | ctfSpecifier TERM!
- ;
-
-declarationSpecifiers
- : (
- // We don't want to keep the typedef keyword in the specifier list.
- // Instead, we keep track that we encountered a typedef in the declaration.
- storageClassSpecifier
- | typeQualifier
- | typeSpecifier
- )+ -> ^(TYPE_SPECIFIER_LIST typeQualifier* typeSpecifier*)
- ;
-
-declaratorList
- : declarator (SEPARATOR declarator)*
- -> ^(TYPE_DECLARATOR_LIST declarator+)
- ;
-
-abstractDeclaratorList
- : abstractDeclarator (SEPARATOR abstractDeclarator)*
- -> ^(TYPE_DECLARATOR_LIST abstractDeclarator+)
- ;
-
-storageClassSpecifier
- : TYPEDEFTOK { typedefOn(); }
- ;
-
-typeSpecifier
- : FLOATTOK
- | INTTOK
- | LONGTOK
- | SHORTTOK
- | SIGNEDTOK
- | UNSIGNEDTOK
- | CHARTOK
- | DOUBLETOK
- | VOIDTOK
- | BOOLTOK
- | COMPLEXTOK
- | IMAGINARYTOK
- | structSpecifier
- | variantSpecifier
- | enumSpecifier
- | ctfTypeSpecifier
- | { inTypealiasAlias() || isTypeName(input.LT(1).getText()) }? => typedefName
- ;
-
-typeQualifier
- : CONSTTOK
- ;
-
-alignAttribute
- : ALIGNTOK LPAREN unaryExpression RPAREN -> ^(ALIGN unaryExpression)
- ;
-
- // you can have an empty struct but not an empty variant
-structBody
-scope Symbols;
-@init {
- $Symbols::types = new HashSet<String>();
-}
- : LCURL structOrVariantDeclarationList? RCURL
- -> ^(STRUCT_BODY structOrVariantDeclarationList?)
- ;
-
-structSpecifier
- : STRUCTTOK
- (
- // We have an IDENTIFIER after 'struct'
- (
- structName
- (
- alignAttribute
- |
- (
- structBody
- ( /* structBody can return an empty tree, so we need those ? */
- alignAttribute
- |
- /* empty */
- )
- )
- |
- /* empty */
- )
- )
- |
- // We have a body after 'struct'
- (
- structBody
- (
- alignAttribute
- |
- /* empty */
- )
- )
- ) -> ^(STRUCT structName? structBody? alignAttribute?)
- ;
-
-structName
- : IDENTIFIER -> ^(STRUCT_NAME IDENTIFIER)
- ;
-
-structOrVariantDeclarationList
- : structOrVariantDeclaration+
- ;
-
-structOrVariantDeclaration
- :
- (
- (
- declarationSpecifiers
- (
- /* If we met a "typedef" */
- {inTypedef()}? => declaratorList {typedefOff();}
- -> ^(TYPEDEF declaratorList declarationSpecifiers)
- | structOrVariantDeclaratorList
- -> ^(SV_DECLARATION declarationSpecifiers structOrVariantDeclaratorList)
- )
- )
- |
- // Lines 3 and 4
- typealiasDecl -> typealiasDecl
- )
- TERM
- ;
-
-specifierQualifierList
- : (typeQualifier | typeSpecifier)+
- -> ^(TYPE_SPECIFIER_LIST typeQualifier* typeSpecifier*)
- ;
-
-structOrVariantDeclaratorList
- : structOrVariantDeclarator (SEPARATOR structOrVariantDeclarator)*
- -> ^(TYPE_DECLARATOR_LIST structOrVariantDeclarator+)
- ;
-
-structOrVariantDeclarator
- :
- /* Bitfields not supported yet */
- (declarator (COLON numberLiteral)?) -> declarator
- /*| (COLON numberLiteral)*/
- ;
-
-variantSpecifier
- : VARIANTTOK
- (
- (
- variantName
- (
- (
- variantTag
- (
- variantBody
- |
- /* empty */
- )
- )
- |
- variantBody
- )
- )
- | (variantTag variantBody)
- | variantBody
- ) -> ^(VARIANT variantName? variantTag? variantBody?)
- ;
-
-variantName
- : IDENTIFIER -> ^(VARIANT_NAME IDENTIFIER)
- ;
-
-variantBody
-scope Symbols;
-@init {
- $Symbols::types = new HashSet<String>();
-}
- : LCURL structOrVariantDeclarationList RCURL
- -> ^(VARIANT_BODY structOrVariantDeclarationList)
- ;
-
-variantTag
- : LT IDENTIFIER GT -> ^(VARIANT_TAG IDENTIFIER)
- ;
-
-enumSpecifier
- : ENUMTOK
- (
- // Lines 1 to 5, when we have "ENUMTOK IDENTIFIER".
- (
- enumName
- (
- enumContainerType enumBody
- |
- enumBody
- |
- // no enumDeclarator or enumBodym
- )
- )
- |
- // Lines 1, 2, 4, 5, when we have no IDENTIFIER.
- (
- enumContainerType enumBody
- |
- enumBody
- )
- ) -> ^(ENUM enumName? enumContainerType? enumBody?)
- ;
-
-enumName
- : IDENTIFIER -> ^(ENUM_NAME IDENTIFIER)
- ;
-
-enumBody
- : LCURL enumeratorList SEPARATOR? RCURL -> ^(ENUM_BODY enumeratorList)
- ;
-
-enumContainerType
- : COLON declarationSpecifiers -> ^(ENUM_CONTAINER_TYPE declarationSpecifiers)
- ;
-
-enumeratorList
- : enumerator (SEPARATOR enumerator)* -> (^(ENUM_ENUMERATOR enumerator))+
- ;
-
-enumerator
- : enumConstant enumeratorValue?
- ;
-
-enumeratorValue
- : ASSIGNMENT e1=unaryExpression
- ( /* empty */
- -> ^(ENUM_VALUE $e1)
- | ELIPSES e2=unaryExpression
- -> ^(ENUM_VALUE_RANGE $e1 $e2)
- )
- ;
-
-declarator
- : pointer* directDeclarator
- -> ^(TYPE_DECLARATOR pointer* directDeclarator)
- ;
-
-directDeclarator
- : (
- IDENTIFIER
- { if (inTypedef()) addTypeName($IDENTIFIER.text); }
- { debug_print($IDENTIFIER.text); }
- /*| LPAREN declarator RPAREN*/ /* Not supported yet */
- )
- directDeclaratorSuffix*
- ;
-
-directDeclaratorSuffix
- : OPENBRAC directDeclaratorLength CLOSEBRAC
- -> ^(LENGTH directDeclaratorLength)
- ;
-
-directDeclaratorLength
- : unaryExpression
- ;
-
-abstractDeclarator
- : pointer+ directAbstractDeclarator?
- -> ^(TYPE_DECLARATOR pointer+ directAbstractDeclarator?)
- | directAbstractDeclarator
- -> ^(TYPE_DECLARATOR directAbstractDeclarator)
- ;
-
-/**
- * In the CTF grammar, direct-abstract-declarator can be empty (because of
- * identifier-opt). We take care of that by appending a '?' to each use of
- * "abstractDeclaratorList".
- */
-directAbstractDeclarator
- : (
- IDENTIFIER
- | (LPAREN abstractDeclarator RPAREN)
- ) (
- OPENBRAC unaryExpression? CLOSEBRAC
- )?
- ;
-
-pointer
- : POINTER typeQualifierList? -> ^(POINTER typeQualifierList?)
- ;
-
-typeQualifierList
- : typeQualifier+
- ;
-
-typedefName
- : {inTypealiasAlias() || isTypeName(input.LT(1).getText())}? IDENTIFIER { if ((inTypedef() || inTypealiasAlias()) && !isTypeName($IDENTIFIER.text)) { addTypeName($IDENTIFIER.text); } }
- ;
-
-/**
- * What goes in the target part of a typealias.
- *
- * For example, the integer part in:
- * typealias integer {...} := my_new_integer;
- */
-typealiasTarget
- : declarationSpecifiers abstractDeclaratorList?
- ;
-
-/**
- * What goes in the alias part of a typealias.
- *
- * For example, the my_new_integer part in:
- * typealias integer {...} := my_new_integer;
- */
-typealiasAlias
-@init {
- typealiasAliasOn();
-}
-@after {
- typealiasAliasOff();
-}
- : abstractDeclaratorList
- | declarationSpecifiers abstractDeclaratorList?
- ;
-
-typealiasDecl
- : TYPEALIASTOK typealiasTarget TYPE_ASSIGNMENT typealiasAlias
- -> ^(TYPEALIAS
- ^(TYPEALIAS_TARGET typealiasTarget)
- ^(TYPEALIAS_ALIAS typealiasAlias))
- ;
-
-// 2.3 CTF stuff
-
-// TODO: Ajouter ceux qui manquent
-ctfKeyword
- : ALIGNTOK
- | EVENTTOK
- | SIGNEDTOK
- | STRINGTOK
- ;
-
-ctfSpecifier
- // event {...}, stream {...}, trace {...}
- : ctfSpecifierHead ctfBody -> ^(ctfSpecifierHead ctfBody)
- // typealias
- | typealiasDecl -> ^(DECLARATION typealiasDecl)
- ;
-
-ctfSpecifierHead
- : EVENTTOK -> EVENT
- | STREAMTOK -> STREAM
- | TRACETOK -> TRACE
- | ENVTOK -> ENV
- | CLOCKTOK -> CLOCK
- | CALLSITETOK -> CALLSITE
- ;
-
-ctfTypeSpecifier
- /* ctfBody can return an empty tree if the body is empty */
- : FLOATINGPOINTTOK ctfBody -> ^(FLOATING_POINT ctfBody?)
- | INTEGERTOK ctfBody -> ^(INTEGER ctfBody?)
- | STRINGTOK ctfBody? -> ^(STRING ctfBody?)
- ;
-
-ctfBody
-scope Symbols;
-@init {
- $Symbols::types = new HashSet<String>();
-}
- : LCURL ctfAssignmentExpressionList? RCURL -> ctfAssignmentExpressionList?
- ;
-
-ctfAssignmentExpressionList
- : (ctfAssignmentExpression TERM!)+
- ;
-
-ctfAssignmentExpression
-@after {
- if (inTypedef()) {
- typedefOff();
- }
-}
- : left=unaryExpression
- ( assignment=ASSIGNMENT right1=unaryExpression
- -> ^(CTF_EXPRESSION_VAL
- ^(CTF_LEFT $left)
- ^(CTF_RIGHT $right1))
- | type_assignment=TYPE_ASSIGNMENT right2=typeSpecifier
- -> ^(CTF_EXPRESSION_TYPE
- ^(CTF_LEFT $left)
- ^(CTF_RIGHT ^(TYPE_SPECIFIER_LIST $right2)))
- )
- | (declarationSpecifiers {inTypedef()}? declaratorList)
- -> ^(TYPEDEF declaratorList declarationSpecifiers)
- | typealiasDecl
- ;
--- /dev/null
+lexer grammar CTFLexer;
+
+options {
+ language = Java;
+}
+
+@lexer::header {
+ package org.eclipse.tracecompass.ctf.parser;
+}
+
+/*
+ * Lexer tokens
+ */
+
+/*
+ * Keywords
+ */
+ALIGNTOK : 'align' ;
+CONSTTOK : 'const' ;
+CHARTOK : 'char' ;
+DOUBLETOK : 'double' ;
+ENUMTOK : 'enum' ;
+EVENTTOK : 'event' ;
+FLOATINGPOINTTOK : 'floating_point' ;
+FLOATTOK : 'float' ;
+INTEGERTOK : 'integer' ;
+INTTOK : 'int' ;
+LONGTOK : 'long' ;
+SHORTTOK : 'short' ;
+SIGNEDTOK : 'signed' ;
+STREAMTOK : 'stream' ;
+STRINGTOK : 'string' ;
+STRUCTTOK : 'struct' ;
+TRACETOK : 'trace' ;
+TYPEALIASTOK : 'typealias' ;
+TYPEDEFTOK : 'typedef' ;
+UNSIGNEDTOK : 'unsigned' ;
+VARIANTTOK : 'variant' ;
+VOIDTOK : 'void' ;
+BOOLTOK : '_Bool' ;
+COMPLEXTOK : '_Complex' ;
+IMAGINARYTOK : '_Imaginary' ;
+ENVTOK : 'env' ;
+CLOCKTOK : 'clock' ;
+/*
+ * Callsite tokens (CTF v1.9)
+ */
+CALLSITETOK : 'callsite' ;
+
+
+/*
+ * These tokens are not part of the CTF standard.
+ * There are planned to be in CTF v1.9
+ */
+NANNUMBERTOK : 'NaN' ;
+INFINITYTOK : '+inf' ;
+NINFINITYTOK : '-inf' ;
+
+/*
+ * Symbols
+ */
+SEPARATOR : ',' ;
+COLON : ':' ;
+ELIPSES : '...' ;
+ASSIGNMENT : '=' ;
+TYPE_ASSIGNMENT : ':=' ;
+LT : '<' ;
+GT : '>' ;
+OPENBRAC : '[' ;
+CLOSEBRAC : ']' ;
+LPAREN : '(' ;
+RPAREN : ')' ;
+LCURL : '{' ;
+RCURL : '}' ;
+TERM : ';' ;
+POINTER : '*' ;
+SIGN : '+' | '-' ;
+ARROW : '->' ;
+DOT : '.' ;
+fragment BACKSLASH : '\\' ;
+
+/* Helpers for integer literals */
+fragment DIGIT : '0'..'9' ;
+fragment OCT_DIGIT : '0'..'7' ;
+fragment OCT_PREFIX : '0' ;
+fragment NONZERO_DIGIT : '1'..'9' ;
+fragment HEX_DIGIT : DIGIT | ('a'..'f') | ('A'..'F') ;
+fragment HEX_PREFIX : '0' ('x' | 'X') ;
+
+/*
+ * Integer literals
+ */
+OCTAL_LITERAL : OCT_PREFIX (OCT_DIGIT)+ INTEGER_TYPES_SUFFIX? ;
+DECIMAL_LITERAL : DIGIT+ INTEGER_TYPES_SUFFIX? ;
+HEX_LITERAL : HEX_PREFIX HEX_DIGIT+ INTEGER_TYPES_SUFFIX? ;
+
+/**
+ * Integer suffix for long, long long and unsigned.
+ *
+ * Matches all possible combination of L, LL and U.
+ */
+fragment INTEGER_TYPES_SUFFIX
+ : ('l' ('l')? | 'L' ('L')?) // l, ll
+ | ('u' | 'U') // u
+ | ('u' | 'U') ('l' ('l')? | 'L' ('L')?) // ul, ull
+ | ('l' ('l')? | 'L' ('L')?) ('u'| 'U') // lu, llu
+ ;
+
+/**
+ * Escape sequences
+ */
+fragment ESCAPE_SEQUENCE
+ : BACKSLASH ('\'' | '"' | '?' | BACKSLASH | 'a' | 'b' | 'f' | 'n' | 'r' | 't' | 'v' )
+ | OCTAL_ESCAPE
+ | UNICODE_ESCAPE
+ | HEXADECIMAL_ESCAPE
+ ;
+
+/**
+ * Octal escape sequence
+ */
+fragment OCTAL_ESCAPE
+ : BACKSLASH ('0'..'3') ('0'..'7') ('0'..'7')
+ | BACKSLASH ('0'..'7') ('0'..'7')
+ | BACKSLASH ('0'..'7')
+ ;
+
+/**
+ * Hexadecimal escape sequence
+ */
+fragment HEXADECIMAL_ESCAPE : BACKSLASH 'x' HEX_DIGIT+ ;
+
+/**
+ * Unicode escape sequence
+ */
+fragment UNICODE_ESCAPE
+ : BACKSLASH 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT
+ | BACKSLASH 'U' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT
+ ;
+
+
+/* Used in both character and string literal */
+fragment STRINGPREFIX : 'L';
+
+/*
+ * Character literal
+ */
+CHARACTER_LITERAL : STRINGPREFIX? SINGLEQUOTE CHAR_CONTENT+ SINGLEQUOTE ;
+fragment CHAR_CONTENT : (ESCAPE_SEQUENCE | ~(BACKSLASH | SINGLEQUOTE)) ;
+fragment SINGLEQUOTE : '\'';
+
+/*
+ * String literal
+ */
+STRING_LITERAL : STRINGPREFIX? DOUBLEQUOTE STRING_CONTENT* DOUBLEQUOTE ;
+fragment STRING_CONTENT : (ESCAPE_SEQUENCE | ~(BACKSLASH | DOUBLEQUOTE)) ;
+fragment DOUBLEQUOTE : '"' ;
+
+/**
+ * Whitespaces
+ */
+WS : (' ' | '\r' | '\t' | '\u000C' | '\n') { $channel = HIDDEN; } ;
+
+/**
+ * Multiline comment
+ */
+// About the greedy option: see page 100-101 of The Definitive ANTLR reference
+// COMMENT : '/*' ( options { greedy = false; } : . )* '*/' { $channel = HIDDEN; } ;
+COMMENT : COMMENT_OPEN .* COMMENT_CLOSE { $channel = HIDDEN; } ;
+fragment COMMENT_OPEN : '/*';
+fragment COMMENT_CLOSE : '*/';
+
+/**
+ * Single line comment
+ */
+LINE_COMMENT : '//' ~('\n')* '\n' { $channel = HIDDEN; } ;
+
+/**
+ * Identifiers
+ */
+IDENTIFIER : NONDIGIT (NONDIGIT | DIGIT)* ;
+fragment NONDIGIT : ('_') | ('A'..'Z') | ('a'..'z') ;
--- /dev/null
+parser grammar CTFParser;
+
+options {
+ language = Java;
+ output = AST;
+ ASTLabelType = CommonTree;
+ tokenVocab = CTFLexer;
+}
+
+tokens {
+ ROOT;
+
+ EVENT;
+ STREAM;
+ TRACE;
+ ENV;
+ CLOCK;
+ CALLSITE;
+
+ DECLARATION;
+ SV_DECLARATION;
+ TYPE_SPECIFIER_LIST;
+ TYPE_DECLARATOR_LIST;
+ TYPE_DECLARATOR;
+
+ STRUCT;
+ STRUCT_NAME;
+ STRUCT_BODY;
+ ALIGN;
+
+ CTF_EXPRESSION_TYPE;
+ CTF_EXPRESSION_VAL;
+ CTF_LEFT;
+ CTF_RIGHT;
+
+ UNARY_EXPRESSION_STRING;
+ UNARY_EXPRESSION_STRING_QUOTES;
+ UNARY_EXPRESSION_DEC;
+ UNARY_EXPRESSION_HEX;
+ UNARY_EXPRESSION_OCT;
+ LENGTH;
+
+ TYPEDEF;
+
+ TYPEALIAS;
+ TYPEALIAS_TARGET;
+ TYPEALIAS_ALIAS;
+
+ INTEGER;
+ STRING;
+ FLOATING_POINT;
+
+ ENUM;
+ ENUM_CONTAINER_TYPE;
+ ENUM_ENUMERATOR;
+ ENUM_NAME;
+ ENUM_VALUE;
+ ENUM_VALUE_RANGE;
+ ENUM_BODY;
+
+ VARIANT;
+ VARIANT_NAME;
+ VARIANT_TAG;
+ VARIANT_BODY;
+
+ DECLARATOR;
+ LENGTH;
+}
+
+/*
+ * Scope for the tracking of types.
+ * For now we just track the names (it's a simple Set), but
+ * later we will have to track the info about the target type.
+ */
+scope Symbols {
+ Set<String> types;
+}
+
+@header {
+ package org.eclipse.tracecompass.ctf.parser;
+ import java.util.Set;
+ import java.util.HashSet;
+}
+
+@members {
+ public CTFParser(TokenStream input, boolean verbose) {
+ this(input);
+ this.verbose = verbose;
+ }
+
+ /**
+ * This method is overriden to disable automatic error recovery.
+ * On a mismatched token, it simply re-throw an exception.
+ */
+ @Override
+ protected Object recoverFromMismatchedToken(IntStream input, int ttype, BitSet follow) throws RecognitionException {
+ throw new MismatchedTokenException(ttype, input);
+ }
+
+ /**
+ * Checks if a given name has been defined has a type.
+ * From: http://www.antlr.org/grammar/1153358328744/C.g
+ *
+ * @param name The name to check.
+ * @return True if is is a type, false otherwise.
+ */
+ boolean isTypeName(String name) {
+ for (int i = Symbols_stack.size() - 1; i >= 0; i--) {
+ Symbols_scope scope = (Symbols_scope) Symbols_stack.get(i);
+ if (scope.types.contains(name)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ void addTypeName(String name) {
+ $Symbols::types.add(name);
+ if (verbose) {
+ debug_print("New type: " + name);
+ }
+ }
+
+ boolean _inTypedef = false;
+
+ void typedefOn() {
+ debug_print("typedefOn");
+ _inTypedef = true;
+ }
+
+ void typedefOff() {
+ debug_print("typedefOff");
+ _inTypedef = false;
+ }
+
+ boolean inTypedef() {
+ return _inTypedef;
+ }
+
+ boolean _inTypealiasAlias = false;
+
+ void typealiasAliasOn() {
+ debug_print("typealiasAliasOn");
+ _inTypealiasAlias = true;
+ }
+
+ void typealiasAliasOff() {
+ debug_print("typealiasAliasOff");
+ _inTypealiasAlias = false;
+ }
+
+ boolean inTypealiasAlias() {
+ return _inTypealiasAlias;
+ }
+
+ void debug_print(String str) {
+ if (verbose) {
+ System.out.println(str);
+ }
+ }
+
+ /* Prints rule entry and exit while parsing */
+ boolean verbose = false;
+}
+
+ /*
+ * Override the catch clause to disable automatic error recovery.
+ * By default, the catch block of every rule simple rethrows the error.
+ */
+@rulecatch {
+ catch (RecognitionException e) {
+ throw e;
+ }
+}
+
+/* The top-level rule. */
+parse
+scope Symbols;
+@init {
+ $Symbols::types = new HashSet<String>();
+}
+ : declaration+ EOF -> ^(ROOT declaration+)
+ ;
+
+numberLiteral
+ : SIGN*
+ ( HEX_LITERAL -> ^(UNARY_EXPRESSION_HEX HEX_LITERAL SIGN*)
+ | DECIMAL_LITERAL -> ^(UNARY_EXPRESSION_DEC DECIMAL_LITERAL SIGN*)
+ | OCTAL_LITERAL -> ^(UNARY_EXPRESSION_OCT OCTAL_LITERAL SIGN*)
+ )
+ ;
+
+primaryExpression
+ : (IDENTIFIER) => IDENTIFIER
+ -> ^(UNARY_EXPRESSION_STRING IDENTIFIER)
+ | (ctfKeyword) => ctfKeyword -> ^(UNARY_EXPRESSION_STRING ctfKeyword)
+ | (STRING_LITERAL) => STRING_LITERAL
+ -> ^(UNARY_EXPRESSION_STRING_QUOTES STRING_LITERAL)
+ /*| (LPAREN unaryExpression RPAREN)*/ // Not supported yet
+ | numberLiteral
+ | enumConstant
+ | CHARACTER_LITERAL
+ ;
+
+postfixExpressionSuffix
+ : OPENBRAC unaryExpression CLOSEBRAC!
+ | (ref=DOT | ref=ARROW) IDENTIFIER
+ -> ^($ref ^(UNARY_EXPRESSION_STRING IDENTIFIER))
+ ;
+
+postfixExpression
+ : primaryExpression postfixExpressionSuffix*
+ | ctfSpecifierHead postfixExpressionSuffix+ // added for ctf-v1.8
+ ;
+
+unaryExpression
+ : postfixExpression
+ /* | ((SIGN postfixExpression[true]) | postfixExpression[false]) */
+ ;
+
+enumConstant
+ : STRING_LITERAL -> ^(UNARY_EXPRESSION_STRING_QUOTES STRING_LITERAL)
+ | IDENTIFIER -> ^(UNARY_EXPRESSION_STRING IDENTIFIER)
+ | ctfKeyword -> ^(UNARY_EXPRESSION_STRING ctfKeyword)
+ ;
+
+// 2.2
+
+declaration
+@after {
+ if (inTypedef()) {
+ typedefOff();
+ }
+}
+ : declarationSpecifiers declaratorList? TERM
+ // When the declaration is completely parsed and was a typedef,
+ // we add the declarators to the symbol table.
+ -> {inTypedef()}?
+ ^(DECLARATION ^(TYPEDEF declaratorList declarationSpecifiers))
+ -> ^(DECLARATION declarationSpecifiers declaratorList?)
+ | ctfSpecifier TERM!
+ ;
+
+declarationSpecifiers
+ : (
+ // We don't want to keep the typedef keyword in the specifier list.
+ // Instead, we keep track that we encountered a typedef in the declaration.
+ storageClassSpecifier
+ | typeQualifier
+ | typeSpecifier
+ )+ -> ^(TYPE_SPECIFIER_LIST typeQualifier* typeSpecifier*)
+ ;
+
+declaratorList
+ : declarator (SEPARATOR declarator)*
+ -> ^(TYPE_DECLARATOR_LIST declarator+)
+ ;
+
+abstractDeclaratorList
+ : abstractDeclarator (SEPARATOR abstractDeclarator)*
+ -> ^(TYPE_DECLARATOR_LIST abstractDeclarator+)
+ ;
+
+storageClassSpecifier
+ : TYPEDEFTOK { typedefOn(); }
+ ;
+
+typeSpecifier
+ : FLOATTOK
+ | INTTOK
+ | LONGTOK
+ | SHORTTOK
+ | SIGNEDTOK
+ | UNSIGNEDTOK
+ | CHARTOK
+ | DOUBLETOK
+ | VOIDTOK
+ | BOOLTOK
+ | COMPLEXTOK
+ | IMAGINARYTOK
+ | structSpecifier
+ | variantSpecifier
+ | enumSpecifier
+ | ctfTypeSpecifier
+ | { inTypealiasAlias() || isTypeName(input.LT(1).getText()) }? => typedefName
+ ;
+
+typeQualifier
+ : CONSTTOK
+ ;
+
+alignAttribute
+ : ALIGNTOK LPAREN unaryExpression RPAREN -> ^(ALIGN unaryExpression)
+ ;
+
+ // you can have an empty struct but not an empty variant
+structBody
+scope Symbols;
+@init {
+ $Symbols::types = new HashSet<String>();
+}
+ : LCURL structOrVariantDeclarationList? RCURL
+ -> ^(STRUCT_BODY structOrVariantDeclarationList?)
+ ;
+
+structSpecifier
+ : STRUCTTOK
+ (
+ // We have an IDENTIFIER after 'struct'
+ (
+ structName
+ (
+ alignAttribute
+ |
+ (
+ structBody
+ ( /* structBody can return an empty tree, so we need those ? */
+ alignAttribute
+ |
+ /* empty */
+ )
+ )
+ |
+ /* empty */
+ )
+ )
+ |
+ // We have a body after 'struct'
+ (
+ structBody
+ (
+ alignAttribute
+ |
+ /* empty */
+ )
+ )
+ ) -> ^(STRUCT structName? structBody? alignAttribute?)
+ ;
+
+structName
+ : IDENTIFIER -> ^(STRUCT_NAME IDENTIFIER)
+ ;
+
+structOrVariantDeclarationList
+ : structOrVariantDeclaration+
+ ;
+
+structOrVariantDeclaration
+ :
+ (
+ (
+ declarationSpecifiers
+ (
+ /* If we met a "typedef" */
+ {inTypedef()}? => declaratorList {typedefOff();}
+ -> ^(TYPEDEF declaratorList declarationSpecifiers)
+ | structOrVariantDeclaratorList
+ -> ^(SV_DECLARATION declarationSpecifiers structOrVariantDeclaratorList)
+ )
+ )
+ |
+ // Lines 3 and 4
+ typealiasDecl -> typealiasDecl
+ )
+ TERM
+ ;
+
+specifierQualifierList
+ : (typeQualifier | typeSpecifier)+
+ -> ^(TYPE_SPECIFIER_LIST typeQualifier* typeSpecifier*)
+ ;
+
+structOrVariantDeclaratorList
+ : structOrVariantDeclarator (SEPARATOR structOrVariantDeclarator)*
+ -> ^(TYPE_DECLARATOR_LIST structOrVariantDeclarator+)
+ ;
+
+structOrVariantDeclarator
+ :
+ /* Bitfields not supported yet */
+ (declarator (COLON numberLiteral)?) -> declarator
+ /*| (COLON numberLiteral)*/
+ ;
+
+variantSpecifier
+ : VARIANTTOK
+ (
+ (
+ variantName
+ (
+ (
+ variantTag
+ (
+ variantBody
+ |
+ /* empty */
+ )
+ )
+ |
+ variantBody
+ )
+ )
+ | (variantTag variantBody)
+ | variantBody
+ ) -> ^(VARIANT variantName? variantTag? variantBody?)
+ ;
+
+variantName
+ : IDENTIFIER -> ^(VARIANT_NAME IDENTIFIER)
+ ;
+
+variantBody
+scope Symbols;
+@init {
+ $Symbols::types = new HashSet<String>();
+}
+ : LCURL structOrVariantDeclarationList RCURL
+ -> ^(VARIANT_BODY structOrVariantDeclarationList)
+ ;
+
+variantTag
+ : LT IDENTIFIER GT -> ^(VARIANT_TAG IDENTIFIER)
+ ;
+
+enumSpecifier
+ : ENUMTOK
+ (
+ // Lines 1 to 5, when we have "ENUMTOK IDENTIFIER".
+ (
+ enumName
+ (
+ enumContainerType enumBody
+ |
+ enumBody
+ |
+ // no enumDeclarator or enumBodym
+ )
+ )
+ |
+ // Lines 1, 2, 4, 5, when we have no IDENTIFIER.
+ (
+ enumContainerType enumBody
+ |
+ enumBody
+ )
+ ) -> ^(ENUM enumName? enumContainerType? enumBody?)
+ ;
+
+enumName
+ : IDENTIFIER -> ^(ENUM_NAME IDENTIFIER)
+ ;
+
+enumBody
+ : LCURL enumeratorList SEPARATOR? RCURL -> ^(ENUM_BODY enumeratorList)
+ ;
+
+enumContainerType
+ : COLON declarationSpecifiers -> ^(ENUM_CONTAINER_TYPE declarationSpecifiers)
+ ;
+
+enumeratorList
+ : enumerator (SEPARATOR enumerator)* -> (^(ENUM_ENUMERATOR enumerator))+
+ ;
+
+enumerator
+ : enumConstant enumeratorValue?
+ ;
+
+enumeratorValue
+ : ASSIGNMENT e1=unaryExpression
+ ( /* empty */
+ -> ^(ENUM_VALUE $e1)
+ | ELIPSES e2=unaryExpression
+ -> ^(ENUM_VALUE_RANGE $e1 $e2)
+ )
+ ;
+
+declarator
+ : pointer* directDeclarator
+ -> ^(TYPE_DECLARATOR pointer* directDeclarator)
+ ;
+
+directDeclarator
+ : (
+ IDENTIFIER
+ { if (inTypedef()) addTypeName($IDENTIFIER.text); }
+ { debug_print($IDENTIFIER.text); }
+ /*| LPAREN declarator RPAREN*/ /* Not supported yet */
+ )
+ directDeclaratorSuffix*
+ ;
+
+directDeclaratorSuffix
+ : OPENBRAC directDeclaratorLength CLOSEBRAC
+ -> ^(LENGTH directDeclaratorLength)
+ ;
+
+directDeclaratorLength
+ : unaryExpression
+ ;
+
+abstractDeclarator
+ : pointer+ directAbstractDeclarator?
+ -> ^(TYPE_DECLARATOR pointer+ directAbstractDeclarator?)
+ | directAbstractDeclarator
+ -> ^(TYPE_DECLARATOR directAbstractDeclarator)
+ ;
+
+/**
+ * In the CTF grammar, direct-abstract-declarator can be empty (because of
+ * identifier-opt). We take care of that by appending a '?' to each use of
+ * "abstractDeclaratorList".
+ */
+directAbstractDeclarator
+ : (
+ IDENTIFIER
+ | (LPAREN abstractDeclarator RPAREN)
+ ) (
+ OPENBRAC unaryExpression? CLOSEBRAC
+ )?
+ ;
+
+pointer
+ : POINTER typeQualifierList? -> ^(POINTER typeQualifierList?)
+ ;
+
+typeQualifierList
+ : typeQualifier+
+ ;
+
+typedefName
+ : {inTypealiasAlias() || isTypeName(input.LT(1).getText())}? IDENTIFIER { if ((inTypedef() || inTypealiasAlias()) && !isTypeName($IDENTIFIER.text)) { addTypeName($IDENTIFIER.text); } }
+ ;
+
+/**
+ * What goes in the target part of a typealias.
+ *
+ * For example, the integer part in:
+ * typealias integer {...} := my_new_integer;
+ */
+typealiasTarget
+ : declarationSpecifiers abstractDeclaratorList?
+ ;
+
+/**
+ * What goes in the alias part of a typealias.
+ *
+ * For example, the my_new_integer part in:
+ * typealias integer {...} := my_new_integer;
+ */
+typealiasAlias
+@init {
+ typealiasAliasOn();
+}
+@after {
+ typealiasAliasOff();
+}
+ : abstractDeclaratorList
+ | declarationSpecifiers abstractDeclaratorList?
+ ;
+
+typealiasDecl
+ : TYPEALIASTOK typealiasTarget TYPE_ASSIGNMENT typealiasAlias
+ -> ^(TYPEALIAS
+ ^(TYPEALIAS_TARGET typealiasTarget)
+ ^(TYPEALIAS_ALIAS typealiasAlias))
+ ;
+
+// 2.3 CTF stuff
+
+// TODO: Ajouter ceux qui manquent
+ctfKeyword
+ : ALIGNTOK
+ | EVENTTOK
+ | SIGNEDTOK
+ | STRINGTOK
+ ;
+
+ctfSpecifier
+ // event {...}, stream {...}, trace {...}
+ : ctfSpecifierHead ctfBody -> ^(ctfSpecifierHead ctfBody)
+ // typealias
+ | typealiasDecl -> ^(DECLARATION typealiasDecl)
+ ;
+
+ctfSpecifierHead
+ : EVENTTOK -> EVENT
+ | STREAMTOK -> STREAM
+ | TRACETOK -> TRACE
+ | ENVTOK -> ENV
+ | CLOCKTOK -> CLOCK
+ | CALLSITETOK -> CALLSITE
+ ;
+
+ctfTypeSpecifier
+ /* ctfBody can return an empty tree if the body is empty */
+ : FLOATINGPOINTTOK ctfBody -> ^(FLOATING_POINT ctfBody?)
+ | INTEGERTOK ctfBody -> ^(INTEGER ctfBody?)
+ | STRINGTOK ctfBody? -> ^(STRING ctfBody?)
+ ;
+
+ctfBody
+scope Symbols;
+@init {
+ $Symbols::types = new HashSet<String>();
+}
+ : LCURL ctfAssignmentExpressionList? RCURL -> ctfAssignmentExpressionList?
+ ;
+
+ctfAssignmentExpressionList
+ : (ctfAssignmentExpression TERM!)+
+ ;
+
+ctfAssignmentExpression
+@after {
+ if (inTypedef()) {
+ typedefOff();
+ }
+}
+ : left=unaryExpression
+ ( assignment=ASSIGNMENT right1=unaryExpression
+ -> ^(CTF_EXPRESSION_VAL
+ ^(CTF_LEFT $left)
+ ^(CTF_RIGHT $right1))
+ | type_assignment=TYPE_ASSIGNMENT right2=typeSpecifier
+ -> ^(CTF_EXPRESSION_TYPE
+ ^(CTF_LEFT $left)
+ ^(CTF_RIGHT ^(TYPE_SPECIFIER_LIST $right2)))
+ )
+ | (declarationSpecifiers {inTypedef()}? declaratorList)
+ -> ^(TYPEDEF declaratorList declarationSpecifiers)
+ | typealiasDecl
+ ;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTrace;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTrace;
import org.eclipse.tracecompass.internal.lttng2.control.core.relayd.ILttngRelaydConnector;
import org.eclipse.tracecompass.internal.lttng2.control.core.relayd.LttngRelaydConnectorFactory;
import org.eclipse.tracecompass.internal.lttng2.control.core.relayd.lttngviewerCommands.AttachReturnCode;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTrace;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTrace;
import org.eclipse.tracecompass.internal.lttng2.kernel.core.Activator;
import org.eclipse.tracecompass.tmf.core.trace.TraceValidationStatus;
import org.eclipse.tracecompass.tmf.ctf.core.CtfTmfTrace;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTrace;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTrace;
import org.eclipse.tracecompass.internal.lttng2.ust.core.Activator;
import org.eclipse.tracecompass.tmf.core.trace.TraceValidationStatus;
import org.eclipse.tracecompass.tmf.ctf.core.CtfTmfTrace;
import java.util.List;
import java.util.Set;
-import org.eclipse.linuxtools.ctf.core.tests.shared.CtfTestTrace;
import org.eclipse.test.performance.Dimension;
import org.eclipse.test.performance.Performance;
import org.eclipse.test.performance.PerformanceMeter;
+import org.eclipse.tracecompass.ctf.core.tests.shared.CtfTestTrace;
import org.eclipse.tracecompass.tmf.core.event.ITmfEvent;
import org.eclipse.tracecompass.tmf.core.exceptions.TmfTraceException;
import org.eclipse.tracecompass.tmf.core.request.ITmfEventRequest;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
-import org.eclipse.linuxtools.ctf.core.tests.shared.CtfTestTrace;
+import org.eclipse.tracecompass.ctf.core.tests.shared.CtfTestTrace;
import org.eclipse.tracecompass.tmf.core.exceptions.TmfTraceException;
import org.eclipse.tracecompass.tmf.ctf.core.CtfTmfEvent;
import org.eclipse.tracecompass.tmf.ctf.core.CtfTmfTrace;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
import org.eclipse.tracecompass.tmf.ctf.core.CtfIterator;
import org.eclipse.tracecompass.tmf.ctf.core.CtfLocation;
import org.eclipse.tracecompass.tmf.ctf.core.CtfLocationInfo;
import java.nio.ByteOrder;
import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.io.BitBuffer;
-import org.eclipse.linuxtools.ctf.core.event.types.EnumDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.FloatDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.FloatDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.IDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StringDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.StructDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.VariantDeclaration;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.internal.ctf.core.event.types.ArrayDeclaration;
-import org.eclipse.linuxtools.internal.ctf.core.event.types.SequenceDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
+import org.eclipse.tracecompass.ctf.core.event.types.EnumDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.FloatDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.FloatDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.IDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StringDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.StructDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.VariantDeclaration;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.internal.ctf.core.event.types.ArrayDeclaration;
+import org.eclipse.tracecompass.internal.ctf.core.event.types.SequenceDeclaration;
import org.eclipse.tracecompass.tmf.ctf.core.CtfTmfEventField;
import org.junit.Before;
import org.junit.Test;
import java.util.Collection;
import java.util.Set;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
import org.eclipse.tracecompass.tmf.core.event.ITmfEventField;
import org.eclipse.tracecompass.tmf.core.event.ITmfEventType;
import org.eclipse.tracecompass.tmf.core.trace.ITmfContext;
import java.util.Map;
-import org.eclipse.linuxtools.ctf.core.CTFStrings;
+import org.eclipse.tracecompass.ctf.core.CTFStrings;
import org.eclipse.tracecompass.statesystem.core.ITmfStateSystem;
import org.eclipse.tracecompass.tmf.core.exceptions.TmfAnalysisException;
import org.eclipse.tracecompass.tmf.core.statistics.ITmfStatistics;
package org.eclipse.tracecompass.tmf.ctf.core;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.ctf.core.trace.CTFStreamInputReader;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTraceReader;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.ctf.core.trace.CTFStreamInputReader;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTraceReader;
import org.eclipse.tracecompass.internal.tmf.ctf.core.Activator;
import org.eclipse.tracecompass.tmf.core.trace.ITmfContext;
import org.eclipse.tracecompass.tmf.core.trace.location.ITmfLocation;
package org.eclipse.tracecompass.tmf.ctf.core;
-import org.eclipse.linuxtools.ctf.core.event.CTFCallsite;
+import org.eclipse.tracecompass.ctf.core.event.CTFCallsite;
import org.eclipse.tracecompass.tmf.core.event.lookup.TmfCallsite;
/**
import java.util.Set;
import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.CTFCallsite;
-import org.eclipse.linuxtools.ctf.core.event.EventDefinition;
-import org.eclipse.linuxtools.ctf.core.event.IEventDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.ICompositeDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.IDefinition;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTrace;
+import org.eclipse.tracecompass.ctf.core.event.CTFCallsite;
+import org.eclipse.tracecompass.ctf.core.event.EventDefinition;
+import org.eclipse.tracecompass.ctf.core.event.IEventDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.ICompositeDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.IDefinition;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTrace;
import org.eclipse.tracecompass.tmf.core.event.ITmfCustomAttributes;
import org.eclipse.tracecompass.tmf.core.event.ITmfEventField;
import org.eclipse.tracecompass.tmf.core.event.ITmfEventType;
package org.eclipse.tracecompass.tmf.ctf.core;
-import org.eclipse.linuxtools.ctf.core.CTFStrings;
-import org.eclipse.linuxtools.ctf.core.event.EventDefinition;
-import org.eclipse.linuxtools.ctf.core.event.IEventDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDefinition;
+import org.eclipse.tracecompass.ctf.core.CTFStrings;
+import org.eclipse.tracecompass.ctf.core.event.EventDefinition;
+import org.eclipse.tracecompass.ctf.core.event.IEventDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDefinition;
import org.eclipse.tracecompass.tmf.core.timestamp.TmfTimeRange;
import org.eclipse.tracecompass.tmf.core.trace.ITmfContext;
import java.util.Collection;
import java.util.List;
-import org.eclipse.linuxtools.ctf.core.event.types.CompoundDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.Definition;
-import org.eclipse.linuxtools.ctf.core.event.types.EnumDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.FloatDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.ICompositeDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.IDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDeclaration;
-import org.eclipse.linuxtools.ctf.core.event.types.IntegerDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.StringDefinition;
-import org.eclipse.linuxtools.ctf.core.event.types.VariantDefinition;
-import org.eclipse.linuxtools.internal.ctf.core.event.types.ArrayDefinition;
-import org.eclipse.linuxtools.internal.ctf.core.event.types.ByteArrayDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.CompoundDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.Definition;
+import org.eclipse.tracecompass.ctf.core.event.types.EnumDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.FloatDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.ICompositeDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.IDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.types.IntegerDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.StringDefinition;
+import org.eclipse.tracecompass.ctf.core.event.types.VariantDefinition;
+import org.eclipse.tracecompass.internal.ctf.core.event.types.ArrayDefinition;
+import org.eclipse.tracecompass.internal.ctf.core.event.types.ByteArrayDefinition;
import org.eclipse.tracecompass.tmf.core.event.ITmfEventField;
import org.eclipse.tracecompass.tmf.core.event.TmfEventField;
package org.eclipse.tracecompass.tmf.ctf.core;
import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.linuxtools.ctf.core.event.EventDefinition;
-import org.eclipse.linuxtools.ctf.core.event.IEventDeclaration;
+import org.eclipse.tracecompass.ctf.core.event.EventDefinition;
+import org.eclipse.tracecompass.ctf.core.event.IEventDeclaration;
import org.eclipse.tracecompass.tmf.core.event.ITmfLostEvent;
import org.eclipse.tracecompass.tmf.core.timestamp.TmfTimeRange;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
-import org.eclipse.linuxtools.ctf.core.event.CTFClock;
-import org.eclipse.linuxtools.ctf.core.event.IEventDeclaration;
-import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTrace;
-import org.eclipse.linuxtools.ctf.core.trace.CTFTraceReader;
+import org.eclipse.tracecompass.ctf.core.event.CTFClock;
+import org.eclipse.tracecompass.ctf.core.event.IEventDeclaration;
+import org.eclipse.tracecompass.ctf.core.trace.CTFReaderException;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTrace;
+import org.eclipse.tracecompass.ctf.core.trace.CTFTraceReader;
import org.eclipse.tracecompass.internal.tmf.ctf.core.Activator;
import org.eclipse.tracecompass.tmf.core.event.ITmfEvent;
import org.eclipse.tracecompass.tmf.core.event.ITmfEventField;