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