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