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
.linuxtools
.ctf
.core
.trace
;
18 import java
.io
.FileFilter
;
19 import java
.io
.FileInputStream
;
20 import java
.io
.IOException
;
21 import java
.io
.Serializable
;
22 import java
.nio
.ByteOrder
;
23 import java
.nio
.MappedByteBuffer
;
24 import java
.nio
.channels
.FileChannel
;
25 import java
.nio
.channels
.FileChannel
.MapMode
;
26 import java
.util
.Arrays
;
27 import java
.util
.Collections
;
28 import java
.util
.Comparator
;
29 import java
.util
.HashMap
;
30 import java
.util
.Iterator
;
31 import java
.util
.LinkedList
;
32 import java
.util
.List
;
34 import java
.util
.Map
.Entry
;
36 import java
.util
.TreeSet
;
37 import java
.util
.UUID
;
39 import org
.eclipse
.linuxtools
.ctf
.core
.event
.CTFCallsite
;
40 import org
.eclipse
.linuxtools
.ctf
.core
.event
.CTFClock
;
41 import org
.eclipse
.linuxtools
.ctf
.core
.event
.EventDefinition
;
42 import org
.eclipse
.linuxtools
.ctf
.core
.event
.IEventDeclaration
;
43 import org
.eclipse
.linuxtools
.ctf
.core
.event
.io
.BitBuffer
;
44 import org
.eclipse
.linuxtools
.ctf
.core
.event
.types
.ArrayDefinition
;
45 import org
.eclipse
.linuxtools
.ctf
.core
.event
.types
.Definition
;
46 import org
.eclipse
.linuxtools
.ctf
.core
.event
.types
.IDefinitionScope
;
47 import org
.eclipse
.linuxtools
.ctf
.core
.event
.types
.IntegerDefinition
;
48 import org
.eclipse
.linuxtools
.ctf
.core
.event
.types
.StructDeclaration
;
49 import org
.eclipse
.linuxtools
.ctf
.core
.event
.types
.StructDefinition
;
50 import org
.eclipse
.linuxtools
.internal
.ctf
.core
.event
.CTFCallsiteComparator
;
51 import org
.eclipse
.linuxtools
.internal
.ctf
.core
.event
.metadata
.exceptions
.ParseException
;
54 * A CTF trace on the file system.
56 * Represents a trace on the filesystem. It is responsible of parsing the
57 * metadata, creating declarations data structures, indexing the event packets
58 * (in other words, all the work that can be shared between readers), but the
59 * actual reading of events is left to TraceReader.
61 * @author Matthew Khouzam
62 * @version $Revision: 1.0 $
64 public class CTFTrace
implements IDefinitionScope
{
66 @SuppressWarnings("nls")
68 public String
toString() {
69 /* Only for debugging, shouldn't be externalized */
70 return "CTFTrace [path=" + fPath
+ ", major=" + fMajor
+ ", minor="
71 + fMinor
+ ", uuid=" + fUuid
+ "]";
75 * The trace directory on the filesystem.
77 private final File fPath
;
80 * Major CTF version number
85 * Minor CTF version number
97 private ByteOrder fByteOrder
;
100 * Packet header structure declaration
102 private StructDeclaration fPacketHeaderDecl
= null;
105 * The clock of the trace
107 private CTFClock fSingleClock
;
110 * Packet header structure definition
112 * This is only used when opening the trace files, to read the first packet
113 * header and see if they are valid trace files.
115 private StructDefinition fPacketHeaderDef
;
118 * Collection of streams contained in the trace.
120 private final Map
<Long
, Stream
> fStreams
= new HashMap
<>();
123 * Collection of environment variables set by the tracer
125 private final Map
<String
, String
> fEnvironment
= new HashMap
<>();
128 * Collection of all the clocks in a system.
130 private final Map
<String
, CTFClock
> fClocks
= new HashMap
<>();
132 /** FileInputStreams to the streams */
133 private final List
<FileInputStream
> fFileInputStreams
= new LinkedList
<>();
135 /** Handlers for the metadata files */
136 private static final FileFilter METADATA_FILE_FILTER
= new MetadataFileFilter();
137 private static final Comparator
<File
> METADATA_COMPARATOR
= new MetadataComparator();
139 /** Callsite helpers */
140 private CTFCallsiteComparator fCtfCallsiteComparator
= new CTFCallsiteComparator();
142 private Map
<String
, TreeSet
<CTFCallsite
>> fCallsitesByName
= new HashMap
<>();
144 /** Callsite helpers */
145 private TreeSet
<CTFCallsite
> fCallsitesByIP
= new TreeSet
<>();
147 // ------------------------------------------------------------------------
149 // ------------------------------------------------------------------------
155 * Filesystem path of the trace directory
156 * @throws CTFReaderException
157 * If no CTF trace was found at the path
159 public CTFTrace(String path
) throws CTFReaderException
{
160 this(new File(path
));
168 * Filesystem path of the trace directory.
169 * @throws CTFReaderException
170 * If no CTF trace was found at the path
172 public CTFTrace(File path
) throws CTFReaderException
{
174 final Metadata metadata
= new Metadata(this);
176 /* Set up the internal containers for this trace */
177 if (!fPath
.exists()) {
178 throw new CTFReaderException("Trace (" + path
.getPath() + ") doesn't exist. Deleted or moved?"); //$NON-NLS-1$ //$NON-NLS-2$
181 if (!fPath
.isDirectory()) {
182 throw new CTFReaderException("Path must be a valid directory"); //$NON-NLS-1$
185 /* Open and parse the metadata file */
186 metadata
.parseFile();
192 * Streamed constructor
201 private void init() {
202 /* Create the definitions needed to read things from the files */
203 if (fPacketHeaderDecl
!= null) {
204 fPacketHeaderDef
= fPacketHeaderDecl
.createDefinition(this, "packet.header"); //$NON-NLS-1$
208 private void init(File path
) throws CTFReaderException
{
212 /* Open all the trace files */
214 /* List files not called metadata and not hidden. */
215 File
[] files
= path
.listFiles(METADATA_FILE_FILTER
);
216 Arrays
.sort(files
, METADATA_COMPARATOR
);
218 /* Try to open each file */
219 for (File streamFile
: files
) {
220 openStreamInput(streamFile
);
223 /* Create their index */
224 for (Stream stream
: getStreams()) {
225 Set
<StreamInput
> inputs
= stream
.getStreamInputs();
226 for (StreamInput s
: inputs
) {
237 public void dispose() {
238 for (FileInputStream fis
: fFileInputStreams
) {
242 } catch (IOException e
) {
243 // do nothing it's ok, we tried to close it.
247 // Invoke GC to release MappedByteBuffer objects (Java bug JDK-4724038)
251 // ------------------------------------------------------------------------
252 // Getters/Setters/Predicates
253 // ------------------------------------------------------------------------
256 * Gets an event declaration hash map for a given streamID
259 * The ID of the stream from which to read
260 * @return The Hash map with the event declarations
263 public Map
<Long
, IEventDeclaration
> getEvents(Long streamId
) {
264 return fStreams
.get(streamId
).getEvents();
268 * Gets an event Declaration hashmap for a given StreamInput
272 * @return an empty hashmap, please see deprecated
274 * @deprecated You should be using
275 * {@link StreamInputReader#getEventDefinitions()} instead.
278 public Map
<Long
, EventDefinition
> getEventDefs(StreamInput id
) {
279 return new HashMap
<>();
283 * Get an event by it's ID
286 * The ID of the stream from which to read
288 * the ID of the event
289 * @return the event declaration
292 public IEventDeclaration
getEventType(long streamId
, long id
) {
293 return getEvents(streamId
).get(id
);
297 * Method getStream gets the stream for a given id
300 * Long the id of the stream
301 * @return Stream the stream that we need
304 public Stream
getStream(Long id
) {
305 return fStreams
.get(id
);
309 * Method nbStreams gets the number of available streams
311 * @return int the number of streams
313 public int nbStreams() {
314 return fStreams
.size();
318 * Method setMajor sets the major version of the trace (DO NOT USE)
321 * long the major version
323 public void setMajor(long major
) {
328 * Method setMinor sets the minor version of the trace (DO NOT USE)
331 * long the minor version
333 public void setMinor(long minor
) {
338 * Method setUUID sets the UUID of a trace
343 public void setUUID(UUID uuid
) {
348 * Method setByteOrder sets the byte order
351 * ByteOrder of the trace, can be little-endian or big-endian
353 public void setByteOrder(ByteOrder byteOrder
) {
354 fByteOrder
= byteOrder
;
358 * Method setPacketHeader sets the packet header of a trace (DO NOT USE)
360 * @param packetHeader
361 * StructDeclaration the header in structdeclaration form
363 public void setPacketHeader(StructDeclaration packetHeader
) {
364 fPacketHeaderDecl
= packetHeader
;
368 * Method majorIsSet is the major version number set?
370 * @return boolean is the major set?
373 public boolean majorIsSet() {
374 return fMajor
!= null;
378 * Method minorIsSet. is the minor version number set?
380 * @return boolean is the minor set?
382 public boolean minorIsSet() {
383 return fMinor
!= null;
387 * Method UUIDIsSet is the UUID set?
389 * @return boolean is the UUID set?
392 public boolean uuidIsSet() {
393 return fUuid
!= null;
397 * Method byteOrderIsSet is the byteorder set?
399 * @return boolean is the byteorder set?
401 public boolean byteOrderIsSet() {
402 return fByteOrder
!= null;
406 * Method packetHeaderIsSet is the packet header set?
408 * @return boolean is the packet header set?
410 public boolean packetHeaderIsSet() {
411 return fPacketHeaderDecl
!= null;
415 * Method getUUID gets the trace UUID
417 * @return UUID gets the trace UUID
419 public UUID
getUUID() {
424 * Method getMajor gets the trace major version
426 * @return long gets the trace major version
428 public long getMajor() {
433 * Method getMinor gets the trace minor version
435 * @return long gets the trace minor version
437 public long getMinor() {
442 * Method getByteOrder gets the trace byte order
444 * @return ByteOrder gets the trace byte order
446 public final ByteOrder
getByteOrder() {
451 * Method getPacketHeader gets the trace packet header
453 * @return StructDeclaration gets the trace packet header
455 public StructDeclaration
getPacketHeader() {
456 return fPacketHeaderDecl
;
460 * Method getTraceDirectory gets the trace directory
462 * @return File the path in "File" format.
464 public File
getTraceDirectory() {
469 * Get all the streams as an iterable.
471 * @return Iterable<Stream> an iterable over streams.
474 public Iterable
<Stream
> getStreams() {
475 return fStreams
.values();
479 * Method getPath gets the path of the trace directory
481 * @return String the path of the trace directory, in string format.
482 * @see java.io.File#getPath()
485 public String
getPath() {
486 return (fPath
!= null) ? fPath
.getPath() : ""; //$NON-NLS-1$
489 // ------------------------------------------------------------------------
491 // ------------------------------------------------------------------------
493 private void addStream(StreamInput s
) {
498 Iterator
<Entry
<Long
, IEventDeclaration
>> it
= s
.getStream()
499 .getEvents().entrySet().iterator();
500 while (it
.hasNext()) {
501 Entry
<Long
, IEventDeclaration
> pairs
= it
.next();
502 Long eventNum
= pairs
.getKey();
503 IEventDeclaration eventDec
= pairs
.getValue();
504 getEvents(s
.getStream().getId()).put(eventNum
, eventDec
);
514 * Tries to open the given file, reads the first packet header of the file
515 * and check its validity. This will add a file to a stream as a streaminput
518 * A trace file in the trace directory.
520 * Which index in the class' streamFileChannel array this file
522 * @throws CTFReaderException
523 * if there is a file error
525 private Stream
openStreamInput(File streamFile
) throws CTFReaderException
{
526 MappedByteBuffer byteBuffer
;
527 BitBuffer streamBitBuffer
;
531 if (!streamFile
.canRead()) {
532 throw new CTFReaderException("Unreadable file : " //$NON-NLS-1$
533 + streamFile
.getPath());
536 FileInputStream fis
= null;
538 /* Open the file and get the FileChannel */
539 fis
= new FileInputStream(streamFile
);
540 fFileInputStreams
.add(fis
);
541 fc
= fis
.getChannel();
543 /* Map one memory page of 4 kiB */
544 byteBuffer
= fc
.map(MapMode
.READ_ONLY
, 0, (int) Math
.min(fc
.size(), 4096L));
545 } catch (IOException e
) {
547 fFileInputStreams
.remove(fis
);
549 /* Shouldn't happen at this stage if every other check passed */
550 throw new CTFReaderException(e
);
553 /* Create a BitBuffer with this mapping and the trace byte order */
554 streamBitBuffer
= new BitBuffer(byteBuffer
, this.getByteOrder());
556 if (fPacketHeaderDef
!= null) {
557 /* Read the packet header */
558 fPacketHeaderDef
.read(streamBitBuffer
);
560 /* Check the magic number */
561 IntegerDefinition magicDef
= (IntegerDefinition
) fPacketHeaderDef
562 .lookupDefinition("magic"); //$NON-NLS-1$
563 int magic
= (int) magicDef
.getValue();
564 if (magic
!= Utils
.CTF_MAGIC
) {
565 throw new CTFReaderException("CTF magic mismatch"); //$NON-NLS-1$
569 ArrayDefinition uuidDef
= (ArrayDefinition
) fPacketHeaderDef
570 .lookupDefinition("uuid"); //$NON-NLS-1$
571 if (uuidDef
!= null) {
572 byte[] uuidArray
= new byte[Utils
.UUID_LEN
];
574 for (int i
= 0; i
< Utils
.UUID_LEN
; i
++) {
575 IntegerDefinition uuidByteDef
= (IntegerDefinition
) uuidDef
577 uuidArray
[i
] = (byte) uuidByteDef
.getValue();
580 UUID otheruuid
= Utils
.makeUUID(uuidArray
);
582 if (!fUuid
.equals(otheruuid
)) {
583 throw new CTFReaderException("UUID mismatch"); //$NON-NLS-1$
587 /* Read the stream ID */
588 Definition streamIDDef
= fPacketHeaderDef
.lookupDefinition("stream_id"); //$NON-NLS-1$
590 if (streamIDDef
instanceof IntegerDefinition
) { // this doubles as a
592 long streamID
= ((IntegerDefinition
) streamIDDef
).getValue();
593 stream
= fStreams
.get(streamID
);
595 /* No stream_id in the packet header */
596 stream
= fStreams
.get(null);
600 /* No packet header, we suppose there is only one stream */
601 stream
= fStreams
.get(null);
604 if (stream
== null) {
605 throw new CTFReaderException("Unexpected end of stream"); //$NON-NLS-1$
608 /* Create the stream input */
609 StreamInput streamInput
= new StreamInput(stream
, fc
, streamFile
);
611 /* Add a reference to the streamInput in the stream */
612 stream
.addInput(streamInput
);
618 * Looks up a definition from packet
623 * @see org.eclipse.linuxtools.ctf.core.event.types.IDefinitionScope#lookupDefinition(String)
626 public Definition
lookupDefinition(String lookupPath
) {
627 if (lookupPath
.equals("trace.packet.header")) { //$NON-NLS-1$
628 return fPacketHeaderDef
;
634 * Add a new stream file to support new streams while the trace is being
638 * the file of the stream
639 * @throws CTFReaderException
640 * A stream had an issue being read
643 public void addStreamFile(File streamFile
) throws CTFReaderException
{
644 openStreamInput(streamFile
);
648 * Registers a new stream to the trace.
652 * @throws ParseException
653 * If there was some problem reading the metadata
656 public void addStream(Stream stream
) throws ParseException
{
659 * Init if not done before
664 * If there is already a stream without id (the null key), it must be
667 if (fStreams
.get(null) != null) {
668 throw new ParseException("Stream without id with multiple streams"); //$NON-NLS-1$
672 * If the stream we try to add has the null key, it must be the only
673 * one. Thus, if the streams container is not empty, it is not valid.
675 if ((stream
.getId() == null) && (fStreams
.size() != 0)) {
676 throw new ParseException("Stream without id with multiple streams"); //$NON-NLS-1$
680 * If a stream with the same ID already exists, it is not valid.
682 Stream existingStream
= fStreams
.get(stream
.getId());
683 if (existingStream
!= null) {
684 throw new ParseException("Stream id already exists"); //$NON-NLS-1$
687 /* This stream is valid and has a unique id. */
688 fStreams
.put(stream
.getId(), stream
);
692 * Gets the Environment variables from the trace metadata (See CTF spec)
694 * @return The environment variables in the form of an unmodifiable map
698 public Map
<String
, String
> getEnvironment() {
699 return Collections
.unmodifiableMap(fEnvironment
);
703 * Add a variable to the environment variables
706 * the name of the variable
708 * the value of the variable
710 public void addEnvironmentVar(String varName
, String varValue
) {
711 fEnvironment
.put(varName
, varValue
);
715 * Add a clock to the clock list
718 * the name of the clock (full name with scope)
722 public void addClock(String nameValue
, CTFClock ctfClock
) {
723 fClocks
.put(nameValue
, ctfClock
);
727 * gets the clock with a specific name
730 * the name of the clock.
733 public CTFClock
getClock(String name
) {
734 return fClocks
.get(name
);
738 * gets the clock if there is only one. (this is 100% of the use cases as of
743 public final CTFClock
getClock() {
744 if (fClocks
.size() == 1) {
745 fSingleClock
= fClocks
.get(fClocks
.keySet().iterator().next());
752 * gets the time offset of a clock with respect to UTC in nanoseconds
754 * @return the time offset of a clock with respect to UTC in nanoseconds
756 public final long getOffset() {
757 if (getClock() == null) {
760 return fSingleClock
.getClockOffset();
764 * gets the time offset of a clock with respect to UTC in nanoseconds
766 * @return the time offset of a clock with respect to UTC in nanoseconds
768 private double getTimeScale() {
769 if (getClock() == null) {
772 return fSingleClock
.getClockScale();
776 * Does the trace need to time scale?
778 * @return if the trace is in ns or cycles.
780 private boolean clockNeedsScale() {
781 if (getClock() == null) {
784 return fSingleClock
.isClockScaled();
788 * the inverse clock for returning to a scale.
790 * @return 1.0 / scale
792 private double getInverseTimeScale() {
793 if (getClock() == null) {
796 return fSingleClock
.getClockAntiScale();
801 * clock cycles since boot
802 * @return time in nanoseconds UTC offset
805 public long timestampCyclesToNanos(long cycles
) {
806 long retVal
= cycles
+ getOffset();
808 * this fix is since quite often the offset will be > than 53 bits and
809 * therefore the conversion will be lossy
811 if (clockNeedsScale()) {
812 retVal
= (long) (retVal
* getTimeScale());
819 * time in nanoseconds UTC offset
820 * @return clock cycles since boot.
823 public long timestampNanoToCycles(long nanos
) {
826 * this fix is since quite often the offset will be > than 53 bits and
827 * therefore the conversion will be lossy
829 if (clockNeedsScale()) {
830 retVal
= (long) (nanos
* getInverseTimeScale());
834 return retVal
- getOffset();
841 * the event name of the callsite
843 * the name of the callsite function
845 * the ip of the callsite
847 * the filename of the callsite
849 * the line number of the callsite
851 public void addCallsite(String eventName
, String funcName
, long ip
,
852 String fileName
, long lineNumber
) {
853 final CTFCallsite cs
= new CTFCallsite(eventName
, funcName
, ip
,
854 fileName
, lineNumber
);
855 TreeSet
<CTFCallsite
> csl
= fCallsitesByName
.get(eventName
);
857 csl
= new TreeSet
<>(fCtfCallsiteComparator
);
858 fCallsitesByName
.put(eventName
, csl
);
863 fCallsitesByIP
.add(cs
);
867 * Gets the set of callsites associated to an event name. O(1)
871 * @return the callsite set can be empty
874 public TreeSet
<CTFCallsite
> getCallsiteCandidates(String eventName
) {
875 TreeSet
<CTFCallsite
> retVal
= fCallsitesByName
.get(eventName
);
876 if (retVal
== null) {
877 retVal
= new TreeSet
<>(fCtfCallsiteComparator
);
883 * The I'm feeling lucky of getCallsiteCandidates O(1)
887 * @return the first callsite that has that event name, can be null
890 public CTFCallsite
getCallsite(String eventName
) {
891 TreeSet
<CTFCallsite
> callsites
= fCallsitesByName
.get(eventName
);
892 if (callsites
!= null) {
893 return callsites
.first();
899 * Gets a callsite from the instruction pointer O(log(n))
902 * the instruction pointer to lookup
903 * @return the callsite just before that IP in the list remember the IP is
904 * backwards on X86, can be null if no callsite is before the IP.
907 public CTFCallsite
getCallsite(long ip
) {
908 CTFCallsite cs
= new CTFCallsite(null, null, ip
, null, 0L);
909 return fCallsitesByIP
.ceiling(cs
);
913 * Gets a callsite using the event name and instruction pointer O(log(n))
916 * the name of the event
918 * the instruction pointer
919 * @return the closest matching callsite, can be null
921 public CTFCallsite
getCallsite(String eventName
, long ip
) {
922 final TreeSet
<CTFCallsite
> candidates
= fCallsitesByName
.get(eventName
);
923 final CTFCallsite dummyCs
= new CTFCallsite(null, null, ip
, null, -1);
924 final CTFCallsite callsite
= candidates
.ceiling(dummyCs
);
925 if (callsite
== null) {
926 return candidates
.floor(dummyCs
);
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());