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