1 /*******************************************************************************
2 * Copyright (c) 2011, 2013 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 *******************************************************************************/
14 package org
.eclipse
.linuxtools
.ctf
.core
.trace
;
17 import java
.io
.FileFilter
;
18 import java
.io
.FileInputStream
;
19 import java
.io
.IOException
;
20 import java
.io
.Serializable
;
21 import java
.nio
.ByteOrder
;
22 import java
.nio
.MappedByteBuffer
;
23 import java
.nio
.channels
.FileChannel
;
24 import java
.nio
.channels
.FileChannel
.MapMode
;
25 import java
.util
.Arrays
;
26 import java
.util
.Collections
;
27 import java
.util
.Comparator
;
28 import java
.util
.HashMap
;
29 import java
.util
.Iterator
;
30 import java
.util
.LinkedList
;
31 import java
.util
.List
;
32 import java
.util
.ListIterator
;
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
.metadata
.exceptions
.ParseException
;
51 import org
.eclipse
.linuxtools
.internal
.ctf
.core
.trace
.StreamInputPacketIndex
;
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=" + path
+ ", major=" + major
+ ", minor="
71 + minor
+ ", uuid=" + uuid
+ "]";
75 * The trace directory on the filesystem.
77 private final File path
;
80 * Major CTF version number
85 * Minor CTF version number
97 private ByteOrder byteOrder
;
100 * Packet header structure declaration
102 private StructDeclaration packetHeaderDecl
= null;
105 * The clock of the trace
107 private CTFClock singleClock
;
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 packetHeaderDef
;
118 * Collection of streams contained in the trace.
120 private final Map
<Long
, Stream
> streams
= new HashMap
<Long
, Stream
>();
123 * Collection of environment variables set by the tracer
125 private final Map
<String
, String
> environment
= new HashMap
<String
, String
>();
128 * Collection of all the clocks in a system.
130 private final Map
<String
, CTFClock
> clocks
= new HashMap
<String
, CTFClock
>();
132 /** FileInputStreams to the streams */
133 private final List
<FileInputStream
> fileInputStreams
= new LinkedList
<FileInputStream
>();
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 /** map of all the event types */
140 private final Map
<Long
,HashMap
<Long
, IEventDeclaration
>> eventDecs
= new HashMap
<Long
, HashMap
<Long
,IEventDeclaration
>>();
142 /** map of all the indexes */
143 private final Map
<StreamInput
, StreamInputPacketIndex
> indexes
= new HashMap
<StreamInput
, StreamInputPacketIndex
>();
145 /** Callsite helpers */
146 private Map
<String
, LinkedList
<CTFCallsite
>> callsitesByName
= new HashMap
<String
, LinkedList
<CTFCallsite
>>();
148 /** Callsite helpers */
149 private TreeSet
<CTFCallsite
> callsitesByIP
= new TreeSet
<CTFCallsite
>();
153 // ------------------------------------------------------------------------
155 // ------------------------------------------------------------------------
161 * Filesystem path of the trace directory
162 * @throws CTFReaderException
163 * If no CTF trace was found at the path
165 public CTFTrace(String path
) throws CTFReaderException
{
166 this(new File(path
));
174 * Filesystem path of the trace directory.
175 * @throws CTFReaderException
176 * If no CTF trace was found at the path
178 public CTFTrace(File path
) throws CTFReaderException
{
180 final Metadata metadata
= new Metadata(this);
182 /* Set up the internal containers for this trace */
183 if (!this.path
.exists()) {
184 throw new CTFReaderException("Trace (" + path
.getPath() + ") doesn't exist. Deleted or moved?"); //$NON-NLS-1$ //$NON-NLS-2$
187 if (!this.path
.isDirectory()) {
188 throw new CTFReaderException("Path must be a valid directory"); //$NON-NLS-1$
191 /* Open and parse the metadata file */
194 /* Open all the trace files */
195 /* Create the definitions needed to read things from the files */
196 if (packetHeaderDecl
!= null) {
197 packetHeaderDef
= packetHeaderDecl
.createDefinition(this,
198 "packet.header"); //$NON-NLS-1$
201 /* List files not called metadata and not hidden. */
202 File
[] files
= path
.listFiles(METADATA_FILE_FILTER
);
203 Arrays
.sort(files
, METADATA_COMPARATOR
);
204 /* Try to open each file */
205 for (File streamFile
: files
) {
206 openStreamInput(streamFile
);
209 /* Create their index */
210 for (Map
.Entry
<Long
, Stream
> stream
: streams
.entrySet()) {
211 Set
<StreamInput
> inputs
= stream
.getValue().getStreamInputs();
212 for (StreamInput s
: inputs
) {
216 Iterator
<Entry
<Long
, IEventDeclaration
>> it
= s
.getStream()
217 .getEvents().entrySet().iterator();
218 while (it
.hasNext()) {
219 Entry
<Long
, IEventDeclaration
> pairs
= it
.next();
220 Long eventNum
= pairs
.getKey();
221 IEventDeclaration eventDec
= pairs
.getValue();
222 getEvents(s
.getStream().getId()).put(eventNum
, eventDec
);
237 public void dispose() {
238 for (FileInputStream fis
: fileInputStreams
) {
242 } catch (IOException e
) {
243 // do nothing it's ok, we tried to close it.
247 System
.gc(); // Invoke GC to release MappedByteBuffer objects (Java bug JDK-4724038)
250 // ------------------------------------------------------------------------
251 // Getters/Setters/Predicates
252 // ------------------------------------------------------------------------
255 * Gets an event declaration hash map for a given streamID
258 * The ID of the stream from which to read
259 * @return The Hash map with the event declarations
262 public Map
<Long
, IEventDeclaration
> getEvents(Long streamId
) {
263 return eventDecs
.get(streamId
);
267 * Gets an index for a given StreamInput
268 * @param id the StreamInput
271 StreamInputPacketIndex
getIndex(StreamInput id
){
272 if(! indexes
.containsKey(id
)){
273 indexes
.put(id
, new StreamInputPacketIndex());
275 return indexes
.get(id
);
280 * Gets an event Declaration hashmap for a given StreamInput
284 * @return an empty hashmap, please see deprecated
286 * @deprecated You should be using {@link StreamInputReader#getEventDefinitions()}
290 public Map
<Long
, EventDefinition
> getEventDefs(StreamInput id
) {
291 return new HashMap
<Long
, EventDefinition
>();
295 * Get an event by it's ID
298 * The ID of the stream from which to read
300 * the ID of the event
301 * @return the event declaration
304 public IEventDeclaration
getEventType(long streamId
, long id
) {
305 return getEvents(streamId
).get(id
);
309 * Method getStream gets the stream for a given id
312 * Long the id of the stream
313 * @return Stream the stream that we need
316 public Stream
getStream(Long id
) {
317 return streams
.get(id
);
321 * Method nbStreams gets the number of available streams
323 * @return int the number of streams
325 public int nbStreams() {
326 return streams
.size();
330 * Method setMajor sets the major version of the trace (DO NOT USE)
333 * long the major version
335 public void setMajor(long major
) {
340 * Method setMinor sets the minor version of the trace (DO NOT USE)
343 * long the minor version
345 public void setMinor(long minor
) {
350 * Method setUUID sets the UUID of a trace
355 public void setUUID(UUID uuid
) {
360 * Method setByteOrder sets the byte order
363 * ByteOrder of the trace, can be little-endian or big-endian
365 public void setByteOrder(ByteOrder byteOrder
) {
366 this.byteOrder
= byteOrder
;
370 * Method setPacketHeader sets the packet header of a trace (DO NOT USE)
372 * @param packetHeader
373 * StructDeclaration the header in structdeclaration form
375 public void setPacketHeader(StructDeclaration packetHeader
) {
376 this.packetHeaderDecl
= packetHeader
;
380 * Method majortIsSet is the major version number set?
382 * @return boolean is the major set?
384 public boolean majortIsSet() {
385 return major
!= null;
389 * Method minorIsSet. is the minor version number set?
391 * @return boolean is the minor set?
393 public boolean minorIsSet() {
394 return minor
!= null;
398 * Method UUIDIsSet is the UUID set?
400 * @return boolean is the UUID set?
403 public boolean uuidIsSet() {
408 * Method byteOrderIsSet is the byteorder set?
410 * @return boolean is the byteorder set?
412 public boolean byteOrderIsSet() {
413 return byteOrder
!= null;
417 * Method packetHeaderIsSet is the packet header set?
419 * @return boolean is the packet header set?
421 public boolean packetHeaderIsSet() {
422 return packetHeaderDecl
!= null;
426 * Method getUUID gets the trace UUID
428 * @return UUID gets the trace UUID
430 public UUID
getUUID() {
435 * Method getMajor gets the trace major version
437 * @return long gets the trace major version
439 public long getMajor() {
444 * Method getMinor gets the trace minor version
446 * @return long gets the trace minor version
448 public long getMinor() {
453 * Method getByteOrder gets the trace byte order
455 * @return ByteOrder gets the trace byte order
457 public final ByteOrder
getByteOrder() {
462 * Method getPacketHeader gets the trace packet header
464 * @return StructDeclaration gets the trace packet header
466 public StructDeclaration
getPacketHeader() {
467 return packetHeaderDecl
;
471 * Method getTraceDirectory gets the trace directory
473 * @return File the path in "File" format.
475 public File
getTraceDirectory() {
480 * Method getStreams get all the streams in a map format.
482 * @return Map<Long,Stream> a map of all the streams.
484 public Map
<Long
, Stream
> getStreams() {
489 * Method getPath gets the path of the trace directory
491 * @return String the path of the trace directory, in string format.
492 * @see java.io.File#getPath()
495 public String
getPath() {
496 return path
.getPath();
499 // ------------------------------------------------------------------------
501 // ------------------------------------------------------------------------
504 * Tries to open the given file, reads the first packet header of the file
505 * and check its validity.
508 * A trace file in the trace directory.
510 * Which index in the class' streamFileChannel array this file
512 * @throws CTFReaderException
514 private void openStreamInput(File streamFile
) throws CTFReaderException
{
515 MappedByteBuffer byteBuffer
;
516 BitBuffer streamBitBuffer
;
520 if (!streamFile
.canRead()) {
521 throw new CTFReaderException("Unreadable file : " //$NON-NLS-1$
522 + streamFile
.getPath());
526 /* Open the file and get the FileChannel */
527 FileInputStream fis
= new FileInputStream(streamFile
);
528 fileInputStreams
.add(fis
);
529 fc
= fis
.getChannel();
531 /* Map one memory page of 4 kiB */
532 byteBuffer
= fc
.map(MapMode
.READ_ONLY
, 0, Math
.min((int)fc
.size(), 4096));
533 } catch (IOException e
) {
534 /* Shouldn't happen at this stage if every other check passed */
535 throw new CTFReaderException(e
);
538 /* Create a BitBuffer with this mapping and the trace byte order */
539 streamBitBuffer
= new BitBuffer(byteBuffer
, this.getByteOrder());
541 if (packetHeaderDef
!= null) {
542 /* Read the packet header */
543 packetHeaderDef
.read(streamBitBuffer
);
545 /* Check the magic number */
546 IntegerDefinition magicDef
= (IntegerDefinition
) packetHeaderDef
547 .lookupDefinition("magic"); //$NON-NLS-1$
548 int magic
= (int) magicDef
.getValue();
549 if (magic
!= Utils
.CTF_MAGIC
) {
550 throw new CTFReaderException("CTF magic mismatch"); //$NON-NLS-1$
554 ArrayDefinition uuidDef
= (ArrayDefinition
) packetHeaderDef
555 .lookupDefinition("uuid"); //$NON-NLS-1$
556 if (uuidDef
!= null) {
557 byte[] uuidArray
= new byte[Utils
.UUID_LEN
];
559 for (int i
= 0; i
< Utils
.UUID_LEN
; i
++) {
560 IntegerDefinition uuidByteDef
= (IntegerDefinition
) uuidDef
562 uuidArray
[i
] = (byte) uuidByteDef
.getValue();
565 UUID otheruuid
= Utils
.makeUUID(uuidArray
);
567 if (!this.uuid
.equals(otheruuid
)) {
568 throw new CTFReaderException("UUID mismatch"); //$NON-NLS-1$
572 /* Read the stream ID */
573 Definition streamIDDef
= packetHeaderDef
.lookupDefinition("stream_id"); //$NON-NLS-1$
575 if (streamIDDef
instanceof IntegerDefinition
) { //this doubles as a null check
576 long streamID
= ((IntegerDefinition
) streamIDDef
).getValue();
577 stream
= streams
.get(streamID
);
579 /* No stream_id in the packet header */
580 stream
= streams
.get(null);
584 /* No packet header, we suppose there is only one stream */
585 stream
= streams
.get(null);
588 if (stream
== null) {
589 throw new CTFReaderException("Unexpected end of stream"); //$NON-NLS-1$
592 /* Create the stream input */
593 StreamInput streamInput
= new StreamInput(stream
, fc
, streamFile
);
595 /* Add a reference to the streamInput in the stream */
596 stream
.addInput(streamInput
);
600 * Looks up a definition from packet
605 * @see org.eclipse.linuxtools.ctf.core.event.types.IDefinitionScope#lookupDefinition(String)
608 public Definition
lookupDefinition(String lookupPath
) {
609 if (lookupPath
.equals("trace.packet.header")) { //$NON-NLS-1$
610 return packetHeaderDef
;
616 * Adds a new stream to the trace.
620 * @throws ParseException
621 * If there was some problem reading the metadata
624 public void addStream(Stream stream
) throws ParseException
{
627 * If there is already a stream without id (the null key), it must be
630 if (streams
.get(null) != null) {
631 throw new ParseException("Stream without id with multiple streams"); //$NON-NLS-1$
635 * If the stream we try to add has the null key, it must be the only
636 * one. Thus, if the streams container is not empty, it is not valid.
638 if ((stream
.getId() == null) && (streams
.size() != 0)) {
639 throw new ParseException("Stream without id with multiple streams"); //$NON-NLS-1$
642 /* If a stream with the same ID already exists, it is not valid. */
643 if (streams
.get(stream
.getId()) != null) {
644 throw new ParseException("Stream id already exists"); //$NON-NLS-1$
647 /* It should be ok now. */
648 streams
.put(stream
.getId(), stream
);
649 eventDecs
.put(stream
.getId(), new HashMap
<Long
,IEventDeclaration
>());
653 * gets the Environment variables from the trace metadata (See CTF spec)
654 * @return the environment variables in a map form (key value)
657 public Map
<String
, String
> getEnvironment() {
662 * Look up a specific environment variable
663 * @param key the key to look for
664 * @return the value of the variable, can be null.
666 public String
lookupEnvironment(String key
) {
667 return environment
.get(key
);
671 * Add a variable to the environment variables
672 * @param varName the name of the variable
673 * @param varValue the value of the variable
675 public void addEnvironmentVar(String varName
, String varValue
) {
676 environment
.put(varName
, varValue
);
680 * Add a clock to the clock list
681 * @param nameValue the name of the clock (full name with scope)
682 * @param ctfClock the clock
684 public void addClock(String nameValue
, CTFClock ctfClock
) {
685 clocks
.put(nameValue
, ctfClock
);
689 * gets the clock with a specific name
690 * @param name the name of the clock.
693 public CTFClock
getClock(String name
) {
694 return clocks
.get(name
);
701 * gets the clock if there is only one. (this is 100% of the use cases as of
706 public final CTFClock
getClock() {
707 if (clocks
.size() == 1) {
708 singleClock
= clocks
.get(clocks
.keySet().iterator().next());
715 * gets the time offset of a clock with respect to UTC in nanoseconds
717 * @return the time offset of a clock with respect to UTC in nanoseconds
719 public final long getOffset() {
720 if (getClock() == null) {
723 return singleClock
.getClockOffset();
727 * gets the time offset of a clock with respect to UTC in nanoseconds
729 * @return the time offset of a clock with respect to UTC in nanoseconds
731 private double getTimeScale() {
732 if (getClock() == null) {
735 return singleClock
.getClockScale();
739 * Does the trace need to time scale?
741 * @return if the trace is in ns or cycles.
743 private boolean clockNeedsScale() {
744 if (getClock() == null) {
747 return singleClock
.isClockScaled();
751 * the inverse clock for returning to a scale.
753 * @return 1.0 / scale
755 private double getInverseTimeScale() {
756 if (getClock() == null) {
759 return singleClock
.getClockAntiScale();
764 * clock cycles since boot
765 * @return time in nanoseconds UTC offset
768 public long timestampCyclesToNanos(long cycles
) {
769 long retVal
= cycles
+ getOffset();
771 * this fix is since quite often the offset will be > than 53 bits and
772 * therefore the conversion will be lossy
774 if (clockNeedsScale()) {
775 retVal
= (long) (retVal
* getTimeScale());
782 * time in nanoseconds UTC offset
783 * @return clock cycles since boot.
786 public long timestampNanoToCycles(long nanos
) {
789 * this fix is since quite often the offset will be > than 53 bits and
790 * therefore the conversion will be lossy
792 if (clockNeedsScale()) {
793 retVal
= (long) (nanos
* getInverseTimeScale());
797 return retVal
- getOffset();
801 * Does a given stream contain any events?
802 * @param id the stream ID
803 * @return true if the stream has events.
805 public boolean hasEvents(Long id
){
806 return eventDecs
.containsKey(id
);
810 * Add an event declaration map to the events map.
811 * @param id the id of a stream
812 * @return the hashmap containing events.
815 public Map
<Long
, IEventDeclaration
> createEvents(Long id
){
816 HashMap
<Long
, IEventDeclaration
> value
= eventDecs
.get(id
);
817 if( value
== null ) {
818 value
= new HashMap
<Long
, IEventDeclaration
>();
819 eventDecs
.put(id
, value
);
828 * the event name of the callsite
830 * the name of the callsite function
832 * the ip of the callsite
834 * the filename of the callsite
836 * the line number of the callsite
838 public void addCallsite(String eventName
, String funcName
, long ip
,
839 String fileName
, long lineNumber
) {
840 final CTFCallsite cs
= new CTFCallsite(eventName
, funcName
, ip
,
841 fileName
, lineNumber
);
842 LinkedList
<CTFCallsite
> csl
= callsitesByName
.get(eventName
);
844 csl
= new LinkedList
<CTFCallsite
>();
845 callsitesByName
.put(eventName
, csl
);
848 ListIterator
<CTFCallsite
> iter
= csl
.listIterator();
850 for (; index
< csl
.size(); index
++) {
851 if (iter
.next().compareTo(cs
) < 0) {
858 callsitesByIP
.add(cs
);
862 * Gets the list of callsites associated to an event name. O(1)
866 * @return the callsite list can be empty
869 public List
<CTFCallsite
> getCallsiteCandidates(String eventName
) {
870 LinkedList
<CTFCallsite
> retVal
= callsitesByName
.get(eventName
);
871 if( retVal
== null ) {
872 retVal
= new LinkedList
<CTFCallsite
>();
878 * The I'm feeling lucky of getCallsiteCandidates O(1)
882 * @return the first callsite that has that event name, can be null
885 public CTFCallsite
getCallsite(String eventName
) {
886 LinkedList
<CTFCallsite
> callsites
= callsitesByName
.get(eventName
);
887 if (callsites
!= null) {
888 return callsites
.getFirst();
894 * Gets a callsite from the instruction pointer O(log(n))
897 * the instruction pointer to lookup
898 * @return the callsite just before that IP in the list remember the IP is
899 * backwards on X86, can be null if no callsite is before the IP.
902 public CTFCallsite
getCallsite(long ip
) {
903 CTFCallsite cs
= new CTFCallsite(null, null, ip
, null, 0L);
904 return callsitesByIP
.ceiling(cs
);
908 * Gets a callsite using the event name and instruction pointer O(log(n))
911 * the name of the event
913 * the instruction pointer
914 * @return the closest matching callsite, can be null
916 public CTFCallsite
getCallsite(String eventName
, long ip
) {
917 final LinkedList
<CTFCallsite
> candidates
= callsitesByName
.get(eventName
);
918 final CTFCallsite dummyCs
= new CTFCallsite(null, null, ip
, null, -1);
919 final int pos
= Collections
.binarySearch(candidates
, dummyCs
)+1;
920 if( pos
>= candidates
.size()) {
923 return candidates
.get(pos
);
928 class MetadataFileFilter
implements FileFilter
{
931 public boolean accept(File pathname
) {
932 if (pathname
.isDirectory()) {
935 if (pathname
.isHidden()) {
938 if (pathname
.getName().equals("metadata")) { //$NON-NLS-1$
946 class MetadataComparator
implements Comparator
<File
>, Serializable
{
948 private static final long serialVersionUID
= 1L;
951 public int compare(File o1
, File o2
) {
952 return o1
.getName().compareTo(o2
.getName());