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

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)