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