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

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)