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