29a011cea13756efd635fe822c1a298c41a6a45e
[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 size, uint8_t *buffer);
64 static int target_write_buffer_default(struct target *target, uint32_t address,
65 uint32_t size, 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
76 /* targets */
77 extern struct target_type arm7tdmi_target;
78 extern struct target_type arm720t_target;
79 extern struct target_type arm9tdmi_target;
80 extern struct target_type arm920t_target;
81 extern struct target_type arm966e_target;
82 extern struct target_type arm946e_target;
83 extern struct target_type arm926ejs_target;
84 extern struct target_type fa526_target;
85 extern struct target_type feroceon_target;
86 extern struct target_type dragonite_target;
87 extern struct target_type xscale_target;
88 extern struct target_type cortexm3_target;
89 extern struct target_type cortexa8_target;
90 extern struct target_type cortexr4_target;
91 extern struct target_type arm11_target;
92 extern struct target_type mips_m4k_target;
93 extern struct target_type avr_target;
94 extern struct target_type dsp563xx_target;
95 extern struct target_type dsp5680xx_target;
96 extern struct target_type testee_target;
97 extern struct target_type avr32_ap7k_target;
98 extern struct target_type hla_target;
99 extern struct target_type nds32_v2_target;
100 extern struct target_type nds32_v3_target;
101 extern struct target_type nds32_v3m_target;
102
103 static struct target_type *target_types[] = {
104 &arm7tdmi_target,
105 &arm9tdmi_target,
106 &arm920t_target,
107 &arm720t_target,
108 &arm966e_target,
109 &arm946e_target,
110 &arm926ejs_target,
111 &fa526_target,
112 &feroceon_target,
113 &dragonite_target,
114 &xscale_target,
115 &cortexm3_target,
116 &cortexa8_target,
117 &cortexr4_target,
118 &arm11_target,
119 &mips_m4k_target,
120 &avr_target,
121 &dsp563xx_target,
122 &dsp5680xx_target,
123 &testee_target,
124 &avr32_ap7k_target,
125 &hla_target,
126 &nds32_v2_target,
127 &nds32_v3_target,
128 &nds32_v3m_target,
129 NULL,
130 };
131
132 struct target *all_targets;
133 static struct target_event_callback *target_event_callbacks;
134 static struct target_timer_callback *target_timer_callbacks;
135 static const int polling_interval = 100;
136
137 static const Jim_Nvp nvp_assert[] = {
138 { .name = "assert", NVP_ASSERT },
139 { .name = "deassert", NVP_DEASSERT },
140 { .name = "T", NVP_ASSERT },
141 { .name = "F", NVP_DEASSERT },
142 { .name = "t", NVP_ASSERT },
143 { .name = "f", NVP_DEASSERT },
144 { .name = NULL, .value = -1 }
145 };
146
147 static const Jim_Nvp nvp_error_target[] = {
148 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
149 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
150 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
151 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
152 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
153 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
154 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
155 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
156 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
157 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
158 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
159 { .value = -1, .name = NULL }
160 };
161
162 static const char *target_strerror_safe(int err)
163 {
164 const Jim_Nvp *n;
165
166 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
167 if (n->name == NULL)
168 return "unknown";
169 else
170 return n->name;
171 }
172
173 static const Jim_Nvp nvp_target_event[] = {
174
175 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
176 { .value = TARGET_EVENT_HALTED, .name = "halted" },
177 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
178 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
179 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
180
181 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
182 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
183
184 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
185 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
186 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
187 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
188 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
189 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
190 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
191 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
192 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
193 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
194 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
195 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
196
197 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
198 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
199
200 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
201 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
202
203 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
204 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
205
206 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
207 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
208
209 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
210 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
211
212 { .name = NULL, .value = -1 }
213 };
214
215 static const Jim_Nvp nvp_target_state[] = {
216 { .name = "unknown", .value = TARGET_UNKNOWN },
217 { .name = "running", .value = TARGET_RUNNING },
218 { .name = "halted", .value = TARGET_HALTED },
219 { .name = "reset", .value = TARGET_RESET },
220 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
221 { .name = NULL, .value = -1 },
222 };
223
224 static const Jim_Nvp nvp_target_debug_reason[] = {
225 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
226 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
227 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
228 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
229 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
230 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
231 { .name = "program-exit" , .value = DBG_REASON_EXIT },
232 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
233 { .name = NULL, .value = -1 },
234 };
235
236 static const Jim_Nvp nvp_target_endian[] = {
237 { .name = "big", .value = TARGET_BIG_ENDIAN },
238 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
239 { .name = "be", .value = TARGET_BIG_ENDIAN },
240 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
241 { .name = NULL, .value = -1 },
242 };
243
244 static const Jim_Nvp nvp_reset_modes[] = {
245 { .name = "unknown", .value = RESET_UNKNOWN },
246 { .name = "run" , .value = RESET_RUN },
247 { .name = "halt" , .value = RESET_HALT },
248 { .name = "init" , .value = RESET_INIT },
249 { .name = NULL , .value = -1 },
250 };
251
252 const char *debug_reason_name(struct target *t)
253 {
254 const char *cp;
255
256 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
257 t->debug_reason)->name;
258 if (!cp) {
259 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
260 cp = "(*BUG*unknown*BUG*)";
261 }
262 return cp;
263 }
264
265 const char *target_state_name(struct target *t)
266 {
267 const char *cp;
268 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
269 if (!cp) {
270 LOG_ERROR("Invalid target state: %d", (int)(t->state));
271 cp = "(*BUG*unknown*BUG*)";
272 }
273 return cp;
274 }
275
276 /* determine the number of the new target */
277 static int new_target_number(void)
278 {
279 struct target *t;
280 int x;
281
282 /* number is 0 based */
283 x = -1;
284 t = all_targets;
285 while (t) {
286 if (x < t->target_number)
287 x = t->target_number;
288 t = t->next;
289 }
290 return x + 1;
291 }
292
293 /* read a uint32_t from a buffer in target memory endianness */
294 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
295 {
296 if (target->endianness == TARGET_LITTLE_ENDIAN)
297 return le_to_h_u32(buffer);
298 else
299 return be_to_h_u32(buffer);
300 }
301
302 /* read a uint24_t from a buffer in target memory endianness */
303 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
304 {
305 if (target->endianness == TARGET_LITTLE_ENDIAN)
306 return le_to_h_u24(buffer);
307 else
308 return be_to_h_u24(buffer);
309 }
310
311 /* read a uint16_t from a buffer in target memory endianness */
312 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
313 {
314 if (target->endianness == TARGET_LITTLE_ENDIAN)
315 return le_to_h_u16(buffer);
316 else
317 return be_to_h_u16(buffer);
318 }
319
320 /* read a uint8_t from a buffer in target memory endianness */
321 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
322 {
323 return *buffer & 0x0ff;
324 }
325
326 /* write a uint32_t to a buffer in target memory endianness */
327 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
328 {
329 if (target->endianness == TARGET_LITTLE_ENDIAN)
330 h_u32_to_le(buffer, value);
331 else
332 h_u32_to_be(buffer, value);
333 }
334
335 /* write a uint24_t to a buffer in target memory endianness */
336 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
337 {
338 if (target->endianness == TARGET_LITTLE_ENDIAN)
339 h_u24_to_le(buffer, value);
340 else
341 h_u24_to_be(buffer, value);
342 }
343
344 /* write a uint16_t to a buffer in target memory endianness */
345 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
346 {
347 if (target->endianness == TARGET_LITTLE_ENDIAN)
348 h_u16_to_le(buffer, value);
349 else
350 h_u16_to_be(buffer, value);
351 }
352
353 /* write a uint8_t to a buffer in target memory endianness */
354 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
355 {
356 *buffer = value;
357 }
358
359 /* write a uint32_t array to a buffer in target memory endianness */
360 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
361 {
362 uint32_t i;
363 for (i = 0; i < count; i++)
364 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
365 }
366
367 /* write a uint16_t array to a buffer in target memory endianness */
368 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
369 {
370 uint32_t i;
371 for (i = 0; i < count; i++)
372 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
373 }
374
375 /* write a uint32_t array to a buffer in target memory endianness */
376 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, uint32_t *srcbuf)
377 {
378 uint32_t i;
379 for (i = 0; i < count; i++)
380 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
381 }
382
383 /* write a uint16_t array to a buffer in target memory endianness */
384 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, uint16_t *srcbuf)
385 {
386 uint32_t i;
387 for (i = 0; i < count; i++)
388 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
389 }
390
391 /* return a pointer to a configured target; id is name or number */
392 struct target *get_target(const char *id)
393 {
394 struct target *target;
395
396 /* try as tcltarget name */
397 for (target = all_targets; target; target = target->next) {
398 if (target_name(target) == NULL)
399 continue;
400 if (strcmp(id, target_name(target)) == 0)
401 return target;
402 }
403
404 /* It's OK to remove this fallback sometime after August 2010 or so */
405
406 /* no match, try as number */
407 unsigned num;
408 if (parse_uint(id, &num) != ERROR_OK)
409 return NULL;
410
411 for (target = all_targets; target; target = target->next) {
412 if (target->target_number == (int)num) {
413 LOG_WARNING("use '%s' as target identifier, not '%u'",
414 target_name(target), num);
415 return target;
416 }
417 }
418
419 return NULL;
420 }
421
422 /* returns a pointer to the n-th configured target */
423 static struct target *get_target_by_num(int num)
424 {
425 struct target *target = all_targets;
426
427 while (target) {
428 if (target->target_number == num)
429 return target;
430 target = target->next;
431 }
432
433 return NULL;
434 }
435
436 struct target *get_current_target(struct command_context *cmd_ctx)
437 {
438 struct target *target = get_target_by_num(cmd_ctx->current_target);
439
440 if (target == NULL) {
441 LOG_ERROR("BUG: current_target out of bounds");
442 exit(-1);
443 }
444
445 return target;
446 }
447
448 int target_poll(struct target *target)
449 {
450 int retval;
451
452 /* We can't poll until after examine */
453 if (!target_was_examined(target)) {
454 /* Fail silently lest we pollute the log */
455 return ERROR_FAIL;
456 }
457
458 retval = target->type->poll(target);
459 if (retval != ERROR_OK)
460 return retval;
461
462 if (target->halt_issued) {
463 if (target->state == TARGET_HALTED)
464 target->halt_issued = false;
465 else {
466 long long t = timeval_ms() - target->halt_issued_time;
467 if (t > DEFAULT_HALT_TIMEOUT) {
468 target->halt_issued = false;
469 LOG_INFO("Halt timed out, wake up GDB.");
470 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
471 }
472 }
473 }
474
475 return ERROR_OK;
476 }
477
478 int target_halt(struct target *target)
479 {
480 int retval;
481 /* We can't poll until after examine */
482 if (!target_was_examined(target)) {
483 LOG_ERROR("Target not examined yet");
484 return ERROR_FAIL;
485 }
486
487 retval = target->type->halt(target);
488 if (retval != ERROR_OK)
489 return retval;
490
491 target->halt_issued = true;
492 target->halt_issued_time = timeval_ms();
493
494 return ERROR_OK;
495 }
496
497 /**
498 * Make the target (re)start executing using its saved execution
499 * context (possibly with some modifications).
500 *
501 * @param target Which target should start executing.
502 * @param current True to use the target's saved program counter instead
503 * of the address parameter
504 * @param address Optionally used as the program counter.
505 * @param handle_breakpoints True iff breakpoints at the resumption PC
506 * should be skipped. (For example, maybe execution was stopped by
507 * such a breakpoint, in which case it would be counterprodutive to
508 * let it re-trigger.
509 * @param debug_execution False if all working areas allocated by OpenOCD
510 * should be released and/or restored to their original contents.
511 * (This would for example be true to run some downloaded "helper"
512 * algorithm code, which resides in one such working buffer and uses
513 * another for data storage.)
514 *
515 * @todo Resolve the ambiguity about what the "debug_execution" flag
516 * signifies. For example, Target implementations don't agree on how
517 * it relates to invalidation of the register cache, or to whether
518 * breakpoints and watchpoints should be enabled. (It would seem wrong
519 * to enable breakpoints when running downloaded "helper" algorithms
520 * (debug_execution true), since the breakpoints would be set to match
521 * target firmware being debugged, not the helper algorithm.... and
522 * enabling them could cause such helpers to malfunction (for example,
523 * by overwriting data with a breakpoint instruction. On the other
524 * hand the infrastructure for running such helpers might use this
525 * procedure but rely on hardware breakpoint to detect termination.)
526 */
527 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
528 {
529 int retval;
530
531 /* We can't poll until after examine */
532 if (!target_was_examined(target)) {
533 LOG_ERROR("Target not examined yet");
534 return ERROR_FAIL;
535 }
536
537 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
538
539 /* note that resume *must* be asynchronous. The CPU can halt before
540 * we poll. The CPU can even halt at the current PC as a result of
541 * a software breakpoint being inserted by (a bug?) the application.
542 */
543 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
544 if (retval != ERROR_OK)
545 return retval;
546
547 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
548
549 return retval;
550 }
551
552 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
553 {
554 char buf[100];
555 int retval;
556 Jim_Nvp *n;
557 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
558 if (n->name == NULL) {
559 LOG_ERROR("invalid reset mode");
560 return ERROR_FAIL;
561 }
562
563 /* disable polling during reset to make reset event scripts
564 * more predictable, i.e. dr/irscan & pathmove in events will
565 * not have JTAG operations injected into the middle of a sequence.
566 */
567 bool save_poll = jtag_poll_get_enabled();
568
569 jtag_poll_set_enabled(false);
570
571 sprintf(buf, "ocd_process_reset %s", n->name);
572 retval = Jim_Eval(cmd_ctx->interp, buf);
573
574 jtag_poll_set_enabled(save_poll);
575
576 if (retval != JIM_OK) {
577 Jim_MakeErrorMessage(cmd_ctx->interp);
578 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
579 return ERROR_FAIL;
580 }
581
582 /* We want any events to be processed before the prompt */
583 retval = target_call_timer_callbacks_now();
584
585 struct target *target;
586 for (target = all_targets; target; target = target->next) {
587 target->type->check_reset(target);
588 target->running_alg = false;
589 }
590
591 return retval;
592 }
593
594 static int identity_virt2phys(struct target *target,
595 uint32_t virtual, uint32_t *physical)
596 {
597 *physical = virtual;
598 return ERROR_OK;
599 }
600
601 static int no_mmu(struct target *target, int *enabled)
602 {
603 *enabled = 0;
604 return ERROR_OK;
605 }
606
607 static int default_examine(struct target *target)
608 {
609 target_set_examined(target);
610 return ERROR_OK;
611 }
612
613 /* no check by default */
614 static int default_check_reset(struct target *target)
615 {
616 return ERROR_OK;
617 }
618
619 int target_examine_one(struct target *target)
620 {
621 return target->type->examine(target);
622 }
623
624 static int jtag_enable_callback(enum jtag_event event, void *priv)
625 {
626 struct target *target = priv;
627
628 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
629 return ERROR_OK;
630
631 jtag_unregister_event_callback(jtag_enable_callback, target);
632
633 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
634
635 int retval = target_examine_one(target);
636 if (retval != ERROR_OK)
637 return retval;
638
639 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
640
641 return retval;
642 }
643
644 /* Targets that correctly implement init + examine, i.e.
645 * no communication with target during init:
646 *
647 * XScale
648 */
649 int target_examine(void)
650 {
651 int retval = ERROR_OK;
652 struct target *target;
653
654 for (target = all_targets; target; target = target->next) {
655 /* defer examination, but don't skip it */
656 if (!target->tap->enabled) {
657 jtag_register_event_callback(jtag_enable_callback,
658 target);
659 continue;
660 }
661
662 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
663
664 retval = target_examine_one(target);
665 if (retval != ERROR_OK)
666 return retval;
667
668 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
669 }
670 return retval;
671 }
672
673 const char *target_type_name(struct target *target)
674 {
675 return target->type->name;
676 }
677
678 static int target_soft_reset_halt(struct target *target)
679 {
680 if (!target_was_examined(target)) {
681 LOG_ERROR("Target not examined yet");
682 return ERROR_FAIL;
683 }
684 if (!target->type->soft_reset_halt) {
685 LOG_ERROR("Target %s does not support soft_reset_halt",
686 target_name(target));
687 return ERROR_FAIL;
688 }
689 return target->type->soft_reset_halt(target);
690 }
691
692 /**
693 * Downloads a target-specific native code algorithm to the target,
694 * and executes it. * Note that some targets may need to set up, enable,
695 * and tear down a breakpoint (hard or * soft) to detect algorithm
696 * termination, while others may support lower overhead schemes where
697 * soft breakpoints embedded in the algorithm automatically terminate the
698 * algorithm.
699 *
700 * @param target used to run the algorithm
701 * @param arch_info target-specific description of the algorithm.
702 */
703 int target_run_algorithm(struct target *target,
704 int num_mem_params, struct mem_param *mem_params,
705 int num_reg_params, struct reg_param *reg_param,
706 uint32_t entry_point, uint32_t exit_point,
707 int timeout_ms, void *arch_info)
708 {
709 int retval = ERROR_FAIL;
710
711 if (!target_was_examined(target)) {
712 LOG_ERROR("Target not examined yet");
713 goto done;
714 }
715 if (!target->type->run_algorithm) {
716 LOG_ERROR("Target type '%s' does not support %s",
717 target_type_name(target), __func__);
718 goto done;
719 }
720
721 target->running_alg = true;
722 retval = target->type->run_algorithm(target,
723 num_mem_params, mem_params,
724 num_reg_params, reg_param,
725 entry_point, exit_point, timeout_ms, arch_info);
726 target->running_alg = false;
727
728 done:
729 return retval;
730 }
731
732 /**
733 * Downloads a target-specific native code algorithm to the target,
734 * executes and leaves it running.
735 *
736 * @param target used to run the algorithm
737 * @param arch_info target-specific description of the algorithm.
738 */
739 int target_start_algorithm(struct target *target,
740 int num_mem_params, struct mem_param *mem_params,
741 int num_reg_params, struct reg_param *reg_params,
742 uint32_t entry_point, uint32_t exit_point,
743 void *arch_info)
744 {
745 int retval = ERROR_FAIL;
746
747 if (!target_was_examined(target)) {
748 LOG_ERROR("Target not examined yet");
749 goto done;
750 }
751 if (!target->type->start_algorithm) {
752 LOG_ERROR("Target type '%s' does not support %s",
753 target_type_name(target), __func__);
754 goto done;
755 }
756 if (target->running_alg) {
757 LOG_ERROR("Target is already running an algorithm");
758 goto done;
759 }
760
761 target->running_alg = true;
762 retval = target->type->start_algorithm(target,
763 num_mem_params, mem_params,
764 num_reg_params, reg_params,
765 entry_point, exit_point, arch_info);
766
767 done:
768 return retval;
769 }
770
771 /**
772 * Waits for an algorithm started with target_start_algorithm() to complete.
773 *
774 * @param target used to run the algorithm
775 * @param arch_info target-specific description of the algorithm.
776 */
777 int target_wait_algorithm(struct target *target,
778 int num_mem_params, struct mem_param *mem_params,
779 int num_reg_params, struct reg_param *reg_params,
780 uint32_t exit_point, int timeout_ms,
781 void *arch_info)
782 {
783 int retval = ERROR_FAIL;
784
785 if (!target->type->wait_algorithm) {
786 LOG_ERROR("Target type '%s' does not support %s",
787 target_type_name(target), __func__);
788 goto done;
789 }
790 if (!target->running_alg) {
791 LOG_ERROR("Target is not running an algorithm");
792 goto done;
793 }
794
795 retval = target->type->wait_algorithm(target,
796 num_mem_params, mem_params,
797 num_reg_params, reg_params,
798 exit_point, timeout_ms, arch_info);
799 if (retval != ERROR_TARGET_TIMEOUT)
800 target->running_alg = false;
801
802 done:
803 return retval;
804 }
805
806 /**
807 * Executes a target-specific native code algorithm in the target.
808 * It differs from target_run_algorithm in that the algorithm is asynchronous.
809 * Because of this it requires an compliant algorithm:
810 * see contrib/loaders/flash/stm32f1x.S for example.
811 *
812 * @param target used to run the algorithm
813 */
814
815 int target_run_flash_async_algorithm(struct target *target,
816 uint8_t *buffer, uint32_t count, int block_size,
817 int num_mem_params, struct mem_param *mem_params,
818 int num_reg_params, struct reg_param *reg_params,
819 uint32_t buffer_start, uint32_t buffer_size,
820 uint32_t entry_point, uint32_t exit_point, void *arch_info)
821 {
822 int retval;
823 int timeout = 0;
824
825 /* Set up working area. First word is write pointer, second word is read pointer,
826 * rest is fifo data area. */
827 uint32_t wp_addr = buffer_start;
828 uint32_t rp_addr = buffer_start + 4;
829 uint32_t fifo_start_addr = buffer_start + 8;
830 uint32_t fifo_end_addr = buffer_start + buffer_size;
831
832 uint32_t wp = fifo_start_addr;
833 uint32_t rp = fifo_start_addr;
834
835 /* validate block_size is 2^n */
836 assert(!block_size || !(block_size & (block_size - 1)));
837
838 retval = target_write_u32(target, wp_addr, wp);
839 if (retval != ERROR_OK)
840 return retval;
841 retval = target_write_u32(target, rp_addr, rp);
842 if (retval != ERROR_OK)
843 return retval;
844
845 /* Start up algorithm on target and let it idle while writing the first chunk */
846 retval = target_start_algorithm(target, num_mem_params, mem_params,
847 num_reg_params, reg_params,
848 entry_point,
849 exit_point,
850 arch_info);
851
852 if (retval != ERROR_OK) {
853 LOG_ERROR("error starting target flash write algorithm");
854 return retval;
855 }
856
857 while (count > 0) {
858
859 retval = target_read_u32(target, rp_addr, &rp);
860 if (retval != ERROR_OK) {
861 LOG_ERROR("failed to get read pointer");
862 break;
863 }
864
865 LOG_DEBUG("count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32, count, wp, rp);
866
867 if (rp == 0) {
868 LOG_ERROR("flash write algorithm aborted by target");
869 retval = ERROR_FLASH_OPERATION_FAILED;
870 break;
871 }
872
873 if ((rp & (block_size - 1)) || rp < fifo_start_addr || rp >= fifo_end_addr) {
874 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
875 break;
876 }
877
878 /* Count the number of bytes available in the fifo without
879 * crossing the wrap around. Make sure to not fill it completely,
880 * because that would make wp == rp and that's the empty condition. */
881 uint32_t thisrun_bytes;
882 if (rp > wp)
883 thisrun_bytes = rp - wp - block_size;
884 else if (rp > fifo_start_addr)
885 thisrun_bytes = fifo_end_addr - wp;
886 else
887 thisrun_bytes = fifo_end_addr - wp - block_size;
888
889 if (thisrun_bytes == 0) {
890 /* Throttle polling a bit if transfer is (much) faster than flash
891 * programming. The exact delay shouldn't matter as long as it's
892 * less than buffer size / flash speed. This is very unlikely to
893 * run when using high latency connections such as USB. */
894 alive_sleep(10);
895
896 /* to stop an infinite loop on some targets check and increment a timeout
897 * this issue was observed on a stellaris using the new ICDI interface */
898 if (timeout++ >= 500) {
899 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
900 return ERROR_FLASH_OPERATION_FAILED;
901 }
902 continue;
903 }
904
905 /* reset our timeout */
906 timeout = 0;
907
908 /* Limit to the amount of data we actually want to write */
909 if (thisrun_bytes > count * block_size)
910 thisrun_bytes = count * block_size;
911
912 /* Write data to fifo */
913 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
914 if (retval != ERROR_OK)
915 break;
916
917 /* Update counters and wrap write pointer */
918 buffer += thisrun_bytes;
919 count -= thisrun_bytes / block_size;
920 wp += thisrun_bytes;
921 if (wp >= fifo_end_addr)
922 wp = fifo_start_addr;
923
924 /* Store updated write pointer to target */
925 retval = target_write_u32(target, wp_addr, wp);
926 if (retval != ERROR_OK)
927 break;
928 }
929
930 if (retval != ERROR_OK) {
931 /* abort flash write algorithm on target */
932 target_write_u32(target, wp_addr, 0);
933 }
934
935 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
936 num_reg_params, reg_params,
937 exit_point,
938 10000,
939 arch_info);
940
941 if (retval2 != ERROR_OK) {
942 LOG_ERROR("error waiting for target flash write algorithm");
943 retval = retval2;
944 }
945
946 return retval;
947 }
948
949 int target_read_memory(struct target *target,
950 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
951 {
952 if (!target_was_examined(target)) {
953 LOG_ERROR("Target not examined yet");
954 return ERROR_FAIL;
955 }
956 return target->type->read_memory(target, address, size, count, buffer);
957 }
958
959 int target_read_phys_memory(struct target *target,
960 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
961 {
962 if (!target_was_examined(target)) {
963 LOG_ERROR("Target not examined yet");
964 return ERROR_FAIL;
965 }
966 return target->type->read_phys_memory(target, address, size, count, buffer);
967 }
968
969 int target_write_memory(struct target *target,
970 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
971 {
972 if (!target_was_examined(target)) {
973 LOG_ERROR("Target not examined yet");
974 return ERROR_FAIL;
975 }
976 return target->type->write_memory(target, address, size, count, buffer);
977 }
978
979 int target_write_phys_memory(struct target *target,
980 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
981 {
982 if (!target_was_examined(target)) {
983 LOG_ERROR("Target not examined yet");
984 return ERROR_FAIL;
985 }
986 return target->type->write_phys_memory(target, address, size, count, buffer);
987 }
988
989 static int target_bulk_write_memory_default(struct target *target,
990 uint32_t address, uint32_t count, const uint8_t *buffer)
991 {
992 return target_write_memory(target, address, 4, count, buffer);
993 }
994
995 int target_add_breakpoint(struct target *target,
996 struct breakpoint *breakpoint)
997 {
998 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
999 LOG_WARNING("target %s is not halted", target_name(target));
1000 return ERROR_TARGET_NOT_HALTED;
1001 }
1002 return target->type->add_breakpoint(target, breakpoint);
1003 }
1004
1005 int target_add_context_breakpoint(struct target *target,
1006 struct breakpoint *breakpoint)
1007 {
1008 if (target->state != TARGET_HALTED) {
1009 LOG_WARNING("target %s is not halted", target_name(target));
1010 return ERROR_TARGET_NOT_HALTED;
1011 }
1012 return target->type->add_context_breakpoint(target, breakpoint);
1013 }
1014
1015 int target_add_hybrid_breakpoint(struct target *target,
1016 struct breakpoint *breakpoint)
1017 {
1018 if (target->state != TARGET_HALTED) {
1019 LOG_WARNING("target %s is not halted", target_name(target));
1020 return ERROR_TARGET_NOT_HALTED;
1021 }
1022 return target->type->add_hybrid_breakpoint(target, breakpoint);
1023 }
1024
1025 int target_remove_breakpoint(struct target *target,
1026 struct breakpoint *breakpoint)
1027 {
1028 return target->type->remove_breakpoint(target, breakpoint);
1029 }
1030
1031 int target_add_watchpoint(struct target *target,
1032 struct watchpoint *watchpoint)
1033 {
1034 if (target->state != TARGET_HALTED) {
1035 LOG_WARNING("target %s is not halted", target_name(target));
1036 return ERROR_TARGET_NOT_HALTED;
1037 }
1038 return target->type->add_watchpoint(target, watchpoint);
1039 }
1040 int target_remove_watchpoint(struct target *target,
1041 struct watchpoint *watchpoint)
1042 {
1043 return target->type->remove_watchpoint(target, watchpoint);
1044 }
1045 int target_hit_watchpoint(struct target *target,
1046 struct watchpoint **hit_watchpoint)
1047 {
1048 if (target->state != TARGET_HALTED) {
1049 LOG_WARNING("target %s is not halted", target->cmd_name);
1050 return ERROR_TARGET_NOT_HALTED;
1051 }
1052
1053 if (target->type->hit_watchpoint == NULL) {
1054 /* For backward compatible, if hit_watchpoint is not implemented,
1055 * return ERROR_FAIL such that gdb_server will not take the nonsense
1056 * information. */
1057 return ERROR_FAIL;
1058 }
1059
1060 return target->type->hit_watchpoint(target, hit_watchpoint);
1061 }
1062
1063 int target_get_gdb_reg_list(struct target *target,
1064 struct reg **reg_list[], int *reg_list_size,
1065 enum target_register_class reg_class)
1066 {
1067 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1068 }
1069 int target_step(struct target *target,
1070 int current, uint32_t address, int handle_breakpoints)
1071 {
1072 return target->type->step(target, current, address, handle_breakpoints);
1073 }
1074
1075 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1076 {
1077 if (target->state != TARGET_HALTED) {
1078 LOG_WARNING("target %s is not halted", target->cmd_name);
1079 return ERROR_TARGET_NOT_HALTED;
1080 }
1081 return target->type->get_gdb_fileio_info(target, fileio_info);
1082 }
1083
1084 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1085 {
1086 if (target->state != TARGET_HALTED) {
1087 LOG_WARNING("target %s is not halted", target->cmd_name);
1088 return ERROR_TARGET_NOT_HALTED;
1089 }
1090 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1091 }
1092
1093 /**
1094 * Reset the @c examined flag for the given target.
1095 * Pure paranoia -- targets are zeroed on allocation.
1096 */
1097 static void target_reset_examined(struct target *target)
1098 {
1099 target->examined = false;
1100 }
1101
1102 static int err_read_phys_memory(struct target *target, uint32_t address,
1103 uint32_t size, uint32_t count, uint8_t *buffer)
1104 {
1105 LOG_ERROR("Not implemented: %s", __func__);
1106 return ERROR_FAIL;
1107 }
1108
1109 static int err_write_phys_memory(struct target *target, uint32_t address,
1110 uint32_t size, uint32_t count, const uint8_t *buffer)
1111 {
1112 LOG_ERROR("Not implemented: %s", __func__);
1113 return ERROR_FAIL;
1114 }
1115
1116 static int handle_target(void *priv);
1117
1118 static int target_init_one(struct command_context *cmd_ctx,
1119 struct target *target)
1120 {
1121 target_reset_examined(target);
1122
1123 struct target_type *type = target->type;
1124 if (type->examine == NULL)
1125 type->examine = default_examine;
1126
1127 if (type->check_reset == NULL)
1128 type->check_reset = default_check_reset;
1129
1130 assert(type->init_target != NULL);
1131
1132 int retval = type->init_target(cmd_ctx, target);
1133 if (ERROR_OK != retval) {
1134 LOG_ERROR("target '%s' init failed", target_name(target));
1135 return retval;
1136 }
1137
1138 /* Sanity-check MMU support ... stub in what we must, to help
1139 * implement it in stages, but warn if we need to do so.
1140 */
1141 if (type->mmu) {
1142 if (type->write_phys_memory == NULL) {
1143 LOG_ERROR("type '%s' is missing write_phys_memory",
1144 type->name);
1145 type->write_phys_memory = err_write_phys_memory;
1146 }
1147 if (type->read_phys_memory == NULL) {
1148 LOG_ERROR("type '%s' is missing read_phys_memory",
1149 type->name);
1150 type->read_phys_memory = err_read_phys_memory;
1151 }
1152 if (type->virt2phys == NULL) {
1153 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1154 type->virt2phys = identity_virt2phys;
1155 }
1156 } else {
1157 /* Make sure no-MMU targets all behave the same: make no
1158 * distinction between physical and virtual addresses, and
1159 * ensure that virt2phys() is always an identity mapping.
1160 */
1161 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1162 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1163
1164 type->mmu = no_mmu;
1165 type->write_phys_memory = type->write_memory;
1166 type->read_phys_memory = type->read_memory;
1167 type->virt2phys = identity_virt2phys;
1168 }
1169
1170 if (target->type->read_buffer == NULL)
1171 target->type->read_buffer = target_read_buffer_default;
1172
1173 if (target->type->write_buffer == NULL)
1174 target->type->write_buffer = target_write_buffer_default;
1175
1176 if (target->type->bulk_write_memory == NULL)
1177 target->type->bulk_write_memory = target_bulk_write_memory_default;
1178
1179 if (target->type->get_gdb_fileio_info == NULL)
1180 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1181
1182 if (target->type->gdb_fileio_end == NULL)
1183 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1184
1185 return ERROR_OK;
1186 }
1187
1188 static int target_init(struct command_context *cmd_ctx)
1189 {
1190 struct target *target;
1191 int retval;
1192
1193 for (target = all_targets; target; target = target->next) {
1194 retval = target_init_one(cmd_ctx, target);
1195 if (ERROR_OK != retval)
1196 return retval;
1197 }
1198
1199 if (!all_targets)
1200 return ERROR_OK;
1201
1202 retval = target_register_user_commands(cmd_ctx);
1203 if (ERROR_OK != retval)
1204 return retval;
1205
1206 retval = target_register_timer_callback(&handle_target,
1207 polling_interval, 1, cmd_ctx->interp);
1208 if (ERROR_OK != retval)
1209 return retval;
1210
1211 return ERROR_OK;
1212 }
1213
1214 COMMAND_HANDLER(handle_target_init_command)
1215 {
1216 int retval;
1217
1218 if (CMD_ARGC != 0)
1219 return ERROR_COMMAND_SYNTAX_ERROR;
1220
1221 static bool target_initialized;
1222 if (target_initialized) {
1223 LOG_INFO("'target init' has already been called");
1224 return ERROR_OK;
1225 }
1226 target_initialized = true;
1227
1228 retval = command_run_line(CMD_CTX, "init_targets");
1229 if (ERROR_OK != retval)
1230 return retval;
1231
1232 retval = command_run_line(CMD_CTX, "init_board");
1233 if (ERROR_OK != retval)
1234 return retval;
1235
1236 LOG_DEBUG("Initializing targets...");
1237 return target_init(CMD_CTX);
1238 }
1239
1240 int target_register_event_callback(int (*callback)(struct target *target,
1241 enum target_event event, void *priv), void *priv)
1242 {
1243 struct target_event_callback **callbacks_p = &target_event_callbacks;
1244
1245 if (callback == NULL)
1246 return ERROR_COMMAND_SYNTAX_ERROR;
1247
1248 if (*callbacks_p) {
1249 while ((*callbacks_p)->next)
1250 callbacks_p = &((*callbacks_p)->next);
1251 callbacks_p = &((*callbacks_p)->next);
1252 }
1253
1254 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1255 (*callbacks_p)->callback = callback;
1256 (*callbacks_p)->priv = priv;
1257 (*callbacks_p)->next = NULL;
1258
1259 return ERROR_OK;
1260 }
1261
1262 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
1263 {
1264 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1265 struct timeval now;
1266
1267 if (callback == NULL)
1268 return ERROR_COMMAND_SYNTAX_ERROR;
1269
1270 if (*callbacks_p) {
1271 while ((*callbacks_p)->next)
1272 callbacks_p = &((*callbacks_p)->next);
1273 callbacks_p = &((*callbacks_p)->next);
1274 }
1275
1276 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1277 (*callbacks_p)->callback = callback;
1278 (*callbacks_p)->periodic = periodic;
1279 (*callbacks_p)->time_ms = time_ms;
1280
1281 gettimeofday(&now, NULL);
1282 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
1283 time_ms -= (time_ms % 1000);
1284 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
1285 if ((*callbacks_p)->when.tv_usec > 1000000) {
1286 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
1287 (*callbacks_p)->when.tv_sec += 1;
1288 }
1289
1290 (*callbacks_p)->priv = priv;
1291 (*callbacks_p)->next = NULL;
1292
1293 return ERROR_OK;
1294 }
1295
1296 int target_unregister_event_callback(int (*callback)(struct target *target,
1297 enum target_event event, void *priv), void *priv)
1298 {
1299 struct target_event_callback **p = &target_event_callbacks;
1300 struct target_event_callback *c = target_event_callbacks;
1301
1302 if (callback == NULL)
1303 return ERROR_COMMAND_SYNTAX_ERROR;
1304
1305 while (c) {
1306 struct target_event_callback *next = c->next;
1307 if ((c->callback == callback) && (c->priv == priv)) {
1308 *p = next;
1309 free(c);
1310 return ERROR_OK;
1311 } else
1312 p = &(c->next);
1313 c = next;
1314 }
1315
1316 return ERROR_OK;
1317 }
1318
1319 static int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1320 {
1321 struct target_timer_callback **p = &target_timer_callbacks;
1322 struct target_timer_callback *c = target_timer_callbacks;
1323
1324 if (callback == NULL)
1325 return ERROR_COMMAND_SYNTAX_ERROR;
1326
1327 while (c) {
1328 struct target_timer_callback *next = c->next;
1329 if ((c->callback == callback) && (c->priv == priv)) {
1330 *p = next;
1331 free(c);
1332 return ERROR_OK;
1333 } else
1334 p = &(c->next);
1335 c = next;
1336 }
1337
1338 return ERROR_OK;
1339 }
1340
1341 int target_call_event_callbacks(struct target *target, enum target_event event)
1342 {
1343 struct target_event_callback *callback = target_event_callbacks;
1344 struct target_event_callback *next_callback;
1345
1346 if (event == TARGET_EVENT_HALTED) {
1347 /* execute early halted first */
1348 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1349 }
1350
1351 LOG_DEBUG("target event %i (%s)", event,
1352 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1353
1354 target_handle_event(target, event);
1355
1356 while (callback) {
1357 next_callback = callback->next;
1358 callback->callback(target, event, callback->priv);
1359 callback = next_callback;
1360 }
1361
1362 return ERROR_OK;
1363 }
1364
1365 static int target_timer_callback_periodic_restart(
1366 struct target_timer_callback *cb, struct timeval *now)
1367 {
1368 int time_ms = cb->time_ms;
1369 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1370 time_ms -= (time_ms % 1000);
1371 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1372 if (cb->when.tv_usec > 1000000) {
1373 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1374 cb->when.tv_sec += 1;
1375 }
1376 return ERROR_OK;
1377 }
1378
1379 static int target_call_timer_callback(struct target_timer_callback *cb,
1380 struct timeval *now)
1381 {
1382 cb->callback(cb->priv);
1383
1384 if (cb->periodic)
1385 return target_timer_callback_periodic_restart(cb, now);
1386
1387 return target_unregister_timer_callback(cb->callback, cb->priv);
1388 }
1389
1390 static int target_call_timer_callbacks_check_time(int checktime)
1391 {
1392 keep_alive();
1393
1394 struct timeval now;
1395 gettimeofday(&now, NULL);
1396
1397 struct target_timer_callback *callback = target_timer_callbacks;
1398 while (callback) {
1399 /* cleaning up may unregister and free this callback */
1400 struct target_timer_callback *next_callback = callback->next;
1401
1402 bool call_it = callback->callback &&
1403 ((!checktime && callback->periodic) ||
1404 now.tv_sec > callback->when.tv_sec ||
1405 (now.tv_sec == callback->when.tv_sec &&
1406 now.tv_usec >= callback->when.tv_usec));
1407
1408 if (call_it) {
1409 int retval = target_call_timer_callback(callback, &now);
1410 if (retval != ERROR_OK)
1411 return retval;
1412 }
1413
1414 callback = next_callback;
1415 }
1416
1417 return ERROR_OK;
1418 }
1419
1420 int target_call_timer_callbacks(void)
1421 {
1422 return target_call_timer_callbacks_check_time(1);
1423 }
1424
1425 /* invoke periodic callbacks immediately */
1426 int target_call_timer_callbacks_now(void)
1427 {
1428 return target_call_timer_callbacks_check_time(0);
1429 }
1430
1431 /* Prints the working area layout for debug purposes */
1432 static void print_wa_layout(struct target *target)
1433 {
1434 struct working_area *c = target->working_areas;
1435
1436 while (c) {
1437 LOG_DEBUG("%c%c 0x%08"PRIx32"-0x%08"PRIx32" (%"PRIu32" bytes)",
1438 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1439 c->address, c->address + c->size - 1, c->size);
1440 c = c->next;
1441 }
1442 }
1443
1444 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1445 static void target_split_working_area(struct working_area *area, uint32_t size)
1446 {
1447 assert(area->free); /* Shouldn't split an allocated area */
1448 assert(size <= area->size); /* Caller should guarantee this */
1449
1450 /* Split only if not already the right size */
1451 if (size < area->size) {
1452 struct working_area *new_wa = malloc(sizeof(*new_wa));
1453
1454 if (new_wa == NULL)
1455 return;
1456
1457 new_wa->next = area->next;
1458 new_wa->size = area->size - size;
1459 new_wa->address = area->address + size;
1460 new_wa->backup = NULL;
1461 new_wa->user = NULL;
1462 new_wa->free = true;
1463
1464 area->next = new_wa;
1465 area->size = size;
1466
1467 /* If backup memory was allocated to this area, it has the wrong size
1468 * now so free it and it will be reallocated if/when needed */
1469 if (area->backup) {
1470 free(area->backup);
1471 area->backup = NULL;
1472 }
1473 }
1474 }
1475
1476 /* Merge all adjacent free areas into one */
1477 static void target_merge_working_areas(struct target *target)
1478 {
1479 struct working_area *c = target->working_areas;
1480
1481 while (c && c->next) {
1482 assert(c->next->address == c->address + c->size); /* This is an invariant */
1483
1484 /* Find two adjacent free areas */
1485 if (c->free && c->next->free) {
1486 /* Merge the last into the first */
1487 c->size += c->next->size;
1488
1489 /* Remove the last */
1490 struct working_area *to_be_freed = c->next;
1491 c->next = c->next->next;
1492 if (to_be_freed->backup)
1493 free(to_be_freed->backup);
1494 free(to_be_freed);
1495
1496 /* If backup memory was allocated to the remaining area, it's has
1497 * the wrong size now */
1498 if (c->backup) {
1499 free(c->backup);
1500 c->backup = NULL;
1501 }
1502 } else {
1503 c = c->next;
1504 }
1505 }
1506 }
1507
1508 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1509 {
1510 /* Reevaluate working area address based on MMU state*/
1511 if (target->working_areas == NULL) {
1512 int retval;
1513 int enabled;
1514
1515 retval = target->type->mmu(target, &enabled);
1516 if (retval != ERROR_OK)
1517 return retval;
1518
1519 if (!enabled) {
1520 if (target->working_area_phys_spec) {
1521 LOG_DEBUG("MMU disabled, using physical "
1522 "address for working memory 0x%08"PRIx32,
1523 target->working_area_phys);
1524 target->working_area = target->working_area_phys;
1525 } else {
1526 LOG_ERROR("No working memory available. "
1527 "Specify -work-area-phys to target.");
1528 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1529 }
1530 } else {
1531 if (target->working_area_virt_spec) {
1532 LOG_DEBUG("MMU enabled, using virtual "
1533 "address for working memory 0x%08"PRIx32,
1534 target->working_area_virt);
1535 target->working_area = target->working_area_virt;
1536 } else {
1537 LOG_ERROR("No working memory available. "
1538 "Specify -work-area-virt to target.");
1539 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1540 }
1541 }
1542
1543 /* Set up initial working area on first call */
1544 struct working_area *new_wa = malloc(sizeof(*new_wa));
1545 if (new_wa) {
1546 new_wa->next = NULL;
1547 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
1548 new_wa->address = target->working_area;
1549 new_wa->backup = NULL;
1550 new_wa->user = NULL;
1551 new_wa->free = true;
1552 }
1553
1554 target->working_areas = new_wa;
1555 }
1556
1557 /* only allocate multiples of 4 byte */
1558 if (size % 4)
1559 size = (size + 3) & (~3UL);
1560
1561 struct working_area *c = target->working_areas;
1562
1563 /* Find the first large enough working area */
1564 while (c) {
1565 if (c->free && c->size >= size)
1566 break;
1567 c = c->next;
1568 }
1569
1570 if (c == NULL)
1571 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1572
1573 /* Split the working area into the requested size */
1574 target_split_working_area(c, size);
1575
1576 LOG_DEBUG("allocated new working area of %"PRIu32" bytes at address 0x%08"PRIx32, size, c->address);
1577
1578 if (target->backup_working_area) {
1579 if (c->backup == NULL) {
1580 c->backup = malloc(c->size);
1581 if (c->backup == NULL)
1582 return ERROR_FAIL;
1583 }
1584
1585 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
1586 if (retval != ERROR_OK)
1587 return retval;
1588 }
1589
1590 /* mark as used, and return the new (reused) area */
1591 c->free = false;
1592 *area = c;
1593
1594 /* user pointer */
1595 c->user = area;
1596
1597 print_wa_layout(target);
1598
1599 return ERROR_OK;
1600 }
1601
1602 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1603 {
1604 int retval;
1605
1606 retval = target_alloc_working_area_try(target, size, area);
1607 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1608 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
1609 return retval;
1610
1611 }
1612
1613 static int target_restore_working_area(struct target *target, struct working_area *area)
1614 {
1615 int retval = ERROR_OK;
1616
1617 if (target->backup_working_area && area->backup != NULL) {
1618 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
1619 if (retval != ERROR_OK)
1620 LOG_ERROR("failed to restore %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1621 area->size, area->address);
1622 }
1623
1624 return retval;
1625 }
1626
1627 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
1628 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1629 {
1630 int retval = ERROR_OK;
1631
1632 if (area->free)
1633 return retval;
1634
1635 if (restore) {
1636 retval = target_restore_working_area(target, area);
1637 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
1638 if (retval != ERROR_OK)
1639 return retval;
1640 }
1641
1642 area->free = true;
1643
1644 LOG_DEBUG("freed %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1645 area->size, area->address);
1646
1647 /* mark user pointer invalid */
1648 /* TODO: Is this really safe? It points to some previous caller's memory.
1649 * How could we know that the area pointer is still in that place and not
1650 * some other vital data? What's the purpose of this, anyway? */
1651 *area->user = NULL;
1652 area->user = NULL;
1653
1654 target_merge_working_areas(target);
1655
1656 print_wa_layout(target);
1657
1658 return retval;
1659 }
1660
1661 int target_free_working_area(struct target *target, struct working_area *area)
1662 {
1663 return target_free_working_area_restore(target, area, 1);
1664 }
1665
1666 /* free resources and restore memory, if restoring memory fails,
1667 * free up resources anyway
1668 */
1669 static void target_free_all_working_areas_restore(struct target *target, int restore)
1670 {
1671 struct working_area *c = target->working_areas;
1672
1673 LOG_DEBUG("freeing all working areas");
1674
1675 /* Loop through all areas, restoring the allocated ones and marking them as free */
1676 while (c) {
1677 if (!c->free) {
1678 if (restore)
1679 target_restore_working_area(target, c);
1680 c->free = true;
1681 *c->user = NULL; /* Same as above */
1682 c->user = NULL;
1683 }
1684 c = c->next;
1685 }
1686
1687 /* Run a merge pass to combine all areas into one */
1688 target_merge_working_areas(target);
1689
1690 print_wa_layout(target);
1691 }
1692
1693 void target_free_all_working_areas(struct target *target)
1694 {
1695 target_free_all_working_areas_restore(target, 1);
1696 }
1697
1698 /* Find the largest number of bytes that can be allocated */
1699 uint32_t target_get_working_area_avail(struct target *target)
1700 {
1701 struct working_area *c = target->working_areas;
1702 uint32_t max_size = 0;
1703
1704 if (c == NULL)
1705 return target->working_area_size;
1706
1707 while (c) {
1708 if (c->free && max_size < c->size)
1709 max_size = c->size;
1710
1711 c = c->next;
1712 }
1713
1714 return max_size;
1715 }
1716
1717 int target_arch_state(struct target *target)
1718 {
1719 int retval;
1720 if (target == NULL) {
1721 LOG_USER("No target has been configured");
1722 return ERROR_OK;
1723 }
1724
1725 LOG_USER("target state: %s", target_state_name(target));
1726
1727 if (target->state != TARGET_HALTED)
1728 return ERROR_OK;
1729
1730 retval = target->type->arch_state(target);
1731 return retval;
1732 }
1733
1734 static int target_get_gdb_fileio_info_default(struct target *target,
1735 struct gdb_fileio_info *fileio_info)
1736 {
1737 /* If target does not support semi-hosting function, target
1738 has no need to provide .get_gdb_fileio_info callback.
1739 It just return ERROR_FAIL and gdb_server will return "Txx"
1740 as target halted every time. */
1741 return ERROR_FAIL;
1742 }
1743
1744 static int target_gdb_fileio_end_default(struct target *target,
1745 int retcode, int fileio_errno, bool ctrl_c)
1746 {
1747 return ERROR_OK;
1748 }
1749
1750 /* Single aligned words are guaranteed to use 16 or 32 bit access
1751 * mode respectively, otherwise data is handled as quickly as
1752 * possible
1753 */
1754 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1755 {
1756 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1757 (int)size, (unsigned)address);
1758
1759 if (!target_was_examined(target)) {
1760 LOG_ERROR("Target not examined yet");
1761 return ERROR_FAIL;
1762 }
1763
1764 if (size == 0)
1765 return ERROR_OK;
1766
1767 if ((address + size - 1) < address) {
1768 /* GDB can request this when e.g. PC is 0xfffffffc*/
1769 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1770 (unsigned)address,
1771 (unsigned)size);
1772 return ERROR_FAIL;
1773 }
1774
1775 return target->type->write_buffer(target, address, size, buffer);
1776 }
1777
1778 static int target_write_buffer_default(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1779 {
1780 int retval = ERROR_OK;
1781
1782 if (((address % 2) == 0) && (size == 2))
1783 return target_write_memory(target, address, 2, 1, buffer);
1784
1785 /* handle unaligned head bytes */
1786 if (address % 4) {
1787 uint32_t unaligned = 4 - (address % 4);
1788
1789 if (unaligned > size)
1790 unaligned = size;
1791
1792 retval = target_write_memory(target, address, 1, unaligned, buffer);
1793 if (retval != ERROR_OK)
1794 return retval;
1795
1796 buffer += unaligned;
1797 address += unaligned;
1798 size -= unaligned;
1799 }
1800
1801 /* handle aligned words */
1802 if (size >= 4) {
1803 int aligned = size - (size % 4);
1804
1805 /* use bulk writes above a certain limit. This may have to be changed */
1806 if (aligned > 128) {
1807 retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer);
1808 if (retval != ERROR_OK)
1809 return retval;
1810 } else {
1811 retval = target_write_memory(target, address, 4, aligned / 4, buffer);
1812 if (retval != ERROR_OK)
1813 return retval;
1814 }
1815
1816 buffer += aligned;
1817 address += aligned;
1818 size -= aligned;
1819 }
1820
1821 /* handle tail writes of less than 4 bytes */
1822 if (size > 0) {
1823 retval = target_write_memory(target, address, 1, size, buffer);
1824 if (retval != ERROR_OK)
1825 return retval;
1826 }
1827
1828 return retval;
1829 }
1830
1831 /* Single aligned words are guaranteed to use 16 or 32 bit access
1832 * mode respectively, otherwise data is handled as quickly as
1833 * possible
1834 */
1835 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1836 {
1837 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1838 (int)size, (unsigned)address);
1839
1840 if (!target_was_examined(target)) {
1841 LOG_ERROR("Target not examined yet");
1842 return ERROR_FAIL;
1843 }
1844
1845 if (size == 0)
1846 return ERROR_OK;
1847
1848 if ((address + size - 1) < address) {
1849 /* GDB can request this when e.g. PC is 0xfffffffc*/
1850 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1851 address,
1852 size);
1853 return ERROR_FAIL;
1854 }
1855
1856 return target->type->read_buffer(target, address, size, buffer);
1857 }
1858
1859 static int target_read_buffer_default(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1860 {
1861 int retval = ERROR_OK;
1862
1863 if (((address % 2) == 0) && (size == 2))
1864 return target_read_memory(target, address, 2, 1, buffer);
1865
1866 /* handle unaligned head bytes */
1867 if (address % 4) {
1868 uint32_t unaligned = 4 - (address % 4);
1869
1870 if (unaligned > size)
1871 unaligned = size;
1872
1873 retval = target_read_memory(target, address, 1, unaligned, buffer);
1874 if (retval != ERROR_OK)
1875 return retval;
1876
1877 buffer += unaligned;
1878 address += unaligned;
1879 size -= unaligned;
1880 }
1881
1882 /* handle aligned words */
1883 if (size >= 4) {
1884 int aligned = size - (size % 4);
1885
1886 retval = target_read_memory(target, address, 4, aligned / 4, buffer);
1887 if (retval != ERROR_OK)
1888 return retval;
1889
1890 buffer += aligned;
1891 address += aligned;
1892 size -= aligned;
1893 }
1894
1895 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1896 if (size >= 2) {
1897 int aligned = size - (size % 2);
1898 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1899 if (retval != ERROR_OK)
1900 return retval;
1901
1902 buffer += aligned;
1903 address += aligned;
1904 size -= aligned;
1905 }
1906 /* handle tail writes of less than 4 bytes */
1907 if (size > 0) {
1908 retval = target_read_memory(target, address, 1, size, buffer);
1909 if (retval != ERROR_OK)
1910 return retval;
1911 }
1912
1913 return ERROR_OK;
1914 }
1915
1916 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1917 {
1918 uint8_t *buffer;
1919 int retval;
1920 uint32_t i;
1921 uint32_t checksum = 0;
1922 if (!target_was_examined(target)) {
1923 LOG_ERROR("Target not examined yet");
1924 return ERROR_FAIL;
1925 }
1926
1927 retval = target->type->checksum_memory(target, address, size, &checksum);
1928 if (retval != ERROR_OK) {
1929 buffer = malloc(size);
1930 if (buffer == NULL) {
1931 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1932 return ERROR_COMMAND_SYNTAX_ERROR;
1933 }
1934 retval = target_read_buffer(target, address, size, buffer);
1935 if (retval != ERROR_OK) {
1936 free(buffer);
1937 return retval;
1938 }
1939
1940 /* convert to target endianness */
1941 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
1942 uint32_t target_data;
1943 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1944 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1945 }
1946
1947 retval = image_calculate_checksum(buffer, size, &checksum);
1948 free(buffer);
1949 }
1950
1951 *crc = checksum;
1952
1953 return retval;
1954 }
1955
1956 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1957 {
1958 int retval;
1959 if (!target_was_examined(target)) {
1960 LOG_ERROR("Target not examined yet");
1961 return ERROR_FAIL;
1962 }
1963
1964 if (target->type->blank_check_memory == 0)
1965 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1966
1967 retval = target->type->blank_check_memory(target, address, size, blank);
1968
1969 return retval;
1970 }
1971
1972 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1973 {
1974 uint8_t value_buf[4];
1975 if (!target_was_examined(target)) {
1976 LOG_ERROR("Target not examined yet");
1977 return ERROR_FAIL;
1978 }
1979
1980 int retval = target_read_memory(target, address, 4, 1, value_buf);
1981
1982 if (retval == ERROR_OK) {
1983 *value = target_buffer_get_u32(target, value_buf);
1984 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1985 address,
1986 *value);
1987 } else {
1988 *value = 0x0;
1989 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1990 address);
1991 }
1992
1993 return retval;
1994 }
1995
1996 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1997 {
1998 uint8_t value_buf[2];
1999 if (!target_was_examined(target)) {
2000 LOG_ERROR("Target not examined yet");
2001 return ERROR_FAIL;
2002 }
2003
2004 int retval = target_read_memory(target, address, 2, 1, value_buf);
2005
2006 if (retval == ERROR_OK) {
2007 *value = target_buffer_get_u16(target, value_buf);
2008 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
2009 address,
2010 *value);
2011 } else {
2012 *value = 0x0;
2013 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2014 address);
2015 }
2016
2017 return retval;
2018 }
2019
2020 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
2021 {
2022 int retval = target_read_memory(target, address, 1, 1, value);
2023 if (!target_was_examined(target)) {
2024 LOG_ERROR("Target not examined yet");
2025 return ERROR_FAIL;
2026 }
2027
2028 if (retval == ERROR_OK) {
2029 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2030 address,
2031 *value);
2032 } else {
2033 *value = 0x0;
2034 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2035 address);
2036 }
2037
2038 return retval;
2039 }
2040
2041 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
2042 {
2043 int retval;
2044 uint8_t value_buf[4];
2045 if (!target_was_examined(target)) {
2046 LOG_ERROR("Target not examined yet");
2047 return ERROR_FAIL;
2048 }
2049
2050 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
2051 address,
2052 value);
2053
2054 target_buffer_set_u32(target, value_buf, value);
2055 retval = target_write_memory(target, address, 4, 1, value_buf);
2056 if (retval != ERROR_OK)
2057 LOG_DEBUG("failed: %i", retval);
2058
2059 return retval;
2060 }
2061
2062 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
2063 {
2064 int retval;
2065 uint8_t value_buf[2];
2066 if (!target_was_examined(target)) {
2067 LOG_ERROR("Target not examined yet");
2068 return ERROR_FAIL;
2069 }
2070
2071 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
2072 address,
2073 value);
2074
2075 target_buffer_set_u16(target, value_buf, value);
2076 retval = target_write_memory(target, address, 2, 1, value_buf);
2077 if (retval != ERROR_OK)
2078 LOG_DEBUG("failed: %i", retval);
2079
2080 return retval;
2081 }
2082
2083 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
2084 {
2085 int retval;
2086 if (!target_was_examined(target)) {
2087 LOG_ERROR("Target not examined yet");
2088 return ERROR_FAIL;
2089 }
2090
2091 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2092 address, value);
2093
2094 retval = target_write_memory(target, address, 1, 1, &value);
2095 if (retval != ERROR_OK)
2096 LOG_DEBUG("failed: %i", retval);
2097
2098 return retval;
2099 }
2100
2101 static int find_target(struct command_context *cmd_ctx, const char *name)
2102 {
2103 struct target *target = get_target(name);
2104 if (target == NULL) {
2105 LOG_ERROR("Target: %s is unknown, try one of:\n", name);
2106 return ERROR_FAIL;
2107 }
2108 if (!target->tap->enabled) {
2109 LOG_USER("Target: TAP %s is disabled, "
2110 "can't be the current target\n",
2111 target->tap->dotted_name);
2112 return ERROR_FAIL;
2113 }
2114
2115 cmd_ctx->current_target = target->target_number;
2116 return ERROR_OK;
2117 }
2118
2119
2120 COMMAND_HANDLER(handle_targets_command)
2121 {
2122 int retval = ERROR_OK;
2123 if (CMD_ARGC == 1) {
2124 retval = find_target(CMD_CTX, CMD_ARGV[0]);
2125 if (retval == ERROR_OK) {
2126 /* we're done! */
2127 return retval;
2128 }
2129 }
2130
2131 struct target *target = all_targets;
2132 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
2133 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
2134 while (target) {
2135 const char *state;
2136 char marker = ' ';
2137
2138 if (target->tap->enabled)
2139 state = target_state_name(target);
2140 else
2141 state = "tap-disabled";
2142
2143 if (CMD_CTX->current_target == target->target_number)
2144 marker = '*';
2145
2146 /* keep columns lined up to match the headers above */
2147 command_print(CMD_CTX,
2148 "%2d%c %-18s %-10s %-6s %-18s %s",
2149 target->target_number,
2150 marker,
2151 target_name(target),
2152 target_type_name(target),
2153 Jim_Nvp_value2name_simple(nvp_target_endian,
2154 target->endianness)->name,
2155 target->tap->dotted_name,
2156 state);
2157 target = target->next;
2158 }
2159
2160 return retval;
2161 }
2162
2163 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2164
2165 static int powerDropout;
2166 static int srstAsserted;
2167
2168 static int runPowerRestore;
2169 static int runPowerDropout;
2170 static int runSrstAsserted;
2171 static int runSrstDeasserted;
2172
2173 static int sense_handler(void)
2174 {
2175 static int prevSrstAsserted;
2176 static int prevPowerdropout;
2177
2178 int retval = jtag_power_dropout(&powerDropout);
2179 if (retval != ERROR_OK)
2180 return retval;
2181
2182 int powerRestored;
2183 powerRestored = prevPowerdropout && !powerDropout;
2184 if (powerRestored)
2185 runPowerRestore = 1;
2186
2187 long long current = timeval_ms();
2188 static long long lastPower;
2189 int waitMore = lastPower + 2000 > current;
2190 if (powerDropout && !waitMore) {
2191 runPowerDropout = 1;
2192 lastPower = current;
2193 }
2194
2195 retval = jtag_srst_asserted(&srstAsserted);
2196 if (retval != ERROR_OK)
2197 return retval;
2198
2199 int srstDeasserted;
2200 srstDeasserted = prevSrstAsserted && !srstAsserted;
2201
2202 static long long lastSrst;
2203 waitMore = lastSrst + 2000 > current;
2204 if (srstDeasserted && !waitMore) {
2205 runSrstDeasserted = 1;
2206 lastSrst = current;
2207 }
2208
2209 if (!prevSrstAsserted && srstAsserted)
2210 runSrstAsserted = 1;
2211
2212 prevSrstAsserted = srstAsserted;
2213 prevPowerdropout = powerDropout;
2214
2215 if (srstDeasserted || powerRestored) {
2216 /* Other than logging the event we can't do anything here.
2217 * Issuing a reset is a particularly bad idea as we might
2218 * be inside a reset already.
2219 */
2220 }
2221
2222 return ERROR_OK;
2223 }
2224
2225 /* process target state changes */
2226 static int handle_target(void *priv)
2227 {
2228 Jim_Interp *interp = (Jim_Interp *)priv;
2229 int retval = ERROR_OK;
2230
2231 if (!is_jtag_poll_safe()) {
2232 /* polling is disabled currently */
2233 return ERROR_OK;
2234 }
2235
2236 /* we do not want to recurse here... */
2237 static int recursive;
2238 if (!recursive) {
2239 recursive = 1;
2240 sense_handler();
2241 /* danger! running these procedures can trigger srst assertions and power dropouts.
2242 * We need to avoid an infinite loop/recursion here and we do that by
2243 * clearing the flags after running these events.
2244 */
2245 int did_something = 0;
2246 if (runSrstAsserted) {
2247 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2248 Jim_Eval(interp, "srst_asserted");
2249 did_something = 1;
2250 }
2251 if (runSrstDeasserted) {
2252 Jim_Eval(interp, "srst_deasserted");
2253 did_something = 1;
2254 }
2255 if (runPowerDropout) {
2256 LOG_INFO("Power dropout detected, running power_dropout proc.");
2257 Jim_Eval(interp, "power_dropout");
2258 did_something = 1;
2259 }
2260 if (runPowerRestore) {
2261 Jim_Eval(interp, "power_restore");
2262 did_something = 1;
2263 }
2264
2265 if (did_something) {
2266 /* clear detect flags */
2267 sense_handler();
2268 }
2269
2270 /* clear action flags */
2271
2272 runSrstAsserted = 0;
2273 runSrstDeasserted = 0;
2274 runPowerRestore = 0;
2275 runPowerDropout = 0;
2276
2277 recursive = 0;
2278 }
2279
2280 /* Poll targets for state changes unless that's globally disabled.
2281 * Skip targets that are currently disabled.
2282 */
2283 for (struct target *target = all_targets;
2284 is_jtag_poll_safe() && target;
2285 target = target->next) {
2286 if (!target->tap->enabled)
2287 continue;
2288
2289 if (target->backoff.times > target->backoff.count) {
2290 /* do not poll this time as we failed previously */
2291 target->backoff.count++;
2292 continue;
2293 }
2294 target->backoff.count = 0;
2295
2296 /* only poll target if we've got power and srst isn't asserted */
2297 if (!powerDropout && !srstAsserted) {
2298 /* polling may fail silently until the target has been examined */
2299 retval = target_poll(target);
2300 if (retval != ERROR_OK) {
2301 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2302 if (target->backoff.times * polling_interval < 5000) {
2303 target->backoff.times *= 2;
2304 target->backoff.times++;
2305 }
2306 LOG_USER("Polling target %s failed, GDB will be halted. Polling again in %dms",
2307 target_name(target),
2308 target->backoff.times * polling_interval);
2309
2310 /* Tell GDB to halt the debugger. This allows the user to
2311 * run monitor commands to handle the situation.
2312 */
2313 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2314 return retval;
2315 }
2316 /* Since we succeeded, we reset backoff count */
2317 if (target->backoff.times > 0)
2318 LOG_USER("Polling target %s succeeded again", target_name(target));
2319 target->backoff.times = 0;
2320 }
2321 }
2322
2323 return retval;
2324 }
2325
2326 COMMAND_HANDLER(handle_reg_command)
2327 {
2328 struct target *target;
2329 struct reg *reg = NULL;
2330 unsigned count = 0;
2331 char *value;
2332
2333 LOG_DEBUG("-");
2334
2335 target = get_current_target(CMD_CTX);
2336
2337 /* list all available registers for the current target */
2338 if (CMD_ARGC == 0) {
2339 struct reg_cache *cache = target->reg_cache;
2340
2341 count = 0;
2342 while (cache) {
2343 unsigned i;
2344
2345 command_print(CMD_CTX, "===== %s", cache->name);
2346
2347 for (i = 0, reg = cache->reg_list;
2348 i < cache->num_regs;
2349 i++, reg++, count++) {
2350 /* only print cached values if they are valid */
2351 if (reg->valid) {
2352 value = buf_to_str(reg->value,
2353 reg->size, 16);
2354 command_print(CMD_CTX,
2355 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2356 count, reg->name,
2357 reg->size, value,
2358 reg->dirty
2359 ? " (dirty)"
2360 : "");
2361 free(value);
2362 } else {
2363 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2364 count, reg->name,
2365 reg->size) ;
2366 }
2367 }
2368 cache = cache->next;
2369 }
2370
2371 return ERROR_OK;
2372 }
2373
2374 /* access a single register by its ordinal number */
2375 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
2376 unsigned num;
2377 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2378
2379 struct reg_cache *cache = target->reg_cache;
2380 count = 0;
2381 while (cache) {
2382 unsigned i;
2383 for (i = 0; i < cache->num_regs; i++) {
2384 if (count++ == num) {
2385 reg = &cache->reg_list[i];
2386 break;
2387 }
2388 }
2389 if (reg)
2390 break;
2391 cache = cache->next;
2392 }
2393
2394 if (!reg) {
2395 command_print(CMD_CTX, "%i is out of bounds, the current target "
2396 "has only %i registers (0 - %i)", num, count, count - 1);
2397 return ERROR_OK;
2398 }
2399 } else {
2400 /* access a single register by its name */
2401 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2402
2403 if (!reg) {
2404 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2405 return ERROR_OK;
2406 }
2407 }
2408
2409 assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
2410
2411 /* display a register */
2412 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
2413 && (CMD_ARGV[1][0] <= '9')))) {
2414 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2415 reg->valid = 0;
2416
2417 if (reg->valid == 0)
2418 reg->type->get(reg);
2419 value = buf_to_str(reg->value, reg->size, 16);
2420 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2421 free(value);
2422 return ERROR_OK;
2423 }
2424
2425 /* set register value */
2426 if (CMD_ARGC == 2) {
2427 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2428 if (buf == NULL)
2429 return ERROR_FAIL;
2430 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2431
2432 reg->type->set(reg, buf);
2433
2434 value = buf_to_str(reg->value, reg->size, 16);
2435 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2436 free(value);
2437
2438 free(buf);
2439
2440 return ERROR_OK;
2441 }
2442
2443 return ERROR_COMMAND_SYNTAX_ERROR;
2444 }
2445
2446 COMMAND_HANDLER(handle_poll_command)
2447 {
2448 int retval = ERROR_OK;
2449 struct target *target = get_current_target(CMD_CTX);
2450
2451 if (CMD_ARGC == 0) {
2452 command_print(CMD_CTX, "background polling: %s",
2453 jtag_poll_get_enabled() ? "on" : "off");
2454 command_print(CMD_CTX, "TAP: %s (%s)",
2455 target->tap->dotted_name,
2456 target->tap->enabled ? "enabled" : "disabled");
2457 if (!target->tap->enabled)
2458 return ERROR_OK;
2459 retval = target_poll(target);
2460 if (retval != ERROR_OK)
2461 return retval;
2462 retval = target_arch_state(target);
2463 if (retval != ERROR_OK)
2464 return retval;
2465 } else if (CMD_ARGC == 1) {
2466 bool enable;
2467 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2468 jtag_poll_set_enabled(enable);
2469 } else
2470 return ERROR_COMMAND_SYNTAX_ERROR;
2471
2472 return retval;
2473 }
2474
2475 COMMAND_HANDLER(handle_wait_halt_command)
2476 {
2477 if (CMD_ARGC > 1)
2478 return ERROR_COMMAND_SYNTAX_ERROR;
2479
2480 unsigned ms = DEFAULT_HALT_TIMEOUT;
2481 if (1 == CMD_ARGC) {
2482 int retval = parse_uint(CMD_ARGV[0], &ms);
2483 if (ERROR_OK != retval)
2484 return ERROR_COMMAND_SYNTAX_ERROR;
2485 }
2486
2487 struct target *target = get_current_target(CMD_CTX);
2488 return target_wait_state(target, TARGET_HALTED, ms);
2489 }
2490
2491 /* wait for target state to change. The trick here is to have a low
2492 * latency for short waits and not to suck up all the CPU time
2493 * on longer waits.
2494 *
2495 * After 500ms, keep_alive() is invoked
2496 */
2497 int target_wait_state(struct target *target, enum target_state state, int ms)
2498 {
2499 int retval;
2500 long long then = 0, cur;
2501 int once = 1;
2502
2503 for (;;) {
2504 retval = target_poll(target);
2505 if (retval != ERROR_OK)
2506 return retval;
2507 if (target->state == state)
2508 break;
2509 cur = timeval_ms();
2510 if (once) {
2511 once = 0;
2512 then = timeval_ms();
2513 LOG_DEBUG("waiting for target %s...",
2514 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2515 }
2516
2517 if (cur-then > 500)
2518 keep_alive();
2519
2520 if ((cur-then) > ms) {
2521 LOG_ERROR("timed out while waiting for target %s",
2522 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2523 return ERROR_FAIL;
2524 }
2525 }
2526
2527 return ERROR_OK;
2528 }
2529
2530 COMMAND_HANDLER(handle_halt_command)
2531 {
2532 LOG_DEBUG("-");
2533
2534 struct target *target = get_current_target(CMD_CTX);
2535 int retval = target_halt(target);
2536 if (ERROR_OK != retval)
2537 return retval;
2538
2539 if (CMD_ARGC == 1) {
2540 unsigned wait_local;
2541 retval = parse_uint(CMD_ARGV[0], &wait_local);
2542 if (ERROR_OK != retval)
2543 return ERROR_COMMAND_SYNTAX_ERROR;
2544 if (!wait_local)
2545 return ERROR_OK;
2546 }
2547
2548 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2549 }
2550
2551 COMMAND_HANDLER(handle_soft_reset_halt_command)
2552 {
2553 struct target *target = get_current_target(CMD_CTX);
2554
2555 LOG_USER("requesting target halt and executing a soft reset");
2556
2557 target_soft_reset_halt(target);
2558
2559 return ERROR_OK;
2560 }
2561
2562 COMMAND_HANDLER(handle_reset_command)
2563 {
2564 if (CMD_ARGC > 1)
2565 return ERROR_COMMAND_SYNTAX_ERROR;
2566
2567 enum target_reset_mode reset_mode = RESET_RUN;
2568 if (CMD_ARGC == 1) {
2569 const Jim_Nvp *n;
2570 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2571 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
2572 return ERROR_COMMAND_SYNTAX_ERROR;
2573 reset_mode = n->value;
2574 }
2575
2576 /* reset *all* targets */
2577 return target_process_reset(CMD_CTX, reset_mode);
2578 }
2579
2580
2581 COMMAND_HANDLER(handle_resume_command)
2582 {
2583 int current = 1;
2584 if (CMD_ARGC > 1)
2585 return ERROR_COMMAND_SYNTAX_ERROR;
2586
2587 struct target *target = get_current_target(CMD_CTX);
2588
2589 /* with no CMD_ARGV, resume from current pc, addr = 0,
2590 * with one arguments, addr = CMD_ARGV[0],
2591 * handle breakpoints, not debugging */
2592 uint32_t addr = 0;
2593 if (CMD_ARGC == 1) {
2594 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2595 current = 0;
2596 }
2597
2598 return target_resume(target, current, addr, 1, 0);
2599 }
2600
2601 COMMAND_HANDLER(handle_step_command)
2602 {
2603 if (CMD_ARGC > 1)
2604 return ERROR_COMMAND_SYNTAX_ERROR;
2605
2606 LOG_DEBUG("-");
2607
2608 /* with no CMD_ARGV, step from current pc, addr = 0,
2609 * with one argument addr = CMD_ARGV[0],
2610 * handle breakpoints, debugging */
2611 uint32_t addr = 0;
2612 int current_pc = 1;
2613 if (CMD_ARGC == 1) {
2614 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2615 current_pc = 0;
2616 }
2617
2618 struct target *target = get_current_target(CMD_CTX);
2619
2620 return target->type->step(target, current_pc, addr, 1);
2621 }
2622
2623 static void handle_md_output(struct command_context *cmd_ctx,
2624 struct target *target, uint32_t address, unsigned size,
2625 unsigned count, const uint8_t *buffer)
2626 {
2627 const unsigned line_bytecnt = 32;
2628 unsigned line_modulo = line_bytecnt / size;
2629
2630 char output[line_bytecnt * 4 + 1];
2631 unsigned output_len = 0;
2632
2633 const char *value_fmt;
2634 switch (size) {
2635 case 4:
2636 value_fmt = "%8.8x ";
2637 break;
2638 case 2:
2639 value_fmt = "%4.4x ";
2640 break;
2641 case 1:
2642 value_fmt = "%2.2x ";
2643 break;
2644 default:
2645 /* "can't happen", caller checked */
2646 LOG_ERROR("invalid memory read size: %u", size);
2647 return;
2648 }
2649
2650 for (unsigned i = 0; i < count; i++) {
2651 if (i % line_modulo == 0) {
2652 output_len += snprintf(output + output_len,
2653 sizeof(output) - output_len,
2654 "0x%8.8x: ",
2655 (unsigned)(address + (i*size)));
2656 }
2657
2658 uint32_t value = 0;
2659 const uint8_t *value_ptr = buffer + i * size;
2660 switch (size) {
2661 case 4:
2662 value = target_buffer_get_u32(target, value_ptr);
2663 break;
2664 case 2:
2665 value = target_buffer_get_u16(target, value_ptr);
2666 break;
2667 case 1:
2668 value = *value_ptr;
2669 }
2670 output_len += snprintf(output + output_len,
2671 sizeof(output) - output_len,
2672 value_fmt, value);
2673
2674 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
2675 command_print(cmd_ctx, "%s", output);
2676 output_len = 0;
2677 }
2678 }
2679 }
2680
2681 COMMAND_HANDLER(handle_md_command)
2682 {
2683 if (CMD_ARGC < 1)
2684 return ERROR_COMMAND_SYNTAX_ERROR;
2685
2686 unsigned size = 0;
2687 switch (CMD_NAME[2]) {
2688 case 'w':
2689 size = 4;
2690 break;
2691 case 'h':
2692 size = 2;
2693 break;
2694 case 'b':
2695 size = 1;
2696 break;
2697 default:
2698 return ERROR_COMMAND_SYNTAX_ERROR;
2699 }
2700
2701 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2702 int (*fn)(struct target *target,
2703 uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2704 if (physical) {
2705 CMD_ARGC--;
2706 CMD_ARGV++;
2707 fn = target_read_phys_memory;
2708 } else
2709 fn = target_read_memory;
2710 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2711 return ERROR_COMMAND_SYNTAX_ERROR;
2712
2713 uint32_t address;
2714 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2715
2716 unsigned count = 1;
2717 if (CMD_ARGC == 2)
2718 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2719
2720 uint8_t *buffer = calloc(count, size);
2721
2722 struct target *target = get_current_target(CMD_CTX);
2723 int retval = fn(target, address, size, count, buffer);
2724 if (ERROR_OK == retval)
2725 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2726
2727 free(buffer);
2728
2729 return retval;
2730 }
2731
2732 typedef int (*target_write_fn)(struct target *target,
2733 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
2734
2735 static int target_write_memory_fast(struct target *target,
2736 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
2737 {
2738 return target_write_buffer(target, address, size * count, buffer);
2739 }
2740
2741 static int target_fill_mem(struct target *target,
2742 uint32_t address,
2743 target_write_fn fn,
2744 unsigned data_size,
2745 /* value */
2746 uint32_t b,
2747 /* count */
2748 unsigned c)
2749 {
2750 /* We have to write in reasonably large chunks to be able
2751 * to fill large memory areas with any sane speed */
2752 const unsigned chunk_size = 16384;
2753 uint8_t *target_buf = malloc(chunk_size * data_size);
2754 if (target_buf == NULL) {
2755 LOG_ERROR("Out of memory");
2756 return ERROR_FAIL;
2757 }
2758
2759 for (unsigned i = 0; i < chunk_size; i++) {
2760 switch (data_size) {
2761 case 4:
2762 target_buffer_set_u32(target, target_buf + i * data_size, b);
2763 break;
2764 case 2:
2765 target_buffer_set_u16(target, target_buf + i * data_size, b);
2766 break;
2767 case 1:
2768 target_buffer_set_u8(target, target_buf + i * data_size, b);
2769 break;
2770 default:
2771 exit(-1);
2772 }
2773 }
2774
2775 int retval = ERROR_OK;
2776
2777 for (unsigned x = 0; x < c; x += chunk_size) {
2778 unsigned current;
2779 current = c - x;
2780 if (current > chunk_size)
2781 current = chunk_size;
2782 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2783 if (retval != ERROR_OK)
2784 break;
2785 /* avoid GDB timeouts */
2786 keep_alive();
2787 }
2788 free(target_buf);
2789
2790 return retval;
2791 }
2792
2793
2794 COMMAND_HANDLER(handle_mw_command)
2795 {
2796 if (CMD_ARGC < 2)
2797 return ERROR_COMMAND_SYNTAX_ERROR;
2798 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2799 target_write_fn fn;
2800 if (physical) {
2801 CMD_ARGC--;
2802 CMD_ARGV++;
2803 fn = target_write_phys_memory;
2804 } else
2805 fn = target_write_memory_fast;
2806 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2807 return ERROR_COMMAND_SYNTAX_ERROR;
2808
2809 uint32_t address;
2810 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2811
2812 uint32_t value;
2813 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2814
2815 unsigned count = 1;
2816 if (CMD_ARGC == 3)
2817 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2818
2819 struct target *target = get_current_target(CMD_CTX);
2820 unsigned wordsize;
2821 switch (CMD_NAME[2]) {
2822 case 'w':
2823 wordsize = 4;
2824 break;
2825 case 'h':
2826 wordsize = 2;
2827 break;
2828 case 'b':
2829 wordsize = 1;
2830 break;
2831 default:
2832 return ERROR_COMMAND_SYNTAX_ERROR;
2833 }
2834
2835 return target_fill_mem(target, address, fn, wordsize, value, count);
2836 }
2837
2838 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2839 uint32_t *min_address, uint32_t *max_address)
2840 {
2841 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2842 return ERROR_COMMAND_SYNTAX_ERROR;
2843
2844 /* a base address isn't always necessary,
2845 * default to 0x0 (i.e. don't relocate) */
2846 if (CMD_ARGC >= 2) {
2847 uint32_t addr;
2848 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2849 image->base_address = addr;
2850 image->base_address_set = 1;
2851 } else
2852 image->base_address_set = 0;
2853
2854 image->start_address_set = 0;
2855
2856 if (CMD_ARGC >= 4)
2857 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2858 if (CMD_ARGC == 5) {
2859 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2860 /* use size (given) to find max (required) */
2861 *max_address += *min_address;
2862 }
2863
2864 if (*min_address > *max_address)
2865 return ERROR_COMMAND_SYNTAX_ERROR;
2866
2867 return ERROR_OK;
2868 }
2869
2870 COMMAND_HANDLER(handle_load_image_command)
2871 {
2872 uint8_t *buffer;
2873 size_t buf_cnt;
2874 uint32_t image_size;
2875 uint32_t min_address = 0;
2876 uint32_t max_address = 0xffffffff;
2877 int i;
2878 struct image image;
2879
2880 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2881 &image, &min_address, &max_address);
2882 if (ERROR_OK != retval)
2883 return retval;
2884
2885 struct target *target = get_current_target(CMD_CTX);
2886
2887 struct duration bench;
2888 duration_start(&bench);
2889
2890 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2891 return ERROR_OK;
2892
2893 image_size = 0x0;
2894 retval = ERROR_OK;
2895 for (i = 0; i < image.num_sections; i++) {
2896 buffer = malloc(image.sections[i].size);
2897 if (buffer == NULL) {
2898 command_print(CMD_CTX,
2899 "error allocating buffer for section (%d bytes)",
2900 (int)(image.sections[i].size));
2901 break;
2902 }
2903
2904 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
2905 if (retval != ERROR_OK) {
2906 free(buffer);
2907 break;
2908 }
2909
2910 uint32_t offset = 0;
2911 uint32_t length = buf_cnt;
2912
2913 /* DANGER!!! beware of unsigned comparision here!!! */
2914
2915 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
2916 (image.sections[i].base_address < max_address)) {
2917
2918 if (image.sections[i].base_address < min_address) {
2919 /* clip addresses below */
2920 offset += min_address-image.sections[i].base_address;
2921 length -= offset;
2922 }
2923
2924 if (image.sections[i].base_address + buf_cnt > max_address)
2925 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2926
2927 retval = target_write_buffer(target,
2928 image.sections[i].base_address + offset, length, buffer + offset);
2929 if (retval != ERROR_OK) {
2930 free(buffer);
2931 break;
2932 }
2933 image_size += length;
2934 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2935 (unsigned int)length,
2936 image.sections[i].base_address + offset);
2937 }
2938
2939 free(buffer);
2940 }
2941
2942 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
2943 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2944 "in %fs (%0.3f KiB/s)", image_size,
2945 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2946 }
2947
2948 image_close(&image);
2949
2950 return retval;
2951
2952 }
2953
2954 COMMAND_HANDLER(handle_dump_image_command)
2955 {
2956 struct fileio fileio;
2957 uint8_t *buffer;
2958 int retval, retvaltemp;
2959 uint32_t address, size;
2960 struct duration bench;
2961 struct target *target = get_current_target(CMD_CTX);
2962
2963 if (CMD_ARGC != 3)
2964 return ERROR_COMMAND_SYNTAX_ERROR;
2965
2966 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2967 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2968
2969 uint32_t buf_size = (size > 4096) ? 4096 : size;
2970 buffer = malloc(buf_size);
2971 if (!buffer)
2972 return ERROR_FAIL;
2973
2974 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
2975 if (retval != ERROR_OK) {
2976 free(buffer);
2977 return retval;
2978 }
2979
2980 duration_start(&bench);
2981
2982 while (size > 0) {
2983 size_t size_written;
2984 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
2985 retval = target_read_buffer(target, address, this_run_size, buffer);
2986 if (retval != ERROR_OK)
2987 break;
2988
2989 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2990 if (retval != ERROR_OK)
2991 break;
2992
2993 size -= this_run_size;
2994 address += this_run_size;
2995 }
2996
2997 free(buffer);
2998
2999 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3000 int filesize;
3001 retval = fileio_size(&fileio, &filesize);
3002 if (retval != ERROR_OK)
3003 return retval;
3004 command_print(CMD_CTX,
3005 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
3006 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3007 }
3008
3009 retvaltemp = fileio_close(&fileio);
3010 if (retvaltemp != ERROR_OK)
3011 return retvaltemp;
3012
3013 return retval;
3014 }
3015
3016 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
3017 {
3018 uint8_t *buffer;
3019 size_t buf_cnt;
3020 uint32_t image_size;
3021 int i;
3022 int retval;
3023 uint32_t checksum = 0;
3024 uint32_t mem_checksum = 0;
3025
3026 struct image image;
3027
3028 struct target *target = get_current_target(CMD_CTX);
3029
3030 if (CMD_ARGC < 1)
3031 return ERROR_COMMAND_SYNTAX_ERROR;
3032
3033 if (!target) {
3034 LOG_ERROR("no target selected");
3035 return ERROR_FAIL;
3036 }
3037
3038 struct duration bench;
3039 duration_start(&bench);
3040
3041 if (CMD_ARGC >= 2) {
3042 uint32_t addr;
3043 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
3044 image.base_address = addr;
3045 image.base_address_set = 1;
3046 } else {
3047 image.base_address_set = 0;
3048 image.base_address = 0x0;
3049 }
3050
3051 image.start_address_set = 0;
3052
3053 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3054 if (retval != ERROR_OK)
3055 return retval;
3056
3057 image_size = 0x0;
3058 int diffs = 0;
3059 retval = ERROR_OK;
3060 for (i = 0; i < image.num_sections; i++) {
3061 buffer = malloc(image.sections[i].size);
3062 if (buffer == NULL) {
3063 command_print(CMD_CTX,
3064 "error allocating buffer for section (%d bytes)",
3065 (int)(image.sections[i].size));
3066 break;
3067 }
3068 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3069 if (retval != ERROR_OK) {
3070 free(buffer);
3071 break;
3072 }
3073
3074 if (verify) {
3075 /* calculate checksum of image */
3076 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3077 if (retval != ERROR_OK) {
3078 free(buffer);
3079 break;
3080 }
3081
3082 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3083 if (retval != ERROR_OK) {
3084 free(buffer);
3085 break;
3086 }
3087
3088 if (checksum != mem_checksum) {
3089 /* failed crc checksum, fall back to a binary compare */
3090 uint8_t *data;
3091
3092 if (diffs == 0)
3093 LOG_ERROR("checksum mismatch - attempting binary compare");
3094
3095 data = (uint8_t *)malloc(buf_cnt);
3096
3097 /* Can we use 32bit word accesses? */
3098 int size = 1;
3099 int count = buf_cnt;
3100 if ((count % 4) == 0) {
3101 size *= 4;
3102 count /= 4;
3103 }
3104 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
3105 if (retval == ERROR_OK) {
3106 uint32_t t;
3107 for (t = 0; t < buf_cnt; t++) {
3108 if (data[t] != buffer[t]) {
3109 command_print(CMD_CTX,
3110 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3111 diffs,
3112 (unsigned)(t + image.sections[i].base_address),
3113 data[t],
3114 buffer[t]);
3115 if (diffs++ >= 127) {
3116 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
3117 free(data);
3118 free(buffer);
3119 goto done;
3120 }
3121 }
3122 keep_alive();
3123 }
3124 }
3125 free(data);
3126 }
3127 } else {
3128 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
3129 image.sections[i].base_address,
3130 buf_cnt);
3131 }
3132
3133 free(buffer);
3134 image_size += buf_cnt;
3135 }
3136 if (diffs > 0)
3137 command_print(CMD_CTX, "No more differences found.");
3138 done:
3139 if (diffs > 0)
3140 retval = ERROR_FAIL;
3141 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3142 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
3143 "in %fs (%0.3f KiB/s)", image_size,
3144 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3145 }
3146
3147 image_close(&image);
3148
3149 return retval;
3150 }
3151
3152 COMMAND_HANDLER(handle_verify_image_command)
3153 {
3154 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
3155 }
3156
3157 COMMAND_HANDLER(handle_test_image_command)
3158 {
3159 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
3160 }
3161
3162 static int handle_bp_command_list(struct command_context *cmd_ctx)
3163 {
3164 struct target *target = get_current_target(cmd_ctx);
3165 struct breakpoint *breakpoint = target->breakpoints;
3166 while (breakpoint) {
3167 if (breakpoint->type == BKPT_SOFT) {
3168 char *buf = buf_to_str(breakpoint->orig_instr,
3169 breakpoint->length, 16);
3170 command_print(cmd_ctx, "IVA breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
3171 breakpoint->address,
3172 breakpoint->length,
3173 breakpoint->set, buf);
3174 free(buf);
3175 } else {
3176 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3177 command_print(cmd_ctx, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3178 breakpoint->asid,
3179 breakpoint->length, breakpoint->set);
3180 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3181 command_print(cmd_ctx, "Hybrid breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3182 breakpoint->address,
3183 breakpoint->length, breakpoint->set);
3184 command_print(cmd_ctx, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3185 breakpoint->asid);
3186 } else
3187 command_print(cmd_ctx, "Breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3188 breakpoint->address,
3189 breakpoint->length, breakpoint->set);
3190 }
3191
3192 breakpoint = breakpoint->next;
3193 }
3194 return ERROR_OK;
3195 }
3196
3197 static int handle_bp_command_set(struct command_context *cmd_ctx,
3198 uint32_t addr, uint32_t asid, uint32_t length, int hw)
3199 {
3200 struct target *target = get_current_target(cmd_ctx);
3201
3202 if (asid == 0) {
3203 int retval = breakpoint_add(target, addr, length, hw);
3204 if (ERROR_OK == retval)
3205 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
3206 else {
3207 LOG_ERROR("Failure setting breakpoint, the same address(IVA) is already used");
3208 return retval;
3209 }
3210 } else if (addr == 0) {
3211 int retval = context_breakpoint_add(target, asid, length, hw);
3212 if (ERROR_OK == retval)
3213 command_print(cmd_ctx, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3214 else {
3215 LOG_ERROR("Failure setting breakpoint, the same address(CONTEXTID) is already used");
3216 return retval;
3217 }
3218 } else {
3219 int retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3220 if (ERROR_OK == retval)
3221 command_print(cmd_ctx, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3222 else {
3223 LOG_ERROR("Failure setting breakpoint, the same address is already used");
3224 return retval;
3225 }
3226 }
3227 return ERROR_OK;
3228 }
3229
3230 COMMAND_HANDLER(handle_bp_command)
3231 {
3232 uint32_t addr;
3233 uint32_t asid;
3234 uint32_t length;
3235 int hw = BKPT_SOFT;
3236
3237 switch (CMD_ARGC) {
3238 case 0:
3239 return handle_bp_command_list(CMD_CTX);
3240
3241 case 2:
3242 asid = 0;
3243 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3244 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3245 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3246
3247 case 3:
3248 if (strcmp(CMD_ARGV[2], "hw") == 0) {
3249 hw = BKPT_HARD;
3250 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3251
3252 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3253
3254 asid = 0;
3255 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3256 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
3257 hw = BKPT_HARD;
3258 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
3259 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3260 addr = 0;
3261 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3262 }
3263
3264 case 4:
3265 hw = BKPT_HARD;
3266 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3267 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
3268 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
3269 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3270
3271 default:
3272 return ERROR_COMMAND_SYNTAX_ERROR;
3273 }
3274 }
3275
3276 COMMAND_HANDLER(handle_rbp_command)
3277 {
3278 if (CMD_ARGC != 1)
3279 return ERROR_COMMAND_SYNTAX_ERROR;
3280
3281 uint32_t addr;
3282 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3283
3284 struct target *target = get_current_target(CMD_CTX);
3285 breakpoint_remove(target, addr);
3286
3287 return ERROR_OK;
3288 }
3289
3290 COMMAND_HANDLER(handle_wp_command)
3291 {
3292 struct target *target = get_current_target(CMD_CTX);
3293
3294 if (CMD_ARGC == 0) {
3295 struct watchpoint *watchpoint = target->watchpoints;
3296
3297 while (watchpoint) {
3298 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
3299 ", len: 0x%8.8" PRIx32
3300 ", r/w/a: %i, value: 0x%8.8" PRIx32
3301 ", mask: 0x%8.8" PRIx32,
3302 watchpoint->address,
3303 watchpoint->length,
3304 (int)watchpoint->rw,
3305 watchpoint->value,
3306 watchpoint->mask);
3307 watchpoint = watchpoint->next;
3308 }
3309 return ERROR_OK;
3310 }
3311
3312 enum watchpoint_rw type = WPT_ACCESS;
3313 uint32_t addr = 0;
3314 uint32_t length = 0;
3315 uint32_t data_value = 0x0;
3316 uint32_t data_mask = 0xffffffff;
3317
3318 switch (CMD_ARGC) {
3319 case 5:
3320 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
3321 /* fall through */
3322 case 4:
3323 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
3324 /* fall through */
3325 case 3:
3326 switch (CMD_ARGV[2][0]) {
3327 case 'r':
3328 type = WPT_READ;
3329 break;
3330 case 'w':
3331 type = WPT_WRITE;
3332 break;
3333 case 'a':
3334 type = WPT_ACCESS;
3335 break;
3336 default:
3337 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3338 return ERROR_COMMAND_SYNTAX_ERROR;
3339 }
3340 /* fall through */
3341 case 2:
3342 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3343 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3344 break;
3345
3346 default:
3347 return ERROR_COMMAND_SYNTAX_ERROR;
3348 }
3349
3350 int retval = watchpoint_add(target, addr, length, type,
3351 data_value, data_mask);
3352 if (ERROR_OK != retval)
3353 LOG_ERROR("Failure setting watchpoints");
3354
3355 return retval;
3356 }
3357
3358 COMMAND_HANDLER(handle_rwp_command)
3359 {
3360 if (CMD_ARGC != 1)
3361 return ERROR_COMMAND_SYNTAX_ERROR;
3362
3363 uint32_t addr;
3364 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3365
3366 struct target *target = get_current_target(CMD_CTX);
3367 watchpoint_remove(target, addr);
3368
3369 return ERROR_OK;
3370 }
3371
3372 /**
3373 * Translate a virtual address to a physical address.
3374 *
3375 * The low-level target implementation must have logged a detailed error
3376 * which is forwarded to telnet/GDB session.
3377 */
3378 COMMAND_HANDLER(handle_virt2phys_command)
3379 {
3380 if (CMD_ARGC != 1)
3381 return ERROR_COMMAND_SYNTAX_ERROR;
3382
3383 uint32_t va;
3384 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3385 uint32_t pa;
3386
3387 struct target *target = get_current_target(CMD_CTX);
3388 int retval = target->type->virt2phys(target, va, &pa);
3389 if (retval == ERROR_OK)
3390 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3391
3392 return retval;
3393 }
3394
3395 static void writeData(FILE *f, const void *data, size_t len)
3396 {
3397 size_t written = fwrite(data, 1, len, f);
3398 if (written != len)
3399 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3400 }
3401
3402 static void writeLong(FILE *f, int l)
3403 {
3404 int i;
3405 for (i = 0; i < 4; i++) {
3406 char c = (l >> (i*8))&0xff;
3407 writeData(f, &c, 1);
3408 }
3409
3410 }
3411
3412 static void writeString(FILE *f, char *s)
3413 {
3414 writeData(f, s, strlen(s));
3415 }
3416
3417 /* Dump a gmon.out histogram file. */
3418 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
3419 {
3420 uint32_t i;
3421 FILE *f = fopen(filename, "w");
3422 if (f == NULL)
3423 return;
3424 writeString(f, "gmon");
3425 writeLong(f, 0x00000001); /* Version */
3426 writeLong(f, 0); /* padding */
3427 writeLong(f, 0); /* padding */
3428 writeLong(f, 0); /* padding */
3429
3430 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3431 writeData(f, &zero, 1);
3432
3433 /* figure out bucket size */
3434 uint32_t min = samples[0];
3435 uint32_t max = samples[0];
3436 for (i = 0; i < sampleNum; i++) {
3437 if (min > samples[i])
3438 min = samples[i];
3439 if (max < samples[i])
3440 max = samples[i];
3441 }
3442
3443 int addressSpace = (max - min + 1);
3444 assert(addressSpace >= 2);
3445
3446 static const uint32_t maxBuckets = 16 * 1024; /* maximum buckets. */
3447 uint32_t length = addressSpace;
3448 if (length > maxBuckets)
3449 length = maxBuckets;
3450 int *buckets = malloc(sizeof(int)*length);
3451 if (buckets == NULL) {
3452 fclose(f);
3453 return;
3454 }
3455 memset(buckets, 0, sizeof(int) * length);
3456 for (i = 0; i < sampleNum; i++) {
3457 uint32_t address = samples[i];
3458 long long a = address - min;
3459 long long b = length - 1;
3460 long long c = addressSpace - 1;
3461 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
3462 buckets[index_t]++;
3463 }
3464
3465 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3466 writeLong(f, min); /* low_pc */
3467 writeLong(f, max); /* high_pc */
3468 writeLong(f, length); /* # of samples */
3469 writeLong(f, 100); /* KLUDGE! We lie, ca. 100Hz best case. */
3470 writeString(f, "seconds");
3471 for (i = 0; i < (15-strlen("seconds")); i++)
3472 writeData(f, &zero, 1);
3473 writeString(f, "s");
3474
3475 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3476
3477 char *data = malloc(2 * length);
3478 if (data != NULL) {
3479 for (i = 0; i < length; i++) {
3480 int val;
3481 val = buckets[i];
3482 if (val > 65535)
3483 val = 65535;
3484 data[i * 2] = val&0xff;
3485 data[i * 2 + 1] = (val >> 8) & 0xff;
3486 }
3487 free(buckets);
3488 writeData(f, data, length * 2);
3489 free(data);
3490 } else
3491 free(buckets);
3492
3493 fclose(f);
3494 }
3495
3496 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3497 * which will be used as a random sampling of PC */
3498 COMMAND_HANDLER(handle_profile_command)
3499 {
3500 struct target *target = get_current_target(CMD_CTX);
3501 struct timeval timeout, now;
3502
3503 gettimeofday(&timeout, NULL);
3504 if (CMD_ARGC != 2)
3505 return ERROR_COMMAND_SYNTAX_ERROR;
3506 unsigned offset;
3507 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3508
3509 timeval_add_time(&timeout, offset, 0);
3510
3511 /**
3512 * @todo: Some cores let us sample the PC without the
3513 * annoying halt/resume step; for example, ARMv7 PCSR.
3514 * Provide a way to use that more efficient mechanism.
3515 */
3516
3517 command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
3518
3519 static const int maxSample = 10000;
3520 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3521 if (samples == NULL)
3522 return ERROR_OK;
3523
3524 int numSamples = 0;
3525 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3526 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3527
3528 int retval = ERROR_OK;
3529 for (;;) {
3530 target_poll(target);
3531 if (target->state == TARGET_HALTED) {
3532 uint32_t t = *((uint32_t *)reg->value);
3533 samples[numSamples++] = t;
3534 /* current pc, addr = 0, do not handle breakpoints, not debugging */
3535 retval = target_resume(target, 1, 0, 0, 0);
3536 target_poll(target);
3537 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3538 } else if (target->state == TARGET_RUNNING) {
3539 /* We want to quickly sample the PC. */
3540 retval = target_halt(target);
3541 if (retval != ERROR_OK) {
3542 free(samples);
3543 return retval;
3544 }
3545 } else {
3546 command_print(CMD_CTX, "Target not halted or running");
3547 retval = ERROR_OK;
3548 break;
3549 }
3550 if (retval != ERROR_OK)
3551 break;
3552
3553 gettimeofday(&now, NULL);
3554 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec)
3555 && (now.tv_usec >= timeout.tv_usec))) {
3556 command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
3557 retval = target_poll(target);
3558 if (retval != ERROR_OK) {
3559 free(samples);
3560 return retval;
3561 }
3562 if (target->state == TARGET_HALTED) {
3563 /* current pc, addr = 0, do not handle
3564 * breakpoints, not debugging */
3565 target_resume(target, 1, 0, 0, 0);
3566 }
3567 retval = target_poll(target);
3568 if (retval != ERROR_OK) {
3569 free(samples);
3570 return retval;
3571 }
3572 writeGmon(samples, numSamples, CMD_ARGV[1]);
3573 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3574 break;
3575 }
3576 }
3577 free(samples);
3578
3579 return retval;
3580 }
3581
3582 static int new_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t val)
3583 {
3584 char *namebuf;
3585 Jim_Obj *nameObjPtr, *valObjPtr;
3586 int result;
3587
3588 namebuf = alloc_printf("%s(%d)", varname, idx);
3589 if (!namebuf)
3590 return JIM_ERR;
3591
3592 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3593 valObjPtr = Jim_NewIntObj(interp, val);
3594 if (!nameObjPtr || !valObjPtr) {
3595 free(namebuf);
3596 return JIM_ERR;
3597 }
3598
3599 Jim_IncrRefCount(nameObjPtr);
3600 Jim_IncrRefCount(valObjPtr);
3601 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3602 Jim_DecrRefCount(interp, nameObjPtr);
3603 Jim_DecrRefCount(interp, valObjPtr);
3604 free(namebuf);
3605 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3606 return result;
3607 }
3608
3609 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3610 {
3611 struct command_context *context;
3612 struct target *target;
3613
3614 context = current_command_context(interp);
3615 assert(context != NULL);
3616
3617 target = get_current_target(context);
3618 if (target == NULL) {
3619 LOG_ERROR("mem2array: no current target");
3620 return JIM_ERR;
3621 }
3622
3623 return target_mem2array(interp, target, argc - 1, argv + 1);
3624 }
3625
3626 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3627 {
3628 long l;
3629 uint32_t width;
3630 int len;
3631 uint32_t addr;
3632 uint32_t count;
3633 uint32_t v;
3634 const char *varname;
3635 int n, e, retval;
3636 uint32_t i;
3637
3638 /* argv[1] = name of array to receive the data
3639 * argv[2] = desired width
3640 * argv[3] = memory address
3641 * argv[4] = count of times to read
3642 */
3643 if (argc != 4) {
3644 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3645 return JIM_ERR;
3646 }
3647 varname = Jim_GetString(argv[0], &len);
3648 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3649
3650 e = Jim_GetLong(interp, argv[1], &l);