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

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)