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