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