hla/hla_interface: call HLA layout API close() on quit
[openocd.git] / src / target / target.c
1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
4 * *
5 * Copyright (C) 2007-2010 Øyvind Harboe *
6 * oyvind.harboe@zylin.com *
7 * *
8 * Copyright (C) 2008, Duane Ellis *
9 * openocd@duaneeellis.com *
10 * *
11 * Copyright (C) 2008 by Spencer Oliver *
12 * spen@spen-soft.co.uk *
13 * *
14 * Copyright (C) 2008 by Rick Altherr *
15 * kc8apf@kc8apf.net> *
16 * *
17 * Copyright (C) 2011 by Broadcom Corporation *
18 * Evan Hunter - ehunter@broadcom.com *
19 * *
20 * Copyright (C) ST-Ericsson SA 2011 *
21 * michel.jaouen@stericsson.com : smp minimum support *
22 * *
23 * Copyright (C) 2011 Andreas Fritiofson *
24 * andreas.fritiofson@gmail.com *
25 * *
26 * This program is free software; you can redistribute it and/or modify *
27 * it under the terms of the GNU General Public License as published by *
28 * the Free Software Foundation; either version 2 of the License, or *
29 * (at your option) any later version. *
30 * *
31 * This program is distributed in the hope that it will be useful, *
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
34 * GNU General Public License for more details. *
35 * *
36 * You should have received a copy of the GNU General Public License *
37 * along with this program; if not, write to the *
38 * Free Software Foundation, Inc., *
39 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
40 ***************************************************************************/
41
42 #ifdef HAVE_CONFIG_H
43 #include "config.h"
44 #endif
45
46 #include <helper/time_support.h>
47 #include <jtag/jtag.h>
48 #include <flash/nor/core.h>
49
50 #include "target.h"
51 #include "target_type.h"
52 #include "target_request.h"
53 #include "breakpoints.h"
54 #include "register.h"
55 #include "trace.h"
56 #include "image.h"
57 #include "rtos/rtos.h"
58 #include "transport/transport.h"
59
60 /* default halt wait timeout (ms) */
61 #define DEFAULT_HALT_TIMEOUT 5000
62
63 static int target_read_buffer_default(struct target *target, uint32_t address,
64 uint32_t count, uint8_t *buffer);
65 static int target_write_buffer_default(struct target *target, uint32_t address,
66 uint32_t count, const uint8_t *buffer);
67 static int target_array2mem(Jim_Interp *interp, struct target *target,
68 int argc, Jim_Obj * const *argv);
69 static int target_mem2array(Jim_Interp *interp, struct target *target,
70 int argc, Jim_Obj * const *argv);
71 static int target_register_user_commands(struct command_context *cmd_ctx);
72 static int target_get_gdb_fileio_info_default(struct target *target,
73 struct gdb_fileio_info *fileio_info);
74 static int target_gdb_fileio_end_default(struct target *target, int retcode,
75 int fileio_errno, bool ctrl_c);
76 static int target_profiling_default(struct target *target, uint32_t *samples,
77 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds);
78
79 /* targets */
80 extern struct target_type arm7tdmi_target;
81 extern struct target_type arm720t_target;
82 extern struct target_type arm9tdmi_target;
83 extern struct target_type arm920t_target;
84 extern struct target_type arm966e_target;
85 extern struct target_type arm946e_target;
86 extern struct target_type arm926ejs_target;
87 extern struct target_type fa526_target;
88 extern struct target_type feroceon_target;
89 extern struct target_type dragonite_target;
90 extern struct target_type xscale_target;
91 extern struct target_type cortexm_target;
92 extern struct target_type cortexa_target;
93 extern struct target_type cortexr4_target;
94 extern struct target_type arm11_target;
95 extern struct target_type mips_m4k_target;
96 extern struct target_type avr_target;
97 extern struct target_type dsp563xx_target;
98 extern struct target_type dsp5680xx_target;
99 extern struct target_type testee_target;
100 extern struct target_type avr32_ap7k_target;
101 extern struct target_type hla_target;
102 extern struct target_type nds32_v2_target;
103 extern struct target_type nds32_v3_target;
104 extern struct target_type nds32_v3m_target;
105 extern struct target_type or1k_target;
106 extern struct target_type quark_x10xx_target;
107
108 static struct target_type *target_types[] = {
109 &arm7tdmi_target,
110 &arm9tdmi_target,
111 &arm920t_target,
112 &arm720t_target,
113 &arm966e_target,
114 &arm946e_target,
115 &arm926ejs_target,
116 &fa526_target,
117 &feroceon_target,
118 &dragonite_target,
119 &xscale_target,
120 &cortexm_target,
121 &cortexa_target,
122 &cortexr4_target,
123 &arm11_target,
124 &mips_m4k_target,
125 &avr_target,
126 &dsp563xx_target,
127 &dsp5680xx_target,
128 &testee_target,
129 &avr32_ap7k_target,
130 &hla_target,
131 &nds32_v2_target,
132 &nds32_v3_target,
133 &nds32_v3m_target,
134 &or1k_target,
135 &quark_x10xx_target,
136 NULL,
137 };
138
139 struct target *all_targets;
140 static struct target_event_callback *target_event_callbacks;
141 static struct target_timer_callback *target_timer_callbacks;
142 LIST_HEAD(target_reset_callback_list);
143 static const int polling_interval = 100;
144
145 static const Jim_Nvp nvp_assert[] = {
146 { .name = "assert", NVP_ASSERT },
147 { .name = "deassert", NVP_DEASSERT },
148 { .name = "T", NVP_ASSERT },
149 { .name = "F", NVP_DEASSERT },
150 { .name = "t", NVP_ASSERT },
151 { .name = "f", NVP_DEASSERT },
152 { .name = NULL, .value = -1 }
153 };
154
155 static const Jim_Nvp nvp_error_target[] = {
156 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
157 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
158 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
159 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
160 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
161 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
162 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
163 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
164 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
165 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
166 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
167 { .value = -1, .name = NULL }
168 };
169
170 static const char *target_strerror_safe(int err)
171 {
172 const Jim_Nvp *n;
173
174 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
175 if (n->name == NULL)
176 return "unknown";
177 else
178 return n->name;
179 }
180
181 static const Jim_Nvp nvp_target_event[] = {
182
183 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
184 { .value = TARGET_EVENT_HALTED, .name = "halted" },
185 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
186 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
187 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
188
189 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
190 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
191
192 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
193 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
194 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
195 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
196 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
197 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
198 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
199 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
200 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
201 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
202 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
203 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
204
205 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
206 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
207
208 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
209 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
210
211 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
212 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
213
214 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
215 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
216
217 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
218 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
219
220 { .name = NULL, .value = -1 }
221 };
222
223 static const Jim_Nvp nvp_target_state[] = {
224 { .name = "unknown", .value = TARGET_UNKNOWN },
225 { .name = "running", .value = TARGET_RUNNING },
226 { .name = "halted", .value = TARGET_HALTED },
227 { .name = "reset", .value = TARGET_RESET },
228 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
229 { .name = NULL, .value = -1 },
230 };
231
232 static const Jim_Nvp nvp_target_debug_reason[] = {
233 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
234 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
235 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
236 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
237 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
238 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
239 { .name = "program-exit" , .value = DBG_REASON_EXIT },
240 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
241 { .name = NULL, .value = -1 },
242 };
243
244 static const Jim_Nvp nvp_target_endian[] = {
245 { .name = "big", .value = TARGET_BIG_ENDIAN },
246 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
247 { .name = "be", .value = TARGET_BIG_ENDIAN },
248 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
249 { .name = NULL, .value = -1 },
250 };
251
252 static const Jim_Nvp nvp_reset_modes[] = {
253 { .name = "unknown", .value = RESET_UNKNOWN },
254 { .name = "run" , .value = RESET_RUN },
255 { .name = "halt" , .value = RESET_HALT },
256 { .name = "init" , .value = RESET_INIT },
257 { .name = NULL , .value = -1 },
258 };
259
260 const char *debug_reason_name(struct target *t)
261 {
262 const char *cp;
263
264 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
265 t->debug_reason)->name;
266 if (!cp) {
267 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
268 cp = "(*BUG*unknown*BUG*)";
269 }
270 return cp;
271 }
272
273 const char *target_state_name(struct target *t)
274 {
275 const char *cp;
276 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
277 if (!cp) {
278 LOG_ERROR("Invalid target state: %d", (int)(t->state));
279 cp = "(*BUG*unknown*BUG*)";
280 }
281 return cp;
282 }
283
284 const char *target_event_name(enum target_event event)
285 {
286 const char *cp;
287 cp = Jim_Nvp_value2name_simple(nvp_target_event, event)->name;
288 if (!cp) {
289 LOG_ERROR("Invalid target event: %d", (int)(event));
290 cp = "(*BUG*unknown*BUG*)";
291 }
292 return cp;
293 }
294
295 const char *target_reset_mode_name(enum target_reset_mode reset_mode)
296 {
297 const char *cp;
298 cp = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode)->name;
299 if (!cp) {
300 LOG_ERROR("Invalid target reset mode: %d", (int)(reset_mode));
301 cp = "(*BUG*unknown*BUG*)";
302 }
303 return cp;
304 }
305
306 /* determine the number of the new target */
307 static int new_target_number(void)
308 {
309 struct target *t;
310 int x;
311
312 /* number is 0 based */
313 x = -1;
314 t = all_targets;
315 while (t) {
316 if (x < t->target_number)
317 x = t->target_number;
318 t = t->next;
319 }
320 return x + 1;
321 }
322
323 /* read a uint64_t from a buffer in target memory endianness */
324 uint64_t target_buffer_get_u64(struct target *target, const uint8_t *buffer)
325 {
326 if (target->endianness == TARGET_LITTLE_ENDIAN)
327 return le_to_h_u64(buffer);
328 else
329 return be_to_h_u64(buffer);
330 }
331
332 /* read a uint32_t from a buffer in target memory endianness */
333 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
334 {
335 if (target->endianness == TARGET_LITTLE_ENDIAN)
336 return le_to_h_u32(buffer);
337 else
338 return be_to_h_u32(buffer);
339 }
340
341 /* read a uint24_t from a buffer in target memory endianness */
342 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
343 {
344 if (target->endianness == TARGET_LITTLE_ENDIAN)
345 return le_to_h_u24(buffer);
346 else
347 return be_to_h_u24(buffer);
348 }
349
350 /* read a uint16_t from a buffer in target memory endianness */
351 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
352 {
353 if (target->endianness == TARGET_LITTLE_ENDIAN)
354 return le_to_h_u16(buffer);
355 else
356 return be_to_h_u16(buffer);
357 }
358
359 /* read a uint8_t from a buffer in target memory endianness */
360 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
361 {
362 return *buffer & 0x0ff;
363 }
364
365 /* write a uint64_t to a buffer in target memory endianness */
366 void target_buffer_set_u64(struct target *target, uint8_t *buffer, uint64_t value)
367 {
368 if (target->endianness == TARGET_LITTLE_ENDIAN)
369 h_u64_to_le(buffer, value);
370 else
371 h_u64_to_be(buffer, value);
372 }
373
374 /* write a uint32_t to a buffer in target memory endianness */
375 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
376 {
377 if (target->endianness == TARGET_LITTLE_ENDIAN)
378 h_u32_to_le(buffer, value);
379 else
380 h_u32_to_be(buffer, value);
381 }
382
383 /* write a uint24_t to a buffer in target memory endianness */
384 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
385 {
386 if (target->endianness == TARGET_LITTLE_ENDIAN)
387 h_u24_to_le(buffer, value);
388 else
389 h_u24_to_be(buffer, value);
390 }
391
392 /* write a uint16_t to a buffer in target memory endianness */
393 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
394 {
395 if (target->endianness == TARGET_LITTLE_ENDIAN)
396 h_u16_to_le(buffer, value);
397 else
398 h_u16_to_be(buffer, value);
399 }
400
401 /* write a uint8_t to a buffer in target memory endianness */
402 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
403 {
404 *buffer = value;
405 }
406
407 /* write a uint64_t array to a buffer in target memory endianness */
408 void target_buffer_get_u64_array(struct target *target, const uint8_t *buffer, uint32_t count, uint64_t *dstbuf)
409 {
410 uint32_t i;
411 for (i = 0; i < count; i++)
412 dstbuf[i] = target_buffer_get_u64(target, &buffer[i * 8]);
413 }
414
415 /* write a uint32_t array to a buffer in target memory endianness */
416 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
417 {
418 uint32_t i;
419 for (i = 0; i < count; i++)
420 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
421 }
422
423 /* write a uint16_t array to a buffer in target memory endianness */
424 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
425 {
426 uint32_t i;
427 for (i = 0; i < count; i++)
428 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
429 }
430
431 /* write a uint64_t array to a buffer in target memory endianness */
432 void target_buffer_set_u64_array(struct target *target, uint8_t *buffer, uint32_t count, const uint64_t *srcbuf)
433 {
434 uint32_t i;
435 for (i = 0; i < count; i++)
436 target_buffer_set_u64(target, &buffer[i * 8], srcbuf[i]);
437 }
438
439 /* write a uint32_t array to a buffer in target memory endianness */
440 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, const uint32_t *srcbuf)
441 {
442 uint32_t i;
443 for (i = 0; i < count; i++)
444 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
445 }
446
447 /* write a uint16_t array to a buffer in target memory endianness */
448 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, const uint16_t *srcbuf)
449 {
450 uint32_t i;
451 for (i = 0; i < count; i++)
452 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
453 }
454
455 /* return a pointer to a configured target; id is name or number */
456 struct target *get_target(const char *id)
457 {
458 struct target *target;
459
460 /* try as tcltarget name */
461 for (target = all_targets; target; target = target->next) {
462 if (target_name(target) == NULL)
463 continue;
464 if (strcmp(id, target_name(target)) == 0)
465 return target;
466 }
467
468 /* It's OK to remove this fallback sometime after August 2010 or so */
469
470 /* no match, try as number */
471 unsigned num;
472 if (parse_uint(id, &num) != ERROR_OK)
473 return NULL;
474
475 for (target = all_targets; target; target = target->next) {
476 if (target->target_number == (int)num) {
477 LOG_WARNING("use '%s' as target identifier, not '%u'",
478 target_name(target), num);
479 return target;
480 }
481 }
482
483 return NULL;
484 }
485
486 /* returns a pointer to the n-th configured target */
487 static struct target *get_target_by_num(int num)
488 {
489 struct target *target = all_targets;
490
491 while (target) {
492 if (target->target_number == num)
493 return target;
494 target = target->next;
495 }
496
497 return NULL;
498 }
499
500 struct target *get_current_target(struct command_context *cmd_ctx)
501 {
502 struct target *target = get_target_by_num(cmd_ctx->current_target);
503
504 if (target == NULL) {
505 LOG_ERROR("BUG: current_target out of bounds");
506 exit(-1);
507 }
508
509 return target;
510 }
511
512 int target_poll(struct target *target)
513 {
514 int retval;
515
516 /* We can't poll until after examine */
517 if (!target_was_examined(target)) {
518 /* Fail silently lest we pollute the log */
519 return ERROR_FAIL;
520 }
521
522 retval = target->type->poll(target);
523 if (retval != ERROR_OK)
524 return retval;
525
526 if (target->halt_issued) {
527 if (target->state == TARGET_HALTED)
528 target->halt_issued = false;
529 else {
530 long long t = timeval_ms() - target->halt_issued_time;
531 if (t > DEFAULT_HALT_TIMEOUT) {
532 target->halt_issued = false;
533 LOG_INFO("Halt timed out, wake up GDB.");
534 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
535 }
536 }
537 }
538
539 return ERROR_OK;
540 }
541
542 int target_halt(struct target *target)
543 {
544 int retval;
545 /* We can't poll until after examine */
546 if (!target_was_examined(target)) {
547 LOG_ERROR("Target not examined yet");
548 return ERROR_FAIL;
549 }
550
551 retval = target->type->halt(target);
552 if (retval != ERROR_OK)
553 return retval;
554
555 target->halt_issued = true;
556 target->halt_issued_time = timeval_ms();
557
558 return ERROR_OK;
559 }
560
561 /**
562 * Make the target (re)start executing using its saved execution
563 * context (possibly with some modifications).
564 *
565 * @param target Which target should start executing.
566 * @param current True to use the target's saved program counter instead
567 * of the address parameter
568 * @param address Optionally used as the program counter.
569 * @param handle_breakpoints True iff breakpoints at the resumption PC
570 * should be skipped. (For example, maybe execution was stopped by
571 * such a breakpoint, in which case it would be counterprodutive to
572 * let it re-trigger.
573 * @param debug_execution False if all working areas allocated by OpenOCD
574 * should be released and/or restored to their original contents.
575 * (This would for example be true to run some downloaded "helper"
576 * algorithm code, which resides in one such working buffer and uses
577 * another for data storage.)
578 *
579 * @todo Resolve the ambiguity about what the "debug_execution" flag
580 * signifies. For example, Target implementations don't agree on how
581 * it relates to invalidation of the register cache, or to whether
582 * breakpoints and watchpoints should be enabled. (It would seem wrong
583 * to enable breakpoints when running downloaded "helper" algorithms
584 * (debug_execution true), since the breakpoints would be set to match
585 * target firmware being debugged, not the helper algorithm.... and
586 * enabling them could cause such helpers to malfunction (for example,
587 * by overwriting data with a breakpoint instruction. On the other
588 * hand the infrastructure for running such helpers might use this
589 * procedure but rely on hardware breakpoint to detect termination.)
590 */
591 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
592 {
593 int retval;
594
595 /* We can't poll until after examine */
596 if (!target_was_examined(target)) {
597 LOG_ERROR("Target not examined yet");
598 return ERROR_FAIL;
599 }
600
601 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
602
603 /* note that resume *must* be asynchronous. The CPU can halt before
604 * we poll. The CPU can even halt at the current PC as a result of
605 * a software breakpoint being inserted by (a bug?) the application.
606 */
607 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
608 if (retval != ERROR_OK)
609 return retval;
610
611 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
612
613 return retval;
614 }
615
616 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
617 {
618 char buf[100];
619 int retval;
620 Jim_Nvp *n;
621 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
622 if (n->name == NULL) {
623 LOG_ERROR("invalid reset mode");
624 return ERROR_FAIL;
625 }
626
627 struct target *target;
628 for (target = all_targets; target; target = target->next)
629 target_call_reset_callbacks(target, reset_mode);
630
631 /* disable polling during reset to make reset event scripts
632 * more predictable, i.e. dr/irscan & pathmove in events will
633 * not have JTAG operations injected into the middle of a sequence.
634 */
635 bool save_poll = jtag_poll_get_enabled();
636
637 jtag_poll_set_enabled(false);
638
639 sprintf(buf, "ocd_process_reset %s", n->name);
640 retval = Jim_Eval(cmd_ctx->interp, buf);
641
642 jtag_poll_set_enabled(save_poll);
643
644 if (retval != JIM_OK) {
645 Jim_MakeErrorMessage(cmd_ctx->interp);
646 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
647 return ERROR_FAIL;
648 }
649
650 /* We want any events to be processed before the prompt */
651 retval = target_call_timer_callbacks_now();
652
653 for (target = all_targets; target; target = target->next) {
654 target->type->check_reset(target);
655 target->running_alg = false;
656 }
657
658 return retval;
659 }
660
661 static int identity_virt2phys(struct target *target,
662 uint32_t virtual, uint32_t *physical)
663 {
664 *physical = virtual;
665 return ERROR_OK;
666 }
667
668 static int no_mmu(struct target *target, int *enabled)
669 {
670 *enabled = 0;
671 return ERROR_OK;
672 }
673
674 static int default_examine(struct target *target)
675 {
676 target_set_examined(target);
677 return ERROR_OK;
678 }
679
680 /* no check by default */
681 static int default_check_reset(struct target *target)
682 {
683 return ERROR_OK;
684 }
685
686 int target_examine_one(struct target *target)
687 {
688 return target->type->examine(target);
689 }
690
691 static int jtag_enable_callback(enum jtag_event event, void *priv)
692 {
693 struct target *target = priv;
694
695 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
696 return ERROR_OK;
697
698 jtag_unregister_event_callback(jtag_enable_callback, target);
699
700 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
701
702 int retval = target_examine_one(target);
703 if (retval != ERROR_OK)
704 return retval;
705
706 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
707
708 return retval;
709 }
710
711 /* Targets that correctly implement init + examine, i.e.
712 * no communication with target during init:
713 *
714 * XScale
715 */
716 int target_examine(void)
717 {
718 int retval = ERROR_OK;
719 struct target *target;
720
721 for (target = all_targets; target; target = target->next) {
722 /* defer examination, but don't skip it */
723 if (!target->tap->enabled) {
724 jtag_register_event_callback(jtag_enable_callback,
725 target);
726 continue;
727 }
728
729 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
730
731 retval = target_examine_one(target);
732 if (retval != ERROR_OK)
733 return retval;
734
735 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
736 }
737 return retval;
738 }
739
740 const char *target_type_name(struct target *target)
741 {
742 return target->type->name;
743 }
744
745 static int target_soft_reset_halt(struct target *target)
746 {
747 if (!target_was_examined(target)) {
748 LOG_ERROR("Target not examined yet");
749 return ERROR_FAIL;
750 }
751 if (!target->type->soft_reset_halt) {
752 LOG_ERROR("Target %s does not support soft_reset_halt",
753 target_name(target));
754 return ERROR_FAIL;
755 }
756 return target->type->soft_reset_halt(target);
757 }
758
759 /**
760 * Downloads a target-specific native code algorithm to the target,
761 * and executes it. * Note that some targets may need to set up, enable,
762 * and tear down a breakpoint (hard or * soft) to detect algorithm
763 * termination, while others may support lower overhead schemes where
764 * soft breakpoints embedded in the algorithm automatically terminate the
765 * algorithm.
766 *
767 * @param target used to run the algorithm
768 * @param arch_info target-specific description of the algorithm.
769 */
770 int target_run_algorithm(struct target *target,
771 int num_mem_params, struct mem_param *mem_params,
772 int num_reg_params, struct reg_param *reg_param,
773 uint32_t entry_point, uint32_t exit_point,
774 int timeout_ms, void *arch_info)
775 {
776 int retval = ERROR_FAIL;
777
778 if (!target_was_examined(target)) {
779 LOG_ERROR("Target not examined yet");
780 goto done;
781 }
782 if (!target->type->run_algorithm) {
783 LOG_ERROR("Target type '%s' does not support %s",
784 target_type_name(target), __func__);
785 goto done;
786 }
787
788 target->running_alg = true;
789 retval = target->type->run_algorithm(target,
790 num_mem_params, mem_params,
791 num_reg_params, reg_param,
792 entry_point, exit_point, timeout_ms, arch_info);
793 target->running_alg = false;
794
795 done:
796 return retval;
797 }
798
799 /**
800 * Downloads a target-specific native code algorithm to the target,
801 * executes and leaves it running.
802 *
803 * @param target used to run the algorithm
804 * @param arch_info target-specific description of the algorithm.
805 */
806 int target_start_algorithm(struct target *target,
807 int num_mem_params, struct mem_param *mem_params,
808 int num_reg_params, struct reg_param *reg_params,
809 uint32_t entry_point, uint32_t exit_point,
810 void *arch_info)
811 {
812 int retval = ERROR_FAIL;
813
814 if (!target_was_examined(target)) {
815 LOG_ERROR("Target not examined yet");
816 goto done;
817 }
818 if (!target->type->start_algorithm) {
819 LOG_ERROR("Target type '%s' does not support %s",
820 target_type_name(target), __func__);
821 goto done;
822 }
823 if (target->running_alg) {
824 LOG_ERROR("Target is already running an algorithm");
825 goto done;
826 }
827
828 target->running_alg = true;
829 retval = target->type->start_algorithm(target,
830 num_mem_params, mem_params,
831 num_reg_params, reg_params,
832 entry_point, exit_point, arch_info);
833
834 done:
835 return retval;
836 }
837
838 /**
839 * Waits for an algorithm started with target_start_algorithm() to complete.
840 *
841 * @param target used to run the algorithm
842 * @param arch_info target-specific description of the algorithm.
843 */
844 int target_wait_algorithm(struct target *target,
845 int num_mem_params, struct mem_param *mem_params,
846 int num_reg_params, struct reg_param *reg_params,
847 uint32_t exit_point, int timeout_ms,
848 void *arch_info)
849 {
850 int retval = ERROR_FAIL;
851
852 if (!target->type->wait_algorithm) {
853 LOG_ERROR("Target type '%s' does not support %s",
854 target_type_name(target), __func__);
855 goto done;
856 }
857 if (!target->running_alg) {
858 LOG_ERROR("Target is not running an algorithm");
859 goto done;
860 }
861
862 retval = target->type->wait_algorithm(target,
863 num_mem_params, mem_params,
864 num_reg_params, reg_params,
865 exit_point, timeout_ms, arch_info);
866 if (retval != ERROR_TARGET_TIMEOUT)
867 target->running_alg = false;
868
869 done:
870 return retval;
871 }
872
873 /**
874 * Executes a target-specific native code algorithm in the target.
875 * It differs from target_run_algorithm in that the algorithm is asynchronous.
876 * Because of this it requires an compliant algorithm:
877 * see contrib/loaders/flash/stm32f1x.S for example.
878 *
879 * @param target used to run the algorithm
880 */
881
882 int target_run_flash_async_algorithm(struct target *target,
883 const uint8_t *buffer, uint32_t count, int block_size,
884 int num_mem_params, struct mem_param *mem_params,
885 int num_reg_params, struct reg_param *reg_params,
886 uint32_t buffer_start, uint32_t buffer_size,
887 uint32_t entry_point, uint32_t exit_point, void *arch_info)
888 {
889 int retval;
890 int timeout = 0;
891
892 const uint8_t *buffer_orig = buffer;
893
894 /* Set up working area. First word is write pointer, second word is read pointer,
895 * rest is fifo data area. */
896 uint32_t wp_addr = buffer_start;
897 uint32_t rp_addr = buffer_start + 4;
898 uint32_t fifo_start_addr = buffer_start + 8;
899 uint32_t fifo_end_addr = buffer_start + buffer_size;
900
901 uint32_t wp = fifo_start_addr;
902 uint32_t rp = fifo_start_addr;
903
904 /* validate block_size is 2^n */
905 assert(!block_size || !(block_size & (block_size - 1)));
906
907 retval = target_write_u32(target, wp_addr, wp);
908 if (retval != ERROR_OK)
909 return retval;
910 retval = target_write_u32(target, rp_addr, rp);
911 if (retval != ERROR_OK)
912 return retval;
913
914 /* Start up algorithm on target and let it idle while writing the first chunk */
915 retval = target_start_algorithm(target, num_mem_params, mem_params,
916 num_reg_params, reg_params,
917 entry_point,
918 exit_point,
919 arch_info);
920
921 if (retval != ERROR_OK) {
922 LOG_ERROR("error starting target flash write algorithm");
923 return retval;
924 }
925
926 while (count > 0) {
927
928 retval = target_read_u32(target, rp_addr, &rp);
929 if (retval != ERROR_OK) {
930 LOG_ERROR("failed to get read pointer");
931 break;
932 }
933
934 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
935 (size_t) (buffer - buffer_orig), count, wp, rp);
936
937 if (rp == 0) {
938 LOG_ERROR("flash write algorithm aborted by target");
939 retval = ERROR_FLASH_OPERATION_FAILED;
940 break;
941 }
942
943 if ((rp & (block_size - 1)) || rp < fifo_start_addr || rp >= fifo_end_addr) {
944 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
945 break;
946 }
947
948 /* Count the number of bytes available in the fifo without
949 * crossing the wrap around. Make sure to not fill it completely,
950 * because that would make wp == rp and that's the empty condition. */
951 uint32_t thisrun_bytes;
952 if (rp > wp)
953 thisrun_bytes = rp - wp - block_size;
954 else if (rp > fifo_start_addr)
955 thisrun_bytes = fifo_end_addr - wp;
956 else
957 thisrun_bytes = fifo_end_addr - wp - block_size;
958
959 if (thisrun_bytes == 0) {
960 /* Throttle polling a bit if transfer is (much) faster than flash
961 * programming. The exact delay shouldn't matter as long as it's
962 * less than buffer size / flash speed. This is very unlikely to
963 * run when using high latency connections such as USB. */
964 alive_sleep(10);
965
966 /* to stop an infinite loop on some targets check and increment a timeout
967 * this issue was observed on a stellaris using the new ICDI interface */
968 if (timeout++ >= 500) {
969 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
970 return ERROR_FLASH_OPERATION_FAILED;
971 }
972 continue;
973 }
974
975 /* reset our timeout */
976 timeout = 0;
977
978 /* Limit to the amount of data we actually want to write */
979 if (thisrun_bytes > count * block_size)
980 thisrun_bytes = count * block_size;
981
982 /* Write data to fifo */
983 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
984 if (retval != ERROR_OK)
985 break;
986
987 /* Update counters and wrap write pointer */
988 buffer += thisrun_bytes;
989 count -= thisrun_bytes / block_size;
990 wp += thisrun_bytes;
991 if (wp >= fifo_end_addr)
992 wp = fifo_start_addr;
993
994 /* Store updated write pointer to target */
995 retval = target_write_u32(target, wp_addr, wp);
996 if (retval != ERROR_OK)
997 break;
998 }
999
1000 if (retval != ERROR_OK) {
1001 /* abort flash write algorithm on target */
1002 target_write_u32(target, wp_addr, 0);
1003 }
1004
1005 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1006 num_reg_params, reg_params,
1007 exit_point,
1008 10000,
1009 arch_info);
1010
1011 if (retval2 != ERROR_OK) {
1012 LOG_ERROR("error waiting for target flash write algorithm");
1013 retval = retval2;
1014 }
1015
1016 return retval;
1017 }
1018
1019 int target_read_memory(struct target *target,
1020 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1021 {
1022 if (!target_was_examined(target)) {
1023 LOG_ERROR("Target not examined yet");
1024 return ERROR_FAIL;
1025 }
1026 return target->type->read_memory(target, address, size, count, buffer);
1027 }
1028
1029 int target_read_phys_memory(struct target *target,
1030 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1031 {
1032 if (!target_was_examined(target)) {
1033 LOG_ERROR("Target not examined yet");
1034 return ERROR_FAIL;
1035 }
1036 return target->type->read_phys_memory(target, address, size, count, buffer);
1037 }
1038
1039 int target_write_memory(struct target *target,
1040 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1041 {
1042 if (!target_was_examined(target)) {
1043 LOG_ERROR("Target not examined yet");
1044 return ERROR_FAIL;
1045 }
1046 return target->type->write_memory(target, address, size, count, buffer);
1047 }
1048
1049 int target_write_phys_memory(struct target *target,
1050 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1051 {
1052 if (!target_was_examined(target)) {
1053 LOG_ERROR("Target not examined yet");
1054 return ERROR_FAIL;
1055 }
1056 return target->type->write_phys_memory(target, address, size, count, buffer);
1057 }
1058
1059 int target_add_breakpoint(struct target *target,
1060 struct breakpoint *breakpoint)
1061 {
1062 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
1063 LOG_WARNING("target %s is not halted", target_name(target));
1064 return ERROR_TARGET_NOT_HALTED;
1065 }
1066 return target->type->add_breakpoint(target, breakpoint);
1067 }
1068
1069 int target_add_context_breakpoint(struct target *target,
1070 struct breakpoint *breakpoint)
1071 {
1072 if (target->state != TARGET_HALTED) {
1073 LOG_WARNING("target %s is not halted", target_name(target));
1074 return ERROR_TARGET_NOT_HALTED;
1075 }
1076 return target->type->add_context_breakpoint(target, breakpoint);
1077 }
1078
1079 int target_add_hybrid_breakpoint(struct target *target,
1080 struct breakpoint *breakpoint)
1081 {
1082 if (target->state != TARGET_HALTED) {
1083 LOG_WARNING("target %s is not halted", target_name(target));
1084 return ERROR_TARGET_NOT_HALTED;
1085 }
1086 return target->type->add_hybrid_breakpoint(target, breakpoint);
1087 }
1088
1089 int target_remove_breakpoint(struct target *target,
1090 struct breakpoint *breakpoint)
1091 {
1092 return target->type->remove_breakpoint(target, breakpoint);
1093 }
1094
1095 int target_add_watchpoint(struct target *target,
1096 struct watchpoint *watchpoint)
1097 {
1098 if (target->state != TARGET_HALTED) {
1099 LOG_WARNING("target %s is not halted", target_name(target));
1100 return ERROR_TARGET_NOT_HALTED;
1101 }
1102 return target->type->add_watchpoint(target, watchpoint);
1103 }
1104 int target_remove_watchpoint(struct target *target,
1105 struct watchpoint *watchpoint)
1106 {
1107 return target->type->remove_watchpoint(target, watchpoint);
1108 }
1109 int target_hit_watchpoint(struct target *target,
1110 struct watchpoint **hit_watchpoint)
1111 {
1112 if (target->state != TARGET_HALTED) {
1113 LOG_WARNING("target %s is not halted", target->cmd_name);
1114 return ERROR_TARGET_NOT_HALTED;
1115 }
1116
1117 if (target->type->hit_watchpoint == NULL) {
1118 /* For backward compatible, if hit_watchpoint is not implemented,
1119 * return ERROR_FAIL such that gdb_server will not take the nonsense
1120 * information. */
1121 return ERROR_FAIL;
1122 }
1123
1124 return target->type->hit_watchpoint(target, hit_watchpoint);
1125 }
1126
1127 int target_get_gdb_reg_list(struct target *target,
1128 struct reg **reg_list[], int *reg_list_size,
1129 enum target_register_class reg_class)
1130 {
1131 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1132 }
1133 int target_step(struct target *target,
1134 int current, uint32_t address, int handle_breakpoints)
1135 {
1136 return target->type->step(target, current, address, handle_breakpoints);
1137 }
1138
1139 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1140 {
1141 if (target->state != TARGET_HALTED) {
1142 LOG_WARNING("target %s is not halted", target->cmd_name);
1143 return ERROR_TARGET_NOT_HALTED;
1144 }
1145 return target->type->get_gdb_fileio_info(target, fileio_info);
1146 }
1147
1148 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1149 {
1150 if (target->state != TARGET_HALTED) {
1151 LOG_WARNING("target %s is not halted", target->cmd_name);
1152 return ERROR_TARGET_NOT_HALTED;
1153 }
1154 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1155 }
1156
1157 int target_profiling(struct target *target, uint32_t *samples,
1158 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1159 {
1160 if (target->state != TARGET_HALTED) {
1161 LOG_WARNING("target %s is not halted", target->cmd_name);
1162 return ERROR_TARGET_NOT_HALTED;
1163 }
1164 return target->type->profiling(target, samples, max_num_samples,
1165 num_samples, seconds);
1166 }
1167
1168 /**
1169 * Reset the @c examined flag for the given target.
1170 * Pure paranoia -- targets are zeroed on allocation.
1171 */
1172 static void target_reset_examined(struct target *target)
1173 {
1174 target->examined = false;
1175 }
1176
1177 static int err_read_phys_memory(struct target *target, uint32_t address,
1178 uint32_t size, uint32_t count, uint8_t *buffer)
1179 {
1180 LOG_ERROR("Not implemented: %s", __func__);
1181 return ERROR_FAIL;
1182 }
1183
1184 static int err_write_phys_memory(struct target *target, uint32_t address,
1185 uint32_t size, uint32_t count, const uint8_t *buffer)
1186 {
1187 LOG_ERROR("Not implemented: %s", __func__);
1188 return ERROR_FAIL;
1189 }
1190
1191 static int handle_target(void *priv);
1192
1193 static int target_init_one(struct command_context *cmd_ctx,
1194 struct target *target)
1195 {
1196 target_reset_examined(target);
1197
1198 struct target_type *type = target->type;
1199 if (type->examine == NULL)
1200 type->examine = default_examine;
1201
1202 if (type->check_reset == NULL)
1203 type->check_reset = default_check_reset;
1204
1205 assert(type->init_target != NULL);
1206
1207 int retval = type->init_target(cmd_ctx, target);
1208 if (ERROR_OK != retval) {
1209 LOG_ERROR("target '%s' init failed", target_name(target));
1210 return retval;
1211 }
1212
1213 /* Sanity-check MMU support ... stub in what we must, to help
1214 * implement it in stages, but warn if we need to do so.
1215 */
1216 if (type->mmu) {
1217 if (type->write_phys_memory == NULL) {
1218 LOG_ERROR("type '%s' is missing write_phys_memory",
1219 type->name);
1220 type->write_phys_memory = err_write_phys_memory;
1221 }
1222 if (type->read_phys_memory == NULL) {
1223 LOG_ERROR("type '%s' is missing read_phys_memory",
1224 type->name);
1225 type->read_phys_memory = err_read_phys_memory;
1226 }
1227 if (type->virt2phys == NULL) {
1228 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1229 type->virt2phys = identity_virt2phys;
1230 }
1231 } else {
1232 /* Make sure no-MMU targets all behave the same: make no
1233 * distinction between physical and virtual addresses, and
1234 * ensure that virt2phys() is always an identity mapping.
1235 */
1236 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1237 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1238
1239 type->mmu = no_mmu;
1240 type->write_phys_memory = type->write_memory;
1241 type->read_phys_memory = type->read_memory;
1242 type->virt2phys = identity_virt2phys;
1243 }
1244
1245 if (target->type->read_buffer == NULL)
1246 target->type->read_buffer = target_read_buffer_default;
1247
1248 if (target->type->write_buffer == NULL)
1249 target->type->write_buffer = target_write_buffer_default;
1250
1251 if (target->type->get_gdb_fileio_info == NULL)
1252 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1253
1254 if (target->type->gdb_fileio_end == NULL)
1255 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1256
1257 if (target->type->profiling == NULL)
1258 target->type->profiling = target_profiling_default;
1259
1260 return ERROR_OK;
1261 }
1262
1263 static int target_init(struct command_context *cmd_ctx)
1264 {
1265 struct target *target;
1266 int retval;
1267
1268 for (target = all_targets; target; target = target->next) {
1269 retval = target_init_one(cmd_ctx, target);
1270 if (ERROR_OK != retval)
1271 return retval;
1272 }
1273
1274 if (!all_targets)
1275 return ERROR_OK;
1276
1277 retval = target_register_user_commands(cmd_ctx);
1278 if (ERROR_OK != retval)
1279 return retval;
1280
1281 retval = target_register_timer_callback(&handle_target,
1282 polling_interval, 1, cmd_ctx->interp);
1283 if (ERROR_OK != retval)
1284 return retval;
1285
1286 return ERROR_OK;
1287 }
1288
1289 COMMAND_HANDLER(handle_target_init_command)
1290 {
1291 int retval;
1292
1293 if (CMD_ARGC != 0)
1294 return ERROR_COMMAND_SYNTAX_ERROR;
1295
1296 static bool target_initialized;
1297 if (target_initialized) {
1298 LOG_INFO("'target init' has already been called");
1299 return ERROR_OK;
1300 }
1301 target_initialized = true;
1302
1303 retval = command_run_line(CMD_CTX, "init_targets");
1304 if (ERROR_OK != retval)
1305 return retval;
1306
1307 retval = command_run_line(CMD_CTX, "init_target_events");
1308 if (ERROR_OK != retval)
1309 return retval;
1310
1311 retval = command_run_line(CMD_CTX, "init_board");
1312 if (ERROR_OK != retval)
1313 return retval;
1314
1315 LOG_DEBUG("Initializing targets...");
1316 return target_init(CMD_CTX);
1317 }
1318
1319 int target_register_event_callback(int (*callback)(struct target *target,
1320 enum target_event event, void *priv), void *priv)
1321 {
1322 struct target_event_callback **callbacks_p = &target_event_callbacks;
1323
1324 if (callback == NULL)
1325 return ERROR_COMMAND_SYNTAX_ERROR;
1326
1327 if (*callbacks_p) {
1328 while ((*callbacks_p)->next)
1329 callbacks_p = &((*callbacks_p)->next);
1330 callbacks_p = &((*callbacks_p)->next);
1331 }
1332
1333 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1334 (*callbacks_p)->callback = callback;
1335 (*callbacks_p)->priv = priv;
1336 (*callbacks_p)->next = NULL;
1337
1338 return ERROR_OK;
1339 }
1340
1341 int target_register_reset_callback(int (*callback)(struct target *target,
1342 enum target_reset_mode reset_mode, void *priv), void *priv)
1343 {
1344 struct target_reset_callback *entry;
1345
1346 if (callback == NULL)
1347 return ERROR_COMMAND_SYNTAX_ERROR;
1348
1349 entry = malloc(sizeof(struct target_reset_callback));
1350 if (entry == NULL) {
1351 LOG_ERROR("error allocating buffer for reset callback entry");
1352 return ERROR_COMMAND_SYNTAX_ERROR;
1353 }
1354
1355 entry->callback = callback;
1356 entry->priv = priv;
1357 list_add(&entry->list, &target_reset_callback_list);
1358
1359
1360 return ERROR_OK;
1361 }
1362
1363 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
1364 {
1365 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1366 struct timeval now;
1367
1368 if (callback == NULL)
1369 return ERROR_COMMAND_SYNTAX_ERROR;
1370
1371 if (*callbacks_p) {
1372 while ((*callbacks_p)->next)
1373 callbacks_p = &((*callbacks_p)->next);
1374 callbacks_p = &((*callbacks_p)->next);
1375 }
1376
1377 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1378 (*callbacks_p)->callback = callback;
1379 (*callbacks_p)->periodic = periodic;
1380 (*callbacks_p)->time_ms = time_ms;
1381 (*callbacks_p)->removed = false;
1382
1383 gettimeofday(&now, NULL);
1384 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
1385 time_ms -= (time_ms % 1000);
1386 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
1387 if ((*callbacks_p)->when.tv_usec > 1000000) {
1388 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
1389 (*callbacks_p)->when.tv_sec += 1;
1390 }
1391
1392 (*callbacks_p)->priv = priv;
1393 (*callbacks_p)->next = NULL;
1394
1395 return ERROR_OK;
1396 }
1397
1398 int target_unregister_event_callback(int (*callback)(struct target *target,
1399 enum target_event event, void *priv), void *priv)
1400 {
1401 struct target_event_callback **p = &target_event_callbacks;
1402 struct target_event_callback *c = target_event_callbacks;
1403
1404 if (callback == NULL)
1405 return ERROR_COMMAND_SYNTAX_ERROR;
1406
1407 while (c) {
1408 struct target_event_callback *next = c->next;
1409 if ((c->callback == callback) && (c->priv == priv)) {
1410 *p = next;
1411 free(c);
1412 return ERROR_OK;
1413 } else
1414 p = &(c->next);
1415 c = next;
1416 }
1417
1418 return ERROR_OK;
1419 }
1420
1421 int target_unregister_reset_callback(int (*callback)(struct target *target,
1422 enum target_reset_mode reset_mode, void *priv), void *priv)
1423 {
1424 struct target_reset_callback *entry;
1425
1426 if (callback == NULL)
1427 return ERROR_COMMAND_SYNTAX_ERROR;
1428
1429 list_for_each_entry(entry, &target_reset_callback_list, list) {
1430 if (entry->callback == callback && entry->priv == priv) {
1431 list_del(&entry->list);
1432 free(entry);
1433 break;
1434 }
1435 }
1436
1437 return ERROR_OK;
1438 }
1439
1440 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1441 {
1442 if (callback == NULL)
1443 return ERROR_COMMAND_SYNTAX_ERROR;
1444
1445 for (struct target_timer_callback *c = target_timer_callbacks;
1446 c; c = c->next) {
1447 if ((c->callback == callback) && (c->priv == priv)) {
1448 c->removed = true;
1449 return ERROR_OK;
1450 }
1451 }
1452
1453 return ERROR_FAIL;
1454 }
1455
1456 int target_call_event_callbacks(struct target *target, enum target_event event)
1457 {
1458 struct target_event_callback *callback = target_event_callbacks;
1459 struct target_event_callback *next_callback;
1460
1461 if (event == TARGET_EVENT_HALTED) {
1462 /* execute early halted first */
1463 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1464 }
1465
1466 LOG_DEBUG("target event %i (%s)", event,
1467 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1468
1469 target_handle_event(target, event);
1470
1471 while (callback) {
1472 next_callback = callback->next;
1473 callback->callback(target, event, callback->priv);
1474 callback = next_callback;
1475 }
1476
1477 return ERROR_OK;
1478 }
1479
1480 int target_call_reset_callbacks(struct target *target, enum target_reset_mode reset_mode)
1481 {
1482 struct target_reset_callback *callback;
1483
1484 LOG_DEBUG("target reset %i (%s)", reset_mode,
1485 Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode)->name);
1486
1487 list_for_each_entry(callback, &target_reset_callback_list, list)
1488 callback->callback(target, reset_mode, callback->priv);
1489
1490 return ERROR_OK;
1491 }
1492
1493 static int target_timer_callback_periodic_restart(
1494 struct target_timer_callback *cb, struct timeval *now)
1495 {
1496 int time_ms = cb->time_ms;
1497 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1498 time_ms -= (time_ms % 1000);
1499 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1500 if (cb->when.tv_usec > 1000000) {
1501 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1502 cb->when.tv_sec += 1;
1503 }
1504 return ERROR_OK;
1505 }
1506
1507 static int target_call_timer_callback(struct target_timer_callback *cb,
1508 struct timeval *now)
1509 {
1510 cb->callback(cb->priv);
1511
1512 if (cb->periodic)
1513 return target_timer_callback_periodic_restart(cb, now);
1514
1515 return target_unregister_timer_callback(cb->callback, cb->priv);
1516 }
1517
1518 static int target_call_timer_callbacks_check_time(int checktime)
1519 {
1520 static bool callback_processing;
1521
1522 /* Do not allow nesting */
1523 if (callback_processing)
1524 return ERROR_OK;
1525
1526 callback_processing = true;
1527
1528 keep_alive();
1529
1530 struct timeval now;
1531 gettimeofday(&now, NULL);
1532
1533 /* Store an address of the place containing a pointer to the
1534 * next item; initially, that's a standalone "root of the
1535 * list" variable. */
1536 struct target_timer_callback **callback = &target_timer_callbacks;
1537 while (*callback) {
1538 if ((*callback)->removed) {
1539 struct target_timer_callback *p = *callback;
1540 *callback = (*callback)->next;
1541 free(p);
1542 continue;
1543 }
1544
1545 bool call_it = (*callback)->callback &&
1546 ((!checktime && (*callback)->periodic) ||
1547 now.tv_sec > (*callback)->when.tv_sec ||
1548 (now.tv_sec == (*callback)->when.tv_sec &&
1549 now.tv_usec >= (*callback)->when.tv_usec));
1550
1551 if (call_it)
1552 target_call_timer_callback(*callback, &now);
1553
1554 callback = &(*callback)->next;
1555 }
1556
1557 callback_processing = false;
1558 return ERROR_OK;
1559 }
1560
1561 int target_call_timer_callbacks(void)
1562 {
1563 return target_call_timer_callbacks_check_time(1);
1564 }
1565
1566 /* invoke periodic callbacks immediately */
1567 int target_call_timer_callbacks_now(void)
1568 {
1569 return target_call_timer_callbacks_check_time(0);
1570 }
1571
1572 /* Prints the working area layout for debug purposes */
1573 static void print_wa_layout(struct target *target)
1574 {
1575 struct working_area *c = target->working_areas;
1576
1577 while (c) {
1578 LOG_DEBUG("%c%c 0x%08"PRIx32"-0x%08"PRIx32" (%"PRIu32" bytes)",
1579 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1580 c->address, c->address + c->size - 1, c->size);
1581 c = c->next;
1582 }
1583 }
1584
1585 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1586 static void target_split_working_area(struct working_area *area, uint32_t size)
1587 {
1588 assert(area->free); /* Shouldn't split an allocated area */
1589 assert(size <= area->size); /* Caller should guarantee this */
1590
1591 /* Split only if not already the right size */
1592 if (size < area->size) {
1593 struct working_area *new_wa = malloc(sizeof(*new_wa));
1594
1595 if (new_wa == NULL)
1596 return;
1597
1598 new_wa->next = area->next;
1599 new_wa->size = area->size - size;
1600 new_wa->address = area->address + size;
1601 new_wa->backup = NULL;
1602 new_wa->user = NULL;
1603 new_wa->free = true;
1604
1605 area->next = new_wa;
1606 area->size = size;
1607
1608 /* If backup memory was allocated to this area, it has the wrong size
1609 * now so free it and it will be reallocated if/when needed */
1610 if (area->backup) {
1611 free(area->backup);
1612 area->backup = NULL;
1613 }
1614 }
1615 }
1616
1617 /* Merge all adjacent free areas into one */
1618 static void target_merge_working_areas(struct target *target)
1619 {
1620 struct working_area *c = target->working_areas;
1621
1622 while (c && c->next) {
1623 assert(c->next->address == c->address + c->size); /* This is an invariant */
1624
1625 /* Find two adjacent free areas */
1626 if (c->free && c->next->free) {
1627 /* Merge the last into the first */
1628 c->size += c->next->size;
1629
1630 /* Remove the last */
1631 struct working_area *to_be_freed = c->next;
1632 c->next = c->next->next;
1633 if (to_be_freed->backup)
1634 free(to_be_freed->backup);
1635 free(to_be_freed);
1636
1637 /* If backup memory was allocated to the remaining area, it's has
1638 * the wrong size now */
1639 if (c->backup) {
1640 free(c->backup);
1641 c->backup = NULL;
1642 }
1643 } else {
1644 c = c->next;
1645 }
1646 }
1647 }
1648
1649 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1650 {
1651 /* Reevaluate working area address based on MMU state*/
1652 if (target->working_areas == NULL) {
1653 int retval;
1654 int enabled;
1655
1656 retval = target->type->mmu(target, &enabled);
1657 if (retval != ERROR_OK)
1658 return retval;
1659
1660 if (!enabled) {
1661 if (target->working_area_phys_spec) {
1662 LOG_DEBUG("MMU disabled, using physical "
1663 "address for working memory 0x%08"PRIx32,
1664 target->working_area_phys);
1665 target->working_area = target->working_area_phys;
1666 } else {
1667 LOG_ERROR("No working memory available. "
1668 "Specify -work-area-phys to target.");
1669 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1670 }
1671 } else {
1672 if (target->working_area_virt_spec) {
1673 LOG_DEBUG("MMU enabled, using virtual "
1674 "address for working memory 0x%08"PRIx32,
1675 target->working_area_virt);
1676 target->working_area = target->working_area_virt;
1677 } else {
1678 LOG_ERROR("No working memory available. "
1679 "Specify -work-area-virt to target.");
1680 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1681 }
1682 }
1683
1684 /* Set up initial working area on first call */
1685 struct working_area *new_wa = malloc(sizeof(*new_wa));
1686 if (new_wa) {
1687 new_wa->next = NULL;
1688 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
1689 new_wa->address = target->working_area;
1690 new_wa->backup = NULL;
1691 new_wa->user = NULL;
1692 new_wa->free = true;
1693 }
1694
1695 target->working_areas = new_wa;
1696 }
1697
1698 /* only allocate multiples of 4 byte */
1699 if (size % 4)
1700 size = (size + 3) & (~3UL);
1701
1702 struct working_area *c = target->working_areas;
1703
1704 /* Find the first large enough working area */
1705 while (c) {
1706 if (c->free && c->size >= size)
1707 break;
1708 c = c->next;
1709 }
1710
1711 if (c == NULL)
1712 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1713
1714 /* Split the working area into the requested size */
1715 target_split_working_area(c, size);
1716
1717 LOG_DEBUG("allocated new working area of %"PRIu32" bytes at address 0x%08"PRIx32, size, c->address);
1718
1719 if (target->backup_working_area) {
1720 if (c->backup == NULL) {
1721 c->backup = malloc(c->size);
1722 if (c->backup == NULL)
1723 return ERROR_FAIL;
1724 }
1725
1726 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
1727 if (retval != ERROR_OK)
1728 return retval;
1729 }
1730
1731 /* mark as used, and return the new (reused) area */
1732 c->free = false;
1733 *area = c;
1734
1735 /* user pointer */
1736 c->user = area;
1737
1738 print_wa_layout(target);
1739
1740 return ERROR_OK;
1741 }
1742
1743 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1744 {
1745 int retval;
1746
1747 retval = target_alloc_working_area_try(target, size, area);
1748 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1749 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
1750 return retval;
1751
1752 }
1753
1754 static int target_restore_working_area(struct target *target, struct working_area *area)
1755 {
1756 int retval = ERROR_OK;
1757
1758 if (target->backup_working_area && area->backup != NULL) {
1759 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
1760 if (retval != ERROR_OK)
1761 LOG_ERROR("failed to restore %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1762 area->size, area->address);
1763 }
1764
1765 return retval;
1766 }
1767
1768 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
1769 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1770 {
1771 int retval = ERROR_OK;
1772
1773 if (area->free)
1774 return retval;
1775
1776 if (restore) {
1777 retval = target_restore_working_area(target, area);
1778 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
1779 if (retval != ERROR_OK)
1780 return retval;
1781 }
1782
1783 area->free = true;
1784
1785 LOG_DEBUG("freed %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1786 area->size, area->address);
1787
1788 /* mark user pointer invalid */
1789 /* TODO: Is this really safe? It points to some previous caller's memory.
1790 * How could we know that the area pointer is still in that place and not
1791 * some other vital data? What's the purpose of this, anyway? */
1792 *area->user = NULL;
1793 area->user = NULL;
1794
1795 target_merge_working_areas(target);
1796
1797 print_wa_layout(target);
1798
1799 return retval;
1800 }
1801
1802 int target_free_working_area(struct target *target, struct working_area *area)
1803 {
1804 return target_free_working_area_restore(target, area, 1);
1805 }
1806
1807 /* free resources and restore memory, if restoring memory fails,
1808 * free up resources anyway
1809 */
1810 static void target_free_all_working_areas_restore(struct target *target, int restore)
1811 {
1812 struct working_area *c = target->working_areas;
1813
1814 LOG_DEBUG("freeing all working areas");
1815
1816 /* Loop through all areas, restoring the allocated ones and marking them as free */
1817 while (c) {
1818 if (!c->free) {
1819 if (restore)
1820 target_restore_working_area(target, c);
1821 c->free = true;
1822 *c->user = NULL; /* Same as above */
1823 c->user = NULL;
1824 }
1825 c = c->next;
1826 }
1827
1828 /* Run a merge pass to combine all areas into one */
1829 target_merge_working_areas(target);
1830
1831 print_wa_layout(target);
1832 }
1833
1834 void target_free_all_working_areas(struct target *target)
1835 {
1836 target_free_all_working_areas_restore(target, 1);
1837 }
1838
1839 /* Find the largest number of bytes that can be allocated */
1840 uint32_t target_get_working_area_avail(struct target *target)
1841 {
1842 struct working_area *c = target->working_areas;
1843 uint32_t max_size = 0;
1844
1845 if (c == NULL)
1846 return target->working_area_size;
1847
1848 while (c) {
1849 if (c->free && max_size < c->size)
1850 max_size = c->size;
1851
1852 c = c->next;
1853 }
1854
1855 return max_size;
1856 }
1857
1858 int target_arch_state(struct target *target)
1859 {
1860 int retval;
1861 if (target == NULL) {
1862 LOG_USER("No target has been configured");
1863 return ERROR_OK;
1864 }
1865
1866 LOG_USER("target state: %s", target_state_name(target));
1867
1868 if (target->state != TARGET_HALTED)
1869 return ERROR_OK;
1870
1871 retval = target->type->arch_state(target);
1872 return retval;
1873 }
1874
1875 static int target_get_gdb_fileio_info_default(struct target *target,
1876 struct gdb_fileio_info *fileio_info)
1877 {
1878 /* If target does not support semi-hosting function, target
1879 has no need to provide .get_gdb_fileio_info callback.
1880 It just return ERROR_FAIL and gdb_server will return "Txx"
1881 as target halted every time. */
1882 return ERROR_FAIL;
1883 }
1884
1885 static int target_gdb_fileio_end_default(struct target *target,
1886 int retcode, int fileio_errno, bool ctrl_c)
1887 {
1888 return ERROR_OK;
1889 }
1890
1891 static int target_profiling_default(struct target *target, uint32_t *samples,
1892 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1893 {
1894 struct timeval timeout, now;
1895
1896 gettimeofday(&timeout, NULL);
1897 timeval_add_time(&timeout, seconds, 0);
1898
1899 LOG_INFO("Starting profiling. Halting and resuming the"
1900 " target as often as we can...");
1901
1902 uint32_t sample_count = 0;
1903 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
1904 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
1905
1906 int retval = ERROR_OK;
1907 for (;;) {
1908 target_poll(target);
1909 if (target->state == TARGET_HALTED) {
1910 uint32_t t = buf_get_u32(reg->value, 0, 32);
1911 samples[sample_count++] = t;
1912 /* current pc, addr = 0, do not handle breakpoints, not debugging */
1913 retval = target_resume(target, 1, 0, 0, 0);
1914 target_poll(target);
1915 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
1916 } else if (target->state == TARGET_RUNNING) {
1917 /* We want to quickly sample the PC. */
1918 retval = target_halt(target);
1919 } else {
1920 LOG_INFO("Target not halted or running");
1921 retval = ERROR_OK;
1922 break;
1923 }
1924
1925 if (retval != ERROR_OK)
1926 break;
1927
1928 gettimeofday(&now, NULL);
1929 if ((sample_count >= max_num_samples) ||
1930 ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec))) {
1931 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
1932 break;
1933 }
1934 }
1935
1936 *num_samples = sample_count;
1937 return retval;
1938 }
1939
1940 /* Single aligned words are guaranteed to use 16 or 32 bit access
1941 * mode respectively, otherwise data is handled as quickly as
1942 * possible
1943 */
1944 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1945 {
1946 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1947 (int)size, (unsigned)address);
1948
1949 if (!target_was_examined(target)) {
1950 LOG_ERROR("Target not examined yet");
1951 return ERROR_FAIL;
1952 }
1953
1954 if (size == 0)
1955 return ERROR_OK;
1956
1957 if ((address + size - 1) < address) {
1958 /* GDB can request this when e.g. PC is 0xfffffffc*/
1959 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1960 (unsigned)address,
1961 (unsigned)size);
1962 return ERROR_FAIL;
1963 }
1964
1965 return target->type->write_buffer(target, address, size, buffer);
1966 }
1967
1968 static int target_write_buffer_default(struct target *target, uint32_t address, uint32_t count, const uint8_t *buffer)
1969 {
1970 uint32_t size;
1971
1972 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
1973 * will have something to do with the size we leave to it. */
1974 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
1975 if (address & size) {
1976 int retval = target_write_memory(target, address, size, 1, buffer);
1977 if (retval != ERROR_OK)
1978 return retval;
1979 address += size;
1980 count -= size;
1981 buffer += size;
1982 }
1983 }
1984
1985 /* Write the data with as large access size as possible. */
1986 for (; size > 0; size /= 2) {
1987 uint32_t aligned = count - count % size;
1988 if (aligned > 0) {
1989 int retval = target_write_memory(target, address, size, aligned / size, buffer);
1990 if (retval != ERROR_OK)
1991 return retval;
1992 address += aligned;
1993 count -= aligned;
1994 buffer += aligned;
1995 }
1996 }
1997
1998 return ERROR_OK;
1999 }
2000
2001 /* Single aligned words are guaranteed to use 16 or 32 bit access
2002 * mode respectively, otherwise data is handled as quickly as
2003 * possible
2004 */
2005 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
2006 {
2007 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
2008 (int)size, (unsigned)address);
2009
2010 if (!target_was_examined(target)) {
2011 LOG_ERROR("Target not examined yet");
2012 return ERROR_FAIL;
2013 }
2014
2015 if (size == 0)
2016 return ERROR_OK;
2017
2018 if ((address + size - 1) < address) {
2019 /* GDB can request this when e.g. PC is 0xfffffffc*/
2020 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
2021 address,
2022 size);
2023 return ERROR_FAIL;
2024 }
2025
2026 return target->type->read_buffer(target, address, size, buffer);
2027 }
2028
2029 static int target_read_buffer_default(struct target *target, uint32_t address, uint32_t count, uint8_t *buffer)
2030 {
2031 uint32_t size;
2032
2033 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
2034 * will have something to do with the size we leave to it. */
2035 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
2036 if (address & size) {
2037 int retval = target_read_memory(target, address, size, 1, buffer);
2038 if (retval != ERROR_OK)
2039 return retval;
2040 address += size;
2041 count -= size;
2042 buffer += size;
2043 }
2044 }
2045
2046 /* Read the data with as large access size as possible. */
2047 for (; size > 0; size /= 2) {
2048 uint32_t aligned = count - count % size;
2049 if (aligned > 0) {
2050 int retval = target_read_memory(target, address, size, aligned / size, buffer);
2051 if (retval != ERROR_OK)
2052 return retval;
2053 address += aligned;
2054 count -= aligned;
2055 buffer += aligned;
2056 }
2057 }
2058
2059 return ERROR_OK;
2060 }
2061
2062 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
2063 {
2064 uint8_t *buffer;
2065 int retval;
2066 uint32_t i;
2067 uint32_t checksum = 0;
2068 if (!target_was_examined(target)) {
2069 LOG_ERROR("Target not examined yet");
2070 return ERROR_FAIL;
2071 }
2072
2073 retval = target->type->checksum_memory(target, address, size, &checksum);
2074 if (retval != ERROR_OK) {
2075 buffer = malloc(size);
2076 if (buffer == NULL) {
2077 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
2078 return ERROR_COMMAND_SYNTAX_ERROR;
2079 }
2080 retval = target_read_buffer(target, address, size, buffer);
2081 if (retval != ERROR_OK) {
2082 free(buffer);
2083 return retval;
2084 }
2085
2086 /* convert to target endianness */
2087 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2088 uint32_t target_data;
2089 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2090 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2091 }
2092
2093 retval = image_calculate_checksum(buffer, size, &checksum);
2094 free(buffer);
2095 }
2096
2097 *crc = checksum;
2098
2099 return retval;
2100 }
2101
2102 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
2103 {
2104 int retval;
2105 if (!target_was_examined(target)) {
2106 LOG_ERROR("Target not examined yet");
2107 return ERROR_FAIL;
2108 }
2109
2110 if (target->type->blank_check_memory == 0)
2111 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2112
2113 retval = target->type->blank_check_memory(target, address, size, blank);
2114
2115 return retval;
2116 }
2117
2118 int target_read_u64(struct target *target, uint64_t address, uint64_t *value)
2119 {
2120 uint8_t value_buf[8];
2121 if (!target_was_examined(target)) {
2122 LOG_ERROR("Target not examined yet");
2123 return ERROR_FAIL;
2124 }
2125
2126 int retval = target_read_memory(target, address, 8, 1, value_buf);
2127
2128 if (retval == ERROR_OK) {
2129 *value = target_buffer_get_u64(target, value_buf);
2130 LOG_DEBUG("address: 0x%" PRIx64 ", value: 0x%16.16" PRIx64 "",
2131 address,
2132 *value);
2133 } else {
2134 *value = 0x0;
2135 LOG_DEBUG("address: 0x%" PRIx64 " failed",
2136 address);
2137 }
2138
2139 return retval;
2140 }
2141
2142 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
2143 {
2144 uint8_t value_buf[4];
2145 if (!target_was_examined(target)) {
2146 LOG_ERROR("Target not examined yet");
2147 return ERROR_FAIL;
2148 }
2149
2150 int retval = target_read_memory(target, address, 4, 1, value_buf);
2151
2152 if (retval == ERROR_OK) {
2153 *value = target_buffer_get_u32(target, value_buf);
2154 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
2155 address,
2156 *value);
2157 } else {
2158 *value = 0x0;
2159 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2160 address);
2161 }
2162
2163 return retval;
2164 }
2165
2166 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
2167 {
2168 uint8_t value_buf[2];
2169 if (!target_was_examined(target)) {
2170 LOG_ERROR("Target not examined yet");
2171 return ERROR_FAIL;
2172 }
2173
2174 int retval = target_read_memory(target, address, 2, 1, value_buf);
2175
2176 if (retval == ERROR_OK) {
2177 *value = target_buffer_get_u16(target, value_buf);
2178 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
2179 address,
2180 *value);
2181 } else {
2182 *value = 0x0;
2183 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2184 address);
2185 }
2186
2187 return retval;
2188 }
2189
2190 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
2191 {
2192 if (!target_was_examined(target)) {
2193 LOG_ERROR("Target not examined yet");
2194 return ERROR_FAIL;
2195 }
2196
2197 int retval = target_read_memory(target, address, 1, 1, value);
2198
2199 if (retval == ERROR_OK) {
2200 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2201 address,
2202 *value);
2203 } else {
2204 *value = 0x0;
2205 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2206 address);
2207 }
2208
2209 return retval;
2210 }
2211
2212 int target_write_u64(struct target *target, uint64_t address, uint64_t value)
2213 {
2214 int retval;
2215 uint8_t value_buf[8];
2216 if (!target_was_examined(target)) {
2217 LOG_ERROR("Target not examined yet");
2218 return ERROR_FAIL;
2219 }
2220
2221 LOG_DEBUG("address: 0x%" PRIx64 ", value: 0x%16.16" PRIx64 "",
2222 address,
2223 value);
2224
2225 target_buffer_set_u64(target, value_buf, value);
2226 retval = target_write_memory(target, address, 8, 1, value_buf);
2227 if (retval != ERROR_OK)
2228 LOG_DEBUG("failed: %i", retval);
2229
2230 return retval;
2231 }
2232
2233 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
2234 {
2235 int retval;
2236 uint8_t value_buf[4];
2237 if (!target_was_examined(target)) {
2238 LOG_ERROR("Target not examined yet");
2239 return ERROR_FAIL;
2240 }
2241
2242 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
2243 address,
2244 value);
2245
2246 target_buffer_set_u32(target, value_buf, value);
2247 retval = target_write_memory(target, address, 4, 1, value_buf);
2248 if (retval != ERROR_OK)
2249 LOG_DEBUG("failed: %i", retval);
2250
2251 return retval;
2252 }
2253
2254 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
2255 {
2256 int retval;
2257 uint8_t value_buf[2];
2258 if (!target_was_examined(target)) {
2259 LOG_ERROR("Target not examined yet");
2260 return ERROR_FAIL;
2261 }
2262
2263 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
2264 address,
2265 value);
2266
2267 target_buffer_set_u16(target, value_buf, value);
2268 retval = target_write_memory(target, address, 2, 1, value_buf);
2269 if (retval != ERROR_OK)
2270 LOG_DEBUG("failed: %i", retval);
2271
2272 return retval;
2273 }
2274
2275 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
2276 {
2277 int retval;
2278 if (!target_was_examined(target)) {
2279 LOG_ERROR("Target not examined yet");
2280 return ERROR_FAIL;
2281 }
2282
2283 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2284 address, value);
2285
2286 retval = target_write_memory(target, address, 1, 1, &value);
2287 if (retval != ERROR_OK)
2288 LOG_DEBUG("failed: %i", retval);
2289
2290 return retval;
2291 }
2292
2293 static int find_target(struct command_context *cmd_ctx, const char *name)
2294 {
2295 struct target *target = get_target(name);
2296 if (target == NULL) {
2297 LOG_ERROR("Target: %s is unknown, try one of:\n", name);
2298 return ERROR_FAIL;
2299 }
2300 if (!target->tap->enabled) {
2301 LOG_USER("Target: TAP %s is disabled, "
2302 "can't be the current target\n",
2303 target->tap->dotted_name);
2304 return ERROR_FAIL;
2305 }
2306
2307 cmd_ctx->current_target = target->target_number;
2308 return ERROR_OK;
2309 }
2310
2311
2312 COMMAND_HANDLER(handle_targets_command)
2313 {
2314 int retval = ERROR_OK;
2315 if (CMD_ARGC == 1) {
2316 retval = find_target(CMD_CTX, CMD_ARGV[0]);
2317 if (retval == ERROR_OK) {
2318 /* we're done! */
2319 return retval;
2320 }
2321 }
2322
2323 struct target *target = all_targets;
2324 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
2325 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
2326 while (target) {
2327 const char *state;
2328 char marker = ' ';
2329
2330 if (target->tap->enabled)
2331 state = target_state_name(target);
2332 else
2333 state = "tap-disabled";
2334
2335 if (CMD_CTX->current_target == target->target_number)
2336 marker = '*';
2337
2338 /* keep columns lined up to match the headers above */
2339 command_print(CMD_CTX,
2340 "%2d%c %-18s %-10s %-6s %-18s %s",
2341 target->target_number,
2342 marker,
2343 target_name(target),
2344 target_type_name(target),
2345 Jim_Nvp_value2name_simple(nvp_target_endian,
2346 target->endianness)->name,
2347 target->tap->dotted_name,
2348 state);
2349 target = target->next;
2350 }
2351
2352 return retval;
2353 }
2354
2355 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2356
2357 static int powerDropout;
2358 static int srstAsserted;
2359
2360 static int runPowerRestore;
2361 static int runPowerDropout;
2362 static int runSrstAsserted;
2363 static int runSrstDeasserted;
2364
2365 static int sense_handler(void)
2366 {
2367 static int prevSrstAsserted;
2368 static int prevPowerdropout;
2369
2370 int retval = jtag_power_dropout(&powerDropout);
2371 if (retval != ERROR_OK)
2372 return retval;
2373
2374 int powerRestored;
2375 powerRestored = prevPowerdropout && !powerDropout;
2376 if (powerRestored)
2377 runPowerRestore = 1;
2378
2379 long long current = timeval_ms();
2380 static long long lastPower;
2381 int waitMore = lastPower + 2000 > current;
2382 if (powerDropout && !waitMore) {
2383 runPowerDropout = 1;
2384 lastPower = current;
2385 }
2386
2387 retval = jtag_srst_asserted(&srstAsserted);
2388 if (retval != ERROR_OK)
2389 return retval;
2390
2391 int srstDeasserted;
2392 srstDeasserted = prevSrstAsserted && !srstAsserted;
2393
2394 static long long lastSrst;
2395 waitMore = lastSrst + 2000 > current;
2396 if (srstDeasserted && !waitMore) {
2397 runSrstDeasserted = 1;
2398 lastSrst = current;
2399 }
2400
2401 if (!prevSrstAsserted && srstAsserted)
2402 runSrstAsserted = 1;
2403
2404 prevSrstAsserted = srstAsserted;
2405 prevPowerdropout = powerDropout;
2406
2407 if (srstDeasserted || powerRestored) {
2408 /* Other than logging the event we can't do anything here.
2409 * Issuing a reset is a particularly bad idea as we might
2410 * be inside a reset already.
2411 */
2412 }
2413
2414 return ERROR_OK;
2415 }
2416
2417 /* process target state changes */
2418 static int handle_target(void *priv)
2419 {
2420 Jim_Interp *interp = (Jim_Interp *)priv;
2421 int retval = ERROR_OK;
2422
2423 if (!is_jtag_poll_safe()) {
2424 /* polling is disabled currently */
2425 return ERROR_OK;
2426 }
2427
2428 /* we do not want to recurse here... */
2429 static int recursive;
2430 if (!recursive) {
2431 recursive = 1;
2432 sense_handler();
2433 /* danger! running these procedures can trigger srst assertions and power dropouts.
2434 * We need to avoid an infinite loop/recursion here and we do that by
2435 * clearing the flags after running these events.
2436 */
2437 int did_something = 0;
2438 if (runSrstAsserted) {
2439 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2440 Jim_Eval(interp, "srst_asserted");
2441 did_something = 1;
2442 }
2443 if (runSrstDeasserted) {
2444 Jim_Eval(interp, "srst_deasserted");
2445 did_something = 1;
2446 }
2447 if (runPowerDropout) {
2448 LOG_INFO("Power dropout detected, running power_dropout proc.");
2449 Jim_Eval(interp, "power_dropout");
2450 did_something = 1;
2451 }
2452 if (runPowerRestore) {
2453 Jim_Eval(interp, "power_restore");
2454 did_something = 1;
2455 }
2456
2457 if (did_something) {
2458 /* clear detect flags */
2459 sense_handler();
2460 }
2461
2462 /* clear action flags */
2463
2464 runSrstAsserted = 0;
2465 runSrstDeasserted = 0;
2466 runPowerRestore = 0;
2467 runPowerDropout = 0;
2468
2469 recursive = 0;
2470 }
2471
2472 /* Poll targets for state changes unless that's globally disabled.
2473 * Skip targets that are currently disabled.
2474 */
2475 for (struct target *target = all_targets;
2476 is_jtag_poll_safe() && target;
2477 target = target->next) {
2478
2479 if (!target_was_examined(target))
2480 continue;
2481
2482 if (!target->tap->enabled)
2483 continue;
2484
2485 if (target->backoff.times > target->backoff.count) {
2486 /* do not poll this time as we failed previously */
2487 target->backoff.count++;
2488 continue;
2489 }
2490 target->backoff.count = 0;
2491
2492 /* only poll target if we've got power and srst isn't asserted */
2493 if (!powerDropout && !srstAsserted) {
2494 /* polling may fail silently until the target has been examined */
2495 retval = target_poll(target);
2496 if (retval != ERROR_OK) {
2497 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2498 if (target->backoff.times * polling_interval < 5000) {
2499 target->backoff.times *= 2;
2500 target->backoff.times++;
2501 }
2502 LOG_USER("Polling target %s failed, GDB will be halted. Polling again in %dms",
2503 target_name(target),
2504 target->backoff.times * polling_interval);
2505
2506 /* Tell GDB to halt the debugger. This allows the user to
2507 * run monitor commands to handle the situation.
2508 */
2509 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2510 return retval;
2511 }
2512 /* Since we succeeded, we reset backoff count */
2513 if (target->backoff.times > 0) {
2514 LOG_USER("Polling target %s succeeded again, trying to reexamine", target_name(target));
2515 target_reset_examined(target);
2516 retval = target_examine_one(target);
2517 /* Target examination could have failed due to unstable connection,
2518 * but we set the examined flag anyway to repoll it later */
2519 if (retval != ERROR_OK) {
2520 target->examined = true;
2521 return retval;
2522 }
2523 }
2524
2525 target->backoff.times = 0;
2526 }
2527 }
2528
2529 return retval;
2530 }
2531
2532 COMMAND_HANDLER(handle_reg_command)
2533 {
2534 struct target *target;
2535 struct reg *reg = NULL;
2536 unsigned count = 0;
2537 char *value;
2538
2539 LOG_DEBUG("-");
2540
2541 target = get_current_target(CMD_CTX);
2542
2543 /* list all available registers for the current target */
2544 if (CMD_ARGC == 0) {
2545 struct reg_cache *cache = target->reg_cache;
2546
2547 count = 0;
2548 while (cache) {
2549 unsigned i;
2550
2551 command_print(CMD_CTX, "===== %s", cache->name);
2552
2553 for (i = 0, reg = cache->reg_list;
2554 i < cache->num_regs;
2555 i++, reg++, count++) {
2556 /* only print cached values if they are valid */
2557 if (reg->valid) {
2558 value = buf_to_str(reg->value,
2559 reg->size, 16);
2560 command_print(CMD_CTX,
2561 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2562 count, reg->name,
2563 reg->size, value,
2564 reg->dirty
2565 ? " (dirty)"
2566 : "");
2567 free(value);
2568 } else {
2569 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2570 count, reg->name,
2571 reg->size) ;
2572 }
2573 }
2574 cache = cache->next;
2575 }
2576
2577 return ERROR_OK;
2578 }
2579
2580 /* access a single register by its ordinal number */
2581 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
2582 unsigned num;
2583 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2584
2585 struct reg_cache *cache = target->reg_cache;
2586 count = 0;
2587 while (cache) {
2588 unsigned i;
2589 for (i = 0; i < cache->num_regs; i++) {
2590 if (count++ == num) {
2591 reg = &cache->reg_list[i];
2592 break;
2593 }
2594 }
2595 if (reg)
2596 break;
2597 cache = cache->next;
2598 }
2599
2600 if (!reg) {
2601 command_print(CMD_CTX, "%i is out of bounds, the current target "
2602 "has only %i registers (0 - %i)", num, count, count - 1);
2603 return ERROR_OK;
2604 }
2605 } else {
2606 /* access a single register by its name */
2607 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2608
2609 if (!reg) {
2610 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2611 return ERROR_OK;
2612 }
2613 }
2614
2615 assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
2616
2617 /* display a register */
2618 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
2619 && (CMD_ARGV[1][0] <= '9')))) {
2620 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2621 reg->valid = 0;
2622
2623 if (reg->valid == 0)
2624 reg->type->get(reg);
2625 value = buf_to_str(reg->value, reg->size, 16);
2626 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2627 free(value);
2628 return ERROR_OK;
2629 }
2630
2631 /* set register value */
2632 if (CMD_ARGC == 2) {
2633 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2634 if (buf == NULL)
2635 return ERROR_FAIL;
2636 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2637
2638 reg->type->set(reg, buf);
2639
2640 value = buf_to_str(reg->value, reg->size, 16);
2641 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2642 free(value);
2643
2644 free(buf);
2645
2646 return ERROR_OK;
2647 }
2648
2649 return ERROR_COMMAND_SYNTAX_ERROR;
2650 }
2651
2652 COMMAND_HANDLER(handle_poll_command)
2653 {
2654 int retval = ERROR_OK;
2655 struct target *target = get_current_target(CMD_CTX);
2656
2657 if (CMD_ARGC == 0) {
2658 command_print(CMD_CTX, "background polling: %s",
2659 jtag_poll_get_enabled() ? "on" : "off");
2660 command_print(CMD_CTX, "TAP: %s (%s)",
2661 target->tap->dotted_name,
2662 target->tap->enabled ? "enabled" : "disabled");
2663 if (!target->tap->enabled)
2664 return ERROR_OK;
2665 retval = target_poll(target);
2666 if (retval != ERROR_OK)
2667 return retval;
2668 retval = target_arch_state(target);
2669 if (retval != ERROR_OK)
2670 return retval;
2671 } else if (CMD_ARGC == 1) {
2672 bool enable;
2673 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2674 jtag_poll_set_enabled(enable);
2675 } else
2676 return ERROR_COMMAND_SYNTAX_ERROR;
2677
2678 return retval;
2679 }
2680
2681 COMMAND_HANDLER(handle_wait_halt_command)
2682 {
2683 if (CMD_ARGC > 1)
2684 return ERROR_COMMAND_SYNTAX_ERROR;
2685
2686 unsigned ms = DEFAULT_HALT_TIMEOUT;
2687 if (1 == CMD_ARGC) {
2688 int retval = parse_uint(CMD_ARGV[0], &ms);
2689 if (ERROR_OK != retval)
2690 return ERROR_COMMAND_SYNTAX_ERROR;
2691 }
2692
2693 struct target *target = get_current_target(CMD_CTX);
2694 return target_wait_state(target, TARGET_HALTED, ms);
2695 }
2696
2697 /* wait for target state to change. The trick here is to have a low
2698 * latency for short waits and not to suck up all the CPU time
2699 * on longer waits.
2700 *
2701 * After 500ms, keep_alive() is invoked
2702 */
2703 int target_wait_state(struct target *target, enum target_state state, int ms)
2704 {
2705 int retval;
2706 long long then = 0, cur;
2707 int once = 1;
2708
2709 for (;;) {
2710 retval = target_poll(target);
2711 if (retval != ERROR_OK)
2712 return retval;
2713 if (target->state == state)
2714 break;
2715 cur = timeval_ms();
2716 if (once) {
2717 once = 0;
2718 then = timeval_ms();
2719 LOG_DEBUG("waiting for target %s...",
2720 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2721 }
2722
2723 if (cur-then > 500)
2724 keep_alive();
2725
2726 if ((cur-then) > ms) {
2727 LOG_ERROR("timed out while waiting for target %s",
2728 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2729 return ERROR_FAIL;
2730 }
2731 }
2732
2733 return ERROR_OK;
2734 }
2735
2736 COMMAND_HANDLER(handle_halt_command)
2737 {
2738 LOG_DEBUG("-");
2739
2740 struct target *target = get_current_target(CMD_CTX);
2741 int retval = target_halt(target);
2742 if (ERROR_OK != retval)
2743 return retval;
2744
2745 if (CMD_ARGC == 1) {
2746 unsigned wait_local;
2747 retval = parse_uint(CMD_ARGV[0], &wait_local);
2748 if (ERROR_OK != retval)
2749 return ERROR_COMMAND_SYNTAX_ERROR;
2750 if (!wait_local)
2751 return ERROR_OK;
2752 }
2753
2754 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2755 }
2756
2757 COMMAND_HANDLER(handle_soft_reset_halt_command)
2758 {
2759 struct target *target = get_current_target(CMD_CTX);
2760
2761 LOG_USER("requesting target halt and executing a soft reset");
2762
2763 target_soft_reset_halt(target);
2764
2765 return ERROR_OK;
2766 }
2767
2768 COMMAND_HANDLER(handle_reset_command)
2769 {
2770 if (CMD_ARGC > 1)
2771 return ERROR_COMMAND_SYNTAX_ERROR;
2772
2773 enum target_reset_mode reset_mode = RESET_RUN;
2774 if (CMD_ARGC == 1) {
2775 const Jim_Nvp *n;
2776 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2777 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
2778 return ERROR_COMMAND_SYNTAX_ERROR;
2779 reset_mode = n->value;
2780 }
2781
2782 /* reset *all* targets */
2783 return target_process_reset(CMD_CTX, reset_mode);
2784 }
2785
2786
2787 COMMAND_HANDLER(handle_resume_command)
2788 {
2789 int current = 1;
2790 if (CMD_ARGC > 1)
2791 return ERROR_COMMAND_SYNTAX_ERROR;
2792
2793 struct target *target = get_current_target(CMD_CTX);
2794
2795 /* with no CMD_ARGV, resume from current pc, addr = 0,
2796 * with one arguments, addr = CMD_ARGV[0],
2797 * handle breakpoints, not debugging */
2798 uint32_t addr = 0;
2799 if (CMD_ARGC == 1) {
2800 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2801 current = 0;
2802 }
2803
2804 return target_resume(target, current, addr, 1, 0);
2805 }
2806
2807 COMMAND_HANDLER(handle_step_command)
2808 {
2809 if (CMD_ARGC > 1)
2810 return ERROR_COMMAND_SYNTAX_ERROR;
2811
2812 LOG_DEBUG("-");
2813
2814 /* with no CMD_ARGV, step from current pc, addr = 0,
2815 * with one argument addr = CMD_ARGV[0],
2816 * handle breakpoints, debugging */
2817 uint32_t addr = 0;
2818 int current_pc = 1;
2819 if (CMD_ARGC == 1) {
2820 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2821 current_pc = 0;
2822 }
2823
2824 struct target *target = get_current_target(CMD_CTX);
2825
2826 return target->type->step(target, current_pc, addr, 1);
2827 }
2828
2829 static void handle_md_output(struct command_context *cmd_ctx,
2830 struct target *target, uint32_t address, unsigned size,
2831 unsigned count, const uint8_t *buffer)
2832 {
2833 const unsigned line_bytecnt = 32;
2834 unsigned line_modulo = line_bytecnt / size;
2835
2836 char output[line_bytecnt * 4 + 1];
2837 unsigned output_len = 0;
2838
2839 const char *value_fmt;
2840 switch (size) {
2841 case 4:
2842 value_fmt = "%8.8x ";
2843 break;
2844 case 2:
2845 value_fmt = "%4.4x ";
2846 break;
2847 case 1:
2848 value_fmt = "%2.2x ";
2849 break;
2850 default:
2851 /* "can't happen", caller checked */
2852 LOG_ERROR("invalid memory read size: %u", size);
2853 return;
2854 }
2855
2856 for (unsigned i = 0; i < count; i++) {
2857 if (i % line_modulo == 0) {
2858 output_len += snprintf(output + output_len,
2859 sizeof(output) - output_len,
2860 "0x%8.8x: ",
2861 (unsigned)(address + (i*size)));
2862 }
2863
2864 uint32_t value = 0;
2865 const uint8_t *value_ptr = buffer + i * size;
2866 switch (size) {
2867 case 4:
2868 value = target_buffer_get_u32(target, value_ptr);
2869 break;
2870 case 2:
2871 value = target_buffer_get_u16(target, value_ptr);
2872 break;
2873 case 1:
2874 value = *value_ptr;
2875 }
2876 output_len += snprintf(output + output_len,
2877 sizeof(output) - output_len,
2878 value_fmt, value);
2879
2880 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
2881 command_print(cmd_ctx, "%s", output);
2882 output_len = 0;
2883 }
2884 }
2885 }
2886
2887 COMMAND_HANDLER(handle_md_command)
2888 {
2889 if (CMD_ARGC < 1)
2890 return ERROR_COMMAND_SYNTAX_ERROR;
2891
2892 unsigned size = 0;
2893 switch (CMD_NAME[2]) {
2894 case 'w':
2895 size = 4;
2896 break;
2897 case 'h':
2898 size = 2;
2899 break;
2900 case 'b':
2901 size = 1;
2902 break;
2903 default:
2904 return ERROR_COMMAND_SYNTAX_ERROR;
2905 }
2906
2907 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2908 int (*fn)(struct target *target,
2909 uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2910 if (physical) {
2911 CMD_ARGC--;
2912 CMD_ARGV++;
2913 fn = target_read_phys_memory;
2914 } else
2915 fn = target_read_memory;
2916 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2917 return ERROR_COMMAND_SYNTAX_ERROR;
2918
2919 uint32_t address;
2920 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2921
2922 unsigned count = 1;
2923 if (CMD_ARGC == 2)
2924 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2925
2926 uint8_t *buffer = calloc(count, size);
2927
2928 struct target *target = get_current_target(CMD_CTX);
2929 int retval = fn(target, address, size, count, buffer);
2930 if (ERROR_OK == retval)
2931 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2932
2933 free(buffer);
2934
2935 return retval;
2936 }
2937
2938 typedef int (*target_write_fn)(struct target *target,
2939 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
2940
2941 static int target_fill_mem(struct target *target,
2942 uint32_t address,
2943 target_write_fn fn,
2944 unsigned data_size,
2945 /* value */
2946 uint32_t b,
2947 /* count */
2948 unsigned c)
2949 {
2950 /* We have to write in reasonably large chunks to be able
2951 * to fill large memory areas with any sane speed */
2952 const unsigned chunk_size = 16384;
2953 uint8_t *target_buf = malloc(chunk_size * data_size);
2954 if (target_buf == NULL) {
2955 LOG_ERROR("Out of memory");
2956 return ERROR_FAIL;
2957 }
2958
2959 for (unsigned i = 0; i < chunk_size; i++) {
2960 switch (data_size) {
2961 case 4:
2962 target_buffer_set_u32(target, target_buf + i * data_size, b);
2963 break;
2964 case 2:
2965 target_buffer_set_u16(target, target_buf + i * data_size, b);
2966 break;
2967 case 1:
2968 target_buffer_set_u8(target, target_buf + i * data_size, b);
2969 break;
2970 default:
2971 exit(-1);
2972 }
2973 }
2974
2975 int retval = ERROR_OK;
2976
2977 for (unsigned x = 0; x < c; x += chunk_size) {
2978 unsigned current;
2979 current = c - x;
2980 if (current > chunk_size)
2981 current = chunk_size;
2982 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2983 if (retval != ERROR_OK)
2984 break;
2985 /* avoid GDB timeouts */
2986 keep_alive();
2987 }
2988 free(target_buf);
2989
2990 return retval;
2991 }
2992
2993
2994 COMMAND_HANDLER(handle_mw_command)
2995 {
2996 if (CMD_ARGC < 2)
2997 return ERROR_COMMAND_SYNTAX_ERROR;
2998 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2999 target_write_fn fn;
3000 if (physical) {
3001 CMD_ARGC--;
3002 CMD_ARGV++;
3003 fn = target_write_phys_memory;
3004 } else
3005 fn = target_write_memory;
3006 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
3007 return ERROR_COMMAND_SYNTAX_ERROR;
3008
3009 uint32_t address;
3010 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
3011
3012 uint32_t value;
3013 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
3014
3015 unsigned count = 1;
3016 if (CMD_ARGC == 3)
3017 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
3018
3019 struct target *target = get_current_target(CMD_CTX);
3020 unsigned wordsize;
3021 switch (CMD_NAME[2]) {
3022 case 'w':
3023 wordsize = 4;
3024 break;
3025 case 'h':
3026 wordsize = 2;
3027 break;
3028 case 'b':
3029 wordsize = 1;
3030 break;
3031 default:
3032 return ERROR_COMMAND_SYNTAX_ERROR;
3033 }
3034
3035 return target_fill_mem(target, address, fn, wordsize, value, count);
3036 }
3037
3038 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
3039 uint32_t *min_address, uint32_t *max_address)
3040 {
3041 if (CMD_ARGC < 1 || CMD_ARGC > 5)
3042 return ERROR_COMMAND_SYNTAX_ERROR;
3043
3044 /* a base address isn't always necessary,
3045 * default to 0x0 (i.e. don't relocate) */
3046 if (CMD_ARGC >= 2) {
3047 uint32_t addr;
3048 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
3049 image->base_address = addr;
3050 image->base_address_set = 1;
3051 } else
3052 image->base_address_set = 0;
3053
3054 image->start_address_set = 0;
3055
3056 if (CMD_ARGC >= 4)
3057 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
3058 if (CMD_ARGC == 5) {
3059 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
3060 /* use size (given) to find max (required) */
3061 *max_address += *min_address;
3062 }
3063
3064 if (*min_address > *max_address)
3065 return ERROR_COMMAND_SYNTAX_ERROR;
3066
3067 return ERROR_OK;
3068 }
3069
3070 COMMAND_HANDLER(handle_load_image_command)
3071 {
3072 uint8_t *buffer;
3073 size_t buf_cnt;
3074 uint32_t image_size;
3075 uint32_t min_address = 0;
3076 uint32_t max_address = 0xffffffff;
3077 int i;
3078 struct image image;
3079
3080 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
3081 &image, &min_address, &max_address);
3082 if (ERROR_OK != retval)
3083 return retval;
3084
3085 struct target *target = get_current_target(CMD_CTX);
3086
3087 struct duration bench;
3088 duration_start(&bench);
3089
3090 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
3091 return ERROR_OK;
3092
3093 image_size = 0x0;
3094 retval = ERROR_OK;
3095 for (i = 0; i < image.num_sections; i++) {
3096 buffer = malloc(image.sections[i].size);
3097 if (buffer == NULL) {
3098 command_print(CMD_CTX,
3099 "error allocating buffer for section (%d bytes)",
3100 (int)(image.sections[i].size));
3101 break;
3102 }
3103
3104 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3105 if (retval != ERROR_OK) {
3106 free(buffer);
3107 break;
3108 }
3109
3110 uint32_t offset = 0;
3111 uint32_t length = buf_cnt;
3112
3113 /* DANGER!!! beware of unsigned comparision here!!! */
3114
3115 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3116 (image.sections[i].base_address < max_address)) {
3117
3118 if (image.sections[i].base_address < min_address) {
3119 /* clip addresses below */
3120 offset += min_address-image.sections[i].base_address;
3121 length -= offset;
3122 }
3123
3124 if (image.sections[i].base_address + buf_cnt > max_address)
3125 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3126
3127 retval = target_write_buffer(target,
3128 image.sections[i].base_address + offset, length, buffer + offset);
3129 if (retval != ERROR_OK) {
3130 free(buffer);
3131 break;
3132 }
3133 image_size += length;
3134 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
3135 (unsigned int)length,
3136 image.sections[i].base_address + offset);
3137 }
3138
3139 free(buffer);
3140 }
3141
3142 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3143 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
3144 "in %fs (%0.3f KiB/s)", image_size,
3145 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3146 }
3147
3148 image_close(&image);
3149
3150 return retval;
3151
3152 }
3153
3154 COMMAND_HANDLER(handle_dump_image_command)
3155 {
3156 struct fileio fileio;
3157 uint8_t *buffer;
3158 int retval, retvaltemp;
3159 uint32_t address, size;
3160 struct duration bench;
3161 struct target *target = get_current_target(CMD_CTX);
3162
3163 if (CMD_ARGC != 3)
3164 return ERROR_COMMAND_SYNTAX_ERROR;
3165
3166 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
3167 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
3168
3169 uint32_t buf_size = (size > 4096) ? 4096 : size;
3170 buffer = malloc(buf_size);
3171 if (!buffer)
3172 return ERROR_FAIL;
3173
3174 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3175 if (retval != ERROR_OK) {
3176 free(buffer);
3177 return retval;
3178 }
3179
3180 duration_start(&bench);
3181
3182 while (size > 0) {
3183 size_t size_written;
3184 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3185 retval = target_read_buffer(target, address, this_run_size, buffer);
3186 if (retval != ERROR_OK)
3187 break;
3188
3189 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
3190 if (retval != ERROR_OK)
3191 break;
3192
3193 size -= this_run_size;
3194 address += this_run_size;
3195 }
3196
3197 free(buffer);
3198
3199 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3200 int filesize;
3201 retval = fileio_size(&fileio, &filesize);
3202 if (retval != ERROR_OK)
3203 return retval;
3204 command_print(CMD_CTX,
3205 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
3206 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3207 }
3208
3209 retvaltemp = fileio_close(&fileio);
3210 if (retvaltemp != ERROR_OK)
3211 return retvaltemp;
3212
3213 return retval;
3214 }
3215
3216 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
3217 {
3218 uint8_t *buffer;
3219 size_t buf_cnt;
3220 uint32_t image_size;
3221 int i;
3222 int retval;
3223 uint32_t checksum = 0;
3224 uint32_t mem_checksum = 0;
3225
3226 struct image image;
3227
3228 struct target *target = get_current_target(CMD_CTX);
3229
3230 if (CMD_ARGC < 1)
3231 return ERROR_COMMAND_SYNTAX_ERROR;
3232
3233 if (!target) {
3234 LOG_ERROR("no target selected");
3235 return ERROR_FAIL;
3236 }
3237
3238 struct duration bench;
3239 duration_start(&bench);
3240
3241 if (CMD_ARGC >= 2) {
3242 uint32_t addr;
3243 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
3244 image.base_address = addr;
3245 image.base_address_set = 1;
3246 } else {
3247 image.base_address_set = 0;
3248 image.base_address = 0x0;
3249 }
3250
3251 image.start_address_set = 0;
3252
3253 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3254 if (retval != ERROR_OK)
3255 return retval;
3256
3257 image_size = 0x0;
3258 int diffs = 0;
3259 retval = ERROR_OK;
3260 for (i = 0; i < image.num_sections; i++) {
3261 buffer = malloc(image.sections[i].size);
3262 if (buffer == NULL) {
3263 command_print(CMD_CTX,
3264 "error allocating buffer for section (%d bytes)",
3265 (int)(image.sections[i].size));
3266 break;
3267 }
3268 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3269 if (retval != ERROR_OK) {
3270 free(buffer);
3271 break;
3272 }
3273
3274 if (verify) {
3275 /* calculate checksum of image */
3276 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3277 if (retval != ERROR_OK) {
3278 free(buffer);
3279 break;
3280 }
3281
3282 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3283 if (retval != ERROR_OK) {
3284 free(buffer);
3285 break;
3286 }
3287
3288 if (checksum != mem_checksum) {
3289 /* failed crc checksum, fall back to a binary compare */
3290 uint8_t *data;
3291
3292 if (diffs == 0)
3293 LOG_ERROR("checksum mismatch - attempting binary compare");
3294
3295 data = malloc(buf_cnt);
3296
3297 /* Can we use 32bit word accesses? */
3298 int size = 1;
3299 int count = buf_cnt;
3300 if ((count % 4) == 0) {
3301 size *= 4;
3302 count /= 4;
3303 }
3304 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
3305 if (retval == ERROR_OK) {
3306 uint32_t t;
3307 for (t = 0; t < buf_cnt; t++) {
3308 if (data[t] != buffer[t]) {
3309 command_print(CMD_CTX,
3310 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3311 diffs,
3312 (unsigned)(t + image.sections[i].base_address),
3313 data[t],
3314 buffer[t]);
3315 if (diffs++ >= 127) {
3316 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
3317 free(data);
3318 free(buffer);
3319 goto done;
3320 }
3321 }
3322 keep_alive();
3323 }
3324 }
3325 free(data);
3326 }
3327 } else {
3328 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
3329 image.sections[i].base_address,
3330 buf_cnt);
3331 }
3332
3333 free(buffer);
3334 image_size += buf_cnt;
3335 }
3336 if (diffs > 0)
3337 command_print(CMD_CTX, "No more differences found.");
3338 done:
3339 if (diffs > 0)
3340 retval = ERROR_FAIL;
3341 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3342 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
3343 "in %fs (%0.3f KiB/s)", image_size,
3344 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3345 }
3346
3347 image_close(&image);
3348
3349 return retval;
3350 }
3351
3352 COMMAND_HANDLER(handle_verify_image_command)
3353 {
3354 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
3355 }
3356
3357 COMMAND_HANDLER(handle_test_image_command)
3358 {
3359 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
3360 }
3361
3362 static int handle_bp_command_list(struct command_context *cmd_ctx)
3363 {
3364 struct target *target = get_current_target(cmd_ctx);
3365 struct breakpoint *breakpoint = target->breakpoints;
3366 while (breakpoint) {
3367 if (breakpoint->type == BKPT_SOFT) {
3368 char *buf = buf_to_str(breakpoint->orig_instr,
3369 breakpoint->length, 16);
3370 command_print(cmd_ctx, "IVA breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
3371 breakpoint->address,
3372 breakpoint->length,
3373 breakpoint->set, buf);
3374 free(buf);
3375 } else {
3376 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3377 command_print(cmd_ctx, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3378 breakpoint->asid,
3379 breakpoint->length, breakpoint->set);
3380 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3381 command_print(cmd_ctx, "Hybrid breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3382 breakpoint->address,
3383 breakpoint->length, breakpoint->set);
3384 command_print(cmd_ctx, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3385 breakpoint->asid);
3386 } else
3387 command_print(cmd_ctx, "Breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3388 breakpoint->address,
3389 breakpoint->length, breakpoint->set);
3390 }
3391
3392 breakpoint = breakpoint->next;
3393 }
3394 return ERROR_OK;
3395 }
3396
3397 static int handle_bp_command_set(struct command_context *cmd_ctx,
3398 uint32_t addr, uint32_t asid, uint32_t length, int hw)
3399 {
3400 struct target *target = get_current_target(cmd_ctx);
3401 int retval;
3402
3403 if (asid == 0) {
3404 retval = breakpoint_add(target, addr, length, hw);
3405 if (ERROR_OK == retval)
3406 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
3407 else {
3408 LOG_ERROR("Failure setting breakpoint, the same address(IVA) is already used");
3409 return retval;
3410 }
3411 } else if (addr == 0) {
3412 if (target->type->add_context_breakpoint == NULL) {
3413 LOG_WARNING("Context breakpoint not available");
3414 return ERROR_OK;
3415 }
3416 retval = context_breakpoint_add(target, asid, length, hw);
3417 if (ERROR_OK == retval)
3418 command_print(cmd_ctx, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3419 else {
3420 LOG_ERROR("Failure setting breakpoint, the same address(CONTEXTID) is already used");
3421 return retval;
3422 }
3423 } else {
3424 if (target->type->add_hybrid_breakpoint == NULL) {
3425 LOG_WARNING("Hybrid breakpoint not available");
3426 return ERROR_OK;
3427 }
3428 retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3429 if (ERROR_OK == retval)
3430 command_print(cmd_ctx, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3431 else {
3432 LOG_ERROR("Failure setting breakpoint, the same address is already used");
3433 return retval;
3434 }
3435 }
3436 return ERROR_OK;
3437 }
3438
3439 COMMAND_HANDLER(handle_bp_command)
3440 {
3441 uint32_t addr;
3442 uint32_t asid;
3443 uint32_t length;
3444 int hw = BKPT_SOFT;
3445
3446 switch (CMD_ARGC) {
3447 case 0:
3448 return handle_bp_command_list(CMD_CTX);
3449
3450 case 2:
3451 asid = 0;
3452 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3453 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3454 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3455
3456 case 3:
3457 if (strcmp(CMD_ARGV[2], "hw") == 0) {
3458 hw = BKPT_HARD;
3459 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3460
3461 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3462
3463 asid = 0;
3464 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3465 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
3466 hw = BKPT_HARD;
3467 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
3468 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3469 addr = 0;
3470 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3471 }
3472
3473 case 4:
3474 hw = BKPT_HARD;
3475 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3476 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
3477 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
3478 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3479
3480 default:
3481 return ERROR_COMMAND_SYNTAX_ERROR;
3482 }
3483 }
3484
3485 COMMAND_HANDLER(handle_rbp_command)
3486 {
3487 if (CMD_ARGC != 1)
3488 return ERROR_COMMAND_SYNTAX_ERROR;
3489
3490 uint32_t addr;
3491 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3492
3493 struct target *target = get_current_target(CMD_CTX);
3494 breakpoint_remove(target, addr);
3495
3496 return ERROR_OK;
3497 }
3498
3499 COMMAND_HANDLER(handle_wp_command)
3500 {
3501 struct target *target = get_current_target(CMD_CTX);
3502
3503 if (CMD_ARGC == 0) {
3504 struct watchpoint *watchpoint = target->watchpoints;
3505
3506 while (watchpoint) {
3507 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
3508 ", len: 0x%8.8" PRIx32
3509 ", r/w/a: %i, value: 0x%8.8" PRIx32
3510 ", mask: 0x%8.8" PRIx32,
3511 watchpoint->address,
3512 watchpoint->length,
3513 (int)watchpoint->rw,
3514 watchpoint->value,
3515 watchpoint->mask);
3516 watchpoint = watchpoint->next;
3517 }
3518 return ERROR_OK;
3519 }
3520
3521 enum watchpoint_rw type = WPT_ACCESS;
3522 uint32_t addr = 0;
3523 uint32_t length = 0;
3524 uint32_t data_value = 0x0;
3525 uint32_t data_mask = 0xffffffff;
3526
3527 switch (CMD_ARGC) {
3528 case 5:
3529 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
3530 /* fall through */
3531 case 4:
3532 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
3533 /* fall through */
3534 case 3:
3535 switch (CMD_ARGV[2][0]) {
3536 case 'r':
3537 type = WPT_READ;
3538 break;
3539 case 'w':
3540 type = WPT_WRITE;
3541 break;
3542 case 'a':
3543 type = WPT_ACCESS;
3544 break;
3545 default:
3546 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3547 return ERROR_COMMAND_SYNTAX_ERROR;
3548 }
3549 /* fall through */
3550 case 2:
3551 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3552 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3553 break;
3554
3555 default:
3556 return ERROR_COMMAND_SYNTAX_ERROR;
3557 }
3558
3559 int retval = watchpoint_add(target, addr, length, type,
3560 data_value, data_mask);
3561 if (ERROR_OK != retval)
3562 LOG_ERROR("Failure setting watchpoints");
3563
3564 return retval;
3565 }
3566
3567 COMMAND_HANDLER(handle_rwp_command)
3568 {
3569 if (CMD_ARGC != 1)
3570 return ERROR_COMMAND_SYNTAX_ERROR;
3571
3572 uint32_t addr;
3573 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3574
3575 struct target *target = get_current_target(CMD_CTX);
3576 watchpoint_remove(target, addr);
3577
3578 return ERROR_OK;
3579 }
3580
3581 /**
3582 * Translate a virtual address to a physical address.
3583 *
3584 * The low-level target implementation must have logged a detailed error
3585 * which is forwarded to telnet/GDB session.
3586 */
3587 COMMAND_HANDLER(handle_virt2phys_command)
3588 {
3589 if (CMD_ARGC != 1)
3590 return ERROR_COMMAND_SYNTAX_ERROR;
3591
3592 uint32_t va;
3593 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3594 uint32_t pa;
3595
3596 struct target *target = get_current_target(CMD_CTX);
3597 int retval = target->type->virt2phys(target, va, &pa);
3598 if (retval == ERROR_OK)
3599 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3600
3601 return retval;
3602 }
3603
3604 static void writeData(FILE *f, const void *data, size_t len)
3605 {
3606 size_t written = fwrite(data, 1, len, f);
3607 if (written != len)
3608 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3609 }
3610
3611 static void writeLong(FILE *f, int l, struct target *target)
3612 {
3613 uint8_t val[4];
3614
3615 target_buffer_set_u32(target, val, l);
3616 writeData(f, val, 4);
3617 }
3618
3619 static void writeString(FILE *f, char *s)
3620 {
3621 writeData(f, s, strlen(s));
3622 }
3623
3624 typedef unsigned char UNIT[2]; /* unit of profiling */
3625
3626 /* Dump a gmon.out histogram file. */
3627 static void write_gmon(uint32_t *samples, uint32_t sampleNum, const char *filename, bool with_range,
3628 uint32_t start_address, uint32_t end_address, struct target *target)
3629 {
3630 uint32_t i;
3631 FILE *f = fopen(filename, "w");
3632 if (f == NULL)
3633 return;
3634 writeString(f, "gmon");
3635 writeLong(f, 0x00000001, target); /* Version */
3636 writeLong(f, 0, target); /* padding */
3637 writeLong(f, 0, target); /* padding */
3638 writeLong(f, 0, target); /* padding */
3639
3640 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3641 writeData(f, &zero, 1);
3642
3643 /* figure out bucket size */
3644 uint32_t min;
3645 uint32_t max;
3646 if (with_range) {
3647 min = start_address;
3648 max = end_address;
3649 } else {
3650 min = samples[0];
3651 max = samples[0];
3652 for (i = 0; i < sampleNum; i++) {
3653 if (min > samples[i])
3654 min = samples[i];
3655 if (max < samples[i])
3656 max = samples[i];
3657 }
3658
3659 /* max should be (largest sample + 1)
3660 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
3661 max++;
3662 }
3663
3664 int addressSpace = max - min;
3665 assert(addressSpace >= 2);
3666
3667 /* FIXME: What is the reasonable number of buckets?
3668 * The profiling result will be more accurate if there are enough buckets. */
3669 static const uint32_t maxBuckets = 128 * 1024; /* maximum buckets. */
3670 uint32_t numBuckets = addressSpace / sizeof(UNIT);
3671 if (numBuckets > maxBuckets)
3672 numBuckets = maxBuckets;
3673 int *buckets = malloc(sizeof(int) * numBuckets);
3674 if (buckets == NULL) {
3675 fclose(f);
3676 return;
3677 }
3678 memset(buckets, 0, sizeof(int) * numBuckets);
3679 for (i = 0; i < sampleNum; i++) {
3680 uint32_t address = samples[i];
3681
3682 if ((address < min) || (max <= address))
3683 continue;
3684
3685 long long a = address - min;
3686 long long b = numBuckets;
3687 long long c = addressSpace;
3688 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
3689 buckets[index_t]++;
3690 }
3691
3692 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3693 writeLong(f, min, target); /* low_pc */
3694 writeLong(f, max, target); /* high_pc */
3695 writeLong(f, numBuckets, target); /* # of buckets */
3696 writeLong(f, 100, target); /* KLUDGE! We lie, ca. 100Hz best case. */
3697 writeString(f, "seconds");
3698 for (i = 0; i < (15-strlen("seconds")); i++)
3699 writeData(f, &zero, 1);
3700 writeString(f, "s");
3701
3702 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3703
3704 char *data = malloc(2 * numBuckets);
3705 if (data != NULL) {
3706 for (i = 0; i < numBuckets; i++) {
3707 int val;
3708 val = buckets[i];
3709 if (val > 65535)
3710 val = 65535;
3711 data[i * 2] = val&0xff;
3712 data[i * 2 + 1] = (val >> 8) & 0xff;
3713 }
3714 free(buckets);
3715 writeData(f, data, numBuckets * 2);
3716 free(data);
3717 } else
3718 free(buckets);
3719
3720 fclose(f);
3721 }
3722
3723 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3724 * which will be used as a random sampling of PC */
3725 COMMAND_HANDLER(handle_profile_command)
3726 {
3727 struct target *target = get_current_target(CMD_CTX);
3728
3729 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
3730 return ERROR_COMMAND_SYNTAX_ERROR;
3731
3732 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
3733 uint32_t offset;
3734 uint32_t num_of_samples;
3735 int retval = ERROR_OK;
3736
3737 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
3738
3739 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
3740 if (samples == NULL) {
3741 LOG_ERROR("No memory to store samples.");
3742 return ERROR_FAIL;
3743 }
3744
3745 /**
3746 * Some cores let us sample the PC without the
3747 * annoying halt/resume step; for example, ARMv7 PCSR.
3748 * Provide a way to use that more efficient mechanism.
3749 */
3750 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
3751 &num_of_samples, offset);
3752 if (retval != ERROR_OK) {
3753 free(samples);
3754 return retval;
3755 }
3756
3757 assert(num_of_samples <= MAX_PROFILE_SAMPLE_NUM);
3758
3759 retval = target_poll(target);
3760 if (retval != ERROR_OK) {
3761 free(samples);
3762 return retval;
3763 }
3764 if (target->state == TARGET_RUNNING) {
3765 retval = target_halt(target);
3766 if (retval != ERROR_OK) {
3767 free(samples);
3768 return retval;
3769 }
3770 }
3771
3772 retval = target_poll(target);
3773 if (retval != ERROR_OK) {
3774 free(samples);
3775 return retval;
3776 }
3777
3778 uint32_t start_address = 0;
3779 uint32_t end_address = 0;
3780 bool with_range = false;
3781 if (CMD_ARGC == 4) {
3782 with_range = true;
3783 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
3784 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
3785 }
3786
3787 write_gmon(samples, num_of_samples, CMD_ARGV[1],
3788 with_range, start_address, end_address, target);
3789 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3790
3791 free(samples);
3792 return retval;
3793 }
3794
3795 static int new_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t val)
3796 {
3797 char *namebuf;
3798 Jim_Obj *nameObjPtr, *valObjPtr;
3799 int result;
3800
3801 namebuf = alloc_printf("%s(%d)", varname, idx);
3802 if (!namebuf)
3803 return JIM_ERR;
3804
3805 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3806 valObjPtr = Jim_NewIntObj(interp, val);
3807 if (!nameObjPtr || !valObjPtr) {
3808 free(namebuf);
3809 return JIM_ERR;
3810 }
3811
3812 Jim_IncrRefCount(nameObjPtr);
3813 Jim_IncrRefCount(valObjPtr);
3814 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3815 Jim_DecrRefCount(interp, nameObjPtr);
3816 Jim_DecrRefCount(interp, valObjPtr);
3817 free(namebuf);
3818 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3819 return result;
3820 }
3821
3822 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3823 {
3824 struct command_context *context;
3825 struct target *target;
3826
3827 context = current_command_context(interp);
3828 assert(context != NULL);
3829
3830 target = get_current_target(context);
3831 if (target == NULL) {
3832 LOG_ERROR("mem2array: no current target");
3833 return JIM_ERR;
3834 }
3835
3836 return target_mem2array(interp, target, argc - 1, argv + 1);
3837 }
3838
3839 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3840 {
3841 long l;
3842 uint32_t width;
3843 int len;
3844 uint32_t addr;
3845 uint32_t count;
3846 uint32_t v;
3847 const char *varname;
3848 int n, e, retval;
3849 uint32_t i;
3850
3851 /* argv[1] = name of array to receive the data
3852 * argv[2] = desired width
3853 * argv[3] = memory address
3854 * argv[4] = count of times to read
3855 */
3856 if (argc != 4) {
3857 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3858 return JIM_ERR;
3859 }
3860 varname = Jim_GetString(argv[0], &len);
3861 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3862
3863 e = Jim_GetLong(interp, argv[1], &l);
3864 width = l;
3865 if (e != JIM_OK)
3866 return e;
3867
3868 e = Jim_GetLong(interp, argv[2], &l);
3869 addr = l;
3870 if (e != JIM_OK)
3871 return e;
3872 e = Jim_GetLong(interp, argv[3], &l);
3873 len = l;
3874 if (e != JIM_OK)
3875 return e;
3876 switch (width) {
3877 case 8:
3878 width = 1;
3879 break;
3880 case 16:
3881 width = 2;
3882 break;
3883 case 32:
3884 width = 4;
3885 break;
3886 default:
3887 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3888 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3889 return JIM_ERR;
3890 }
3891 if (len == 0) {
3892 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3893 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3894 return JIM_ERR;
3895 }
3896 if ((addr + (len * width)) < addr) {
3897 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3898 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3899 return JIM_ERR;
3900 }
3901 /* absurd transfer size? */
3902 if (len > 65536) {
3903 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3904 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3905 return JIM_ERR;
3906 }
3907
3908 if ((width == 1) ||
3909 ((width == 2) && ((addr & 1) == 0)) ||
3910 ((width == 4) && ((addr & 3) == 0))) {
3911 /* all is well */
3912 } else {
3913 char buf[100];
3914 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3915 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3916 addr,
3917 width);
3918 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3919 return JIM_ERR;
3920 }
3921
3922 /* Transfer loop */
3923
3924 /* index counter */
3925 n = 0;
3926
3927 size_t buffersize = 4096;
3928 uint8_t *buffer = malloc(buffersize);
3929 if (buffer == NULL)
3930 return JIM_ERR;
3931
3932 /* assume ok */
3933 e = JIM_OK;
3934 while (len) {
3935 /* Slurp... in buffer size chunks */
3936
3937 count = len; /* in objects.. */
3938 if (count > (buffersize / width))
3939 count = (buffersize / width);
3940
3941 retval = target_read_memory(target, addr, width, count, buffer);
3942 if (retval != ERROR_OK) {
3943 /* BOO !*/
3944 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3945 (unsigned int)addr,
3946 (int)width,
3947 (int)count);
3948 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3949 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3950 e = JIM_ERR;
3951 break;
3952 } else {
3953 v = 0; /* shut up gcc */
3954 for (i = 0; i < count ; i++, n++) {
3955 switch (width) {
3956 case 4:
3957 v = target_buffer_get_u32(target, &buffer[i*width]);
3958 break;
3959 case 2:
3960 v = target_buffer_get_u16(target, &buffer[i*width]);
3961 break;
3962 case 1:
3963 v = buffer[i] & 0x0ff;
3964 break;
3965 }
3966 new_int_array_element(interp, varname, n, v);
3967 }
3968 len -= count;
3969 addr += count * width;
3970 }
3971 }
3972
3973 free(buffer);
3974
3975 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3976
3977 return e;
3978 }
3979
3980 static int get_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t *val)
3981 {
3982 char *namebuf;
3983 Jim_Obj *nameObjPtr, *valObjPtr;
3984 int result;
3985 long l;
3986
3987 namebuf = alloc_printf("%s(%d)", varname, idx);
3988 if (!namebuf)
3989 return JIM_ERR;
3990
3991 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3992 if (!nameObjPtr) {
3993 free(namebuf);
3994 return JIM_ERR;
3995 }
3996
3997 Jim_IncrRefCount(nameObjPtr);
3998 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3999 Jim_DecrRefCount(interp, nameObjPtr);
4000 free(namebuf);
4001 if (valObjPtr == NULL)
4002 return JIM_ERR;
4003
4004 result = Jim_GetLong(interp, valObjPtr, &l);
4005 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
4006 *val = l;
4007 return result;
4008 }
4009
4010 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4011 {
4012 struct command_context *context;
4013 struct target *target;
4014
4015 context = current_command_context(interp);
4016 assert(context != NULL);
4017
4018 target = get_current_target(context);
4019 if (target == NULL) {
4020 LOG_ERROR("array2mem: no current target");
4021 return JIM_ERR;
4022 }
4023
4024 return target_array2mem(interp, target, argc-1, argv + 1);
4025 }
4026
4027 static int target_array2mem(Jim_Interp *interp, struct target *target,
4028 int argc, Jim_Obj *const *argv)
4029 {
4030 long l;
4031 uint32_t width;
4032 int len;
4033 uint32_t addr;
4034 uint32_t count;
4035 uint32_t v;
4036 const char *varname;
4037 int n, e, retval;
4038 uint32_t i;
4039
4040 /* argv[1] = name of array to get the data
4041 * argv[2] = desired width
4042 * argv[3] = memory address
4043 * argv[4] = count to write
4044 */
4045 if (argc != 4) {
4046 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
4047 return JIM_ERR;
4048 }
4049 varname = Jim_GetString(argv[0], &len);
4050 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
4051
4052 e = Jim_GetLong(interp, argv[1], &l);
4053 width = l;
4054 if (e != JIM_OK)
4055 return e;
4056
4057 e = Jim_GetLong(interp, argv[2], &l);
4058 addr = l;
4059 if (e != JIM_OK)
4060 return e;
4061 e = Jim_GetLong(interp, argv[3], &l);
4062 len = l;
4063 if (e != JIM_OK)
4064 return e;
4065 switch (width) {
4066 case 8:
4067 width = 1;
4068 break;
4069 case 16:
4070 width = 2;
4071 break;
4072 case 32:
4073 width = 4;
4074 break;
4075 default:
4076 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4077 Jim_AppendStrings(interp, Jim_GetResult(interp),
4078 "Invalid width param, must be 8/16/32", NULL);
4079 return JIM_ERR;
4080 }
4081 if (len == 0) {
4082 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4083 Jim_AppendStrings(interp, Jim_GetResult(interp),
4084 "array2mem: zero width read?", NULL);
4085 return JIM_ERR;
4086 }
4087 if ((addr + (len * width)) < addr) {
4088 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4089 Jim_AppendStrings(interp, Jim_GetResult(interp),
4090 "array2mem: addr + len - wraps to zero?", NULL);
4091 return JIM_ERR;
4092 }
4093 /* absurd transfer size? */
4094 if (len > 65536) {
4095 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4096 Jim_AppendStrings(interp, Jim_GetResult(interp),
4097 "array2mem: absurd > 64K item request", NULL);
4098 return JIM_ERR;
4099 }
4100
4101 if ((width == 1) ||
4102 ((width == 2) && ((addr & 1) == 0)) ||
4103 ((width == 4) && ((addr & 3) == 0))) {
4104 /* all is well */
4105 } else {
4106 char buf[100];
4107 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4108 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
4109 (unsigned int)addr,
4110 (int)width);
4111 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
4112 return JIM_ERR;
4113 }
4114
4115 /* Transfer loop */
4116
4117 /* index counter */
4118 n = 0;
4119 /* assume ok */
4120 e = JIM_OK;
4121
4122 size_t buffersize = 4096;
4123 uint8_t *buffer = malloc(buffersize);
4124 if (buffer == NULL)
4125 return JIM_ERR;
4126
4127 while (len) {
4128 /* Slurp... in buffer size chunks */
4129
4130 count = len; /* in objects.. */
4131 if (count > (buffersize / width))
4132 count = (buffersize / width);
4133
4134 v = 0; /* shut up gcc */
4135 for (i = 0; i < count; i++, n++) {
4136 get_int_array_element(interp, varname, n, &v);
4137 switch (width) {
4138 case 4:
4139 target_buffer_set_u32(target, &buffer[i * width], v);
4140 break;
4141 case 2:
4142 target_buffer_set_u16(target, &buffer[i * width], v);
4143 break;
4144 case 1:
4145 buffer[i] = v & 0x0ff;
4146 break;
4147 }
4148 }
4149 len -= count;
4150
4151 retval = target_write_memory(target, addr, width, count, buffer);
4152 if (retval != ERROR_OK) {
4153 /* BOO !*/
4154 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
4155 (unsigned int)addr,
4156 (int)width,
4157 (int)count);
4158 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4159 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
4160 e = JIM_ERR;
4161 break;
4162 }
4163 addr += count * width;
4164 }
4165
4166 free(buffer);
4167
4168 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4169
4170 return e;
4171 }
4172
4173 /* FIX? should we propagate errors here rather than printing them
4174 * and continuing?
4175 */
4176 void target_handle_event(struct target *target, enum target_event e)
4177 {
4178 struct target_event_action *teap;
4179
4180 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4181 if (teap->event == e) {
4182 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
4183 target->target_number,
4184 target_name(target),
4185 target_type_name(target),
4186 e,
4187 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
4188 Jim_GetString(teap->body, NULL));
4189 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK) {
4190 Jim_MakeErrorMessage(teap->interp);
4191 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
4192 }
4193 }
4194 }
4195 }
4196
4197 /**
4198 * Returns true only if the target has a handler for the specified event.
4199 */
4200 bool target_has_event_action(struct target *target, enum target_event event)
4201 {
4202 struct target_event_action *teap;
4203
4204 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4205 if (teap->event == event)
4206 return true;
4207 }
4208 return false;
4209 }
4210
4211 enum target_cfg_param {
4212 TCFG_TYPE,
4213 TCFG_EVENT,
4214 TCFG_WORK_AREA_VIRT,
4215 TCFG_WORK_AREA_PHYS,
4216 TCFG_WORK_AREA_SIZE,
4217 TCFG_WORK_AREA_BACKUP,
4218 TCFG_ENDIAN,
4219 TCFG_COREID,
4220 TCFG_CHAIN_POSITION,
4221 TCFG_DBGBASE,
4222 TCFG_RTOS,
4223 };
4224
4225 static Jim_Nvp nvp_config_opts[] = {
4226 { .name = "-type", .value = TCFG_TYPE },
4227 { .name = "-event", .value = TCFG_EVENT },
4228 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
4229 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
4230 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
4231 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
4232 { .name = "-endian" , .value = TCFG_ENDIAN },
4233 { .name = "-coreid", .value = TCFG_COREID },
4234 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
4235 { .name = "-dbgbase", .value = TCFG_DBGBASE },
4236 { .name = "-rtos", .value = TCFG_RTOS },
4237 { .name = NULL, .value = -1 }
4238 };
4239
4240 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
4241 {
4242 Jim_Nvp *n;
4243 Jim_Obj *o;
4244 jim_wide w;
4245 int e;
4246
4247 /* parse config or cget options ... */
4248 while (goi->argc > 0) {
4249 Jim_SetEmptyResult(goi->interp);
4250 /* Jim_GetOpt_Debug(goi); */
4251
4252 if (target->type->target_jim_configure) {
4253 /* target defines a configure function */
4254 /* target gets first dibs on parameters */
4255 e = (*(target->type->target_jim_configure))(target, goi);
4256 if (e == JIM_OK) {
4257 /* more? */
4258 continue;
4259 }
4260 if (e == JIM_ERR) {
4261 /* An error */
4262 return e;
4263 }
4264 /* otherwise we 'continue' below */
4265 }
4266 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
4267 if (e != JIM_OK) {
4268 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
4269 return e;
4270 }
4271 switch (n->value) {
4272 case TCFG_TYPE:
4273 /* not setable */
4274 if (goi->isconfigure) {
4275 Jim_SetResultFormatted(goi->interp,
4276 "not settable: %s", n->name);
4277 return JIM_ERR;
4278 } else {
4279 no_params:
4280 if (goi->argc != 0) {
4281 Jim_WrongNumArgs(goi->interp,
4282 goi->argc, goi->argv,
4283 "NO PARAMS");
4284 return JIM_ERR;
4285 }
4286 }
4287 Jim_SetResultString(goi->interp,
4288 target_type_name(target), -1);
4289 /* loop for more */
4290 break;
4291 case TCFG_EVENT:
4292 if (goi->argc == 0) {
4293 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4294 return JIM_ERR;
4295 }
4296
4297 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
4298 if (e != JIM_OK) {
4299 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
4300 return e;
4301 }
4302
4303 if (goi->isconfigure) {
4304 if (goi->argc != 1) {
4305 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4306 return JIM_ERR;
4307 }
4308 } else {
4309 if (goi->argc != 0) {
4310 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4311 return JIM_ERR;
4312 }
4313 }
4314
4315 {
4316 struct target_event_action *teap;
4317
4318 teap = target->event_action;
4319 /* replace existing? */
4320 while (teap) {
4321 if (teap->event == (enum target_event)n->value)
4322 break;
4323 teap = teap->next;
4324 }
4325
4326 if (goi->isconfigure) {
4327 bool replace = true;
4328 if (teap == NULL) {
4329 /* create new */
4330 teap = calloc(1, sizeof(*teap));
4331 replace = false;
4332 }
4333 teap->event = n->value;
4334 teap->interp = goi->interp;
4335 Jim_GetOpt_Obj(goi, &o);
4336 if (teap->body)
4337 Jim_DecrRefCount(teap->interp, teap->body);
4338 teap->body = Jim_DuplicateObj(goi->interp, o);
4339 /*
4340 * FIXME:
4341 * Tcl/TK - "tk events" have a nice feature.
4342 * See the "BIND" command.
4343 * We should support that here.
4344 * You can specify %X and %Y in the event code.
4345 * The idea is: %T - target name.
4346 * The idea is: %N - target number
4347 * The idea is: %E - event name.
4348 */
4349 Jim_IncrRefCount(teap->body);
4350
4351 if (!replace) {
4352 /* add to head of event list */
4353 teap->next = target->event_action;
4354 target->event_action = teap;
4355 }
4356 Jim_SetEmptyResult(goi->interp);
4357 } else {
4358 /* get */
4359 if (teap == NULL)
4360 Jim_SetEmptyResult(goi->interp);
4361 else
4362 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
4363 }
4364 }
4365 /* loop for more */
4366 break;
4367
4368 case TCFG_WORK_AREA_VIRT:
4369 if (goi->isconfigure) {
4370 target_free_all_working_areas(target);
4371 e = Jim_GetOpt_Wide(goi, &w);
4372 if (e != JIM_OK)
4373 return e;
4374 target->working_area_virt = w;
4375 target->working_area_virt_spec = true;
4376 } else {
4377 if (goi->argc != 0)
4378 goto no_params;
4379 }
4380 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
4381 /* loop for more */
4382 break;
4383
4384 case TCFG_WORK_AREA_PHYS:
4385 if (goi->isconfigure) {
4386 target_free_all_working_areas(target);
4387 e = Jim_GetOpt_Wide(goi, &w);
4388 if (e != JIM_OK)
4389 return e;
4390 target->working_area_phys = w;
4391 target->working_area_phys_spec = true;
4392 } else {
4393 if (goi->argc != 0)
4394 goto no_params;
4395 }
4396 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
4397 /* loop for more */
4398 break;
4399
4400 case TCFG_WORK_AREA_SIZE:
4401 if (goi->isconfigure) {
4402 target_free_all_working_areas(target);
4403 e = Jim_GetOpt_Wide(goi, &w);
4404 if (e != JIM_OK)
4405 return e;
4406 target->working_area_size = w;
4407 } else {
4408 if (goi->argc != 0)
4409 goto no_params;
4410 }
4411 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4412 /* loop for more */
4413 break;
4414
4415 case TCFG_WORK_AREA_BACKUP:
4416 if (goi->isconfigure) {
4417 target_free_all_working_areas(target);
4418 e = Jim_GetOpt_Wide(goi, &w);
4419 if (e != JIM_OK)
4420 return e;
4421 /* make this exactly 1 or 0 */
4422 target->backup_working_area = (!!w);
4423 } else {
4424 if (goi->argc != 0)
4425 goto no_params;
4426 }
4427 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
4428 /* loop for more e*/
4429 break;
4430
4431
4432 case TCFG_ENDIAN:
4433 if (goi->isconfigure) {
4434 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
4435 if (e != JIM_OK) {
4436 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
4437 return e;
4438 }
4439 target->endianness = n->value;
4440 } else {
4441 if (goi->argc != 0)
4442 goto no_params;
4443 }
4444 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4445 if (n->name == NULL) {
4446 target->endianness = TARGET_LITTLE_ENDIAN;
4447 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4448 }
4449 Jim_SetResultString(goi->interp, n->name, -1);
4450 /* loop for more */
4451 break;
4452
4453 case TCFG_COREID:
4454 if (goi->isconfigure) {
4455 e = Jim_GetOpt_Wide(goi, &w);
4456 if (e != JIM_OK)
4457 return e;
4458 target->coreid = (int32_t)w;
4459 } else {
4460 if (goi->argc != 0)
4461 goto no_params;
4462 }
4463 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4464 /* loop for more */
4465 break;
4466
4467 case TCFG_CHAIN_POSITION:
4468 if (goi->isconfigure) {
4469 Jim_Obj *o_t;
4470 struct jtag_tap *tap;
4471 target_free_all_working_areas(target);
4472 e = Jim_GetOpt_Obj(goi, &o_t);
4473 if (e != JIM_OK)
4474 return e;
4475 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4476 if (tap == NULL)
4477 return JIM_ERR;
4478 /* make this exactly 1 or 0 */
4479 target->tap = tap;
4480 } else {
4481 if (goi->argc != 0)
4482 goto no_params;
4483 }
4484 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4485 /* loop for more e*/
4486 break;
4487 case TCFG_DBGBASE:
4488 if (goi->isconfigure) {
4489 e = Jim_GetOpt_Wide(goi, &w);
4490 if (e != JIM_OK)
4491 return e;
4492 target->dbgbase = (uint32_t)w;
4493 target->dbgbase_set = true;
4494 } else {
4495 if (goi->argc != 0)
4496 goto no_params;
4497 }
4498 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4499 /* loop for more */
4500 break;
4501
4502 case TCFG_RTOS:
4503 /* RTOS */
4504 {
4505 int result = rtos_create(goi, target);
4506 if (result != JIM_OK)
4507 return result;
4508 }
4509 /* loop for more */
4510 break;
4511 }
4512 } /* while (goi->argc) */
4513
4514
4515 /* done - we return */
4516 return JIM_OK;
4517 }
4518
4519 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
4520 {
4521 Jim_GetOptInfo goi;
4522
4523 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4524 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4525 int need_args = 1 + goi.isconfigure;
4526 if (goi.argc < need_args) {
4527 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4528 goi.isconfigure
4529 ? "missing: -option VALUE ..."
4530 : "missing: -option ...");
4531 return JIM_ERR;
4532 }
4533 struct target *target = Jim_CmdPrivData(goi.interp);
4534 return target_configure(&goi, target);
4535 }
4536
4537 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4538 {
4539 const char *cmd_name = Jim_GetString(argv[0], NULL);
4540
4541 Jim_GetOptInfo goi;
4542 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4543
4544 if (goi.argc < 2 || goi.argc > 4) {
4545 Jim_SetResultFormatted(goi.interp,
4546 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4547 return JIM_ERR;
4548 }
4549
4550 target_write_fn fn;
4551 fn = target_write_memory;
4552
4553 int e;
4554 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4555 /* consume it */
4556 struct Jim_Obj *obj;
4557 e = Jim_GetOpt_Obj(&goi, &obj);
4558 if (e != JIM_OK)
4559 return e;
4560
4561 fn = target_write_phys_memory;
4562 }
4563
4564 jim_wide a;
4565 e = Jim_GetOpt_Wide(&goi, &a);
4566 if (e != JIM_OK)
4567 return e;
4568
4569 jim_wide b;
4570 e = Jim_GetOpt_Wide(&goi, &b);
4571 if (e != JIM_OK)
4572 return e;
4573
4574 jim_wide c = 1;
4575 if (goi.argc == 1) {
4576 e = Jim_GetOpt_Wide(&goi, &c);
4577 if (e != JIM_OK)
4578 return e;
4579 }
4580
4581 /* all args must be consumed */
4582 if (goi.argc != 0)
4583 return JIM_ERR;
4584
4585 struct target *target = Jim_CmdPrivData(goi.interp);
4586 unsigned data_size;
4587 if (strcasecmp(cmd_name, "mww") == 0)
4588 data_size = 4;
4589 else if (strcasecmp(cmd_name, "mwh") == 0)
4590 data_size = 2;
4591 else if (strcasecmp(cmd_name, "mwb") == 0)
4592 data_size = 1;
4593 else {
4594 LOG_ERROR("command '%s' unknown: ", cmd_name);
4595 return JIM_ERR;
4596 }
4597
4598 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4599 }
4600
4601 /**
4602 * @brief Reads an array of words/halfwords/bytes from target memory starting at specified address.
4603 *
4604 * Usage: mdw [phys] <address> [<count>] - for 32 bit reads
4605 * mdh [phys] <address> [<count>] - for 16 bit reads
4606 * mdb [phys] <address> [<count>] - for 8 bit reads
4607 *
4608 * Count defaults to 1.
4609 *
4610 * Calls target_read_memory or target_read_phys_memory depending on
4611 * the presence of the "phys" argument
4612 * Reads the target memory in blocks of max. 32 bytes, and returns an array of ints formatted
4613 * to int representation in base16.
4614 * Also outputs read data in a human readable form using command_print
4615 *
4616 * @param phys if present target_read_phys_memory will be used instead of target_read_memory
4617 * @param address address where to start the read. May be specified in decimal or hex using the standard "0x" prefix
4618 * @param count optional count parameter to read an array of values. If not specified, defaults to 1.
4619 * @returns: JIM_ERR on error or JIM_OK on success and sets the result string to an array of ascii formatted numbers
4620 * on success, with [<count>] number of elements.
4621 *
4622 * In case of little endian target:
4623 * Example1: "mdw 0x00000000" returns "10123456"
4624 * Exmaple2: "mdh 0x00000000 1" returns "3456"
4625 * Example3: "mdb 0x00000000" returns "56"
4626 * Example4: "mdh 0x00000000 2" returns "3456 1012"
4627 * Example5: "mdb 0x00000000 3" returns "56 34 12"
4628 **/
4629 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4630 {
4631 const char *cmd_name = Jim_GetString(argv[0], NULL);
4632
4633 Jim_GetOptInfo goi;
4634 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4635
4636 if ((goi.argc < 1) || (goi.argc > 3)) {
4637 Jim_SetResultFormatted(goi.interp,
4638 "usage: %s [phys] <address> [<count>]", cmd_name);
4639 return JIM_ERR;
4640 }
4641
4642 int (*fn)(struct target *target,
4643 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4644 fn = target_read_memory;
4645
4646 int e;
4647 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4648 /* consume it */
4649 struct Jim_Obj *obj;
4650 e = Jim_GetOpt_Obj(&goi, &obj);
4651 if (e != JIM_OK)
4652 return e;
4653
4654 fn = target_read_phys_memory;
4655 }
4656
4657 /* Read address parameter */
4658 jim_wide addr;
4659 e = Jim_GetOpt_Wide(&goi, &addr);
4660 if (e != JIM_OK)
4661 return JIM_ERR;
4662
4663 /* If next parameter exists, read it out as the count parameter, if not, set it to 1 (default) */
4664 jim_wide count;
4665 if (goi.argc == 1) {
4666 e = Jim_GetOpt_Wide(&goi, &count);
4667 if (e != JIM_OK)
4668 return JIM_ERR;
4669 } else
4670 count = 1;
4671
4672 /* all args must be consumed */
4673 if (goi.argc != 0)
4674 return JIM_ERR;
4675
4676 jim_wide dwidth = 1; /* shut up gcc */
4677 if (strcasecmp(cmd_name, "mdw") == 0)
4678 dwidth = 4;
4679 else if (strcasecmp(cmd_name, "mdh") == 0)
4680 dwidth = 2;
4681 else if (strcasecmp(cmd_name, "mdb") == 0)
4682 dwidth = 1;
4683 else {
4684 LOG_ERROR("command '%s' unknown: ", cmd_name);
4685 return JIM_ERR;
4686 }
4687
4688 /* convert count to "bytes" */
4689 int bytes = count * dwidth;
4690
4691 struct target *target = Jim_CmdPrivData(goi.interp);
4692 uint8_t target_buf[32];
4693 jim_wide x, y, z;
4694 while (bytes > 0) {
4695 y = (bytes < 16) ? bytes : 16; /* y = min(bytes, 16); */
4696
4697 /* Try to read out next block */
4698 e = fn(target, addr, dwidth, y / dwidth, target_buf);
4699
4700 if (e != ERROR_OK) {
4701 Jim_SetResultFormatted(interp, "error reading target @ 0x%08lx", (long)addr);
4702 return JIM_ERR;
4703 }
4704
4705 command_print_sameline(NULL, "0x%08x ", (int)(addr));
4706 switch (dwidth) {
4707 case 4:
4708 for (x = 0; x < 16 && x < y; x += 4) {
4709 z = target_buffer_get_u32(target, &(target_buf[x]));
4710 command_print_sameline(NULL, "%08x ", (int)(z));
4711 }
4712 for (; (x < 16) ; x += 4)
4713 command_print_sameline(NULL, " ");
4714 break;
4715 case 2:
4716 for (x = 0; x < 16 && x < y; x += 2) {
4717 z = target_buffer_get_u16(target, &(target_buf[x]));
4718 command_print_sameline(NULL, "%04x ", (int)(z));
4719 }
4720 for (; (x < 16) ; x += 2)
4721 command_print_sameline(NULL, " ");
4722 break;
4723 case 1:
4724 default:
4725 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4726 z = target_buffer_get_u8(target, &(target_buf[x]));
4727 command_print_sameline(NULL, "%02x ", (int)(z));
4728 }
4729 for (; (x < 16) ; x += 1)
4730 command_print_sameline(NULL, " ");
4731 break;
4732 }
4733 /* ascii-ify the bytes */
4734 for (x = 0 ; x < y ; x++) {
4735 if ((target_buf[x] >= 0x20) &&
4736 (target_buf[x] <= 0x7e)) {
4737 /* good */
4738 } else {
4739 /* smack it */
4740 target_buf[x] = '.';
4741 }
4742 }
4743 /* space pad */
4744 while (x < 16) {
4745 target_buf[x] = ' ';
4746 x++;
4747 }
4748 /* terminate */
4749 target_buf[16] = 0;
4750 /* print - with a newline */
4751 command_print_sameline(NULL, "%s\n", target_buf);
4752 /* NEXT... */
4753 bytes -= 16;
4754 addr += 16;
4755 }
4756 return JIM_OK;
4757 }
4758
4759 static int jim_target_mem2array(Jim_Interp *interp,
4760 int argc, Jim_Obj *const *argv)
4761 {
4762 struct target *target = Jim_CmdPrivData(interp);
4763 return target_mem2array(interp, target, argc - 1, argv + 1);
4764 }
4765
4766 static int jim_target_array2mem(Jim_Interp *interp,
4767 int argc, Jim_Obj *const *argv)
4768 {
4769 struct target *target = Jim_CmdPrivData(interp);
4770 return target_array2mem(interp, target, argc - 1, argv + 1);
4771 }
4772
4773 static int jim_target_tap_disabled(Jim_Interp *interp)
4774 {
4775 Jim_SetResultFormatted(interp, "[TAP is disabled]");
4776 return JIM_ERR;
4777 }
4778
4779 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4780 {
4781 if (argc != 1) {
4782 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4783 return JIM_ERR;
4784 }
4785 struct target *target = Jim_CmdPrivData(interp);
4786 if (!target->tap->enabled)
4787 return jim_target_tap_disabled(interp);
4788
4789 int e = target->type->examine(target);
4790 if (e != ERROR_OK)
4791 return JIM_ERR;
4792 return JIM_OK;
4793 }
4794
4795 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4796 {
4797 if (argc != 1) {
4798 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4799 return JIM_ERR;
4800 }
4801 struct target *target = Jim_CmdPrivData(interp);
4802
4803 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4804 return JIM_ERR;
4805
4806 return JIM_OK;
4807 }
4808
4809 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4810 {
4811 if (argc != 1) {
4812 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4813 return JIM_ERR;
4814 }
4815 struct target *target = Jim_CmdPrivData(interp);
4816 if (!target->tap->enabled)
4817 return jim_target_tap_disabled(interp);
4818
4819 int e;
4820 if (!(target_was_examined(target)))
4821 e = ERROR_TARGET_NOT_EXAMINED;
4822 else
4823 e = target->type->poll(target);
4824 if (e != ERROR_OK)
4825 return JIM_ERR;
4826 return JIM_OK;
4827 }
4828
4829 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4830 {
4831 Jim_GetOptInfo goi;
4832 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4833
4834 if (goi.argc != 2) {
4835 Jim_WrongNumArgs(interp, 0, argv,
4836 "([tT]|[fF]|assert|deassert) BOOL");
4837 return JIM_ERR;
4838 }
4839
4840 Jim_Nvp *n;
4841 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4842 if (e != JIM_OK) {
4843 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4844 return e;
4845 }
4846 /* the halt or not param */
4847 jim_wide a;
4848 e = Jim_GetOpt_Wide(&goi, &a);
4849 if (e != JIM_OK)
4850 return e;
4851
4852 struct target *target = Jim_CmdPrivData(goi.interp);
4853 if (!target->tap->enabled)
4854 return jim_target_tap_disabled(interp);
4855 if (!(target_was_examined(target))) {
4856 LOG_ERROR("Target not examined yet");
4857 return ERROR_TARGET_NOT_EXAMINED;
4858 }
4859 if (!target->type->assert_reset || !target->type->deassert_reset) {
4860 Jim_SetResultFormatted(interp,
4861 "No target-specific reset for %s",
4862 target_name(target));
4863 return JIM_ERR;
4864 }
4865 /* determine if we should halt or not. */
4866 target->reset_halt = !!a;
4867 /* When this happens - all workareas are invalid. */
4868 target_free_all_working_areas_restore(target, 0);
4869
4870 /* do the assert */
4871 if (n->value == NVP_ASSERT)
4872 e = target->type->assert_reset(target);
4873 else
4874 e = target->type->deassert_reset(target);
4875 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4876 }
4877
4878 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4879 {
4880 if (argc != 1) {
4881 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4882 return JIM_ERR;
4883 }
4884 struct target *target = Jim_CmdPrivData(interp);
4885 if (!target->tap->enabled)
4886 return jim_target_tap_disabled(interp);
4887 int e = target->type->halt(target);
4888 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4889 }
4890
4891 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4892 {
4893 Jim_GetOptInfo goi;
4894 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4895
4896 /* params: <name> statename timeoutmsecs */
4897 if (goi.argc != 2) {
4898 const char *cmd_name = Jim_GetString(argv[0], NULL);
4899 Jim_SetResultFormatted(goi.interp,
4900 "%s <state_name> <timeout_in_msec>", cmd_name);
4901 return JIM_ERR;
4902 }
4903
4904 Jim_Nvp *n;
4905 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4906 if (e != JIM_OK) {
4907 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state, 1);
4908 return e;
4909 }
4910 jim_wide a;
4911 e = Jim_GetOpt_Wide(&goi, &a);
4912 if (e != JIM_OK)
4913 return e;
4914 struct target *target = Jim_CmdPrivData(interp);
4915 if (!target->tap->enabled)
4916 return jim_target_tap_disabled(interp);
4917
4918 e = target_wait_state(target, n->value, a);
4919 if (e != ERROR_OK) {
4920 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4921 Jim_SetResultFormatted(goi.interp,
4922 "target: %s wait %s fails (%#s) %s",
4923 target_name(target), n->name,
4924 eObj, target_strerror_safe(e));
4925 Jim_FreeNewObj(interp, eObj);
4926 return JIM_ERR;
4927 }
4928 return JIM_OK;
4929 }
4930 /* List for human, Events defined for this target.
4931 * scripts/programs should use 'name cget -event NAME'
4932 */
4933 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4934 {
4935 struct command_context *cmd_ctx = current_command_context(interp);
4936 assert(cmd_ctx != NULL);
4937
4938 struct target *target = Jim_CmdPrivData(interp);
4939 struct target_event_action *teap = target->event_action;
4940 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4941 target->target_number,
4942 target_name(target));
4943 command_print(cmd_ctx, "%-25s | Body", "Event");
4944 command_print(cmd_ctx, "------------------------- | "
4945 "----------------------------------------");
4946 while (teap) {
4947 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4948 command_print(cmd_ctx, "%-25s | %s",
4949 opt->name, Jim_GetString(teap->body, NULL));
4950 teap = teap->next;
4951 }
4952 command_print(cmd_ctx, "***END***");
4953 return JIM_OK;
4954 }
4955 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4956 {
4957 if (argc != 1) {
4958 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4959 return JIM_ERR;
4960 }
4961 struct target *target = Jim_CmdPrivData(interp);
4962 Jim_SetResultString(interp, target_state_name(target), -1);
4963 return JIM_OK;
4964 }
4965 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4966 {
4967 Jim_GetOptInfo goi;
4968 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4969 if (goi.argc != 1) {
4970 const char *cmd_name = Jim_GetString(argv[0], NULL);
4971 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
4972 return JIM_ERR;
4973 }
4974 Jim_Nvp *n;
4975 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4976 if (e != JIM_OK) {
4977 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4978 return e;
4979 }
4980 struct target *target = Jim_CmdPrivData(interp);
4981 target_handle_event(target, n->value);
4982 return JIM_OK;
4983 }
4984
4985 static const struct command_registration target_instance_command_handlers[] = {
4986 {
4987 .name = "configure",
4988 .mode = COMMAND_CONFIG,
4989 .jim_handler = jim_target_configure,
4990 .help = "configure a new target for use",
4991 .usage = "[target_attribute ...]",
4992 },
4993 {
4994 .name = "cget",
4995 .mode = COMMAND_ANY,
4996 .jim_handler = jim_target_configure,
4997 .help = "returns the specified target attribute",
4998 .usage = "target_attribute",
4999 },
5000 {
5001 .name = "mww",
5002 .mode = COMMAND_EXEC,
5003 .jim_handler = jim_target_mw,
5004 .help = "Write 32-bit word(s) to target memory",
5005 .usage = "address data [count]",
5006 },
5007 {
5008 .name = "mwh",
5009 .mode = COMMAND_EXEC,
5010 .jim_handler = jim_target_mw,
5011 .help = "Write 16-bit half-word(s) to target memory",
5012 .usage = "address data [count]",
5013 },
5014 {
5015 .name = "mwb",
5016 .mode = COMMAND_EXEC,
5017 .jim_handler = jim_target_mw,
5018 .help = "Write byte(s) to target memory",
5019 .usage = "address data [count]",
5020 },
5021 {
5022 .name = "mdw",
5023 .mode = COMMAND_EXEC,
5024 .jim_handler = jim_target_md,
5025 .help = "Display target memory as 32-bit words",
5026 .usage = "address [count]",
5027 },
5028 {
5029 .name = "mdh",
5030 .mode = COMMAND_EXEC,
5031 .jim_handler = jim_target_md,
5032 .help = "Display target memory as 16-bit half-words",
5033 .usage = "address [count]",
5034 },
5035 {
5036 .name = "mdb",
5037 .mode = COMMAND_EXEC,
5038 .jim_handler = jim_target_md,
5039 .help = "Display target memory as 8-bit bytes",
5040 .usage = "address [count]",
5041 },
5042 {
5043 .name = "array2mem",
5044 .mode = COMMAND_EXEC,
5045 .jim_handler = jim_target_array2mem,
5046 .help = "Writes Tcl array of 8/16/32 bit numbers "
5047 "to target memory",
5048 .usage = "arrayname bitwidth address count",
5049 },
5050 {
5051 .name = "mem2array",
5052 .mode = COMMAND_EXEC,
5053 .jim_handler = jim_target_mem2array,
5054 .help = "Loads Tcl array of 8/16/32 bit numbers "
5055 "from target memory",
5056 .usage = "arrayname bitwidth address count",
5057 },
5058 {
5059 .name = "eventlist",
5060 .mode = COMMAND_EXEC,
5061 .jim_handler = jim_target_event_list,
5062 .help = "displays a table of events defined for this target",
5063 },
5064 {
5065 .name = "curstate",
5066 .mode = COMMAND_EXEC,
5067 .jim_handler = jim_target_current_state,
5068 .help = "displays the current state of this target",
5069 },
5070 {
5071 .name = "arp_examine",
5072 .mode = COMMAND_EXEC,
5073 .jim_handler = jim_target_examine,
5074 .help = "used internally for reset processing",
5075 },
5076 {
5077 .name = "arp_halt_gdb",
5078 .mode = COMMAND_EXEC,
5079 .jim_handler = jim_target_halt_gdb,
5080 .help = "used internally for reset processing to halt GDB",
5081 },
5082 {
5083 .name = "arp_poll",
5084 .mode = COMMAND_EXEC,
5085 .jim_handler = jim_target_poll,
5086 .help = "used internally for reset processing",
5087 },
5088 {
5089 .name = "arp_reset",
5090 .mode = COMMAND_EXEC,
5091 .jim_handler = jim_target_reset,
5092 .help = "used internally for reset processing",
5093 },
5094 {
5095 .name = "arp_halt",
5096 .mode = COMMAND_EXEC,
5097 .jim_handler = jim_target_halt,
5098 .help = "used internally for reset processing",
5099 },
5100 {
5101 .name = "arp_waitstate",
5102 .mode = COMMAND_EXEC,
5103 .jim_handler = jim_target_wait_state,
5104 .help = "used internally for reset processing",
5105 },
5106 {
5107 .name = "invoke-event",
5108 .mode = COMMAND_EXEC,
5109 .jim_handler = jim_target_invoke_event,
5110 .help = "invoke handler for specified event",
5111 .usage = "event_name",
5112 },
5113 COMMAND_REGISTRATION_DONE
5114 };
5115
5116 static int target_create(Jim_GetOptInfo *goi)
5117 {
5118 Jim_Obj *new_cmd;
5119 Jim_Cmd *cmd;
5120 const char *cp;
5121 char *cp2;
5122 int e;
5123 int x;
5124 struct target *target;
5125 struct command_context *cmd_ctx;
5126
5127 cmd_ctx = current_command_context(goi->interp);
5128 assert(cmd_ctx != NULL);
5129
5130 if (goi->argc < 3) {
5131 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
5132 return JIM_ERR;
5133 }
5134
5135 /* COMMAND */
5136 Jim_GetOpt_Obj(goi, &new_cmd);
5137 /* does this command exist? */
5138 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
5139 if (cmd) {
5140 cp = Jim_GetString(new_cmd, NULL);
5141 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
5142 return JIM_ERR;
5143 }
5144
5145 /* TYPE */
5146 e = Jim_GetOpt_String(goi, &cp2, NULL);
5147 if (e != JIM_OK)
5148 return e;
5149 cp = cp2;
5150 struct transport *tr = get_current_transport();
5151 if (tr->override_target) {
5152 e = tr->override_target(&cp);
5153 if (e != ERROR_OK) {
5154 LOG_ERROR("The selected transport doesn't support this target");
5155 return JIM_ERR;
5156 }
5157 LOG_INFO("The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD");
5158 }
5159 /* now does target type exist */
5160 for (x = 0 ; target_types[x] ; x++) {
5161 if (0 == strcmp(cp, target_types[x]->name)) {
5162 /* found */
5163 break;
5164 }
5165
5166 /* check for deprecated name */
5167 if (target_types[x]->deprecated_name) {
5168 if (0 == strcmp(cp, target_types[x]->deprecated_name)) {
5169 /* found */
5170 LOG_WARNING("target name is deprecated use: \'%s\'", target_types[x]->name);
5171 break;
5172 }
5173 }
5174 }
5175 if (target_types[x] == NULL) {
5176 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
5177 for (x = 0 ; target_types[x] ; x++) {
5178 if (target_types[x + 1]) {
5179 Jim_AppendStrings(goi->interp,
5180 Jim_GetResult(goi->interp),
5181 target_types[x]->name,
5182 ", ", NULL);
5183 } else {
5184 Jim_AppendStrings(goi->interp,
5185 Jim_GetResult(goi->interp),
5186 " or ",
5187 target_types[x]->name, NULL);
5188 }
5189 }
5190 return JIM_ERR;
5191 }
5192
5193 /* Create it */
5194 target = calloc(1, sizeof(struct target));
5195 /* set target number */
5196 target->target_number = new_target_number();
5197 cmd_ctx->current_target = target->target_number;
5198
5199 /* allocate memory for each unique target type */
5200 target->type = calloc(1, sizeof(struct target_type));
5201
5202 memcpy(target->type, target_types[x], sizeof(struct target_type));
5203
5204 /* will be set by "-endian" */
5205 target->endianness = TARGET_ENDIAN_UNKNOWN;
5206
5207 /* default to first core, override with -coreid */
5208 target->coreid = 0;
5209
5210 target->working_area = 0x0;
5211 target->working_area_size = 0x0;
5212 target->working_areas = NULL;
5213 target->backup_working_area = 0;
5214
5215 target->state = TARGET_UNKNOWN;
5216 target->debug_reason = DBG_REASON_UNDEFINED;
5217 target->reg_cache = NULL;
5218 target->breakpoints = NULL;
5219 target->watchpoints = NULL;
5220 target->next = NULL;
5221 target->arch_info = NULL;
5222
5223 target->display = 1;
5224
5225 target->halt_issued = false;
5226
5227 /* initialize trace information */
5228 target->trace_info = malloc(sizeof(struct trace));
5229 target->trace_info->num_trace_points = 0;
5230 target->trace_info->trace_points_size = 0;
5231 target->trace_info->trace_points = NULL;
5232 target->trace_info->trace_history_size = 0;
5233 target->trace_info->trace_history = NULL;
5234 target->trace_info->trace_history_pos = 0;
5235 target->trace_info->trace_history_overflowed = 0;
5236
5237 target->dbgmsg = NULL;
5238 target->dbg_msg_enabled = 0;
5239
5240 target->endianness = TARGET_ENDIAN_UNKNOWN;
5241
5242 target->rtos = NULL;
5243 target->rtos_auto_detect = false;
5244
5245 /* Do the rest as "configure" options */
5246 goi->isconfigure = 1;
5247 e = target_configure(goi, target);
5248
5249 if (target->tap == NULL) {
5250 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
5251 e = JIM_ERR;
5252 }
5253
5254 if (e != JIM_OK) {
5255 free(target->type);
5256 free(target);
5257 return e;
5258 }
5259
5260 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
5261 /* default endian to little if not specified */
5262 target->endianness = TARGET_LITTLE_ENDIAN;
5263 }
5264
5265 cp = Jim_GetString(new_cmd, NULL);
5266 target->cmd_name = strdup(cp);
5267
5268 /* create the target specific commands */
5269 if (target->type->commands) {
5270 e = register_commands(cmd_ctx, NULL, target->type->commands);
5271 if (ERROR_OK != e)
5272 LOG_ERROR("unable to register '%s' commands", cp);
5273 }
5274 if (target->type->target_create)
5275 (*(target->type->target_create))(target, goi->interp);
5276
5277 /* append to end of list */
5278 {
5279 struct target **tpp;
5280 tpp = &(all_targets);
5281 while (*tpp)
5282 tpp = &((*tpp)->next);
5283 *tpp = target;
5284 }
5285
5286 /* now - create the new target name command */
5287 const struct command_registration target_subcommands[] = {
5288 {
5289 .chain = target_instance_command_handlers,
5290 },
5291 {
5292 .chain = target->type->commands,
5293 },
5294 COMMAND_REGISTRATION_DONE
5295 };
5296 const struct command_registration target_commands[] = {
5297 {
5298 .name = cp,
5299 .mode = COMMAND_ANY,
5300 .help = "target command group",
5301 .usage = "",
5302 .chain = target_subcommands,
5303 },
5304 COMMAND_REGISTRATION_DONE
5305 };
5306 e = register_commands(cmd_ctx, NULL, target_commands);
5307 if (ERROR_OK != e)
5308 return JIM_ERR;
5309
5310 struct command *c = command_find_in_context(cmd_ctx, cp);
5311 assert(c);
5312 command_set_handler_data(c, target);
5313
5314 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
5315 }
5316
5317 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5318 {
5319 if (argc != 1) {
5320 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5321 return JIM_ERR;
5322 }
5323 struct command_context *cmd_ctx = current_command_context(interp);
5324 assert(cmd_ctx != NULL);
5325
5326 Jim_SetResultString(interp, target_name(get_current_target(cmd_ctx)), -1);
5327 return JIM_OK;
5328 }
5329
5330 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5331 {
5332 if (argc != 1) {
5333 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5334 return JIM_ERR;
5335 }
5336 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5337 for (unsigned x = 0; NULL != target_types[x]; x++) {
5338 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5339 Jim_NewStringObj(interp, target_types[x]->name, -1));
5340 }
5341 return JIM_OK;
5342 }
5343
5344 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5345 {
5346 if (argc != 1) {
5347 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5348 return JIM_ERR;
5349 }
5350 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5351 struct target *target = all_targets;
5352 while (target) {
5353 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5354 Jim_NewStringObj(interp, target_name(target), -1));
5355 target = target->next;
5356 }
5357 return JIM_OK;
5358 }
5359
5360 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5361 {
5362 int i;
5363 const char *targetname;
5364 int retval, len;
5365 struct target *target = (struct target *) NULL;
5366 struct target_list *head, *curr, *new;
5367 curr = (struct target_list *) NULL;
5368 head = (struct target_list *) NULL;
5369
5370 retval = 0;
5371 LOG_DEBUG("%d", argc);
5372 /* argv[1] = target to associate in smp
5373 * argv[2] = target to assoicate in smp
5374 * argv[3] ...
5375 */
5376
5377 for (i = 1; i < argc; i++) {
5378
5379 targetname = Jim_GetString(argv[i], &len);
5380 target = get_target(targetname);
5381 LOG_DEBUG("%s ", targetname);
5382 if (target) {
5383 new = malloc(sizeof(struct target_list));
5384 new->target = target;
5385 new->next = (struct target_list *)NULL;
5386 if (head == (struct target_list *)NULL) {
5387 head = new;
5388 curr = head;
5389 } else {
5390 curr->next = new;
5391 curr = new;
5392 }
5393 }
5394 }
5395 /* now parse the list of cpu and put the target in smp mode*/
5396 curr = head;
5397
5398 while (curr != (struct target_list *)NULL) {
5399 target = curr->target;
5400 target->smp = 1;
5401 target->head = head;
5402 curr = curr->next;
5403 }
5404
5405 if (target && target->rtos)
5406 retval = rtos_smp_init(head->target);
5407
5408 return retval;
5409 }
5410
5411
5412 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5413 {
5414 Jim_GetOptInfo goi;
5415 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5416 if (goi.argc < 3) {
5417 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5418 "<name> <target_type> [<target_options> ...]");
5419 return JIM_ERR;
5420 }
5421 return target_create(&goi);
5422 }
5423
5424 static const struct command_registration target_subcommand_handlers[] = {
5425 {
5426 .name = "init",
5427 .mode = COMMAND_CONFIG,
5428 .handler = handle_target_init_command,
5429 .help = "initialize targets",
5430 },
5431 {
5432 .name = "create",
5433 /* REVISIT this should be COMMAND_CONFIG ... */
5434 .mode = COMMAND_ANY,
5435 .jim_handler = jim_target_create,
5436 .usage = "name type '-chain-position' name [options ...]",
5437 .help = "Creates and selects a new target",
5438 },
5439 {
5440 .name = "current",
5441 .mode = COMMAND_ANY,
5442 .jim_handler = jim_target_current,
5443 .help = "Returns the currently selected target",
5444 },
5445 {
5446 .name = "types",
5447 .mode = COMMAND_ANY,
5448 .jim_handler = jim_target_types,
5449 .help = "Returns the available target types as "
5450 "a list of strings",
5451 },
5452 {
5453 .name = "names",
5454 .mode = COMMAND_ANY,
5455 .jim_handler = jim_target_names,
5456 .help = "Returns the names of all targets as a list of strings",
5457 },
5458 {
5459 .name = "smp",
5460 .mode = COMMAND_ANY,
5461 .jim_handler = jim_target_smp,
5462 .usage = "targetname1 targetname2 ...",
5463 .help = "gather several target in a smp list"
5464 },
5465
5466 COMMAND_REGISTRATION_DONE
5467 };
5468
5469 struct FastLoad {
5470 uint32_t address;
5471 uint8_t *data;
5472 int length;
5473
5474 };
5475
5476 static int fastload_num;
5477 static struct FastLoad *fastload;
5478
5479 static void free_fastload(void)
5480 {
5481 if (fastload != NULL) {
5482 int i;
5483 for (i = 0; i < fastload_num; i++) {
5484 if (fastload[i].data)
5485 free(fastload[i].data);
5486 }
5487 free(fastload);
5488 fastload = NULL;
5489 }
5490 }
5491
5492 COMMAND_HANDLER(handle_fast_load_image_command)
5493 {
5494 uint8_t *buffer;
5495 size_t buf_cnt;
5496 uint32_t image_size;
5497 uint32_t min_address = 0;
5498 uint32_t max_address = 0xffffffff;
5499 int i;
5500
5501 struct image image;
5502
5503 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5504 &image, &min_address, &max_address);
5505 if (ERROR_OK != retval)
5506 return retval;
5507
5508 struct duration bench;
5509 duration_start(&bench);
5510
5511 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5512 if (retval != ERROR_OK)
5513 return retval;
5514
5515 image_size = 0x0;
5516 retval = ERROR_OK;
5517 fastload_num = image.num_sections;
5518 fastload = malloc(sizeof(struct FastLoad)*image.num_sections);
5519 if (fastload == NULL) {
5520 command_print(CMD_CTX, "out of memory");
5521 image_close(&image);
5522 return ERROR_FAIL;
5523 }
5524 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5525 for (i = 0; i < image.num_sections; i++) {
5526 buffer = malloc(image.sections[i].size);
5527 if (buffer == NULL) {
5528 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5529 (int)(image.sections[i].size));
5530 retval = ERROR_FAIL;
5531 break;
5532 }
5533
5534 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
5535 if (retval != ERROR_OK) {
5536 free(buffer);
5537 break;
5538 }
5539
5540 uint32_t offset = 0;
5541 uint32_t length = buf_cnt;
5542
5543 /* DANGER!!! beware of unsigned comparision here!!! */
5544
5545 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
5546 (image.sections[i].base_address < max_address)) {
5547 if (image.sections[i].base_address < min_address) {
5548 /* clip addresses below */
5549 offset += min_address-image.sections[i].base_address;
5550 length -= offset;
5551 }
5552
5553 if (image.sections[i].base_address + buf_cnt > max_address)
5554 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5555
5556 fastload[i].address = image.sections[i].base_address + offset;
5557 fastload[i].data = malloc(length);
5558 if (fastload[i].data == NULL) {
5559 free(buffer);
5560 command_print(CMD_CTX, "error allocating buffer for section (%" PRIu32 " bytes)",
5561 length);
5562 retval = ERROR_FAIL;
5563 break;
5564 }
5565 memcpy(fastload[i].data, buffer + offset, length);
5566 fastload[i].length = length;
5567
5568 image_size += length;
5569 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5570 (unsigned int)length,
5571 ((unsigned int)(image.sections[i].base_address + offset)));
5572 }
5573
5574 free(buffer);
5575 }
5576
5577 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
5578 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5579 "in %fs (%0.3f KiB/s)", image_size,
5580 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5581
5582 command_print(CMD_CTX,
5583 "WARNING: image has not been loaded to target!"
5584 "You can issue a 'fast_load' to finish loading.");
5585 }
5586
5587 image_close(&image);
5588
5589 if (retval != ERROR_OK)
5590 free_fastload();
5591
5592 return retval;
5593 }
5594
5595 COMMAND_HANDLER(handle_fast_load_command)
5596 {
5597 if (CMD_ARGC > 0)
5598 return ERROR_COMMAND_SYNTAX_ERROR;
5599 if (fastload == NULL) {
5600 LOG_ERROR("No image in memory");
5601 return ERROR_FAIL;
5602 }
5603 int i;
5604 int ms = timeval_ms();
5605 int size = 0;
5606 int retval = ERROR_OK;
5607 for (i = 0; i < fastload_num; i++) {
5608 struct target *target = get_current_target(CMD_CTX);
5609 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5610 (unsigned int)(fastload[i].address),
5611 (unsigned int)(fastload[i].length));
5612 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5613 if (retval != ERROR_OK)
5614 break;
5615 size += fastload[i].length;
5616 }
5617 if (retval == ERROR_OK) {
5618 int after = timeval_ms();
5619 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5620 }
5621 return retval;
5622 }
5623
5624 static const struct command_registration target_command_handlers[] = {
5625 {
5626 .name = "targets",
5627 .handler = handle_targets_command,
5628 .mode = COMMAND_ANY,
5629 .help = "change current default target (one parameter) "
5630 "or prints table of all targets (no parameters)",
5631 .usage = "[target]",
5632 },
5633 {
5634 .name = "target",
5635 .mode = COMMAND_CONFIG,
5636 .help = "configure target",
5637
5638 .chain = target_subcommand_handlers,
5639 },
5640 COMMAND_REGISTRATION_DONE
5641 };
5642
5643 int target_register_commands(struct command_context *cmd_ctx)
5644 {
5645 return register_commands(cmd_ctx, NULL, target_command_handlers);
5646 }
5647
5648 static bool target_reset_nag = true;
5649
5650 bool get_target_reset_nag(void)
5651 {
5652 return target_reset_nag;
5653 }
5654
5655 COMMAND_HANDLER(handle_target_reset_nag)
5656 {
5657 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5658 &target_reset_nag, "Nag after each reset about options to improve "
5659 "performance");
5660 }
5661
5662 COMMAND_HANDLER(handle_ps_command)
5663 {
5664 struct target *target = get_current_target(CMD_CTX);
5665 char *display;
5666 if (target->state != TARGET_HALTED) {
5667 LOG_INFO("target not halted !!");
5668 return ERROR_OK;
5669 }
5670
5671 if ((target->rtos) && (target->rtos->type)
5672 && (target->rtos->type->ps_command)) {
5673 display = target->rtos->type->ps_command(target);
5674 command_print(CMD_CTX, "%s", display);
5675 free(display);
5676 return ERROR_OK;
5677 } else {
5678 LOG_INFO("failed");
5679 return ERROR_TARGET_FAILURE;
5680 }
5681 }
5682
5683 static void binprint(struct command_context *cmd_ctx, const char *text, const uint8_t *buf, int size)
5684 {
5685 if (text != NULL)
5686 command_print_sameline(cmd_ctx, "%s", text);
5687 for (int i = 0; i < size; i++)
5688 command_print_sameline(cmd_ctx, " %02x", buf[i]);
5689 command_print(cmd_ctx, " ");
5690 }
5691
5692 COMMAND_HANDLER(handle_test_mem_access_command)
5693 {
5694 struct target *target = get_current_target(CMD_CTX);
5695 uint32_t test_size;
5696 int retval = ERROR_OK;
5697
5698 if (target->state != TARGET_HALTED) {
5699 LOG_INFO("target not halted !!");
5700 return ERROR_FAIL;
5701 }
5702
5703 if (CMD_ARGC != 1)
5704 return ERROR_COMMAND_SYNTAX_ERROR;
5705
5706 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], test_size);
5707
5708 /* Test reads */
5709 size_t num_bytes = test_size + 4;
5710
5711 struct working_area *wa = NULL;
5712 retval = target_alloc_working_area(target, num_bytes, &wa);
5713 if (retval != ERROR_OK) {
5714 LOG_ERROR("Not enough working area");
5715 return ERROR_FAIL;
5716 }
5717
5718 uint8_t *test_pattern = malloc(num_bytes);
5719
5720 for (size_t i = 0; i < num_bytes; i++)
5721 test_pattern[i] = rand();
5722
5723 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
5724 if (retval != ERROR_OK) {
5725 LOG_ERROR("Test pattern write failed");
5726 goto out;
5727 }
5728
5729 for (int host_offset = 0; host_offset <= 1; host_offset++) {
5730 for (int size = 1; size <= 4; size *= 2) {
5731 for (int offset = 0; offset < 4; offset++) {
5732 uint32_t count = test_size / size;
5733 size_t host_bufsiz = (count + 2) * size + host_offset;
5734 uint8_t *read_ref = malloc(host_bufsiz);
5735 uint8_t *read_buf = malloc(host_bufsiz);
5736
5737 for (size_t i = 0; i < host_bufsiz; i++) {
5738 read_ref[i] = rand();
5739 read_buf[i] = read_ref[i];
5740 }
5741 command_print_sameline(CMD_CTX,
5742 "Test read %" PRIu32 " x %d @ %d to %saligned buffer: ", count,
5743 size, offset, host_offset ? "un" : "");
5744
5745 struct duration bench;
5746 duration_start(&bench);
5747
5748 retval = target_read_memory(target, wa->address + offset, size, count,
5749 read_buf + size + host_offset);
5750
5751 duration_measure(&bench);
5752
5753 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
5754 command_print(CMD_CTX, "Unsupported alignment");
5755 goto next;
5756 } else if (retval != ERROR_OK) {
5757 command_print(CMD_CTX, "Memory read failed");
5758 goto next;
5759 }
5760
5761 /* replay on host */
5762 memcpy(read_ref + size + host_offset, test_pattern + offset, count * size);
5763
5764 /* check result */
5765 int result = memcmp(read_ref, read_buf, host_bufsiz);
5766 if (result == 0) {
5767 command_print(CMD_CTX, "Pass in %fs (%0.3f KiB/s)",
5768 duration_elapsed(&bench),
5769 duration_kbps(&bench, count * size));
5770 } else {
5771 command_print(CMD_CTX, "Compare failed");
5772 binprint(CMD_CTX, "ref:", read_ref, host_bufsiz);
5773 binprint(CMD_CTX, "buf:", read_buf, host_bufsiz);
5774 }
5775 next:
5776 free(read_ref);
5777 free(read_buf);
5778 }
5779 }
5780 }
5781
5782 out:
5783 free(test_pattern);
5784
5785 if (wa != NULL)
5786 target_free_working_area(target, wa);
5787
5788 /* Test writes */
5789 num_bytes = test_size + 4 + 4 + 4;
5790
5791 retval = target_alloc_working_area(target, num_bytes, &wa);
5792 if (retval != ERROR_OK) {
5793 LOG_ERROR("Not enough working area");
5794 return ERROR_FAIL;
5795 }
5796
5797 test_pattern = malloc(num_bytes);
5798
5799 for (size_t i = 0; i < num_bytes; i++)
5800 test_pattern[i] = rand();
5801
5802 for (int host_offset = 0; host_offset <= 1; host_offset++) {
5803 for (int size = 1; size <= 4; size *= 2) {
5804 for (int offset = 0; offset < 4; offset++) {
5805 uint32_t count = test_size / size;
5806 size_t host_bufsiz = count * size + host_offset;
5807 uint8_t *read_ref = malloc(num_bytes);
5808 uint8_t *read_buf = malloc(num_bytes);
5809 uint8_t *write_buf = malloc(host_bufsiz);
5810
5811 for (size_t i = 0; i < host_bufsiz; i++)
5812 write_buf[i] = rand();
5813 command_print_sameline(CMD_CTX,
5814 "Test write %" PRIu32 " x %d @ %d from %saligned buffer: ", count,
5815 size, offset, host_offset ? "un" : "");
5816
5817 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
5818 if (retval != ERROR_OK) {
5819 command_print(CMD_CTX, "Test pattern write failed");
5820 goto nextw;
5821 }
5822
5823 /* replay on host */
5824 memcpy(read_ref, test_pattern, num_bytes);
5825 memcpy(read_ref + size + offset, write_buf + host_offset, count * size);
5826
5827 struct duration bench;
5828 duration_start(&bench);
5829
5830 retval = target_write_memory(target, wa->address + size + offset, size, count,
5831 write_buf + host_offset);
5832
5833 duration_measure(&bench);
5834
5835 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
5836 command_print(CMD_CTX, "Unsupported alignment");
5837 goto nextw;
5838 } else if (retval != ERROR_OK) {
5839 command_print(CMD_CTX, "Memory write failed");
5840 goto nextw;
5841 }
5842
5843 /* read back */
5844 retval = target_read_memory(target, wa->address, 1, num_bytes, read_buf);
5845 if (retval != ERROR_OK) {
5846 command_print(CMD_CTX, "Test pattern write failed");
5847 goto nextw;
5848 }
5849
5850 /* check result */
5851 int result = memcmp(read_ref, read_buf, num_bytes);
5852 if (result == 0) {
5853 command_print(CMD_CTX, "Pass in %fs (%0.3f KiB/s)",
5854 duration_elapsed(&bench),
5855 duration_kbps(&bench, count * size));
5856 } else {
5857 command_print(CMD_CTX, "Compare failed");
5858 binprint(CMD_CTX, "ref:", read_ref, num_bytes);
5859 binprint(CMD_CTX, "buf:", read_buf, num_bytes);
5860 }
5861 nextw:
5862 free(read_ref);
5863 free(read_buf);
5864 }
5865 }
5866 }
5867
5868 free(test_pattern);
5869
5870 if (wa != NULL)
5871 target_free_working_area(target, wa);
5872 return retval;
5873 }
5874
5875 static const struct command_registration target_exec_command_handlers[] = {
5876 {
5877 .name = "fast_load_image",
5878 .handler = handle_fast_load_image_command,
5879 .mode = COMMAND_ANY,
5880 .help = "Load image into server memory for later use by "
5881 "fast_load; primarily for profiling",
5882 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5883 "[min_address [max_length]]",
5884 },
5885 {
5886 .name = "fast_load",
5887 .handler = handle_fast_load_command,
5888 .mode = COMMAND_EXEC,
5889 .help = "loads active fast load image to current target "
5890 "- mainly for profiling purposes",
5891 .usage = "",
5892 },
5893 {
5894 .name = "profile",
5895 .handler = handle_profile_command,
5896 .mode = COMMAND_EXEC,
5897 .usage = "seconds filename [start end]",
5898 .help = "profiling samples the CPU PC",
5899 },
5900 /** @todo don't register virt2phys() unless target supports it */
5901 {
5902 .name = "virt2phys",
5903 .handler = handle_virt2phys_command,
5904 .mode = COMMAND_ANY,
5905 .help = "translate a virtual address into a physical address",
5906 .usage = "virtual_address",
5907 },
5908 {
5909 .name = "reg",
5910 .handler = handle_reg_command,
5911 .mode = COMMAND_EXEC,
5912 .help = "display (reread from target with \"force\") or set a register; "
5913 "with no arguments, displays all registers and their values",
5914 .usage = "[(register_number|register_name) [(value|'force')]]",
5915 },
5916 {
5917 .name = "poll",
5918 .handler = handle_poll_command,
5919 .mode = COMMAND_EXEC,
5920 .help = "poll target state; or reconfigure background polling",
5921 .usage = "['on'|'off']",
5922 },
5923 {
5924 .name = "wait_halt",
5925 .handler = handle_wait_halt_command,
5926 .mode = COMMAND_EXEC,
5927 .help = "wait up to the specified number of milliseconds "
5928 "(default 5000) for a previously requested halt",
5929 .usage = "[milliseconds]",
5930 },
5931 {
5932 .name = "halt",
5933 .handler = handle_halt_command,
5934 .mode = COMMAND_EXEC,
5935 .help = "request target to halt, then wait up to the specified"
5936 "number of milliseconds (default 5000) for it to complete",
5937 .usage = "[milliseconds]",
5938 },
5939 {
5940 .name = "resume",
5941 .handler = handle_resume_command,
5942 .mode = COMMAND_EXEC,
5943 .help = "resume target execution from current PC or address",
5944 .usage = "[address]",
5945 },
5946 {
5947 .name = "reset",
5948 .handler = handle_reset_command,
5949 .mode = COMMAND_EXEC,
5950 .usage = "[run|halt|init]",
5951 .help = "Reset all targets into the specified mode."
5952 "Default reset mode is run, if not given.",
5953 },
5954 {
5955 .name = "soft_reset_halt",
5956 .handler = handle_soft_reset_halt_command,
5957 .mode = COMMAND_EXEC,
5958 .usage = "",
5959 .help = "halt the target and do a soft reset",
5960 },
5961 {
5962 .name = "step",
5963 .handler = handle_step_command,
5964 .mode = COMMAND_EXEC,
5965 .help = "step one instruction from current PC or address",
5966 .usage = "[address]",
5967 },
5968 {
5969 .name = "mdw",
5970 .handler = handle_md_command,
5971 .mode = COMMAND_EXEC,
5972 .help = "display memory words",
5973 .usage = "['phys'] address [count]",
5974 },
5975 {
5976 .name = "mdh",
5977 .handler = handle_md_command,
5978 .mode = COMMAND_EXEC,
5979 .help = "display memory half-words",
5980 .usage = "['phys'] address [count]",
5981 },
5982 {
5983 .name = "mdb",
5984 .handler = handle_md_command,
5985 .mode = COMMAND_EXEC,
5986 .help = "display memory bytes",
5987 .usage = "['phys'] address [count]",
5988 },
5989 {
5990 .name = "mww",
5991 .handler = handle_mw_command,
5992 .mode = COMMAND_EXEC,
5993 .help = "write memory word",
5994 .usage = "['phys'] address value [count]",
5995 },
5996 {
5997 .name = "mwh",
5998 .handler = handle_mw_command,
5999 .mode = COMMAND_EXEC,
6000 .help = "write memory half-word",
6001 .usage = "['phys'] address value [count]",
6002 },
6003 {
6004 .name = "mwb",
6005 .handler = handle_mw_command,
6006 .mode = COMMAND_EXEC,
6007 .help = "write memory byte",
6008 .usage = "['phys'] address value [count]",
6009 },
6010 {
6011 .name = "bp",
6012 .handler = handle_bp_command,
6013 .mode = COMMAND_EXEC,
6014 .help = "list or set hardware or software breakpoint",
6015 .usage = "<address> [<asid>]<length> ['hw'|'hw_ctx']",
6016 },
6017 {
6018 .name = "rbp",
6019 .handler = handle_rbp_command,
6020 .mode = COMMAND_EXEC,
6021 .help = "remove breakpoint",
6022 .usage = "address",
6023 },
6024 {
6025 .name = "wp",
6026 .handler = handle_wp_command,
6027 .mode = COMMAND_EXEC,
6028 .help = "list (no params) or create watchpoints",
6029 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
6030 },
6031 {
6032 .name = "rwp",
6033 .handler = handle_rwp_command,
6034 .mode = COMMAND_EXEC,
6035 .help = "remove watchpoint",
6036 .usage = "address",
6037 },
6038 {
6039 .name = "load_image",
6040 .handler = handle_load_image_command,
6041 .mode = COMMAND_EXEC,
6042 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6043 "[min_address] [max_length]",
6044 },
6045 {
6046 .name = "dump_image",
6047 .handler = handle_dump_image_command,
6048 .mode = COMMAND_EXEC,
6049 .usage = "filename address size",
6050 },
6051 {
6052 .name = "verify_image",
6053 .handler = handle_verify_image_command,
6054 .mode = COMMAND_EXEC,
6055 .usage = "filename [offset [type]]",
6056 },
6057 {
6058 .name = "test_image",
6059 .handler = handle_test_image_command,
6060 .mode = COMMAND_EXEC,
6061 .usage = "filename [offset [type]]",
6062 },
6063 {
6064 .name = "mem2array",
6065 .mode = COMMAND_EXEC,
6066 .jim_handler = jim_mem2array,
6067 .help = "read 8/16/32 bit memory and return as a TCL array "
6068 "for script processing",
6069 .usage = "arrayname bitwidth address count",
6070 },
6071 {
6072 .name = "array2mem",
6073 .mode = COMMAND_EXEC,
6074 .jim_handler = jim_array2mem,
6075 .help = "convert a TCL array to memory locations "
6076 "and write the 8/16/32 bit values",
6077 .usage = "arrayname bitwidth address count",
6078 },
6079 {
6080 .name = "reset_nag",
6081 .handler = handle_target_reset_nag,
6082 .mode = COMMAND_ANY,
6083 .help = "Nag after each reset about options that could have been "
6084 "enabled to improve performance. ",
6085 .usage = "['enable'|'disable']",
6086 },
6087 {
6088 .name = "ps",
6089 .handler = handle_ps_command,
6090 .mode = COMMAND_EXEC,
6091 .help = "list all tasks ",
6092 .usage = " ",
6093 },
6094 {
6095 .name = "test_mem_access",
6096 .handler = handle_test_mem_access_command,
6097 .mode = COMMAND_EXEC,
6098 .help = "Test the target's memory access functions",
6099 .usage = "size",
6100 },
6101
6102 COMMAND_REGISTRATION_DONE
6103 };
6104 static int target_register_user_commands(struct command_context *cmd_ctx)
6105 {
6106 int retval = ERROR_OK;
6107 retval = target_request_register_commands(cmd_ctx);
6108 if (retval != ERROR_OK)
6109 return retval;
6110
6111 retval = trace_register_commands(cmd_ctx);
6112 if (retval != ERROR_OK)
6113 return retval;
6114
6115
6116 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);
6117 }

