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