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

Linking to existing account procedure

If you already have an account and want to add another login method you MUST first sign in with your existing account and then change URL to read https://review.openocd.org/login/?link to get to this page again but this time it'll work for linking. Thank you.

SSH host keys fingerprints

1024 SHA256:YKx8b7u5ZWdcbp7/4AeXNaqElP49m6QrwfXaqQGJAOk gerrit-code-review@openocd.zylin.com (DSA)
384 SHA256:jHIbSQa4REvwCFG4cq5LBlBLxmxSqelQPem/EXIrxjk gerrit-code-review@openocd.org (ECDSA)
521 SHA256:UAOPYkU9Fjtcao0Ul/Rrlnj/OsQvt+pgdYSZ4jOYdgs gerrit-code-review@openocd.org (ECDSA)
256 SHA256:A13M5QlnozFOvTllybRZH6vm7iSt0XLxbA48yfc2yfY gerrit-code-review@openocd.org (ECDSA)
256 SHA256:spYMBqEYoAOtK7yZBrcwE8ZpYt6b68Cfh9yEVetvbXg gerrit-code-review@openocd.org (ED25519)
+--[ED25519 256]--+
|=..              |
|+o..   .         |
|*.o   . .        |
|+B . . .         |
|Bo. = o S        |
|Oo.+ + =         |
|oB=.* = . o      |
| =+=.+   + E     |
|. .=o   . o      |
+----[SHA256]-----+
2048 SHA256:0Onrb7/PHjpo6iVZ7xQX2riKN83FJ3KGU0TvI0TaFG4 gerrit-code-review@openocd.zylin.com (RSA)