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