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