have "reg" command print cache names too
[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                         command_print(cmd_ctx, "===== %s", cache->name);
1827
1828                         for (i = 0, reg = cache->reg_list;
1829                                         i < cache->num_regs;
1830                                         i++, reg++, count++)
1831                         {
1832                                 /* only print cached values if they are valid */
1833                                 if (reg->valid) {
1834                                         value = buf_to_str(reg->value,
1835                                                         reg->size, 16);
1836                                         command_print(cmd_ctx,
1837                                                         "(%i) %s (/%" PRIu32 "): 0x%s%s",
1838                                                         count, reg->name,
1839                                                         reg->size, value,
1840                                                         reg->dirty
1841                                                                 ? " (dirty)"
1842                                                                 : "");
1843                                         free(value);
1844                                 } else {
1845                                         command_print(cmd_ctx, "(%i) %s (/%" PRIu32 ")",
1846                                                           count, reg->name,
1847                                                           reg->size) ;
1848                                 }
1849                         }
1850                         cache = cache->next;
1851                 }
1852
1853                 return ERROR_OK;
1854         }
1855
1856         /* access a single register by its ordinal number */
1857         if ((args[0][0] >= '0') && (args[0][0] <= '9'))
1858         {
1859                 unsigned num;
1860                 int retval = parse_uint(args[0], &num);
1861                 if (ERROR_OK != retval)
1862                         return ERROR_COMMAND_SYNTAX_ERROR;
1863
1864                 reg_cache_t *cache = target->reg_cache;
1865                 count = 0;
1866                 while (cache)
1867                 {
1868                         int i;
1869                         for (i = 0; i < cache->num_regs; i++)
1870                         {
1871                                 if (count++ == (int)num)
1872                                 {
1873                                         reg = &cache->reg_list[i];
1874                                         break;
1875                                 }
1876                         }
1877                         if (reg)
1878                                 break;
1879                         cache = cache->next;
1880                 }
1881
1882                 if (!reg)
1883                 {
1884                         command_print(cmd_ctx, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
1885                         return ERROR_OK;
1886                 }
1887         } else /* access a single register by its name */
1888         {
1889                 reg = register_get_by_name(target->reg_cache, args[0], 1);
1890
1891                 if (!reg)
1892                 {
1893                         command_print(cmd_ctx, "register %s not found in current target", args[0]);
1894                         return ERROR_OK;
1895                 }
1896         }
1897
1898         /* display a register */
1899         if ((argc == 1) || ((argc == 2) && !((args[1][0] >= '0') && (args[1][0] <= '9'))))
1900         {
1901                 if ((argc == 2) && (strcmp(args[1], "force") == 0))
1902                         reg->valid = 0;
1903
1904                 if (reg->valid == 0)
1905                 {
1906                         reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
1907                         arch_type->get(reg);
1908                 }
1909                 value = buf_to_str(reg->value, reg->size, 16);
1910                 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1911                 free(value);
1912                 return ERROR_OK;
1913         }
1914
1915         /* set register value */
1916         if (argc == 2)
1917         {
1918                 uint8_t *buf = malloc(CEIL(reg->size, 8));
1919                 str_to_buf(args[1], strlen(args[1]), buf, reg->size, 0);
1920
1921                 reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
1922                 arch_type->set(reg, buf);
1923
1924                 value = buf_to_str(reg->value, reg->size, 16);
1925                 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1926                 free(value);
1927
1928                 free(buf);
1929
1930                 return ERROR_OK;
1931         }
1932
1933         command_print(cmd_ctx, "usage: reg <#|name> [value]");
1934
1935         return ERROR_OK;
1936 }
1937
1938 static int handle_poll_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1939 {
1940         int retval = ERROR_OK;
1941         target_t *target = get_current_target(cmd_ctx);
1942
1943         if (argc == 0)
1944         {
1945                 command_print(cmd_ctx, "background polling: %s",
1946                                 jtag_poll_get_enabled() ? "on" : "off");
1947                 command_print(cmd_ctx, "TAP: %s (%s)",
1948                                 target->tap->dotted_name,
1949                                 target->tap->enabled ? "enabled" : "disabled");
1950                 if (!target->tap->enabled)
1951                         return ERROR_OK;
1952                 if ((retval = target_poll(target)) != ERROR_OK)
1953                         return retval;
1954                 if ((retval = target_arch_state(target)) != ERROR_OK)
1955                         return retval;
1956
1957         }
1958         else if (argc == 1)
1959         {
1960                 if (strcmp(args[0], "on") == 0)
1961                 {
1962                         jtag_poll_set_enabled(true);
1963                 }
1964                 else if (strcmp(args[0], "off") == 0)
1965                 {
1966                         jtag_poll_set_enabled(false);
1967                 }
1968                 else
1969                 {
1970                         command_print(cmd_ctx, "arg is \"on\" or \"off\"");
1971                 }
1972         } else
1973         {
1974                 return ERROR_COMMAND_SYNTAX_ERROR;
1975         }
1976
1977         return retval;
1978 }
1979
1980 static int handle_wait_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1981 {
1982         if (argc > 1)
1983                 return ERROR_COMMAND_SYNTAX_ERROR;
1984
1985         unsigned ms = 5000;
1986         if (1 == argc)
1987         {
1988                 int retval = parse_uint(args[0], &ms);
1989                 if (ERROR_OK != retval)
1990                 {
1991                         command_print(cmd_ctx, "usage: %s [seconds]", cmd);
1992                         return ERROR_COMMAND_SYNTAX_ERROR;
1993                 }
1994                 // convert seconds (given) to milliseconds (needed)
1995                 ms *= 1000;
1996         }
1997
1998         target_t *target = get_current_target(cmd_ctx);
1999         return target_wait_state(target, TARGET_HALTED, ms);
2000 }
2001
2002 /* wait for target state to change. The trick here is to have a low
2003  * latency for short waits and not to suck up all the CPU time
2004  * on longer waits.
2005  *
2006  * After 500ms, keep_alive() is invoked
2007  */
2008 int target_wait_state(target_t *target, enum target_state state, int ms)
2009 {
2010         int retval;
2011         long long then = 0, cur;
2012         int once = 1;
2013
2014         for (;;)
2015         {
2016                 if ((retval = target_poll(target)) != ERROR_OK)
2017                         return retval;
2018                 if (target->state == state)
2019                 {
2020                         break;
2021                 }
2022                 cur = timeval_ms();
2023                 if (once)
2024                 {
2025                         once = 0;
2026                         then = timeval_ms();
2027                         LOG_DEBUG("waiting for target %s...",
2028                                 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2029                 }
2030
2031                 if (cur-then > 500)
2032                 {
2033                         keep_alive();
2034                 }
2035
2036                 if ((cur-then) > ms)
2037                 {
2038                         LOG_ERROR("timed out while waiting for target %s",
2039                                 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2040                         return ERROR_FAIL;
2041                 }
2042         }
2043
2044         return ERROR_OK;
2045 }
2046
2047 static int handle_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2048 {
2049         LOG_DEBUG("-");
2050
2051         target_t *target = get_current_target(cmd_ctx);
2052         int retval = target_halt(target);
2053         if (ERROR_OK != retval)
2054                 return retval;
2055
2056         if (argc == 1)
2057         {
2058                 unsigned wait;
2059                 retval = parse_uint(args[0], &wait);
2060                 if (ERROR_OK != retval)
2061                         return ERROR_COMMAND_SYNTAX_ERROR;
2062                 if (!wait)
2063                         return ERROR_OK;
2064         }
2065
2066         return handle_wait_halt_command(cmd_ctx, cmd, args, argc);
2067 }
2068
2069 static int handle_soft_reset_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2070 {
2071         target_t *target = get_current_target(cmd_ctx);
2072
2073         LOG_USER("requesting target halt and executing a soft reset");
2074
2075         target->type->soft_reset_halt(target);
2076
2077         return ERROR_OK;
2078 }
2079
2080 static int handle_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2081 {
2082         if (argc > 1)
2083                 return ERROR_COMMAND_SYNTAX_ERROR;
2084
2085         enum target_reset_mode reset_mode = RESET_RUN;
2086         if (argc == 1)
2087         {
2088                 const Jim_Nvp *n;
2089                 n = Jim_Nvp_name2value_simple(nvp_reset_modes, args[0]);
2090                 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2091                         return ERROR_COMMAND_SYNTAX_ERROR;
2092                 }
2093                 reset_mode = n->value;
2094         }
2095
2096         /* reset *all* targets */
2097         return target_process_reset(cmd_ctx, reset_mode);
2098 }
2099
2100
2101 static int handle_resume_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2102 {
2103         int current = 1;
2104         if (argc > 1)
2105                 return ERROR_COMMAND_SYNTAX_ERROR;
2106
2107         target_t *target = get_current_target(cmd_ctx);
2108         target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2109
2110         /* with no args, resume from current pc, addr = 0,
2111          * with one arguments, addr = args[0],
2112          * handle breakpoints, not debugging */
2113         uint32_t addr = 0;
2114         if (argc == 1)
2115         {
2116                 int retval = parse_u32(args[0], &addr);
2117                 if (ERROR_OK != retval)
2118                         return retval;
2119                 current = 0;
2120         }
2121
2122         return target_resume(target, current, addr, 1, 0);
2123 }
2124
2125 static int handle_step_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2126 {
2127         if (argc > 1)
2128                 return ERROR_COMMAND_SYNTAX_ERROR;
2129
2130         LOG_DEBUG("-");
2131
2132         /* with no args, step from current pc, addr = 0,
2133          * with one argument addr = args[0],
2134          * handle breakpoints, debugging */
2135         uint32_t addr = 0;
2136         int current_pc = 1;
2137         if (argc == 1)
2138         {
2139                 int retval = parse_u32(args[0], &addr);
2140                 if (ERROR_OK != retval)
2141                         return retval;
2142                 current_pc = 0;
2143         }
2144
2145         target_t *target = get_current_target(cmd_ctx);
2146
2147         return target->type->step(target, current_pc, addr, 1);
2148 }
2149
2150 static void handle_md_output(struct command_context_s *cmd_ctx,
2151                 struct target_s *target, uint32_t address, unsigned size,
2152                 unsigned count, const uint8_t *buffer)
2153 {
2154         const unsigned line_bytecnt = 32;
2155         unsigned line_modulo = line_bytecnt / size;
2156
2157         char output[line_bytecnt * 4 + 1];
2158         unsigned output_len = 0;
2159
2160         const char *value_fmt;
2161         switch (size) {
2162         case 4: value_fmt = "%8.8x "; break;
2163         case 2: value_fmt = "%4.2x "; break;
2164         case 1: value_fmt = "%2.2x "; break;
2165         default:
2166                 LOG_ERROR("invalid memory read size: %u", size);
2167                 exit(-1);
2168         }
2169
2170         for (unsigned i = 0; i < count; i++)
2171         {
2172                 if (i % line_modulo == 0)
2173                 {
2174                         output_len += snprintf(output + output_len,
2175                                         sizeof(output) - output_len,
2176                                         "0x%8.8x: ",
2177                                         (unsigned)(address + (i*size)));
2178                 }
2179
2180                 uint32_t value = 0;
2181                 const uint8_t *value_ptr = buffer + i * size;
2182                 switch (size) {
2183                 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2184                 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2185                 case 1: value = *value_ptr;
2186                 }
2187                 output_len += snprintf(output + output_len,
2188                                 sizeof(output) - output_len,
2189                                 value_fmt, value);
2190
2191                 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2192                 {
2193                         command_print(cmd_ctx, "%s", output);
2194                         output_len = 0;
2195                 }
2196         }
2197 }
2198
2199 static int handle_md_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2200 {
2201         if (argc < 1)
2202                 return ERROR_COMMAND_SYNTAX_ERROR;
2203
2204         unsigned size = 0;
2205         switch (cmd[2]) {
2206         case 'w': size = 4; break;
2207         case 'h': size = 2; break;
2208         case 'b': size = 1; break;
2209         default: return ERROR_COMMAND_SYNTAX_ERROR;
2210         }
2211
2212         bool physical=strcmp(args[0], "phys")==0;
2213         int (*fn)(struct target_s *target,
2214                         uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2215         if (physical)
2216         {
2217                 argc--;
2218                 args++;
2219                 fn=target_read_phys_memory;
2220         } else
2221         {
2222                 fn=target_read_memory;
2223         }
2224         if ((argc < 1) || (argc > 2))
2225         {
2226                 return ERROR_COMMAND_SYNTAX_ERROR;
2227         }
2228         uint32_t address;
2229         int retval = parse_u32(args[0], &address);
2230         if (ERROR_OK != retval)
2231                 return retval;
2232
2233         unsigned count = 1;
2234         if (argc == 2)
2235         {
2236                 retval = parse_uint(args[1], &count);
2237                 if (ERROR_OK != retval)
2238                         return retval;
2239         }
2240
2241         uint8_t *buffer = calloc(count, size);
2242
2243         target_t *target = get_current_target(cmd_ctx);
2244         retval = fn(target, address, size, count, buffer);
2245         if (ERROR_OK == retval)
2246                 handle_md_output(cmd_ctx, target, address, size, count, buffer);
2247
2248         free(buffer);
2249
2250         return retval;
2251 }
2252
2253 static int handle_mw_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2254 {
2255         if (argc < 2)
2256         {
2257                 return ERROR_COMMAND_SYNTAX_ERROR;
2258         }
2259         bool physical=strcmp(args[0], "phys")==0;
2260         int (*fn)(struct target_s *target,
2261                         uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2262         if (physical)
2263         {
2264                 argc--;
2265                 args++;
2266                 fn=target_write_phys_memory;
2267         } else
2268         {
2269                 fn=target_write_memory;
2270         }
2271         if ((argc < 2) || (argc > 3))
2272                 return ERROR_COMMAND_SYNTAX_ERROR;
2273
2274         uint32_t address;
2275         int retval = parse_u32(args[0], &address);
2276         if (ERROR_OK != retval)
2277                 return retval;
2278
2279         uint32_t value;
2280         retval = parse_u32(args[1], &value);
2281         if (ERROR_OK != retval)
2282                 return retval;
2283
2284         unsigned count = 1;
2285         if (argc == 3)
2286         {
2287                 retval = parse_uint(args[2], &count);
2288                 if (ERROR_OK != retval)
2289                         return retval;
2290         }
2291
2292         target_t *target = get_current_target(cmd_ctx);
2293         unsigned wordsize;
2294         uint8_t value_buf[4];
2295         switch (cmd[2])
2296         {
2297                 case 'w':
2298                         wordsize = 4;
2299                         target_buffer_set_u32(target, value_buf, value);
2300                         break;
2301                 case 'h':
2302                         wordsize = 2;
2303                         target_buffer_set_u16(target, value_buf, value);
2304                         break;
2305                 case 'b':
2306                         wordsize = 1;
2307                         value_buf[0] = value;
2308                         break;
2309                 default:
2310                         return ERROR_COMMAND_SYNTAX_ERROR;
2311         }
2312         for (unsigned i = 0; i < count; i++)
2313         {
2314                 retval = fn(target,
2315                                 address + i * wordsize, wordsize, 1, value_buf);
2316                 if (ERROR_OK != retval)
2317                         return retval;
2318                 keep_alive();
2319         }
2320
2321         return ERROR_OK;
2322
2323 }
2324
2325 static int parse_load_image_command_args(char **args, int argc,
2326                 image_t *image, uint32_t *min_address, uint32_t *max_address)
2327 {
2328         if (argc < 1 || argc > 5)
2329                 return ERROR_COMMAND_SYNTAX_ERROR;
2330
2331         /* a base address isn't always necessary,
2332          * default to 0x0 (i.e. don't relocate) */
2333         if (argc >= 2)
2334         {
2335                 uint32_t addr;
2336                 int retval = parse_u32(args[1], &addr);
2337                 if (ERROR_OK != retval)
2338                         return ERROR_COMMAND_SYNTAX_ERROR;
2339                 image->base_address = addr;
2340                 image->base_address_set = 1;
2341         }
2342         else
2343                 image->base_address_set = 0;
2344
2345         image->start_address_set = 0;
2346
2347         if (argc >= 4)
2348         {
2349                 int retval = parse_u32(args[3], min_address);
2350                 if (ERROR_OK != retval)
2351                         return ERROR_COMMAND_SYNTAX_ERROR;
2352         }
2353         if (argc == 5)
2354         {
2355                 int retval = parse_u32(args[4], max_address);
2356                 if (ERROR_OK != retval)
2357                         return ERROR_COMMAND_SYNTAX_ERROR;
2358                 // use size (given) to find max (required)
2359                 *max_address += *min_address;
2360         }
2361
2362         if (*min_address > *max_address)
2363                 return ERROR_COMMAND_SYNTAX_ERROR;
2364
2365         return ERROR_OK;
2366 }
2367
2368 static int handle_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2369 {
2370         uint8_t *buffer;
2371         uint32_t buf_cnt;
2372         uint32_t image_size;
2373         uint32_t min_address = 0;
2374         uint32_t max_address = 0xffffffff;
2375         int i;
2376         int retvaltemp;
2377
2378         image_t image;
2379
2380         duration_t duration;
2381         char *duration_text;
2382
2383         int retval = parse_load_image_command_args(args, argc,
2384                         &image, &min_address, &max_address);
2385         if (ERROR_OK != retval)
2386                 return retval;
2387
2388         target_t *target = get_current_target(cmd_ctx);
2389         duration_start_measure(&duration);
2390
2391         if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
2392         {
2393                 return ERROR_OK;
2394         }
2395
2396         image_size = 0x0;
2397         retval = ERROR_OK;
2398         for (i = 0; i < image.num_sections; i++)
2399         {
2400                 buffer = malloc(image.sections[i].size);
2401                 if (buffer == NULL)
2402                 {
2403                         command_print(cmd_ctx,
2404                                                   "error allocating buffer for section (%d bytes)",
2405                                                   (int)(image.sections[i].size));
2406                         break;
2407                 }
2408
2409                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2410                 {
2411                         free(buffer);
2412                         break;
2413                 }
2414
2415                 uint32_t offset = 0;
2416                 uint32_t length = buf_cnt;
2417
2418                 /* DANGER!!! beware of unsigned comparision here!!! */
2419
2420                 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2421                                 (image.sections[i].base_address < max_address))
2422                 {
2423                         if (image.sections[i].base_address < min_address)
2424                         {
2425                                 /* clip addresses below */
2426                                 offset += min_address-image.sections[i].base_address;
2427                                 length -= offset;
2428                         }
2429
2430                         if (image.sections[i].base_address + buf_cnt > max_address)
2431                         {
2432                                 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2433                         }
2434
2435                         if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2436                         {
2437                                 free(buffer);
2438                                 break;
2439                         }
2440                         image_size += length;
2441                         command_print(cmd_ctx, "%u bytes written at address 0x%8.8" PRIx32 "",
2442                                                   (unsigned int)length,
2443                                                   image.sections[i].base_address + offset);
2444                 }
2445
2446                 free(buffer);
2447         }
2448
2449         if ((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2450         {
2451                 image_close(&image);
2452                 return retvaltemp;
2453         }
2454
2455         if (retval == ERROR_OK)
2456         {
2457                 command_print(cmd_ctx, "downloaded %u byte in %s",
2458                                           (unsigned int)image_size,
2459                                           duration_text);
2460         }
2461         free(duration_text);
2462
2463         image_close(&image);
2464
2465         return retval;
2466
2467 }
2468
2469 static int handle_dump_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2470 {
2471         fileio_t fileio;
2472
2473         uint8_t buffer[560];
2474         int retvaltemp;
2475
2476         duration_t duration;
2477         char *duration_text;
2478
2479         target_t *target = get_current_target(cmd_ctx);
2480
2481         if (argc != 3)
2482         {
2483                 command_print(cmd_ctx, "usage: dump_image <filename> <address> <size>");
2484                 return ERROR_OK;
2485         }
2486
2487         uint32_t address;
2488         int retval = parse_u32(args[1], &address);
2489         if (ERROR_OK != retval)
2490                 return retval;
2491
2492         uint32_t size;
2493         retval = parse_u32(args[2], &size);
2494         if (ERROR_OK != retval)
2495                 return retval;
2496
2497         if (fileio_open(&fileio, args[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
2498         {
2499                 return ERROR_OK;
2500         }
2501
2502         duration_start_measure(&duration);
2503
2504         while (size > 0)
2505         {
2506                 uint32_t size_written;
2507                 uint32_t this_run_size = (size > 560) ? 560 : size;
2508
2509                 retval = target_read_buffer(target, address, this_run_size, buffer);
2510                 if (retval != ERROR_OK)
2511                 {
2512                         break;
2513                 }
2514
2515                 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2516                 if (retval != ERROR_OK)
2517                 {
2518                         break;
2519                 }
2520
2521                 size -= this_run_size;
2522                 address += this_run_size;
2523         }
2524
2525         if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2526                 return retvaltemp;
2527
2528         if ((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2529                 return retvaltemp;
2530
2531         if (retval == ERROR_OK)
2532         {
2533                 command_print(cmd_ctx, "dumped %lld byte in %s",
2534                                 fileio.size, duration_text);
2535                 free(duration_text);
2536         }
2537
2538         return retval;
2539 }
2540
2541 static int handle_verify_image_command_internal(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc, int verify)
2542 {
2543         uint8_t *buffer;
2544         uint32_t buf_cnt;
2545         uint32_t image_size;
2546         int i;
2547         int retval, retvaltemp;
2548         uint32_t checksum = 0;
2549         uint32_t mem_checksum = 0;
2550
2551         image_t image;
2552
2553         duration_t duration;
2554         char *duration_text;
2555
2556         target_t *target = get_current_target(cmd_ctx);
2557
2558         if (argc < 1)
2559         {
2560                 return ERROR_COMMAND_SYNTAX_ERROR;
2561         }
2562
2563         if (!target)
2564         {
2565                 LOG_ERROR("no target selected");
2566                 return ERROR_FAIL;
2567         }
2568
2569         duration_start_measure(&duration);
2570
2571         if (argc >= 2)
2572         {
2573                 uint32_t addr;
2574                 retval = parse_u32(args[1], &addr);
2575                 if (ERROR_OK != retval)
2576                         return ERROR_COMMAND_SYNTAX_ERROR;
2577                 image.base_address = addr;
2578                 image.base_address_set = 1;
2579         }
2580         else
2581         {
2582                 image.base_address_set = 0;
2583                 image.base_address = 0x0;
2584         }
2585
2586         image.start_address_set = 0;
2587
2588         if ((retval = image_open(&image, args[0], (argc == 3) ? args[2] : NULL)) != ERROR_OK)
2589         {
2590                 return retval;
2591         }
2592
2593         image_size = 0x0;
2594         retval = ERROR_OK;
2595         for (i = 0; i < image.num_sections; i++)
2596         {
2597                 buffer = malloc(image.sections[i].size);
2598                 if (buffer == NULL)
2599                 {
2600                         command_print(cmd_ctx,
2601                                                   "error allocating buffer for section (%d bytes)",
2602                                                   (int)(image.sections[i].size));
2603                         break;
2604                 }
2605                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2606                 {
2607                         free(buffer);
2608                         break;
2609                 }
2610
2611                 if (verify)
2612                 {
2613                         /* calculate checksum of image */
2614                         image_calculate_checksum(buffer, buf_cnt, &checksum);
2615
2616                         retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2617                         if (retval != ERROR_OK)
2618                         {
2619                                 free(buffer);
2620                                 break;
2621                         }
2622
2623                         if (checksum != mem_checksum)
2624                         {
2625                                 /* failed crc checksum, fall back to a binary compare */
2626                                 uint8_t *data;
2627
2628                                 command_print(cmd_ctx, "checksum mismatch - attempting binary compare");
2629
2630                                 data = (uint8_t*)malloc(buf_cnt);
2631
2632                                 /* Can we use 32bit word accesses? */
2633                                 int size = 1;
2634                                 int count = buf_cnt;
2635                                 if ((count % 4) == 0)
2636                                 {
2637                                         size *= 4;
2638                                         count /= 4;
2639                                 }
2640                                 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2641                                 if (retval == ERROR_OK)
2642                                 {
2643                                         uint32_t t;
2644                                         for (t = 0; t < buf_cnt; t++)
2645                                         {
2646                                                 if (data[t] != buffer[t])
2647                                                 {
2648                                                         command_print(cmd_ctx,
2649                                                                                   "Verify operation failed address 0x%08x. Was 0x%02x instead of 0x%02x\n",
2650                                                                                   (unsigned)(t + image.sections[i].base_address),
2651                                                                                   data[t],
2652                                                                                   buffer[t]);
2653                                                         free(data);
2654                                                         free(buffer);
2655                                                         retval = ERROR_FAIL;
2656                                                         goto done;
2657                                                 }
2658                                                 if ((t%16384) == 0)
2659                                                 {
2660                                                         keep_alive();
2661                                                 }
2662                                         }
2663                                 }
2664
2665                                 free(data);
2666                         }
2667                 } else
2668                 {
2669                         command_print(cmd_ctx, "address 0x%08" PRIx32 " length 0x%08" PRIx32 "",
2670                                                   image.sections[i].base_address,
2671                                                   buf_cnt);
2672                 }
2673
2674                 free(buffer);
2675                 image_size += buf_cnt;
2676         }
2677 done:
2678
2679         if ((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2680         {
2681                 image_close(&image);
2682                 return retvaltemp;
2683         }
2684
2685         if (retval == ERROR_OK)
2686         {
2687                 command_print(cmd_ctx, "verified %u bytes in %s",
2688                                           (unsigned int)image_size,
2689                                           duration_text);
2690         }
2691         free(duration_text);
2692
2693         image_close(&image);
2694
2695         return retval;
2696 }
2697
2698 static int handle_verify_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2699 {
2700         return handle_verify_image_command_internal(cmd_ctx, cmd, args, argc, 1);
2701 }
2702
2703 static int handle_test_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2704 {
2705         return handle_verify_image_command_internal(cmd_ctx, cmd, args, argc, 0);
2706 }
2707
2708 static int handle_bp_command_list(struct command_context_s *cmd_ctx)
2709 {
2710         target_t *target = get_current_target(cmd_ctx);
2711         breakpoint_t *breakpoint = target->breakpoints;
2712         while (breakpoint)
2713         {
2714                 if (breakpoint->type == BKPT_SOFT)
2715                 {
2716                         char* buf = buf_to_str(breakpoint->orig_instr,
2717                                         breakpoint->length, 16);
2718                         command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2719                                         breakpoint->address,
2720                                         breakpoint->length,
2721                                         breakpoint->set, buf);
2722                         free(buf);
2723                 }
2724                 else
2725                 {
2726                         command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2727                                                   breakpoint->address,
2728                                                   breakpoint->length, breakpoint->set);
2729                 }
2730
2731                 breakpoint = breakpoint->next;
2732         }
2733         return ERROR_OK;
2734 }
2735
2736 static int handle_bp_command_set(struct command_context_s *cmd_ctx,
2737                 uint32_t addr, uint32_t length, int hw)
2738 {
2739         target_t *target = get_current_target(cmd_ctx);
2740         int retval = breakpoint_add(target, addr, length, hw);
2741         if (ERROR_OK == retval)
2742                 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2743         else
2744                 LOG_ERROR("Failure setting breakpoint");
2745         return retval;
2746 }
2747
2748 static int handle_bp_command(struct command_context_s *cmd_ctx,
2749                 char *cmd, char **args, int argc)
2750 {
2751         if (argc == 0)
2752                 return handle_bp_command_list(cmd_ctx);
2753
2754         if (argc < 2 || argc > 3)
2755         {
2756                 command_print(cmd_ctx, "usage: bp <address> <length> ['hw']");
2757                 return ERROR_COMMAND_SYNTAX_ERROR;
2758         }
2759
2760         uint32_t addr;
2761         int retval = parse_u32(args[0], &addr);
2762         if (ERROR_OK != retval)
2763                 return retval;
2764
2765         uint32_t length;
2766         retval = parse_u32(args[1], &length);
2767         if (ERROR_OK != retval)
2768                 return retval;
2769
2770         int hw = BKPT_SOFT;
2771         if (argc == 3)
2772         {
2773                 if (strcmp(args[2], "hw") == 0)
2774                         hw = BKPT_HARD;
2775                 else
2776                         return ERROR_COMMAND_SYNTAX_ERROR;
2777         }
2778
2779         return handle_bp_command_set(cmd_ctx, addr, length, hw);
2780 }
2781
2782 static int handle_rbp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2783 {
2784         if (argc != 1)
2785                 return ERROR_COMMAND_SYNTAX_ERROR;
2786
2787         uint32_t addr;
2788         int retval = parse_u32(args[0], &addr);
2789         if (ERROR_OK != retval)
2790                 return retval;
2791
2792         target_t *target = get_current_target(cmd_ctx);
2793         breakpoint_remove(target, addr);
2794
2795         return ERROR_OK;
2796 }
2797
2798 static int handle_wp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2799 {
2800         target_t *target = get_current_target(cmd_ctx);
2801
2802         if (argc == 0)
2803         {
2804                 watchpoint_t *watchpoint = target->watchpoints;
2805
2806                 while (watchpoint)
2807                 {
2808                         command_print(cmd_ctx,
2809                                                   "address: 0x%8.8" PRIx32 ", len: 0x%8.8x, r/w/a: %i, value: 0x%8.8" PRIx32 ", mask: 0x%8.8" PRIx32 "",
2810                                                   watchpoint->address,
2811                                                   watchpoint->length,
2812                                                   (int)(watchpoint->rw),
2813                                                   watchpoint->value,
2814                                                   watchpoint->mask);
2815                         watchpoint = watchpoint->next;
2816                 }
2817                 return ERROR_OK;
2818         }
2819
2820         enum watchpoint_rw type = WPT_ACCESS;
2821         uint32_t addr = 0;
2822         uint32_t length = 0;
2823         uint32_t data_value = 0x0;
2824         uint32_t data_mask = 0xffffffff;
2825         int retval;
2826
2827         switch (argc)
2828         {
2829         case 5:
2830                 retval = parse_u32(args[4], &data_mask);
2831                 if (ERROR_OK != retval)
2832                         return retval;
2833                 // fall through
2834         case 4:
2835                 retval = parse_u32(args[3], &data_value);
2836                 if (ERROR_OK != retval)
2837                         return retval;
2838                 // fall through
2839         case 3:
2840                 switch (args[2][0])
2841                 {
2842                 case 'r':
2843                         type = WPT_READ;
2844                         break;
2845                 case 'w':
2846                         type = WPT_WRITE;
2847                         break;
2848                 case 'a':
2849                         type = WPT_ACCESS;
2850                         break;
2851                 default:
2852                         LOG_ERROR("invalid watchpoint mode ('%c')", args[2][0]);
2853                         return ERROR_COMMAND_SYNTAX_ERROR;
2854                 }
2855                 // fall through
2856         case 2:
2857                 retval = parse_u32(args[1], &length);
2858                 if (ERROR_OK != retval)
2859                         return retval;
2860                 retval = parse_u32(args[0], &addr);
2861                 if (ERROR_OK != retval)
2862                         return retval;
2863                 break;
2864
2865         default:
2866                 command_print(cmd_ctx, "usage: wp <address> <length> [r/w/a] [value] [mask]");
2867                 return ERROR_COMMAND_SYNTAX_ERROR;
2868         }
2869
2870         retval = watchpoint_add(target, addr, length, type,
2871                         data_value, data_mask);
2872         if (ERROR_OK != retval)
2873                 LOG_ERROR("Failure setting watchpoints");
2874
2875         return retval;
2876 }
2877
2878 static int handle_rwp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2879 {
2880         if (argc != 1)
2881                 return ERROR_COMMAND_SYNTAX_ERROR;
2882
2883         uint32_t addr;
2884         int retval = parse_u32(args[0], &addr);
2885         if (ERROR_OK != retval)
2886                 return retval;
2887
2888         target_t *target = get_current_target(cmd_ctx);
2889         watchpoint_remove(target, addr);
2890
2891         return ERROR_OK;
2892 }
2893
2894
2895 /**
2896  * Translate a virtual address to a physical address.
2897  *
2898  * The low-level target implementation must have logged a detailed error
2899  * which is forwarded to telnet/GDB session.
2900  */
2901 static int handle_virt2phys_command(command_context_t *cmd_ctx,
2902                 char *cmd, char **args, int argc)
2903 {
2904         if (argc != 1)
2905                 return ERROR_COMMAND_SYNTAX_ERROR;
2906
2907         uint32_t va;
2908         int retval = parse_u32(args[0], &va);
2909         if (ERROR_OK != retval)
2910                 return retval;
2911         uint32_t pa;
2912
2913         target_t *target = get_current_target(cmd_ctx);
2914         retval = target->type->virt2phys(target, va, &pa);
2915         if (retval == ERROR_OK)
2916                 command_print(cmd_ctx, "Physical address 0x%08" PRIx32 "", pa);
2917
2918         return retval;
2919 }
2920
2921 static void writeData(FILE *f, const void *data, size_t len)
2922 {
2923         size_t written = fwrite(data, 1, len, f);
2924         if (written != len)
2925                 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
2926 }
2927
2928 static void writeLong(FILE *f, int l)
2929 {
2930         int i;
2931         for (i = 0; i < 4; i++)
2932         {
2933                 char c = (l >> (i*8))&0xff;
2934                 writeData(f, &c, 1);
2935         }
2936
2937 }
2938
2939 static void writeString(FILE *f, char *s)
2940 {
2941         writeData(f, s, strlen(s));
2942 }
2943
2944 /* Dump a gmon.out histogram file. */
2945 static void writeGmon(uint32_t *samples, uint32_t sampleNum, char *filename)
2946 {
2947         uint32_t i;
2948         FILE *f = fopen(filename, "w");
2949         if (f == NULL)
2950                 return;
2951         writeString(f, "gmon");
2952         writeLong(f, 0x00000001); /* Version */
2953         writeLong(f, 0); /* padding */
2954         writeLong(f, 0); /* padding */
2955         writeLong(f, 0); /* padding */
2956
2957         uint8_t zero = 0;  /* GMON_TAG_TIME_HIST */
2958         writeData(f, &zero, 1);
2959
2960         /* figure out bucket size */
2961         uint32_t min = samples[0];
2962         uint32_t max = samples[0];
2963         for (i = 0; i < sampleNum; i++)
2964         {
2965                 if (min > samples[i])
2966                 {
2967                         min = samples[i];
2968                 }
2969                 if (max < samples[i])
2970                 {
2971                         max = samples[i];
2972                 }
2973         }
2974
2975         int addressSpace = (max-min + 1);
2976
2977         static const uint32_t maxBuckets = 256 * 1024; /* maximum buckets. */
2978         uint32_t length = addressSpace;
2979         if (length > maxBuckets)
2980         {
2981                 length = maxBuckets;
2982         }
2983         int *buckets = malloc(sizeof(int)*length);
2984         if (buckets == NULL)
2985         {
2986                 fclose(f);
2987                 return;
2988         }
2989         memset(buckets, 0, sizeof(int)*length);
2990         for (i = 0; i < sampleNum;i++)
2991         {
2992                 uint32_t address = samples[i];
2993                 long long a = address-min;
2994                 long long b = length-1;
2995                 long long c = addressSpace-1;
2996                 int index = (a*b)/c; /* danger!!!! int32 overflows */
2997                 buckets[index]++;
2998         }
2999
3000         /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3001         writeLong(f, min);                      /* low_pc */
3002         writeLong(f, max);                      /* high_pc */
3003         writeLong(f, length);           /* # of samples */
3004         writeLong(f, 64000000);         /* 64MHz */
3005         writeString(f, "seconds");
3006         for (i = 0; i < (15-strlen("seconds")); i++)
3007                 writeData(f, &zero, 1);
3008         writeString(f, "s");
3009
3010         /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3011
3012         char *data = malloc(2*length);
3013         if (data != NULL)
3014         {
3015                 for (i = 0; i < length;i++)
3016                 {
3017                         int val;
3018                         val = buckets[i];
3019                         if (val > 65535)
3020                         {
3021                                 val = 65535;
3022                         }
3023                         data[i*2]=val&0xff;
3024                         data[i*2 + 1]=(val >> 8)&0xff;
3025                 }
3026                 free(buckets);
3027                 writeData(f, data, length * 2);
3028                 free(data);
3029         } else
3030         {
3031                 free(buckets);
3032         }
3033
3034         fclose(f);
3035 }
3036
3037 /* profiling samples the CPU PC as quickly as OpenOCD is able, which will be used as a random sampling of PC */
3038 static int handle_profile_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
3039 {
3040         target_t *target = get_current_target(cmd_ctx);
3041         struct timeval timeout, now;
3042
3043         gettimeofday(&timeout, NULL);
3044         if (argc != 2)
3045         {
3046                 return ERROR_COMMAND_SYNTAX_ERROR;
3047         }
3048         unsigned offset;
3049         int retval = parse_uint(args[0], &offset);
3050         if (ERROR_OK != retval)
3051                 return retval;
3052
3053         timeval_add_time(&timeout, offset, 0);
3054
3055         command_print(cmd_ctx, "Starting profiling. Halting and resuming the target as often as we can...");
3056
3057         static const int maxSample = 10000;
3058         uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3059         if (samples == NULL)
3060                 return ERROR_OK;
3061
3062         int numSamples = 0;
3063         /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3064         reg_t *reg = register_get_by_name(target->reg_cache, "pc", 1);
3065
3066         for (;;)
3067         {
3068                 target_poll(target);
3069                 if (target->state == TARGET_HALTED)
3070                 {
3071                         uint32_t t=*((uint32_t *)reg->value);
3072                         samples[numSamples++]=t;
3073                         retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3074                         target_poll(target);
3075                         alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3076                 } else if (target->state == TARGET_RUNNING)
3077                 {
3078                         /* We want to quickly sample the PC. */
3079                         if ((retval = target_halt(target)) != ERROR_OK)
3080                         {
3081                                 free(samples);
3082                                 return retval;
3083                         }
3084                 } else
3085                 {
3086                         command_print(cmd_ctx, "Target not halted or running");
3087                         retval = ERROR_OK;
3088                         break;
3089                 }
3090                 if (retval != ERROR_OK)
3091                 {
3092                         break;
3093                 }
3094
3095                 gettimeofday(&now, NULL);
3096                 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3097                 {
3098                         command_print(cmd_ctx, "Profiling completed. %d samples.", numSamples);
3099                         if ((retval = target_poll(target)) != ERROR_OK)
3100                         {
3101                                 free(samples);
3102                                 return retval;
3103                         }
3104                         if (target->state == TARGET_HALTED)
3105                         {
3106                                 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3107                         }
3108                         if ((retval = target_poll(target)) != ERROR_OK)
3109                         {
3110                                 free(samples);
3111                                 return retval;
3112                         }
3113                         writeGmon(samples, numSamples, args[1]);
3114                         command_print(cmd_ctx, "Wrote %s", args[1]);
3115                         break;
3116                 }
3117         }
3118         free(samples);
3119
3120         return ERROR_OK;
3121 }
3122
3123 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3124 {
3125         char *namebuf;
3126         Jim_Obj *nameObjPtr, *valObjPtr;
3127         int result;
3128
3129         namebuf = alloc_printf("%s(%d)", varname, idx);
3130         if (!namebuf)
3131                 return JIM_ERR;
3132
3133         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3134         valObjPtr = Jim_NewIntObj(interp, val);
3135         if (!nameObjPtr || !valObjPtr)
3136         {
3137                 free(namebuf);
3138                 return JIM_ERR;
3139         }
3140
3141         Jim_IncrRefCount(nameObjPtr);
3142         Jim_IncrRefCount(valObjPtr);
3143         result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3144         Jim_DecrRefCount(interp, nameObjPtr);
3145         Jim_DecrRefCount(interp, valObjPtr);
3146         free(namebuf);
3147         /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3148         return result;
3149 }
3150
3151 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3152 {
3153         command_context_t *context;
3154         target_t *target;
3155
3156         context = Jim_GetAssocData(interp, "context");
3157         if (context == NULL)
3158         {
3159                 LOG_ERROR("mem2array: no command context");
3160                 return JIM_ERR;
3161         }
3162         target = get_current_target(context);
3163         if (target == NULL)
3164         {
3165                 LOG_ERROR("mem2array: no current target");
3166                 return JIM_ERR;
3167         }
3168
3169         return  target_mem2array(interp, target, argc-1, argv + 1);
3170 }
3171
3172 static int target_mem2array(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv)
3173 {
3174         long l;
3175         uint32_t width;
3176         int len;
3177         uint32_t addr;
3178         uint32_t count;
3179         uint32_t v;
3180         const char *varname;
3181         uint8_t buffer[4096];
3182         int  n, e, retval;
3183         uint32_t i;
3184
3185         /* argv[1] = name of array to receive the data
3186          * argv[2] = desired width
3187          * argv[3] = memory address
3188          * argv[4] = count of times to read
3189          */
3190         if (argc != 4) {
3191                 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3192                 return JIM_ERR;
3193         }
3194         varname = Jim_GetString(argv[0], &len);
3195         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3196
3197         e = Jim_GetLong(interp, argv[1], &l);
3198         width = l;
3199         if (e != JIM_OK) {
3200                 return e;
3201         }
3202
3203         e = Jim_GetLong(interp, argv[2], &l);
3204         addr = l;
3205         if (e != JIM_OK) {
3206                 return e;
3207         }
3208         e = Jim_GetLong(interp, argv[3], &l);
3209         len = l;
3210         if (e != JIM_OK) {
3211                 return e;
3212         }
3213         switch (width) {
3214                 case 8:
3215                         width = 1;
3216                         break;
3217                 case 16:
3218                         width = 2;
3219                         break;
3220                 case 32:
3221                         width = 4;
3222                         break;
3223                 default:
3224                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3225                         Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3226                         return JIM_ERR;
3227         }
3228         if (len == 0) {
3229                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3230                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3231                 return JIM_ERR;
3232         }
3233         if ((addr + (len * width)) < addr) {
3234                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3235                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3236                 return JIM_ERR;
3237         }
3238         /* absurd transfer size? */
3239         if (len > 65536) {
3240                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3241                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3242                 return JIM_ERR;
3243         }
3244
3245         if ((width == 1) ||
3246                 ((width == 2) && ((addr & 1) == 0)) ||
3247                 ((width == 4) && ((addr & 3) == 0))) {
3248                 /* all is well */
3249         } else {
3250                 char buf[100];
3251                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3252                 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3253                                 addr,
3254                                 width);
3255                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3256                 return JIM_ERR;
3257         }
3258
3259         /* Transfer loop */
3260
3261         /* index counter */
3262         n = 0;
3263         /* assume ok */
3264         e = JIM_OK;
3265         while (len) {
3266                 /* Slurp... in buffer size chunks */
3267
3268                 count = len; /* in objects.. */
3269                 if (count > (sizeof(buffer)/width)) {
3270                         count = (sizeof(buffer)/width);
3271                 }
3272
3273                 retval = target_read_memory(target, addr, width, count, buffer);
3274                 if (retval != ERROR_OK) {
3275                         /* BOO !*/
3276                         LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3277                                           (unsigned int)addr,
3278                                           (int)width,
3279                                           (int)count);
3280                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3281                         Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3282                         e = JIM_ERR;
3283                         len = 0;
3284                 } else {
3285                         v = 0; /* shut up gcc */
3286                         for (i = 0 ;i < count ;i++, n++) {
3287                                 switch (width) {
3288                                         case 4:
3289                                                 v = target_buffer_get_u32(target, &buffer[i*width]);
3290                                                 break;
3291                                         case 2:
3292                                                 v = target_buffer_get_u16(target, &buffer[i*width]);
3293                                                 break;
3294                                         case 1:
3295                                                 v = buffer[i] & 0x0ff;
3296                                                 break;
3297                                 }
3298                                 new_int_array_element(interp, varname, n, v);
3299                         }
3300                         len -= count;
3301                 }
3302         }
3303
3304         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3305
3306         return JIM_OK;
3307 }
3308
3309 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3310 {
3311         char *namebuf;
3312         Jim_Obj *nameObjPtr, *valObjPtr;
3313         int result;
3314         long l;
3315
3316         namebuf = alloc_printf("%s(%d)", varname, idx);
3317         if (!namebuf)
3318                 return JIM_ERR;
3319
3320         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3321         if (!nameObjPtr)
3322         {
3323                 free(namebuf);
3324                 return JIM_ERR;
3325         }
3326
3327         Jim_IncrRefCount(nameObjPtr);
3328         valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3329         Jim_DecrRefCount(interp, nameObjPtr);
3330         free(namebuf);
3331         if (valObjPtr == NULL)
3332                 return JIM_ERR;
3333
3334         result = Jim_GetLong(interp, valObjPtr, &l);
3335         /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3336         *val = l;
3337         return result;
3338 }
3339
3340 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3341 {
3342         command_context_t *context;
3343         target_t *target;
3344
3345         context = Jim_GetAssocData(interp, "context");
3346         if (context == NULL) {
3347                 LOG_ERROR("array2mem: no command context");
3348                 return JIM_ERR;
3349         }
3350         target = get_current_target(context);
3351         if (target == NULL) {
3352                 LOG_ERROR("array2mem: no current target");
3353                 return JIM_ERR;
3354         }
3355
3356         return target_array2mem(interp,target, argc-1, argv + 1);
3357 }
3358
3359 static int target_array2mem(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv)
3360 {
3361         long l;
3362         uint32_t width;
3363         int len;
3364         uint32_t addr;
3365         uint32_t count;
3366         uint32_t v;
3367         const char *varname;
3368         uint8_t buffer[4096];
3369         int  n, e, retval;
3370         uint32_t i;
3371
3372         /* argv[1] = name of array to get the data
3373          * argv[2] = desired width
3374          * argv[3] = memory address
3375          * argv[4] = count to write
3376          */
3377         if (argc != 4) {
3378                 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3379                 return JIM_ERR;
3380         }
3381         varname = Jim_GetString(argv[0], &len);
3382         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3383
3384         e = Jim_GetLong(interp, argv[1], &l);
3385         width = l;
3386         if (e != JIM_OK) {
3387                 return e;
3388         }
3389
3390         e = Jim_GetLong(interp, argv[2], &l);
3391         addr = l;
3392         if (e != JIM_OK) {
3393                 return e;
3394         }
3395         e = Jim_GetLong(interp, argv[3], &l);
3396         len = l;
3397         if (e != JIM_OK) {
3398                 return e;
3399         }
3400         switch (width) {
3401                 case 8:
3402                         width = 1;
3403                         break;
3404                 case 16:
3405                         width = 2;
3406                         break;
3407                 case 32:
3408                         width = 4;
3409                         break;
3410                 default:
3411                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3412                         Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3413                         return JIM_ERR;
3414         }
3415         if (len == 0) {
3416                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3417                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3418                 return JIM_ERR;
3419         }
3420         if ((addr + (len * width)) < addr) {
3421                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3422                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3423                 return JIM_ERR;
3424         }
3425         /* absurd transfer size? */
3426         if (len > 65536) {
3427                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3428                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3429                 return JIM_ERR;
3430         }
3431
3432         if ((width == 1) ||
3433                 ((width == 2) && ((addr & 1) == 0)) ||
3434                 ((width == 4) && ((addr & 3) == 0))) {
3435                 /* all is well */
3436         } else {
3437                 char buf[100];
3438                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3439                 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3440                                 (unsigned int)addr,
3441                                 (int)width);
3442                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3443                 return JIM_ERR;
3444         }
3445
3446         /* Transfer loop */
3447
3448         /* index counter */
3449         n = 0;
3450         /* assume ok */
3451         e = JIM_OK;
3452         while (len) {
3453                 /* Slurp... in buffer size chunks */
3454
3455                 count = len; /* in objects.. */
3456                 if (count > (sizeof(buffer)/width)) {
3457                         count = (sizeof(buffer)/width);
3458                 }
3459
3460                 v = 0; /* shut up gcc */
3461                 for (i = 0 ;i < count ;i++, n++) {
3462                         get_int_array_element(interp, varname, n, &v);
3463                         switch (width) {
3464                         case 4:
3465                                 target_buffer_set_u32(target, &buffer[i*width], v);
3466                                 break;
3467                         case 2:
3468                                 target_buffer_set_u16(target, &buffer[i*width], v);
3469                                 break;
3470                         case 1:
3471                                 buffer[i] = v & 0x0ff;
3472                                 break;
3473                         }
3474                 }
3475                 len -= count;
3476
3477                 retval = target_write_memory(target, addr, width, count, buffer);
3478                 if (retval != ERROR_OK) {
3479                         /* BOO !*/
3480                         LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3481                                           (unsigned int)addr,
3482                                           (int)width,
3483                                           (int)count);
3484                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3485                         Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3486                         e = JIM_ERR;
3487                         len = 0;
3488                 }
3489         }
3490
3491         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3492
3493         return JIM_OK;
3494 }
3495
3496 void target_all_handle_event(enum target_event e)
3497 {
3498         target_t *target;
3499
3500         LOG_DEBUG("**all*targets: event: %d, %s",
3501                            (int)e,
3502                            Jim_Nvp_value2name_simple(nvp_target_event, e)->name);
3503
3504         target = all_targets;
3505         while (target) {
3506                 target_handle_event(target, e);
3507                 target = target->next;
3508         }
3509 }
3510
3511
3512 /* FIX? should we propagate errors here rather than printing them
3513  * and continuing?
3514  */
3515 void target_handle_event(target_t *target, enum target_event e)
3516 {
3517         target_event_action_t *teap;
3518
3519         for (teap = target->event_action; teap != NULL; teap = teap->next) {
3520                 if (teap->event == e) {
3521                         LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3522                                            target->target_number,
3523                                            target->cmd_name,
3524                                            target_get_name(target),
3525                                            e,
3526                                            Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3527                                            Jim_GetString(teap->body, NULL));
3528                         if (Jim_EvalObj(interp, teap->body) != JIM_OK)
3529                         {
3530                                 Jim_PrintErrorMessage(interp);
3531                         }
3532                 }
3533         }
3534 }
3535
3536 enum target_cfg_param {
3537         TCFG_TYPE,
3538         TCFG_EVENT,
3539         TCFG_WORK_AREA_VIRT,
3540         TCFG_WORK_AREA_PHYS,
3541         TCFG_WORK_AREA_SIZE,
3542         TCFG_WORK_AREA_BACKUP,
3543         TCFG_ENDIAN,
3544         TCFG_VARIANT,
3545         TCFG_CHAIN_POSITION,
3546 };
3547
3548 static Jim_Nvp nvp_config_opts[] = {
3549         { .name = "-type",             .value = TCFG_TYPE },
3550         { .name = "-event",            .value = TCFG_EVENT },
3551         { .name = "-work-area-virt",   .value = TCFG_WORK_AREA_VIRT },
3552         { .name = "-work-area-phys",   .value = TCFG_WORK_AREA_PHYS },
3553         { .name = "-work-area-size",   .value = TCFG_WORK_AREA_SIZE },
3554         { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3555         { .name = "-endian" ,          .value = TCFG_ENDIAN },
3556         { .name = "-variant",          .value = TCFG_VARIANT },
3557         { .name = "-chain-position",   .value = TCFG_CHAIN_POSITION },
3558
3559         { .name = NULL, .value = -1 }
3560 };
3561
3562 static int target_configure(Jim_GetOptInfo *goi, target_t *target)
3563 {
3564         Jim_Nvp *n;
3565         Jim_Obj *o;
3566         jim_wide w;
3567         char *cp;
3568         int e;
3569
3570         /* parse config or cget options ... */
3571         while (goi->argc > 0) {
3572                 Jim_SetEmptyResult(goi->interp);
3573                 /* Jim_GetOpt_Debug(goi); */
3574
3575                 if (target->type->target_jim_configure) {
3576                         /* target defines a configure function */
3577                         /* target gets first dibs on parameters */
3578                         e = (*(target->type->target_jim_configure))(target, goi);
3579                         if (e == JIM_OK) {
3580                                 /* more? */
3581                                 continue;
3582                         }
3583                         if (e == JIM_ERR) {
3584                                 /* An error */
3585                                 return e;
3586                         }
3587                         /* otherwise we 'continue' below */
3588                 }
3589                 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3590                 if (e != JIM_OK) {
3591                         Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3592                         return e;
3593                 }
3594                 switch (n->value) {
3595                 case TCFG_TYPE:
3596                         /* not setable */
3597                         if (goi->isconfigure) {
3598                                 Jim_SetResult_sprintf(goi->interp, "not setable: %s", n->name);
3599                                 return JIM_ERR;
3600                         } else {
3601                         no_params:
3602                                 if (goi->argc != 0) {
3603                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "NO PARAMS");
3604                                         return JIM_ERR;
3605                                 }
3606                         }
3607                         Jim_SetResultString(goi->interp, target_get_name(target), -1);
3608                         /* loop for more */
3609                         break;
3610                 case TCFG_EVENT:
3611                         if (goi->argc == 0) {
3612                                 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3613                                 return JIM_ERR;
3614                         }
3615
3616                         e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3617                         if (e != JIM_OK) {
3618                                 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3619                                 return e;
3620                         }
3621
3622                         if (goi->isconfigure) {
3623                                 if (goi->argc != 1) {
3624                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3625                                         return JIM_ERR;
3626                                 }
3627                         } else {
3628                                 if (goi->argc != 0) {
3629                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3630                                         return JIM_ERR;
3631                                 }
3632                         }
3633
3634                         {
3635                                 target_event_action_t *teap;
3636
3637                                 teap = target->event_action;
3638                                 /* replace existing? */
3639                                 while (teap) {
3640                                         if (teap->event == (enum target_event)n->value) {
3641                                                 break;
3642                                         }
3643                                         teap = teap->next;
3644                                 }
3645
3646                                 if (goi->isconfigure) {
3647                                         bool replace = true;
3648                                         if (teap == NULL) {
3649                                                 /* create new */
3650                                                 teap = calloc(1, sizeof(*teap));
3651                                                 replace = false;
3652                                         }
3653                                         teap->event = n->value;
3654                                         Jim_GetOpt_Obj(goi, &o);
3655                                         if (teap->body) {
3656                                                 Jim_DecrRefCount(interp, teap->body);
3657                                         }
3658                                         teap->body  = Jim_DuplicateObj(goi->interp, o);
3659                                         /*
3660                                          * FIXME:
3661                                          *     Tcl/TK - "tk events" have a nice feature.
3662                                          *     See the "BIND" command.
3663                                          *    We should support that here.
3664                                          *     You can specify %X and %Y in the event code.
3665                                          *     The idea is: %T - target name.
3666                                          *     The idea is: %N - target number
3667                                          *     The idea is: %E - event name.
3668                                          */
3669                                         Jim_IncrRefCount(teap->body);
3670
3671                                         if (!replace)
3672                                         {
3673                                                 /* add to head of event list */
3674                                                 teap->next = target->event_action;
3675                                                 target->event_action = teap;
3676                                         }
3677                                         Jim_SetEmptyResult(goi->interp);
3678                                 } else {
3679                                         /* get */
3680                                         if (teap == NULL) {
3681                                                 Jim_SetEmptyResult(goi->interp);
3682                                         } else {
3683                                                 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3684                                         }
3685                                 }
3686                         }
3687                         /* loop for more */
3688                         break;
3689
3690                 case TCFG_WORK_AREA_VIRT:
3691                         if (goi->isconfigure) {
3692                                 target_free_all_working_areas(target);
3693                                 e = Jim_GetOpt_Wide(goi, &w);
3694                                 if (e != JIM_OK) {
3695                                         return e;
3696                                 }
3697                                 target->working_area_virt = w;
3698                         } else {
3699                                 if (goi->argc != 0) {
3700                                         goto no_params;
3701                                 }
3702                         }
3703                         Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3704                         /* loop for more */
3705                         break;
3706
3707                 case TCFG_WORK_AREA_PHYS:
3708                         if (goi->isconfigure) {
3709                                 target_free_all_working_areas(target);
3710                                 e = Jim_GetOpt_Wide(goi, &w);
3711                                 if (e != JIM_OK) {
3712                                         return e;
3713                                 }
3714                                 target->working_area_phys = w;
3715                         } else {
3716                                 if (goi->argc != 0) {
3717                                         goto no_params;
3718                                 }
3719                         }
3720                         Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3721                         /* loop for more */
3722                         break;
3723
3724                 case TCFG_WORK_AREA_SIZE:
3725                         if (goi->isconfigure) {
3726                                 target_free_all_working_areas(target);
3727                                 e = Jim_GetOpt_Wide(goi, &w);
3728                                 if (e != JIM_OK) {
3729                                         return e;
3730                                 }
3731                                 target->working_area_size = w;
3732                         } else {
3733                                 if (goi->argc != 0) {
3734                                         goto no_params;
3735                                 }
3736                         }
3737                         Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3738                         /* loop for more */
3739                         break;
3740
3741                 case TCFG_WORK_AREA_BACKUP:
3742                         if (goi->isconfigure) {
3743                                 target_free_all_working_areas(target);
3744                                 e = Jim_GetOpt_Wide(goi, &w);
3745                                 if (e != JIM_OK) {
3746                                         return e;
3747                                 }
3748                                 /* make this exactly 1 or 0 */
3749                                 target->backup_working_area = (!!w);
3750                         } else {
3751                                 if (goi->argc != 0) {
3752                                         goto no_params;
3753                                 }
3754                         }
3755                         Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3756                         /* loop for more e*/
3757                         break;
3758
3759                 case TCFG_ENDIAN:
3760                         if (goi->isconfigure) {
3761                                 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3762                                 if (e != JIM_OK) {
3763                                         Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3764                                         return e;
3765                                 }
3766                                 target->endianness = n->value;
3767                         } else {
3768                                 if (goi->argc != 0) {
3769                                         goto no_params;
3770                                 }
3771                         }
3772                         n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3773                         if (n->name == NULL) {
3774                                 target->endianness = TARGET_LITTLE_ENDIAN;
3775                                 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3776                         }
3777                         Jim_SetResultString(goi->interp, n->name, -1);
3778                         /* loop for more */
3779                         break;
3780
3781                 case TCFG_VARIANT:
3782                         if (goi->isconfigure) {
3783                                 if (goi->argc < 1) {
3784                                         Jim_SetResult_sprintf(goi->interp,
3785                                                                                    "%s ?STRING?",
3786                                                                                    n->name);
3787                                         return JIM_ERR;
3788                                 }
3789                                 if (target->variant) {
3790                                         free((void *)(target->variant));
3791                                 }
3792                                 e = Jim_GetOpt_String(goi, &cp, NULL);
3793                                 target->variant = strdup(cp);
3794                         } else {
3795                                 if (goi->argc != 0) {
3796                                         goto no_params;
3797                                 }
3798                         }
3799                         Jim_SetResultString(goi->interp, target->variant,-1);
3800                         /* loop for more */
3801                         break;
3802                 case TCFG_CHAIN_POSITION:
3803                         if (goi->isconfigure) {
3804                                 Jim_Obj *o;
3805                                 jtag_tap_t *tap;
3806                                 target_free_all_working_areas(target);
3807                                 e = Jim_GetOpt_Obj(goi, &o);
3808                                 if (e != JIM_OK) {
3809                                         return e;
3810                                 }
3811                                 tap = jtag_tap_by_jim_obj(goi->interp, o);
3812                                 if (tap == NULL) {
3813                                         return JIM_ERR;
3814                                 }
3815                                 /* make this exactly 1 or 0 */
3816                                 target->tap = tap;
3817                         } else {
3818                                 if (goi->argc != 0) {
3819                                         goto no_params;
3820                                 }
3821                         }
3822                         Jim_SetResultString(interp, target->tap->dotted_name, -1);
3823                         /* loop for more e*/
3824                         break;
3825                 }
3826         } /* while (goi->argc) */
3827
3828
3829                 /* done - we return */
3830         return JIM_OK;
3831 }
3832
3833 /** this is the 'tcl' handler for the target specific command */
3834 static int tcl_target_func(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3835 {
3836         Jim_GetOptInfo goi;
3837         jim_wide a,b,c;
3838         int x,y,z;
3839         uint8_t  target_buf[32];
3840         Jim_Nvp *n;
3841         target_t *target;
3842         struct command_context_s *cmd_ctx;
3843         int e;
3844
3845         enum {
3846                 TS_CMD_CONFIGURE,
3847                 TS_CMD_CGET,
3848
3849                 TS_CMD_MWW, TS_CMD_MWH, TS_CMD_MWB,
3850                 TS_CMD_MDW, TS_CMD_MDH, TS_CMD_MDB,
3851                 TS_CMD_MRW, TS_CMD_MRH, TS_CMD_MRB,
3852                 TS_CMD_MEM2ARRAY, TS_CMD_ARRAY2MEM,
3853                 TS_CMD_EXAMINE,
3854                 TS_CMD_POLL,
3855                 TS_CMD_RESET,
3856                 TS_CMD_HALT,
3857                 TS_CMD_WAITSTATE,
3858                 TS_CMD_EVENTLIST,
3859                 TS_CMD_CURSTATE,
3860                 TS_CMD_INVOKE_EVENT,
3861         };
3862
3863         static const Jim_Nvp target_options[] = {
3864                 { .name = "configure", .value = TS_CMD_CONFIGURE },
3865                 { .name = "cget", .value = TS_CMD_CGET },
3866                 { .name = "mww", .value = TS_CMD_MWW },
3867                 { .name = "mwh", .value = TS_CMD_MWH },
3868                 { .name = "mwb", .value = TS_CMD_MWB },
3869                 { .name = "mdw", .value = TS_CMD_MDW },
3870                 { .name = "mdh", .value = TS_CMD_MDH },
3871                 { .name = "mdb", .value = TS_CMD_MDB },
3872                 { .name = "mem2array", .value = TS_CMD_MEM2ARRAY },
3873                 { .name = "array2mem", .value = TS_CMD_ARRAY2MEM },
3874                 { .name = "eventlist", .value = TS_CMD_EVENTLIST },
3875                 { .name = "curstate",  .value = TS_CMD_CURSTATE },
3876
3877                 { .name = "arp_examine", .value = TS_CMD_EXAMINE },
3878                 { .name = "arp_poll", .value = TS_CMD_POLL },
3879                 { .name = "arp_reset", .value = TS_CMD_RESET },
3880                 { .name = "arp_halt", .value = TS_CMD_HALT },
3881                 { .name = "arp_waitstate", .value = TS_CMD_WAITSTATE },
3882                 { .name = "invoke-event", .value = TS_CMD_INVOKE_EVENT },
3883
3884                 { .name = NULL, .value = -1 },
3885         };
3886
3887         /* go past the "command" */
3888         Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
3889
3890         target = Jim_CmdPrivData(goi.interp);
3891         cmd_ctx = Jim_GetAssocData(goi.interp, "context");
3892
3893         /* commands here are in an NVP table */
3894         e = Jim_GetOpt_Nvp(&goi, target_options, &n);
3895         if (e != JIM_OK) {
3896                 Jim_GetOpt_NvpUnknown(&goi, target_options, 0);
3897                 return e;
3898         }
3899         /* Assume blank result */
3900         Jim_SetEmptyResult(goi.interp);
3901
3902         switch (n->value) {
3903         case TS_CMD_CONFIGURE:
3904                 if (goi.argc < 2) {
3905                         Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "missing: -option VALUE ...");
3906                         return JIM_ERR;
3907                 }
3908                 goi.isconfigure = 1;
3909                 return target_configure(&goi, target);
3910         case TS_CMD_CGET:
3911                 // some things take params
3912                 if (goi.argc < 1) {
3913                         Jim_WrongNumArgs(goi.interp, 0, goi.argv, "missing: ?-option?");
3914                         return JIM_ERR;
3915                 }
3916                 goi.isconfigure = 0;
3917                 return target_configure(&goi, target);
3918                 break;
3919         case TS_CMD_MWW:
3920         case TS_CMD_MWH:
3921         case TS_CMD_MWB:
3922                 /* argv[0] = cmd
3923                  * argv[1] = address
3924                  * argv[2] = data
3925                  * argv[3] = optional count.
3926                  */
3927
3928                 if ((goi.argc == 2) || (goi.argc == 3)) {
3929                         /* all is well */
3930                 } else {
3931                 mwx_error:
3932                         Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR DATA [COUNT]", n->name);
3933                         return JIM_ERR;
3934                 }
3935
3936                 e = Jim_GetOpt_Wide(&goi, &a);
3937                 if (e != JIM_OK) {
3938                         goto mwx_error;
3939                 }
3940
3941                 e = Jim_GetOpt_Wide(&goi, &b);
3942                 if (e != JIM_OK) {
3943                         goto mwx_error;
3944                 }
3945                 if (goi.argc == 3) {
3946                         e = Jim_GetOpt_Wide(&goi, &c);
3947                         if (e != JIM_OK) {
3948                                 goto mwx_error;
3949                         }
3950                 } else {
3951                         c = 1;
3952                 }
3953
3954                 switch (n->value) {
3955                 case TS_CMD_MWW:
3956                         target_buffer_set_u32(target, target_buf, b);
3957                         b = 4;
3958                         break;
3959                 case TS_CMD_MWH:
3960                         target_buffer_set_u16(target, target_buf, b);
3961                         b = 2;
3962                         break;
3963                 case TS_CMD_MWB:
3964                         target_buffer_set_u8(target, target_buf, b);
3965                         b = 1;
3966                         break;
3967                 }
3968                 for (x = 0 ; x < c ; x++) {
3969                         e = target_write_memory(target, a, b, 1, target_buf);
3970                         if (e != ERROR_OK) {
3971                                 Jim_SetResult_sprintf(interp, "Error writing @ 0x%08x: %d\n", (int)(a), e);
3972                                 return JIM_ERR;
3973                         }
3974                         /* b = width */
3975                         a = a + b;
3976                 }
3977                 return JIM_OK;
3978                 break;
3979
3980                 /* display */
3981         case TS_CMD_MDW:
3982         case TS_CMD_MDH:
3983         case TS_CMD_MDB:
3984                 /* argv[0] = command
3985                  * argv[1] = address
3986                  * argv[2] = optional count
3987                  */
3988                 if ((goi.argc == 2) || (goi.argc == 3)) {
3989                         Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR [COUNT]", n->name);
3990                         return JIM_ERR;
3991                 }
3992                 e = Jim_GetOpt_Wide(&goi, &a);
3993                 if (e != JIM_OK) {
3994                         return JIM_ERR;
3995                 }
3996                 if (goi.argc) {
3997                         e = Jim_GetOpt_Wide(&goi, &c);
3998                         if (e != JIM_OK) {
3999                                 return JIM_ERR;
4000                         }
4001                 } else {
4002                         c = 1;
4003                 }
4004                 b = 1; /* shut up gcc */
4005                 switch (n->value) {
4006                 case TS_CMD_MDW:
4007                         b =  4;
4008                         break;
4009                 case TS_CMD_MDH:
4010                         b = 2;
4011                         break;
4012                 case TS_CMD_MDB:
4013                         b = 1;
4014                         break;
4015                 }
4016
4017                 /* convert to "bytes" */
4018                 c = c * b;
4019                 /* count is now in 'BYTES' */
4020                 while (c > 0) {
4021                         y = c;
4022                         if (y > 16) {
4023                                 y = 16;
4024                         }
4025                         e = target_read_memory(target, a, b, y / b, target_buf);
4026                         if (e != ERROR_OK) {
4027                                 Jim_SetResult_sprintf(interp, "error reading target @ 0x%08lx", (int)(a));
4028                                 return JIM_ERR;
4029                         }
4030
4031                         Jim_fprintf(interp, interp->cookie_stdout, "0x%08x ", (int)(a));
4032                         switch (b) {
4033                         case 4:
4034                                 for (x = 0 ; (x < 16) && (x < y) ; x += 4) {
4035                                         z = target_buffer_get_u32(target, &(target_buf[ x * 4 ]));
4036                                         Jim_fprintf(interp, interp->cookie_stdout, "%08x ", (int)(z));
4037                                 }
4038                                 for (; (x < 16) ; x += 4) {
4039                                         Jim_fprintf(interp, interp->cookie_stdout, "         ");
4040                                 }
4041                                 break;
4042                         case 2:
4043                                 for (x = 0 ; (x < 16) && (x < y) ; x += 2) {
4044                                         z = target_buffer_get_u16(target, &(target_buf[ x * 2 ]));
4045                                         Jim_fprintf(interp, interp->cookie_stdout, "%04x ", (int)(z));
4046                                 }
4047                                 for (; (x < 16) ; x += 2) {
4048                                         Jim_fprintf(interp, interp->cookie_stdout, "     ");
4049                                 }
4050                                 break;
4051                         case 1:
4052                         default:
4053                                 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4054                                         z = target_buffer_get_u8(target, &(target_buf[ x * 4 ]));
4055                                         Jim_fprintf(interp, interp->cookie_stdout, "%02x ", (int)(z));
4056                                 }
4057                                 for (; (x < 16) ; x += 1) {
4058                                         Jim_fprintf(interp, interp->cookie_stdout, "   ");
4059                                 }
4060                                 break;
4061                         }
4062                         /* ascii-ify the bytes */
4063                         for (x = 0 ; x < y ; x++) {
4064                                 if ((target_buf[x] >= 0x20) &&
4065                                         (target_buf[x] <= 0x7e)) {
4066                                         /* good */
4067                                 } else {
4068                                         /* smack it */
4069                                         target_buf[x] = '.';
4070                                 }
4071                         }
4072                         /* space pad  */
4073                         while (x < 16) {
4074                                 target_buf[x] = ' ';
4075                                 x++;
4076                         }
4077                         /* terminate */
4078                         target_buf[16] = 0;
4079                         /* print - with a newline */
4080                         Jim_fprintf(interp, interp->cookie_stdout, "%s\n", target_buf);
4081                         /* NEXT... */
4082                         c -= 16;
4083                         a += 16;
4084                 }
4085                 return JIM_OK;
4086         case TS_CMD_MEM2ARRAY:
4087                 return target_mem2array(goi.interp, target, goi.argc, goi.argv);
4088                 break;
4089         case TS_CMD_ARRAY2MEM:
4090                 return target_array2mem(goi.interp, target, goi.argc, goi.argv);
4091                 break;
4092         case TS_CMD_EXAMINE:
4093                 if (goi.argc) {
4094                         Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4095                         return JIM_ERR;
4096                 }
4097                 if (!target->tap->enabled)
4098                         goto err_tap_disabled;
4099                 e = target->type->examine(target);
4100                 if (e != ERROR_OK) {
4101                         Jim_SetResult_sprintf(interp, "examine-fails: %d", e);
4102                         return JIM_ERR;
4103                 }
4104                 return JIM_OK;
4105         case TS_CMD_POLL:
4106                 if (goi.argc) {
4107                         Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4108                         return JIM_ERR;
4109                 }
4110                 if (!target->tap->enabled)
4111                         goto err_tap_disabled;
4112                 if (!(target_was_examined(target))) {
4113                         e = ERROR_TARGET_NOT_EXAMINED;
4114                 } else {
4115                         e = target->type->poll(target);
4116                 }
4117                 if (e != ERROR_OK) {
4118                         Jim_SetResult_sprintf(interp, "poll-fails: %d", e);
4119                         return JIM_ERR;
4120                 } else {
4121                         return JIM_OK;
4122                 }
4123                 break;
4124         case TS_CMD_RESET:
4125                 if (goi.argc != 2) {
4126                         Jim_WrongNumArgs(interp, 2, argv,
4127                                         "([tT]|[fF]|assert|deassert) BOOL");
4128                         return JIM_ERR;
4129                 }
4130                 e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4131                 if (e != JIM_OK) {
4132                         Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4133                         return e;
4134                 }
4135                 /* the halt or not param */
4136                 e = Jim_GetOpt_Wide(&goi, &a);
4137                 if (e != JIM_OK) {
4138                         return e;
4139                 }
4140                 if (!target->tap->enabled)
4141                         goto err_tap_disabled;
4142                 if (!target->type->assert_reset
4143                                 || !target->type->deassert_reset) {
4144                         Jim_SetResult_sprintf(interp,
4145                                         "No target-specific reset for %s",
4146                                         target->cmd_name);
4147                         return JIM_ERR;
4148                 }
4149                 /* determine if we should halt or not. */
4150                 target->reset_halt = !!a;
4151                 /* When this happens - all workareas are invalid. */
4152                 target_free_all_working_areas_restore(target, 0);
4153
4154                 /* do the assert */
4155                 if (n->value == NVP_ASSERT) {
4156                         e = target->type->assert_reset(target);
4157                 } else {
4158                         e = target->type->deassert_reset(target);
4159                 }
4160                 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4161         case TS_CMD_HALT:
4162                 if (goi.argc) {
4163                         Jim_WrongNumArgs(goi.interp, 0, argv, "halt [no parameters]");
4164                         return JIM_ERR;
4165                 }
4166                 if (!target->tap->enabled)
4167                         goto err_tap_disabled;
4168                 e = target->type->halt(target);
4169                 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4170         case TS_CMD_WAITSTATE:
4171                 /* params:  <name>  statename timeoutmsecs */
4172                 if (goi.argc != 2) {
4173                         Jim_SetResult_sprintf(goi.interp, "%s STATENAME TIMEOUTMSECS", n->name);
4174                         return JIM_ERR;
4175                 }
4176                 e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4177                 if (e != JIM_OK) {
4178                         Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4179                         return e;
4180                 }
4181                 e = Jim_GetOpt_Wide(&goi, &a);
4182                 if (e != JIM_OK) {
4183                         return e;
4184                 }
4185                 if (!target->tap->enabled)
4186                         goto err_tap_disabled;
4187                 e = target_wait_state(target, n->value, a);
4188                 if (e != ERROR_OK) {
4189                         Jim_SetResult_sprintf(goi.interp,
4190                                                                    "target: %s wait %s fails (%d) %s",
4191                                                                    target->cmd_name,
4192                                                                    n->name,
4193                                                                    e, target_strerror_safe(e));
4194                         return JIM_ERR;
4195                 } else {
4196                         return JIM_OK;
4197                 }
4198         case TS_CMD_EVENTLIST:
4199                 /* List for human, Events defined for this target.
4200                  * scripts/programs should use 'name cget -event NAME'
4201                  */
4202                 {
4203                         target_event_action_t *teap;
4204                         teap = target->event_action;
4205                         command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4206                                                    target->target_number,
4207                                                    target->cmd_name);
4208                         command_print(cmd_ctx, "%-25s | Body", "Event");
4209                         command_print(cmd_ctx, "------------------------- | ----------------------------------------");
4210                         while (teap) {
4211                                 command_print(cmd_ctx,
4212                                                            "%-25s | %s",
4213                                                            Jim_Nvp_value2name_simple(nvp_target_event, teap->event)->name,
4214                                                            Jim_GetString(teap->body, NULL));
4215                                 teap = teap->next;
4216                         }
4217                         command_print(cmd_ctx, "***END***");
4218                         return JIM_OK;
4219                 }
4220         case TS_CMD_CURSTATE:
4221                 if (goi.argc != 0) {
4222                         Jim_WrongNumArgs(goi.interp, 0, argv, "[no parameters]");
4223                         return JIM_ERR;
4224                 }
4225                 Jim_SetResultString(goi.interp,
4226                                                         target_state_name( target ),
4227                                                         -1);
4228                 return JIM_OK;
4229         case TS_CMD_INVOKE_EVENT:
4230                 if (goi.argc != 1) {
4231                         Jim_SetResult_sprintf(goi.interp, "%s ?EVENTNAME?",n->name);
4232                         return JIM_ERR;
4233                 }
4234                 e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4235                 if (e != JIM_OK) {
4236                         Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4237                         return e;
4238                 }
4239                 target_handle_event(target, n->value);
4240                 return JIM_OK;
4241         }
4242         return JIM_ERR;
4243
4244 err_tap_disabled:
4245         Jim_SetResult_sprintf(interp, "[TAP is disabled]");
4246         return JIM_ERR;
4247 }
4248
4249 static int target_create(Jim_GetOptInfo *goi)
4250 {
4251         Jim_Obj *new_cmd;
4252         Jim_Cmd *cmd;
4253         const char *cp;
4254         char *cp2;
4255         int e;
4256         int x;
4257         target_t *target;
4258         struct command_context_s *cmd_ctx;
4259
4260         cmd_ctx = Jim_GetAssocData(goi->interp, "context");
4261         if (goi->argc < 3) {
4262                 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4263                 return JIM_ERR;
4264         }
4265
4266         /* COMMAND */
4267         Jim_GetOpt_Obj(goi, &new_cmd);
4268         /* does this command exist? */
4269         cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4270         if (cmd) {
4271                 cp = Jim_GetString(new_cmd, NULL);
4272                 Jim_SetResult_sprintf(goi->interp, "Command/target: %s Exists", cp);
4273                 return JIM_ERR;
4274         }
4275
4276         /* TYPE */
4277         e = Jim_GetOpt_String(goi, &cp2, NULL);
4278         cp = cp2;
4279         /* now does target type exist */
4280         for (x = 0 ; target_types[x] ; x++) {
4281                 if (0 == strcmp(cp, target_types[x]->name)) {
4282                         /* found */
4283                         break;
4284                 }
4285         }
4286         if (target_types[x] == NULL) {
4287                 Jim_SetResult_sprintf(goi->interp, "Unknown target type %s, try one of ", cp);
4288                 for (x = 0 ; target_types[x] ; x++) {
4289                         if (target_types[x + 1]) {
4290                                 Jim_AppendStrings(goi->interp,
4291                                                                    Jim_GetResult(goi->interp),
4292                                                                    target_types[x]->name,
4293                                                                    ", ", NULL);
4294                         } else {
4295                                 Jim_AppendStrings(goi->interp,
4296                                                                    Jim_GetResult(goi->interp),
4297                                                                    " or ",
4298                                                                    target_types[x]->name,NULL);
4299                         }
4300                 }
4301                 return JIM_ERR;
4302         }
4303
4304         /* Create it */
4305         target = calloc(1,sizeof(target_t));
4306         /* set target number */
4307         target->target_number = new_target_number();
4308
4309         /* allocate memory for each unique target type */
4310         target->type = (target_type_t*)calloc(1,sizeof(target_type_t));
4311
4312         memcpy(target->type, target_types[x], sizeof(target_type_t));
4313
4314         /* will be set by "-endian" */
4315         target->endianness = TARGET_ENDIAN_UNKNOWN;
4316
4317         target->working_area        = 0x0;
4318         target->working_area_size   = 0x0;
4319         target->working_areas       = NULL;
4320         target->backup_working_area = 0;
4321
4322         target->state               = TARGET_UNKNOWN;
4323         target->debug_reason        = DBG_REASON_UNDEFINED;
4324         target->reg_cache           = NULL;
4325         target->breakpoints         = NULL;
4326         target->watchpoints         = NULL;
4327         target->next                = NULL;
4328         target->arch_info           = NULL;
4329
4330         target->display             = 1;
4331
4332         target->halt_issued                     = false;
4333
4334         /* initialize trace information */
4335         target->trace_info = malloc(sizeof(trace_t));
4336         target->trace_info->num_trace_points         = 0;
4337         target->trace_info->trace_points_size        = 0;
4338         target->trace_info->trace_points             = NULL;
4339         target->trace_info->trace_history_size       = 0;
4340         target->trace_info->trace_history            = NULL;
4341         target->trace_info->trace_history_pos        = 0;
4342         target->trace_info->trace_history_overflowed = 0;
4343
4344         target->dbgmsg          = NULL;
4345         target->dbg_msg_enabled = 0;
4346
4347         target->endianness = TARGET_ENDIAN_UNKNOWN;
4348
4349         /* Do the rest as "configure" options */
4350         goi->isconfigure = 1;
4351         e = target_configure(goi, target);
4352
4353         if (target->tap == NULL)
4354         {
4355                 Jim_SetResultString(interp, "-chain-position required when creating target", -1);
4356                 e = JIM_ERR;
4357         }
4358
4359         if (e != JIM_OK) {
4360                 free(target->type);
4361                 free(target);
4362                 return e;
4363         }
4364
4365         if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4366                 /* default endian to little if not specified */
4367                 target->endianness = TARGET_LITTLE_ENDIAN;
4368         }
4369
4370         /* incase variant is not set */
4371         if (!target->variant)
4372                 target->variant = strdup("");
4373
4374         /* create the target specific commands */
4375         if (target->type->register_commands) {
4376                 (*(target->type->register_commands))(cmd_ctx);
4377         }
4378         if (target->type->target_create) {
4379                 (*(target->type->target_create))(target, goi->interp);
4380         }
4381
4382         /* append to end of list */
4383         {
4384                 target_t **tpp;
4385                 tpp = &(all_targets);
4386                 while (*tpp) {
4387                         tpp = &((*tpp)->next);
4388                 }
4389                 *tpp = target;
4390         }
4391
4392         cp = Jim_GetString(new_cmd, NULL);
4393         target->cmd_name = strdup(cp);
4394
4395         /* now - create the new target name command */
4396         e = Jim_CreateCommand(goi->interp,
4397                                                    /* name */
4398                                                    cp,
4399                                                    tcl_target_func, /* C function */
4400                                                    target, /* private data */
4401                                                    NULL); /* no del proc */
4402
4403         return e;
4404 }
4405
4406 static int jim_target(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4407 {
4408         int x,r,e;
4409         jim_wide w;
4410         struct command_context_s *cmd_ctx;
4411         target_t *target;
4412         Jim_GetOptInfo goi;
4413         enum tcmd {
4414                 /* TG = target generic */
4415                 TG_CMD_CREATE,
4416                 TG_CMD_TYPES,
4417                 TG_CMD_NAMES,
4418                 TG_CMD_CURRENT,
4419                 TG_CMD_NUMBER,
4420                 TG_CMD_COUNT,
4421         };
4422         const char *target_cmds[] = {
4423                 "create", "types", "names", "current", "number",
4424                 "count",
4425                 NULL /* terminate */
4426         };
4427
4428         LOG_DEBUG("Target command params:");
4429         LOG_DEBUG("%s", Jim_Debug_ArgvString(interp, argc, argv));
4430
4431         cmd_ctx = Jim_GetAssocData(interp, "context");
4432
4433         Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
4434
4435         if (goi.argc == 0) {
4436                 Jim_WrongNumArgs(interp, 1, argv, "missing: command ...");
4437                 return JIM_ERR;
4438         }
4439
4440         /* Jim_GetOpt_Debug(&goi); */
4441         r = Jim_GetOpt_Enum(&goi, target_cmds, &x);
4442         if (r != JIM_OK) {
4443                 return r;
4444         }
4445
4446         switch (x) {
4447         default:
4448                 Jim_Panic(goi.interp,"Why am I here?");
4449                 return JIM_ERR;
4450         case TG_CMD_CURRENT:
4451                 if (goi.argc != 0) {
4452                         Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4453                         return JIM_ERR;
4454                 }
4455                 Jim_SetResultString(goi.interp, get_current_target(cmd_ctx)->cmd_name, -1);
4456                 return JIM_OK;
4457         case TG_CMD_TYPES:
4458                 if (goi.argc != 0) {
4459                         Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4460                         return JIM_ERR;
4461                 }
4462                 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4463                 for (x = 0 ; target_types[x] ; x++) {
4464                         Jim_ListAppendElement(goi.interp,
4465                                                                    Jim_GetResult(goi.interp),
4466                                                                    Jim_NewStringObj(goi.interp, target_types[x]->name, -1));
4467                 }
4468                 return JIM_OK;
4469         case TG_CMD_NAMES:
4470                 if (goi.argc != 0) {
4471                         Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4472                         return JIM_ERR;
4473                 }
4474                 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4475                 target = all_targets;
4476                 while (target) {
4477                         Jim_ListAppendElement(goi.interp,
4478                                                                    Jim_GetResult(goi.interp),
4479                                                                    Jim_NewStringObj(goi.interp, target->cmd_name, -1));
4480                         target = target->next;
4481                 }
4482                 return JIM_OK;
4483         case TG_CMD_CREATE:
4484                 if (goi.argc < 3) {
4485                         Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "?name  ... config options ...");
4486                         return JIM_ERR;
4487                 }
4488                 return target_create(&goi);
4489                 break;
4490         case TG_CMD_NUMBER:
4491                 /* It's OK to remove this mechanism sometime after August 2010 or so */
4492                 LOG_WARNING("don't use numbers as target identifiers; use names");
4493                 if (goi.argc != 1) {
4494                         Jim_SetResult_sprintf(goi.interp, "expected: target number ?NUMBER?");
4495                         return JIM_ERR;
4496                 }
4497                 e = Jim_GetOpt_Wide(&goi, &w);
4498                 if (e != JIM_OK) {
4499                         return JIM_ERR;
4500                 }
4501                 for (x = 0, target = all_targets; target; target = target->next, x++) {
4502                         if (target->target_number == w)
4503                                 break;
4504                 }
4505                 if (target == NULL) {
4506                         Jim_SetResult_sprintf(goi.interp,
4507                                         "Target: number %d does not exist", (int)(w));
4508                         return JIM_ERR;
4509                 }
4510                 Jim_SetResultString(goi.interp, target->cmd_name, -1);
4511                 return JIM_OK;
4512         case TG_CMD_COUNT:
4513                 if (goi.argc != 0) {
4514                         Jim_WrongNumArgs(goi.interp, 0, goi.argv, "<no parameters>");
4515                         return JIM_ERR;
4516                 }
4517                 for (x = 0, target = all_targets; target; target = target->next, x++)
4518                         continue;
4519                 Jim_SetResult(goi.interp, Jim_NewIntObj(goi.interp, x));
4520                 return JIM_OK;
4521         }
4522
4523         return JIM_ERR;
4524 }
4525
4526
4527 struct FastLoad
4528 {
4529         uint32_t address;
4530         uint8_t *data;
4531         int length;
4532
4533 };
4534
4535 static int fastload_num;
4536 static struct FastLoad *fastload;
4537
4538 static void free_fastload(void)
4539 {
4540         if (fastload != NULL)
4541         {
4542                 int i;
4543                 for (i = 0; i < fastload_num; i++)
4544                 {
4545                         if (fastload[i].data)
4546                                 free(fastload[i].data);
4547                 }
4548                 free(fastload);
4549                 fastload = NULL;
4550         }
4551 }
4552
4553
4554
4555
4556 static int handle_fast_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
4557 {
4558         uint8_t *buffer;
4559         uint32_t buf_cnt;
4560         uint32_t image_size;
4561         uint32_t min_address = 0;
4562         uint32_t max_address = 0xffffffff;
4563         int i;
4564
4565         image_t image;
4566
4567         duration_t duration;
4568         char *duration_text;
4569
4570         int retval = parse_load_image_command_args(args, argc,
4571                         &image, &min_address, &max_address);
4572         if (ERROR_OK != retval)
4573                 return retval;
4574
4575         duration_start_measure(&duration);
4576
4577         if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
4578         {
4579                 return ERROR_OK;
4580         }
4581
4582         image_size = 0x0;
4583         retval = ERROR_OK;
4584         fastload_num = image.num_sections;
4585         fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
4586         if (fastload == NULL)
4587         {
4588                 image_close(&image);
4589                 return ERROR_FAIL;
4590         }
4591         memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
4592         for (i = 0; i < image.num_sections; i++)
4593         {
4594                 buffer = malloc(image.sections[i].size);
4595                 if (buffer == NULL)
4596                 {
4597                         command_print(cmd_ctx, "error allocating buffer for section (%d bytes)",
4598                                                   (int)(image.sections[i].size));
4599                         break;
4600                 }
4601
4602                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
4603                 {
4604                         free(buffer);
4605                         break;
4606                 }
4607
4608                 uint32_t offset = 0;
4609                 uint32_t length = buf_cnt;
4610
4611
4612                 /* DANGER!!! beware of unsigned comparision here!!! */
4613
4614                 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
4615                                 (image.sections[i].base_address < max_address))
4616                 {
4617                         if (image.sections[i].base_address < min_address)
4618                         {
4619                                 /* clip addresses below */
4620                                 offset += min_address-image.sections[i].base_address;
4621                                 length -= offset;
4622                         }
4623
4624                         if (image.sections[i].base_address + buf_cnt > max_address)
4625                         {
4626                                 length -= (image.sections[i].base_address + buf_cnt)-max_address;
4627                         }
4628
4629                         fastload[i].address = image.sections[i].base_address + offset;
4630                         fastload[i].data = malloc(length);
4631                         if (fastload[i].data == NULL)
4632                         {
4633                                 free(buffer);
4634                                 break;
4635                         }
4636                         memcpy(fastload[i].data, buffer + offset, length);
4637                         fastload[i].length = length;
4638
4639                         image_size += length;
4640                         command_print(cmd_ctx, "%u bytes written at address 0x%8.8x",
4641                                                   (unsigned int)length,
4642                                                   ((unsigned int)(image.sections[i].base_address + offset)));
4643                 }
4644
4645                 free(buffer);
4646         }
4647
4648         duration_stop_measure(&duration, &duration_text);
4649         if (retval == ERROR_OK)
4650         {
4651                 command_print(cmd_ctx, "Loaded %u bytes in %s", (unsigned int)image_size, duration_text);
4652                 command_print(cmd_ctx, "NB!!! image has not been loaded to target, issue a subsequent 'fast_load' to do so.");
4653         }
4654         free(duration_text);
4655
4656         image_close(&image);
4657
4658         if (retval != ERROR_OK)
4659         {
4660                 free_fastload();
4661         }
4662
4663         return retval;
4664 }
4665
4666 static int handle_fast_load_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
4667 {
4668         if (argc > 0)
4669                 return ERROR_COMMAND_SYNTAX_ERROR;
4670         if (fastload == NULL)
4671         {
4672                 LOG_ERROR("No image in memory");
4673                 return ERROR_FAIL;
4674         }
4675         int i;
4676         int ms = timeval_ms();
4677         int size = 0;
4678         int retval = ERROR_OK;
4679         for (i = 0; i < fastload_num;i++)
4680         {
4681                 target_t *target = get_current_target(cmd_ctx);
4682                 command_print(cmd_ctx, "Write to 0x%08x, length 0x%08x",
4683                                           (unsigned int)(fastload[i].address),
4684                                           (unsigned int)(fastload[i].length));
4685                 if (retval == ERROR_OK)
4686                 {
4687                         retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
4688                 }
4689                 size += fastload[i].length;
4690         }
4691         int after = timeval_ms();
4692         command_print(cmd_ctx, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
4693         return retval;
4694 }
4695
4696
4697 /*
4698  * Local Variables:
4699  * c-basic-offset: 4
4700  * tab-width: 4
4701  * End:
4702  */