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