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