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