ced09e900966f36d2042868cdafcc47fd4e30b00
[fw/openocd] / src / target / target.c
1 /***************************************************************************
2  *   Copyright (C) 2005 by Dominic Rath                                    *
3  *   Dominic.Rath@gmx.de                                                   *
4  *                                                                         *
5  *   Copyright (C) 2007-2009 Ã˜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  *   This program is free software; you can redistribute it and/or modify  *
18  *   it under the terms of the GNU General Public License as published by  *
19  *   the Free Software Foundation; either version 2 of the License, or     *
20  *   (at your option) any later version.                                   *
21  *                                                                         *
22  *   This program is distributed in the hope that it will be useful,       *
23  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
24  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
25  *   GNU General Public License for more details.                          *
26  *                                                                         *
27  *   You should have received a copy of the GNU General Public License     *
28  *   along with this program; if not, write to the                         *
29  *   Free Software Foundation, Inc.,                                       *
30  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
31  ***************************************************************************/
32 #ifdef HAVE_CONFIG_H
33 #include "config.h"
34 #endif
35
36 #include "target.h"
37 #include "target_type.h"
38 #include "target_request.h"
39 #include "time_support.h"
40 #include "register.h"
41 #include "trace.h"
42 #include "image.h"
43 #include "jtag.h"
44
45
46 static int handle_targets_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
47
48 static int handle_reg_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
49 static int handle_poll_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
50 static int handle_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
51 static int handle_wait_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
52 static int handle_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
53 static int handle_soft_reset_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
54 static int handle_resume_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
55 static int handle_step_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
56 static int handle_md_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
57 static int handle_mw_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
58 static int handle_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
59 static int handle_dump_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
60 static int handle_verify_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
61 static int handle_test_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
62 static int handle_bp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
63 static int handle_rbp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
64 static int handle_wp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
65 static int handle_rwp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
66 static int handle_virt2phys_command(command_context_t *cmd_ctx, char *cmd, char **args, int argc);
67 static int handle_profile_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
68 static int handle_fast_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
69 static int handle_fast_load_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
70
71 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
72 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
73 static int jim_target(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
74
75 static int target_array2mem(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv);
76 static int target_mem2array(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv);
77
78 /* targets */
79 extern target_type_t arm7tdmi_target;
80 extern target_type_t arm720t_target;
81 extern target_type_t arm9tdmi_target;
82 extern target_type_t arm920t_target;
83 extern target_type_t arm966e_target;
84 extern target_type_t arm926ejs_target;
85 extern target_type_t fa526_target;
86 extern target_type_t feroceon_target;
87 extern target_type_t dragonite_target;
88 extern target_type_t xscale_target;
89 extern target_type_t cortexm3_target;
90 extern target_type_t cortexa8_target;
91 extern target_type_t arm11_target;
92 extern target_type_t mips_m4k_target;
93 extern target_type_t avr_target;
94
95 target_type_t *target_types[] =
96 {
97         &arm7tdmi_target,
98         &arm9tdmi_target,
99         &arm920t_target,
100         &arm720t_target,
101         &arm966e_target,
102         &arm926ejs_target,
103         &fa526_target,
104         &feroceon_target,
105         &dragonite_target,
106         &xscale_target,
107         &cortexm3_target,
108         &cortexa8_target,
109         &arm11_target,
110         &mips_m4k_target,
111         &avr_target,
112         NULL,
113 };
114
115 target_t *all_targets = NULL;
116 target_event_callback_t *target_event_callbacks = NULL;
117 target_timer_callback_t *target_timer_callbacks = NULL;
118
119 const Jim_Nvp nvp_assert[] = {
120         { .name = "assert", NVP_ASSERT },
121         { .name = "deassert", NVP_DEASSERT },
122         { .name = "T", NVP_ASSERT },
123         { .name = "F", NVP_DEASSERT },
124         { .name = "t", NVP_ASSERT },
125         { .name = "f", NVP_DEASSERT },
126         { .name = NULL, .value = -1 }
127 };
128
129 const Jim_Nvp nvp_error_target[] = {
130         { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
131         { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
132         { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
133         { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
134         { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
135         { .value = ERROR_TARGET_UNALIGNED_ACCESS   , .name = "err-unaligned-access" },
136         { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
137         { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
138         { .value = ERROR_TARGET_TRANSLATION_FAULT  , .name = "err-translation-fault" },
139         { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
140         { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
141         { .value = -1, .name = NULL }
142 };
143
144 const char *target_strerror_safe(int err)
145 {
146         const Jim_Nvp *n;
147
148         n = Jim_Nvp_value2name_simple(nvp_error_target, err);
149         if (n->name == NULL) {
150                 return "unknown";
151         } else {
152                 return n->name;
153         }
154 }
155
156 static const Jim_Nvp nvp_target_event[] = {
157         { .value = TARGET_EVENT_OLD_gdb_program_config , .name = "old-gdb_program_config" },
158         { .value = TARGET_EVENT_OLD_pre_resume         , .name = "old-pre_resume" },
159
160         { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
161         { .value = TARGET_EVENT_HALTED, .name = "halted" },
162         { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
163         { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
164         { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
165
166         { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
167         { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
168
169         /* historical name */
170
171         { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
172
173         { .value = TARGET_EVENT_RESET_ASSERT_PRE,    .name = "reset-assert-pre" },
174         { .value = TARGET_EVENT_RESET_ASSERT_POST,   .name = "reset-assert-post" },
175         { .value = TARGET_EVENT_RESET_DEASSERT_PRE,  .name = "reset-deassert-pre" },
176         { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
177         { .value = TARGET_EVENT_RESET_HALT_PRE,      .name = "reset-halt-pre" },
178         { .value = TARGET_EVENT_RESET_HALT_POST,     .name = "reset-halt-post" },
179         { .value = TARGET_EVENT_RESET_WAIT_PRE,      .name = "reset-wait-pre" },
180         { .value = TARGET_EVENT_RESET_WAIT_POST,     .name = "reset-wait-post" },
181         { .value = TARGET_EVENT_RESET_INIT , .name = "reset-init" },
182         { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
183
184         { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
185         { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
186
187         { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
188         { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
189
190         { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
191         { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
192
193         { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
194         { .value = TARGET_EVENT_GDB_FLASH_WRITE_END  , .name = "gdb-flash-write-end"   },
195
196         { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
197         { .value = TARGET_EVENT_GDB_FLASH_ERASE_END  , .name = "gdb-flash-erase-end" },
198
199         { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
200         { .value = TARGET_EVENT_RESUMED     , .name = "resume-ok" },
201         { .value = TARGET_EVENT_RESUME_END  , .name = "resume-end" },
202
203         { .name = NULL, .value = -1 }
204 };
205
206 const Jim_Nvp nvp_target_state[] = {
207         { .name = "unknown", .value = TARGET_UNKNOWN },
208         { .name = "running", .value = TARGET_RUNNING },
209         { .name = "halted",  .value = TARGET_HALTED },
210         { .name = "reset",   .value = TARGET_RESET },
211         { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
212         { .name = NULL, .value = -1 },
213 };
214
215 const Jim_Nvp nvp_target_debug_reason [] = {
216         { .name = "debug-request"            , .value = DBG_REASON_DBGRQ },
217         { .name = "breakpoint"               , .value = DBG_REASON_BREAKPOINT },
218         { .name = "watchpoint"               , .value = DBG_REASON_WATCHPOINT },
219         { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
220         { .name = "single-step"              , .value = DBG_REASON_SINGLESTEP },
221         { .name = "target-not-halted"        , .value = DBG_REASON_NOTHALTED  },
222         { .name = "undefined"                , .value = DBG_REASON_UNDEFINED },
223         { .name = NULL, .value = -1 },
224 };
225
226 const Jim_Nvp nvp_target_endian[] = {
227         { .name = "big",    .value = TARGET_BIG_ENDIAN },
228         { .name = "little", .value = TARGET_LITTLE_ENDIAN },
229         { .name = "be",     .value = TARGET_BIG_ENDIAN },
230         { .name = "le",     .value = TARGET_LITTLE_ENDIAN },
231         { .name = NULL,     .value = -1 },
232 };
233
234 const Jim_Nvp nvp_reset_modes[] = {
235         { .name = "unknown", .value = RESET_UNKNOWN },
236         { .name = "run"    , .value = RESET_RUN },
237         { .name = "halt"   , .value = RESET_HALT },
238         { .name = "init"   , .value = RESET_INIT },
239         { .name = NULL     , .value = -1 },
240 };
241
242 const char *
243 target_state_name( target_t *t )
244 {
245         const char *cp;
246         cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
247         if( !cp ){
248                 LOG_ERROR("Invalid target state: %d", (int)(t->state));
249                 cp = "(*BUG*unknown*BUG*)";
250         }
251         return cp;
252 }
253
254 /* determine the number of the new target */
255 static int new_target_number(void)
256 {
257         target_t *t;
258         int x;
259
260         /* number is 0 based */
261         x = -1;
262         t = all_targets;
263         while (t) {
264                 if (x < t->target_number) {
265                         x = t->target_number;
266                 }
267                 t = t->next;
268         }
269         return x + 1;
270 }
271
272 /* read a uint32_t from a buffer in target memory endianness */
273 uint32_t target_buffer_get_u32(target_t *target, const uint8_t *buffer)
274 {
275         if (target->endianness == TARGET_LITTLE_ENDIAN)
276                 return le_to_h_u32(buffer);
277         else
278                 return be_to_h_u32(buffer);
279 }
280
281 /* read a uint16_t from a buffer in target memory endianness */
282 uint16_t target_buffer_get_u16(target_t *target, const uint8_t *buffer)
283 {
284         if (target->endianness == TARGET_LITTLE_ENDIAN)
285                 return le_to_h_u16(buffer);
286         else
287                 return be_to_h_u16(buffer);
288 }
289
290 /* read a uint8_t from a buffer in target memory endianness */
291 uint8_t target_buffer_get_u8(target_t *target, const uint8_t *buffer)
292 {
293         return *buffer & 0x0ff;
294 }
295
296 /* write a uint32_t to a buffer in target memory endianness */
297 void target_buffer_set_u32(target_t *target, uint8_t *buffer, uint32_t value)
298 {
299         if (target->endianness == TARGET_LITTLE_ENDIAN)
300                 h_u32_to_le(buffer, value);
301         else
302                 h_u32_to_be(buffer, value);
303 }
304
305 /* write a uint16_t to a buffer in target memory endianness */
306 void target_buffer_set_u16(target_t *target, uint8_t *buffer, uint16_t value)
307 {
308         if (target->endianness == TARGET_LITTLE_ENDIAN)
309                 h_u16_to_le(buffer, value);
310         else
311                 h_u16_to_be(buffer, value);
312 }
313
314 /* write a uint8_t to a buffer in target memory endianness */
315 void target_buffer_set_u8(target_t *target, uint8_t *buffer, uint8_t value)
316 {
317         *buffer = value;
318 }
319
320 /* return a pointer to a configured target; id is name or number */
321 target_t *get_target(const char *id)
322 {
323         target_t *target;
324
325         /* try as tcltarget name */
326         for (target = all_targets; target; target = target->next) {
327                 if (target->cmd_name == NULL)
328                         continue;
329                 if (strcmp(id, target->cmd_name) == 0)
330                         return target;
331         }
332
333         /* It's OK to remove this fallback sometime after August 2010 or so */
334
335         /* no match, try as number */
336         unsigned num;
337         if (parse_uint(id, &num) != ERROR_OK)
338                 return NULL;
339
340         for (target = all_targets; target; target = target->next) {
341                 if (target->target_number == (int)num) {
342                         LOG_WARNING("use '%s' as target identifier, not '%u'",
343                                         target->cmd_name, num);
344                         return target;
345                 }
346         }
347
348         return NULL;
349 }
350
351 /* returns a pointer to the n-th configured target */
352 static target_t *get_target_by_num(int num)
353 {
354         target_t *target = all_targets;
355
356         while (target) {
357                 if (target->target_number == num) {
358                         return target;
359                 }
360                 target = target->next;
361         }
362
363         return NULL;
364 }
365
366 target_t* get_current_target(command_context_t *cmd_ctx)
367 {
368         target_t *target = get_target_by_num(cmd_ctx->current_target);
369
370         if (target == NULL)
371         {
372                 LOG_ERROR("BUG: current_target out of bounds");
373                 exit(-1);
374         }
375
376         return target;
377 }
378
379 int target_poll(struct target_s *target)
380 {
381         /* We can't poll until after examine */
382         if (!target_was_examined(target))
383         {
384                 /* Fail silently lest we pollute the log */
385                 return ERROR_FAIL;
386         }
387         return target->type->poll(target);
388 }
389
390 int target_halt(struct target_s *target)
391 {
392         /* We can't poll until after examine */
393         if (!target_was_examined(target))
394         {
395                 LOG_ERROR("Target not examined yet");
396                 return ERROR_FAIL;
397         }
398         return target->type->halt(target);
399 }
400
401 int target_resume(struct target_s *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
402 {
403         int retval;
404
405         /* We can't poll until after examine */
406         if (!target_was_examined(target))
407         {
408                 LOG_ERROR("Target not examined yet");
409                 return ERROR_FAIL;
410         }
411
412         /* note that resume *must* be asynchronous. The CPU can halt before we poll. The CPU can
413          * even halt at the current PC as a result of a software breakpoint being inserted by (a bug?)
414          * the application.
415          */
416         if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
417                 return retval;
418
419         return retval;
420 }
421
422 int target_process_reset(struct command_context_s *cmd_ctx, enum target_reset_mode reset_mode)
423 {
424         char buf[100];
425         int retval;
426         Jim_Nvp *n;
427         n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
428         if (n->name == NULL) {
429                 LOG_ERROR("invalid reset mode");
430                 return ERROR_FAIL;
431         }
432
433         /* disable polling during reset to make reset event scripts
434          * more predictable, i.e. dr/irscan & pathmove in events will
435          * not have JTAG operations injected into the middle of a sequence.
436          */
437         bool save_poll = jtag_poll_get_enabled();
438
439         jtag_poll_set_enabled(false);
440
441         sprintf(buf, "ocd_process_reset %s", n->name);
442         retval = Jim_Eval(interp, buf);
443
444         jtag_poll_set_enabled(save_poll);
445
446         if (retval != JIM_OK) {
447                 Jim_PrintErrorMessage(interp);
448                 return ERROR_FAIL;
449         }
450
451         /* We want any events to be processed before the prompt */
452         retval = target_call_timer_callbacks_now();
453
454         return retval;
455 }
456
457 static int default_virt2phys(struct target_s *target, uint32_t virtual, uint32_t *physical)
458 {
459         *physical = virtual;
460         return ERROR_OK;
461 }
462
463 static int default_mmu(struct target_s *target, int *enabled)
464 {
465         *enabled = 0;
466         return ERROR_OK;
467 }
468
469 static int default_examine(struct target_s *target)
470 {
471         target_set_examined(target);
472         return ERROR_OK;
473 }
474
475 int target_examine_one(struct target_s *target)
476 {
477         return target->type->examine(target);
478 }
479
480 static int jtag_enable_callback(enum jtag_event event, void *priv)
481 {
482         target_t *target = priv;
483
484         if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
485                 return ERROR_OK;
486
487         jtag_unregister_event_callback(jtag_enable_callback, target);
488         return target_examine_one(target);
489 }
490
491
492 /* Targets that correctly implement init + examine, i.e.
493  * no communication with target during init:
494  *
495  * XScale
496  */
497 int target_examine(void)
498 {
499         int retval = ERROR_OK;
500         target_t *target;
501
502         for (target = all_targets; target; target = target->next)
503         {
504                 /* defer examination, but don't skip it */
505                 if (!target->tap->enabled) {
506                         jtag_register_event_callback(jtag_enable_callback,
507                                         target);
508                         continue;
509                 }
510                 if ((retval = target_examine_one(target)) != ERROR_OK)
511                         return retval;
512         }
513         return retval;
514 }
515 const char *target_get_name(struct target_s *target)
516 {
517         return target->type->name;
518 }
519
520 static int target_write_memory_imp(struct target_s *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
521 {
522         if (!target_was_examined(target))
523         {
524                 LOG_ERROR("Target not examined yet");
525                 return ERROR_FAIL;
526         }
527         return target->type->write_memory_imp(target, address, size, count, buffer);
528 }
529
530 static int target_read_memory_imp(struct target_s *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
531 {
532         if (!target_was_examined(target))
533         {
534                 LOG_ERROR("Target not examined yet");
535                 return ERROR_FAIL;
536         }
537         return target->type->read_memory_imp(target, address, size, count, buffer);
538 }
539
540 static int target_soft_reset_halt_imp(struct target_s *target)
541 {
542         if (!target_was_examined(target))
543         {
544                 LOG_ERROR("Target not examined yet");
545                 return ERROR_FAIL;
546         }
547         if (!target->type->soft_reset_halt_imp) {
548                 LOG_ERROR("Target %s does not support soft_reset_halt",
549                                 target->cmd_name);
550                 return ERROR_FAIL;
551         }
552         return target->type->soft_reset_halt_imp(target);
553 }
554
555 static int target_run_algorithm_imp(struct target_s *target, int num_mem_params, mem_param_t *mem_params, int num_reg_params, reg_param_t *reg_param, uint32_t entry_point, uint32_t exit_point, int timeout_ms, void *arch_info)
556 {
557         if (!target_was_examined(target))
558         {
559                 LOG_ERROR("Target not examined yet");
560                 return ERROR_FAIL;
561         }
562         return target->type->run_algorithm_imp(target, num_mem_params, mem_params, num_reg_params, reg_param, entry_point, exit_point, timeout_ms, arch_info);
563 }
564
565 int target_read_memory(struct target_s *target,
566                 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
567 {
568         return target->type->read_memory(target, address, size, count, buffer);
569 }
570
571 int target_write_memory(struct target_s *target,
572                 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
573 {
574         return target->type->write_memory(target, address, size, count, buffer);
575 }
576 int target_bulk_write_memory(struct target_s *target,
577                 uint32_t address, uint32_t count, uint8_t *buffer)
578 {
579         return target->type->bulk_write_memory(target, address, count, buffer);
580 }
581
582 int target_add_breakpoint(struct target_s *target,
583                 struct breakpoint_s *breakpoint)
584 {
585         return target->type->add_breakpoint(target, breakpoint);
586 }
587 int target_remove_breakpoint(struct target_s *target,
588                 struct breakpoint_s *breakpoint)
589 {
590         return target->type->remove_breakpoint(target, breakpoint);
591 }
592
593 int target_add_watchpoint(struct target_s *target,
594                 struct watchpoint_s *watchpoint)
595 {
596         return target->type->add_watchpoint(target, watchpoint);
597 }
598 int target_remove_watchpoint(struct target_s *target,
599                 struct watchpoint_s *watchpoint)
600 {
601         return target->type->remove_watchpoint(target, watchpoint);
602 }
603
604 int target_get_gdb_reg_list(struct target_s *target,
605                 struct reg_s **reg_list[], int *reg_list_size)
606 {
607         return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
608 }
609 int target_step(struct target_s *target,
610                 int current, uint32_t address, int handle_breakpoints)
611 {
612         return target->type->step(target, current, address, handle_breakpoints);
613 }
614
615
616 int target_run_algorithm(struct target_s *target,
617                 int num_mem_params, mem_param_t *mem_params,
618                 int num_reg_params, reg_param_t *reg_param,
619                 uint32_t entry_point, uint32_t exit_point,
620                 int timeout_ms, void *arch_info)
621 {
622         return target->type->run_algorithm(target,
623                         num_mem_params, mem_params, num_reg_params, reg_param,
624                         entry_point, exit_point, timeout_ms, arch_info);
625 }
626
627 /// @returns @c true if the target has been examined.
628 bool target_was_examined(struct target_s *target)
629 {
630         return target->type->examined;
631 }
632 /// Sets the @c examined flag for the given target.
633 void target_set_examined(struct target_s *target)
634 {
635         target->type->examined = true;
636 }
637 // Reset the @c examined flag for the given target.
638 void target_reset_examined(struct target_s *target)
639 {
640         target->type->examined = false;
641 }
642
643
644 int target_init(struct command_context_s *cmd_ctx)
645 {
646         target_t *target = all_targets;
647         int retval;
648
649         while (target)
650         {
651                 target_reset_examined(target);
652                 if (target->type->examine == NULL)
653                 {
654                         target->type->examine = default_examine;
655                 }
656
657                 if ((retval = target->type->init_target(cmd_ctx, target)) != ERROR_OK)
658                 {
659                         LOG_ERROR("target '%s' init failed", target_get_name(target));
660                         return retval;
661                 }
662
663                 /* Set up default functions if none are provided by target */
664                 if (target->type->virt2phys == NULL)
665                 {
666                         target->type->virt2phys = default_virt2phys;
667                 }
668                 target->type->virt2phys = default_virt2phys;
669                 /* a non-invasive way(in terms of patches) to add some code that
670                  * runs before the type->write/read_memory implementation
671                  */
672                 target->type->write_memory_imp = target->type->write_memory;
673                 target->type->write_memory = target_write_memory_imp;
674                 target->type->read_memory_imp = target->type->read_memory;
675                 target->type->read_memory = target_read_memory_imp;
676                 target->type->soft_reset_halt_imp = target->type->soft_reset_halt;
677                 target->type->soft_reset_halt = target_soft_reset_halt_imp;
678                 target->type->run_algorithm_imp = target->type->run_algorithm;
679                 target->type->run_algorithm = target_run_algorithm_imp;
680
681                 if (target->type->mmu == NULL)
682                 {
683                         target->type->mmu = default_mmu;
684                 }
685                 target = target->next;
686         }
687
688         if (all_targets)
689         {
690                 if ((retval = target_register_user_commands(cmd_ctx)) != ERROR_OK)
691                         return retval;
692                 if ((retval = target_register_timer_callback(handle_target, 100, 1, NULL)) != ERROR_OK)
693                         return retval;
694         }
695
696         return ERROR_OK;
697 }
698
699 int target_register_event_callback(int (*callback)(struct target_s *target, enum target_event event, void *priv), void *priv)
700 {
701         target_event_callback_t **callbacks_p = &target_event_callbacks;
702
703         if (callback == NULL)
704         {
705                 return ERROR_INVALID_ARGUMENTS;
706         }
707
708         if (*callbacks_p)
709         {
710                 while ((*callbacks_p)->next)
711                         callbacks_p = &((*callbacks_p)->next);
712                 callbacks_p = &((*callbacks_p)->next);
713         }
714
715         (*callbacks_p) = malloc(sizeof(target_event_callback_t));
716         (*callbacks_p)->callback = callback;
717         (*callbacks_p)->priv = priv;
718         (*callbacks_p)->next = NULL;
719
720         return ERROR_OK;
721 }
722
723 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
724 {
725         target_timer_callback_t **callbacks_p = &target_timer_callbacks;
726         struct timeval now;
727
728         if (callback == NULL)
729         {
730                 return ERROR_INVALID_ARGUMENTS;
731         }
732
733         if (*callbacks_p)
734         {
735                 while ((*callbacks_p)->next)
736                         callbacks_p = &((*callbacks_p)->next);
737                 callbacks_p = &((*callbacks_p)->next);
738         }
739
740         (*callbacks_p) = malloc(sizeof(target_timer_callback_t));
741         (*callbacks_p)->callback = callback;
742         (*callbacks_p)->periodic = periodic;
743         (*callbacks_p)->time_ms = time_ms;
744
745         gettimeofday(&now, NULL);
746         (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
747         time_ms -= (time_ms % 1000);
748         (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
749         if ((*callbacks_p)->when.tv_usec > 1000000)
750         {
751                 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
752                 (*callbacks_p)->when.tv_sec += 1;
753         }
754
755         (*callbacks_p)->priv = priv;
756         (*callbacks_p)->next = NULL;
757
758         return ERROR_OK;
759 }
760
761 int target_unregister_event_callback(int (*callback)(struct target_s *target, enum target_event event, void *priv), void *priv)
762 {
763         target_event_callback_t **p = &target_event_callbacks;
764         target_event_callback_t *c = target_event_callbacks;
765
766         if (callback == NULL)
767         {
768                 return ERROR_INVALID_ARGUMENTS;
769         }
770
771         while (c)
772         {
773                 target_event_callback_t *next = c->next;
774                 if ((c->callback == callback) && (c->priv == priv))
775                 {
776                         *p = next;
777                         free(c);
778                         return ERROR_OK;
779                 }
780                 else
781                         p = &(c->next);
782                 c = next;
783         }
784
785         return ERROR_OK;
786 }
787
788 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
789 {
790         target_timer_callback_t **p = &target_timer_callbacks;
791         target_timer_callback_t *c = target_timer_callbacks;
792
793         if (callback == NULL)
794         {
795                 return ERROR_INVALID_ARGUMENTS;
796         }
797
798         while (c)
799         {
800                 target_timer_callback_t *next = c->next;
801                 if ((c->callback == callback) && (c->priv == priv))
802                 {
803                         *p = next;
804                         free(c);
805                         return ERROR_OK;
806                 }
807                 else
808                         p = &(c->next);
809                 c = next;
810         }
811
812         return ERROR_OK;
813 }
814
815 int target_call_event_callbacks(target_t *target, enum target_event event)
816 {
817         target_event_callback_t *callback = target_event_callbacks;
818         target_event_callback_t *next_callback;
819
820         if (event == TARGET_EVENT_HALTED)
821         {
822                 /* execute early halted first */
823                 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
824         }
825
826         LOG_DEBUG("target event %i (%s)",
827                           event,
828                           Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
829
830         target_handle_event(target, event);
831
832         while (callback)
833         {
834                 next_callback = callback->next;
835                 callback->callback(target, event, callback->priv);
836                 callback = next_callback;
837         }
838
839         return ERROR_OK;
840 }
841
842 static int target_timer_callback_periodic_restart(
843                 target_timer_callback_t *cb, struct timeval *now)
844 {
845         int time_ms = cb->time_ms;
846         cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
847         time_ms -= (time_ms % 1000);
848         cb->when.tv_sec = now->tv_sec + time_ms / 1000;
849         if (cb->when.tv_usec > 1000000)
850         {
851                 cb->when.tv_usec = cb->when.tv_usec - 1000000;
852                 cb->when.tv_sec += 1;
853         }
854         return ERROR_OK;
855 }
856
857 static int target_call_timer_callback(target_timer_callback_t *cb,
858                 struct timeval *now)
859 {
860         cb->callback(cb->priv);
861
862         if (cb->periodic)
863                 return target_timer_callback_periodic_restart(cb, now);
864
865         return target_unregister_timer_callback(cb->callback, cb->priv);
866 }
867
868 static int target_call_timer_callbacks_check_time(int checktime)
869 {
870         keep_alive();
871
872         struct timeval now;
873         gettimeofday(&now, NULL);
874
875         target_timer_callback_t *callback = target_timer_callbacks;
876         while (callback)
877         {
878                 // cleaning up may unregister and free this callback
879                 target_timer_callback_t *next_callback = callback->next;
880
881                 bool call_it = callback->callback &&
882                         ((!checktime && callback->periodic) ||
883                           now.tv_sec > callback->when.tv_sec ||
884                          (now.tv_sec == callback->when.tv_sec &&
885                           now.tv_usec >= callback->when.tv_usec));
886
887                 if (call_it)
888                 {
889                         int retval = target_call_timer_callback(callback, &now);
890                         if (retval != ERROR_OK)
891                                 return retval;
892                 }
893
894                 callback = next_callback;
895         }
896
897         return ERROR_OK;
898 }
899
900 int target_call_timer_callbacks(void)
901 {
902         return target_call_timer_callbacks_check_time(1);
903 }
904
905 /* invoke periodic callbacks immediately */
906 int target_call_timer_callbacks_now(void)
907 {
908         return target_call_timer_callbacks_check_time(0);
909 }
910
911 int target_alloc_working_area(struct target_s *target, uint32_t size, working_area_t **area)
912 {
913         working_area_t *c = target->working_areas;
914         working_area_t *new_wa = NULL;
915
916         /* Reevaluate working area address based on MMU state*/
917         if (target->working_areas == NULL)
918         {
919                 int retval;
920                 int enabled;
921                 retval = target->type->mmu(target, &enabled);
922                 if (retval != ERROR_OK)
923                 {
924                         return retval;
925                 }
926                 if (enabled)
927                 {
928                         target->working_area = target->working_area_virt;
929                 }
930                 else
931                 {
932                         target->working_area = target->working_area_phys;
933                 }
934         }
935
936         /* only allocate multiples of 4 byte */
937         if (size % 4)
938         {
939                 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
940                 size = (size + 3) & (~3);
941         }
942
943         /* see if there's already a matching working area */
944         while (c)
945         {
946                 if ((c->free) && (c->size == size))
947                 {
948                         new_wa = c;
949                         break;
950                 }
951                 c = c->next;
952         }
953
954         /* if not, allocate a new one */
955         if (!new_wa)
956         {
957                 working_area_t **p = &target->working_areas;
958                 uint32_t first_free = target->working_area;
959                 uint32_t free_size = target->working_area_size;
960
961                 LOG_DEBUG("allocating new working area");
962
963                 c = target->working_areas;
964                 while (c)
965                 {
966                         first_free += c->size;
967                         free_size -= c->size;
968                         p = &c->next;
969                         c = c->next;
970                 }
971
972                 if (free_size < size)
973                 {
974                         LOG_WARNING("not enough working area available(requested %u, free %u)",
975                                     (unsigned)(size), (unsigned)(free_size));
976                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
977                 }
978
979                 new_wa = malloc(sizeof(working_area_t));
980                 new_wa->next = NULL;
981                 new_wa->size = size;
982                 new_wa->address = first_free;
983
984                 if (target->backup_working_area)
985                 {
986                         int retval;
987                         new_wa->backup = malloc(new_wa->size);
988                         if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
989                         {
990                                 free(new_wa->backup);
991                                 free(new_wa);
992                                 return retval;
993                         }
994                 }
995                 else
996                 {
997                         new_wa->backup = NULL;
998                 }
999
1000                 /* put new entry in list */
1001                 *p = new_wa;
1002         }
1003
1004         /* mark as used, and return the new (reused) area */
1005         new_wa->free = 0;
1006         *area = new_wa;
1007
1008         /* user pointer */
1009         new_wa->user = area;
1010
1011         return ERROR_OK;
1012 }
1013
1014 int target_free_working_area_restore(struct target_s *target, working_area_t *area, int restore)
1015 {
1016         if (area->free)
1017                 return ERROR_OK;
1018
1019         if (restore && target->backup_working_area)
1020         {
1021                 int retval;
1022                 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1023                         return retval;
1024         }
1025
1026         area->free = 1;
1027
1028         /* mark user pointer invalid */
1029         *area->user = NULL;
1030         area->user = NULL;
1031
1032         return ERROR_OK;
1033 }
1034
1035 int target_free_working_area(struct target_s *target, working_area_t *area)
1036 {
1037         return target_free_working_area_restore(target, area, 1);
1038 }
1039
1040 /* free resources and restore memory, if restoring memory fails,
1041  * free up resources anyway
1042  */
1043 void target_free_all_working_areas_restore(struct target_s *target, int restore)
1044 {
1045         working_area_t *c = target->working_areas;
1046
1047         while (c)
1048         {
1049                 working_area_t *next = c->next;
1050                 target_free_working_area_restore(target, c, restore);
1051
1052                 if (c->backup)
1053                         free(c->backup);
1054
1055                 free(c);
1056
1057                 c = next;
1058         }
1059
1060         target->working_areas = NULL;
1061 }
1062
1063 void target_free_all_working_areas(struct target_s *target)
1064 {
1065         target_free_all_working_areas_restore(target, 1);
1066 }
1067
1068 int target_register_commands(struct command_context_s *cmd_ctx)
1069 {
1070
1071         register_command(cmd_ctx, NULL, "targets", handle_targets_command, COMMAND_EXEC, "change the current command line target (one parameter) or lists targets (with no parameter)");
1072
1073
1074
1075
1076         register_jim(cmd_ctx, "target", jim_target, "configure target");
1077
1078         return ERROR_OK;
1079 }
1080
1081 int target_arch_state(struct target_s *target)
1082 {
1083         int retval;
1084         if (target == NULL)
1085         {
1086                 LOG_USER("No target has been configured");
1087                 return ERROR_OK;
1088         }
1089
1090         LOG_USER("target state: %s", target_state_name( target ));
1091
1092         if (target->state != TARGET_HALTED)
1093                 return ERROR_OK;
1094
1095         retval = target->type->arch_state(target);
1096         return retval;
1097 }
1098
1099 /* Single aligned words are guaranteed to use 16 or 32 bit access
1100  * mode respectively, otherwise data is handled as quickly as
1101  * possible
1102  */
1103 int target_write_buffer(struct target_s *target, uint32_t address, uint32_t size, uint8_t *buffer)
1104 {
1105         int retval;
1106         LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1107                   (int)size, (unsigned)address);
1108
1109         if (!target_was_examined(target))
1110         {
1111                 LOG_ERROR("Target not examined yet");
1112                 return ERROR_FAIL;
1113         }
1114
1115         if (size == 0) {
1116                 return ERROR_OK;
1117         }
1118
1119         if ((address + size - 1) < address)
1120         {
1121                 /* GDB can request this when e.g. PC is 0xfffffffc*/
1122                 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1123                                   (unsigned)address,
1124                                   (unsigned)size);
1125                 return ERROR_FAIL;
1126         }
1127
1128         if (((address % 2) == 0) && (size == 2))
1129         {
1130                 return target_write_memory(target, address, 2, 1, buffer);
1131         }
1132
1133         /* handle unaligned head bytes */
1134         if (address % 4)
1135         {
1136                 uint32_t unaligned = 4 - (address % 4);
1137
1138                 if (unaligned > size)
1139                         unaligned = size;
1140
1141                 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1142                         return retval;
1143
1144                 buffer += unaligned;
1145                 address += unaligned;
1146                 size -= unaligned;
1147         }
1148
1149         /* handle aligned words */
1150         if (size >= 4)
1151         {
1152                 int aligned = size - (size % 4);
1153
1154                 /* use bulk writes above a certain limit. This may have to be changed */
1155                 if (aligned > 128)
1156                 {
1157                         if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1158                                 return retval;
1159                 }
1160                 else
1161                 {
1162                         if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1163                                 return retval;
1164                 }
1165
1166                 buffer += aligned;
1167                 address += aligned;
1168                 size -= aligned;
1169         }
1170
1171         /* handle tail writes of less than 4 bytes */
1172         if (size > 0)
1173         {
1174                 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1175                         return retval;
1176         }
1177
1178         return ERROR_OK;
1179 }
1180
1181 /* Single aligned words are guaranteed to use 16 or 32 bit access
1182  * mode respectively, otherwise data is handled as quickly as
1183  * possible
1184  */
1185 int target_read_buffer(struct target_s *target, uint32_t address, uint32_t size, uint8_t *buffer)
1186 {
1187         int retval;
1188         LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1189                           (int)size, (unsigned)address);
1190
1191         if (!target_was_examined(target))
1192         {
1193                 LOG_ERROR("Target not examined yet");
1194                 return ERROR_FAIL;
1195         }
1196
1197         if (size == 0) {
1198                 return ERROR_OK;
1199         }
1200
1201         if ((address + size - 1) < address)
1202         {
1203                 /* GDB can request this when e.g. PC is 0xfffffffc*/
1204                 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1205                                   address,
1206                                   size);
1207                 return ERROR_FAIL;
1208         }
1209
1210         if (((address % 2) == 0) && (size == 2))
1211         {
1212                 return target_read_memory(target, address, 2, 1, buffer);
1213         }
1214
1215         /* handle unaligned head bytes */
1216         if (address % 4)
1217         {
1218                 uint32_t unaligned = 4 - (address % 4);
1219
1220                 if (unaligned > size)
1221                         unaligned = size;
1222
1223                 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1224                         return retval;
1225
1226                 buffer += unaligned;
1227                 address += unaligned;
1228                 size -= unaligned;
1229         }
1230
1231         /* handle aligned words */
1232         if (size >= 4)
1233         {
1234                 int aligned = size - (size % 4);
1235
1236                 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1237                         return retval;
1238
1239                 buffer += aligned;
1240                 address += aligned;
1241                 size -= aligned;
1242         }
1243
1244         /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1245         if(size >=2)
1246         {
1247                 int aligned = size - (size%2);
1248                 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1249                 if (retval != ERROR_OK)
1250                         return retval;
1251
1252                 buffer += aligned;
1253                 address += aligned;
1254                 size -= aligned;
1255         }
1256         /* handle tail writes of less than 4 bytes */
1257         if (size > 0)
1258         {
1259                 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1260                         return retval;
1261         }
1262
1263         return ERROR_OK;
1264 }
1265
1266 int target_checksum_memory(struct target_s *target, uint32_t address, uint32_t size, uint32_t* crc)
1267 {
1268         uint8_t *buffer;
1269         int retval;
1270         uint32_t i;
1271         uint32_t checksum = 0;
1272         if (!target_was_examined(target))
1273         {
1274                 LOG_ERROR("Target not examined yet");
1275                 return ERROR_FAIL;
1276         }
1277
1278         if ((retval = target->type->checksum_memory(target, address,
1279                 size, &checksum)) != ERROR_OK)
1280         {
1281                 buffer = malloc(size);
1282                 if (buffer == NULL)
1283                 {
1284                         LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1285                         return ERROR_INVALID_ARGUMENTS;
1286                 }
1287                 retval = target_read_buffer(target, address, size, buffer);
1288                 if (retval != ERROR_OK)
1289                 {
1290                         free(buffer);
1291                         return retval;
1292                 }
1293
1294                 /* convert to target endianess */
1295                 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1296                 {
1297                         uint32_t target_data;
1298                         target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1299                         target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1300                 }
1301
1302                 retval = image_calculate_checksum(buffer, size, &checksum);
1303                 free(buffer);
1304         }
1305
1306         *crc = checksum;
1307
1308         return retval;
1309 }
1310
1311 int target_blank_check_memory(struct target_s *target, uint32_t address, uint32_t size, uint32_t* blank)
1312 {
1313         int retval;
1314         if (!target_was_examined(target))
1315         {
1316                 LOG_ERROR("Target not examined yet");
1317                 return ERROR_FAIL;
1318         }
1319
1320         if (target->type->blank_check_memory == 0)
1321                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1322
1323         retval = target->type->blank_check_memory(target, address, size, blank);
1324
1325         return retval;
1326 }
1327
1328 int target_read_u32(struct target_s *target, uint32_t address, uint32_t *value)
1329 {
1330         uint8_t value_buf[4];
1331         if (!target_was_examined(target))
1332         {
1333                 LOG_ERROR("Target not examined yet");
1334                 return ERROR_FAIL;
1335         }
1336
1337         int retval = target_read_memory(target, address, 4, 1, value_buf);
1338
1339         if (retval == ERROR_OK)
1340         {
1341                 *value = target_buffer_get_u32(target, value_buf);
1342                 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1343                                   address,
1344                                   *value);
1345         }
1346         else
1347         {
1348                 *value = 0x0;
1349                 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1350                                   address);
1351         }
1352
1353         return retval;
1354 }
1355
1356 int target_read_u16(struct target_s *target, uint32_t address, uint16_t *value)
1357 {
1358         uint8_t value_buf[2];
1359         if (!target_was_examined(target))
1360         {
1361                 LOG_ERROR("Target not examined yet");
1362                 return ERROR_FAIL;
1363         }
1364
1365         int retval = target_read_memory(target, address, 2, 1, value_buf);
1366
1367         if (retval == ERROR_OK)
1368         {
1369                 *value = target_buffer_get_u16(target, value_buf);
1370                 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1371                                   address,
1372                                   *value);
1373         }
1374         else
1375         {
1376                 *value = 0x0;
1377                 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1378                                   address);
1379         }
1380
1381         return retval;
1382 }
1383
1384 int target_read_u8(struct target_s *target, uint32_t address, uint8_t *value)
1385 {
1386         int retval = target_read_memory(target, address, 1, 1, value);
1387         if (!target_was_examined(target))
1388         {
1389                 LOG_ERROR("Target not examined yet");
1390                 return ERROR_FAIL;
1391         }
1392
1393         if (retval == ERROR_OK)
1394         {
1395                 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1396                                   address,
1397                                   *value);
1398         }
1399         else
1400         {
1401                 *value = 0x0;
1402                 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1403                                   address);
1404         }
1405
1406         return retval;
1407 }
1408
1409 int target_write_u32(struct target_s *target, uint32_t address, uint32_t value)
1410 {
1411         int retval;
1412         uint8_t value_buf[4];
1413         if (!target_was_examined(target))
1414         {
1415                 LOG_ERROR("Target not examined yet");
1416                 return ERROR_FAIL;
1417         }
1418
1419         LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1420                           address,
1421                           value);
1422
1423         target_buffer_set_u32(target, value_buf, value);
1424         if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1425         {
1426                 LOG_DEBUG("failed: %i", retval);
1427         }
1428
1429         return retval;
1430 }
1431
1432 int target_write_u16(struct target_s *target, uint32_t address, uint16_t value)
1433 {
1434         int retval;
1435         uint8_t value_buf[2];
1436         if (!target_was_examined(target))
1437         {
1438                 LOG_ERROR("Target not examined yet");
1439                 return ERROR_FAIL;
1440         }
1441
1442         LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1443                           address,
1444                           value);
1445
1446         target_buffer_set_u16(target, value_buf, value);
1447         if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1448         {
1449                 LOG_DEBUG("failed: %i", retval);
1450         }
1451
1452         return retval;
1453 }
1454
1455 int target_write_u8(struct target_s *target, uint32_t address, uint8_t value)
1456 {
1457         int retval;
1458         if (!target_was_examined(target))
1459         {
1460                 LOG_ERROR("Target not examined yet");
1461                 return ERROR_FAIL;
1462         }
1463
1464         LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1465                           address, value);
1466
1467         if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1468         {
1469                 LOG_DEBUG("failed: %i", retval);
1470         }
1471
1472         return retval;
1473 }
1474
1475 int target_register_user_commands(struct command_context_s *cmd_ctx)
1476 {
1477         int retval = ERROR_OK;
1478
1479
1480         /* script procedures */
1481         register_command(cmd_ctx, NULL, "profile", handle_profile_command, COMMAND_EXEC, "profiling samples the CPU PC");
1482         register_jim(cmd_ctx, "ocd_mem2array", jim_mem2array, "read memory and return as a TCL array for script processing <ARRAYNAME> <WIDTH = 32/16/8> <ADDRESS> <COUNT>");
1483         register_jim(cmd_ctx, "ocd_array2mem", jim_array2mem, "convert a TCL array to memory locations and write the values  <ARRAYNAME> <WIDTH = 32/16/8> <ADDRESS> <COUNT>");
1484
1485         register_command(cmd_ctx, NULL, "fast_load_image", handle_fast_load_image_command, COMMAND_ANY,
1486                         "same args as load_image, image stored in memory - mainly for profiling purposes");
1487
1488         register_command(cmd_ctx, NULL, "fast_load", handle_fast_load_command, COMMAND_ANY,
1489                         "loads active fast load image to current target - mainly for profiling purposes");
1490
1491
1492         register_command(cmd_ctx, NULL, "virt2phys", handle_virt2phys_command, COMMAND_ANY, "translate a virtual address into a physical address");
1493         register_command(cmd_ctx,  NULL, "reg", handle_reg_command, COMMAND_EXEC, "display or set a register");
1494         register_command(cmd_ctx,  NULL, "poll", handle_poll_command, COMMAND_EXEC, "poll target state");
1495         register_command(cmd_ctx,  NULL, "wait_halt", handle_wait_halt_command, COMMAND_EXEC, "wait for target halt [time (s)]");
1496         register_command(cmd_ctx,  NULL, "halt", handle_halt_command, COMMAND_EXEC, "halt target");
1497         register_command(cmd_ctx,  NULL, "resume", handle_resume_command, COMMAND_EXEC, "resume target [addr]");
1498         register_command(cmd_ctx,  NULL, "step", handle_step_command, COMMAND_EXEC, "step one instruction from current PC or [addr]");
1499         register_command(cmd_ctx,  NULL, "reset", handle_reset_command, COMMAND_EXEC, "reset target [run | halt | init] - default is run");
1500         register_command(cmd_ctx,  NULL, "soft_reset_halt", handle_soft_reset_halt_command, COMMAND_EXEC, "halt the target and do a soft reset");
1501
1502         register_command(cmd_ctx,  NULL, "mdw", handle_md_command, COMMAND_EXEC, "display memory words <addr> [count]");
1503         register_command(cmd_ctx,  NULL, "mdh", handle_md_command, COMMAND_EXEC, "display memory half-words <addr> [count]");
1504         register_command(cmd_ctx,  NULL, "mdb", handle_md_command, COMMAND_EXEC, "display memory bytes <addr> [count]");
1505
1506         register_command(cmd_ctx,  NULL, "mww", handle_mw_command, COMMAND_EXEC, "write memory word <addr> <value> [count]");
1507         register_command(cmd_ctx,  NULL, "mwh", handle_mw_command, COMMAND_EXEC, "write memory half-word <addr> <value> [count]");
1508         register_command(cmd_ctx,  NULL, "mwb", handle_mw_command, COMMAND_EXEC, "write memory byte <addr> <value> [count]");
1509
1510         register_command(cmd_ctx,  NULL, "bp",
1511                         handle_bp_command, COMMAND_EXEC,
1512                         "list or set breakpoint [<address> <length> [hw]]");
1513         register_command(cmd_ctx,  NULL, "rbp",
1514                         handle_rbp_command, COMMAND_EXEC,
1515                         "remove breakpoint <address>");
1516         register_command(cmd_ctx,  NULL, "wp",
1517                         handle_wp_command, COMMAND_EXEC,
1518                         "list or set watchpoint "
1519                                 "[<address> <length> <r/w/a> [value] [mask]]");
1520         register_command(cmd_ctx,  NULL, "rwp",
1521                         handle_rwp_command, COMMAND_EXEC,
1522                         "remove watchpoint <address>");
1523
1524         register_command(cmd_ctx,  NULL, "load_image", handle_load_image_command, COMMAND_EXEC, "load_image <file> <address> ['bin'|'ihex'|'elf'|'s19'] [min_address] [max_length]");
1525         register_command(cmd_ctx,  NULL, "dump_image", handle_dump_image_command, COMMAND_EXEC, "dump_image <file> <address> <size>");
1526         register_command(cmd_ctx,  NULL, "verify_image", handle_verify_image_command, COMMAND_EXEC, "verify_image <file> [offset] [type]");
1527         register_command(cmd_ctx,  NULL, "test_image", handle_test_image_command, COMMAND_EXEC, "test_image <file> [offset] [type]");
1528
1529         if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
1530                 return retval;
1531         if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
1532                 return retval;
1533
1534         return retval;
1535 }
1536
1537 static int handle_targets_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1538 {
1539         target_t *target = all_targets;
1540
1541         if (argc == 1)
1542         {
1543                 target = get_target(args[0]);
1544                 if (target == NULL) {
1545                         command_print(cmd_ctx,"Target: %s is unknown, try one of:\n", args[0]);
1546                         goto DumpTargets;
1547                 }
1548                 if (!target->tap->enabled) {
1549                         command_print(cmd_ctx,"Target: TAP %s is disabled, "
1550                                         "can't be the current target\n",
1551                                         target->tap->dotted_name);
1552                         return ERROR_FAIL;
1553                 }
1554
1555                 cmd_ctx->current_target = target->target_number;
1556                 return ERROR_OK;
1557         }
1558 DumpTargets:
1559
1560         target = all_targets;
1561         command_print(cmd_ctx, "    TargetName         Type       Endian TapName            State       ");
1562         command_print(cmd_ctx, "--  ------------------ ---------- ------ ------------------ ------------");
1563         while (target)
1564         {
1565                 const char *state;
1566                 char marker = ' ';
1567
1568                 if (target->tap->enabled)
1569                         state = target_state_name( target );
1570                 else
1571                         state = "tap-disabled";
1572
1573                 if (cmd_ctx->current_target == target->target_number)
1574                         marker = '*';
1575
1576                 /* keep columns lined up to match the headers above */
1577                 command_print(cmd_ctx, "%2d%c %-18s %-10s %-6s %-18s %s",
1578                                           target->target_number,
1579                                           marker,
1580                                           target->cmd_name,
1581                                           target_get_name(target),
1582                                           Jim_Nvp_value2name_simple(nvp_target_endian,
1583                                                                 target->endianness)->name,
1584                                           target->tap->dotted_name,
1585                                           state);
1586                 target = target->next;
1587         }
1588
1589         return ERROR_OK;
1590 }
1591
1592 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1593
1594 static int powerDropout;
1595 static int srstAsserted;
1596
1597 static int runPowerRestore;
1598 static int runPowerDropout;
1599 static int runSrstAsserted;
1600 static int runSrstDeasserted;
1601
1602 static int sense_handler(void)
1603 {
1604         static int prevSrstAsserted = 0;
1605         static int prevPowerdropout = 0;
1606
1607         int retval;
1608         if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1609                 return retval;
1610
1611         int powerRestored;
1612         powerRestored = prevPowerdropout && !powerDropout;
1613         if (powerRestored)
1614         {
1615                 runPowerRestore = 1;
1616         }
1617
1618         long long current = timeval_ms();
1619         static long long lastPower = 0;
1620         int waitMore = lastPower + 2000 > current;
1621         if (powerDropout && !waitMore)
1622         {
1623                 runPowerDropout = 1;
1624                 lastPower = current;
1625         }
1626
1627         if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1628                 return retval;
1629
1630         int srstDeasserted;
1631         srstDeasserted = prevSrstAsserted && !srstAsserted;
1632
1633         static long long lastSrst = 0;
1634         waitMore = lastSrst + 2000 > current;
1635         if (srstDeasserted && !waitMore)
1636         {
1637                 runSrstDeasserted = 1;
1638                 lastSrst = current;
1639         }
1640
1641         if (!prevSrstAsserted && srstAsserted)
1642         {
1643                 runSrstAsserted = 1;
1644         }
1645
1646         prevSrstAsserted = srstAsserted;
1647         prevPowerdropout = powerDropout;
1648
1649         if (srstDeasserted || powerRestored)
1650         {
1651                 /* Other than logging the event we can't do anything here.
1652                  * Issuing a reset is a particularly bad idea as we might
1653                  * be inside a reset already.
1654                  */
1655         }
1656
1657         return ERROR_OK;
1658 }
1659
1660 static void target_call_event_callbacks_all(enum target_event e) {
1661         target_t *target;
1662         target = all_targets;
1663         while (target) {
1664                 target_call_event_callbacks(target, e);
1665                 target = target->next;
1666         }
1667 }
1668
1669 /* process target state changes */
1670 int handle_target(void *priv)
1671 {
1672         int retval = ERROR_OK;
1673
1674         /* we do not want to recurse here... */
1675         static int recursive = 0;
1676         if (! recursive)
1677         {
1678                 recursive = 1;
1679                 sense_handler();
1680                 /* danger! running these procedures can trigger srst assertions and power dropouts.
1681                  * We need to avoid an infinite loop/recursion here and we do that by
1682                  * clearing the flags after running these events.
1683                  */
1684                 int did_something = 0;
1685                 if (runSrstAsserted)
1686                 {
1687                         target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1688                         Jim_Eval(interp, "srst_asserted");
1689                         did_something = 1;
1690                 }
1691                 if (runSrstDeasserted)
1692                 {
1693                         Jim_Eval(interp, "srst_deasserted");
1694                         did_something = 1;
1695                 }
1696                 if (runPowerDropout)
1697                 {
1698                         target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1699                         Jim_Eval(interp, "power_dropout");
1700                         did_something = 1;
1701                 }
1702                 if (runPowerRestore)
1703                 {
1704                         Jim_Eval(interp, "power_restore");
1705                         did_something = 1;
1706                 }
1707
1708                 if (did_something)
1709                 {
1710                         /* clear detect flags */
1711                         sense_handler();
1712                 }
1713
1714                 /* clear action flags */
1715
1716                 runSrstAsserted = 0;
1717                 runSrstDeasserted = 0;
1718                 runPowerRestore = 0;
1719                 runPowerDropout = 0;
1720
1721                 recursive = 0;
1722         }
1723
1724         /* Poll targets for state changes unless that's globally disabled.
1725          * Skip targets that are currently disabled.
1726          */
1727         for (target_t *target = all_targets;
1728                         is_jtag_poll_safe() && target;
1729                         target = target->next)
1730         {
1731                 if (!target->tap->enabled)
1732                         continue;
1733
1734                 /* only poll target if we've got power and srst isn't asserted */
1735                 if (!powerDropout && !srstAsserted)
1736                 {
1737                         /* polling may fail silently until the target has been examined */
1738                         if ((retval = target_poll(target)) != ERROR_OK)
1739                         {
1740                                 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1741                                 return retval;
1742                         }
1743                 }
1744         }
1745
1746         return retval;
1747 }
1748
1749 static int handle_reg_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1750 {
1751         target_t *target;
1752         reg_t *reg = NULL;
1753         int count = 0;
1754         char *value;
1755
1756         LOG_DEBUG("-");
1757
1758         target = get_current_target(cmd_ctx);
1759
1760         /* list all available registers for the current target */
1761         if (argc == 0)
1762         {
1763                 reg_cache_t *cache = target->reg_cache;
1764
1765                 count = 0;
1766                 while (cache)
1767                 {
1768                         int i;
1769
1770                         for (i = 0, reg = cache->reg_list;
1771                                         i < cache->num_regs;
1772                                         i++, reg++, count++)
1773                         {
1774                                 /* only print cached values if they are valid */
1775                                 if (reg->valid) {
1776                                         value = buf_to_str(reg->value,
1777                                                         reg->size, 16);
1778                                         command_print(cmd_ctx,
1779                                                         "(%i) %s (/%" PRIu32 "): 0x%s%s",
1780                                                         count, reg->name,
1781                                                         reg->size, value,
1782                                                         reg->dirty
1783                                                                 ? " (dirty)"
1784                                                                 : "");
1785                                         free(value);
1786                                 } else {
1787                                         command_print(cmd_ctx, "(%i) %s (/%" PRIu32 ")",
1788                                                           count, reg->name,
1789                                                           reg->size) ;
1790                                 }
1791                         }
1792                         cache = cache->next;
1793                 }
1794
1795                 return ERROR_OK;
1796         }
1797
1798         /* access a single register by its ordinal number */
1799         if ((args[0][0] >= '0') && (args[0][0] <= '9'))
1800         {
1801                 unsigned num;
1802                 int retval = parse_uint(args[0], &num);
1803                 if (ERROR_OK != retval)
1804                         return ERROR_COMMAND_SYNTAX_ERROR;
1805
1806                 reg_cache_t *cache = target->reg_cache;
1807                 count = 0;
1808                 while (cache)
1809                 {
1810                         int i;
1811                         for (i = 0; i < cache->num_regs; i++)
1812                         {
1813                                 if (count++ == (int)num)
1814                                 {
1815                                         reg = &cache->reg_list[i];
1816                                         break;
1817                                 }
1818                         }
1819                         if (reg)
1820                                 break;
1821                         cache = cache->next;
1822                 }
1823
1824                 if (!reg)
1825                 {
1826                         command_print(cmd_ctx, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
1827                         return ERROR_OK;
1828                 }
1829         } else /* access a single register by its name */
1830         {
1831                 reg = register_get_by_name(target->reg_cache, args[0], 1);
1832
1833                 if (!reg)
1834                 {
1835                         command_print(cmd_ctx, "register %s not found in current target", args[0]);
1836                         return ERROR_OK;
1837                 }
1838         }
1839
1840         /* display a register */
1841         if ((argc == 1) || ((argc == 2) && !((args[1][0] >= '0') && (args[1][0] <= '9'))))
1842         {
1843                 if ((argc == 2) && (strcmp(args[1], "force") == 0))
1844                         reg->valid = 0;
1845
1846                 if (reg->valid == 0)
1847                 {
1848                         reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
1849                         arch_type->get(reg);
1850                 }
1851                 value = buf_to_str(reg->value, reg->size, 16);
1852                 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1853                 free(value);
1854                 return ERROR_OK;
1855         }
1856
1857         /* set register value */
1858         if (argc == 2)
1859         {
1860                 uint8_t *buf = malloc(CEIL(reg->size, 8));
1861                 str_to_buf(args[1], strlen(args[1]), buf, reg->size, 0);
1862
1863                 reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
1864                 arch_type->set(reg, buf);
1865
1866                 value = buf_to_str(reg->value, reg->size, 16);
1867                 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1868                 free(value);
1869
1870                 free(buf);
1871
1872                 return ERROR_OK;
1873         }
1874
1875         command_print(cmd_ctx, "usage: reg <#|name> [value]");
1876
1877         return ERROR_OK;
1878 }
1879
1880 static int handle_poll_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1881 {
1882         int retval = ERROR_OK;
1883         target_t *target = get_current_target(cmd_ctx);
1884
1885         if (argc == 0)
1886         {
1887                 command_print(cmd_ctx, "background polling: %s",
1888                                 jtag_poll_get_enabled() ? "on" : "off");
1889                 command_print(cmd_ctx, "TAP: %s (%s)",
1890                                 target->tap->dotted_name,
1891                                 target->tap->enabled ? "enabled" : "disabled");
1892                 if (!target->tap->enabled)
1893                         return ERROR_OK;
1894                 if ((retval = target_poll(target)) != ERROR_OK)
1895                         return retval;
1896                 if ((retval = target_arch_state(target)) != ERROR_OK)
1897                         return retval;
1898
1899         }
1900         else if (argc == 1)
1901         {
1902                 if (strcmp(args[0], "on") == 0)
1903                 {
1904                         jtag_poll_set_enabled(true);
1905                 }
1906                 else if (strcmp(args[0], "off") == 0)
1907                 {
1908                         jtag_poll_set_enabled(false);
1909                 }
1910                 else
1911                 {
1912                         command_print(cmd_ctx, "arg is \"on\" or \"off\"");
1913                 }
1914         } else
1915         {
1916                 return ERROR_COMMAND_SYNTAX_ERROR;
1917         }
1918
1919         return retval;
1920 }
1921
1922 static int handle_wait_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1923 {
1924         if (argc > 1)
1925                 return ERROR_COMMAND_SYNTAX_ERROR;
1926
1927         unsigned ms = 5000;
1928         if (1 == argc)
1929         {
1930                 int retval = parse_uint(args[0], &ms);
1931                 if (ERROR_OK != retval)
1932                 {
1933                         command_print(cmd_ctx, "usage: %s [seconds]", cmd);
1934                         return ERROR_COMMAND_SYNTAX_ERROR;
1935                 }
1936                 // convert seconds (given) to milliseconds (needed)
1937                 ms *= 1000;
1938         }
1939
1940         target_t *target = get_current_target(cmd_ctx);
1941         return target_wait_state(target, TARGET_HALTED, ms);
1942 }
1943
1944 /* wait for target state to change. The trick here is to have a low
1945  * latency for short waits and not to suck up all the CPU time
1946  * on longer waits.
1947  *
1948  * After 500ms, keep_alive() is invoked
1949  */
1950 int target_wait_state(target_t *target, enum target_state state, int ms)
1951 {
1952         int retval;
1953         long long then = 0, cur;
1954         int once = 1;
1955
1956         for (;;)
1957         {
1958                 if ((retval = target_poll(target)) != ERROR_OK)
1959                         return retval;
1960                 if (target->state == state)
1961                 {
1962                         break;
1963                 }
1964                 cur = timeval_ms();
1965                 if (once)
1966                 {
1967                         once = 0;
1968                         then = timeval_ms();
1969                         LOG_DEBUG("waiting for target %s...",
1970                                 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
1971                 }
1972
1973                 if (cur-then > 500)
1974                 {
1975                         keep_alive();
1976                 }
1977
1978                 if ((cur-then) > ms)
1979                 {
1980                         LOG_ERROR("timed out while waiting for target %s",
1981                                 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
1982                         return ERROR_FAIL;
1983                 }
1984         }
1985
1986         return ERROR_OK;
1987 }
1988
1989 static int handle_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1990 {
1991         LOG_DEBUG("-");
1992
1993         target_t *target = get_current_target(cmd_ctx);
1994         int retval = target_halt(target);
1995         if (ERROR_OK != retval)
1996                 return retval;
1997
1998         if (argc == 1)
1999         {
2000                 unsigned wait;
2001                 retval = parse_uint(args[0], &wait);
2002                 if (ERROR_OK != retval)
2003                         return ERROR_COMMAND_SYNTAX_ERROR;
2004                 if (!wait)
2005                         return ERROR_OK;
2006         }
2007
2008         return handle_wait_halt_command(cmd_ctx, cmd, args, argc);
2009 }
2010
2011 static int handle_soft_reset_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2012 {
2013         target_t *target = get_current_target(cmd_ctx);
2014
2015         LOG_USER("requesting target halt and executing a soft reset");
2016
2017         target->type->soft_reset_halt(target);
2018
2019         return ERROR_OK;
2020 }
2021
2022 static int handle_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2023 {
2024         if (argc > 1)
2025                 return ERROR_COMMAND_SYNTAX_ERROR;
2026
2027         enum target_reset_mode reset_mode = RESET_RUN;
2028         if (argc == 1)
2029         {
2030                 const Jim_Nvp *n;
2031                 n = Jim_Nvp_name2value_simple(nvp_reset_modes, args[0]);
2032                 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2033                         return ERROR_COMMAND_SYNTAX_ERROR;
2034                 }
2035                 reset_mode = n->value;
2036         }
2037
2038         /* reset *all* targets */
2039         return target_process_reset(cmd_ctx, reset_mode);
2040 }
2041
2042
2043 static int handle_resume_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2044 {
2045         int current = 1;
2046         if (argc > 1)
2047                 return ERROR_COMMAND_SYNTAX_ERROR;
2048
2049         target_t *target = get_current_target(cmd_ctx);
2050         target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2051
2052         /* with no args, resume from current pc, addr = 0,
2053          * with one arguments, addr = args[0],
2054          * handle breakpoints, not debugging */
2055         uint32_t addr = 0;
2056         if (argc == 1)
2057         {
2058                 int retval = parse_u32(args[0], &addr);
2059                 if (ERROR_OK != retval)
2060                         return retval;
2061                 current = 0;
2062         }
2063
2064         return target_resume(target, current, addr, 1, 0);
2065 }
2066
2067 static int handle_step_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2068 {
2069         if (argc > 1)
2070                 return ERROR_COMMAND_SYNTAX_ERROR;
2071
2072         LOG_DEBUG("-");
2073
2074         /* with no args, step from current pc, addr = 0,
2075          * with one argument addr = args[0],
2076          * handle breakpoints, debugging */
2077         uint32_t addr = 0;
2078         int current_pc = 1;
2079         if (argc == 1)
2080         {
2081                 int retval = parse_u32(args[0], &addr);
2082                 if (ERROR_OK != retval)
2083                         return retval;
2084                 current_pc = 0;
2085         }
2086
2087         target_t *target = get_current_target(cmd_ctx);
2088
2089         return target->type->step(target, current_pc, addr, 1);
2090 }
2091
2092 static void handle_md_output(struct command_context_s *cmd_ctx,
2093                 struct target_s *target, uint32_t address, unsigned size,
2094                 unsigned count, const uint8_t *buffer)
2095 {
2096         const unsigned line_bytecnt = 32;
2097         unsigned line_modulo = line_bytecnt / size;
2098
2099         char output[line_bytecnt * 4 + 1];
2100         unsigned output_len = 0;
2101
2102         const char *value_fmt;
2103         switch (size) {
2104         case 4: value_fmt = "%8.8x "; break;
2105         case 2: value_fmt = "%4.2x "; break;
2106         case 1: value_fmt = "%2.2x "; break;
2107         default:
2108                 LOG_ERROR("invalid memory read size: %u", size);
2109                 exit(-1);
2110         }
2111
2112         for (unsigned i = 0; i < count; i++)
2113         {
2114                 if (i % line_modulo == 0)
2115                 {
2116                         output_len += snprintf(output + output_len,
2117                                         sizeof(output) - output_len,
2118                                         "0x%8.8x: ",
2119                                         (unsigned)(address + (i*size)));
2120                 }
2121
2122                 uint32_t value = 0;
2123                 const uint8_t *value_ptr = buffer + i * size;
2124                 switch (size) {
2125                 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2126                 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2127                 case 1: value = *value_ptr;
2128                 }
2129                 output_len += snprintf(output + output_len,
2130                                 sizeof(output) - output_len,
2131                                 value_fmt, value);
2132
2133                 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2134                 {
2135                         command_print(cmd_ctx, "%s", output);
2136                         output_len = 0;
2137                 }
2138         }
2139 }
2140
2141 static int handle_md_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2142 {
2143         if (argc < 1)
2144                 return ERROR_COMMAND_SYNTAX_ERROR;
2145
2146         unsigned size = 0;
2147         switch (cmd[2]) {
2148         case 'w': size = 4; break;
2149         case 'h': size = 2; break;
2150         case 'b': size = 1; break;
2151         default: return ERROR_COMMAND_SYNTAX_ERROR;
2152         }
2153
2154         uint32_t address;
2155         int retval = parse_u32(args[0], &address);
2156         if (ERROR_OK != retval)
2157                 return retval;
2158
2159         unsigned count = 1;
2160         if (argc == 2)
2161         {
2162                 retval = parse_uint(args[1], &count);
2163                 if (ERROR_OK != retval)
2164                         return retval;
2165         }
2166
2167         uint8_t *buffer = calloc(count, size);
2168
2169         target_t *target = get_current_target(cmd_ctx);
2170         retval = target_read_memory(target,
2171                                 address, size, count, buffer);
2172         if (ERROR_OK == retval)
2173                 handle_md_output(cmd_ctx, target, address, size, count, buffer);
2174
2175         free(buffer);
2176
2177         return retval;
2178 }
2179
2180 static int handle_mw_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2181 {
2182          if ((argc < 2) || (argc > 3))
2183                 return ERROR_COMMAND_SYNTAX_ERROR;
2184
2185         uint32_t address;
2186         int retval = parse_u32(args[0], &address);
2187         if (ERROR_OK != retval)
2188                 return retval;
2189
2190         uint32_t value;
2191         retval = parse_u32(args[1], &value);
2192         if (ERROR_OK != retval)
2193                 return retval;
2194
2195         unsigned count = 1;
2196         if (argc == 3)
2197         {
2198                 retval = parse_uint(args[2], &count);
2199                 if (ERROR_OK != retval)
2200                         return retval;
2201         }
2202
2203         target_t *target = get_current_target(cmd_ctx);
2204         unsigned wordsize;
2205         uint8_t value_buf[4];
2206         switch (cmd[2])
2207         {
2208                 case 'w':
2209                         wordsize = 4;
2210                         target_buffer_set_u32(target, value_buf, value);
2211                         break;
2212                 case 'h':
2213                         wordsize = 2;
2214                         target_buffer_set_u16(target, value_buf, value);
2215                         break;
2216                 case 'b':
2217                         wordsize = 1;
2218                         value_buf[0] = value;
2219                         break;
2220                 default:
2221                         return ERROR_COMMAND_SYNTAX_ERROR;
2222         }
2223         for (unsigned i = 0; i < count; i++)
2224         {
2225                 retval = target_write_memory(target,
2226                                 address + i * wordsize, wordsize, 1, value_buf);
2227                 if (ERROR_OK != retval)
2228                         return retval;
2229                 keep_alive();
2230         }
2231
2232         return ERROR_OK;
2233
2234 }
2235
2236 static int parse_load_image_command_args(char **args, int argc,
2237                 image_t *image, uint32_t *min_address, uint32_t *max_address)
2238 {
2239         if (argc < 1 || argc > 5)
2240                 return ERROR_COMMAND_SYNTAX_ERROR;
2241
2242         /* a base address isn't always necessary,
2243          * default to 0x0 (i.e. don't relocate) */
2244         if (argc >= 2)
2245         {
2246                 uint32_t addr;
2247                 int retval = parse_u32(args[1], &addr);
2248                 if (ERROR_OK != retval)
2249                         return ERROR_COMMAND_SYNTAX_ERROR;
2250                 image->base_address = addr;
2251                 image->base_address_set = 1;
2252         }
2253         else
2254                 image->base_address_set = 0;
2255
2256         image->start_address_set = 0;
2257
2258         if (argc >= 4)
2259         {
2260                 int retval = parse_u32(args[3], min_address);
2261                 if (ERROR_OK != retval)
2262                         return ERROR_COMMAND_SYNTAX_ERROR;
2263         }
2264         if (argc == 5)
2265         {
2266                 int retval = parse_u32(args[4], max_address);
2267                 if (ERROR_OK != retval)
2268                         return ERROR_COMMAND_SYNTAX_ERROR;
2269                 // use size (given) to find max (required)
2270                 *max_address += *min_address;
2271         }
2272
2273         if (*min_address > *max_address)
2274                 return ERROR_COMMAND_SYNTAX_ERROR;
2275
2276         return ERROR_OK;
2277 }
2278
2279 static int handle_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2280 {
2281         uint8_t *buffer;
2282         uint32_t buf_cnt;
2283         uint32_t image_size;
2284         uint32_t min_address = 0;
2285         uint32_t max_address = 0xffffffff;
2286         int i;
2287         int retvaltemp;
2288
2289         image_t image;
2290
2291         duration_t duration;
2292         char *duration_text;
2293
2294         int retval = parse_load_image_command_args(args, argc,
2295                         &image, &min_address, &max_address);
2296         if (ERROR_OK != retval)
2297                 return retval;
2298
2299         target_t *target = get_current_target(cmd_ctx);
2300         duration_start_measure(&duration);
2301
2302         if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
2303         {
2304                 return ERROR_OK;
2305         }
2306
2307         image_size = 0x0;
2308         retval = ERROR_OK;
2309         for (i = 0; i < image.num_sections; i++)
2310         {
2311                 buffer = malloc(image.sections[i].size);
2312                 if (buffer == NULL)
2313                 {
2314                         command_print(cmd_ctx,
2315                                                   "error allocating buffer for section (%d bytes)",
2316                                                   (int)(image.sections[i].size));
2317                         break;
2318                 }
2319
2320                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2321                 {
2322                         free(buffer);
2323                         break;
2324                 }
2325
2326                 uint32_t offset = 0;
2327                 uint32_t length = buf_cnt;
2328
2329                 /* DANGER!!! beware of unsigned comparision here!!! */
2330
2331                 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2332                                 (image.sections[i].base_address < max_address))
2333                 {
2334                         if (image.sections[i].base_address < min_address)
2335                         {
2336                                 /* clip addresses below */
2337                                 offset += min_address-image.sections[i].base_address;
2338                                 length -= offset;
2339                         }
2340
2341                         if (image.sections[i].base_address + buf_cnt > max_address)
2342                         {
2343                                 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2344                         }
2345
2346                         if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2347                         {
2348                                 free(buffer);
2349                                 break;
2350                         }
2351                         image_size += length;
2352                         command_print(cmd_ctx, "%u bytes written at address 0x%8.8" PRIx32 "",
2353                                                   (unsigned int)length,
2354                                                   image.sections[i].base_address + offset);
2355                 }
2356
2357                 free(buffer);
2358         }
2359
2360         if ((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2361         {
2362                 image_close(&image);
2363                 return retvaltemp;
2364         }
2365
2366         if (retval == ERROR_OK)
2367         {
2368                 command_print(cmd_ctx, "downloaded %u byte in %s",
2369                                           (unsigned int)image_size,
2370                                           duration_text);
2371         }
2372         free(duration_text);
2373
2374         image_close(&image);
2375
2376         return retval;
2377
2378 }
2379
2380 static int handle_dump_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2381 {
2382         fileio_t fileio;
2383
2384         uint8_t buffer[560];
2385         int retvaltemp;
2386
2387         duration_t duration;
2388         char *duration_text;
2389
2390         target_t *target = get_current_target(cmd_ctx);
2391
2392         if (argc != 3)
2393         {
2394                 command_print(cmd_ctx, "usage: dump_image <filename> <address> <size>");
2395                 return ERROR_OK;
2396         }
2397
2398         uint32_t address;
2399         int retval = parse_u32(args[1], &address);
2400         if (ERROR_OK != retval)
2401                 return retval;
2402
2403         uint32_t size;
2404         retval = parse_u32(args[2], &size);
2405         if (ERROR_OK != retval)
2406                 return retval;
2407
2408         if (fileio_open(&fileio, args[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
2409         {
2410                 return ERROR_OK;
2411         }
2412
2413         duration_start_measure(&duration);
2414
2415         while (size > 0)
2416         {
2417                 uint32_t size_written;
2418                 uint32_t this_run_size = (size > 560) ? 560 : size;
2419
2420                 retval = target_read_buffer(target, address, this_run_size, buffer);
2421                 if (retval != ERROR_OK)
2422                 {
2423                         break;
2424                 }
2425
2426                 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2427                 if (retval != ERROR_OK)
2428                 {
2429                         break;
2430                 }
2431
2432                 size -= this_run_size;
2433                 address += this_run_size;
2434         }
2435
2436         if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2437                 return retvaltemp;
2438
2439         if ((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2440                 return retvaltemp;
2441
2442         if (retval == ERROR_OK)
2443         {
2444                 command_print(cmd_ctx, "dumped %lld byte in %s",
2445                                 fileio.size, duration_text);
2446                 free(duration_text);
2447         }
2448
2449         return retval;
2450 }
2451
2452 static int handle_verify_image_command_internal(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc, int verify)
2453 {
2454         uint8_t *buffer;
2455         uint32_t buf_cnt;
2456         uint32_t image_size;
2457         int i;
2458         int retval, retvaltemp;
2459         uint32_t checksum = 0;
2460         uint32_t mem_checksum = 0;
2461
2462         image_t image;
2463
2464         duration_t duration;
2465         char *duration_text;
2466
2467         target_t *target = get_current_target(cmd_ctx);
2468
2469         if (argc < 1)
2470         {
2471                 return ERROR_COMMAND_SYNTAX_ERROR;
2472         }
2473
2474         if (!target)
2475         {
2476                 LOG_ERROR("no target selected");
2477                 return ERROR_FAIL;
2478         }
2479
2480         duration_start_measure(&duration);
2481
2482         if (argc >= 2)
2483         {
2484                 uint32_t addr;
2485                 retval = parse_u32(args[1], &addr);
2486                 if (ERROR_OK != retval)
2487                         return ERROR_COMMAND_SYNTAX_ERROR;
2488                 image.base_address = addr;
2489                 image.base_address_set = 1;
2490         }
2491         else
2492         {
2493                 image.base_address_set = 0;
2494                 image.base_address = 0x0;
2495         }
2496
2497         image.start_address_set = 0;
2498
2499         if ((retval = image_open(&image, args[0], (argc == 3) ? args[2] : NULL)) != ERROR_OK)
2500         {
2501                 return retval;
2502         }
2503
2504         image_size = 0x0;
2505         retval = ERROR_OK;
2506         for (i = 0; i < image.num_sections; i++)
2507         {
2508                 buffer = malloc(image.sections[i].size);
2509                 if (buffer == NULL)
2510                 {
2511                         command_print(cmd_ctx,
2512                                                   "error allocating buffer for section (%d bytes)",
2513                                                   (int)(image.sections[i].size));
2514                         break;
2515                 }
2516                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2517                 {
2518                         free(buffer);
2519                         break;
2520                 }
2521
2522                 if (verify)
2523                 {
2524                         /* calculate checksum of image */
2525                         image_calculate_checksum(buffer, buf_cnt, &checksum);
2526
2527                         retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2528                         if (retval != ERROR_OK)
2529                         {
2530                                 free(buffer);
2531                                 break;
2532                         }
2533
2534                         if (checksum != mem_checksum)
2535                         {
2536                                 /* failed crc checksum, fall back to a binary compare */
2537                                 uint8_t *data;
2538
2539                                 command_print(cmd_ctx, "checksum mismatch - attempting binary compare");
2540
2541                                 data = (uint8_t*)malloc(buf_cnt);
2542
2543                                 /* Can we use 32bit word accesses? */
2544                                 int size = 1;
2545                                 int count = buf_cnt;
2546                                 if ((count % 4) == 0)
2547                                 {
2548                                         size *= 4;
2549                                         count /= 4;
2550                                 }
2551                                 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2552                                 if (retval == ERROR_OK)
2553                                 {
2554                                         uint32_t t;
2555                                         for (t = 0; t < buf_cnt; t++)
2556                                         {
2557                                                 if (data[t] != buffer[t])
2558                                                 {
2559                                                         command_print(cmd_ctx,
2560                                                                                   "Verify operation failed address 0x%08x. Was 0x%02x instead of 0x%02x\n",
2561                                                                                   (unsigned)(t + image.sections[i].base_address),
2562                                                                                   data[t],
2563                                                                                   buffer[t]);
2564                                                         free(data);
2565                                                         free(buffer);
2566                                                         retval = ERROR_FAIL;
2567                                                         goto done;
2568                                                 }
2569                                                 if ((t%16384) == 0)
2570                                                 {
2571                                                         keep_alive();
2572                                                 }
2573                                         }
2574                                 }
2575
2576                                 free(data);
2577                         }
2578                 } else
2579                 {
2580                         command_print(cmd_ctx, "address 0x%08" PRIx32 " length 0x%08" PRIx32 "",
2581                                                   image.sections[i].base_address,
2582                                                   buf_cnt);
2583                 }
2584
2585                 free(buffer);
2586                 image_size += buf_cnt;
2587         }
2588 done:
2589
2590         if ((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2591         {
2592                 image_close(&image);
2593                 return retvaltemp;
2594         }
2595
2596         if (retval == ERROR_OK)
2597         {
2598                 command_print(cmd_ctx, "verified %u bytes in %s",
2599                                           (unsigned int)image_size,
2600                                           duration_text);
2601         }
2602         free(duration_text);
2603
2604         image_close(&image);
2605
2606         return retval;
2607 }
2608
2609 static int handle_verify_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2610 {
2611         return handle_verify_image_command_internal(cmd_ctx, cmd, args, argc, 1);
2612 }
2613
2614 static int handle_test_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2615 {
2616         return handle_verify_image_command_internal(cmd_ctx, cmd, args, argc, 0);
2617 }
2618
2619 static int handle_bp_command_list(struct command_context_s *cmd_ctx)
2620 {
2621         target_t *target = get_current_target(cmd_ctx);
2622         breakpoint_t *breakpoint = target->breakpoints;
2623         while (breakpoint)
2624         {
2625                 if (breakpoint->type == BKPT_SOFT)
2626                 {
2627                         char* buf = buf_to_str(breakpoint->orig_instr,
2628                                         breakpoint->length, 16);
2629                         command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2630                                         breakpoint->address,
2631                                         breakpoint->length,
2632                                         breakpoint->set, buf);
2633                         free(buf);
2634                 }
2635                 else
2636                 {
2637                         command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2638                                                   breakpoint->address,
2639                                                   breakpoint->length, breakpoint->set);
2640                 }
2641
2642                 breakpoint = breakpoint->next;
2643         }
2644         return ERROR_OK;
2645 }
2646
2647 static int handle_bp_command_set(struct command_context_s *cmd_ctx,
2648                 uint32_t addr, uint32_t length, int hw)
2649 {
2650         target_t *target = get_current_target(cmd_ctx);
2651         int retval = breakpoint_add(target, addr, length, hw);
2652         if (ERROR_OK == retval)
2653                 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2654         else
2655                 LOG_ERROR("Failure setting breakpoint");
2656         return retval;
2657 }
2658
2659 static int handle_bp_command(struct command_context_s *cmd_ctx,
2660                 char *cmd, char **args, int argc)
2661 {
2662         if (argc == 0)
2663                 return handle_bp_command_list(cmd_ctx);
2664
2665         if (argc < 2 || argc > 3)
2666         {
2667                 command_print(cmd_ctx, "usage: bp <address> <length> ['hw']");
2668                 return ERROR_COMMAND_SYNTAX_ERROR;
2669         }
2670
2671         uint32_t addr;
2672         int retval = parse_u32(args[0], &addr);
2673         if (ERROR_OK != retval)
2674                 return retval;
2675
2676         uint32_t length;
2677         retval = parse_u32(args[1], &length);
2678         if (ERROR_OK != retval)
2679                 return retval;
2680
2681         int hw = BKPT_SOFT;
2682         if (argc == 3)
2683         {
2684                 if (strcmp(args[2], "hw") == 0)
2685                         hw = BKPT_HARD;
2686                 else
2687                         return ERROR_COMMAND_SYNTAX_ERROR;
2688         }
2689
2690         return handle_bp_command_set(cmd_ctx, addr, length, hw);
2691 }
2692
2693 static int handle_rbp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2694 {
2695         if (argc != 1)
2696                 return ERROR_COMMAND_SYNTAX_ERROR;
2697
2698         uint32_t addr;
2699         int retval = parse_u32(args[0], &addr);
2700         if (ERROR_OK != retval)
2701                 return retval;
2702
2703         target_t *target = get_current_target(cmd_ctx);
2704         breakpoint_remove(target, addr);
2705
2706         return ERROR_OK;
2707 }
2708
2709 static int handle_wp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2710 {
2711         target_t *target = get_current_target(cmd_ctx);
2712
2713         if (argc == 0)
2714         {
2715                 watchpoint_t *watchpoint = target->watchpoints;
2716
2717                 while (watchpoint)
2718                 {
2719                         command_print(cmd_ctx,
2720                                                   "address: 0x%8.8" PRIx32 ", len: 0x%8.8x, r/w/a: %i, value: 0x%8.8" PRIx32 ", mask: 0x%8.8" PRIx32 "",
2721                                                   watchpoint->address,
2722                                                   watchpoint->length,
2723                                                   (int)(watchpoint->rw),
2724                                                   watchpoint->value,
2725                                                   watchpoint->mask);
2726                         watchpoint = watchpoint->next;
2727                 }
2728                 return ERROR_OK;
2729         }
2730
2731         enum watchpoint_rw type = WPT_ACCESS;
2732         uint32_t addr = 0;
2733         uint32_t length = 0;
2734         uint32_t data_value = 0x0;
2735         uint32_t data_mask = 0xffffffff;
2736         int retval;
2737
2738         switch (argc)
2739         {
2740         case 5:
2741                 retval = parse_u32(args[4], &data_mask);
2742                 if (ERROR_OK != retval)
2743                         return retval;
2744                 // fall through
2745         case 4:
2746                 retval = parse_u32(args[3], &data_value);
2747                 if (ERROR_OK != retval)
2748                         return retval;
2749                 // fall through
2750         case 3:
2751                 switch (args[2][0])
2752                 {
2753                 case 'r':
2754                         type = WPT_READ;
2755                         break;
2756                 case 'w':
2757                         type = WPT_WRITE;
2758                         break;
2759                 case 'a':
2760                         type = WPT_ACCESS;
2761                         break;
2762                 default:
2763                         LOG_ERROR("invalid watchpoint mode ('%c')", args[2][0]);
2764                         return ERROR_COMMAND_SYNTAX_ERROR;
2765                 }
2766                 // fall through
2767         case 2:
2768                 retval = parse_u32(args[1], &length);
2769                 if (ERROR_OK != retval)
2770                         return retval;
2771                 retval = parse_u32(args[0], &addr);
2772                 if (ERROR_OK != retval)
2773                         return retval;
2774                 break;
2775
2776         default:
2777                 command_print(cmd_ctx, "usage: wp <address> <length> [r/w/a] [value] [mask]");
2778                 return ERROR_COMMAND_SYNTAX_ERROR;
2779         }
2780
2781         retval = watchpoint_add(target, addr, length, type,
2782                         data_value, data_mask);
2783         if (ERROR_OK != retval)
2784                 LOG_ERROR("Failure setting watchpoints");
2785
2786         return retval;
2787 }
2788
2789 static int handle_rwp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2790 {
2791         if (argc != 1)
2792                 return ERROR_COMMAND_SYNTAX_ERROR;
2793
2794         uint32_t addr;
2795         int retval = parse_u32(args[0], &addr);
2796         if (ERROR_OK != retval)
2797                 return retval;
2798
2799         target_t *target = get_current_target(cmd_ctx);
2800         watchpoint_remove(target, addr);
2801
2802         return ERROR_OK;
2803 }
2804
2805
2806 /**
2807  * Translate a virtual address to a physical address.
2808  *
2809  * The low-level target implementation must have logged a detailed error
2810  * which is forwarded to telnet/GDB session.
2811  */
2812 static int handle_virt2phys_command(command_context_t *cmd_ctx,
2813                 char *cmd, char **args, int argc)
2814 {
2815         if (argc != 1)
2816                 return ERROR_COMMAND_SYNTAX_ERROR;
2817
2818         uint32_t va;
2819         int retval = parse_u32(args[0], &va);
2820         if (ERROR_OK != retval)
2821                 return retval;
2822         uint32_t pa;
2823
2824         target_t *target = get_current_target(cmd_ctx);
2825         retval = target->type->virt2phys(target, va, &pa);
2826         if (retval == ERROR_OK)
2827                 command_print(cmd_ctx, "Physical address 0x%08" PRIx32 "", pa);
2828
2829         return retval;
2830 }
2831
2832 static void writeData(FILE *f, const void *data, size_t len)
2833 {
2834         size_t written = fwrite(data, 1, len, f);
2835         if (written != len)
2836                 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
2837 }
2838
2839 static void writeLong(FILE *f, int l)
2840 {
2841         int i;
2842         for (i = 0; i < 4; i++)
2843         {
2844                 char c = (l >> (i*8))&0xff;
2845                 writeData(f, &c, 1);
2846         }
2847
2848 }
2849
2850 static void writeString(FILE *f, char *s)
2851 {
2852         writeData(f, s, strlen(s));
2853 }
2854
2855 /* Dump a gmon.out histogram file. */
2856 static void writeGmon(uint32_t *samples, uint32_t sampleNum, char *filename)
2857 {
2858         uint32_t i;
2859         FILE *f = fopen(filename, "w");
2860         if (f == NULL)
2861                 return;
2862         writeString(f, "gmon");
2863         writeLong(f, 0x00000001); /* Version */
2864         writeLong(f, 0); /* padding */
2865         writeLong(f, 0); /* padding */
2866         writeLong(f, 0); /* padding */
2867
2868         uint8_t zero = 0;  /* GMON_TAG_TIME_HIST */
2869         writeData(f, &zero, 1);
2870
2871         /* figure out bucket size */
2872         uint32_t min = samples[0];
2873         uint32_t max = samples[0];
2874         for (i = 0; i < sampleNum; i++)
2875         {
2876                 if (min > samples[i])
2877                 {
2878                         min = samples[i];
2879                 }
2880                 if (max < samples[i])
2881                 {
2882                         max = samples[i];
2883                 }
2884         }
2885
2886         int addressSpace = (max-min + 1);
2887
2888         static const uint32_t maxBuckets = 256 * 1024; /* maximum buckets. */
2889         uint32_t length = addressSpace;
2890         if (length > maxBuckets)
2891         {
2892                 length = maxBuckets;
2893         }
2894         int *buckets = malloc(sizeof(int)*length);
2895         if (buckets == NULL)
2896         {
2897                 fclose(f);
2898                 return;
2899         }
2900         memset(buckets, 0, sizeof(int)*length);
2901         for (i = 0; i < sampleNum;i++)
2902         {
2903                 uint32_t address = samples[i];
2904                 long long a = address-min;
2905                 long long b = length-1;
2906                 long long c = addressSpace-1;
2907                 int index = (a*b)/c; /* danger!!!! int32 overflows */
2908                 buckets[index]++;
2909         }
2910
2911         /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
2912         writeLong(f, min);                      /* low_pc */
2913         writeLong(f, max);                      /* high_pc */
2914         writeLong(f, length);           /* # of samples */
2915         writeLong(f, 64000000);         /* 64MHz */
2916         writeString(f, "seconds");
2917         for (i = 0; i < (15-strlen("seconds")); i++)
2918                 writeData(f, &zero, 1);
2919         writeString(f, "s");
2920
2921         /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
2922
2923         char *data = malloc(2*length);
2924         if (data != NULL)
2925         {
2926                 for (i = 0; i < length;i++)
2927                 {
2928                         int val;
2929                         val = buckets[i];
2930                         if (val > 65535)
2931                         {
2932                                 val = 65535;
2933                         }
2934                         data[i*2]=val&0xff;
2935                         data[i*2 + 1]=(val >> 8)&0xff;
2936                 }
2937                 free(buckets);
2938                 writeData(f, data, length * 2);
2939                 free(data);
2940         } else
2941         {
2942                 free(buckets);
2943         }
2944
2945         fclose(f);
2946 }
2947
2948 /* profiling samples the CPU PC as quickly as OpenOCD is able, which will be used as a random sampling of PC */
2949 static int handle_profile_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2950 {
2951         target_t *target = get_current_target(cmd_ctx);
2952         struct timeval timeout, now;
2953
2954         gettimeofday(&timeout, NULL);
2955         if (argc != 2)
2956         {
2957                 return ERROR_COMMAND_SYNTAX_ERROR;
2958         }
2959         unsigned offset;
2960         int retval = parse_uint(args[0], &offset);
2961         if (ERROR_OK != retval)
2962                 return retval;
2963
2964         timeval_add_time(&timeout, offset, 0);
2965
2966         command_print(cmd_ctx, "Starting profiling. Halting and resuming the target as often as we can...");
2967
2968         static const int maxSample = 10000;
2969         uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
2970         if (samples == NULL)
2971                 return ERROR_OK;
2972
2973         int numSamples = 0;
2974         /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
2975         reg_t *reg = register_get_by_name(target->reg_cache, "pc", 1);
2976
2977         for (;;)
2978         {
2979                 target_poll(target);
2980                 if (target->state == TARGET_HALTED)
2981                 {
2982                         uint32_t t=*((uint32_t *)reg->value);
2983                         samples[numSamples++]=t;
2984                         retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
2985                         target_poll(target);
2986                         alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
2987                 } else if (target->state == TARGET_RUNNING)
2988                 {
2989                         /* We want to quickly sample the PC. */
2990                         if ((retval = target_halt(target)) != ERROR_OK)
2991                         {
2992                                 free(samples);
2993                                 return retval;
2994                         }
2995                 } else
2996                 {
2997                         command_print(cmd_ctx, "Target not halted or running");
2998                         retval = ERROR_OK;
2999                         break;
3000                 }
3001                 if (retval != ERROR_OK)
3002                 {
3003                         break;
3004                 }
3005
3006                 gettimeofday(&now, NULL);
3007                 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3008                 {
3009                         command_print(cmd_ctx, "Profiling completed. %d samples.", numSamples);
3010                         if ((retval = target_poll(target)) != ERROR_OK)
3011                         {
3012                                 free(samples);
3013                                 return retval;
3014                         }
3015                         if (target->state == TARGET_HALTED)
3016                         {
3017                                 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3018                         }
3019                         if ((retval = target_poll(target)) != ERROR_OK)
3020                         {
3021                                 free(samples);
3022                                 return retval;
3023                         }
3024                         writeGmon(samples, numSamples, args[1]);
3025                         command_print(cmd_ctx, "Wrote %s", args[1]);
3026                         break;
3027                 }
3028         }
3029         free(samples);
3030
3031         return ERROR_OK;
3032 }
3033
3034 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3035 {
3036         char *namebuf;
3037         Jim_Obj *nameObjPtr, *valObjPtr;
3038         int result;
3039
3040         namebuf = alloc_printf("%s(%d)", varname, idx);
3041         if (!namebuf)
3042                 return JIM_ERR;
3043
3044         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3045         valObjPtr = Jim_NewIntObj(interp, val);
3046         if (!nameObjPtr || !valObjPtr)
3047         {
3048                 free(namebuf);
3049                 return JIM_ERR;
3050         }
3051
3052         Jim_IncrRefCount(nameObjPtr);
3053         Jim_IncrRefCount(valObjPtr);
3054         result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3055         Jim_DecrRefCount(interp, nameObjPtr);
3056         Jim_DecrRefCount(interp, valObjPtr);
3057         free(namebuf);
3058         /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3059         return result;
3060 }
3061
3062 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3063 {
3064         command_context_t *context;
3065         target_t *target;
3066
3067         context = Jim_GetAssocData(interp, "context");
3068         if (context == NULL)
3069         {
3070                 LOG_ERROR("mem2array: no command context");
3071                 return JIM_ERR;
3072         }
3073         target = get_current_target(context);
3074         if (target == NULL)
3075         {
3076                 LOG_ERROR("mem2array: no current target");
3077                 return JIM_ERR;
3078         }
3079
3080         return  target_mem2array(interp, target, argc-1, argv + 1);
3081 }
3082
3083 static int target_mem2array(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv)
3084 {
3085         long l;
3086         uint32_t width;
3087         int len;
3088         uint32_t addr;
3089         uint32_t count;
3090         uint32_t v;
3091         const char *varname;
3092         uint8_t buffer[4096];
3093         int  n, e, retval;
3094         uint32_t i;
3095
3096         /* argv[1] = name of array to receive the data
3097          * argv[2] = desired width
3098          * argv[3] = memory address
3099          * argv[4] = count of times to read
3100          */
3101         if (argc != 4) {
3102                 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3103                 return JIM_ERR;
3104         }
3105         varname = Jim_GetString(argv[0], &len);
3106         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3107
3108         e = Jim_GetLong(interp, argv[1], &l);
3109         width = l;
3110         if (e != JIM_OK) {
3111                 return e;
3112         }
3113
3114         e = Jim_GetLong(interp, argv[2], &l);
3115         addr = l;
3116         if (e != JIM_OK) {
3117                 return e;
3118         }
3119         e = Jim_GetLong(interp, argv[3], &l);
3120         len = l;
3121         if (e != JIM_OK) {
3122                 return e;
3123         }
3124         switch (width) {
3125                 case 8:
3126                         width = 1;
3127                         break;
3128                 case 16:
3129                         width = 2;
3130                         break;
3131                 case 32:
3132                         width = 4;
3133                         break;
3134                 default:
3135                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3136                         Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3137                         return JIM_ERR;
3138         }
3139         if (len == 0) {
3140                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3141                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3142                 return JIM_ERR;
3143         }
3144         if ((addr + (len * width)) < addr) {
3145                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3146                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3147                 return JIM_ERR;
3148         }
3149         /* absurd transfer size? */
3150         if (len > 65536) {
3151                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3152                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3153                 return JIM_ERR;
3154         }
3155
3156         if ((width == 1) ||
3157                 ((width == 2) && ((addr & 1) == 0)) ||
3158                 ((width == 4) && ((addr & 3) == 0))) {
3159                 /* all is well */
3160         } else {
3161                 char buf[100];
3162                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3163                 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3164                                 addr,
3165                                 width);
3166                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3167                 return JIM_ERR;
3168         }
3169
3170         /* Transfer loop */
3171
3172         /* index counter */
3173         n = 0;
3174         /* assume ok */
3175         e = JIM_OK;
3176         while (len) {
3177                 /* Slurp... in buffer size chunks */
3178
3179                 count = len; /* in objects.. */
3180                 if (count > (sizeof(buffer)/width)) {
3181                         count = (sizeof(buffer)/width);
3182                 }
3183
3184                 retval = target_read_memory(target, addr, width, count, buffer);
3185                 if (retval != ERROR_OK) {
3186                         /* BOO !*/
3187                         LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3188                                           (unsigned int)addr,
3189                                           (int)width,
3190                                           (int)count);
3191                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3192                         Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3193                         e = JIM_ERR;
3194                         len = 0;
3195                 } else {
3196                         v = 0; /* shut up gcc */
3197                         for (i = 0 ;i < count ;i++, n++) {
3198                                 switch (width) {
3199                                         case 4:
3200                                                 v = target_buffer_get_u32(target, &buffer[i*width]);
3201                                                 break;
3202                                         case 2:
3203                                                 v = target_buffer_get_u16(target, &buffer[i*width]);
3204                                                 break;
3205                                         case 1:
3206                                                 v = buffer[i] & 0x0ff;
3207                                                 break;
3208                                 }
3209                                 new_int_array_element(interp, varname, n, v);
3210                         }
3211                         len -= count;
3212                 }
3213         }
3214
3215         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3216
3217         return JIM_OK;
3218 }
3219
3220 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3221 {
3222         char *namebuf;
3223         Jim_Obj *nameObjPtr, *valObjPtr;
3224         int result;
3225         long l;
3226
3227         namebuf = alloc_printf("%s(%d)", varname, idx);
3228         if (!namebuf)
3229                 return JIM_ERR;
3230
3231         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3232         if (!nameObjPtr)
3233         {
3234                 free(namebuf);
3235                 return JIM_ERR;
3236         }
3237
3238         Jim_IncrRefCount(nameObjPtr);
3239         valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3240         Jim_DecrRefCount(interp, nameObjPtr);
3241         free(namebuf);
3242         if (valObjPtr == NULL)
3243                 return JIM_ERR;
3244
3245         result = Jim_GetLong(interp, valObjPtr, &l);
3246         /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3247         *val = l;
3248         return result;
3249 }
3250
3251 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3252 {
3253         command_context_t *context;
3254         target_t *target;
3255
3256         context = Jim_GetAssocData(interp, "context");
3257         if (context == NULL) {
3258                 LOG_ERROR("array2mem: no command context");
3259                 return JIM_ERR;
3260         }
3261         target = get_current_target(context);
3262         if (target == NULL) {
3263                 LOG_ERROR("array2mem: no current target");
3264                 return JIM_ERR;
3265         }
3266
3267         return target_array2mem(interp,target, argc-1, argv + 1);
3268 }
3269
3270 static int target_array2mem(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv)
3271 {
3272         long l;
3273         uint32_t width;
3274         int len;
3275         uint32_t addr;
3276         uint32_t count;
3277         uint32_t v;
3278         const char *varname;
3279         uint8_t buffer[4096];
3280         int  n, e, retval;
3281         uint32_t i;
3282
3283         /* argv[1] = name of array to get the data
3284          * argv[2] = desired width
3285          * argv[3] = memory address
3286          * argv[4] = count to write
3287          */
3288         if (argc != 4) {
3289                 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3290                 return JIM_ERR;
3291         }
3292         varname = Jim_GetString(argv[0], &len);
3293         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3294
3295         e = Jim_GetLong(interp, argv[1], &l);
3296         width = l;
3297         if (e != JIM_OK) {
3298                 return e;
3299         }
3300
3301         e = Jim_GetLong(interp, argv[2], &l);
3302         addr = l;
3303         if (e != JIM_OK) {
3304                 return e;
3305         }
3306         e = Jim_GetLong(interp, argv[3], &l);
3307         len = l;
3308         if (e != JIM_OK) {
3309                 return e;
3310         }
3311         switch (width) {
3312                 case 8:
3313                         width = 1;
3314                         break;
3315                 case 16:
3316                         width = 2;
3317                         break;
3318                 case 32:
3319                         width = 4;
3320                         break;
3321                 default:
3322                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3323                         Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3324                         return JIM_ERR;
3325         }
3326         if (len == 0) {
3327                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3328                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3329                 return JIM_ERR;
3330         }
3331         if ((addr + (len * width)) < addr) {
3332                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3333                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3334                 return JIM_ERR;
3335         }
3336         /* absurd transfer size? */
3337         if (len > 65536) {
3338                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3339                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3340                 return JIM_ERR;
3341         }
3342
3343         if ((width == 1) ||
3344                 ((width == 2) && ((addr & 1) == 0)) ||
3345                 ((width == 4) && ((addr & 3) == 0))) {
3346                 /* all is well */
3347         } else {
3348                 char buf[100];
3349                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3350                 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3351                                 (unsigned int)addr,
3352                                 (int)width);
3353                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3354                 return JIM_ERR;
3355         }
3356
3357         /* Transfer loop */
3358
3359         /* index counter */
3360         n = 0;
3361         /* assume ok */
3362         e = JIM_OK;
3363         while (len) {
3364                 /* Slurp... in buffer size chunks */
3365
3366                 count = len; /* in objects.. */
3367                 if (count > (sizeof(buffer)/width)) {
3368                         count = (sizeof(buffer)/width);
3369                 }
3370
3371                 v = 0; /* shut up gcc */
3372                 for (i = 0 ;i < count ;i++, n++) {
3373                         get_int_array_element(interp, varname, n, &v);
3374                         switch (width) {
3375                         case 4:
3376                                 target_buffer_set_u32(target, &buffer[i*width], v);
3377                                 break;
3378                         case 2:
3379                                 target_buffer_set_u16(target, &buffer[i*width], v);
3380                                 break;
3381                         case 1:
3382                                 buffer[i] = v & 0x0ff;
3383                                 break;
3384                         }
3385                 }
3386                 len -= count;
3387
3388                 retval = target_write_memory(target, addr, width, count, buffer);
3389                 if (retval != ERROR_OK) {
3390                         /* BOO !*/
3391                         LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3392                                           (unsigned int)addr,
3393                                           (int)width,
3394                                           (int)count);
3395                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3396                         Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3397                         e = JIM_ERR;
3398                         len = 0;
3399                 }
3400         }
3401
3402         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3403
3404         return JIM_OK;
3405 }
3406
3407 void target_all_handle_event(enum target_event e)
3408 {
3409         target_t *target;
3410
3411         LOG_DEBUG("**all*targets: event: %d, %s",
3412                            (int)e,
3413                            Jim_Nvp_value2name_simple(nvp_target_event, e)->name);
3414
3415         target = all_targets;
3416         while (target) {
3417                 target_handle_event(target, e);
3418                 target = target->next;
3419         }
3420 }
3421
3422 void target_handle_event(target_t *target, enum target_event e)
3423 {
3424         target_event_action_t *teap;
3425
3426         for (teap = target->event_action; teap != NULL; teap = teap->next) {
3427                 if (teap->event == e) {
3428                         LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3429                                            target->target_number,
3430                                            target->cmd_name,
3431                                            target_get_name(target),
3432                                            e,
3433                                            Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3434                                            Jim_GetString(teap->body, NULL));
3435                         if (Jim_EvalObj(interp, teap->body) != JIM_OK)
3436                         {
3437                                 Jim_PrintErrorMessage(interp);
3438                         }
3439                 }
3440         }
3441 }
3442
3443 enum target_cfg_param {
3444         TCFG_TYPE,
3445         TCFG_EVENT,
3446         TCFG_WORK_AREA_VIRT,
3447         TCFG_WORK_AREA_PHYS,
3448         TCFG_WORK_AREA_SIZE,
3449         TCFG_WORK_AREA_BACKUP,
3450         TCFG_ENDIAN,
3451         TCFG_VARIANT,
3452         TCFG_CHAIN_POSITION,
3453 };
3454
3455 static Jim_Nvp nvp_config_opts[] = {
3456         { .name = "-type",             .value = TCFG_TYPE },
3457         { .name = "-event",            .value = TCFG_EVENT },
3458         { .name = "-work-area-virt",   .value = TCFG_WORK_AREA_VIRT },
3459         { .name = "-work-area-phys",   .value = TCFG_WORK_AREA_PHYS },
3460         { .name = "-work-area-size",   .value = TCFG_WORK_AREA_SIZE },
3461         { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3462         { .name = "-endian" ,          .value = TCFG_ENDIAN },
3463         { .name = "-variant",          .value = TCFG_VARIANT },
3464         { .name = "-chain-position",   .value = TCFG_CHAIN_POSITION },
3465
3466         { .name = NULL, .value = -1 }
3467 };
3468
3469 static int target_configure(Jim_GetOptInfo *goi, target_t *target)
3470 {
3471         Jim_Nvp *n;
3472         Jim_Obj *o;
3473         jim_wide w;
3474         char *cp;
3475         int e;
3476
3477         /* parse config or cget options ... */
3478         while (goi->argc > 0) {
3479                 Jim_SetEmptyResult(goi->interp);
3480                 /* Jim_GetOpt_Debug(goi); */
3481
3482                 if (target->type->target_jim_configure) {
3483                         /* target defines a configure function */
3484                         /* target gets first dibs on parameters */
3485                         e = (*(target->type->target_jim_configure))(target, goi);
3486                         if (e == JIM_OK) {
3487                                 /* more? */
3488                                 continue;
3489                         }
3490                         if (e == JIM_ERR) {
3491                                 /* An error */
3492                                 return e;
3493                         }
3494                         /* otherwise we 'continue' below */
3495                 }
3496                 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3497                 if (e != JIM_OK) {
3498                         Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3499                         return e;
3500                 }
3501                 switch (n->value) {
3502                 case TCFG_TYPE:
3503                         /* not setable */
3504                         if (goi->isconfigure) {
3505                                 Jim_SetResult_sprintf(goi->interp, "not setable: %s", n->name);
3506                                 return JIM_ERR;
3507                         } else {
3508                         no_params:
3509                                 if (goi->argc != 0) {
3510                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "NO PARAMS");
3511                                         return JIM_ERR;
3512                                 }
3513                         }
3514                         Jim_SetResultString(goi->interp, target_get_name(target), -1);
3515                         /* loop for more */
3516                         break;
3517                 case TCFG_EVENT:
3518                         if (goi->argc == 0) {
3519                                 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3520                                 return JIM_ERR;
3521                         }
3522
3523                         e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3524                         if (e != JIM_OK) {
3525                                 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3526                                 return e;
3527                         }
3528
3529                         if (goi->isconfigure) {
3530                                 if (goi->argc != 1) {
3531                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3532                                         return JIM_ERR;
3533                                 }
3534                         } else {
3535                                 if (goi->argc != 0) {
3536                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3537                                         return JIM_ERR;
3538                                 }
3539                         }
3540
3541                         {
3542                                 target_event_action_t *teap;
3543
3544                                 teap = target->event_action;
3545                                 /* replace existing? */
3546                                 while (teap) {
3547                                         if (teap->event == (enum target_event)n->value) {
3548                                                 break;
3549                                         }
3550                                         teap = teap->next;
3551                                 }
3552
3553                                 if (goi->isconfigure) {
3554                                         bool replace = true;
3555                                         if (teap == NULL) {
3556                                                 /* create new */
3557                                                 teap = calloc(1, sizeof(*teap));
3558                                                 replace = false;
3559                                         }
3560                                         teap->event = n->value;
3561                                         Jim_GetOpt_Obj(goi, &o);
3562                                         if (teap->body) {
3563                                                 Jim_DecrRefCount(interp, teap->body);
3564                                         }
3565                                         teap->body  = Jim_DuplicateObj(goi->interp, o);
3566                                         /*
3567                                          * FIXME:
3568                                          *     Tcl/TK - "tk events" have a nice feature.
3569                                          *     See the "BIND" command.
3570                                          *    We should support that here.
3571                                          *     You can specify %X and %Y in the event code.
3572                                          *     The idea is: %T - target name.
3573                                          *     The idea is: %N - target number
3574                                          *     The idea is: %E - event name.
3575                                          */
3576                                         Jim_IncrRefCount(teap->body);
3577
3578                                         if (!replace)
3579                                         {
3580                                                 /* add to head of event list */
3581                                                 teap->next = target->event_action;
3582                                                 target->event_action = teap;
3583                                         }
3584                                         Jim_SetEmptyResult(goi->interp);
3585                                 } else {
3586                                         /* get */
3587                                         if (teap == NULL) {
3588                                                 Jim_SetEmptyResult(goi->interp);
3589                                         } else {
3590                                                 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3591                                         }
3592                                 }
3593                         }
3594                         /* loop for more */
3595                         break;
3596
3597                 case TCFG_WORK_AREA_VIRT:
3598                         if (goi->isconfigure) {
3599                                 target_free_all_working_areas(target);
3600                                 e = Jim_GetOpt_Wide(goi, &w);
3601                                 if (e != JIM_OK) {
3602                                         return e;
3603                                 }
3604                                 target->working_area_virt = w;
3605                         } else {
3606                                 if (goi->argc != 0) {
3607                                         goto no_params;
3608                                 }
3609                         }
3610                         Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3611                         /* loop for more */
3612                         break;
3613
3614                 case TCFG_WORK_AREA_PHYS:
3615                         if (goi->isconfigure) {
3616                                 target_free_all_working_areas(target);
3617                                 e = Jim_GetOpt_Wide(goi, &w);
3618                                 if (e != JIM_OK) {
3619                                         return e;
3620                                 }
3621                                 target->working_area_phys = w;
3622                         } else {
3623                                 if (goi->argc != 0) {
3624                                         goto no_params;
3625                                 }
3626                         }
3627                         Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3628                         /* loop for more */
3629                         break;
3630
3631                 case TCFG_WORK_AREA_SIZE:
3632                         if (goi->isconfigure) {
3633                                 target_free_all_working_areas(target);
3634                                 e = Jim_GetOpt_Wide(goi, &w);
3635                                 if (e != JIM_OK) {
3636                                         return e;
3637                                 }
3638                                 target->working_area_size = w;
3639                         } else {
3640                                 if (goi->argc != 0) {
3641                                         goto no_params;
3642                                 }
3643                         }
3644                         Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3645                         /* loop for more */
3646                         break;
3647
3648                 case TCFG_WORK_AREA_BACKUP:
3649                         if (goi->isconfigure) {
3650                                 target_free_all_working_areas(target);
3651                                 e = Jim_GetOpt_Wide(goi, &w);
3652                                 if (e != JIM_OK) {
3653                                         return e;
3654                                 }
3655                                 /* make this exactly 1 or 0 */
3656                                 target->backup_working_area = (!!w);
3657                         } else {
3658                                 if (goi->argc != 0) {
3659                                         goto no_params;
3660                                 }
3661                         }
3662                         Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3663                         /* loop for more e*/
3664                         break;
3665
3666                 case TCFG_ENDIAN:
3667                         if (goi->isconfigure) {
3668                                 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3669                                 if (e != JIM_OK) {
3670                                         Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3671                                         return e;
3672                                 }
3673                                 target->endianness = n->value;
3674                         } else {
3675                                 if (goi->argc != 0) {
3676                                         goto no_params;
3677                                 }
3678                         }
3679                         n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3680                         if (n->name == NULL) {
3681                                 target->endianness = TARGET_LITTLE_ENDIAN;
3682                                 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3683                         }
3684                         Jim_SetResultString(goi->interp, n->name, -1);
3685                         /* loop for more */
3686                         break;
3687
3688                 case TCFG_VARIANT:
3689                         if (goi->isconfigure) {
3690                                 if (goi->argc < 1) {
3691                                         Jim_SetResult_sprintf(goi->interp,
3692                                                                                    "%s ?STRING?",
3693                                                                                    n->name);
3694                                         return JIM_ERR;
3695                                 }
3696                                 if (target->variant) {
3697                                         free((void *)(target->variant));
3698                                 }
3699                                 e = Jim_GetOpt_String(goi, &cp, NULL);
3700                                 target->variant = strdup(cp);
3701                         } else {
3702                                 if (goi->argc != 0) {
3703                                         goto no_params;
3704                                 }
3705                         }
3706                         Jim_SetResultString(goi->interp, target->variant,-1);
3707                         /* loop for more */
3708                         break;
3709                 case TCFG_CHAIN_POSITION:
3710                         if (goi->isconfigure) {
3711                                 Jim_Obj *o;
3712                                 jtag_tap_t *tap;
3713                                 target_free_all_working_areas(target);
3714                                 e = Jim_GetOpt_Obj(goi, &o);
3715                                 if (e != JIM_OK) {
3716                                         return e;
3717                                 }
3718                                 tap = jtag_tap_by_jim_obj(goi->interp, o);
3719                                 if (tap == NULL) {
3720                                         return JIM_ERR;
3721                                 }
3722                                 /* make this exactly 1 or 0 */
3723                                 target->tap = tap;
3724                         } else {
3725                                 if (goi->argc != 0) {
3726                                         goto no_params;
3727                                 }
3728                         }
3729                         Jim_SetResultString(interp, target->tap->dotted_name, -1);
3730                         /* loop for more e*/
3731                         break;
3732                 }
3733         } /* while (goi->argc) */
3734
3735
3736                 /* done - we return */
3737         return JIM_OK;
3738 }
3739
3740 /** this is the 'tcl' handler for the target specific command */
3741 static int tcl_target_func(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3742 {
3743         Jim_GetOptInfo goi;
3744         jim_wide a,b,c;
3745         int x,y,z;
3746         uint8_t  target_buf[32];
3747         Jim_Nvp *n;
3748         target_t *target;
3749         struct command_context_s *cmd_ctx;
3750         int e;
3751
3752         enum {
3753                 TS_CMD_CONFIGURE,
3754                 TS_CMD_CGET,
3755
3756                 TS_CMD_MWW, TS_CMD_MWH, TS_CMD_MWB,
3757                 TS_CMD_MDW, TS_CMD_MDH, TS_CMD_MDB,
3758                 TS_CMD_MRW, TS_CMD_MRH, TS_CMD_MRB,
3759                 TS_CMD_MEM2ARRAY, TS_CMD_ARRAY2MEM,
3760                 TS_CMD_EXAMINE,
3761                 TS_CMD_POLL,
3762                 TS_CMD_RESET,
3763                 TS_CMD_HALT,
3764                 TS_CMD_WAITSTATE,
3765                 TS_CMD_EVENTLIST,
3766                 TS_CMD_CURSTATE,
3767                 TS_CMD_INVOKE_EVENT,
3768         };
3769
3770         static const Jim_Nvp target_options[] = {
3771                 { .name = "configure", .value = TS_CMD_CONFIGURE },
3772                 { .name = "cget", .value = TS_CMD_CGET },
3773                 { .name = "mww", .value = TS_CMD_MWW },
3774                 { .name = "mwh", .value = TS_CMD_MWH },
3775                 { .name = "mwb", .value = TS_CMD_MWB },
3776                 { .name = "mdw", .value = TS_CMD_MDW },
3777                 { .name = "mdh", .value = TS_CMD_MDH },
3778                 { .name = "mdb", .value = TS_CMD_MDB },
3779                 { .name = "mem2array", .value = TS_CMD_MEM2ARRAY },
3780                 { .name = "array2mem", .value = TS_CMD_ARRAY2MEM },
3781                 { .name = "eventlist", .value = TS_CMD_EVENTLIST },
3782                 { .name = "curstate",  .value = TS_CMD_CURSTATE },
3783
3784                 { .name = "arp_examine", .value = TS_CMD_EXAMINE },
3785                 { .name = "arp_poll", .value = TS_CMD_POLL },
3786                 { .name = "arp_reset", .value = TS_CMD_RESET },
3787                 { .name = "arp_halt", .value = TS_CMD_HALT },
3788                 { .name = "arp_waitstate", .value = TS_CMD_WAITSTATE },
3789                 { .name = "invoke-event", .value = TS_CMD_INVOKE_EVENT },
3790
3791                 { .name = NULL, .value = -1 },
3792         };
3793
3794         /* go past the "command" */
3795         Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
3796
3797         target = Jim_CmdPrivData(goi.interp);
3798         cmd_ctx = Jim_GetAssocData(goi.interp, "context");
3799
3800         /* commands here are in an NVP table */
3801         e = Jim_GetOpt_Nvp(&goi, target_options, &n);
3802         if (e != JIM_OK) {
3803                 Jim_GetOpt_NvpUnknown(&goi, target_options, 0);
3804                 return e;
3805         }
3806         /* Assume blank result */
3807         Jim_SetEmptyResult(goi.interp);
3808
3809         switch (n->value) {
3810         case TS_CMD_CONFIGURE:
3811                 if (goi.argc < 2) {
3812                         Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "missing: -option VALUE ...");
3813                         return JIM_ERR;
3814                 }
3815                 goi.isconfigure = 1;
3816                 return target_configure(&goi, target);
3817         case TS_CMD_CGET:
3818                 // some things take params
3819                 if (goi.argc < 1) {
3820                         Jim_WrongNumArgs(goi.interp, 0, goi.argv, "missing: ?-option?");
3821                         return JIM_ERR;
3822                 }
3823                 goi.isconfigure = 0;
3824                 return target_configure(&goi, target);
3825                 break;
3826         case TS_CMD_MWW:
3827         case TS_CMD_MWH:
3828         case TS_CMD_MWB:
3829                 /* argv[0] = cmd
3830                  * argv[1] = address
3831                  * argv[2] = data
3832                  * argv[3] = optional count.
3833                  */
3834
3835                 if ((goi.argc == 2) || (goi.argc == 3)) {
3836                         /* all is well */
3837                 } else {
3838                 mwx_error:
3839                         Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR DATA [COUNT]", n->name);
3840                         return JIM_ERR;
3841                 }
3842
3843                 e = Jim_GetOpt_Wide(&goi, &a);
3844                 if (e != JIM_OK) {
3845                         goto mwx_error;
3846                 }
3847
3848                 e = Jim_GetOpt_Wide(&goi, &b);
3849                 if (e != JIM_OK) {
3850                         goto mwx_error;
3851                 }
3852                 if (goi.argc == 3) {
3853                         e = Jim_GetOpt_Wide(&goi, &c);
3854                         if (e != JIM_OK) {
3855                                 goto mwx_error;
3856                         }
3857                 } else {
3858                         c = 1;
3859                 }
3860
3861                 switch (n->value) {
3862                 case TS_CMD_MWW:
3863                         target_buffer_set_u32(target, target_buf, b);
3864                         b = 4;
3865                         break;
3866                 case TS_CMD_MWH:
3867                         target_buffer_set_u16(target, target_buf, b);
3868                         b = 2;
3869                         break;
3870                 case TS_CMD_MWB:
3871                         target_buffer_set_u8(target, target_buf, b);
3872                         b = 1;
3873                         break;
3874                 }
3875                 for (x = 0 ; x < c ; x++) {
3876                         e = target_write_memory(target, a, b, 1, target_buf);
3877                         if (e != ERROR_OK) {
3878                                 Jim_SetResult_sprintf(interp, "Error writing @ 0x%08x: %d\n", (int)(a), e);
3879                                 return JIM_ERR;
3880                         }
3881                         /* b = width */
3882                         a = a + b;
3883                 }
3884                 return JIM_OK;
3885                 break;
3886
3887                 /* display */
3888         case TS_CMD_MDW:
3889         case TS_CMD_MDH:
3890         case TS_CMD_MDB:
3891                 /* argv[0] = command
3892                  * argv[1] = address
3893                  * argv[2] = optional count
3894                  */
3895                 if ((goi.argc == 2) || (goi.argc == 3)) {
3896                         Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR [COUNT]", n->name);
3897                         return JIM_ERR;
3898                 }
3899                 e = Jim_GetOpt_Wide(&goi, &a);
3900                 if (e != JIM_OK) {
3901                         return JIM_ERR;
3902                 }
3903                 if (goi.argc) {
3904                         e = Jim_GetOpt_Wide(&goi, &c);
3905                         if (e != JIM_OK) {
3906                                 return JIM_ERR;
3907                         }
3908                 } else {
3909                         c = 1;
3910                 }
3911                 b = 1; /* shut up gcc */
3912                 switch (n->value) {
3913                 case TS_CMD_MDW:
3914                         b =  4;
3915                         break;
3916                 case TS_CMD_MDH:
3917                         b = 2;
3918                         break;
3919                 case TS_CMD_MDB:
3920                         b = 1;
3921                         break;
3922                 }
3923
3924                 /* convert to "bytes" */
3925                 c = c * b;
3926                 /* count is now in 'BYTES' */
3927                 while (c > 0) {
3928                         y = c;
3929                         if (y > 16) {
3930                                 y = 16;
3931                         }
3932                         e = target_read_memory(target, a, b, y / b, target_buf);
3933                         if (e != ERROR_OK) {
3934                                 Jim_SetResult_sprintf(interp, "error reading target @ 0x%08lx", (int)(a));
3935                                 return JIM_ERR;
3936                         }
3937
3938                         Jim_fprintf(interp, interp->cookie_stdout, "0x%08x ", (int)(a));
3939                         switch (b) {
3940                         case 4:
3941                                 for (x = 0 ; (x < 16) && (x < y) ; x += 4) {
3942                                         z = target_buffer_get_u32(target, &(target_buf[ x * 4 ]));
3943                                         Jim_fprintf(interp, interp->cookie_stdout, "%08x ", (int)(z));
3944                                 }
3945                                 for (; (x < 16) ; x += 4) {
3946                                         Jim_fprintf(interp, interp->cookie_stdout, "         ");
3947                                 }
3948                                 break;
3949                         case 2:
3950                                 for (x = 0 ; (x < 16) && (x < y) ; x += 2) {
3951                                         z = target_buffer_get_u16(target, &(target_buf[ x * 2 ]));
3952                                         Jim_fprintf(interp, interp->cookie_stdout, "%04x ", (int)(z));
3953                                 }
3954                                 for (; (x < 16) ; x += 2) {
3955                                         Jim_fprintf(interp, interp->cookie_stdout, "     ");
3956                                 }
3957                                 break;
3958                         case 1:
3959                         default:
3960                                 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
3961                                         z = target_buffer_get_u8(target, &(target_buf[ x * 4 ]));
3962                                         Jim_fprintf(interp, interp->cookie_stdout, "%02x ", (int)(z));
3963                                 }
3964                                 for (; (x < 16) ; x += 1) {
3965                                         Jim_fprintf(interp, interp->cookie_stdout, "   ");
3966                                 }
3967                                 break;
3968                         }
3969                         /* ascii-ify the bytes */
3970                         for (x = 0 ; x < y ; x++) {
3971                                 if ((target_buf[x] >= 0x20) &&
3972                                         (target_buf[x] <= 0x7e)) {
3973                                         /* good */
3974                                 } else {
3975                                         /* smack it */
3976                                         target_buf[x] = '.';
3977                                 }
3978                         }
3979                         /* space pad  */
3980                         while (x < 16) {
3981                                 target_buf[x] = ' ';
3982                                 x++;
3983                         }
3984                         /* terminate */
3985                         target_buf[16] = 0;
3986                         /* print - with a newline */
3987                         Jim_fprintf(interp, interp->cookie_stdout, "%s\n", target_buf);
3988                         /* NEXT... */
3989                         c -= 16;
3990                         a += 16;
3991                 }
3992                 return JIM_OK;
3993         case TS_CMD_MEM2ARRAY:
3994                 return target_mem2array(goi.interp, target, goi.argc, goi.argv);
3995                 break;
3996         case TS_CMD_ARRAY2MEM:
3997                 return target_array2mem(goi.interp, target, goi.argc, goi.argv);
3998                 break;
3999         case TS_CMD_EXAMINE:
4000                 if (goi.argc) {
4001                         Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4002                         return JIM_ERR;
4003                 }
4004                 if (!target->tap->enabled)
4005                         goto err_tap_disabled;
4006                 e = target->type->examine(target);
4007                 if (e != ERROR_OK) {
4008                         Jim_SetResult_sprintf(interp, "examine-fails: %d", e);
4009                         return JIM_ERR;
4010                 }
4011                 return JIM_OK;
4012         case TS_CMD_POLL:
4013                 if (goi.argc) {
4014                         Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4015                         return JIM_ERR;
4016                 }
4017                 if (!target->tap->enabled)
4018                         goto err_tap_disabled;
4019                 if (!(target_was_examined(target))) {
4020                         e = ERROR_TARGET_NOT_EXAMINED;
4021                 } else {
4022                         e = target->type->poll(target);
4023                 }
4024                 if (e != ERROR_OK) {
4025                         Jim_SetResult_sprintf(interp, "poll-fails: %d", e);
4026                         return JIM_ERR;
4027                 } else {
4028                         return JIM_OK;
4029                 }
4030                 break;
4031         case TS_CMD_RESET:
4032                 if (goi.argc != 2) {
4033                         Jim_WrongNumArgs(interp, 2, argv,
4034                                         "([tT]|[fF]|assert|deassert) BOOL");
4035                         return JIM_ERR;
4036                 }
4037                 e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4038                 if (e != JIM_OK) {
4039                         Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4040                         return e;
4041                 }
4042                 /* the halt or not param */
4043                 e = Jim_GetOpt_Wide(&goi, &a);
4044                 if (e != JIM_OK) {
4045                         return e;
4046                 }
4047                 if (!target->tap->enabled)
4048                         goto err_tap_disabled;
4049                 if (!target->type->assert_reset
4050                                 || !target->type->deassert_reset) {
4051                         Jim_SetResult_sprintf(interp,
4052                                         "No target-specific reset for %s",
4053                                         target->cmd_name);
4054                         return JIM_ERR;
4055                 }
4056                 /* determine if we should halt or not. */
4057                 target->reset_halt = !!a;
4058                 /* When this happens - all workareas are invalid. */
4059                 target_free_all_working_areas_restore(target, 0);
4060
4061                 /* do the assert */
4062                 if (n->value == NVP_ASSERT) {
4063                         target->type->assert_reset(target);
4064                 } else {
4065                         target->type->deassert_reset(target);
4066                 }
4067                 return JIM_OK;
4068         case TS_CMD_HALT:
4069                 if (goi.argc) {
4070                         Jim_WrongNumArgs(goi.interp, 0, argv, "halt [no parameters]");
4071                         return JIM_ERR;
4072                 }
4073                 if (!target->tap->enabled)
4074                         goto err_tap_disabled;
4075                 target->type->halt(target);
4076                 return JIM_OK;
4077         case TS_CMD_WAITSTATE:
4078                 /* params:  <name>  statename timeoutmsecs */
4079                 if (goi.argc != 2) {
4080                         Jim_SetResult_sprintf(goi.interp, "%s STATENAME TIMEOUTMSECS", n->name);
4081                         return JIM_ERR;
4082                 }
4083                 e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4084                 if (e != JIM_OK) {
4085                         Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4086                         return e;
4087                 }
4088                 e = Jim_GetOpt_Wide(&goi, &a);
4089                 if (e != JIM_OK) {
4090                         return e;
4091                 }
4092                 if (!target->tap->enabled)
4093                         goto err_tap_disabled;
4094                 e = target_wait_state(target, n->value, a);
4095                 if (e != ERROR_OK) {
4096                         Jim_SetResult_sprintf(goi.interp,
4097                                                                    "target: %s wait %s fails (%d) %s",
4098                                                                    target->cmd_name,
4099                                                                    n->name,
4100                                                                    e, target_strerror_safe(e));
4101                         return JIM_ERR;
4102                 } else {
4103                         return JIM_OK;
4104                 }
4105         case TS_CMD_EVENTLIST:
4106                 /* List for human, Events defined for this target.
4107                  * scripts/programs should use 'name cget -event NAME'
4108                  */
4109                 {
4110                         target_event_action_t *teap;
4111                         teap = target->event_action;
4112                         command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4113                                                    target->target_number,
4114                                                    target->cmd_name);
4115                         command_print(cmd_ctx, "%-25s | Body", "Event");
4116                         command_print(cmd_ctx, "------------------------- | ----------------------------------------");
4117                         while (teap) {
4118                                 command_print(cmd_ctx,
4119                                                            "%-25s | %s",
4120                                                            Jim_Nvp_value2name_simple(nvp_target_event, teap->event)->name,
4121                                                            Jim_GetString(teap->body, NULL));
4122                                 teap = teap->next;
4123                         }
4124                         command_print(cmd_ctx, "***END***");
4125                         return JIM_OK;
4126                 }
4127         case TS_CMD_CURSTATE:
4128                 if (goi.argc != 0) {
4129                         Jim_WrongNumArgs(goi.interp, 0, argv, "[no parameters]");
4130                         return JIM_ERR;
4131                 }
4132                 Jim_SetResultString(goi.interp,
4133                                                         target_state_name( target ),
4134                                                         -1);
4135                 return JIM_OK;
4136         case TS_CMD_INVOKE_EVENT:
4137                 if (goi.argc != 1) {
4138                         Jim_SetResult_sprintf(goi.interp, "%s ?EVENTNAME?",n->name);
4139                         return JIM_ERR;
4140                 }
4141                 e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4142                 if (e != JIM_OK) {
4143                         Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4144                         return e;
4145                 }
4146                 target_handle_event(target, n->value);
4147                 return JIM_OK;
4148         }
4149         return JIM_ERR;
4150
4151 err_tap_disabled:
4152         Jim_SetResult_sprintf(interp, "[TAP is disabled]");
4153         return JIM_ERR;
4154 }
4155
4156 static int target_create(Jim_GetOptInfo *goi)
4157 {
4158         Jim_Obj *new_cmd;
4159         Jim_Cmd *cmd;
4160         const char *cp;
4161         char *cp2;
4162         int e;
4163         int x;
4164         target_t *target;
4165         struct command_context_s *cmd_ctx;
4166
4167         cmd_ctx = Jim_GetAssocData(goi->interp, "context");
4168         if (goi->argc < 3) {
4169                 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4170                 return JIM_ERR;
4171         }
4172
4173         /* COMMAND */
4174         Jim_GetOpt_Obj(goi, &new_cmd);
4175         /* does this command exist? */
4176         cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4177         if (cmd) {
4178                 cp = Jim_GetString(new_cmd, NULL);
4179                 Jim_SetResult_sprintf(goi->interp, "Command/target: %s Exists", cp);
4180                 return JIM_ERR;
4181         }
4182
4183         /* TYPE */
4184         e = Jim_GetOpt_String(goi, &cp2, NULL);
4185         cp = cp2;
4186         /* now does target type exist */
4187         for (x = 0 ; target_types[x] ; x++) {
4188                 if (0 == strcmp(cp, target_types[x]->name)) {
4189                         /* found */
4190                         break;
4191                 }
4192         }
4193         if (target_types[x] == NULL) {
4194                 Jim_SetResult_sprintf(goi->interp, "Unknown target type %s, try one of ", cp);
4195                 for (x = 0 ; target_types[x] ; x++) {
4196                         if (target_types[x + 1]) {
4197                                 Jim_AppendStrings(goi->interp,
4198                                                                    Jim_GetResult(goi->interp),
4199                                                                    target_types[x]->name,
4200                                                                    ", ", NULL);
4201                         } else {
4202                                 Jim_AppendStrings(goi->interp,
4203                                                                    Jim_GetResult(goi->interp),
4204                                                                    " or ",
4205                                                                    target_types[x]->name,NULL);
4206                         }
4207                 }
4208                 return JIM_ERR;
4209         }
4210
4211         /* Create it */
4212         target = calloc(1,sizeof(target_t));
4213         /* set target number */
4214         target->target_number = new_target_number();
4215
4216         /* allocate memory for each unique target type */
4217         target->type = (target_type_t*)calloc(1,sizeof(target_type_t));
4218
4219         memcpy(target->type, target_types[x], sizeof(target_type_t));
4220
4221         /* will be set by "-endian" */
4222         target->endianness = TARGET_ENDIAN_UNKNOWN;
4223
4224         target->working_area        = 0x0;
4225         target->working_area_size   = 0x0;
4226         target->working_areas       = NULL;
4227         target->backup_working_area = 0;
4228
4229         target->state               = TARGET_UNKNOWN;
4230         target->debug_reason        = DBG_REASON_UNDEFINED;
4231         target->reg_cache           = NULL;
4232         target->breakpoints         = NULL;
4233         target->watchpoints         = NULL;
4234         target->next                = NULL;
4235         target->arch_info           = NULL;
4236
4237         target->display             = 1;
4238
4239         /* initialize trace information */
4240         target->trace_info = malloc(sizeof(trace_t));
4241         target->trace_info->num_trace_points         = 0;
4242         target->trace_info->trace_points_size        = 0;
4243         target->trace_info->trace_points             = NULL;
4244         target->trace_info->trace_history_size       = 0;
4245         target->trace_info->trace_history            = NULL;
4246         target->trace_info->trace_history_pos        = 0;
4247         target->trace_info->trace_history_overflowed = 0;
4248
4249         target->dbgmsg          = NULL;
4250         target->dbg_msg_enabled = 0;
4251
4252         target->endianness = TARGET_ENDIAN_UNKNOWN;
4253
4254         /* Do the rest as "configure" options */
4255         goi->isconfigure = 1;
4256         e = target_configure(goi, target);
4257
4258         if (target->tap == NULL)
4259         {
4260                 Jim_SetResultString(interp, "-chain-position required when creating target", -1);
4261                 e = JIM_ERR;
4262         }
4263
4264         if (e != JIM_OK) {
4265                 free(target->type);
4266                 free(target);
4267                 return e;
4268         }
4269
4270         if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4271                 /* default endian to little if not specified */
4272                 target->endianness = TARGET_LITTLE_ENDIAN;
4273         }
4274
4275         /* incase variant is not set */
4276         if (!target->variant)
4277                 target->variant = strdup("");
4278
4279         /* create the target specific commands */
4280         if (target->type->register_commands) {
4281                 (*(target->type->register_commands))(cmd_ctx);
4282         }
4283         if (target->type->target_create) {
4284                 (*(target->type->target_create))(target, goi->interp);
4285         }
4286
4287         /* append to end of list */
4288         {
4289                 target_t **tpp;
4290                 tpp = &(all_targets);
4291                 while (*tpp) {
4292                         tpp = &((*tpp)->next);
4293                 }
4294                 *tpp = target;
4295         }
4296
4297         cp = Jim_GetString(new_cmd, NULL);
4298         target->cmd_name = strdup(cp);
4299
4300         /* now - create the new target name command */
4301         e = Jim_CreateCommand(goi->interp,
4302                                                    /* name */
4303                                                    cp,
4304                                                    tcl_target_func, /* C function */
4305                                                    target, /* private data */
4306                                                    NULL); /* no del proc */
4307
4308         return e;
4309 }
4310
4311 static int jim_target(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4312 {
4313         int x,r,e;
4314         jim_wide w;
4315         struct command_context_s *cmd_ctx;
4316         target_t *target;
4317         Jim_GetOptInfo goi;
4318         enum tcmd {
4319                 /* TG = target generic */
4320                 TG_CMD_CREATE,
4321                 TG_CMD_TYPES,
4322                 TG_CMD_NAMES,
4323                 TG_CMD_CURRENT,
4324                 TG_CMD_NUMBER,
4325                 TG_CMD_COUNT,
4326         };
4327         const char *target_cmds[] = {
4328                 "create", "types", "names", "current", "number",
4329                 "count",
4330                 NULL /* terminate */
4331         };
4332
4333         LOG_DEBUG("Target command params:");
4334         LOG_DEBUG("%s", Jim_Debug_ArgvString(interp, argc, argv));
4335
4336         cmd_ctx = Jim_GetAssocData(interp, "context");
4337
4338         Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
4339
4340         if (goi.argc == 0) {
4341                 Jim_WrongNumArgs(interp, 1, argv, "missing: command ...");
4342                 return JIM_ERR;
4343         }
4344
4345         /* Jim_GetOpt_Debug(&goi); */
4346         r = Jim_GetOpt_Enum(&goi, target_cmds, &x);
4347         if (r != JIM_OK) {
4348                 return r;
4349         }
4350
4351         switch (x) {
4352         default:
4353                 Jim_Panic(goi.interp,"Why am I here?");
4354                 return JIM_ERR;
4355         case TG_CMD_CURRENT:
4356                 if (goi.argc != 0) {
4357                         Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4358                         return JIM_ERR;
4359                 }
4360                 Jim_SetResultString(goi.interp, get_current_target(cmd_ctx)->cmd_name, -1);
4361                 return JIM_OK;
4362         case TG_CMD_TYPES:
4363                 if (goi.argc != 0) {
4364                         Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4365                         return JIM_ERR;
4366                 }
4367                 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4368                 for (x = 0 ; target_types[x] ; x++) {
4369                         Jim_ListAppendElement(goi.interp,
4370                                                                    Jim_GetResult(goi.interp),
4371                                                                    Jim_NewStringObj(goi.interp, target_types[x]->name, -1));
4372                 }
4373                 return JIM_OK;
4374         case TG_CMD_NAMES:
4375                 if (goi.argc != 0) {
4376                         Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4377                         return JIM_ERR;
4378                 }
4379                 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4380                 target = all_targets;
4381                 while (target) {
4382                         Jim_ListAppendElement(goi.interp,
4383                                                                    Jim_GetResult(goi.interp),
4384                                                                    Jim_NewStringObj(goi.interp, target->cmd_name, -1));
4385                         target = target->next;
4386                 }
4387                 return JIM_OK;
4388         case TG_CMD_CREATE:
4389                 if (goi.argc < 3) {
4390                         Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "?name  ... config options ...");
4391                         return JIM_ERR;
4392                 }
4393                 return target_create(&goi);
4394                 break;
4395         case TG_CMD_NUMBER:
4396                 /* It's OK to remove this mechanism sometime after August 2010 or so */
4397                 LOG_WARNING("don't use numbers as target identifiers; use names");
4398                 if (goi.argc != 1) {
4399                         Jim_SetResult_sprintf(goi.interp, "expected: target number ?NUMBER?");
4400                         return JIM_ERR;
4401                 }
4402                 e = Jim_GetOpt_Wide(&goi, &w);
4403                 if (e != JIM_OK) {
4404                         return JIM_ERR;
4405                 }
4406                 for (x = 0, target = all_targets; target; target = target->next, x++) {
4407                         if (target->target_number == w)
4408                                 break;
4409                 }
4410                 if (target == NULL) {
4411                         Jim_SetResult_sprintf(goi.interp,
4412                                         "Target: number %d does not exist", (int)(w));
4413                         return JIM_ERR;
4414                 }
4415                 Jim_SetResultString(goi.interp, target->cmd_name, -1);
4416                 return JIM_OK;
4417         case TG_CMD_COUNT:
4418                 if (goi.argc != 0) {
4419                         Jim_WrongNumArgs(goi.interp, 0, goi.argv, "<no parameters>");
4420                         return JIM_ERR;
4421                 }
4422                 for (x = 0, target = all_targets; target; target = target->next, x++)
4423                         continue;
4424                 Jim_SetResult(goi.interp, Jim_NewIntObj(goi.interp, x));
4425                 return JIM_OK;
4426         }
4427
4428         return JIM_ERR;
4429 }
4430
4431
4432 struct FastLoad
4433 {
4434         uint32_t address;
4435         uint8_t *data;
4436         int length;
4437
4438 };
4439
4440 static int fastload_num;
4441 static struct FastLoad *fastload;
4442
4443 static void free_fastload(void)
4444 {
4445         if (fastload != NULL)
4446         {
4447                 int i;
4448                 for (i = 0; i < fastload_num; i++)
4449                 {
4450                         if (fastload[i].data)
4451                                 free(fastload[i].data);
4452                 }
4453                 free(fastload);
4454                 fastload = NULL;
4455         }
4456 }
4457
4458
4459
4460
4461 static int handle_fast_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
4462 {
4463         uint8_t *buffer;
4464         uint32_t buf_cnt;
4465         uint32_t image_size;
4466         uint32_t min_address = 0;
4467         uint32_t max_address = 0xffffffff;
4468         int i;
4469
4470         image_t image;
4471
4472         duration_t duration;
4473         char *duration_text;
4474
4475         int retval = parse_load_image_command_args(args, argc,
4476                         &image, &min_address, &max_address);
4477         if (ERROR_OK != retval)
4478                 return retval;
4479
4480         duration_start_measure(&duration);
4481
4482         if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
4483         {
4484                 return ERROR_OK;
4485         }
4486
4487         image_size = 0x0;
4488         retval = ERROR_OK;
4489         fastload_num = image.num_sections;
4490         fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
4491         if (fastload == NULL)
4492         {
4493                 image_close(&image);
4494                 return ERROR_FAIL;
4495         }
4496         memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
4497         for (i = 0; i < image.num_sections; i++)
4498         {
4499                 buffer = malloc(image.sections[i].size);
4500                 if (buffer == NULL)
4501                 {
4502                         command_print(cmd_ctx, "error allocating buffer for section (%d bytes)",
4503                                                   (int)(image.sections[i].size));
4504                         break;
4505                 }
4506
4507                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
4508                 {
4509                         free(buffer);
4510                         break;
4511                 }
4512
4513                 uint32_t offset = 0;
4514                 uint32_t length = buf_cnt;
4515
4516
4517                 /* DANGER!!! beware of unsigned comparision here!!! */
4518
4519                 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
4520                                 (image.sections[i].base_address < max_address))
4521                 {
4522                         if (image.sections[i].base_address < min_address)
4523                         {
4524                                 /* clip addresses below */
4525                                 offset += min_address-image.sections[i].base_address;
4526                                 length -= offset;
4527                         }
4528
4529                         if (image.sections[i].base_address + buf_cnt > max_address)
4530                         {
4531                                 length -= (image.sections[i].base_address + buf_cnt)-max_address;
4532                         }
4533
4534                         fastload[i].address = image.sections[i].base_address + offset;
4535                         fastload[i].data = malloc(length);
4536                         if (fastload[i].data == NULL)
4537                         {
4538                                 free(buffer);
4539                                 break;
4540                         }
4541                         memcpy(fastload[i].data, buffer + offset, length);
4542                         fastload[i].length = length;
4543
4544                         image_size += length;
4545                         command_print(cmd_ctx, "%u bytes written at address 0x%8.8x",
4546                                                   (unsigned int)length,
4547                                                   ((unsigned int)(image.sections[i].base_address + offset)));
4548                 }
4549
4550                 free(buffer);
4551         }
4552
4553         duration_stop_measure(&duration, &duration_text);
4554         if (retval == ERROR_OK)
4555         {
4556                 command_print(cmd_ctx, "Loaded %u bytes in %s", (unsigned int)image_size, duration_text);
4557                 command_print(cmd_ctx, "NB!!! image has not been loaded to target, issue a subsequent 'fast_load' to do so.");
4558         }
4559         free(duration_text);
4560
4561         image_close(&image);
4562
4563         if (retval != ERROR_OK)
4564         {
4565                 free_fastload();
4566         }
4567
4568         return retval;
4569 }
4570
4571 static int handle_fast_load_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
4572 {
4573         if (argc > 0)
4574                 return ERROR_COMMAND_SYNTAX_ERROR;
4575         if (fastload == NULL)
4576         {
4577                 LOG_ERROR("No image in memory");
4578                 return ERROR_FAIL;
4579         }
4580         int i;
4581         int ms = timeval_ms();
4582         int size = 0;
4583         int retval = ERROR_OK;
4584         for (i = 0; i < fastload_num;i++)
4585         {
4586                 target_t *target = get_current_target(cmd_ctx);
4587                 command_print(cmd_ctx, "Write to 0x%08x, length 0x%08x",
4588                                           (unsigned int)(fastload[i].address),
4589                                           (unsigned int)(fastload[i].length));
4590                 if (retval == ERROR_OK)
4591                 {
4592                         retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
4593                 }
4594                 size += fastload[i].length;
4595         }
4596         int after = timeval_ms();
4597         command_print(cmd_ctx, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
4598         return retval;
4599 }
4600
4601
4602 /*
4603  * Local Variables:
4604  * c-basic-offset: 4
4605  * tab-width: 4
4606  * End:
4607  */