1 /*!
2  * \file       ocsd_dcd_tree.h
3  * \brief      OpenCSD : Trace Decode Tree.
4  *
5  * \copyright  Copyright (c) 2015, ARM Limited. All Rights Reserved.
6  */
7 
8 
9 /*
10  * Redistribution and use in source and binary forms, with or without modification,
11  * are permitted provided that the following conditions are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright notice,
14  * this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright notice,
17  * this list of conditions and the following disclaimer in the documentation
18  * and/or other materials provided with the distribution.
19  *
20  * 3. Neither the name of the copyright holder nor the names of its contributors
21  * may be used to endorse or promote products derived from this software without
22  * specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
26  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27  * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
28  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
29  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
31  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 #ifndef ARM_OCSD_DCD_TREE_H_INCLUDED
37 #define ARM_OCSD_DCD_TREE_H_INCLUDED
38 
39 #include <vector>
40 #include <list>
41 
42 #include "opencsd.h"
43 #include "ocsd_dcd_tree_elem.h"
44 
45 /** @defgroup dcd_tree OpenCSD Library : Trace Decode Tree.
46     @brief Create a multi source decode tree for a single trace capture buffer.
47 
48     Use to create a connected set of decoder objects to decode a trace buffer.
49     There may be multiple trace sources within the capture buffer.
50 
51 @{*/
52 
53 /*!
54  * @class DecodeTree
55  * @brief Class to manage the decoding of data from a single trace sink .
56  *
57  *  Provides functionality to build a tree of decode objects capable of decoding
58  *  multiple trace sources within a single trace sink (capture buffer).
59  *
60  */
61 class DecodeTree : public ITrcDataIn
62 {
63 public:
64 /** @name Creation and Destruction
65 @{*/
66     DecodeTree();   //!< default constructor
67     ~DecodeTree();  //!< default destructor
68 
69     /*!
70      * @brief Create a decode tree.
71      * Automatically creates a trace frame deformatter if required and a default error log component.
72      *
73      * @param src_type : Data stream source type, can be CoreSight frame formatted trace, or single demuxed trace data stream,
74      * @param formatterCfgFlags : Configuration flags for trace de-formatter.
75      *
76      * @return DecodeTree * : pointer to the decode tree, 0 if creation failed.
77      */
78     static DecodeTree *CreateDecodeTree(const ocsd_dcd_tree_src_t src_type, const uint32_t formatterCfgFlags);
79 
80     /** @brief Destroy a decode tree */
81     static void DestroyDecodeTree(DecodeTree *p_dcd_tree);
82 
83 /** @}*/
84 
85 
86 /** @name Error and element Logging
87 @{*/
88     /** @brief The library default error logger */
89     static ocsdDefaultErrorLogger* getDefaultErrorLogger() { return &s_error_logger; };
90 
91     /** the current error logging interface in use */
92     static ITraceErrorLog *getCurrentErrorLogI() { return s_i_error_logger; };
93 
94     /** set an alternate error logging interface. */
95     static void setAlternateErrorLogger(ITraceErrorLog *p_error_logger);
96 
97     /** get the list of packet printers for this decode tree */
98     std::vector<ItemPrinter *> &getPrinterList() { return m_printer_list; };
99 
100     /** add a protocol packet printer */
101     ocsd_err_t addPacketPrinter(uint8_t CSID, bool bMonitor, ItemPrinter **ppPrinter);
102 
103     /** add a raw frame printer */
104     ocsd_err_t addRawFramePrinter(RawFramePrinter **ppPrinter, uint32_t flags);
105 
106     /** add a generic element output printer */
107     ocsd_err_t addGenElemPrinter(TrcGenericElementPrinter **ppPrinter);
108 
109 
110 
111 /** @}*/
112 
113 
114 /** @name Trace Data Path
115 @{*/
116     /** @brief Trace Data input interface (ITrcDataIn)
117 
118         Decode tree implements the data in interface : ITrcDataIn .
119         Captured raw trace data is passed into the deformatter and decoders via this method.
120     */
121     virtual ocsd_datapath_resp_t TraceDataIn( const ocsd_datapath_op_t op,
122                                                const ocsd_trc_index_t index,
123                                                const uint32_t dataBlockSize,
124                                                const uint8_t *pDataBlock,
125                                                uint32_t *numBytesProcessed);
126 
127     /*!
128      * @brief Decoded Trace output.
129      *
130      * Client trace analysis program attaches a generic trace element interface to
131      * receive the output from the trace decode operations.
132      *
133      * @param *i_gen_trace_elem : Pointer to the interface.
134      */
135     void setGenTraceElemOutI(ITrcGenElemIn *i_gen_trace_elem);
136 
137     /*! @brief Return the connected generic element interface */
138     ITrcGenElemIn *getGenTraceElemOutI() const { return m_i_gen_elem_out; };
139 
140 /** @}*/
141 
142 /** @name Decoder Management
143 @{*/
144 
145     /*!
146      * Creates a decoder that is registered with the library under the supplied name.
147      * createFlags determine if a full packet processor / packet decoder pair or
148      * packet processor only is created.
149      * Uses the supplied configuration structure.
150      *
151      * @param &decoderName : registered name of decoder
152      * @param createFlags :  Decoder creation options.
153      * @param *pConfig : Pointer to a valid configuration structure for the named decoder.
154      *
155      * @return ocsd_err_t  : Library error code or OCSD_OK if successful.
156      */
157     ocsd_err_t createDecoder(const std::string &decoderName, const int createFlags, const CSConfig *pConfig);
158 
159     /*  */
160     /*!
161      * Remove a decoder / packet processor attached to an Trace ID output on the frame de-mux.
162      *
163      * Once removed another decoder can be created that has a CSConfig using that ID.
164      *
165      * @param CSID : Trace ID to remove.
166      *
167      * @return ocsd_err_t  :  Library error code or OCSD_OK if successful.
168      */
169     ocsd_err_t removeDecoder(const uint8_t CSID);
170 
171 
172 /* get decoder elements currently in use  */
173 
174     /*!
175      * Find a decode tree element associated with a specific CoreSight trace ID.   *
176      */
177     DecodeTreeElement *getDecoderElement(const uint8_t CSID) const;
178     /* iterate decoder elements */
179 
180     /*!
181      * Decode tree iteration. Return the first tree element 0 if no elements avaiable.
182      *
183      * @param &elemID : CoreSight Trace ID associated with this element
184      */
185     DecodeTreeElement *getFirstElement(uint8_t &elemID);
186     /*!
187      * Return the next tree element - or 0 if no futher elements avaiable.
188      *
189      * @param &elemID : CoreSight Trace ID associated with this element
190      */
191     DecodeTreeElement *getNextElement(uint8_t &elemID);
192 
193 /* set key interfaces - attach / replace on any existing tree components */
194 
195     /*!
196      * Set an ARM instruction opcode decoder.
197      *
198      * @param *i_instr_decode : Pointer to the interface.
199      */
200     void setInstrDecoder(IInstrDecode *i_instr_decode);
201     /*!
202      * Set a target memory access interface - used to access program image memory for instruction
203      * trace decode.
204      *
205      * @param *i_mem_access : Pointer to the interface.
206      */
207     void setMemAccessI(ITargetMemAccess *i_mem_access);
208 
209 
210 /** @}*/
211 
212 /** @name Memory Access Mapper
213 
214     A memory mapper is used to organise a collection of memory accessor objects that contain the
215     memory images for different areas of traced instruction memory. These areas could be the executed
216     program and a set of loaded .so libraries for example - each of which would have code sections in
217     different memory locations.
218 
219     A memory accessor represents a snapshot of an area of memory as it appeared during trace capture,
220     for a given memory space. Memory spaces are described by the ocsd_mem_space_acc_t enum. The most
221     general memory space is OCSD_MEM_SPACE_ANY. This represents memory that can be secure or none-secure,
222     available at any exception level.
223 
224     The memory mapper will not allow two accessors to overlap in the same memory space.
225 
226     The trace decdoer will access memory with a memory space parameter that represents the current core
227     state - the mapper will find the closest memory space match for the address.
228 
229     e.g. if the core is accessing secure EL3, then the most specialised matching space will be accessed.
230     If an EL3 space matches that will be used, otherwise the any secure, and finally _ANY.
231 
232     It is no necessary for clients to register memory accessors for all spaces - _ANY will be sufficient
233     in many cases.
234 
235 
236 @{*/
237 
238     /*  */
239     /*!
240      * This creates a memory mapper within the decode tree.
241      *
242      * @param type : defaults to MEMACC_MAP_GLOBAL (only type available at present)
243      *
244      * @return ocsd_err_t  : Library error code or OCSD_OK if successful.
245      */
246     ocsd_err_t createMemAccMapper(memacc_mapper_t type = MEMACC_MAP_GLOBAL);
247 
248     /*!
249      * Get a pointer to the memory mapper. Allows a client to add memory accessors directly to the mapper.
250      * @return TrcMemAccMapper  : Pointer to the mapper.
251      */
252     TrcMemAccMapper *getMemAccMapper() const { return m_default_mapper; };
253 
254     /*!
255      * Set an external mapper rather than create a mapper in the decode tree.
256      * Setting this will also destroy any internal mapper that was previously created.
257      *
258      * @param pMapper : pointer to the mapper to add.
259      */
260     void setExternMemAccMapper(TrcMemAccMapper * pMapper);
261 
262     /*!
263      * Return true if a mapper has been set (internal or external
264      */
265     const bool hasMemAccMapper() const { return (bool)(m_default_mapper != 0); };
266 
267     void logMappedRanges();     //!< Log the mapped memory ranges to the default message logger.
268 
269 /** @}*/
270 
271 /** @name Memory Accessors
272   A memory accessor represents a snapshot of an area of memory as it appeared during trace capture.
273 
274   Memory spaces represent either common global memory, or Secure / none-secure and EL specific spaces.
275 
276 @{*/
277 
278     /*!
279      * Creates a memory accessor for a memory block in the supplied buffer and adds to the current mapper.
280      *
281      * @param address : Start address for the memory block in the memory map.
282      * @param mem_space : Memory space
283      * @param *p_mem_buffer : start of the buffer.
284      * @param mem_length : length of the buffer.
285      *
286      * @return ocsd_err_t  : Library error code or OCSD_OK if successful.
287      */
288     ocsd_err_t addBufferMemAcc(const ocsd_vaddr_t address, const ocsd_mem_space_acc_t mem_space, const uint8_t *p_mem_buffer, const uint32_t mem_length);
289 
290     /*!
291      * Creates a memory accessor for a memory block supplied as a contiguous binary data file, and adds to the current mapper.
292      *
293      * @param address : Start address for the memory block in the memory map.
294      * @param mem_space : Memory space
295      * @param &filepath : Path to the binary data file
296      *
297      * @return ocsd_err_t  : Library error code or OCSD_OK if successful.
298      */
299     ocsd_err_t addBinFileMemAcc(const ocsd_vaddr_t address, const ocsd_mem_space_acc_t mem_space, const std::string &filepath);
300 
301     /*!
302      * Creates a memory accessor for a memory block supplied as a one or more memory regions in a binary file.
303      * Region structures are created that describe the memory start address, the offset within the binary file
304      * for that address, and the length of the region. This accessor can be used to point to the code section
305      * in a program file for example.
306      *
307      * @param *region_array : array of valid memory regions in the file.
308      * @param num_regions : number of regions
309      * @param mem_space : Memory space
310      * @param &filepath : Path to the binary data file
311      *
312      * @return ocsd_err_t  : Library error code or OCSD_OK if successful.
313      */
314     ocsd_err_t addBinFileRegionMemAcc(const ocsd_file_mem_region_t *region_array, const int num_regions, const ocsd_mem_space_acc_t mem_space, const std::string &filepath);
315 
316     /*!
317      * This memory accessor allows the client to supply a callback function for the region
318      * defined by the start and end addresses. This can be used to supply a custom memory accessor,
319      * or to directly access memory if the decode is running live on a target system.
320      *
321      * @param st_address : start address of region.
322      * @param en_address : end address of region.
323      * @param mem_space : Memory space
324      * @param p_cb_func : Callback function
325      * @param *p_context : client supplied context information
326      *
327      * @return ocsd_err_t  : Library error code or OCSD_OK if successful.
328      */
329     ocsd_err_t addCallbackMemAcc(const ocsd_vaddr_t st_address, const ocsd_vaddr_t en_address, const ocsd_mem_space_acc_t mem_space, Fn_MemAcc_CB p_cb_func, const void *p_context);
330 
331     /*!
332      * Remove the memory accessor from the map, that begins at the given address, for the memory space provided.
333      *
334      * @param address : Start address of the memory accessor.
335      * @param mem_space : Memory space for the memory accessor.
336      *
337      * @return ocsd_err_t  : Library error code or OCSD_OK if successful.
338      */
339     ocsd_err_t removeMemAccByAddress(const ocsd_vaddr_t address, const ocsd_mem_space_acc_t mem_space);
340 
341 /** @}*/
342 
343 /** @name CoreSight Trace Frame De-mux
344 @{*/
345 
346     //! Get the Trace Frame de-mux.
347     TraceFormatterFrameDecoder *getFrameDeformatter() const { return m_frame_deformatter_root; };
348 
349 
350     /*! @brief ID filtering - sets the output filter on the trace deformatter.
351 
352         Only supplied IDs will be decoded.
353 
354         No effect if no decoder attached for the ID
355 
356         @param ids : Vector of CS Trace IDs
357     */
358     ocsd_err_t setIDFilter(std::vector<uint8_t> &ids);  // only supplied IDs will be decoded
359 
360     ocsd_err_t clearIDFilter(); //!< remove filter, all IDs will be decoded
361 
362 /** @}*/
363 
364 private:
365     bool initialise(const ocsd_dcd_tree_src_t type, uint32_t formatterCfgFlags);
366     const bool usingFormatter() const { return (bool)(m_dcd_tree_type ==  OCSD_TRC_SRC_FRAME_FORMATTED); };
367     void setSingleRoot(TrcPktProcI *pComp);
368     ocsd_err_t createDecodeElement(const uint8_t CSID);
369     void destroyDecodeElement(const uint8_t CSID);
370     void destroyMemAccMapper();
371 
372     ocsd_dcd_tree_src_t m_dcd_tree_type;
373 
374     IInstrDecode *m_i_instr_decode;
375     ITargetMemAccess *m_i_mem_access;
376     ITrcGenElemIn *m_i_gen_elem_out;    //!< Output interface for generic elements from decoder.
377 
378     ITrcDataIn* m_i_decoder_root;   /*!< root decoder object interface - either deformatter or single packet processor */
379 
380     TraceFormatterFrameDecoder *m_frame_deformatter_root;
381 
382     DecodeTreeElement *m_decode_elements[0x80];
383 
384     uint8_t m_decode_elem_iter;
385 
386     TrcMemAccMapper *m_default_mapper;  //!< the mem acc mapper to use
387     bool m_created_mapper;              //!< true if created by decode tree object
388 
389     std::vector<ItemPrinter *> m_printer_list;  //!< list of packet printers.
390 
391     /* global error logger  - all sources */
392     static ITraceErrorLog *s_i_error_logger;
393     static std::list<DecodeTree *> s_trace_dcd_trees;
394 
395     /**! default error logger */
396     static ocsdDefaultErrorLogger s_error_logger;
397 
398     /**! default instruction decoder */
399     static TrcIDecode s_instruction_decoder;
400 };
401 
402 /** @}*/
403 
404 #endif // ARM_OCSD_DCD_TREE_H_INCLUDED
405 
406 /* End of File ocsd_dcd_tree.h */
407