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

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)