1 /*******************************************************************************
2 * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
4 * All rights reserved. This program and the accompanying materials are made
5 * available under the terms of the Eclipse Public License v1.0 which
6 * accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * Matthew Khouzam - Initial API and implementation
11 * Alexandre Montplaisir - Initial API and implementation
12 * Simon Delisle - Replace LinkedList by TreeSet in callsitesByName attribute
13 *******************************************************************************/
15 package org
.eclipse
.tracecompass
.ctf
.core
.trace
;
18 import java
.io
.FileFilter
;
19 import java
.io
.IOException
;
20 import java
.io
.Serializable
;
21 import java
.nio
.ByteBuffer
;
22 import java
.nio
.ByteOrder
;
23 import java
.nio
.channels
.FileChannel
;
24 import java
.nio
.channels
.FileChannel
.MapMode
;
25 import java
.nio
.file
.StandardOpenOption
;
26 import java
.util
.Arrays
;
27 import java
.util
.Collection
;
28 import java
.util
.Collections
;
29 import java
.util
.Comparator
;
30 import java
.util
.HashMap
;
33 import java
.util
.TreeSet
;
34 import java
.util
.UUID
;
36 import org
.eclipse
.tracecompass
.ctf
.core
.CTFException
;
37 import org
.eclipse
.tracecompass
.ctf
.core
.CTFStrings
;
38 import org
.eclipse
.tracecompass
.ctf
.core
.event
.CTFCallsite
;
39 import org
.eclipse
.tracecompass
.ctf
.core
.event
.CTFClock
;
40 import org
.eclipse
.tracecompass
.ctf
.core
.event
.IEventDeclaration
;
41 import org
.eclipse
.tracecompass
.ctf
.core
.event
.io
.BitBuffer
;
42 import org
.eclipse
.tracecompass
.ctf
.core
.event
.metadata
.DeclarationScope
;
43 import org
.eclipse
.tracecompass
.ctf
.core
.event
.scope
.IDefinitionScope
;
44 import org
.eclipse
.tracecompass
.ctf
.core
.event
.scope
.ILexicalScope
;
45 import org
.eclipse
.tracecompass
.ctf
.core
.event
.types
.AbstractArrayDefinition
;
46 import org
.eclipse
.tracecompass
.ctf
.core
.event
.types
.Definition
;
47 import org
.eclipse
.tracecompass
.ctf
.core
.event
.types
.IDefinition
;
48 import org
.eclipse
.tracecompass
.ctf
.core
.event
.types
.IntegerDefinition
;
49 import org
.eclipse
.tracecompass
.ctf
.core
.event
.types
.StructDeclaration
;
50 import org
.eclipse
.tracecompass
.ctf
.core
.event
.types
.StructDefinition
;
51 import org
.eclipse
.tracecompass
.internal
.ctf
.core
.SafeMappedByteBuffer
;
52 import org
.eclipse
.tracecompass
.internal
.ctf
.core
.event
.CTFCallsiteComparator
;
53 import org
.eclipse
.tracecompass
.internal
.ctf
.core
.event
.metadata
.MetadataStrings
;
54 import org
.eclipse
.tracecompass
.internal
.ctf
.core
.event
.metadata
.exceptions
.ParseException
;
55 import org
.eclipse
.tracecompass
.internal
.ctf
.core
.trace
.Utils
;
58 * A CTF trace on the file system.
60 * Represents a trace on the filesystem. It is responsible of parsing the
61 * metadata, creating declarations data structures, indexing the event packets
62 * (in other words, all the work that can be shared between readers), but the
63 * actual reading of events is left to TraceReader.
65 * TODO: internalize CTFTrace and DeclarationScope
67 * @author Matthew Khouzam
68 * @version $Revision: 1.0 $
70 public class CTFTrace
implements IDefinitionScope
{
73 public String
toString() {
74 /* Only for debugging, shouldn't be externalized */
75 return "CTFTrace [path=" + fPath
+ ", major=" + fMajor
+ ", minor=" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
76 + fMinor
+ ", uuid=" + fUuid
+ "]"; //$NON-NLS-1$ //$NON-NLS-2$
80 * The trace directory on the filesystem.
82 private final File fPath
;
85 * Major CTF version number
90 * Minor CTF version number
102 private ByteOrder fByteOrder
;
105 * Packet header structure declaration
107 private StructDeclaration fPacketHeaderDecl
= null;
110 * The clock of the trace
112 private CTFClock fSingleClock
= null;
115 * Packet header structure definition
117 * This is only used when opening the trace files, to read the first packet
118 * header and see if they are valid trace files.
120 private StructDefinition fPacketHeaderDef
;
123 * Collection of streams contained in the trace.
125 private final Map
<Long
, CTFStream
> fStreams
= new HashMap
<>();
128 * Collection of environment variables set by the tracer
130 private final Map
<String
, String
> fEnvironment
= new HashMap
<>();
133 * Collection of all the clocks in a system.
135 private final Map
<String
, CTFClock
> fClocks
= new HashMap
<>();
137 /** Handlers for the metadata files */
138 private static final FileFilter METADATA_FILE_FILTER
= new MetadataFileFilter();
139 private static final Comparator
<File
> METADATA_COMPARATOR
= new MetadataComparator();
141 /** Callsite helpers */
142 private CTFCallsiteComparator fCtfCallsiteComparator
= new CTFCallsiteComparator();
144 private Map
<String
, TreeSet
<CTFCallsite
>> fCallsitesByName
= new HashMap
<>();
146 /** Callsite helpers */
147 private TreeSet
<CTFCallsite
> fCallsitesByIP
= new TreeSet
<>();
149 private final DeclarationScope fScope
= new DeclarationScope(null, MetadataStrings
.TRACE
);
151 // ------------------------------------------------------------------------
153 // ------------------------------------------------------------------------
159 * Filesystem path of the trace directory
160 * @throws CTFException
161 * If no CTF trace was found at the path
163 public CTFTrace(String path
) throws CTFException
{
164 this(new File(path
));
171 * Filesystem path of the trace directory.
172 * @throws CTFException
173 * If no CTF trace was found at the path
175 public CTFTrace(File path
) throws CTFException
{
177 final Metadata metadata
= new Metadata(this);
179 /* Set up the internal containers for this trace */
180 if (!fPath
.exists()) {
181 throw new CTFException("Trace (" + path
.getPath() + ") doesn't exist. Deleted or moved?"); //$NON-NLS-1$ //$NON-NLS-2$
184 if (!fPath
.isDirectory()) {
185 throw new CTFException("Path must be a valid directory"); //$NON-NLS-1$
188 /* Open and parse the metadata file */
189 metadata
.parseFile();
195 * Streamed constructor
201 private void init(File path
) throws CTFException
{
203 /* Open all the trace files */
205 /* List files not called metadata and not hidden. */
206 File
[] files
= path
.listFiles(METADATA_FILE_FILTER
);
207 Arrays
.sort(files
, METADATA_COMPARATOR
);
209 /* Try to open each file */
210 for (File streamFile
: files
) {
211 openStreamInput(streamFile
);
214 /* Create their index */
215 for (CTFStream stream
: getStreams()) {
216 Set
<CTFStreamInput
> inputs
= stream
.getStreamInputs();
217 for (CTFStreamInput s
: inputs
) {
223 // ------------------------------------------------------------------------
224 // Getters/Setters/Predicates
225 // ------------------------------------------------------------------------
228 * Gets an event declaration list for a given streamID
231 * The ID of the stream from which to read
232 * @return The list of event declarations
234 public Collection
<IEventDeclaration
> getEventDeclarations(Long streamId
) {
235 return fStreams
.get(streamId
).getEventDeclarations();
239 * Method getStream gets the stream for a given id
242 * Long the id of the stream
243 * @return Stream the stream that we need
245 public CTFStream
getStream(Long id
) {
247 return fStreams
.get(0L);
249 return fStreams
.get(id
);
253 * Method nbStreams gets the number of available streams
255 * @return int the number of streams
257 public int nbStreams() {
258 return fStreams
.size();
262 * Method setMajor sets the major version of the trace (DO NOT USE)
265 * long the major version
267 public void setMajor(long major
) {
272 * Method setMinor sets the minor version of the trace (DO NOT USE)
275 * long the minor version
277 public void setMinor(long minor
) {
282 * Method setUUID sets the UUID of a trace
287 public void setUUID(UUID uuid
) {
292 * Method setByteOrder sets the byte order
295 * ByteOrder of the trace, can be little-endian or big-endian
297 public void setByteOrder(ByteOrder byteOrder
) {
298 fByteOrder
= byteOrder
;
302 * Method setPacketHeader sets the packet header of a trace (DO NOT USE)
304 * @param packetHeader
305 * StructDeclaration the header in structdeclaration form
307 public void setPacketHeader(StructDeclaration packetHeader
) {
308 fPacketHeaderDecl
= packetHeader
;
312 * Method majorIsSet is the major version number set?
314 * @return boolean is the major set?
316 public boolean majorIsSet() {
317 return fMajor
!= null;
321 * Method minorIsSet. is the minor version number set?
323 * @return boolean is the minor set?
325 public boolean minorIsSet() {
326 return fMinor
!= null;
330 * Method UUIDIsSet is the UUID set?
332 * @return boolean is the UUID set?
334 public boolean uuidIsSet() {
335 return fUuid
!= null;
339 * Method byteOrderIsSet is the byteorder set?
341 * @return boolean is the byteorder set?
343 public boolean byteOrderIsSet() {
344 return fByteOrder
!= null;
348 * Method packetHeaderIsSet is the packet header set?
350 * @return boolean is the packet header set?
352 public boolean packetHeaderIsSet() {
353 return fPacketHeaderDecl
!= null;
357 * Method getUUID gets the trace UUID
359 * @return UUID gets the trace UUID
361 public UUID
getUUID() {
366 * Method getMajor gets the trace major version
368 * @return long gets the trace major version
370 public long getMajor() {
375 * Method getMinor gets the trace minor version
377 * @return long gets the trace minor version
379 public long getMinor() {
384 * Method getByteOrder gets the trace byte order
386 * @return ByteOrder gets the trace byte order
388 public final ByteOrder
getByteOrder() {
393 * Method getPacketHeader gets the trace packet header
395 * @return StructDeclaration gets the trace packet header
397 public StructDeclaration
getPacketHeader() {
398 return fPacketHeaderDecl
;
402 * Method getTraceDirectory gets the trace directory
404 * @return File the path in "File" format.
406 public File
getTraceDirectory() {
411 * Get all the streams as an iterable.
413 * @return Iterable<Stream> an iterable over streams.
415 public Iterable
<CTFStream
> getStreams() {
416 return fStreams
.values();
420 * Method getPath gets the path of the trace directory
422 * @return String the path of the trace directory, in string format.
423 * @see java.io.File#getPath()
425 public String
getPath() {
426 return (fPath
!= null) ? fPath
.getPath() : ""; //$NON-NLS-1$
429 // ------------------------------------------------------------------------
431 // ------------------------------------------------------------------------
433 private void addStream(CTFStreamInput s
) {
438 CTFStream stream
= s
.getStream();
439 fStreams
.put(stream
.getId(), stream
);
448 * Tries to open the given file, reads the first packet header of the file
449 * and check its validity. This will add a file to a stream as a streaminput
452 * A trace file in the trace directory.
454 * Which index in the class' streamFileChannel array this file
456 * @throws CTFException
457 * if there is a file error
459 private CTFStream
openStreamInput(File streamFile
) throws CTFException
{
460 ByteBuffer byteBuffer
;
461 BitBuffer streamBitBuffer
;
464 if (!streamFile
.canRead()) {
465 throw new CTFException("Unreadable file : " //$NON-NLS-1$
466 + streamFile
.getPath());
468 if (streamFile
.length() == 0) {
471 try (FileChannel fc
= FileChannel
.open(streamFile
.toPath(), StandardOpenOption
.READ
)) {
472 /* Map one memory page of 4 kiB */
473 byteBuffer
= SafeMappedByteBuffer
.map(fc
, MapMode
.READ_ONLY
, 0, (int) Math
.min(fc
.size(), 4096L));
474 if (byteBuffer
== null) {
475 throw new IllegalStateException("Failed to allocate memory"); //$NON-NLS-1$
477 /* Create a BitBuffer with this mapping and the trace byte order */
478 streamBitBuffer
= new BitBuffer(byteBuffer
, this.getByteOrder());
479 if (fPacketHeaderDecl
!= null) {
480 /* Read the packet header */
481 fPacketHeaderDef
= fPacketHeaderDecl
.createDefinition(this, ILexicalScope
.PACKET_HEADER
, streamBitBuffer
);
483 } catch (IOException e
) {
484 /* Shouldn't happen at this stage if every other check passed */
485 throw new CTFException(e
);
487 if (fPacketHeaderDef
!= null) {
488 validateMagicNumber(fPacketHeaderDef
);
490 validateUUID(fPacketHeaderDef
);
492 /* Read the stream ID */
493 IDefinition streamIDDef
= fPacketHeaderDef
.lookupDefinition("stream_id"); //$NON-NLS-1$
495 if (streamIDDef
instanceof IntegerDefinition
) {
496 /* This doubles as a null check */
497 long streamID
= ((IntegerDefinition
) streamIDDef
).getValue();
498 stream
= fStreams
.get(streamID
);
500 /* No stream_id in the packet header */
501 stream
= getStream(null);
505 /* No packet header, we suppose there is only one stream */
506 stream
= getStream(null);
509 if (stream
== null) {
510 throw new CTFException("Unexpected end of stream"); //$NON-NLS-1$
514 * Create the stream input and add a reference to the streamInput in the
517 stream
.addInput(new CTFStreamInput(stream
, streamFile
));
522 private void validateUUID(StructDefinition packetHeaderDef
) throws CTFException
{
523 IDefinition lookupDefinition
= packetHeaderDef
.lookupDefinition("uuid"); //$NON-NLS-1$
524 AbstractArrayDefinition uuidDef
= (AbstractArrayDefinition
) lookupDefinition
;
525 if (uuidDef
!= null) {
526 UUID otheruuid
= Utils
.getUUIDfromDefinition(uuidDef
);
527 if (!fUuid
.equals(otheruuid
)) {
528 throw new CTFException("UUID mismatch"); //$NON-NLS-1$
533 private static void validateMagicNumber(StructDefinition packetHeaderDef
) throws CTFException
{
534 IntegerDefinition magicDef
= (IntegerDefinition
) packetHeaderDef
.lookupDefinition(CTFStrings
.MAGIC
);
535 if (magicDef
!= null) {
536 int magic
= (int) magicDef
.getValue();
537 if (magic
!= Utils
.CTF_MAGIC
) {
538 throw new CTFException("CTF magic mismatch"); //$NON-NLS-1$
543 // ------------------------------------------------------------------------
545 // ------------------------------------------------------------------------
551 public ILexicalScope
getScopePath() {
552 return ILexicalScope
.TRACE
;
556 * Looks up a definition from packet
561 * @see org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope#lookupDefinition(String)
564 public Definition
lookupDefinition(String lookupPath
) {
565 if (lookupPath
.equals(ILexicalScope
.TRACE_PACKET_HEADER
.getPath())) {
566 return fPacketHeaderDef
;
571 // ------------------------------------------------------------------------
572 // Live trace reading
573 // ------------------------------------------------------------------------
576 * Add a new stream file to support new streams while the trace is being
580 * the file of the stream
581 * @throws CTFException
582 * A stream had an issue being read
584 public void addStreamFile(File streamFile
) throws CTFException
{
585 openStreamInput(streamFile
);
589 * Registers a new stream to the trace.
593 * @throws ParseException
594 * If there was some problem reading the metadata
596 public void addStream(CTFStream stream
) throws ParseException
{
598 * If there is already a stream without id (the null key), it must be
601 if (fStreams
.get(null) != null) {
602 throw new ParseException("Stream without id with multiple streams"); //$NON-NLS-1$
606 * If the stream we try to add has no key set, it must be the only one.
607 * Thus, if the streams container is not empty, it is not valid.
609 if ((!stream
.isIdSet()) && (!fStreams
.isEmpty())) {
610 throw new ParseException("Stream without id with multiple streams"); //$NON-NLS-1$
614 * If a stream with the same ID already exists, it is not valid.
616 CTFStream existingStream
= fStreams
.get(stream
.getId());
617 if (existingStream
!= null) {
618 throw new ParseException("Stream id already exists"); //$NON-NLS-1$
621 /* This stream is valid and has a unique id. */
622 fStreams
.put(stream
.getId(), stream
);
626 * Gets the Environment variables from the trace metadata (See CTF spec)
628 * @return The environment variables in the form of an unmodifiable map
631 public Map
<String
, String
> getEnvironment() {
632 return Collections
.unmodifiableMap(fEnvironment
);
636 * Add a variable to the environment variables
639 * the name of the variable
641 * the value of the variable
643 public void addEnvironmentVar(String varName
, String varValue
) {
644 fEnvironment
.put(varName
, varValue
);
648 * Add a clock to the clock list
651 * the name of the clock (full name with scope)
655 public void addClock(String nameValue
, CTFClock ctfClock
) {
656 fClocks
.put(nameValue
, ctfClock
);
660 * gets the clock with a specific name
663 * the name of the clock.
666 public CTFClock
getClock(String name
) {
667 return fClocks
.get(name
);
671 * gets the clock if there is only one. (this is 100% of the use cases as of
676 public final CTFClock
getClock() {
677 if (fSingleClock
!= null && fClocks
.size() == 1) {
680 if (fClocks
.size() == 1) {
681 fSingleClock
= fClocks
.get(fClocks
.keySet().iterator().next());
688 * gets the time offset of a clock with respect to UTC in nanoseconds
690 * @return the time offset of a clock with respect to UTC in nanoseconds
692 public final long getOffset() {
693 if (getClock() == null) {
696 return fSingleClock
.getClockOffset();
700 * gets the time offset of a clock with respect to UTC in nanoseconds
702 * @return the time offset of a clock with respect to UTC in nanoseconds
704 private double getTimeScale() {
705 if (getClock() == null) {
708 return fSingleClock
.getClockScale();
712 * Gets the current first packet start time
714 * @return the current start time
716 public long getCurrentStartTime() {
717 long currentStart
= Long
.MAX_VALUE
;
718 for (CTFStream stream
: fStreams
.values()) {
719 for (CTFStreamInput si
: stream
.getStreamInputs()) {
720 currentStart
= Math
.min(currentStart
, si
.getIndex().getElement(0).getTimestampBegin());
723 return timestampCyclesToNanos(currentStart
);
727 * Gets the current last packet end time
729 * @return the current end time
731 public long getCurrentEndTime() {
732 long currentEnd
= Long
.MIN_VALUE
;
733 for (CTFStream stream
: fStreams
.values()) {
734 for (CTFStreamInput si
: stream
.getStreamInputs()) {
735 currentEnd
= Math
.max(currentEnd
, si
.getTimestampEnd());
738 return timestampCyclesToNanos(currentEnd
);
742 * Does the trace need to time scale?
744 * @return if the trace is in ns or cycles.
746 private boolean clockNeedsScale() {
747 if (getClock() == null) {
750 return fSingleClock
.isClockScaled();
754 * the inverse clock for returning to a scale.
756 * @return 1.0 / scale
758 private double getInverseTimeScale() {
759 if (getClock() == null) {
762 return fSingleClock
.getClockAntiScale();
767 * clock cycles since boot
768 * @return time in nanoseconds UTC offset
770 public long timestampCyclesToNanos(long cycles
) {
771 long retVal
= cycles
+ getOffset();
773 * this fix is since quite often the offset will be > than 53 bits and
774 * therefore the conversion will be lossy
776 if (clockNeedsScale()) {
777 retVal
= (long) (retVal
* getTimeScale());
784 * time in nanoseconds UTC offset
785 * @return clock cycles since boot.
787 public long timestampNanoToCycles(long nanos
) {
790 * this fix is since quite often the offset will be > than 53 bits and
791 * therefore the conversion will be lossy
793 if (clockNeedsScale()) {
794 retVal
= (long) (nanos
* getInverseTimeScale());
798 return retVal
- getOffset();
805 * the event name of the callsite
807 * the name of the callsite function
809 * the ip of the callsite
811 * the filename of the callsite
813 * the line number of the callsite
815 public void addCallsite(String eventName
, String funcName
, long ip
,
816 String fileName
, long lineNumber
) {
817 final CTFCallsite cs
= new CTFCallsite(eventName
, funcName
, ip
,
818 fileName
, lineNumber
);
819 TreeSet
<CTFCallsite
> csl
= fCallsitesByName
.get(eventName
);
821 csl
= new TreeSet
<>(fCtfCallsiteComparator
);
822 fCallsitesByName
.put(eventName
, csl
);
827 fCallsitesByIP
.add(cs
);
831 * Gets the set of callsites associated to an event name. O(1)
835 * @return the callsite set can be empty
837 public TreeSet
<CTFCallsite
> getCallsiteCandidates(String eventName
) {
838 TreeSet
<CTFCallsite
> retVal
= fCallsitesByName
.get(eventName
);
839 if (retVal
== null) {
840 retVal
= new TreeSet
<>(fCtfCallsiteComparator
);
846 * The I'm feeling lucky of getCallsiteCandidates O(1)
850 * @return the first callsite that has that event name, can be null
852 public CTFCallsite
getCallsite(String eventName
) {
853 TreeSet
<CTFCallsite
> callsites
= fCallsitesByName
.get(eventName
);
854 if (callsites
!= null) {
855 return callsites
.first();
861 * Gets a callsite from the instruction pointer O(log(n))
864 * the instruction pointer to lookup
865 * @return the callsite just before that IP in the list remember the IP is
866 * backwards on X86, can be null if no callsite is before the IP.
868 public CTFCallsite
getCallsite(long ip
) {
869 CTFCallsite cs
= new CTFCallsite(null, null, ip
, null, 0L);
870 return fCallsitesByIP
.ceiling(cs
);
874 * Gets a callsite using the event name and instruction pointer O(log(n))
877 * the name of the event
879 * the instruction pointer
880 * @return the closest matching callsite, can be null
882 public CTFCallsite
getCallsite(String eventName
, long ip
) {
883 final TreeSet
<CTFCallsite
> candidates
= fCallsitesByName
.get(eventName
);
884 if (candidates
== null) {
887 final CTFCallsite dummyCs
= new CTFCallsite(null, null, ip
, null, -1);
888 final CTFCallsite callsite
= candidates
.ceiling(dummyCs
);
889 if (callsite
== null) {
890 return candidates
.floor(dummyCs
);
899 * the ID of the stream
901 * new file in the stream
902 * @throws CTFException
903 * The file must exist
905 public void addStream(long id
, File streamFile
) throws CTFException
{
906 CTFStream stream
= null;
907 final File file
= streamFile
;
909 throw new CTFException("cannot create a stream with no file"); //$NON-NLS-1$
911 if (fStreams
.containsKey(id
)) {
912 stream
= fStreams
.get(id
);
914 stream
= new CTFStream(this);
915 fStreams
.put(id
, stream
);
917 stream
.addInput(new CTFStreamInput(stream
, file
));
921 * Gets the current trace scope
923 * @return the current declaration scope
927 public DeclarationScope
getScope() {
932 class MetadataFileFilter
implements FileFilter
{
935 public boolean accept(File pathname
) {
936 if (pathname
.isDirectory()) {
939 if (pathname
.isHidden()) {
942 if (pathname
.getName().equals("metadata")) { //$NON-NLS-1$
950 class MetadataComparator
implements Comparator
<File
>, Serializable
{
952 private static final long serialVersionUID
= 1L;
955 public int compare(File o1
, File o2
) {
956 return o1
.getName().compareTo(o2
.getName());