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 * 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=" + 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 /** Callsite helpers */
140 private CTFCallsiteComparator ctfCallsiteComparator
= new CTFCallsiteComparator();
142 private Map
<String
, TreeSet
<CTFCallsite
>> callsitesByName
= new HashMap
<String
, TreeSet
<CTFCallsite
>>();
144 /** Callsite helpers */
145 private TreeSet
<CTFCallsite
> callsitesByIP
= new TreeSet
<CTFCallsite
>();
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 (!this.path
.exists()) {
178 throw new CTFReaderException("Trace (" + path
.getPath() + ") doesn't exist. Deleted or moved?"); //$NON-NLS-1$ //$NON-NLS-2$
181 if (!this.path
.isDirectory()) {
182 throw new CTFReaderException("Path must be a valid directory"); //$NON-NLS-1$
185 /* Open and parse the metadata file */
188 /* Open all the trace files */
189 /* Create the definitions needed to read things from the files */
190 if (packetHeaderDecl
!= null) {
191 packetHeaderDef
= packetHeaderDecl
.createDefinition(this, "packet.header"); //$NON-NLS-1$
194 /* List files not called metadata and not hidden. */
195 File
[] files
= path
.listFiles(METADATA_FILE_FILTER
);
196 Arrays
.sort(files
, METADATA_COMPARATOR
);
197 /* Try to open each file */
198 for (File streamFile
: files
) {
199 openStreamInput(streamFile
);
202 /* Create their index */
203 for (Stream stream
: getStreams()) {
204 Set
<StreamInput
> inputs
= stream
.getStreamInputs();
205 for (StreamInput s
: inputs
) {
209 Iterator
<Entry
<Long
, IEventDeclaration
>> it
= s
.getStream()
210 .getEvents().entrySet().iterator();
211 while (it
.hasNext()) {
212 Entry
<Long
, IEventDeclaration
> pairs
= it
.next();
213 Long eventNum
= pairs
.getKey();
214 IEventDeclaration eventDec
= pairs
.getValue();
215 getEvents(s
.getStream().getId()).put(eventNum
, eventDec
);
231 public void dispose() {
232 for (FileInputStream fis
: fileInputStreams
) {
236 } catch (IOException e
) {
237 // do nothing it's ok, we tried to close it.
241 // Invoke GC to release MappedByteBuffer objects (Java bug JDK-4724038)
245 // ------------------------------------------------------------------------
246 // Getters/Setters/Predicates
247 // ------------------------------------------------------------------------
250 * Gets an event declaration hash map for a given streamID
253 * The ID of the stream from which to read
254 * @return The Hash map with the event declarations
257 public Map
<Long
, IEventDeclaration
> getEvents(Long streamId
) {
258 return streams
.get(streamId
).getEvents();
262 * Gets an event Declaration hashmap for a given StreamInput
266 * @return an empty hashmap, please see deprecated
268 * @deprecated You should be using
269 * {@link StreamInputReader#getEventDefinitions()} instead.
272 public Map
<Long
, EventDefinition
> getEventDefs(StreamInput id
) {
273 return new HashMap
<Long
, EventDefinition
>();
277 * Get an event by it's ID
280 * The ID of the stream from which to read
282 * the ID of the event
283 * @return the event declaration
286 public IEventDeclaration
getEventType(long streamId
, long id
) {
287 return getEvents(streamId
).get(id
);
291 * Method getStream gets the stream for a given id
294 * Long the id of the stream
295 * @return Stream the stream that we need
298 public Stream
getStream(Long id
) {
299 return streams
.get(id
);
303 * Method nbStreams gets the number of available streams
305 * @return int the number of streams
307 public int nbStreams() {
308 return streams
.size();
312 * Method setMajor sets the major version of the trace (DO NOT USE)
315 * long the major version
317 public void setMajor(long major
) {
322 * Method setMinor sets the minor version of the trace (DO NOT USE)
325 * long the minor version
327 public void setMinor(long minor
) {
332 * Method setUUID sets the UUID of a trace
337 public void setUUID(UUID uuid
) {
342 * Method setByteOrder sets the byte order
345 * ByteOrder of the trace, can be little-endian or big-endian
347 public void setByteOrder(ByteOrder byteOrder
) {
348 this.byteOrder
= byteOrder
;
352 * Method setPacketHeader sets the packet header of a trace (DO NOT USE)
354 * @param packetHeader
355 * StructDeclaration the header in structdeclaration form
357 public void setPacketHeader(StructDeclaration packetHeader
) {
358 this.packetHeaderDecl
= packetHeader
;
362 * Method majorIsSet is the major version number set?
364 * @return boolean is the major set?
367 public boolean majorIsSet() {
368 return major
!= null;
372 * Method minorIsSet. is the minor version number set?
374 * @return boolean is the minor set?
376 public boolean minorIsSet() {
377 return minor
!= null;
381 * Method UUIDIsSet is the UUID set?
383 * @return boolean is the UUID set?
386 public boolean uuidIsSet() {
391 * Method byteOrderIsSet is the byteorder set?
393 * @return boolean is the byteorder set?
395 public boolean byteOrderIsSet() {
396 return byteOrder
!= null;
400 * Method packetHeaderIsSet is the packet header set?
402 * @return boolean is the packet header set?
404 public boolean packetHeaderIsSet() {
405 return packetHeaderDecl
!= null;
409 * Method getUUID gets the trace UUID
411 * @return UUID gets the trace UUID
413 public UUID
getUUID() {
418 * Method getMajor gets the trace major version
420 * @return long gets the trace major version
422 public long getMajor() {
427 * Method getMinor gets the trace minor version
429 * @return long gets the trace minor version
431 public long getMinor() {
436 * Method getByteOrder gets the trace byte order
438 * @return ByteOrder gets the trace byte order
440 public final ByteOrder
getByteOrder() {
445 * Method getPacketHeader gets the trace packet header
447 * @return StructDeclaration gets the trace packet header
449 public StructDeclaration
getPacketHeader() {
450 return packetHeaderDecl
;
454 * Method getTraceDirectory gets the trace directory
456 * @return File the path in "File" format.
458 public File
getTraceDirectory() {
463 * Get all the streams as an iterable.
465 * @return Iterable<Stream> an iterable over streams.
467 public Iterable
<Stream
> getStreams() {
468 return streams
.values();
472 * Method getPath gets the path of the trace directory
474 * @return String the path of the trace directory, in string format.
475 * @see java.io.File#getPath()
478 public String
getPath() {
479 return path
.getPath();
482 // ------------------------------------------------------------------------
484 // ------------------------------------------------------------------------
487 * Tries to open the given file, reads the first packet header of the file
488 * and check its validity.
491 * A trace file in the trace directory.
493 * Which index in the class' streamFileChannel array this file
495 * @throws CTFReaderException
497 private void openStreamInput(File streamFile
) throws CTFReaderException
{
498 MappedByteBuffer byteBuffer
;
499 BitBuffer streamBitBuffer
;
503 if (!streamFile
.canRead()) {
504 throw new CTFReaderException("Unreadable file : " //$NON-NLS-1$
505 + streamFile
.getPath());
509 /* Open the file and get the FileChannel */
510 FileInputStream fis
= new FileInputStream(streamFile
);
511 fileInputStreams
.add(fis
);
512 fc
= fis
.getChannel();
514 /* Map one memory page of 4 kiB */
515 byteBuffer
= fc
.map(MapMode
.READ_ONLY
, 0, (int) Math
.min(fc
.size(), 4096L));
516 } catch (IOException e
) {
517 /* Shouldn't happen at this stage if every other check passed */
518 throw new CTFReaderException(e
);
521 /* Create a BitBuffer with this mapping and the trace byte order */
522 streamBitBuffer
= new BitBuffer(byteBuffer
, this.getByteOrder());
524 if (packetHeaderDef
!= null) {
525 /* Read the packet header */
526 packetHeaderDef
.read(streamBitBuffer
);
528 /* Check the magic number */
529 IntegerDefinition magicDef
= (IntegerDefinition
) packetHeaderDef
530 .lookupDefinition("magic"); //$NON-NLS-1$
531 int magic
= (int) magicDef
.getValue();
532 if (magic
!= Utils
.CTF_MAGIC
) {
533 throw new CTFReaderException("CTF magic mismatch"); //$NON-NLS-1$
537 ArrayDefinition uuidDef
= (ArrayDefinition
) packetHeaderDef
538 .lookupDefinition("uuid"); //$NON-NLS-1$
539 if (uuidDef
!= null) {
540 byte[] uuidArray
= new byte[Utils
.UUID_LEN
];
542 for (int i
= 0; i
< Utils
.UUID_LEN
; i
++) {
543 IntegerDefinition uuidByteDef
= (IntegerDefinition
) uuidDef
545 uuidArray
[i
] = (byte) uuidByteDef
.getValue();
548 UUID otheruuid
= Utils
.makeUUID(uuidArray
);
550 if (!this.uuid
.equals(otheruuid
)) {
551 throw new CTFReaderException("UUID mismatch"); //$NON-NLS-1$
555 /* Read the stream ID */
556 Definition streamIDDef
= packetHeaderDef
.lookupDefinition("stream_id"); //$NON-NLS-1$
558 if (streamIDDef
instanceof IntegerDefinition
) { // this doubles as a
560 long streamID
= ((IntegerDefinition
) streamIDDef
).getValue();
561 stream
= streams
.get(streamID
);
563 /* No stream_id in the packet header */
564 stream
= streams
.get(null);
568 /* No packet header, we suppose there is only one stream */
569 stream
= streams
.get(null);
572 if (stream
== null) {
573 throw new CTFReaderException("Unexpected end of stream"); //$NON-NLS-1$
576 /* Create the stream input */
577 StreamInput streamInput
= new StreamInput(stream
, fc
, streamFile
);
579 /* Add a reference to the streamInput in the stream */
580 stream
.addInput(streamInput
);
584 * Looks up a definition from packet
589 * @see org.eclipse.linuxtools.ctf.core.event.types.IDefinitionScope#lookupDefinition(String)
592 public Definition
lookupDefinition(String lookupPath
) {
593 if (lookupPath
.equals("trace.packet.header")) { //$NON-NLS-1$
594 return packetHeaderDef
;
600 * Adds a new stream to the trace.
604 * @throws ParseException
605 * If there was some problem reading the metadata
608 public void addStream(Stream stream
) throws ParseException
{
611 * If there is already a stream without id (the null key), it must be
614 if (streams
.get(null) != null) {
615 throw new ParseException("Stream without id with multiple streams"); //$NON-NLS-1$
619 * If the stream we try to add has the null key, it must be the only
620 * one. Thus, if the streams container is not empty, it is not valid.
622 if ((stream
.getId() == null) && (streams
.size() != 0)) {
623 throw new ParseException("Stream without id with multiple streams"); //$NON-NLS-1$
626 /* If a stream with the same ID already exists, it is not valid. */
627 if (streams
.get(stream
.getId()) != null) {
628 throw new ParseException("Stream id already exists"); //$NON-NLS-1$
631 /* This stream is valid and has a unique id. */
632 streams
.put(stream
.getId(), stream
);
636 * Gets the Environment variables from the trace metadata (See CTF spec)
638 * @return The environment variables in the form of an unmodifiable map
642 public Map
<String
, String
> getEnvironment() {
643 return Collections
.unmodifiableMap(environment
);
647 * Add a variable to the environment variables
650 * the name of the variable
652 * the value of the variable
654 public void addEnvironmentVar(String varName
, String varValue
) {
655 environment
.put(varName
, varValue
);
659 * Add a clock to the clock list
662 * the name of the clock (full name with scope)
666 public void addClock(String nameValue
, CTFClock ctfClock
) {
667 clocks
.put(nameValue
, ctfClock
);
671 * gets the clock with a specific name
674 * the name of the clock.
677 public CTFClock
getClock(String name
) {
678 return clocks
.get(name
);
682 * gets the clock if there is only one. (this is 100% of the use cases as of
687 public final CTFClock
getClock() {
688 if (clocks
.size() == 1) {
689 singleClock
= clocks
.get(clocks
.keySet().iterator().next());
696 * gets the time offset of a clock with respect to UTC in nanoseconds
698 * @return the time offset of a clock with respect to UTC in nanoseconds
700 public final long getOffset() {
701 if (getClock() == null) {
704 return singleClock
.getClockOffset();
708 * gets the time offset of a clock with respect to UTC in nanoseconds
710 * @return the time offset of a clock with respect to UTC in nanoseconds
712 private double getTimeScale() {
713 if (getClock() == null) {
716 return singleClock
.getClockScale();
720 * Does the trace need to time scale?
722 * @return if the trace is in ns or cycles.
724 private boolean clockNeedsScale() {
725 if (getClock() == null) {
728 return singleClock
.isClockScaled();
732 * the inverse clock for returning to a scale.
734 * @return 1.0 / scale
736 private double getInverseTimeScale() {
737 if (getClock() == null) {
740 return singleClock
.getClockAntiScale();
745 * clock cycles since boot
746 * @return time in nanoseconds UTC offset
749 public long timestampCyclesToNanos(long cycles
) {
750 long retVal
= cycles
+ getOffset();
752 * this fix is since quite often the offset will be > than 53 bits and
753 * therefore the conversion will be lossy
755 if (clockNeedsScale()) {
756 retVal
= (long) (retVal
* getTimeScale());
763 * time in nanoseconds UTC offset
764 * @return clock cycles since boot.
767 public long timestampNanoToCycles(long nanos
) {
770 * this fix is since quite often the offset will be > than 53 bits and
771 * therefore the conversion will be lossy
773 if (clockNeedsScale()) {
774 retVal
= (long) (nanos
* getInverseTimeScale());
778 return retVal
- getOffset();
785 * the event name of the callsite
787 * the name of the callsite function
789 * the ip of the callsite
791 * the filename of the callsite
793 * the line number of the callsite
795 public void addCallsite(String eventName
, String funcName
, long ip
,
796 String fileName
, long lineNumber
) {
797 final CTFCallsite cs
= new CTFCallsite(eventName
, funcName
, ip
,
798 fileName
, lineNumber
);
799 TreeSet
<CTFCallsite
> csl
= callsitesByName
.get(eventName
);
801 csl
= new TreeSet
<CTFCallsite
>(ctfCallsiteComparator
);
802 callsitesByName
.put(eventName
, csl
);
807 callsitesByIP
.add(cs
);
811 * Gets the set of callsites associated to an event name. O(1)
815 * @return the callsite set can be empty
818 public TreeSet
<CTFCallsite
> getCallsiteCandidates(String eventName
) {
819 TreeSet
<CTFCallsite
> retVal
= callsitesByName
.get(eventName
);
820 if (retVal
== null) {
821 retVal
= new TreeSet
<CTFCallsite
>(ctfCallsiteComparator
);
827 * The I'm feeling lucky of getCallsiteCandidates O(1)
831 * @return the first callsite that has that event name, can be null
834 public CTFCallsite
getCallsite(String eventName
) {
835 TreeSet
<CTFCallsite
> callsites
= callsitesByName
.get(eventName
);
836 if (callsites
!= null) {
837 return callsites
.first();
843 * Gets a callsite from the instruction pointer O(log(n))
846 * the instruction pointer to lookup
847 * @return the callsite just before that IP in the list remember the IP is
848 * backwards on X86, can be null if no callsite is before the IP.
851 public CTFCallsite
getCallsite(long ip
) {
852 CTFCallsite cs
= new CTFCallsite(null, null, ip
, null, 0L);
853 return callsitesByIP
.ceiling(cs
);
857 * Gets a callsite using the event name and instruction pointer O(log(n))
860 * the name of the event
862 * the instruction pointer
863 * @return the closest matching callsite, can be null
865 public CTFCallsite
getCallsite(String eventName
, long ip
) {
866 final TreeSet
<CTFCallsite
> candidates
= callsitesByName
.get(eventName
);
867 final CTFCallsite dummyCs
= new CTFCallsite(null, null, ip
, null, -1);
868 final CTFCallsite callsite
= candidates
.ceiling(dummyCs
);
869 if (callsite
== null) {
870 return candidates
.floor(dummyCs
);
876 class MetadataFileFilter
implements FileFilter
{
879 public boolean accept(File pathname
) {
880 if (pathname
.isDirectory()) {
883 if (pathname
.isHidden()) {
886 if (pathname
.getName().equals("metadata")) { //$NON-NLS-1$
894 class MetadataComparator
implements Comparator
<File
>, Serializable
{
896 private static final long serialVersionUID
= 1L;
899 public int compare(File o1
, File o2
) {
900 return o1
.getName().compareTo(o2
.getName());