Linking to existing account procedure

If you already have an account and want to add another login method you MUST first sign in with your existing account and then change URL to read https://review.openocd.org/login/?link to get to this page again but this time it'll work for linking. Thank you.

SSH host keys fingerprints

1024 SHA256:YKx8b7u5ZWdcbp7/4AeXNaqElP49m6QrwfXaqQGJAOk gerrit-code-review@openocd.zylin.com (DSA)
384 SHA256:jHIbSQa4REvwCFG4cq5LBlBLxmxSqelQPem/EXIrxjk gerrit-code-review@openocd.org (ECDSA)
521 SHA256:UAOPYkU9Fjtcao0Ul/Rrlnj/OsQvt+pgdYSZ4jOYdgs gerrit-code-review@openocd.org (ECDSA)
256 SHA256:A13M5QlnozFOvTllybRZH6vm7iSt0XLxbA48yfc2yfY gerrit-code-review@openocd.org (ECDSA)
256 SHA256:spYMBqEYoAOtK7yZBrcwE8ZpYt6b68Cfh9yEVetvbXg gerrit-code-review@openocd.org (ED25519)
+--[ED25519 256]--+
|=..              |
|+o..   .         |
|*.o   . .        |
|+B . . .         |
|Bo. = o S        |
|Oo.+ + =         |
|oB=.* = . o      |
| =+=.+   + E     |
|. .=o   . o      |
+----[SHA256]-----+
2048 SHA256:0Onrb7/PHjpo6iVZ7xQX2riKN83FJ3KGU0TvI0TaFG4 gerrit-code-review@openocd.zylin.com (RSA)