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