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

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)