1 /*
2 * \file mem_buff_demo.cpp
3 * \brief OpenCSD: using the library with memory buffers for data.
4 *
5 * \copyright Copyright (c) 2018, ARM Limited. All Rights Reserved.
6 */
7
8 /*
9 * Redistribution and use in source and binary forms, with or without modification,
10 * are permitted provided that the following conditions are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright notice,
13 * this list of conditions and the following disclaimer.
14 *
15 * 2. Redistributions in binary form must reproduce the above copyright notice,
16 * this list of conditions and the following disclaimer in the documentation
17 * and/or other materials provided with the distribution.
18 *
19 * 3. Neither the name of the copyright holder nor the names of its contributors
20 * may be used to endorse or promote products derived from this software without
21 * specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
25 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26 * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
27 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
28 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
30 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
32 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 */
34
35 /* Example showing techniques to drive library using only memory buffers as input data
36 * and image data, avoiding file i/o in main processing routines. (File I/O used to
37 * initially populate buffers but this can be replaced if data is generated by a client
38 * environment running live.)
39 */
40
41 #include <cstdio>
42 #include <string>
43 #include <iostream>
44 #include <sstream>
45 #include <cstring>
46
47 #include "opencsd.h" // the library
48
49 // uncomment below to use callback function for program memory image
50 // #define EXAMPLE_USE_MEM_CALLBACK
51
52 /* Input trace buffer */
53 static uint8_t *input_trace_data = 0;
54 static uint32_t input_trace_data_size = 0;
55
56 /* program memory image for decode */
57 static uint8_t *program_image_buffer = 0; // buffer for image data.
58 static uint32_t program_image_size = 0; // size of program image data.
59 static ocsd_vaddr_t program_image_address = 0; // load address on target of program image.
60
61 /* a message logger to pass to the error logger / decoder. */
62 static ocsdMsgLogger logger;
63
64 /* logger callback function - print out error strings */
65 class logCallback : public ocsdMsgLogStrOutI
66 {
67 public:
logCallback()68 logCallback() {};
~logCallback()69 virtual ~logCallback() {};
printOutStr(const std::string & outStr)70 virtual void printOutStr(const std::string &outStr)
71 {
72 std::cout << outStr.c_str();
73 }
74 };
75 static logCallback logCB;
76
77 /* Decode tree is the main decoder framework - contains the frame unpacker,
78 packet and trace stream decoders, plus memory image references */
79 static DecodeTree *pDecoder = 0;
80
81 /* an error logger - Decode tree registers all components with the error logger
82 so that errors can be correctly attributed and printed if required
83 */
84 static ocsdDefaultErrorLogger err_log;
85
86 /* callbacks used by the library */
87 #ifdef EXAMPLE_USE_MEM_CALLBACK
88 // program memory image callback definition
89 uint32_t mem_access_callback_fn(const void *p_context, const ocsd_vaddr_t address, const ocsd_mem_space_acc_t mem_space, const uint32_t reqBytes, uint8_t *byteBuffer);
90 #endif
91
92 // callback for the decoder output elements
93 class DecoderOutputProcessor : public ITrcGenElemIn
94 {
95 public:
DecoderOutputProcessor()96 DecoderOutputProcessor() {};
~DecoderOutputProcessor()97 virtual ~DecoderOutputProcessor() {};
98
TraceElemIn(const ocsd_trc_index_t index_sop,const uint8_t trc_chan_id,const OcsdTraceElement & elem)99 virtual ocsd_datapath_resp_t TraceElemIn(const ocsd_trc_index_t index_sop,
100 const uint8_t trc_chan_id,
101 const OcsdTraceElement &elem)
102 {
103 // must fully process or make a copy of data in here.
104 // element reference only valid for scope of call.
105
106 // for the example program we will stringise and print -
107 // but this is a client program implmentation dependent.
108 std::string elemStr;
109 std::ostringstream oss;
110 oss << "Idx:" << index_sop << "; ID:" << std::hex << (uint32_t)trc_chan_id << "; ";
111 elem.toString(elemStr);
112 oss << elemStr << std::endl;
113 logger.LogMsg(oss.str());
114 return OCSD_RESP_CONT;
115 }
116 };
117 static DecoderOutputProcessor output;
118
119 /* for test purposes we are initialising from files, but this could be generated test data as
120 part of a larger program and / or compiled in memory images.
121
122 We have hardcoded in one of the snapshots supplied with the library
123 */
initDataBuffers()124 static int initDataBuffers()
125 {
126 FILE *fp;
127 std::string filename;
128 long size;
129
130 /* the file names to create the data buffers */
131 #ifdef _WIN32
132 static const char *default_base_snapshot_path = "..\\..\\..\\snapshots";
133 static const char *juno_snapshot = "\\juno_r1_1\\";
134 #else
135 static const char *default_base_snapshot_path = "../../../snapshots";
136 static const char *juno_snapshot = "/juno_r1_1/";
137 #endif
138
139 /* trace data and memory file dump names and values - taken from snapshot metadata */
140 static const char *trace_data_filename = "cstrace.bin";
141 static const char *memory_dump_filename = "kernel_dump.bin";
142 static ocsd_vaddr_t mem_dump_address = 0xFFFFFFC000081000;
143
144 /* load up the trace data */
145 filename = default_base_snapshot_path;
146 filename += (std::string)juno_snapshot;
147 filename += (std::string)trace_data_filename;
148
149 fp = fopen(filename.c_str(), "rb");
150 if (!fp)
151 return OCSD_ERR_FILE_ERROR;
152 fseek(fp, 0, SEEK_END);
153 size = ftell(fp);
154 input_trace_data_size = (uint32_t)size;
155 input_trace_data = new (std::nothrow) uint8_t[input_trace_data_size];
156 if (!input_trace_data) {
157 fclose(fp);
158 return OCSD_ERR_MEM;
159 }
160 rewind(fp);
161 fread(input_trace_data, 1, input_trace_data_size, fp);
162 fclose(fp);
163
164 /* load up a memory image */
165 filename = default_base_snapshot_path;
166 filename += (std::string)juno_snapshot;
167 filename += (std::string)memory_dump_filename;
168
169 fp = fopen(filename.c_str(), "rb");
170 if (!fp)
171 return OCSD_ERR_FILE_ERROR;
172 fseek(fp, 0, SEEK_END);
173 size = ftell(fp);
174 program_image_size = (uint32_t)size;
175 program_image_buffer = new (std::nothrow) uint8_t[program_image_size];
176 if (!program_image_buffer) {
177 fclose(fp);
178 return OCSD_ERR_MEM;
179 }
180 rewind(fp);
181 fread(program_image_buffer, 1, program_image_size, fp);
182 fclose(fp);
183 program_image_address = mem_dump_address;
184 return OCSD_OK;
185 }
186
createETMv4StreamDecoder()187 static ocsd_err_t createETMv4StreamDecoder()
188 {
189 ocsd_etmv4_cfg trace_config;
190 ocsd_err_t err = OCSD_OK;
191 EtmV4Config *pCfg = 0;
192
193 /*
194 * populate the ETMv4 configuration structure with
195 * hard coded values from snapshot .ini files.
196 */
197
198 trace_config.arch_ver = ARCH_V8;
199 trace_config.core_prof = profile_CortexA;
200
201 trace_config.reg_configr = 0x000000C1;
202 trace_config.reg_traceidr = 0x00000010; /* this is the trace ID -> 0x10, change this to analyse other streams in snapshot.*/
203 trace_config.reg_idr0 = 0x28000EA1;
204 trace_config.reg_idr1 = 0x4100F403;
205 trace_config.reg_idr2 = 0x00000488;
206 trace_config.reg_idr8 = 0x0;
207 trace_config.reg_idr9 = 0x0;
208 trace_config.reg_idr10 = 0x0;
209 trace_config.reg_idr11 = 0x0;
210 trace_config.reg_idr12 = 0x0;
211 trace_config.reg_idr13 = 0x0;
212
213 pCfg = new (std::nothrow) EtmV4Config(&trace_config);
214 if (!pCfg)
215 return OCSD_ERR_MEM;
216
217 err = pDecoder->createDecoder(OCSD_BUILTIN_DCD_ETMV4I, /* etm v4 decoder */
218 OCSD_CREATE_FLG_FULL_DECODER, /* full trace decode */
219 pCfg);
220 delete pCfg;
221 return err;
222 }
223
224 /* Create the decode tree and add the error logger, stream decoder, memory image data to it.
225 Also register the output callback that processes the decoded trace packets. */
initialiseDecoder()226 static ocsd_err_t initialiseDecoder()
227 {
228 ocsd_err_t ret = OCSD_OK;
229
230 /* use the creation function to get the type of decoder we want
231 either OCSD_TRC_SRC_SINGLE : single trace source - not frame formatted
232 OCSD_TRC_SRC_FRAME_FORMATTED :multi source - CoreSight trace frame
233 and set the config flags for operation
234 OCSD_DFRMTR_FRAME_MEM_ALIGN: input data mem aligned -> no syncs
235
236 For this test we create a decode that can unpack frames and is not expecting sync packets.
237 */
238 pDecoder = DecodeTree::CreateDecodeTree(OCSD_TRC_SRC_FRAME_FORMATTED, OCSD_DFRMTR_FRAME_MEM_ALIGN);
239 if (!pDecoder)
240 return OCSD_ERR_MEM;
241
242 /* set up decoder logging - the message logger for output, and the error logger for the library */
243 logger.setLogOpts(ocsdMsgLogger::OUT_STR_CB); /* no IO from the logger, just a string callback. */
244 logger.setStrOutFn(&logCB); /* set the callback - in this example it will go to stdio but this is up to the implementor. */
245
246 // for debugging - stdio and file
247 // logger.setLogOpts(ocsdMsgLogger::OUT_FILE | ocsdMsgLogger::OUT_STDOUT);
248
249 err_log.initErrorLogger(OCSD_ERR_SEV_INFO);
250 err_log.setOutputLogger(&logger); /* pass the output logger to the error logger. */
251
252 pDecoder->setAlternateErrorLogger(&err_log); /* pass the error logger to the decoder, do not use the library version. */
253
254 /* now set up the elements that the decoder needs */
255
256 /* we will decode one of the streams in this example
257 create a Full decode ETMv4 stream decoder */
258 ret = createETMv4StreamDecoder();
259 if (ret != OCSD_OK)
260 return ret;
261
262 /* as this has full decode we must supply a memory image. */
263
264 ret = pDecoder->createMemAccMapper(); // the mapper is needed to add code images to.
265 if (ret != OCSD_OK)
266 return ret;
267
268 #ifdef EXAMPLE_USE_MEM_CALLBACK
269 // in this example we have a single buffer so we demonstrate how to use a callback.
270 // we are passing the buffer pointer as context as we only have one buffer, but this
271 // could be a structure that is a list of memory image buffers. Context is entirely
272 // client defined.
273 // Always use OCSD_MEM_SPACE_ANY unless there is a reason to restrict the image to a specific
274 // memory space.
275 pDecoder->addCallbackMemAcc(program_image_address, program_image_address + program_image_size-1,
276 OCSD_MEM_SPACE_ANY,mem_access_callback_fn, program_image_buffer);
277 #else
278 // or we can use the built in memory buffer interface - split our one buffer into two to
279 // demonstrate the addition of multiple regions
280 ocsd_vaddr_t block1_st, block2_st;
281 uint32_t block1_sz, block2_sz;
282 uint8_t *p_block1, *p_block2;
283
284 // break our single buffer into 2 buffers for demo purposes
285 block1_sz = program_image_size / 2;
286 block1_sz &= ~0x3; // align
287 block2_sz = program_image_size - block1_sz;
288 block1_st = program_image_address; // loaded program memory start address of program
289 block2_st = program_image_address + block1_sz;
290 p_block1 = program_image_buffer;
291 p_block2 = program_image_buffer + block1_sz;
292
293 /* how to add 2 "separate" buffers to the decoder */
294 // Always use OCSD_MEM_SPACE_ANY unless there is a reason to restrict the image to a specific
295 // memory space.
296 ret = pDecoder->addBufferMemAcc(block1_st, OCSD_MEM_SPACE_ANY, p_block1, block1_sz);
297 if (ret != OCSD_OK)
298 return ret;
299
300 ret = pDecoder->addBufferMemAcc(block2_st, OCSD_MEM_SPACE_ANY, p_block2, block2_sz);
301 if (ret != OCSD_OK)
302 return ret;
303 #endif
304
305 /* finally we need to provide an output callback to recieve the decoded information */
306 pDecoder->setGenTraceElemOutI(&output);
307 return ret;
308 }
309
310 /* get rid of the objects we created */
destroyDecoder()311 static void destroyDecoder()
312 {
313 delete pDecoder;
314 delete [] input_trace_data;
315 delete [] program_image_buffer;
316 }
317
318 #ifdef EXAMPLE_USE_MEM_CALLBACK
319 /* if we set up to use a callback to access memory image then this is what will be called. */
320 /* In this case the client must do all the work in determining if the requested address is in the
321 memory area. */
mem_access_callback_fn(const void * p_context,const ocsd_vaddr_t address,const ocsd_mem_space_acc_t mem_space,const uint32_t reqBytes,uint8_t * byteBuffer)322 uint32_t mem_access_callback_fn(const void *p_context, const ocsd_vaddr_t address,
323 const ocsd_mem_space_acc_t mem_space, const uint32_t reqBytes, uint8_t *byteBuffer)
324 {
325 ocsd_vaddr_t buf_end_address = program_image_address + program_image_size - 1;
326 uint32_t read_bytes = reqBytes;
327
328 /* context should be our memory image buffer - if not return 0 bytes read */
329 if (p_context != program_image_buffer)
330 return 0;
331
332 /* not concerned with memory spaces - assume all global */
333 if ((address < program_image_address) || (address > buf_end_address))
334 return 0; // requested address not in our buffer.
335
336 // if requested bytes from address more than we have, only read to end of buffer
337 if ((address + reqBytes - 1) > buf_end_address)
338 read_bytes = (uint32_t)(buf_end_address - (address - 1));
339
340 // copy the requested data.
341 memcpy(byteBuffer, program_image_buffer + (address - program_image_address), read_bytes);
342
343 return read_bytes;
344 }
345 #endif
346
347 /* use the decoder to process the global trace data buffer */
processTraceData(uint32_t * bytes_done)348 static ocsd_datapath_resp_t processTraceData(uint32_t *bytes_done)
349 {
350 /* process in blocks of fixed size. */
351 #define DATA_CHUNK_SIZE 2048
352
353 ocsd_datapath_resp_t resp = OCSD_RESP_CONT;
354 uint32_t block_size, buff_offset, bytes_to_do = input_trace_data_size, bytes_processed;
355 ocsd_trc_index_t index = 0;
356
357 /* process the data in chunks, until either all done or
358 * error occurs.
359 */
360 while ((resp == OCSD_RESP_CONT) && (bytes_to_do))
361 {
362 /* size up a block of input data */
363 block_size = (bytes_to_do >= DATA_CHUNK_SIZE) ? DATA_CHUNK_SIZE : bytes_to_do;
364 buff_offset = input_trace_data_size - bytes_to_do;
365
366 /* push it through the decoder */
367 resp = pDecoder->TraceDataIn(OCSD_OP_DATA, index, block_size,
368 input_trace_data + buff_offset, &bytes_processed);
369
370 /* adjust counter per bytes processed */
371 bytes_to_do -= bytes_processed;
372 index += bytes_processed;
373 }
374
375 /* if all done then signal end of trace - flushes out any remaining data */
376 if (!bytes_to_do)
377 resp = pDecoder->TraceDataIn(OCSD_OP_EOT, 0, 0, 0, 0);
378
379 /* return amount processed */
380 *bytes_done = input_trace_data_size - bytes_to_do;
381 return resp;
382 }
383
384 /* main routine - init input data, decode, finish ... */
main(int argc,char * argv[])385 int main(int argc, char* argv[])
386 {
387 int ret = OCSD_OK;
388 ocsd_datapath_resp_t retd;
389 char msg[256];
390 uint32_t bytes_done;
391
392 /* initialise all the data needed for decode */
393 if ((ret = initDataBuffers()) != OCSD_OK)
394 {
395 logger.LogMsg("Failed to create trace data buffers\n");
396 return ret;
397 }
398 /* initialise a decoder object */
399 if ((ret = initialiseDecoder()) == OCSD_OK)
400 {
401 retd = processTraceData(&bytes_done);
402 if (!OCSD_DATA_RESP_IS_CONT(retd))
403 {
404 ret = OCSD_ERR_DATA_DECODE_FATAL;
405 logger.LogMsg("Processing failed with data error\n");
406 }
407
408 /* get rid of the decoder and print a brief result. */
409 destroyDecoder();
410 sprintf(msg, "Processed %u bytes out of %u\n", bytes_done, input_trace_data_size);
411 logger.LogMsg(msg);
412 }
413 else
414 logger.LogMsg("Failed to create decoder for trace processing\n");
415 return ret;
416 }
417