jtag/core, target: unregister JTAG events
[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, see <http://www.gnu.org/licenses/>. *
38 ***************************************************************************/
39
40 #ifdef HAVE_CONFIG_H
41 #include "config.h"
42 #endif
43
44 #include <helper/time_support.h>
45 #include <jtag/jtag.h>
46 #include <flash/nor/core.h>
47
48 #include "target.h"
49 #include "target_type.h"
50 #include "target_request.h"
51 #include "breakpoints.h"
52 #include "register.h"
53 #include "trace.h"
54 #include "image.h"
55 #include "rtos/rtos.h"
56 #include "transport/transport.h"
57 #include "arm_cti.h"
58
59 /* default halt wait timeout (ms) */
60 #define DEFAULT_HALT_TIMEOUT 5000
61
62 static int target_read_buffer_default(struct target *target, target_addr_t address,
63 uint32_t count, uint8_t *buffer);
64 static int target_write_buffer_default(struct target *target, target_addr_t address,
65 uint32_t count, const uint8_t *buffer);
66 static int target_array2mem(Jim_Interp *interp, struct target *target,
67 int argc, Jim_Obj * const *argv);
68 static int target_mem2array(Jim_Interp *interp, struct target *target,
69 int argc, Jim_Obj * const *argv);
70 static int target_register_user_commands(struct command_context *cmd_ctx);
71 static int target_get_gdb_fileio_info_default(struct target *target,
72 struct gdb_fileio_info *fileio_info);
73 static int target_gdb_fileio_end_default(struct target *target, int retcode,
74 int fileio_errno, bool ctrl_c);
75 static int target_profiling_default(struct target *target, uint32_t *samples,
76 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds);
77
78 /* targets */
79 extern struct target_type arm7tdmi_target;
80 extern struct target_type arm720t_target;
81 extern struct target_type arm9tdmi_target;
82 extern struct target_type arm920t_target;
83 extern struct target_type arm966e_target;
84 extern struct target_type arm946e_target;
85 extern struct target_type arm926ejs_target;
86 extern struct target_type fa526_target;
87 extern struct target_type feroceon_target;
88 extern struct target_type dragonite_target;
89 extern struct target_type xscale_target;
90 extern struct target_type cortexm_target;
91 extern struct target_type cortexa_target;
92 extern struct target_type aarch64_target;
93 extern struct target_type cortexr4_target;
94 extern struct target_type arm11_target;
95 extern struct target_type ls1_sap_target;
96 extern struct target_type mips_m4k_target;
97 extern struct target_type avr_target;
98 extern struct target_type dsp563xx_target;
99 extern struct target_type dsp5680xx_target;
100 extern struct target_type testee_target;
101 extern struct target_type avr32_ap7k_target;
102 extern struct target_type hla_target;
103 extern struct target_type nds32_v2_target;
104 extern struct target_type nds32_v3_target;
105 extern struct target_type nds32_v3m_target;
106 extern struct target_type or1k_target;
107 extern struct target_type quark_x10xx_target;
108 extern struct target_type quark_d20xx_target;
109 extern struct target_type stm8_target;
110
111 static struct target_type *target_types[] = {
112 &arm7tdmi_target,
113 &arm9tdmi_target,
114 &arm920t_target,
115 &arm720t_target,
116 &arm966e_target,
117 &arm946e_target,
118 &arm926ejs_target,
119 &fa526_target,
120 &feroceon_target,
121 &dragonite_target,
122 &xscale_target,
123 &cortexm_target,
124 &cortexa_target,
125 &cortexr4_target,
126 &arm11_target,
127 &ls1_sap_target,
128 &mips_m4k_target,
129 &avr_target,
130 &dsp563xx_target,
131 &dsp5680xx_target,
132 &testee_target,
133 &avr32_ap7k_target,
134 &hla_target,
135 &nds32_v2_target,
136 &nds32_v3_target,
137 &nds32_v3m_target,
138 &or1k_target,
139 &quark_x10xx_target,
140 &quark_d20xx_target,
141 &stm8_target,
142 #if BUILD_TARGET64
143 &aarch64_target,
144 #endif
145 NULL,
146 };
147
148 struct target *all_targets;
149 static struct target_event_callback *target_event_callbacks;
150 static struct target_timer_callback *target_timer_callbacks;
151 LIST_HEAD(target_reset_callback_list);
152 LIST_HEAD(target_trace_callback_list);
153 static const int polling_interval = 100;
154
155 static const Jim_Nvp nvp_assert[] = {
156 { .name = "assert", NVP_ASSERT },
157 { .name = "deassert", NVP_DEASSERT },
158 { .name = "T", NVP_ASSERT },
159 { .name = "F", NVP_DEASSERT },
160 { .name = "t", NVP_ASSERT },
161 { .name = "f", NVP_DEASSERT },
162 { .name = NULL, .value = -1 }
163 };
164
165 static const Jim_Nvp nvp_error_target[] = {
166 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
167 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
168 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
169 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
170 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
171 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
172 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
173 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
174 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
175 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
176 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
177 { .value = -1, .name = NULL }
178 };
179
180 static const char *target_strerror_safe(int err)
181 {
182 const Jim_Nvp *n;
183
184 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
185 if (n->name == NULL)
186 return "unknown";
187 else
188 return n->name;
189 }
190
191 static const Jim_Nvp nvp_target_event[] = {
192
193 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
194 { .value = TARGET_EVENT_HALTED, .name = "halted" },
195 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
196 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
197 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
198
199 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
200 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
201
202 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
203 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
204 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
205 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
206 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
207 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
208 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
209 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
210
211 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
212 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
213
214 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
215 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
216
217 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
218 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
219
220 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
221 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
222
223 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
224 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
225
226 { .value = TARGET_EVENT_TRACE_CONFIG, .name = "trace-config" },
227
228 { .name = NULL, .value = -1 }
229 };
230
231 static const Jim_Nvp nvp_target_state[] = {
232 { .name = "unknown", .value = TARGET_UNKNOWN },
233 { .name = "running", .value = TARGET_RUNNING },
234 { .name = "halted", .value = TARGET_HALTED },
235 { .name = "reset", .value = TARGET_RESET },
236 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
237 { .name = NULL, .value = -1 },
238 };
239
240 static const Jim_Nvp nvp_target_debug_reason[] = {
241 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
242 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
243 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
244 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
245 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
246 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
247 { .name = "program-exit" , .value = DBG_REASON_EXIT },
248 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
249 { .name = NULL, .value = -1 },
250 };
251
252 static const Jim_Nvp nvp_target_endian[] = {
253 { .name = "big", .value = TARGET_BIG_ENDIAN },
254 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
255 { .name = "be", .value = TARGET_BIG_ENDIAN },
256 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
257 { .name = NULL, .value = -1 },
258 };
259
260 static const Jim_Nvp nvp_reset_modes[] = {
261 { .name = "unknown", .value = RESET_UNKNOWN },
262 { .name = "run" , .value = RESET_RUN },
263 { .name = "halt" , .value = RESET_HALT },
264 { .name = "init" , .value = RESET_INIT },
265 { .name = NULL , .value = -1 },
266 };
267
268 const char *debug_reason_name(struct target *t)
269 {
270 const char *cp;
271
272 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
273 t->debug_reason)->name;
274 if (!cp) {
275 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
276 cp = "(*BUG*unknown*BUG*)";
277 }
278 return cp;
279 }
280
281 const char *target_state_name(struct target *t)
282 {
283 const char *cp;
284 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
285 if (!cp) {
286 LOG_ERROR("Invalid target state: %d", (int)(t->state));
287 cp = "(*BUG*unknown*BUG*)";
288 }
289
290 if (!target_was_examined(t) && t->defer_examine)
291 cp = "examine deferred";
292
293 return cp;
294 }
295
296 const char *target_event_name(enum target_event event)
297 {
298 const char *cp;
299 cp = Jim_Nvp_value2name_simple(nvp_target_event, event)->name;
300 if (!cp) {
301 LOG_ERROR("Invalid target event: %d", (int)(event));
302 cp = "(*BUG*unknown*BUG*)";
303 }
304 return cp;
305 }
306
307 const char *target_reset_mode_name(enum target_reset_mode reset_mode)
308 {
309 const char *cp;
310 cp = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode)->name;
311 if (!cp) {
312 LOG_ERROR("Invalid target reset mode: %d", (int)(reset_mode));
313 cp = "(*BUG*unknown*BUG*)";
314 }
315 return cp;
316 }
317
318 /* determine the number of the new target */
319 static int new_target_number(void)
320 {
321 struct target *t;
322 int x;
323
324 /* number is 0 based */
325 x = -1;
326 t = all_targets;
327 while (t) {
328 if (x < t->target_number)
329 x = t->target_number;
330 t = t->next;
331 }
332 return x + 1;
333 }
334
335 /* read a uint64_t from a buffer in target memory endianness */
336 uint64_t target_buffer_get_u64(struct target *target, const uint8_t *buffer)
337 {
338 if (target->endianness == TARGET_LITTLE_ENDIAN)
339 return le_to_h_u64(buffer);
340 else
341 return be_to_h_u64(buffer);
342 }
343
344 /* read a uint32_t from a buffer in target memory endianness */
345 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
346 {
347 if (target->endianness == TARGET_LITTLE_ENDIAN)
348 return le_to_h_u32(buffer);
349 else
350 return be_to_h_u32(buffer);
351 }
352
353 /* read a uint24_t from a buffer in target memory endianness */
354 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
355 {
356 if (target->endianness == TARGET_LITTLE_ENDIAN)
357 return le_to_h_u24(buffer);
358 else
359 return be_to_h_u24(buffer);
360 }
361
362 /* read a uint16_t from a buffer in target memory endianness */
363 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
364 {
365 if (target->endianness == TARGET_LITTLE_ENDIAN)
366 return le_to_h_u16(buffer);
367 else
368 return be_to_h_u16(buffer);
369 }
370
371 /* read a uint8_t from a buffer in target memory endianness */
372 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
373 {
374 return *buffer & 0x0ff;
375 }
376
377 /* write a uint64_t to a buffer in target memory endianness */
378 void target_buffer_set_u64(struct target *target, uint8_t *buffer, uint64_t value)
379 {
380 if (target->endianness == TARGET_LITTLE_ENDIAN)
381 h_u64_to_le(buffer, value);
382 else
383 h_u64_to_be(buffer, value);
384 }
385
386 /* write a uint32_t to a buffer in target memory endianness */
387 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
388 {
389 if (target->endianness == TARGET_LITTLE_ENDIAN)
390 h_u32_to_le(buffer, value);
391 else
392 h_u32_to_be(buffer, value);
393 }
394
395 /* write a uint24_t to a buffer in target memory endianness */
396 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
397 {
398 if (target->endianness == TARGET_LITTLE_ENDIAN)
399 h_u24_to_le(buffer, value);
400 else
401 h_u24_to_be(buffer, value);
402 }
403
404 /* write a uint16_t to a buffer in target memory endianness */
405 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
406 {
407 if (target->endianness == TARGET_LITTLE_ENDIAN)
408 h_u16_to_le(buffer, value);
409 else
410 h_u16_to_be(buffer, value);
411 }
412
413 /* write a uint8_t to a buffer in target memory endianness */
414 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
415 {
416 *buffer = value;
417 }
418
419 /* write a uint64_t array to a buffer in target memory endianness */
420 void target_buffer_get_u64_array(struct target *target, const uint8_t *buffer, uint32_t count, uint64_t *dstbuf)
421 {
422 uint32_t i;
423 for (i = 0; i < count; i++)
424 dstbuf[i] = target_buffer_get_u64(target, &buffer[i * 8]);
425 }
426
427 /* write a uint32_t array to a buffer in target memory endianness */
428 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
429 {
430 uint32_t i;
431 for (i = 0; i < count; i++)
432 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
433 }
434
435 /* write a uint16_t array to a buffer in target memory endianness */
436 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
437 {
438 uint32_t i;
439 for (i = 0; i < count; i++)
440 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
441 }
442
443 /* write a uint64_t array to a buffer in target memory endianness */
444 void target_buffer_set_u64_array(struct target *target, uint8_t *buffer, uint32_t count, const uint64_t *srcbuf)
445 {
446 uint32_t i;
447 for (i = 0; i < count; i++)
448 target_buffer_set_u64(target, &buffer[i * 8], srcbuf[i]);
449 }
450
451 /* write a uint32_t array to a buffer in target memory endianness */
452 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, const uint32_t *srcbuf)
453 {
454 uint32_t i;
455 for (i = 0; i < count; i++)
456 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
457 }
458
459 /* write a uint16_t array to a buffer in target memory endianness */
460 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, const uint16_t *srcbuf)
461 {
462 uint32_t i;
463 for (i = 0; i < count; i++)
464 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
465 }
466
467 /* return a pointer to a configured target; id is name or number */
468 struct target *get_target(const char *id)
469 {
470 struct target *target;
471
472 /* try as tcltarget name */
473 for (target = all_targets; target; target = target->next) {
474 if (target_name(target) == NULL)
475 continue;
476 if (strcmp(id, target_name(target)) == 0)
477 return target;
478 }
479
480 /* It's OK to remove this fallback sometime after August 2010 or so */
481
482 /* no match, try as number */
483 unsigned num;
484 if (parse_uint(id, &num) != ERROR_OK)
485 return NULL;
486
487 for (target = all_targets; target; target = target->next) {
488 if (target->target_number == (int)num) {
489 LOG_WARNING("use '%s' as target identifier, not '%u'",
490 target_name(target), num);
491 return target;
492 }
493 }
494
495 return NULL;
496 }
497
498 /* returns a pointer to the n-th configured target */
499 struct target *get_target_by_num(int num)
500 {
501 struct target *target = all_targets;
502
503 while (target) {
504 if (target->target_number == num)
505 return target;
506 target = target->next;
507 }
508
509 return NULL;
510 }
511
512 struct target *get_current_target(struct command_context *cmd_ctx)
513 {
514 struct target *target = cmd_ctx->current_target_override
515 ? cmd_ctx->current_target_override
516 : cmd_ctx->current_target;
517
518 if (target == NULL) {
519 LOG_ERROR("BUG: current_target out of bounds");
520 exit(-1);
521 }
522
523 return target;
524 }
525
526 int target_poll(struct target *target)
527 {
528 int retval;
529
530 /* We can't poll until after examine */
531 if (!target_was_examined(target)) {
532 /* Fail silently lest we pollute the log */
533 return ERROR_FAIL;
534 }
535
536 retval = target->type->poll(target);
537 if (retval != ERROR_OK)
538 return retval;
539
540 if (target->halt_issued) {
541 if (target->state == TARGET_HALTED)
542 target->halt_issued = false;
543 else {
544 int64_t t = timeval_ms() - target->halt_issued_time;
545 if (t > DEFAULT_HALT_TIMEOUT) {
546 target->halt_issued = false;
547 LOG_INFO("Halt timed out, wake up GDB.");
548 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
549 }
550 }
551 }
552
553 return ERROR_OK;
554 }
555
556 int target_halt(struct target *target)
557 {
558 int retval;
559 /* We can't poll until after examine */
560 if (!target_was_examined(target)) {
561 LOG_ERROR("Target not examined yet");
562 return ERROR_FAIL;
563 }
564
565 retval = target->type->halt(target);
566 if (retval != ERROR_OK)
567 return retval;
568
569 target->halt_issued = true;
570 target->halt_issued_time = timeval_ms();
571
572 return ERROR_OK;
573 }
574
575 /**
576 * Make the target (re)start executing using its saved execution
577 * context (possibly with some modifications).
578 *
579 * @param target Which target should start executing.
580 * @param current True to use the target's saved program counter instead
581 * of the address parameter
582 * @param address Optionally used as the program counter.
583 * @param handle_breakpoints True iff breakpoints at the resumption PC
584 * should be skipped. (For example, maybe execution was stopped by
585 * such a breakpoint, in which case it would be counterprodutive to
586 * let it re-trigger.
587 * @param debug_execution False if all working areas allocated by OpenOCD
588 * should be released and/or restored to their original contents.
589 * (This would for example be true to run some downloaded "helper"
590 * algorithm code, which resides in one such working buffer and uses
591 * another for data storage.)
592 *
593 * @todo Resolve the ambiguity about what the "debug_execution" flag
594 * signifies. For example, Target implementations don't agree on how
595 * it relates to invalidation of the register cache, or to whether
596 * breakpoints and watchpoints should be enabled. (It would seem wrong
597 * to enable breakpoints when running downloaded "helper" algorithms
598 * (debug_execution true), since the breakpoints would be set to match
599 * target firmware being debugged, not the helper algorithm.... and
600 * enabling them could cause such helpers to malfunction (for example,
601 * by overwriting data with a breakpoint instruction. On the other
602 * hand the infrastructure for running such helpers might use this
603 * procedure but rely on hardware breakpoint to detect termination.)
604 */
605 int target_resume(struct target *target, int current, target_addr_t address,
606 int handle_breakpoints, int debug_execution)
607 {
608 int retval;
609
610 /* We can't poll until after examine */
611 if (!target_was_examined(target)) {
612 LOG_ERROR("Target not examined yet");
613 return ERROR_FAIL;
614 }
615
616 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
617
618 /* note that resume *must* be asynchronous. The CPU can halt before
619 * we poll. The CPU can even halt at the current PC as a result of
620 * a software breakpoint being inserted by (a bug?) the application.
621 */
622 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
623 if (retval != ERROR_OK)
624 return retval;
625
626 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
627
628 return retval;
629 }
630
631 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
632 {
633 char buf[100];
634 int retval;
635 Jim_Nvp *n;
636 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
637 if (n->name == NULL) {
638 LOG_ERROR("invalid reset mode");
639 return ERROR_FAIL;
640 }
641
642 struct target *target;
643 for (target = all_targets; target; target = target->next)
644 target_call_reset_callbacks(target, reset_mode);
645
646 /* disable polling during reset to make reset event scripts
647 * more predictable, i.e. dr/irscan & pathmove in events will
648 * not have JTAG operations injected into the middle of a sequence.
649 */
650 bool save_poll = jtag_poll_get_enabled();
651
652 jtag_poll_set_enabled(false);
653
654 sprintf(buf, "ocd_process_reset %s", n->name);
655 retval = Jim_Eval(cmd_ctx->interp, buf);
656
657 jtag_poll_set_enabled(save_poll);
658
659 if (retval != JIM_OK) {
660 Jim_MakeErrorMessage(cmd_ctx->interp);
661 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
662 return ERROR_FAIL;
663 }
664
665 /* We want any events to be processed before the prompt */
666 retval = target_call_timer_callbacks_now();
667
668 for (target = all_targets; target; target = target->next) {
669 target->type->check_reset(target);
670 target->running_alg = false;
671 }
672
673 return retval;
674 }
675
676 static int identity_virt2phys(struct target *target,
677 target_addr_t virtual, target_addr_t *physical)
678 {
679 *physical = virtual;
680 return ERROR_OK;
681 }
682
683 static int no_mmu(struct target *target, int *enabled)
684 {
685 *enabled = 0;
686 return ERROR_OK;
687 }
688
689 static int default_examine(struct target *target)
690 {
691 target_set_examined(target);
692 return ERROR_OK;
693 }
694
695 /* no check by default */
696 static int default_check_reset(struct target *target)
697 {
698 return ERROR_OK;
699 }
700
701 int target_examine_one(struct target *target)
702 {
703 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
704
705 int retval = target->type->examine(target);
706 if (retval != ERROR_OK)
707 return retval;
708
709 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
710
711 return ERROR_OK;
712 }
713
714 static int jtag_enable_callback(enum jtag_event event, void *priv)
715 {
716 struct target *target = priv;
717
718 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
719 return ERROR_OK;
720
721 jtag_unregister_event_callback(jtag_enable_callback, target);
722
723 return target_examine_one(target);
724 }
725
726 /* Targets that correctly implement init + examine, i.e.
727 * no communication with target during init:
728 *
729 * XScale
730 */
731 int target_examine(void)
732 {
733 int retval = ERROR_OK;
734 struct target *target;
735
736 for (target = all_targets; target; target = target->next) {
737 /* defer examination, but don't skip it */
738 if (!target->tap->enabled) {
739 jtag_register_event_callback(jtag_enable_callback,
740 target);
741 continue;
742 }
743
744 if (target->defer_examine)
745 continue;
746
747 retval = target_examine_one(target);
748 if (retval != ERROR_OK)
749 return retval;
750 }
751 return retval;
752 }
753
754 const char *target_type_name(struct target *target)
755 {
756 return target->type->name;
757 }
758
759 static int target_soft_reset_halt(struct target *target)
760 {
761 if (!target_was_examined(target)) {
762 LOG_ERROR("Target not examined yet");
763 return ERROR_FAIL;
764 }
765 if (!target->type->soft_reset_halt) {
766 LOG_ERROR("Target %s does not support soft_reset_halt",
767 target_name(target));
768 return ERROR_FAIL;
769 }
770 return target->type->soft_reset_halt(target);
771 }
772
773 /**
774 * Downloads a target-specific native code algorithm to the target,
775 * and executes it. * Note that some targets may need to set up, enable,
776 * and tear down a breakpoint (hard or * soft) to detect algorithm
777 * termination, while others may support lower overhead schemes where
778 * soft breakpoints embedded in the algorithm automatically terminate the
779 * algorithm.
780 *
781 * @param target used to run the algorithm
782 * @param arch_info target-specific description of the algorithm.
783 */
784 int target_run_algorithm(struct target *target,
785 int num_mem_params, struct mem_param *mem_params,
786 int num_reg_params, struct reg_param *reg_param,
787 uint32_t entry_point, uint32_t exit_point,
788 int timeout_ms, void *arch_info)
789 {
790 int retval = ERROR_FAIL;
791
792 if (!target_was_examined(target)) {
793 LOG_ERROR("Target not examined yet");
794 goto done;
795 }
796 if (!target->type->run_algorithm) {
797 LOG_ERROR("Target type '%s' does not support %s",
798 target_type_name(target), __func__);
799 goto done;
800 }
801
802 target->running_alg = true;
803 retval = target->type->run_algorithm(target,
804 num_mem_params, mem_params,
805 num_reg_params, reg_param,
806 entry_point, exit_point, timeout_ms, arch_info);
807 target->running_alg = false;
808
809 done:
810 return retval;
811 }
812
813 /**
814 * Executes a target-specific native code algorithm and leaves it running.
815 *
816 * @param target used to run the algorithm
817 * @param arch_info target-specific description of the algorithm.
818 */
819 int target_start_algorithm(struct target *target,
820 int num_mem_params, struct mem_param *mem_params,
821 int num_reg_params, struct reg_param *reg_params,
822 uint32_t entry_point, uint32_t exit_point,
823 void *arch_info)
824 {
825 int retval = ERROR_FAIL;
826
827 if (!target_was_examined(target)) {
828 LOG_ERROR("Target not examined yet");
829 goto done;
830 }
831 if (!target->type->start_algorithm) {
832 LOG_ERROR("Target type '%s' does not support %s",
833 target_type_name(target), __func__);
834 goto done;
835 }
836 if (target->running_alg) {
837 LOG_ERROR("Target is already running an algorithm");
838 goto done;
839 }
840
841 target->running_alg = true;
842 retval = target->type->start_algorithm(target,
843 num_mem_params, mem_params,
844 num_reg_params, reg_params,
845 entry_point, exit_point, arch_info);
846
847 done:
848 return retval;
849 }
850
851 /**
852 * Waits for an algorithm started with target_start_algorithm() to complete.
853 *
854 * @param target used to run the algorithm
855 * @param arch_info target-specific description of the algorithm.
856 */
857 int target_wait_algorithm(struct target *target,
858 int num_mem_params, struct mem_param *mem_params,
859 int num_reg_params, struct reg_param *reg_params,
860 uint32_t exit_point, int timeout_ms,
861 void *arch_info)
862 {
863 int retval = ERROR_FAIL;
864
865 if (!target->type->wait_algorithm) {
866 LOG_ERROR("Target type '%s' does not support %s",
867 target_type_name(target), __func__);
868 goto done;
869 }
870 if (!target->running_alg) {
871 LOG_ERROR("Target is not running an algorithm");
872 goto done;
873 }
874
875 retval = target->type->wait_algorithm(target,
876 num_mem_params, mem_params,
877 num_reg_params, reg_params,
878 exit_point, timeout_ms, arch_info);
879 if (retval != ERROR_TARGET_TIMEOUT)
880 target->running_alg = false;
881
882 done:
883 return retval;
884 }
885
886 /**
887 * Streams data to a circular buffer on target intended for consumption by code
888 * running asynchronously on target.
889 *
890 * This is intended for applications where target-specific native code runs
891 * on the target, receives data from the circular buffer, does something with
892 * it (most likely writing it to a flash memory), and advances the circular
893 * buffer pointer.
894 *
895 * This assumes that the helper algorithm has already been loaded to the target,
896 * but has not been started yet. Given memory and register parameters are passed
897 * to the algorithm.
898 *
899 * The buffer is defined by (buffer_start, buffer_size) arguments and has the
900 * following format:
901 *
902 * [buffer_start + 0, buffer_start + 4):
903 * Write Pointer address (aka head). Written and updated by this
904 * routine when new data is written to the circular buffer.
905 * [buffer_start + 4, buffer_start + 8):
906 * Read Pointer address (aka tail). Updated by code running on the
907 * target after it consumes data.
908 * [buffer_start + 8, buffer_start + buffer_size):
909 * Circular buffer contents.
910 *
911 * See contrib/loaders/flash/stm32f1x.S for an example.
912 *
913 * @param target used to run the algorithm
914 * @param buffer address on the host where data to be sent is located
915 * @param count number of blocks to send
916 * @param block_size size in bytes of each block
917 * @param num_mem_params count of memory-based params to pass to algorithm
918 * @param mem_params memory-based params to pass to algorithm
919 * @param num_reg_params count of register-based params to pass to algorithm
920 * @param reg_params memory-based params to pass to algorithm
921 * @param buffer_start address on the target of the circular buffer structure
922 * @param buffer_size size of the circular buffer structure
923 * @param entry_point address on the target to execute to start the algorithm
924 * @param exit_point address at which to set a breakpoint to catch the
925 * end of the algorithm; can be 0 if target triggers a breakpoint itself
926 */
927
928 int target_run_flash_async_algorithm(struct target *target,
929 const uint8_t *buffer, uint32_t count, int block_size,
930 int num_mem_params, struct mem_param *mem_params,
931 int num_reg_params, struct reg_param *reg_params,
932 uint32_t buffer_start, uint32_t buffer_size,
933 uint32_t entry_point, uint32_t exit_point, void *arch_info)
934 {
935 int retval;
936 int timeout = 0;
937
938 const uint8_t *buffer_orig = buffer;
939
940 /* Set up working area. First word is write pointer, second word is read pointer,
941 * rest is fifo data area. */
942 uint32_t wp_addr = buffer_start;
943 uint32_t rp_addr = buffer_start + 4;
944 uint32_t fifo_start_addr = buffer_start + 8;
945 uint32_t fifo_end_addr = buffer_start + buffer_size;
946
947 uint32_t wp = fifo_start_addr;
948 uint32_t rp = fifo_start_addr;
949
950 /* validate block_size is 2^n */
951 assert(!block_size || !(block_size & (block_size - 1)));
952
953 retval = target_write_u32(target, wp_addr, wp);
954 if (retval != ERROR_OK)
955 return retval;
956 retval = target_write_u32(target, rp_addr, rp);
957 if (retval != ERROR_OK)
958 return retval;
959
960 /* Start up algorithm on target and let it idle while writing the first chunk */
961 retval = target_start_algorithm(target, num_mem_params, mem_params,
962 num_reg_params, reg_params,
963 entry_point,
964 exit_point,
965 arch_info);
966
967 if (retval != ERROR_OK) {
968 LOG_ERROR("error starting target flash write algorithm");
969 return retval;
970 }
971
972 while (count > 0) {
973
974 retval = target_read_u32(target, rp_addr, &rp);
975 if (retval != ERROR_OK) {
976 LOG_ERROR("failed to get read pointer");
977 break;
978 }
979
980 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
981 (size_t) (buffer - buffer_orig), count, wp, rp);
982
983 if (rp == 0) {
984 LOG_ERROR("flash write algorithm aborted by target");
985 retval = ERROR_FLASH_OPERATION_FAILED;
986 break;
987 }
988
989 if (((rp - fifo_start_addr) & (block_size - 1)) || rp < fifo_start_addr || rp >= fifo_end_addr) {
990 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
991 break;
992 }
993
994 /* Count the number of bytes available in the fifo without
995 * crossing the wrap around. Make sure to not fill it completely,
996 * because that would make wp == rp and that's the empty condition. */
997 uint32_t thisrun_bytes;
998 if (rp > wp)
999 thisrun_bytes = rp - wp - block_size;
1000 else if (rp > fifo_start_addr)
1001 thisrun_bytes = fifo_end_addr - wp;
1002 else
1003 thisrun_bytes = fifo_end_addr - wp - block_size;
1004
1005 if (thisrun_bytes == 0) {
1006 /* Throttle polling a bit if transfer is (much) faster than flash
1007 * programming. The exact delay shouldn't matter as long as it's
1008 * less than buffer size / flash speed. This is very unlikely to
1009 * run when using high latency connections such as USB. */
1010 alive_sleep(10);
1011
1012 /* to stop an infinite loop on some targets check and increment a timeout
1013 * this issue was observed on a stellaris using the new ICDI interface */
1014 if (timeout++ >= 500) {
1015 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1016 return ERROR_FLASH_OPERATION_FAILED;
1017 }
1018 continue;
1019 }
1020
1021 /* reset our timeout */
1022 timeout = 0;
1023
1024 /* Limit to the amount of data we actually want to write */
1025 if (thisrun_bytes > count * block_size)
1026 thisrun_bytes = count * block_size;
1027
1028 /* Write data to fifo */
1029 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
1030 if (retval != ERROR_OK)
1031 break;
1032
1033 /* Update counters and wrap write pointer */
1034 buffer += thisrun_bytes;
1035 count -= thisrun_bytes / block_size;
1036 wp += thisrun_bytes;
1037 if (wp >= fifo_end_addr)
1038 wp = fifo_start_addr;
1039
1040 /* Store updated write pointer to target */
1041 retval = target_write_u32(target, wp_addr, wp);
1042 if (retval != ERROR_OK)
1043 break;
1044 }
1045
1046 if (retval != ERROR_OK) {
1047 /* abort flash write algorithm on target */
1048 target_write_u32(target, wp_addr, 0);
1049 }
1050
1051 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1052 num_reg_params, reg_params,
1053 exit_point,
1054 10000,
1055 arch_info);
1056
1057 if (retval2 != ERROR_OK) {
1058 LOG_ERROR("error waiting for target flash write algorithm");
1059 retval = retval2;
1060 }
1061
1062 if (retval == ERROR_OK) {
1063 /* check if algorithm set rp = 0 after fifo writer loop finished */
1064 retval = target_read_u32(target, rp_addr, &rp);
1065 if (retval == ERROR_OK && rp == 0) {
1066 LOG_ERROR("flash write algorithm aborted by target");
1067 retval = ERROR_FLASH_OPERATION_FAILED;
1068 }
1069 }
1070
1071 return retval;
1072 }
1073
1074 int target_read_memory(struct target *target,
1075 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1076 {
1077 if (!target_was_examined(target)) {
1078 LOG_ERROR("Target not examined yet");
1079 return ERROR_FAIL;
1080 }
1081 if (!target->type->read_memory) {
1082 LOG_ERROR("Target %s doesn't support read_memory", target_name(target));
1083 return ERROR_FAIL;
1084 }
1085 return target->type->read_memory(target, address, size, count, buffer);
1086 }
1087
1088 int target_read_phys_memory(struct target *target,
1089 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1090 {
1091 if (!target_was_examined(target)) {
1092 LOG_ERROR("Target not examined yet");
1093 return ERROR_FAIL;
1094 }
1095 if (!target->type->read_phys_memory) {
1096 LOG_ERROR("Target %s doesn't support read_phys_memory", target_name(target));
1097 return ERROR_FAIL;
1098 }
1099 return target->type->read_phys_memory(target, address, size, count, buffer);
1100 }
1101
1102 int target_write_memory(struct target *target,
1103 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1104 {
1105 if (!target_was_examined(target)) {
1106 LOG_ERROR("Target not examined yet");
1107 return ERROR_FAIL;
1108 }
1109 if (!target->type->write_memory) {
1110 LOG_ERROR("Target %s doesn't support write_memory", target_name(target));
1111 return ERROR_FAIL;
1112 }
1113 return target->type->write_memory(target, address, size, count, buffer);
1114 }
1115
1116 int target_write_phys_memory(struct target *target,
1117 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1118 {
1119 if (!target_was_examined(target)) {
1120 LOG_ERROR("Target not examined yet");
1121 return ERROR_FAIL;
1122 }
1123 if (!target->type->write_phys_memory) {
1124 LOG_ERROR("Target %s doesn't support write_phys_memory", target_name(target));
1125 return ERROR_FAIL;
1126 }
1127 return target->type->write_phys_memory(target, address, size, count, buffer);
1128 }
1129
1130 int target_add_breakpoint(struct target *target,
1131 struct breakpoint *breakpoint)
1132 {
1133 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
1134 LOG_WARNING("target %s is not halted (add breakpoint)", target_name(target));
1135 return ERROR_TARGET_NOT_HALTED;
1136 }
1137 return target->type->add_breakpoint(target, breakpoint);
1138 }
1139
1140 int target_add_context_breakpoint(struct target *target,
1141 struct breakpoint *breakpoint)
1142 {
1143 if (target->state != TARGET_HALTED) {
1144 LOG_WARNING("target %s is not halted (add context breakpoint)", target_name(target));
1145 return ERROR_TARGET_NOT_HALTED;
1146 }
1147 return target->type->add_context_breakpoint(target, breakpoint);
1148 }
1149
1150 int target_add_hybrid_breakpoint(struct target *target,
1151 struct breakpoint *breakpoint)
1152 {
1153 if (target->state != TARGET_HALTED) {
1154 LOG_WARNING("target %s is not halted (add hybrid breakpoint)", target_name(target));
1155 return ERROR_TARGET_NOT_HALTED;
1156 }
1157 return target->type->add_hybrid_breakpoint(target, breakpoint);
1158 }
1159
1160 int target_remove_breakpoint(struct target *target,
1161 struct breakpoint *breakpoint)
1162 {
1163 return target->type->remove_breakpoint(target, breakpoint);
1164 }
1165
1166 int target_add_watchpoint(struct target *target,
1167 struct watchpoint *watchpoint)
1168 {
1169 if (target->state != TARGET_HALTED) {
1170 LOG_WARNING("target %s is not halted (add watchpoint)", target_name(target));
1171 return ERROR_TARGET_NOT_HALTED;
1172 }
1173 return target->type->add_watchpoint(target, watchpoint);
1174 }
1175 int target_remove_watchpoint(struct target *target,
1176 struct watchpoint *watchpoint)
1177 {
1178 return target->type->remove_watchpoint(target, watchpoint);
1179 }
1180 int target_hit_watchpoint(struct target *target,
1181 struct watchpoint **hit_watchpoint)
1182 {
1183 if (target->state != TARGET_HALTED) {
1184 LOG_WARNING("target %s is not halted (hit watchpoint)", target->cmd_name);
1185 return ERROR_TARGET_NOT_HALTED;
1186 }
1187
1188 if (target->type->hit_watchpoint == NULL) {
1189 /* For backward compatible, if hit_watchpoint is not implemented,
1190 * return ERROR_FAIL such that gdb_server will not take the nonsense
1191 * information. */
1192 return ERROR_FAIL;
1193 }
1194
1195 return target->type->hit_watchpoint(target, hit_watchpoint);
1196 }
1197
1198 int target_get_gdb_reg_list(struct target *target,
1199 struct reg **reg_list[], int *reg_list_size,
1200 enum target_register_class reg_class)
1201 {
1202 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1203 }
1204 int target_step(struct target *target,
1205 int current, target_addr_t address, int handle_breakpoints)
1206 {
1207 return target->type->step(target, current, address, handle_breakpoints);
1208 }
1209
1210 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1211 {
1212 if (target->state != TARGET_HALTED) {
1213 LOG_WARNING("target %s is not halted (gdb fileio)", target->cmd_name);
1214 return ERROR_TARGET_NOT_HALTED;
1215 }
1216 return target->type->get_gdb_fileio_info(target, fileio_info);
1217 }
1218
1219 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1220 {
1221 if (target->state != TARGET_HALTED) {
1222 LOG_WARNING("target %s is not halted (gdb fileio end)", target->cmd_name);
1223 return ERROR_TARGET_NOT_HALTED;
1224 }
1225 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1226 }
1227
1228 int target_profiling(struct target *target, uint32_t *samples,
1229 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1230 {
1231 if (target->state != TARGET_HALTED) {
1232 LOG_WARNING("target %s is not halted (profiling)", target->cmd_name);
1233 return ERROR_TARGET_NOT_HALTED;
1234 }
1235 return target->type->profiling(target, samples, max_num_samples,
1236 num_samples, seconds);
1237 }
1238
1239 /**
1240 * Reset the @c examined flag for the given target.
1241 * Pure paranoia -- targets are zeroed on allocation.
1242 */
1243 static void target_reset_examined(struct target *target)
1244 {
1245 target->examined = false;
1246 }
1247
1248 static int handle_target(void *priv);
1249
1250 static int target_init_one(struct command_context *cmd_ctx,
1251 struct target *target)
1252 {
1253 target_reset_examined(target);
1254
1255 struct target_type *type = target->type;
1256 if (type->examine == NULL)
1257 type->examine = default_examine;
1258
1259 if (type->check_reset == NULL)
1260 type->check_reset = default_check_reset;
1261
1262 assert(type->init_target != NULL);
1263
1264 int retval = type->init_target(cmd_ctx, target);
1265 if (ERROR_OK != retval) {
1266 LOG_ERROR("target '%s' init failed", target_name(target));
1267 return retval;
1268 }
1269
1270 /* Sanity-check MMU support ... stub in what we must, to help
1271 * implement it in stages, but warn if we need to do so.
1272 */
1273 if (type->mmu) {
1274 if (type->virt2phys == NULL) {
1275 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1276 type->virt2phys = identity_virt2phys;
1277 }
1278 } else {
1279 /* Make sure no-MMU targets all behave the same: make no
1280 * distinction between physical and virtual addresses, and
1281 * ensure that virt2phys() is always an identity mapping.
1282 */
1283 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1284 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1285
1286 type->mmu = no_mmu;
1287 type->write_phys_memory = type->write_memory;
1288 type->read_phys_memory = type->read_memory;
1289 type->virt2phys = identity_virt2phys;
1290 }
1291
1292 if (target->type->read_buffer == NULL)
1293 target->type->read_buffer = target_read_buffer_default;
1294
1295 if (target->type->write_buffer == NULL)
1296 target->type->write_buffer = target_write_buffer_default;
1297
1298 if (target->type->get_gdb_fileio_info == NULL)
1299 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1300
1301 if (target->type->gdb_fileio_end == NULL)
1302 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1303
1304 if (target->type->profiling == NULL)
1305 target->type->profiling = target_profiling_default;
1306
1307 return ERROR_OK;
1308 }
1309
1310 static int target_init(struct command_context *cmd_ctx)
1311 {
1312 struct target *target;
1313 int retval;
1314
1315 for (target = all_targets; target; target = target->next) {
1316 retval = target_init_one(cmd_ctx, target);
1317 if (ERROR_OK != retval)
1318 return retval;
1319 }
1320
1321 if (!all_targets)
1322 return ERROR_OK;
1323
1324 retval = target_register_user_commands(cmd_ctx);
1325 if (ERROR_OK != retval)
1326 return retval;
1327
1328 retval = target_register_timer_callback(&handle_target,
1329 polling_interval, 1, cmd_ctx->interp);
1330 if (ERROR_OK != retval)
1331 return retval;
1332
1333 return ERROR_OK;
1334 }
1335
1336 COMMAND_HANDLER(handle_target_init_command)
1337 {
1338 int retval;
1339
1340 if (CMD_ARGC != 0)
1341 return ERROR_COMMAND_SYNTAX_ERROR;
1342
1343 static bool target_initialized;
1344 if (target_initialized) {
1345 LOG_INFO("'target init' has already been called");
1346 return ERROR_OK;
1347 }
1348 target_initialized = true;
1349
1350 retval = command_run_line(CMD_CTX, "init_targets");
1351 if (ERROR_OK != retval)
1352 return retval;
1353
1354 retval = command_run_line(CMD_CTX, "init_target_events");
1355 if (ERROR_OK != retval)
1356 return retval;
1357
1358 retval = command_run_line(CMD_CTX, "init_board");
1359 if (ERROR_OK != retval)
1360 return retval;
1361
1362 LOG_DEBUG("Initializing targets...");
1363 return target_init(CMD_CTX);
1364 }
1365
1366 int target_register_event_callback(int (*callback)(struct target *target,
1367 enum target_event event, void *priv), void *priv)
1368 {
1369 struct target_event_callback **callbacks_p = &target_event_callbacks;
1370
1371 if (callback == NULL)
1372 return ERROR_COMMAND_SYNTAX_ERROR;
1373
1374 if (*callbacks_p) {
1375 while ((*callbacks_p)->next)
1376 callbacks_p = &((*callbacks_p)->next);
1377 callbacks_p = &((*callbacks_p)->next);
1378 }
1379
1380 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1381 (*callbacks_p)->callback = callback;
1382 (*callbacks_p)->priv = priv;
1383 (*callbacks_p)->next = NULL;
1384
1385 return ERROR_OK;
1386 }
1387
1388 int target_register_reset_callback(int (*callback)(struct target *target,
1389 enum target_reset_mode reset_mode, void *priv), void *priv)
1390 {
1391 struct target_reset_callback *entry;
1392
1393 if (callback == NULL)
1394 return ERROR_COMMAND_SYNTAX_ERROR;
1395
1396 entry = malloc(sizeof(struct target_reset_callback));
1397 if (entry == NULL) {
1398 LOG_ERROR("error allocating buffer for reset callback entry");
1399 return ERROR_COMMAND_SYNTAX_ERROR;
1400 }
1401
1402 entry->callback = callback;
1403 entry->priv = priv;
1404 list_add(&entry->list, &target_reset_callback_list);
1405
1406
1407 return ERROR_OK;
1408 }
1409
1410 int target_register_trace_callback(int (*callback)(struct target *target,
1411 size_t len, uint8_t *data, void *priv), void *priv)
1412 {
1413 struct target_trace_callback *entry;
1414
1415 if (callback == NULL)
1416 return ERROR_COMMAND_SYNTAX_ERROR;
1417
1418 entry = malloc(sizeof(struct target_trace_callback));
1419 if (entry == NULL) {
1420 LOG_ERROR("error allocating buffer for trace callback entry");
1421 return ERROR_COMMAND_SYNTAX_ERROR;
1422 }
1423
1424 entry->callback = callback;
1425 entry->priv = priv;
1426 list_add(&entry->list, &target_trace_callback_list);
1427
1428
1429 return ERROR_OK;
1430 }
1431
1432 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
1433 {
1434 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1435
1436 if (callback == NULL)
1437 return ERROR_COMMAND_SYNTAX_ERROR;
1438
1439 if (*callbacks_p) {
1440 while ((*callbacks_p)->next)
1441 callbacks_p = &((*callbacks_p)->next);
1442 callbacks_p = &((*callbacks_p)->next);
1443 }
1444
1445 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1446 (*callbacks_p)->callback = callback;
1447 (*callbacks_p)->periodic = periodic;
1448 (*callbacks_p)->time_ms = time_ms;
1449 (*callbacks_p)->removed = false;
1450
1451 gettimeofday(&(*callbacks_p)->when, NULL);
1452 timeval_add_time(&(*callbacks_p)->when, 0, time_ms * 1000);
1453
1454 (*callbacks_p)->priv = priv;
1455 (*callbacks_p)->next = NULL;
1456
1457 return ERROR_OK;
1458 }
1459
1460 int target_unregister_event_callback(int (*callback)(struct target *target,
1461 enum target_event event, void *priv), void *priv)
1462 {
1463 struct target_event_callback **p = &target_event_callbacks;
1464 struct target_event_callback *c = target_event_callbacks;
1465
1466 if (callback == NULL)
1467 return ERROR_COMMAND_SYNTAX_ERROR;
1468
1469 while (c) {
1470 struct target_event_callback *next = c->next;
1471 if ((c->callback == callback) && (c->priv == priv)) {
1472 *p = next;
1473 free(c);
1474 return ERROR_OK;
1475 } else
1476 p = &(c->next);
1477 c = next;
1478 }
1479
1480 return ERROR_OK;
1481 }
1482
1483 int target_unregister_reset_callback(int (*callback)(struct target *target,
1484 enum target_reset_mode reset_mode, void *priv), void *priv)
1485 {
1486 struct target_reset_callback *entry;
1487
1488 if (callback == NULL)
1489 return ERROR_COMMAND_SYNTAX_ERROR;
1490
1491 list_for_each_entry(entry, &target_reset_callback_list, list) {
1492 if (entry->callback == callback && entry->priv == priv) {
1493 list_del(&entry->list);
1494 free(entry);
1495 break;
1496 }
1497 }
1498
1499 return ERROR_OK;
1500 }
1501
1502 int target_unregister_trace_callback(int (*callback)(struct target *target,
1503 size_t len, uint8_t *data, void *priv), void *priv)
1504 {
1505 struct target_trace_callback *entry;
1506
1507 if (callback == NULL)
1508 return ERROR_COMMAND_SYNTAX_ERROR;
1509
1510 list_for_each_entry(entry, &target_trace_callback_list, list) {
1511 if (entry->callback == callback && entry->priv == priv) {
1512 list_del(&entry->list);
1513 free(entry);
1514 break;
1515 }
1516 }
1517
1518 return ERROR_OK;
1519 }
1520
1521 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1522 {
1523 if (callback == NULL)
1524 return ERROR_COMMAND_SYNTAX_ERROR;
1525
1526 for (struct target_timer_callback *c = target_timer_callbacks;
1527 c; c = c->next) {
1528 if ((c->callback == callback) && (c->priv == priv)) {
1529 c->removed = true;
1530 return ERROR_OK;
1531 }
1532 }
1533
1534 return ERROR_FAIL;
1535 }
1536
1537 int target_call_event_callbacks(struct target *target, enum target_event event)
1538 {
1539 struct target_event_callback *callback = target_event_callbacks;
1540 struct target_event_callback *next_callback;
1541
1542 if (event == TARGET_EVENT_HALTED) {
1543 /* execute early halted first */
1544 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1545 }
1546
1547 LOG_DEBUG("target event %i (%s)", event,
1548 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1549
1550 target_handle_event(target, event);
1551
1552 while (callback) {
1553 next_callback = callback->next;
1554 callback->callback(target, event, callback->priv);
1555 callback = next_callback;
1556 }
1557
1558 return ERROR_OK;
1559 }
1560
1561 int target_call_reset_callbacks(struct target *target, enum target_reset_mode reset_mode)
1562 {
1563 struct target_reset_callback *callback;
1564
1565 LOG_DEBUG("target reset %i (%s)", reset_mode,
1566 Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode)->name);
1567
1568 list_for_each_entry(callback, &target_reset_callback_list, list)
1569 callback->callback(target, reset_mode, callback->priv);
1570
1571 return ERROR_OK;
1572 }
1573
1574 int target_call_trace_callbacks(struct target *target, size_t len, uint8_t *data)
1575 {
1576 struct target_trace_callback *callback;
1577
1578 list_for_each_entry(callback, &target_trace_callback_list, list)
1579 callback->callback(target, len, data, callback->priv);
1580
1581 return ERROR_OK;
1582 }
1583
1584 static int target_timer_callback_periodic_restart(
1585 struct target_timer_callback *cb, struct timeval *now)
1586 {
1587 cb->when = *now;
1588 timeval_add_time(&cb->when, 0, cb->time_ms * 1000L);
1589 return ERROR_OK;
1590 }
1591
1592 static int target_call_timer_callback(struct target_timer_callback *cb,
1593 struct timeval *now)
1594 {
1595 cb->callback(cb->priv);
1596
1597 if (cb->periodic)
1598 return target_timer_callback_periodic_restart(cb, now);
1599
1600 return target_unregister_timer_callback(cb->callback, cb->priv);
1601 }
1602
1603 static int target_call_timer_callbacks_check_time(int checktime)
1604 {
1605 static bool callback_processing;
1606
1607 /* Do not allow nesting */
1608 if (callback_processing)
1609 return ERROR_OK;
1610
1611 callback_processing = true;
1612
1613 keep_alive();
1614
1615 struct timeval now;
1616 gettimeofday(&now, NULL);
1617
1618 /* Store an address of the place containing a pointer to the
1619 * next item; initially, that's a standalone "root of the
1620 * list" variable. */
1621 struct target_timer_callback **callback = &target_timer_callbacks;
1622 while (*callback) {
1623 if ((*callback)->removed) {
1624 struct target_timer_callback *p = *callback;
1625 *callback = (*callback)->next;
1626 free(p);
1627 continue;
1628 }
1629
1630 bool call_it = (*callback)->callback &&
1631 ((!checktime && (*callback)->periodic) ||
1632 timeval_compare(&now, &(*callback)->when) >= 0);
1633
1634 if (call_it)
1635 target_call_timer_callback(*callback, &now);
1636
1637 callback = &(*callback)->next;
1638 }
1639
1640 callback_processing = false;
1641 return ERROR_OK;
1642 }
1643
1644 int target_call_timer_callbacks(void)
1645 {
1646 return target_call_timer_callbacks_check_time(1);
1647 }
1648
1649 /* invoke periodic callbacks immediately */
1650 int target_call_timer_callbacks_now(void)
1651 {
1652 return target_call_timer_callbacks_check_time(0);
1653 }
1654
1655 /* Prints the working area layout for debug purposes */
1656 static void print_wa_layout(struct target *target)
1657 {
1658 struct working_area *c = target->working_areas;
1659
1660 while (c) {
1661 LOG_DEBUG("%c%c " TARGET_ADDR_FMT "-" TARGET_ADDR_FMT " (%" PRIu32 " bytes)",
1662 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1663 c->address, c->address + c->size - 1, c->size);
1664 c = c->next;
1665 }
1666 }
1667
1668 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1669 static void target_split_working_area(struct working_area *area, uint32_t size)
1670 {
1671 assert(area->free); /* Shouldn't split an allocated area */
1672 assert(size <= area->size); /* Caller should guarantee this */
1673
1674 /* Split only if not already the right size */
1675 if (size < area->size) {
1676 struct working_area *new_wa = malloc(sizeof(*new_wa));
1677
1678 if (new_wa == NULL)
1679 return;
1680
1681 new_wa->next = area->next;
1682 new_wa->size = area->size - size;
1683 new_wa->address = area->address + size;
1684 new_wa->backup = NULL;
1685 new_wa->user = NULL;
1686 new_wa->free = true;
1687
1688 area->next = new_wa;
1689 area->size = size;
1690
1691 /* If backup memory was allocated to this area, it has the wrong size
1692 * now so free it and it will be reallocated if/when needed */
1693 if (area->backup) {
1694 free(area->backup);
1695 area->backup = NULL;
1696 }
1697 }
1698 }
1699
1700 /* Merge all adjacent free areas into one */
1701 static void target_merge_working_areas(struct target *target)
1702 {
1703 struct working_area *c = target->working_areas;
1704
1705 while (c && c->next) {
1706 assert(c->next->address == c->address + c->size); /* This is an invariant */
1707
1708 /* Find two adjacent free areas */
1709 if (c->free && c->next->free) {
1710 /* Merge the last into the first */
1711 c->size += c->next->size;
1712
1713 /* Remove the last */
1714 struct working_area *to_be_freed = c->next;
1715 c->next = c->next->next;
1716 if (to_be_freed->backup)
1717 free(to_be_freed->backup);
1718 free(to_be_freed);
1719
1720 /* If backup memory was allocated to the remaining area, it's has
1721 * the wrong size now */
1722 if (c->backup) {
1723 free(c->backup);
1724 c->backup = NULL;
1725 }
1726 } else {
1727 c = c->next;
1728 }
1729 }
1730 }
1731
1732 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1733 {
1734 /* Reevaluate working area address based on MMU state*/
1735 if (target->working_areas == NULL) {
1736 int retval;
1737 int enabled;
1738
1739 retval = target->type->mmu(target, &enabled);
1740 if (retval != ERROR_OK)
1741 return retval;
1742
1743 if (!enabled) {
1744 if (target->working_area_phys_spec) {
1745 LOG_DEBUG("MMU disabled, using physical "
1746 "address for working memory " TARGET_ADDR_FMT,
1747 target->working_area_phys);
1748 target->working_area = target->working_area_phys;
1749 } else {
1750 LOG_ERROR("No working memory available. "
1751 "Specify -work-area-phys to target.");
1752 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1753 }
1754 } else {
1755 if (target->working_area_virt_spec) {
1756 LOG_DEBUG("MMU enabled, using virtual "
1757 "address for working memory " TARGET_ADDR_FMT,
1758 target->working_area_virt);
1759 target->working_area = target->working_area_virt;
1760 } else {
1761 LOG_ERROR("No working memory available. "
1762 "Specify -work-area-virt to target.");
1763 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1764 }
1765 }
1766
1767 /* Set up initial working area on first call */
1768 struct working_area *new_wa = malloc(sizeof(*new_wa));
1769 if (new_wa) {
1770 new_wa->next = NULL;
1771 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
1772 new_wa->address = target->working_area;
1773 new_wa->backup = NULL;
1774 new_wa->user = NULL;
1775 new_wa->free = true;
1776 }
1777
1778 target->working_areas = new_wa;
1779 }
1780
1781 /* only allocate multiples of 4 byte */
1782 if (size % 4)
1783 size = (size + 3) & (~3UL);
1784
1785 struct working_area *c = target->working_areas;
1786
1787 /* Find the first large enough working area */
1788 while (c) {
1789 if (c->free && c->size >= size)
1790 break;
1791 c = c->next;
1792 }
1793
1794 if (c == NULL)
1795 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1796
1797 /* Split the working area into the requested size */
1798 target_split_working_area(c, size);
1799
1800 LOG_DEBUG("allocated new working area of %" PRIu32 " bytes at address " TARGET_ADDR_FMT,
1801 size, c->address);
1802
1803 if (target->backup_working_area) {
1804 if (c->backup == NULL) {
1805 c->backup = malloc(c->size);
1806 if (c->backup == NULL)
1807 return ERROR_FAIL;
1808 }
1809
1810 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
1811 if (retval != ERROR_OK)
1812 return retval;
1813 }
1814
1815 /* mark as used, and return the new (reused) area */
1816 c->free = false;
1817 *area = c;
1818
1819 /* user pointer */
1820 c->user = area;
1821
1822 print_wa_layout(target);
1823
1824 return ERROR_OK;
1825 }
1826
1827 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1828 {
1829 int retval;
1830
1831 retval = target_alloc_working_area_try(target, size, area);
1832 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1833 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
1834 return retval;
1835
1836 }
1837
1838 static int target_restore_working_area(struct target *target, struct working_area *area)
1839 {
1840 int retval = ERROR_OK;
1841
1842 if (target->backup_working_area && area->backup != NULL) {
1843 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
1844 if (retval != ERROR_OK)
1845 LOG_ERROR("failed to restore %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
1846 area->size, area->address);
1847 }
1848
1849 return retval;
1850 }
1851
1852 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
1853 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1854 {
1855 int retval = ERROR_OK;
1856
1857 if (area->free)
1858 return retval;
1859
1860 if (restore) {
1861 retval = target_restore_working_area(target, area);
1862 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
1863 if (retval != ERROR_OK)
1864 return retval;
1865 }
1866
1867 area->free = true;
1868
1869 LOG_DEBUG("freed %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
1870 area->size, area->address);
1871
1872 /* mark user pointer invalid */
1873 /* TODO: Is this really safe? It points to some previous caller's memory.
1874 * How could we know that the area pointer is still in that place and not
1875 * some other vital data? What's the purpose of this, anyway? */
1876 *area->user = NULL;
1877 area->user = NULL;
1878
1879 target_merge_working_areas(target);
1880
1881 print_wa_layout(target);
1882
1883 return retval;
1884 }
1885
1886 int target_free_working_area(struct target *target, struct working_area *area)
1887 {
1888 return target_free_working_area_restore(target, area, 1);
1889 }
1890
1891 static void target_destroy(struct target *target)
1892 {
1893 if (target->type->deinit_target)
1894 target->type->deinit_target(target);
1895
1896 jtag_unregister_event_callback(jtag_enable_callback, target);
1897
1898 struct target_event_action *teap = target->event_action;
1899 while (teap) {
1900 struct target_event_action *next = teap->next;
1901 Jim_DecrRefCount(teap->interp, teap->body);
1902 free(teap);
1903 teap = next;
1904 }
1905
1906 target_free_all_working_areas(target);
1907 /* Now we have none or only one working area marked as free */
1908 if (target->working_areas) {
1909 free(target->working_areas->backup);
1910 free(target->working_areas);
1911 }
1912
1913 free(target->type);
1914 free(target->trace_info);
1915 free(target->fileio_info);
1916 free(target->cmd_name);
1917 free(target);
1918 }
1919
1920 void target_quit(void)
1921 {
1922 struct target_event_callback *pe = target_event_callbacks;
1923 while (pe) {
1924 struct target_event_callback *t = pe->next;
1925 free(pe);
1926 pe = t;
1927 }
1928 target_event_callbacks = NULL;
1929
1930 struct target_timer_callback *pt = target_timer_callbacks;
1931 while (pt) {
1932 struct target_timer_callback *t = pt->next;
1933 free(pt);
1934 pt = t;
1935 }
1936 target_timer_callbacks = NULL;
1937
1938 for (struct target *target = all_targets; target;) {
1939 struct target *tmp;
1940
1941 tmp = target->next;
1942 target_destroy(target);
1943 target = tmp;
1944 }
1945
1946 all_targets = NULL;
1947 }
1948
1949 /* free resources and restore memory, if restoring memory fails,
1950 * free up resources anyway
1951 */
1952 static void target_free_all_working_areas_restore(struct target *target, int restore)
1953 {
1954 struct working_area *c = target->working_areas;
1955
1956 LOG_DEBUG("freeing all working areas");
1957
1958 /* Loop through all areas, restoring the allocated ones and marking them as free */
1959 while (c) {
1960 if (!c->free) {
1961 if (restore)
1962 target_restore_working_area(target, c);
1963 c->free = true;
1964 *c->user = NULL; /* Same as above */
1965 c->user = NULL;
1966 }
1967 c = c->next;
1968 }
1969
1970 /* Run a merge pass to combine all areas into one */
1971 target_merge_working_areas(target);
1972
1973 print_wa_layout(target);
1974 }
1975
1976 void target_free_all_working_areas(struct target *target)
1977 {
1978 target_free_all_working_areas_restore(target, 1);
1979 }
1980
1981 /* Find the largest number of bytes that can be allocated */
1982 uint32_t target_get_working_area_avail(struct target *target)
1983 {
1984 struct working_area *c = target->working_areas;
1985 uint32_t max_size = 0;
1986
1987 if (c == NULL)
1988 return target->working_area_size;
1989
1990 while (c) {
1991 if (c->free && max_size < c->size)
1992 max_size = c->size;
1993
1994 c = c->next;
1995 }
1996
1997 return max_size;
1998 }
1999
2000 int target_arch_state(struct target *target)
2001 {
2002 int retval;
2003 if (target == NULL) {
2004 LOG_WARNING("No target has been configured");
2005 return ERROR_OK;
2006 }
2007
2008 if (target->state != TARGET_HALTED)
2009 return ERROR_OK;
2010
2011 retval = target->type->arch_state(target);
2012 return retval;
2013 }
2014
2015 static int target_get_gdb_fileio_info_default(struct target *target,
2016 struct gdb_fileio_info *fileio_info)
2017 {
2018 /* If target does not support semi-hosting function, target
2019 has no need to provide .get_gdb_fileio_info callback.
2020 It just return ERROR_FAIL and gdb_server will return "Txx"
2021 as target halted every time. */
2022 return ERROR_FAIL;
2023 }
2024
2025 static int target_gdb_fileio_end_default(struct target *target,
2026 int retcode, int fileio_errno, bool ctrl_c)
2027 {
2028 return ERROR_OK;
2029 }
2030
2031 static int target_profiling_default(struct target *target, uint32_t *samples,
2032 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
2033 {
2034 struct timeval timeout, now;
2035
2036 gettimeofday(&timeout, NULL);
2037 timeval_add_time(&timeout, seconds, 0);
2038
2039 LOG_INFO("Starting profiling. Halting and resuming the"
2040 " target as often as we can...");
2041
2042 uint32_t sample_count = 0;
2043 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
2044 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
2045
2046 int retval = ERROR_OK;
2047 for (;;) {
2048 target_poll(target);
2049 if (target->state == TARGET_HALTED) {
2050 uint32_t t = buf_get_u32(reg->value, 0, 32);
2051 samples[sample_count++] = t;
2052 /* current pc, addr = 0, do not handle breakpoints, not debugging */
2053 retval = target_resume(target, 1, 0, 0, 0);
2054 target_poll(target);
2055 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
2056 } else if (target->state == TARGET_RUNNING) {
2057 /* We want to quickly sample the PC. */
2058 retval = target_halt(target);
2059 } else {
2060 LOG_INFO("Target not halted or running");
2061 retval = ERROR_OK;
2062 break;
2063 }
2064
2065 if (retval != ERROR_OK)
2066 break;
2067
2068 gettimeofday(&now, NULL);
2069 if ((sample_count >= max_num_samples) || timeval_compare(&now, &timeout) >= 0) {
2070 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
2071 break;
2072 }
2073 }
2074
2075 *num_samples = sample_count;
2076 return retval;
2077 }
2078
2079 /* Single aligned words are guaranteed to use 16 or 32 bit access
2080 * mode respectively, otherwise data is handled as quickly as
2081 * possible
2082 */
2083 int target_write_buffer(struct target *target, target_addr_t address, uint32_t size, const uint8_t *buffer)
2084 {
2085 LOG_DEBUG("writing buffer of %" PRIi32 " byte at " TARGET_ADDR_FMT,
2086 size, address);
2087
2088 if (!target_was_examined(target)) {
2089 LOG_ERROR("Target not examined yet");
2090 return ERROR_FAIL;
2091 }
2092
2093 if (size == 0)
2094 return ERROR_OK;
2095
2096 if ((address + size - 1) < address) {
2097 /* GDB can request this when e.g. PC is 0xfffffffc */
2098 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2099 address,
2100 size);
2101 return ERROR_FAIL;
2102 }
2103
2104 return target->type->write_buffer(target, address, size, buffer);
2105 }
2106
2107 static int target_write_buffer_default(struct target *target,
2108 target_addr_t address, uint32_t count, const uint8_t *buffer)
2109 {
2110 uint32_t size;
2111
2112 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
2113 * will have something to do with the size we leave to it. */
2114 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
2115 if (address & size) {
2116 int retval = target_write_memory(target, address, size, 1, buffer);
2117 if (retval != ERROR_OK)
2118 return retval;
2119 address += size;
2120 count -= size;
2121 buffer += size;
2122 }
2123 }
2124
2125 /* Write the data with as large access size as possible. */
2126 for (; size > 0; size /= 2) {
2127 uint32_t aligned = count - count % size;
2128 if (aligned > 0) {
2129 int retval = target_write_memory(target, address, size, aligned / size, buffer);
2130 if (retval != ERROR_OK)
2131 return retval;
2132 address += aligned;
2133 count -= aligned;
2134 buffer += aligned;
2135 }
2136 }
2137
2138 return ERROR_OK;
2139 }
2140
2141 /* Single aligned words are guaranteed to use 16 or 32 bit access
2142 * mode respectively, otherwise data is handled as quickly as
2143 * possible
2144 */
2145 int target_read_buffer(struct target *target, target_addr_t address, uint32_t size, uint8_t *buffer)
2146 {
2147 LOG_DEBUG("reading buffer of %" PRIi32 " byte at " TARGET_ADDR_FMT,
2148 size, address);
2149
2150 if (!target_was_examined(target)) {
2151 LOG_ERROR("Target not examined yet");
2152 return ERROR_FAIL;
2153 }
2154
2155 if (size == 0)
2156 return ERROR_OK;
2157
2158 if ((address + size - 1) < address) {
2159 /* GDB can request this when e.g. PC is 0xfffffffc */
2160 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2161 address,
2162 size);
2163 return ERROR_FAIL;
2164 }
2165
2166 return target->type->read_buffer(target, address, size, buffer);
2167 }
2168
2169 static int target_read_buffer_default(struct target *target, target_addr_t address, uint32_t count, uint8_t *buffer)
2170 {
2171 uint32_t size;
2172
2173 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
2174 * will have something to do with the size we leave to it. */
2175 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
2176 if (address & size) {
2177 int retval = target_read_memory(target, address, size, 1, buffer);
2178 if (retval != ERROR_OK)
2179 return retval;
2180 address += size;
2181 count -= size;
2182 buffer += size;
2183 }
2184 }
2185
2186 /* Read the data with as large access size as possible. */
2187 for (; size > 0; size /= 2) {
2188 uint32_t aligned = count - count % size;
2189 if (aligned > 0) {
2190 int retval = target_read_memory(target, address, size, aligned / size, buffer);
2191 if (retval != ERROR_OK)
2192 return retval;
2193 address += aligned;
2194 count -= aligned;
2195 buffer += aligned;
2196 }
2197 }
2198
2199 return ERROR_OK;
2200 }
2201
2202 int target_checksum_memory(struct target *target, target_addr_t address, uint32_t size, uint32_t* crc)
2203 {
2204 uint8_t *buffer;
2205 int retval;
2206 uint32_t i;
2207 uint32_t checksum = 0;
2208 if (!target_was_examined(target)) {
2209 LOG_ERROR("Target not examined yet");
2210 return ERROR_FAIL;
2211 }
2212
2213 retval = target->type->checksum_memory(target, address, size, &checksum);
2214 if (retval != ERROR_OK) {
2215 buffer = malloc(size);
2216 if (buffer == NULL) {
2217 LOG_ERROR("error allocating buffer for section (%" PRId32 " bytes)", size);
2218 return ERROR_COMMAND_SYNTAX_ERROR;
2219 }
2220 retval = target_read_buffer(target, address, size, buffer);
2221 if (retval != ERROR_OK) {
2222 free(buffer);
2223 return retval;
2224 }
2225
2226 /* convert to target endianness */
2227 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2228 uint32_t target_data;
2229 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2230 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2231 }
2232
2233 retval = image_calculate_checksum(buffer, size, &checksum);
2234 free(buffer);
2235 }
2236
2237 *crc = checksum;
2238
2239 return retval;
2240 }
2241
2242 int target_blank_check_memory(struct target *target, target_addr_t address, uint32_t size, uint32_t* blank,
2243 uint8_t erased_value)
2244 {
2245 int retval;
2246 if (!target_was_examined(target)) {
2247 LOG_ERROR("Target not examined yet");
2248 return ERROR_FAIL;
2249 }
2250
2251 if (target->type->blank_check_memory == 0)
2252 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2253
2254 retval = target->type->blank_check_memory(target, address, size, blank, erased_value);
2255
2256 return retval;
2257 }
2258
2259 int target_read_u64(struct target *target, target_addr_t address, uint64_t *value)
2260 {
2261 uint8_t value_buf[8];
2262 if (!target_was_examined(target)) {
2263 LOG_ERROR("Target not examined yet");
2264 return ERROR_FAIL;
2265 }
2266
2267 int retval = target_read_memory(target, address, 8, 1, value_buf);
2268
2269 if (retval == ERROR_OK) {
2270 *value = target_buffer_get_u64(target, value_buf);
2271 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2272 address,
2273 *value);
2274 } else {
2275 *value = 0x0;
2276 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2277 address);
2278 }
2279
2280 return retval;
2281 }
2282
2283 int target_read_u32(struct target *target, target_addr_t address, uint32_t *value)
2284 {
2285 uint8_t value_buf[4];
2286 if (!target_was_examined(target)) {
2287 LOG_ERROR("Target not examined yet");
2288 return ERROR_FAIL;
2289 }
2290
2291 int retval = target_read_memory(target, address, 4, 1, value_buf);
2292
2293 if (retval == ERROR_OK) {
2294 *value = target_buffer_get_u32(target, value_buf);
2295 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2296 address,
2297 *value);
2298 } else {
2299 *value = 0x0;
2300 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2301 address);
2302 }
2303
2304 return retval;
2305 }
2306
2307 int target_read_u16(struct target *target, target_addr_t address, uint16_t *value)
2308 {
2309 uint8_t value_buf[2];
2310 if (!target_was_examined(target)) {
2311 LOG_ERROR("Target not examined yet");
2312 return ERROR_FAIL;
2313 }
2314
2315 int retval = target_read_memory(target, address, 2, 1, value_buf);
2316
2317 if (retval == ERROR_OK) {
2318 *value = target_buffer_get_u16(target, value_buf);
2319 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%4.4" PRIx16,
2320 address,
2321 *value);
2322 } else {
2323 *value = 0x0;
2324 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2325 address);
2326 }
2327
2328 return retval;
2329 }
2330
2331 int target_read_u8(struct target *target, target_addr_t address, uint8_t *value)
2332 {
2333 if (!target_was_examined(target)) {
2334 LOG_ERROR("Target not examined yet");
2335 return ERROR_FAIL;
2336 }
2337
2338 int retval = target_read_memory(target, address, 1, 1, value);
2339
2340 if (retval == ERROR_OK) {
2341 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2342 address,
2343 *value);
2344 } else {
2345 *value = 0x0;
2346 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2347 address);
2348 }
2349
2350 return retval;
2351 }
2352
2353 int target_write_u64(struct target *target, target_addr_t address, uint64_t value)
2354 {
2355 int retval;
2356 uint8_t value_buf[8];
2357 if (!target_was_examined(target)) {
2358 LOG_ERROR("Target not examined yet");
2359 return ERROR_FAIL;
2360 }
2361
2362 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2363 address,
2364 value);
2365
2366 target_buffer_set_u64(target, value_buf, value);
2367 retval = target_write_memory(target, address, 8, 1, value_buf);
2368 if (retval != ERROR_OK)
2369 LOG_DEBUG("failed: %i", retval);
2370
2371 return retval;
2372 }
2373
2374 int target_write_u32(struct target *target, target_addr_t address, uint32_t value)
2375 {
2376 int retval;
2377 uint8_t value_buf[4];
2378 if (!target_was_examined(target)) {
2379 LOG_ERROR("Target not examined yet");
2380 return ERROR_FAIL;
2381 }
2382
2383 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2384 address,
2385 value);
2386
2387 target_buffer_set_u32(target, value_buf, value);
2388 retval = target_write_memory(target, address, 4, 1, value_buf);
2389 if (retval != ERROR_OK)
2390 LOG_DEBUG("failed: %i", retval);
2391
2392 return retval;
2393 }
2394
2395 int target_write_u16(struct target *target, target_addr_t address, uint16_t value)
2396 {
2397 int retval;
2398 uint8_t value_buf[2];
2399 if (!target_was_examined(target)) {
2400 LOG_ERROR("Target not examined yet");
2401 return ERROR_FAIL;
2402 }
2403
2404 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2405 address,
2406 value);
2407
2408 target_buffer_set_u16(target, value_buf, value);
2409 retval = target_write_memory(target, address, 2, 1, value_buf);
2410 if (retval != ERROR_OK)
2411 LOG_DEBUG("failed: %i", retval);
2412
2413 return retval;
2414 }
2415
2416 int target_write_u8(struct target *target, target_addr_t address, uint8_t value)
2417 {
2418 int retval;
2419 if (!target_was_examined(target)) {
2420 LOG_ERROR("Target not examined yet");
2421 return ERROR_FAIL;
2422 }
2423
2424 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2425 address, value);
2426
2427 retval = target_write_memory(target, address, 1, 1, &value);
2428 if (retval != ERROR_OK)
2429 LOG_DEBUG("failed: %i", retval);
2430
2431 return retval;
2432 }
2433
2434 int target_write_phys_u64(struct target *target, target_addr_t address, uint64_t value)
2435 {
2436 int retval;
2437 uint8_t value_buf[8];
2438 if (!target_was_examined(target)) {
2439 LOG_ERROR("Target not examined yet");
2440 return ERROR_FAIL;
2441 }
2442
2443 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2444 address,
2445 value);
2446
2447 target_buffer_set_u64(target, value_buf, value);
2448 retval = target_write_phys_memory(target, address, 8, 1, value_buf);
2449 if (retval != ERROR_OK)
2450 LOG_DEBUG("failed: %i", retval);
2451
2452 return retval;
2453 }
2454
2455 int target_write_phys_u32(struct target *target, target_addr_t address, uint32_t value)
2456 {
2457 int retval;
2458 uint8_t value_buf[4];
2459 if (!target_was_examined(target)) {
2460 LOG_ERROR("Target not examined yet");
2461 return ERROR_FAIL;
2462 }
2463
2464 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2465 address,
2466 value);
2467
2468 target_buffer_set_u32(target, value_buf, value);
2469 retval = target_write_phys_memory(target, address, 4, 1, value_buf);
2470 if (retval != ERROR_OK)
2471 LOG_DEBUG("failed: %i", retval);
2472
2473 return retval;
2474 }
2475
2476 int target_write_phys_u16(struct target *target, target_addr_t address, uint16_t value)
2477 {
2478 int retval;
2479 uint8_t value_buf[2];
2480 if (!target_was_examined(target)) {
2481 LOG_ERROR("Target not examined yet");
2482 return ERROR_FAIL;
2483 }
2484
2485 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2486 address,
2487 value);
2488
2489 target_buffer_set_u16(target, value_buf, value);
2490 retval = target_write_phys_memory(target, address, 2, 1, value_buf);
2491 if (retval != ERROR_OK)
2492 LOG_DEBUG("failed: %i", retval);
2493
2494 return retval;
2495 }
2496
2497 int target_write_phys_u8(struct target *target, target_addr_t address, uint8_t value)
2498 {
2499 int retval;
2500 if (!target_was_examined(target)) {
2501 LOG_ERROR("Target not examined yet");
2502 return ERROR_FAIL;
2503 }
2504
2505 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2506 address, value);
2507
2508 retval = target_write_phys_memory(target, address, 1, 1, &value);
2509 if (retval != ERROR_OK)
2510 LOG_DEBUG("failed: %i", retval);
2511
2512 return retval;
2513 }
2514
2515 static int find_target(struct command_context *cmd_ctx, const char *name)
2516 {
2517 struct target *target = get_target(name);
2518 if (target == NULL) {
2519 LOG_ERROR("Target: %s is unknown, try one of:\n", name);
2520 return ERROR_FAIL;
2521 }
2522 if (!target->tap->enabled) {
2523 LOG_USER("Target: TAP %s is disabled, "
2524 "can't be the current target\n",
2525 target->tap->dotted_name);
2526 return ERROR_FAIL;
2527 }
2528
2529 cmd_ctx->current_target = target;
2530 if (cmd_ctx->current_target_override)
2531 cmd_ctx->current_target_override = target;
2532
2533 return ERROR_OK;
2534 }
2535
2536
2537 COMMAND_HANDLER(handle_targets_command)
2538 {
2539 int retval = ERROR_OK;
2540 if (CMD_ARGC == 1) {
2541 retval = find_target(CMD_CTX, CMD_ARGV[0]);
2542 if (retval == ERROR_OK) {
2543 /* we're done! */
2544 return retval;
2545 }
2546 }
2547
2548 struct target *target = all_targets;
2549 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
2550 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
2551 while (target) {
2552 const char *state;
2553 char marker = ' ';
2554
2555 if (target->tap->enabled)
2556 state = target_state_name(target);
2557 else
2558 state = "tap-disabled";
2559
2560 if (CMD_CTX->current_target == target)
2561 marker = '*';
2562
2563 /* keep columns lined up to match the headers above */
2564 command_print(CMD_CTX,
2565 "%2d%c %-18s %-10s %-6s %-18s %s",
2566 target->target_number,
2567 marker,
2568 target_name(target),
2569 target_type_name(target),
2570 Jim_Nvp_value2name_simple(nvp_target_endian,
2571 target->endianness)->name,
2572 target->tap->dotted_name,
2573 state);
2574 target = target->next;
2575 }
2576
2577 return retval;
2578 }
2579
2580 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2581
2582 static int powerDropout;
2583 static int srstAsserted;
2584
2585 static int runPowerRestore;
2586 static int runPowerDropout;
2587 static int runSrstAsserted;
2588 static int runSrstDeasserted;
2589
2590 static int sense_handler(void)
2591 {
2592 static int prevSrstAsserted;
2593 static int prevPowerdropout;
2594
2595 int retval = jtag_power_dropout(&powerDropout);
2596 if (retval != ERROR_OK)
2597 return retval;
2598
2599 int powerRestored;
2600 powerRestored = prevPowerdropout && !powerDropout;
2601 if (powerRestored)
2602 runPowerRestore = 1;
2603
2604 int64_t current = timeval_ms();
2605 static int64_t lastPower;
2606 bool waitMore = lastPower + 2000 > current;
2607 if (powerDropout && !waitMore) {
2608 runPowerDropout = 1;
2609 lastPower = current;
2610 }
2611
2612 retval = jtag_srst_asserted(&srstAsserted);
2613 if (retval != ERROR_OK)
2614 return retval;
2615
2616 int srstDeasserted;
2617 srstDeasserted = prevSrstAsserted && !srstAsserted;
2618
2619 static int64_t lastSrst;
2620 waitMore = lastSrst + 2000 > current;
2621 if (srstDeasserted && !waitMore) {
2622 runSrstDeasserted = 1;
2623 lastSrst = current;
2624 }
2625
2626 if (!prevSrstAsserted && srstAsserted)
2627 runSrstAsserted = 1;
2628
2629 prevSrstAsserted = srstAsserted;
2630 prevPowerdropout = powerDropout;
2631
2632 if (srstDeasserted || powerRestored) {
2633 /* Other than logging the event we can't do anything here.
2634 * Issuing a reset is a particularly bad idea as we might
2635 * be inside a reset already.
2636 */
2637 }
2638
2639 return ERROR_OK;
2640 }
2641
2642 /* process target state changes */
2643 static int handle_target(void *priv)
2644 {
2645 Jim_Interp *interp = (Jim_Interp *)priv;
2646 int retval = ERROR_OK;
2647
2648 if (!is_jtag_poll_safe()) {
2649 /* polling is disabled currently */
2650 return ERROR_OK;
2651 }
2652
2653 /* we do not want to recurse here... */
2654 static int recursive;
2655 if (!recursive) {
2656 recursive = 1;
2657 sense_handler();
2658 /* danger! running these procedures can trigger srst assertions and power dropouts.
2659 * We need to avoid an infinite loop/recursion here and we do that by
2660 * clearing the flags after running these events.
2661 */
2662 int did_something = 0;
2663 if (runSrstAsserted) {
2664 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2665 Jim_Eval(interp, "srst_asserted");
2666 did_something = 1;
2667 }
2668 if (runSrstDeasserted) {
2669 Jim_Eval(interp, "srst_deasserted");
2670 did_something = 1;
2671 }
2672 if (runPowerDropout) {
2673 LOG_INFO("Power dropout detected, running power_dropout proc.");
2674 Jim_Eval(interp, "power_dropout");
2675 did_something = 1;
2676 }
2677 if (runPowerRestore) {
2678 Jim_Eval(interp, "power_restore");
2679 did_something = 1;
2680 }
2681
2682 if (did_something) {
2683 /* clear detect flags */
2684 sense_handler();
2685 }
2686
2687 /* clear action flags */
2688
2689 runSrstAsserted = 0;
2690 runSrstDeasserted = 0;
2691 runPowerRestore = 0;
2692 runPowerDropout = 0;
2693
2694 recursive = 0;
2695 }
2696
2697 /* Poll targets for state changes unless that's globally disabled.
2698 * Skip targets that are currently disabled.
2699 */
2700 for (struct target *target = all_targets;
2701 is_jtag_poll_safe() && target;
2702 target = target->next) {
2703
2704 if (!target_was_examined(target))
2705 continue;
2706
2707 if (!target->tap->enabled)
2708 continue;
2709
2710 if (target->backoff.times > target->backoff.count) {
2711 /* do not poll this time as we failed previously */
2712 target->backoff.count++;
2713 continue;
2714 }
2715 target->backoff.count = 0;
2716
2717 /* only poll target if we've got power and srst isn't asserted */
2718 if (!powerDropout && !srstAsserted) {
2719 /* polling may fail silently until the target has been examined */
2720 retval = target_poll(target);
2721 if (retval != ERROR_OK) {
2722 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2723 if (target->backoff.times * polling_interval < 5000) {
2724 target->backoff.times *= 2;
2725 target->backoff.times++;
2726 }
2727
2728 /* Tell GDB to halt the debugger. This allows the user to
2729 * run monitor commands to handle the situation.
2730 */
2731 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2732 }
2733 if (target->backoff.times > 0) {
2734 LOG_USER("Polling target %s failed, trying to reexamine", target_name(target));
2735 target_reset_examined(target);
2736 retval = target_examine_one(target);
2737 /* Target examination could have failed due to unstable connection,
2738 * but we set the examined flag anyway to repoll it later */
2739 if (retval != ERROR_OK) {
2740 target->examined = true;
2741 LOG_USER("Examination failed, GDB will be halted. Polling again in %dms",
2742 target->backoff.times * polling_interval);
2743 return retval;
2744 }
2745 }
2746
2747 /* Since we succeeded, we reset backoff count */
2748 target->backoff.times = 0;
2749 }
2750 }
2751
2752 return retval;
2753 }
2754
2755 COMMAND_HANDLER(handle_reg_command)
2756 {
2757 struct target *target;
2758 struct reg *reg = NULL;
2759 unsigned count = 0;
2760 char *value;
2761
2762 LOG_DEBUG("-");
2763
2764 target = get_current_target(CMD_CTX);
2765
2766 /* list all available registers for the current target */
2767 if (CMD_ARGC == 0) {
2768 struct reg_cache *cache = target->reg_cache;
2769
2770 count = 0;
2771 while (cache) {
2772 unsigned i;
2773
2774 command_print(CMD_CTX, "===== %s", cache->name);
2775
2776 for (i = 0, reg = cache->reg_list;
2777 i < cache->num_regs;
2778 i++, reg++, count++) {
2779 /* only print cached values if they are valid */
2780 if (reg->valid) {
2781 value = buf_to_str(reg->value,
2782 reg->size, 16);
2783 command_print(CMD_CTX,
2784 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2785 count, reg->name,
2786 reg->size, value,
2787 reg->dirty
2788 ? " (dirty)"
2789 : "");
2790 free(value);
2791 } else {
2792 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2793 count, reg->name,
2794 reg->size) ;
2795 }
2796 }
2797 cache = cache->next;
2798 }
2799
2800 return ERROR_OK;
2801 }
2802
2803 /* access a single register by its ordinal number */
2804 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
2805 unsigned num;
2806 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2807
2808 struct reg_cache *cache = target->reg_cache;
2809 count = 0;
2810 while (cache) {
2811 unsigned i;
2812 for (i = 0; i < cache->num_regs; i++) {
2813 if (count++ == num) {
2814 reg = &cache->reg_list[i];
2815 break;
2816 }
2817 }
2818 if (reg)
2819 break;
2820 cache = cache->next;
2821 }
2822
2823 if (!reg) {
2824 command_print(CMD_CTX, "%i is out of bounds, the current target "
2825 "has only %i registers (0 - %i)", num, count, count - 1);
2826 return ERROR_OK;
2827 }
2828 } else {
2829 /* access a single register by its name */
2830 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2831
2832 if (!reg) {
2833 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2834 return ERROR_OK;
2835 }
2836 }
2837
2838 assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
2839
2840 /* display a register */
2841 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
2842 && (CMD_ARGV[1][0] <= '9')))) {
2843 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2844 reg->valid = 0;
2845
2846 if (reg->valid == 0)
2847 reg->type->get(reg);
2848 value = buf_to_str(reg->value, reg->size, 16);
2849 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2850 free(value);
2851 return ERROR_OK;
2852 }
2853
2854 /* set register value */
2855 if (CMD_ARGC == 2) {
2856 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2857 if (buf == NULL)
2858 return ERROR_FAIL;
2859 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2860
2861 reg->type->set(reg, buf);
2862
2863 value = buf_to_str(reg->value, reg->size, 16);
2864 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2865 free(value);
2866
2867 free(buf);
2868
2869 return ERROR_OK;
2870 }
2871
2872 return ERROR_COMMAND_SYNTAX_ERROR;
2873 }
2874
2875 COMMAND_HANDLER(handle_poll_command)
2876 {
2877 int retval = ERROR_OK;
2878 struct target *target = get_current_target(CMD_CTX);
2879
2880 if (CMD_ARGC == 0) {
2881 command_print(CMD_CTX, "background polling: %s",
2882 jtag_poll_get_enabled() ? "on" : "off");
2883 command_print(CMD_CTX, "TAP: %s (%s)",
2884 target->tap->dotted_name,
2885 target->tap->enabled ? "enabled" : "disabled");
2886 if (!target->tap->enabled)
2887 return ERROR_OK;
2888 retval = target_poll(target);
2889 if (retval != ERROR_OK)
2890 return retval;
2891 retval = target_arch_state(target);
2892 if (retval != ERROR_OK)
2893 return retval;
2894 } else if (CMD_ARGC == 1) {
2895 bool enable;
2896 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2897 jtag_poll_set_enabled(enable);
2898 } else
2899 return ERROR_COMMAND_SYNTAX_ERROR;
2900
2901 return retval;
2902 }
2903
2904 COMMAND_HANDLER(handle_wait_halt_command)
2905 {
2906 if (CMD_ARGC > 1)
2907 return ERROR_COMMAND_SYNTAX_ERROR;
2908
2909 unsigned ms = DEFAULT_HALT_TIMEOUT;
2910 if (1 == CMD_ARGC) {
2911 int retval = parse_uint(CMD_ARGV[0], &ms);
2912 if (ERROR_OK != retval)
2913 return ERROR_COMMAND_SYNTAX_ERROR;
2914 }
2915
2916 struct target *target = get_current_target(CMD_CTX);
2917 return target_wait_state(target, TARGET_HALTED, ms);
2918 }
2919
2920 /* wait for target state to change. The trick here is to have a low
2921 * latency for short waits and not to suck up all the CPU time
2922 * on longer waits.
2923 *
2924 * After 500ms, keep_alive() is invoked
2925 */
2926 int target_wait_state(struct target *target, enum target_state state, int ms)
2927 {
2928 int retval;
2929 int64_t then = 0, cur;
2930 bool once = true;
2931
2932 for (;;) {
2933 retval = target_poll(target);
2934 if (retval != ERROR_OK)
2935 return retval;
2936 if (target->state == state)
2937 break;
2938 cur = timeval_ms();
2939 if (once) {
2940 once = false;
2941 then = timeval_ms();
2942 LOG_DEBUG("waiting for target %s...",
2943 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2944 }
2945
2946 if (cur-then > 500)
2947 keep_alive();
2948
2949 if ((cur-then) > ms) {
2950 LOG_ERROR("timed out while waiting for target %s",
2951 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2952 return ERROR_FAIL;
2953 }
2954 }
2955
2956 return ERROR_OK;
2957 }
2958
2959 COMMAND_HANDLER(handle_halt_command)
2960 {
2961 LOG_DEBUG("-");
2962
2963 struct target *target = get_current_target(CMD_CTX);
2964
2965 target->verbose_halt_msg = true;
2966
2967 int retval = target_halt(target);
2968 if (ERROR_OK != retval)
2969 return retval;
2970
2971 if (CMD_ARGC == 1) {
2972 unsigned wait_local;
2973 retval = parse_uint(CMD_ARGV[0], &wait_local);
2974 if (ERROR_OK != retval)
2975 return ERROR_COMMAND_SYNTAX_ERROR;
2976 if (!wait_local)
2977 return ERROR_OK;
2978 }
2979
2980 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2981 }
2982
2983 COMMAND_HANDLER(handle_soft_reset_halt_command)
2984 {
2985 struct target *target = get_current_target(CMD_CTX);
2986
2987 LOG_USER("requesting target halt and executing a soft reset");
2988
2989 target_soft_reset_halt(target);
2990
2991 return ERROR_OK;
2992 }
2993
2994 COMMAND_HANDLER(handle_reset_command)
2995 {
2996 if (CMD_ARGC > 1)
2997 return ERROR_COMMAND_SYNTAX_ERROR;
2998
2999 enum target_reset_mode reset_mode = RESET_RUN;
3000 if (CMD_ARGC == 1) {
3001 const Jim_Nvp *n;
3002 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
3003 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
3004 return ERROR_COMMAND_SYNTAX_ERROR;
3005 reset_mode = n->value;
3006 }
3007
3008 /* reset *all* targets */
3009 return target_process_reset(CMD_CTX, reset_mode);
3010 }
3011
3012
3013 COMMAND_HANDLER(handle_resume_command)
3014 {
3015 int current = 1;
3016 if (CMD_ARGC > 1)
3017 return ERROR_COMMAND_SYNTAX_ERROR;
3018
3019 struct target *target = get_current_target(CMD_CTX);
3020
3021 /* with no CMD_ARGV, resume from current pc, addr = 0,
3022 * with one arguments, addr = CMD_ARGV[0],
3023 * handle breakpoints, not debugging */
3024 target_addr_t addr = 0;
3025 if (CMD_ARGC == 1) {
3026 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3027 current = 0;
3028 }
3029
3030 return target_resume(target, current, addr, 1, 0);
3031 }
3032
3033 COMMAND_HANDLER(handle_step_command)
3034 {
3035 if (CMD_ARGC > 1)
3036 return ERROR_COMMAND_SYNTAX_ERROR;
3037
3038 LOG_DEBUG("-");
3039
3040 /* with no CMD_ARGV, step from current pc, addr = 0,
3041 * with one argument addr = CMD_ARGV[0],
3042 * handle breakpoints, debugging */
3043 target_addr_t addr = 0;
3044 int current_pc = 1;
3045 if (CMD_ARGC == 1) {
3046 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3047 current_pc = 0;
3048 }
3049
3050 struct target *target = get_current_target(CMD_CTX);
3051
3052 return target->type->step(target, current_pc, addr, 1);
3053 }
3054
3055 static void handle_md_output(struct command_context *cmd_ctx,
3056 struct target *target, target_addr_t address, unsigned size,
3057 unsigned count, const uint8_t *buffer)
3058 {
3059 const unsigned line_bytecnt = 32;
3060 unsigned line_modulo = line_bytecnt / size;
3061
3062 char output[line_bytecnt * 4 + 1];
3063 unsigned output_len = 0;
3064
3065 const char *value_fmt;
3066 switch (size) {
3067 case 8:
3068 value_fmt = "%16.16"PRIx64" ";
3069 break;
3070 case 4:
3071 value_fmt = "%8.8"PRIx64" ";
3072 break;
3073 case 2:
3074 value_fmt = "%4.4"PRIx64" ";
3075 break;
3076 case 1:
3077 value_fmt = "%2.2"PRIx64" ";
3078 break;
3079 default:
3080 /* "can't happen", caller checked */
3081 LOG_ERROR("invalid memory read size: %u", size);
3082 return;
3083 }
3084
3085 for (unsigned i = 0; i < count; i++) {
3086 if (i % line_modulo == 0) {
3087 output_len += snprintf(output + output_len,
3088 sizeof(output) - output_len,
3089 TARGET_ADDR_FMT ": ",
3090 (address + (i * size)));
3091 }
3092
3093 uint64_t value = 0;
3094 const uint8_t *value_ptr = buffer + i * size;
3095 switch (size) {
3096 case 8:
3097 value = target_buffer_get_u64(target, value_ptr);
3098 break;
3099 case 4:
3100 value = target_buffer_get_u32(target, value_ptr);
3101 break;
3102 case 2:
3103 value = target_buffer_get_u16(target, value_ptr);
3104 break;
3105 case 1:
3106 value = *value_ptr;
3107 }
3108 output_len += snprintf(output + output_len,
3109 sizeof(output) - output_len,
3110 value_fmt, value);
3111
3112 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
3113 command_print(cmd_ctx, "%s", output);
3114 output_len = 0;
3115 }
3116 }
3117 }
3118
3119 COMMAND_HANDLER(handle_md_command)
3120 {
3121 if (CMD_ARGC < 1)
3122 return ERROR_COMMAND_SYNTAX_ERROR;
3123
3124 unsigned size = 0;
3125 switch (CMD_NAME[2]) {
3126 case 'd':
3127 size = 8;
3128 break;
3129 case 'w':
3130 size = 4;
3131 break;
3132 case 'h':
3133 size = 2;
3134 break;
3135 case 'b':
3136 size = 1;
3137 break;
3138 default:
3139 return ERROR_COMMAND_SYNTAX_ERROR;
3140 }
3141
3142 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3143 int (*fn)(struct target *target,
3144 target_addr_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
3145 if (physical) {
3146 CMD_ARGC--;
3147 CMD_ARGV++;
3148 fn = target_read_phys_memory;
3149 } else
3150 fn = target_read_memory;
3151 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
3152 return ERROR_COMMAND_SYNTAX_ERROR;
3153
3154 target_addr_t address;
3155 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3156
3157 unsigned count = 1;
3158 if (CMD_ARGC == 2)
3159 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
3160
3161 uint8_t *buffer = calloc(count, size);
3162 if (buffer == NULL) {
3163 LOG_ERROR("Failed to allocate md read buffer");
3164 return ERROR_FAIL;
3165 }
3166
3167 struct target *target = get_current_target(CMD_CTX);
3168 int retval = fn(target, address, size, count, buffer);
3169 if (ERROR_OK == retval)
3170 handle_md_output(CMD_CTX, target, address, size, count, buffer);
3171
3172 free(buffer);
3173
3174 return retval;
3175 }
3176
3177 typedef int (*target_write_fn)(struct target *target,
3178 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
3179
3180 static int target_fill_mem(struct target *target,
3181 target_addr_t address,
3182 target_write_fn fn,
3183 unsigned data_size,
3184 /* value */
3185 uint64_t b,
3186 /* count */
3187 unsigned c)
3188 {
3189 /* We have to write in reasonably large chunks to be able
3190 * to fill large memory areas with any sane speed */
3191 const unsigned chunk_size = 16384;
3192 uint8_t *target_buf = malloc(chunk_size * data_size);
3193 if (target_buf == NULL) {
3194 LOG_ERROR("Out of memory");
3195