"reset" without arguments now execute a "reset run".
[fw/openocd] / src / target / target.c
1 /***************************************************************************
2  *   Copyright (C) 2005 by Dominic Rath                                    *
3  *   Dominic.Rath@gmx.de                                                   *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) any later version.                                   *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
19  ***************************************************************************/
20 #ifdef HAVE_CONFIG_H
21 #include "config.h"
22 #endif
23
24 #include "replacements.h"
25 #include "target.h"
26 #include "target_request.h"
27
28 #include "log.h"
29 #include "configuration.h"
30 #include "binarybuffer.h"
31 #include "jtag.h"
32
33 #include <string.h>
34 #include <stdlib.h>
35 #include <inttypes.h>
36
37 #include <sys/types.h>
38 #include <sys/stat.h>
39 #include <unistd.h>
40 #include <errno.h>
41
42 #include <sys/time.h>
43 #include <time.h>
44
45 #include <time_support.h>
46
47 #include <fileio.h>
48 #include <image.h>
49
50 int cli_target_callback_event_handler(struct target_s *target, enum target_event event, void *priv);
51
52 int handle_target_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
53 int handle_targets_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
54
55 int handle_run_and_halt_time_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
56 int handle_working_area_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
57
58 int handle_reg_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
59 int handle_poll_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
60 int handle_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
61 int handle_wait_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
62 int handle_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
63 int handle_soft_reset_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
64 int handle_resume_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
65 int handle_step_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
66 int handle_md_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
67 int handle_mw_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
68 int handle_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
69 int handle_dump_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
70 int handle_verify_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
71 int handle_bp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
72 int handle_rbp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
73 int handle_wp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
74 int handle_rwp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
75 int handle_virt2phys_command(command_context_t *cmd_ctx, char *cmd, char **args, int argc);
76 int handle_profile_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
77 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
78 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
79
80
81 /* targets */
82 extern target_type_t arm7tdmi_target;
83 extern target_type_t arm720t_target;
84 extern target_type_t arm9tdmi_target;
85 extern target_type_t arm920t_target;
86 extern target_type_t arm966e_target;
87 extern target_type_t arm926ejs_target;
88 extern target_type_t feroceon_target;
89 extern target_type_t xscale_target;
90 extern target_type_t cortexm3_target;
91 extern target_type_t arm11_target;
92
93 target_type_t *target_types[] =
94 {
95         &arm7tdmi_target,
96         &arm9tdmi_target,
97         &arm920t_target,
98         &arm720t_target,
99         &arm966e_target,
100         &arm926ejs_target,
101         &feroceon_target,
102         &xscale_target,
103         &cortexm3_target,
104         &arm11_target,
105         NULL,
106 };
107
108 target_t *targets = NULL;
109 target_event_callback_t *target_event_callbacks = NULL;
110 target_timer_callback_t *target_timer_callbacks = NULL;
111
112 char *target_state_strings[] =
113 {
114         "unknown",
115         "running",
116         "halted",
117         "reset",
118         "debug_running",
119 };
120
121 char *target_debug_reason_strings[] =
122 {
123         "debug request", "breakpoint", "watchpoint",
124         "watchpoint and breakpoint", "single step",
125         "target not halted", "undefined"
126 };
127
128 char *target_endianess_strings[] =
129 {
130         "big endian",
131         "little endian",
132 };
133
134 static int target_continous_poll = 1;
135
136 /* read a u32 from a buffer in target memory endianness */
137 u32 target_buffer_get_u32(target_t *target, u8 *buffer)
138 {
139         if (target->endianness == TARGET_LITTLE_ENDIAN)
140                 return le_to_h_u32(buffer);
141         else
142                 return be_to_h_u32(buffer);
143 }
144
145 /* read a u16 from a buffer in target memory endianness */
146 u16 target_buffer_get_u16(target_t *target, u8 *buffer)
147 {
148         if (target->endianness == TARGET_LITTLE_ENDIAN)
149                 return le_to_h_u16(buffer);
150         else
151                 return be_to_h_u16(buffer);
152 }
153
154 /* write a u32 to a buffer in target memory endianness */
155 void target_buffer_set_u32(target_t *target, u8 *buffer, u32 value)
156 {
157         if (target->endianness == TARGET_LITTLE_ENDIAN)
158                 h_u32_to_le(buffer, value);
159         else
160                 h_u32_to_be(buffer, value);
161 }
162
163 /* write a u16 to a buffer in target memory endianness */
164 void target_buffer_set_u16(target_t *target, u8 *buffer, u16 value)
165 {
166         if (target->endianness == TARGET_LITTLE_ENDIAN)
167                 h_u16_to_le(buffer, value);
168         else
169                 h_u16_to_be(buffer, value);
170 }
171
172 /* returns a pointer to the n-th configured target */
173 target_t* get_target_by_num(int num)
174 {
175         target_t *target = targets;
176         int i = 0;
177
178         while (target)
179         {
180                 if (num == i)
181                         return target;
182                 target = target->next;
183                 i++;
184         }
185
186         return NULL;
187 }
188
189 int get_num_by_target(target_t *query_target)
190 {
191         target_t *target = targets;
192         int i = 0;      
193         
194         while (target)
195         {
196                 if (target == query_target)
197                         return i;
198                 target = target->next;
199                 i++;
200         }
201         
202         return -1;
203 }
204
205 target_t* get_current_target(command_context_t *cmd_ctx)
206 {
207         target_t *target = get_target_by_num(cmd_ctx->current_target);
208         
209         if (target == NULL)
210         {
211                 LOG_ERROR("BUG: current_target out of bounds");
212                 exit(-1);
213         }
214         
215         return target;
216 }
217
218 /* Process target initialization, when target entered debug out of reset
219  * the handler is unregistered at the end of this function, so it's only called once
220  */
221 int target_init_handler(struct target_s *target, enum target_event event, void *priv)
222 {
223         struct command_context_s *cmd_ctx = priv;
224         
225         if (event == TARGET_EVENT_HALTED)
226         {
227                 target_unregister_event_callback(target_init_handler, priv);
228                 target_invoke_script(cmd_ctx, target, "post_reset");
229                 jtag_execute_queue();
230         }
231         
232         return ERROR_OK;
233 }
234
235 int target_run_and_halt_handler(void *priv)
236 {
237         target_t *target = priv;
238         
239         target_halt(target);
240         
241         return ERROR_OK;
242 }
243
244 int target_poll(struct target_s *target)
245 {
246         /* We can't poll until after examine */
247         if (!target->type->examined)
248         {
249                 /* Fail silently lest we pollute the log */
250                 return ERROR_FAIL;
251         }
252         return target->type->poll(target);
253 }
254
255 int target_halt(struct target_s *target)
256 {
257         /* We can't poll until after examine */
258         if (!target->type->examined)
259         {
260                 LOG_ERROR("Target not examined yet");
261                 return ERROR_FAIL;
262         }
263         return target->type->halt(target);
264 }
265
266 int target_resume(struct target_s *target, int current, u32 address, int handle_breakpoints, int debug_execution)
267 {
268         int retval;
269         
270         /* We can't poll until after examine */
271         if (!target->type->examined)
272         {
273                 LOG_ERROR("Target not examined yet");
274                 return ERROR_FAIL;
275         }
276         
277         /* note that resume *must* be asynchronous. The CPU can halt before we poll. The CPU can
278          * even halt at the current PC as a result of a software breakpoint being inserted by (a bug?)
279          * the application.
280          */
281         if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
282                 return retval;
283         
284         return retval;
285 }
286
287 int target_process_reset(struct command_context_s *cmd_ctx)
288 {
289         int retval = ERROR_OK;
290         target_t *target;
291         struct timeval timeout, now;
292
293         jtag->speed(jtag_speed);
294
295         target = targets;
296         while (target)
297         {
298                 target_invoke_script(cmd_ctx, target, "pre_reset");
299                 target = target->next;
300         }
301         
302         if ((retval = jtag_init_reset(cmd_ctx)) != ERROR_OK)
303                 return retval;
304         
305         keep_alive(); /* we might be running on a very slow JTAG clk */
306         
307         /* First time this is executed after launching OpenOCD, it will read out 
308          * the type of CPU, etc. and init Embedded ICE registers in host
309          * memory. 
310          * 
311          * It will also set up ICE registers in the target.
312          * 
313          * However, if we assert TRST later, we need to set up the registers again. 
314          * 
315          * For the "reset halt/init" case we must only set up the registers here.
316          */
317         if ((retval = target_examine(cmd_ctx)) != ERROR_OK)
318                 return retval;
319         
320         keep_alive(); /* we might be running on a very slow JTAG clk */
321         
322         /* prepare reset_halt where necessary */
323         target = targets;
324         while (target)
325         {
326                 if (jtag_reset_config & RESET_SRST_PULLS_TRST)
327                 {
328                         switch (target->reset_mode)
329                         {
330                                 case RESET_HALT:
331                                         command_print(cmd_ctx, "nSRST pulls nTRST, falling back to \"reset run_and_halt\"");
332                                         target->reset_mode = RESET_RUN_AND_HALT;
333                                         break;
334                                 case RESET_INIT:
335                                         command_print(cmd_ctx, "nSRST pulls nTRST, falling back to \"reset run_and_init\"");
336                                         target->reset_mode = RESET_RUN_AND_INIT;
337                                         break;
338                                 default:
339                                         break;
340                         } 
341                 }
342                 target = target->next;
343         }
344         
345         target = targets;
346         while (target)
347         {
348                 /* we have no idea what state the target is in, so we
349                  * have to drop working areas
350                  */
351                 target_free_all_working_areas_restore(target, 0);
352                 target->type->assert_reset(target);
353                 target = target->next;
354         }
355         if ((retval = jtag_execute_queue()) != ERROR_OK)
356         {
357                 LOG_WARNING("JTAG communication failed asserting reset.");
358                 retval = ERROR_OK;
359         }
360         
361         /* request target halt if necessary, and schedule further action */
362         target = targets;
363         while (target)
364         {
365                 switch (target->reset_mode)
366                 {
367                         case RESET_RUN:
368                                 /* nothing to do if target just wants to be run */
369                                 break;
370                         case RESET_RUN_AND_HALT:
371                                 /* schedule halt */
372                                 target_register_timer_callback(target_run_and_halt_handler, target->run_and_halt_time, 0, target);
373                                 break;
374                         case RESET_RUN_AND_INIT:
375                                 /* schedule halt */
376                                 target_register_timer_callback(target_run_and_halt_handler, target->run_and_halt_time, 0, target);
377                                 target_register_event_callback(target_init_handler, cmd_ctx);
378                                 break;
379                         case RESET_HALT:
380                                 target_halt(target);
381                                 break;
382                         case RESET_INIT:
383                                 target_halt(target);
384                                 target_register_event_callback(target_init_handler, cmd_ctx);
385                                 break;
386                         default:
387                                 LOG_ERROR("BUG: unknown target->reset_mode");
388                 }
389                 target = target->next;
390         }
391         
392         if ((retval = jtag_execute_queue()) != ERROR_OK)
393         {
394                 LOG_WARNING("JTAG communication failed while reset was asserted. Consider using srst_only for reset_config.");
395                 retval = ERROR_OK;              
396         }
397         
398         target = targets;
399         while (target)
400         {
401                 target->type->deassert_reset(target);
402                 target = target->next;
403         }
404         
405         if ((retval = jtag_execute_queue()) != ERROR_OK)
406         {
407                 LOG_WARNING("JTAG communication failed while deasserting reset.");
408                 retval = ERROR_OK;
409         }
410
411         if (jtag_reset_config & RESET_SRST_PULLS_TRST)
412         {
413                 /* If TRST was asserted we need to set up registers again */
414                 if ((retval = target_examine(cmd_ctx)) != ERROR_OK)
415                         return retval;
416         }               
417         
418         /* post reset scripts can be quite long, increase speed now. If post
419          * reset scripts needs a different speed, they can set the speed to
420          * whatever they need.
421          */
422         jtag->speed(jtag_speed_post_reset);
423         
424         LOG_DEBUG("Waiting for halted stated as approperiate");
425         
426         /* Wait for reset to complete, maximum 5 seconds. */    
427         gettimeofday(&timeout, NULL);
428         timeval_add_time(&timeout, 5, 0);
429         for(;;)
430         {
431                 gettimeofday(&now, NULL);
432                 
433                 target_call_timer_callbacks_now();
434                 
435                 target = targets;
436                 while (target)
437                 {
438                         LOG_DEBUG("Polling target");
439                         target_poll(target);
440                         if ((target->reset_mode == RESET_RUN_AND_INIT) || 
441                                         (target->reset_mode == RESET_RUN_AND_HALT) ||
442                                         (target->reset_mode == RESET_HALT) ||
443                                         (target->reset_mode == RESET_INIT))
444                         {
445                                 if (target->state != TARGET_HALTED)
446                                 {
447                                         if ((now.tv_sec > timeout.tv_sec) || ((now.tv_sec == timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
448                                         {
449                                                 LOG_USER("Timed out waiting for halt after reset");
450                                                 goto done;
451                                         }
452                                         /* this will send alive messages on e.g. GDB remote protocol. */
453                                         usleep(500*1000); 
454                                         LOG_USER_N("%s", ""); /* avoid warning about zero length formatting message*/ 
455                                         goto again;
456                                 }
457                         }
458                         target = target->next;
459                 }
460                 /* All targets we're waiting for are halted */
461                 break;
462                 
463                 again:;
464         }
465         done:
466         
467         
468         /* We want any events to be processed before the prompt */
469         target_call_timer_callbacks_now();
470
471         /* if we timed out we need to unregister these handlers */
472         target = targets;
473         while (target)
474         {
475                 target_unregister_timer_callback(target_run_and_halt_handler, target);
476                 target = target->next;
477         }
478         target_unregister_event_callback(target_init_handler, cmd_ctx);
479         
480         
481         return retval;
482 }
483
484 static int default_virt2phys(struct target_s *target, u32 virtual, u32 *physical)
485 {
486         *physical = virtual;
487         return ERROR_OK;
488 }
489
490 static int default_mmu(struct target_s *target, int *enabled)
491 {
492         *enabled = 0;
493         return ERROR_OK;
494 }
495
496 static int default_examine(struct command_context_s *cmd_ctx, struct target_s *target)
497 {
498         target->type->examined = 1;
499         return ERROR_OK;
500 }
501
502
503 /* Targets that correctly implement init+examine, i.e.
504  * no communication with target during init:
505  * 
506  * XScale 
507  */
508 int target_examine(struct command_context_s *cmd_ctx)
509 {
510         int retval = ERROR_OK;
511         target_t *target = targets;
512         while (target)
513         {
514                 if ((retval = target->type->examine(cmd_ctx, target))!=ERROR_OK)
515                         return retval;
516                 target = target->next;
517         }
518         return retval;
519 }
520
521 static int target_write_memory_imp(struct target_s *target, u32 address, u32 size, u32 count, u8 *buffer)
522 {
523         if (!target->type->examined)
524         {
525                 LOG_ERROR("Target not examined yet");
526                 return ERROR_FAIL;
527         }
528         return target->type->write_memory_imp(target, address, size, count, buffer);
529 }
530
531 static int target_read_memory_imp(struct target_s *target, u32 address, u32 size, u32 count, u8 *buffer)
532 {
533         if (!target->type->examined)
534         {
535                 LOG_ERROR("Target not examined yet");
536                 return ERROR_FAIL;
537         }
538         return target->type->read_memory_imp(target, address, size, count, buffer);
539 }
540
541 static int target_soft_reset_halt_imp(struct target_s *target)
542 {
543         if (!target->type->examined)
544         {
545                 LOG_ERROR("Target not examined yet");
546                 return ERROR_FAIL;
547         }
548         return target->type->soft_reset_halt_imp(target);
549 }
550
551 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, u32 entry_point, u32 exit_point, int timeout_ms, void *arch_info)
552 {
553         if (!target->type->examined)
554         {
555                 LOG_ERROR("Target not examined yet");
556                 return ERROR_FAIL;
557         }
558         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);
559 }
560
561 int target_init(struct command_context_s *cmd_ctx)
562 {
563         target_t *target = targets;
564         
565         while (target)
566         {
567                 target->type->examined = 0;
568                 if (target->type->examine == NULL)
569                 {
570                         target->type->examine = default_examine;
571                 }
572                 
573                 if (target->type->init_target(cmd_ctx, target) != ERROR_OK)
574                 {
575                         LOG_ERROR("target '%s' init failed", target->type->name);
576                         exit(-1);
577                 }
578                 
579                 /* Set up default functions if none are provided by target */
580                 if (target->type->virt2phys == NULL)
581                 {
582                         target->type->virt2phys = default_virt2phys;
583                 }
584                 target->type->virt2phys = default_virt2phys;
585                 /* a non-invasive way(in terms of patches) to add some code that
586                  * runs before the type->write/read_memory implementation
587                  */
588                 target->type->write_memory_imp = target->type->write_memory;
589                 target->type->write_memory = target_write_memory_imp;
590                 target->type->read_memory_imp = target->type->read_memory;
591                 target->type->read_memory = target_read_memory_imp;
592                 target->type->soft_reset_halt_imp = target->type->soft_reset_halt;
593                 target->type->soft_reset_halt = target_soft_reset_halt_imp;
594                 target->type->run_algorithm_imp = target->type->run_algorithm;
595                 target->type->run_algorithm = target_run_algorithm_imp;
596
597                 
598                 if (target->type->mmu == NULL)
599                 {
600                         target->type->mmu = default_mmu;
601                 }
602                 target = target->next;
603         }
604         
605         if (targets)
606         {
607                 target_register_user_commands(cmd_ctx);
608                 target_register_timer_callback(handle_target, 100, 1, NULL);
609         }
610                 
611         return ERROR_OK;
612 }
613
614 int target_register_event_callback(int (*callback)(struct target_s *target, enum target_event event, void *priv), void *priv)
615 {
616         target_event_callback_t **callbacks_p = &target_event_callbacks;
617         
618         if (callback == NULL)
619         {
620                 return ERROR_INVALID_ARGUMENTS;
621         }
622         
623         if (*callbacks_p)
624         {
625                 while ((*callbacks_p)->next)
626                         callbacks_p = &((*callbacks_p)->next);
627                 callbacks_p = &((*callbacks_p)->next);
628         }
629         
630         (*callbacks_p) = malloc(sizeof(target_event_callback_t));
631         (*callbacks_p)->callback = callback;
632         (*callbacks_p)->priv = priv;
633         (*callbacks_p)->next = NULL;
634         
635         return ERROR_OK;
636 }
637
638 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
639 {
640         target_timer_callback_t **callbacks_p = &target_timer_callbacks;
641         struct timeval now;
642         
643         if (callback == NULL)
644         {
645                 return ERROR_INVALID_ARGUMENTS;
646         }
647         
648         if (*callbacks_p)
649         {
650                 while ((*callbacks_p)->next)
651                         callbacks_p = &((*callbacks_p)->next);
652                 callbacks_p = &((*callbacks_p)->next);
653         }
654         
655         (*callbacks_p) = malloc(sizeof(target_timer_callback_t));
656         (*callbacks_p)->callback = callback;
657         (*callbacks_p)->periodic = periodic;
658         (*callbacks_p)->time_ms = time_ms;
659         
660         gettimeofday(&now, NULL);
661         (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
662         time_ms -= (time_ms % 1000);
663         (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
664         if ((*callbacks_p)->when.tv_usec > 1000000)
665         {
666                 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
667                 (*callbacks_p)->when.tv_sec += 1;
668         }
669         
670         (*callbacks_p)->priv = priv;
671         (*callbacks_p)->next = NULL;
672         
673         return ERROR_OK;
674 }
675
676 int target_unregister_event_callback(int (*callback)(struct target_s *target, enum target_event event, void *priv), void *priv)
677 {
678         target_event_callback_t **p = &target_event_callbacks;
679         target_event_callback_t *c = target_event_callbacks;
680         
681         if (callback == NULL)
682         {
683                 return ERROR_INVALID_ARGUMENTS;
684         }
685                 
686         while (c)
687         {
688                 target_event_callback_t *next = c->next;
689                 if ((c->callback == callback) && (c->priv == priv))
690                 {
691                         *p = next;
692                         free(c);
693                         return ERROR_OK;
694                 }
695                 else
696                         p = &(c->next);
697                 c = next;
698         }
699         
700         return ERROR_OK;
701 }
702
703 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
704 {
705         target_timer_callback_t **p = &target_timer_callbacks;
706         target_timer_callback_t *c = target_timer_callbacks;
707         
708         if (callback == NULL)
709         {
710                 return ERROR_INVALID_ARGUMENTS;
711         }
712                 
713         while (c)
714         {
715                 target_timer_callback_t *next = c->next;
716                 if ((c->callback == callback) && (c->priv == priv))
717                 {
718                         *p = next;
719                         free(c);
720                         return ERROR_OK;
721                 }
722                 else
723                         p = &(c->next);
724                 c = next;
725         }
726         
727         return ERROR_OK;
728 }
729
730 int target_call_event_callbacks(target_t *target, enum target_event event)
731 {
732         target_event_callback_t *callback = target_event_callbacks;
733         target_event_callback_t *next_callback;
734         
735         LOG_DEBUG("target event %i", event);
736         
737         while (callback)
738         {
739                 next_callback = callback->next;
740                 callback->callback(target, event, callback->priv);
741                 callback = next_callback;
742         }
743         
744         return ERROR_OK;
745 }
746
747 static int target_call_timer_callbacks_check_time(int checktime)
748 {
749         target_timer_callback_t *callback = target_timer_callbacks;
750         target_timer_callback_t *next_callback;
751         struct timeval now;
752
753         keep_alive();
754         
755         gettimeofday(&now, NULL);
756         
757         while (callback)
758         {
759                 next_callback = callback->next;
760                 
761                 if ((!checktime&&callback->periodic)||
762                                 (((now.tv_sec >= callback->when.tv_sec) && (now.tv_usec >= callback->when.tv_usec))
763                                                 || (now.tv_sec > callback->when.tv_sec)))
764                 {
765                         if(callback->callback != NULL)
766                         {
767                                 callback->callback(callback->priv);
768                                 if (callback->periodic)
769                                 {
770                                         int time_ms = callback->time_ms;
771                                         callback->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
772                                         time_ms -= (time_ms % 1000);
773                                         callback->when.tv_sec = now.tv_sec + time_ms / 1000;
774                                         if (callback->when.tv_usec > 1000000)
775                                         {
776                                                 callback->when.tv_usec = callback->when.tv_usec - 1000000;
777                                                 callback->when.tv_sec += 1;
778                                         }
779                                 }
780                                 else
781                                         target_unregister_timer_callback(callback->callback, callback->priv);
782                         }
783                 }
784                         
785                 callback = next_callback;
786         }
787         
788         return ERROR_OK;
789 }
790
791 int target_call_timer_callbacks()
792 {
793         return target_call_timer_callbacks_check_time(1);
794 }
795
796 /* invoke periodic callbacks immediately */
797 int target_call_timer_callbacks_now()
798 {
799         return target_call_timer_callbacks(0);
800 }
801
802 int target_alloc_working_area(struct target_s *target, u32 size, working_area_t **area)
803 {
804         working_area_t *c = target->working_areas;
805         working_area_t *new_wa = NULL;
806         
807         /* Reevaluate working area address based on MMU state*/
808         if (target->working_areas == NULL)
809         {
810                 int retval;
811                 int enabled;
812                 retval = target->type->mmu(target, &enabled);
813                 if (retval != ERROR_OK)
814                 {
815                         return retval;
816                 }
817                 if (enabled)
818                 {
819                         target->working_area = target->working_area_virt;
820                 }
821                 else
822                 {
823                         target->working_area = target->working_area_phys;
824                 }
825         }
826         
827         /* only allocate multiples of 4 byte */
828         if (size % 4)
829         {
830                 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes, padding");
831                 size = CEIL(size, 4);
832         }
833         
834         /* see if there's already a matching working area */
835         while (c)
836         {
837                 if ((c->free) && (c->size == size))
838                 {
839                         new_wa = c;
840                         break;
841                 }
842                 c = c->next;
843         }
844         
845         /* if not, allocate a new one */
846         if (!new_wa)
847         {
848                 working_area_t **p = &target->working_areas;
849                 u32 first_free = target->working_area;
850                 u32 free_size = target->working_area_size;
851                 
852                 LOG_DEBUG("allocating new working area");
853                 
854                 c = target->working_areas;
855                 while (c)
856                 {
857                         first_free += c->size;
858                         free_size -= c->size;
859                         p = &c->next;
860                         c = c->next;
861                 }
862                 
863                 if (free_size < size)
864                 {
865                         LOG_WARNING("not enough working area available(requested %d, free %d)", size, free_size);
866                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
867                 }
868                 
869                 new_wa = malloc(sizeof(working_area_t));
870                 new_wa->next = NULL;
871                 new_wa->size = size;
872                 new_wa->address = first_free;
873                 
874                 if (target->backup_working_area)
875                 {
876                         new_wa->backup = malloc(new_wa->size);
877                         target->type->read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup);
878                 }
879                 else
880                 {
881                         new_wa->backup = NULL;
882                 }
883                 
884                 /* put new entry in list */
885                 *p = new_wa;
886         }
887         
888         /* mark as used, and return the new (reused) area */
889         new_wa->free = 0;
890         *area = new_wa;
891         
892         /* user pointer */
893         new_wa->user = area;
894         
895         return ERROR_OK;
896 }
897
898 int target_free_working_area_restore(struct target_s *target, working_area_t *area, int restore)
899 {
900         if (area->free)
901                 return ERROR_OK;
902         
903         if (restore&&target->backup_working_area)
904                 target->type->write_memory(target, area->address, 4, area->size / 4, area->backup);
905         
906         area->free = 1;
907         
908         /* mark user pointer invalid */
909         *area->user = NULL;
910         area->user = NULL;
911         
912         return ERROR_OK;
913 }
914
915 int target_free_working_area(struct target_s *target, working_area_t *area)
916 {
917         return target_free_working_area_restore(target, area, 1);
918 }
919
920 int target_free_all_working_areas_restore(struct target_s *target, int restore)
921 {
922         working_area_t *c = target->working_areas;
923
924         while (c)
925         {
926                 working_area_t *next = c->next;
927                 target_free_working_area_restore(target, c, restore);
928                 
929                 if (c->backup)
930                         free(c->backup);
931                 
932                 free(c);
933                 
934                 c = next;
935         }
936         
937         target->working_areas = NULL;
938         
939         return ERROR_OK;
940 }
941
942 int target_free_all_working_areas(struct target_s *target)
943 {
944         return target_free_all_working_areas_restore(target, 1); 
945 }
946
947 int target_register_commands(struct command_context_s *cmd_ctx)
948 {
949         register_command(cmd_ctx, NULL, "target", handle_target_command, COMMAND_CONFIG, "target <cpu> [reset_init default - DEPRECATED] <chainpos> <endianness> <variant> [cpu type specifc args]");
950         register_command(cmd_ctx, NULL, "targets", handle_targets_command, COMMAND_EXEC, NULL);
951         register_command(cmd_ctx, NULL, "run_and_halt_time", handle_run_and_halt_time_command, COMMAND_CONFIG, "<target> <run time ms>");
952         register_command(cmd_ctx, NULL, "working_area", handle_working_area_command, COMMAND_ANY, "working_area <target#> <address> <size> <'backup'|'nobackup'> [virtual address]");
953         register_command(cmd_ctx, NULL, "virt2phys", handle_virt2phys_command, COMMAND_ANY, "virt2phys <virtual address>");
954         register_command(cmd_ctx, NULL, "profile", handle_profile_command, COMMAND_EXEC, "PRELIMINARY! - profile <seconds> <gmon.out>");
955
956
957         /* script procedures */
958         register_jim(cmd_ctx, "openocd_mem2array", jim_mem2array, "read memory and return as a TCL array for script processing");
959         register_jim(cmd_ctx, "openocd_array2mem", jim_array2mem, "convert a TCL array to memory locations and write the values");
960         return ERROR_OK;
961 }
962
963 int target_arch_state(struct target_s *target)
964 {
965         int retval;
966         if (target==NULL)
967         {
968                 LOG_USER("No target has been configured");
969                 return ERROR_OK;
970         }
971         
972         LOG_USER("target state: %s", target_state_strings[target->state]);
973         
974         if (target->state!=TARGET_HALTED)
975                 return ERROR_OK;
976         
977         retval=target->type->arch_state(target);
978         return retval;
979 }
980
981 /* Single aligned words are guaranteed to use 16 or 32 bit access 
982  * mode respectively, otherwise data is handled as quickly as 
983  * possible
984  */
985 int target_write_buffer(struct target_s *target, u32 address, u32 size, u8 *buffer)
986 {
987         int retval;
988         if (!target->type->examined)
989         {
990                 LOG_ERROR("Target not examined yet");
991                 return ERROR_FAIL;
992         }
993         
994         LOG_DEBUG("writing buffer of %i byte at 0x%8.8x", size, address);
995         
996         if (((address % 2) == 0) && (size == 2))
997         {
998                 return target->type->write_memory(target, address, 2, 1, buffer);
999         }
1000         
1001         /* handle unaligned head bytes */
1002         if (address % 4)
1003         {
1004                 int unaligned = 4 - (address % 4);
1005                 
1006                 if (unaligned > size)
1007                         unaligned = size;
1008
1009                 if ((retval = target->type->write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1010                         return retval;
1011                 
1012                 buffer += unaligned;
1013                 address += unaligned;
1014                 size -= unaligned;
1015         }
1016                 
1017         /* handle aligned words */
1018         if (size >= 4)
1019         {
1020                 int aligned = size - (size % 4);
1021         
1022                 /* use bulk writes above a certain limit. This may have to be changed */
1023                 if (aligned > 128)
1024                 {
1025                         if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1026                                 return retval;
1027                 }
1028                 else
1029                 {
1030                         if ((retval = target->type->write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1031                                 return retval;
1032                 }
1033                 
1034                 buffer += aligned;
1035                 address += aligned;
1036                 size -= aligned;
1037         }
1038         
1039         /* handle tail writes of less than 4 bytes */
1040         if (size > 0)
1041         {
1042                 if ((retval = target->type->write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1043                         return retval;
1044         }
1045         
1046         return ERROR_OK;
1047 }
1048
1049
1050 /* Single aligned words are guaranteed to use 16 or 32 bit access 
1051  * mode respectively, otherwise data is handled as quickly as 
1052  * possible
1053  */
1054 int target_read_buffer(struct target_s *target, u32 address, u32 size, u8 *buffer)
1055 {
1056         int retval;
1057         if (!target->type->examined)
1058         {
1059                 LOG_ERROR("Target not examined yet");
1060                 return ERROR_FAIL;
1061         }
1062
1063         LOG_DEBUG("reading buffer of %i byte at 0x%8.8x", size, address);
1064         
1065         if (((address % 2) == 0) && (size == 2))
1066         {
1067                 return target->type->read_memory(target, address, 2, 1, buffer);
1068         }
1069         
1070         /* handle unaligned head bytes */
1071         if (address % 4)
1072         {
1073                 int unaligned = 4 - (address % 4);
1074                 
1075                 if (unaligned > size)
1076                         unaligned = size;
1077
1078                 if ((retval = target->type->read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1079                         return retval;
1080                 
1081                 buffer += unaligned;
1082                 address += unaligned;
1083                 size -= unaligned;
1084         }
1085                 
1086         /* handle aligned words */
1087         if (size >= 4)
1088         {
1089                 int aligned = size - (size % 4);
1090         
1091                 if ((retval = target->type->read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1092                         return retval;
1093                 
1094                 buffer += aligned;
1095                 address += aligned;
1096                 size -= aligned;
1097         }
1098         
1099         /* handle tail writes of less than 4 bytes */
1100         if (size > 0)
1101         {
1102                 if ((retval = target->type->read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1103                         return retval;
1104         }
1105         
1106         return ERROR_OK;
1107 }
1108
1109 int target_checksum_memory(struct target_s *target, u32 address, u32 size, u32* crc)
1110 {
1111         u8 *buffer;
1112         int retval;
1113         int i;
1114         u32 checksum = 0;
1115         if (!target->type->examined)
1116         {
1117                 LOG_ERROR("Target not examined yet");
1118                 return ERROR_FAIL;
1119         }
1120         
1121         if ((retval = target->type->checksum_memory(target, address,
1122                 size, &checksum)) == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1123         {
1124                 buffer = malloc(size);
1125                 if (buffer == NULL)
1126                 {
1127                         LOG_ERROR("error allocating buffer for section (%d bytes)", size);
1128                         return ERROR_INVALID_ARGUMENTS;
1129                 }
1130                 retval = target_read_buffer(target, address, size, buffer);
1131                 if (retval != ERROR_OK)
1132                 {
1133                         free(buffer);
1134                         return retval;
1135                 }
1136
1137                 /* convert to target endianess */
1138                 for (i = 0; i < (size/sizeof(u32)); i++)
1139                 {
1140                         u32 target_data;
1141                         target_data = target_buffer_get_u32(target, &buffer[i*sizeof(u32)]);
1142                         target_buffer_set_u32(target, &buffer[i*sizeof(u32)], target_data);
1143                 }
1144
1145                 retval = image_calculate_checksum( buffer, size, &checksum );
1146                 free(buffer);
1147         }
1148         
1149         *crc = checksum;
1150         
1151         return retval;
1152 }
1153
1154 int target_blank_check_memory(struct target_s *target, u32 address, u32 size, u32* blank)
1155 {
1156         int retval;
1157         if (!target->type->examined)
1158         {
1159                 LOG_ERROR("Target not examined yet");
1160                 return ERROR_FAIL;
1161         }
1162         
1163         if (target->type->blank_check_memory == 0)
1164                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1165         
1166         retval = target->type->blank_check_memory(target, address, size, blank);
1167                         
1168         return retval;
1169 }
1170
1171 int target_read_u32(struct target_s *target, u32 address, u32 *value)
1172 {
1173         u8 value_buf[4];
1174         if (!target->type->examined)
1175         {
1176                 LOG_ERROR("Target not examined yet");
1177                 return ERROR_FAIL;
1178         }
1179
1180         int retval = target->type->read_memory(target, address, 4, 1, value_buf);
1181         
1182         if (retval == ERROR_OK)
1183         {
1184                 *value = target_buffer_get_u32(target, value_buf);
1185                 LOG_DEBUG("address: 0x%8.8x, value: 0x%8.8x", address, *value);
1186         }
1187         else
1188         {
1189                 *value = 0x0;
1190                 LOG_DEBUG("address: 0x%8.8x failed", address);
1191         }
1192         
1193         return retval;
1194 }
1195
1196 int target_read_u16(struct target_s *target, u32 address, u16 *value)
1197 {
1198         u8 value_buf[2];
1199         if (!target->type->examined)
1200         {
1201                 LOG_ERROR("Target not examined yet");
1202                 return ERROR_FAIL;
1203         }
1204
1205         int retval = target->type->read_memory(target, address, 2, 1, value_buf);
1206         
1207         if (retval == ERROR_OK)
1208         {
1209                 *value = target_buffer_get_u16(target, value_buf);
1210                 LOG_DEBUG("address: 0x%8.8x, value: 0x%4.4x", address, *value);
1211         }
1212         else
1213         {
1214                 *value = 0x0;
1215                 LOG_DEBUG("address: 0x%8.8x failed", address);
1216         }
1217         
1218         return retval;
1219 }
1220
1221 int target_read_u8(struct target_s *target, u32 address, u8 *value)
1222 {
1223         int retval = target->type->read_memory(target, address, 1, 1, value);
1224         if (!target->type->examined)
1225         {
1226                 LOG_ERROR("Target not examined yet");
1227                 return ERROR_FAIL;
1228         }
1229
1230         if (retval == ERROR_OK)
1231         {
1232                 LOG_DEBUG("address: 0x%8.8x, value: 0x%2.2x", address, *value);
1233         }
1234         else
1235         {
1236                 *value = 0x0;
1237                 LOG_DEBUG("address: 0x%8.8x failed", address);
1238         }
1239         
1240         return retval;
1241 }
1242
1243 int target_write_u32(struct target_s *target, u32 address, u32 value)
1244 {
1245         int retval;
1246         u8 value_buf[4];
1247         if (!target->type->examined)
1248         {
1249                 LOG_ERROR("Target not examined yet");
1250                 return ERROR_FAIL;
1251         }
1252
1253         LOG_DEBUG("address: 0x%8.8x, value: 0x%8.8x", address, value);
1254
1255         target_buffer_set_u32(target, value_buf, value);        
1256         if ((retval = target->type->write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1257         {
1258                 LOG_DEBUG("failed: %i", retval);
1259         }
1260         
1261         return retval;
1262 }
1263
1264 int target_write_u16(struct target_s *target, u32 address, u16 value)
1265 {
1266         int retval;
1267         u8 value_buf[2];
1268         if (!target->type->examined)
1269         {
1270                 LOG_ERROR("Target not examined yet");
1271                 return ERROR_FAIL;
1272         }
1273
1274         LOG_DEBUG("address: 0x%8.8x, value: 0x%8.8x", address, value);
1275
1276         target_buffer_set_u16(target, value_buf, value);        
1277         if ((retval = target->type->write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1278         {
1279                 LOG_DEBUG("failed: %i", retval);
1280         }
1281         
1282         return retval;
1283 }
1284
1285 int target_write_u8(struct target_s *target, u32 address, u8 value)
1286 {
1287         int retval;
1288         if (!target->type->examined)
1289         {
1290                 LOG_ERROR("Target not examined yet");
1291                 return ERROR_FAIL;
1292         }
1293
1294         LOG_DEBUG("address: 0x%8.8x, value: 0x%2.2x", address, value);
1295
1296         if ((retval = target->type->read_memory(target, address, 1, 1, &value)) != ERROR_OK)
1297         {
1298                 LOG_DEBUG("failed: %i", retval);
1299         }
1300         
1301         return retval;
1302 }
1303
1304 int target_register_user_commands(struct command_context_s *cmd_ctx)
1305 {
1306         register_command(cmd_ctx,  NULL, "reg", handle_reg_command, COMMAND_EXEC, NULL);
1307         register_command(cmd_ctx,  NULL, "poll", handle_poll_command, COMMAND_EXEC, "poll target state");
1308         register_command(cmd_ctx,  NULL, "wait_halt", handle_wait_halt_command, COMMAND_EXEC, "wait for target halt [time (s)]");
1309         register_command(cmd_ctx,  NULL, "halt", handle_halt_command, COMMAND_EXEC, "halt target");
1310         register_command(cmd_ctx,  NULL, "resume", handle_resume_command, COMMAND_EXEC, "resume target [addr]");
1311         register_command(cmd_ctx,  NULL, "step", handle_step_command, COMMAND_EXEC, "step one instruction from current PC or [addr]");
1312         register_command(cmd_ctx,  NULL, "reset", handle_reset_command, COMMAND_EXEC, "reset target [run|halt|init|run_and_halt|run_and_init]");
1313         register_command(cmd_ctx,  NULL, "soft_reset_halt", handle_soft_reset_halt_command, COMMAND_EXEC, "halt the target and do a soft reset");
1314
1315         register_command(cmd_ctx,  NULL, "mdw", handle_md_command, COMMAND_EXEC, "display memory words <addr> [count]");
1316         register_command(cmd_ctx,  NULL, "mdh", handle_md_command, COMMAND_EXEC, "display memory half-words <addr> [count]");
1317         register_command(cmd_ctx,  NULL, "mdb", handle_md_command, COMMAND_EXEC, "display memory bytes <addr> [count]");
1318         
1319         register_command(cmd_ctx,  NULL, "mww", handle_mw_command, COMMAND_EXEC, "write memory word <addr> <value> [count]");
1320         register_command(cmd_ctx,  NULL, "mwh", handle_mw_command, COMMAND_EXEC, "write memory half-word <addr> <value> [count]");
1321         register_command(cmd_ctx,  NULL, "mwb", handle_mw_command, COMMAND_EXEC, "write memory byte <addr> <value> [count]");
1322         
1323         register_command(cmd_ctx,  NULL, "bp", handle_bp_command, COMMAND_EXEC, "set breakpoint <address> <length> [hw]");      
1324         register_command(cmd_ctx,  NULL, "rbp", handle_rbp_command, COMMAND_EXEC, "remove breakpoint <adress>");
1325         register_command(cmd_ctx,  NULL, "wp", handle_wp_command, COMMAND_EXEC, "set watchpoint <address> <length> <r/w/a> [value] [mask]");    
1326         register_command(cmd_ctx,  NULL, "rwp", handle_rwp_command, COMMAND_EXEC, "remove watchpoint <adress>");
1327         
1328         register_command(cmd_ctx,  NULL, "load_image", handle_load_image_command, COMMAND_EXEC, "load_image <file> <address> ['bin'|'ihex'|'elf'|'s19']");
1329         register_command(cmd_ctx,  NULL, "dump_image", handle_dump_image_command, COMMAND_EXEC, "dump_image <file> <address> <size>");
1330         register_command(cmd_ctx,  NULL, "verify_image", handle_verify_image_command, COMMAND_EXEC, "verify_image <file> [offset] [type]");
1331         register_command(cmd_ctx,  NULL, "load_binary", handle_load_image_command, COMMAND_EXEC, "[DEPRECATED] load_binary <file> <address>");
1332         register_command(cmd_ctx,  NULL, "dump_binary", handle_dump_image_command, COMMAND_EXEC, "[DEPRECATED] dump_binary <file> <address> <size>");
1333         
1334         target_request_register_commands(cmd_ctx);
1335         trace_register_commands(cmd_ctx);
1336         
1337         return ERROR_OK;
1338 }
1339
1340 int handle_targets_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1341 {
1342         target_t *target = targets;
1343         int count = 0;
1344         
1345         if (argc == 1)
1346         {
1347                 int num = strtoul(args[0], NULL, 0);
1348                 
1349                 while (target)
1350                 {
1351                         count++;
1352                         target = target->next;
1353                 }
1354                 
1355                 if (num < count)
1356                         cmd_ctx->current_target = num;
1357                 else
1358                         command_print(cmd_ctx, "%i is out of bounds, only %i targets are configured", num, count);
1359                         
1360                 return ERROR_OK;
1361         }
1362                 
1363         while (target)
1364         {
1365                 command_print(cmd_ctx, "%i: %s (%s), state: %s", count++, target->type->name, target_endianess_strings[target->endianness], target_state_strings[target->state]);
1366                 target = target->next;
1367         }
1368         
1369         return ERROR_OK;
1370 }
1371
1372 int handle_target_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1373 {
1374         int i;
1375         int found = 0;
1376         
1377         if (argc < 3)
1378         {
1379                 return ERROR_COMMAND_SYNTAX_ERROR;
1380         }
1381         
1382         /* search for the specified target */
1383         if (args[0] && (args[0][0] != 0))
1384         {
1385                 for (i = 0; target_types[i]; i++)
1386                 {
1387                         if (strcmp(args[0], target_types[i]->name) == 0)
1388                         {
1389                                 target_t **last_target_p = &targets;
1390                                 
1391                                 /* register target specific commands */
1392                                 if (target_types[i]->register_commands(cmd_ctx) != ERROR_OK)
1393                                 {
1394                                         LOG_ERROR("couldn't register '%s' commands", args[0]);
1395                                         exit(-1);
1396                                 }
1397
1398                                 if (*last_target_p)
1399                                 {
1400                                         while ((*last_target_p)->next)
1401                                                 last_target_p = &((*last_target_p)->next);
1402                                         last_target_p = &((*last_target_p)->next);
1403                                 }
1404
1405                                 *last_target_p = malloc(sizeof(target_t));
1406                                 
1407                                 /* allocate memory for each unique target type */
1408                                 (*last_target_p)->type = (target_type_t*)malloc(sizeof(target_type_t));
1409                                 *((*last_target_p)->type) = *target_types[i]; 
1410                                 
1411                                 if (strcmp(args[1], "big") == 0)
1412                                         (*last_target_p)->endianness = TARGET_BIG_ENDIAN;
1413                                 else if (strcmp(args[1], "little") == 0)
1414                                         (*last_target_p)->endianness = TARGET_LITTLE_ENDIAN;
1415                                 else
1416                                 {
1417                                         LOG_ERROR("endianness must be either 'little' or 'big', not '%s'", args[1]);
1418                                         return ERROR_COMMAND_SYNTAX_ERROR;
1419                                 }
1420                                 
1421                                 if (strcmp(args[2], "reset_halt") == 0)
1422                                 {
1423                                         LOG_WARNING("reset_mode argument is deprecated. reset_mode = reset_run");
1424                                 }
1425                                 else if (strcmp(args[2], "reset_run") == 0)
1426                                 {
1427                                         LOG_WARNING("reset_mode argument is deprecated. reset_mode = reset_run");
1428                                 }
1429                                 else if (strcmp(args[2], "reset_init") == 0)
1430                                 {
1431                                         LOG_WARNING("reset_mode argument is deprecated. reset_mode = reset_run");
1432                                 }
1433                                 else if (strcmp(args[2], "run_and_halt") == 0)
1434                                 {
1435                                         LOG_WARNING("reset_mode argument is deprecated. reset_mode = reset_run");
1436                                 }
1437                                 else if (strcmp(args[2], "run_and_init") == 0)
1438                                 {
1439                                         LOG_WARNING("reset_mode argument is deprecated. reset_mode = reset_run");
1440                                 }
1441                                 else
1442                                 {
1443                                         /* Kludge! we want to make this reset arg optional while remaining compatible! */
1444                                         args--;
1445                                         argc++;
1446                                 }
1447                                 (*last_target_p)->run_and_halt_time = 1000; /* default 1s */
1448                                 
1449                                 (*last_target_p)->working_area = 0x0;
1450                                 (*last_target_p)->working_area_size = 0x0;
1451                                 (*last_target_p)->working_areas = NULL;
1452                                 (*last_target_p)->backup_working_area = 0;
1453                                 
1454                                 (*last_target_p)->state = TARGET_UNKNOWN;
1455                                 (*last_target_p)->debug_reason = DBG_REASON_UNDEFINED;
1456                                 (*last_target_p)->reg_cache = NULL;
1457                                 (*last_target_p)->breakpoints = NULL;
1458                                 (*last_target_p)->watchpoints = NULL;
1459                                 (*last_target_p)->next = NULL;
1460                                 (*last_target_p)->arch_info = NULL;
1461                                 
1462                                 /* initialize trace information */
1463                                 (*last_target_p)->trace_info = malloc(sizeof(trace_t));
1464                                 (*last_target_p)->trace_info->num_trace_points = 0;
1465                                 (*last_target_p)->trace_info->trace_points_size = 0;
1466                                 (*last_target_p)->trace_info->trace_points = NULL;
1467                                 (*last_target_p)->trace_info->trace_history_size = 0;
1468                                 (*last_target_p)->trace_info->trace_history = NULL;
1469                                 (*last_target_p)->trace_info->trace_history_pos = 0;
1470                                 (*last_target_p)->trace_info->trace_history_overflowed = 0;
1471                                 
1472                                 (*last_target_p)->dbgmsg = NULL;
1473                                 (*last_target_p)->dbg_msg_enabled = 0;
1474                                                                 
1475                                 (*last_target_p)->type->target_command(cmd_ctx, cmd, args, argc, *last_target_p);
1476                                 
1477                                 found = 1;
1478                                 break;
1479                         }
1480                 }
1481         }
1482         
1483         /* no matching target found */
1484         if (!found)
1485         {
1486                 LOG_ERROR("target '%s' not found", args[0]);
1487                 return ERROR_COMMAND_SYNTAX_ERROR;
1488         }
1489
1490         return ERROR_OK;
1491 }
1492
1493 int target_invoke_script(struct command_context_s *cmd_ctx, target_t *target, char *name)
1494 {
1495         return command_run_linef(cmd_ctx, " if {[catch {info body target_%s_%d} t]==0} {target_%s_%d}", 
1496         name, get_num_by_target(target),
1497         name, get_num_by_target(target));
1498 }
1499
1500 int handle_run_and_halt_time_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1501 {
1502         target_t *target = NULL;
1503         
1504         if (argc < 2)
1505         {
1506                 return ERROR_COMMAND_SYNTAX_ERROR;
1507         }
1508         
1509         target = get_target_by_num(strtoul(args[0], NULL, 0));
1510         if (!target)
1511         {
1512                 return ERROR_COMMAND_SYNTAX_ERROR;
1513         }
1514         
1515         target->run_and_halt_time = strtoul(args[1], NULL, 0);
1516         
1517         return ERROR_OK;
1518 }
1519
1520 int handle_working_area_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1521 {
1522         target_t *target = NULL;
1523         
1524         if ((argc < 4) || (argc > 5))
1525         {
1526                 return ERROR_COMMAND_SYNTAX_ERROR;
1527         }
1528         
1529         target = get_target_by_num(strtoul(args[0], NULL, 0));
1530         if (!target)
1531         {
1532                 return ERROR_COMMAND_SYNTAX_ERROR;
1533         }
1534         target_free_all_working_areas(target);
1535         
1536         target->working_area_phys = target->working_area_virt = strtoul(args[1], NULL, 0);
1537         if (argc == 5)
1538         {
1539                 target->working_area_virt = strtoul(args[4], NULL, 0);
1540         }
1541         target->working_area_size = strtoul(args[2], NULL, 0);
1542         
1543         if (strcmp(args[3], "backup") == 0)
1544         {
1545                 target->backup_working_area = 1;
1546         }
1547         else if (strcmp(args[3], "nobackup") == 0)
1548         {
1549                 target->backup_working_area = 0;
1550         }
1551         else
1552         {
1553                 LOG_ERROR("unrecognized <backup|nobackup> argument (%s)", args[3]);
1554                 return ERROR_COMMAND_SYNTAX_ERROR;
1555         }
1556         
1557         return ERROR_OK;
1558 }
1559
1560
1561 /* process target state changes */
1562 int handle_target(void *priv)
1563 {
1564         target_t *target = targets;
1565         
1566         while (target)
1567         {
1568                 if (target_continous_poll)
1569                 {
1570                         /* polling may fail silently until the target has been examined */
1571                         target_poll(target);
1572                 }
1573         
1574                 target = target->next;
1575         }
1576         
1577         return ERROR_OK;
1578 }
1579
1580 int handle_reg_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1581 {
1582         target_t *target;
1583         reg_t *reg = NULL;
1584         int count = 0;
1585         char *value;
1586         
1587         LOG_DEBUG("-");
1588         
1589         target = get_current_target(cmd_ctx);
1590         
1591         /* list all available registers for the current target */
1592         if (argc == 0)
1593         {
1594                 reg_cache_t *cache = target->reg_cache;
1595                 
1596                 count = 0;
1597                 while(cache)
1598                 {
1599                         int i;
1600                         for (i = 0; i < cache->num_regs; i++)
1601                         {
1602                                 value = buf_to_str(cache->reg_list[i].value, cache->reg_list[i].size, 16);
1603                                 command_print(cmd_ctx, "(%i) %s (/%i): 0x%s (dirty: %i, valid: %i)", count++, cache->reg_list[i].name, cache->reg_list[i].size, value, cache->reg_list[i].dirty, cache->reg_list[i].valid);
1604                                 free(value);
1605                         }
1606                         cache = cache->next;
1607                 }
1608                 
1609                 return ERROR_OK;
1610         }
1611         
1612         /* access a single register by its ordinal number */
1613         if ((args[0][0] >= '0') && (args[0][0] <= '9'))
1614         {
1615                 int num = strtoul(args[0], NULL, 0);
1616                 reg_cache_t *cache = target->reg_cache;
1617                 
1618                 count = 0;
1619                 while(cache)
1620                 {
1621                         int i;
1622                         for (i = 0; i < cache->num_regs; i++)
1623                         {
1624                                 if (count++ == num)
1625                                 {
1626                                         reg = &cache->reg_list[i];
1627                                         break;
1628                                 }
1629                         }
1630                         if (reg)
1631                                 break;
1632                         cache = cache->next;
1633                 }
1634                 
1635                 if (!reg)
1636                 {
1637                         command_print(cmd_ctx, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
1638                         return ERROR_OK;
1639                 }
1640         } else /* access a single register by its name */
1641         {
1642                 reg = register_get_by_name(target->reg_cache, args[0], 1);
1643                 
1644                 if (!reg)
1645                 {
1646                         command_print(cmd_ctx, "register %s not found in current target", args[0]);
1647                         return ERROR_OK;
1648                 }
1649         }
1650
1651         /* display a register */
1652         if ((argc == 1) || ((argc == 2) && !((args[1][0] >= '0') && (args[1][0] <= '9'))))
1653         {
1654                 if ((argc == 2) && (strcmp(args[1], "force") == 0))
1655                         reg->valid = 0;
1656                 
1657                 if (reg->valid == 0)
1658                 {
1659                         reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
1660                         if (arch_type == NULL)
1661                         {
1662                                 LOG_ERROR("BUG: encountered unregistered arch type");
1663                                 return ERROR_OK;
1664                         }
1665                         arch_type->get(reg);
1666                 }
1667                 value = buf_to_str(reg->value, reg->size, 16);
1668                 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, reg->size, value);
1669                 free(value);
1670                 return ERROR_OK;
1671         }
1672         
1673         /* set register value */
1674         if (argc == 2)
1675         {
1676                 u8 *buf = malloc(CEIL(reg->size, 8));
1677                 str_to_buf(args[1], strlen(args[1]), buf, reg->size, 0);
1678
1679                 reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
1680                 if (arch_type == NULL)
1681                 {
1682                         LOG_ERROR("BUG: encountered unregistered arch type");
1683                         return ERROR_OK;
1684                 }
1685                 
1686                 arch_type->set(reg, buf);
1687                 
1688                 value = buf_to_str(reg->value, reg->size, 16);
1689                 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, reg->size, value);
1690                 free(value);
1691                 
1692                 free(buf);
1693                 
1694                 return ERROR_OK;
1695         }
1696         
1697         command_print(cmd_ctx, "usage: reg <#|name> [value]");
1698         
1699         return ERROR_OK;
1700 }
1701
1702 static int wait_state(struct command_context_s *cmd_ctx, char *cmd, enum target_state state, int ms);
1703
1704 int handle_poll_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1705 {
1706         target_t *target = get_current_target(cmd_ctx);
1707
1708         if (argc == 0)
1709         {
1710                 target_poll(target);
1711                 target_arch_state(target);
1712         }
1713         else
1714         {
1715                 if (strcmp(args[0], "on") == 0)
1716                 {
1717                         target_continous_poll = 1;
1718                 }
1719                 else if (strcmp(args[0], "off") == 0)
1720                 {
1721                         target_continous_poll = 0;
1722                 }
1723                 else
1724                 {
1725                         command_print(cmd_ctx, "arg is \"on\" or \"off\"");
1726                 }
1727         }
1728         
1729         
1730         return ERROR_OK;
1731 }
1732
1733 int handle_wait_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1734 {
1735         int ms = 5000;
1736         
1737         if (argc > 0)
1738         {
1739                 char *end;
1740
1741                 ms = strtoul(args[0], &end, 0) * 1000;
1742                 if (*end)
1743                 {
1744                         command_print(cmd_ctx, "usage: %s [seconds]", cmd);
1745                         return ERROR_OK;
1746                 }
1747         }
1748
1749         return wait_state(cmd_ctx, cmd, TARGET_HALTED, ms); 
1750 }
1751
1752 static int wait_state(struct command_context_s *cmd_ctx, char *cmd, enum target_state state, int ms)
1753 {
1754         int retval;
1755         struct timeval timeout, now;
1756         int once=1;
1757         gettimeofday(&timeout, NULL);
1758         timeval_add_time(&timeout, 0, ms * 1000);
1759         
1760         target_t *target = get_current_target(cmd_ctx);
1761         for (;;)
1762         {
1763                 if ((retval=target_poll(target))!=ERROR_OK)
1764                         return retval;
1765                 target_call_timer_callbacks_now();
1766                 if (target->state == state)
1767                 {
1768                         break;
1769                 }
1770                 if (once)
1771                 {
1772                         once=0;
1773                         command_print(cmd_ctx, "waiting for target %s...", target_state_strings[state]);
1774                 }
1775                 
1776                 gettimeofday(&now, NULL);
1777                 if ((now.tv_sec > timeout.tv_sec) || ((now.tv_sec == timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
1778                 {
1779                         LOG_ERROR("timed out while waiting for target %s", target_state_strings[state]);
1780                         break;
1781                 }
1782         }
1783         
1784         return ERROR_OK;
1785 }
1786
1787 int handle_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1788 {
1789         int retval;
1790         target_t *target = get_current_target(cmd_ctx);
1791
1792         LOG_DEBUG("-");
1793
1794         if ((retval = target_halt(target)) != ERROR_OK)
1795         {
1796                 return retval;
1797         }
1798         
1799         return handle_wait_halt_command(cmd_ctx, cmd, args, argc);
1800 }
1801
1802 int handle_soft_reset_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1803 {
1804         target_t *target = get_current_target(cmd_ctx);
1805         
1806         LOG_USER("requesting target halt and executing a soft reset");
1807         
1808         target->type->soft_reset_halt(target);
1809         
1810         return ERROR_OK;
1811 }
1812
1813 int handle_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1814 {
1815         target_t *target = get_current_target(cmd_ctx);
1816         enum target_reset_mode reset_mode = RESET_RUN;
1817         
1818         LOG_DEBUG("-");
1819         
1820         if (argc >= 1)
1821         {
1822                 if (strcmp("run", args[0]) == 0)
1823                         reset_mode = RESET_RUN;
1824                 else if (strcmp("halt", args[0]) == 0)
1825                         reset_mode = RESET_HALT;
1826                 else if (strcmp("init", args[0]) == 0)
1827                         reset_mode = RESET_INIT;
1828                 else if (strcmp("run_and_halt", args[0]) == 0)
1829                 {
1830                         reset_mode = RESET_RUN_AND_HALT;
1831                         if (argc >= 2)
1832                         {
1833                                 target->run_and_halt_time = strtoul(args[1], NULL, 0);
1834                         }
1835                 }
1836                 else if (strcmp("run_and_init", args[0]) == 0)
1837                 {
1838                         reset_mode = RESET_RUN_AND_INIT;
1839                         if (argc >= 2)
1840                         {
1841                                 target->run_and_halt_time = strtoul(args[1], NULL, 0);
1842                         }
1843                 }
1844                 else
1845                 {
1846                         command_print(cmd_ctx, "usage: reset ['run', 'halt', 'init', 'run_and_halt', 'run_and_init]");
1847                         return ERROR_OK;
1848                 }
1849         }
1850         
1851         /* temporarily modify mode of current reset target */
1852         target->reset_mode = reset_mode;
1853
1854         /* reset *all* targets */
1855         target_process_reset(cmd_ctx);
1856         
1857         return ERROR_OK;
1858 }
1859
1860 int handle_resume_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1861 {
1862         int retval;
1863         target_t *target = get_current_target(cmd_ctx);
1864         
1865         target_invoke_script(cmd_ctx, target, "pre_resume");
1866         
1867         if (argc == 0)
1868                 retval = target_resume(target, 1, 0, 1, 0); /* current pc, addr = 0, handle breakpoints, not debugging */
1869         else if (argc == 1)
1870                 retval = target_resume(target, 0, strtoul(args[0], NULL, 0), 1, 0); /* addr = args[0], handle breakpoints, not debugging */
1871         else
1872         {
1873                 return ERROR_COMMAND_SYNTAX_ERROR;
1874         }
1875         
1876         return retval;
1877 }
1878
1879 int handle_step_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1880 {
1881         target_t *target = get_current_target(cmd_ctx);
1882         
1883         LOG_DEBUG("-");
1884         
1885         if (argc == 0)
1886                 target->type->step(target, 1, 0, 1); /* current pc, addr = 0, handle breakpoints */
1887
1888         if (argc == 1)
1889                 target->type->step(target, 0, strtoul(args[0], NULL, 0), 1); /* addr = args[0], handle breakpoints */
1890         
1891         return ERROR_OK;
1892 }
1893
1894 int handle_md_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1895 {
1896         const int line_bytecnt = 32;
1897         int count = 1;
1898         int size = 4;
1899         u32 address = 0;
1900         int line_modulo;
1901         int i;
1902
1903         char output[128];
1904         int output_len;
1905
1906         int retval;
1907
1908         u8 *buffer;
1909         target_t *target = get_current_target(cmd_ctx);
1910
1911         if (argc < 1)
1912                 return ERROR_OK;
1913
1914         if (argc == 2)
1915                 count = strtoul(args[1], NULL, 0);
1916
1917         address = strtoul(args[0], NULL, 0);
1918         
1919
1920         switch (cmd[2])
1921         {
1922                 case 'w':
1923                         size = 4; line_modulo = line_bytecnt / 4;
1924                         break;
1925                 case 'h':
1926                         size = 2; line_modulo = line_bytecnt / 2;
1927                         break;
1928                 case 'b':
1929                         size = 1; line_modulo = line_bytecnt / 1;
1930                         break;
1931                 default:
1932                         return ERROR_OK;
1933         }
1934
1935         buffer = calloc(count, size);
1936         retval  = target->type->read_memory(target, address, size, count, buffer);
1937         if (retval == ERROR_OK)
1938         {
1939                 output_len = 0;
1940         
1941                 for (i = 0; i < count; i++)
1942                 {
1943                         if (i%line_modulo == 0)
1944                                 output_len += snprintf(output + output_len, 128 - output_len, "0x%8.8x: ", address + (i*size));
1945                         
1946                         switch (size)
1947                         {
1948                                 case 4:
1949                                         output_len += snprintf(output + output_len, 128 - output_len, "%8.8x ", target_buffer_get_u32(target, &buffer[i*4]));
1950                                         break;
1951                                 case 2:
1952                                         output_len += snprintf(output + output_len, 128 - output_len, "%4.4x ", target_buffer_get_u16(target, &buffer[i*2]));
1953                                         break;
1954                                 case 1:
1955                                         output_len += snprintf(output + output_len, 128 - output_len, "%2.2x ", buffer[i*1]);
1956                                         break;
1957                         }
1958         
1959                         if ((i%line_modulo == line_modulo-1) || (i == count - 1))
1960                         {
1961                                 command_print(cmd_ctx, output);
1962                                 output_len = 0;
1963                         }
1964                 }
1965         }
1966
1967         free(buffer);
1968         
1969         return retval;
1970 }
1971
1972 int handle_mw_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1973 {
1974         u32 address = 0;
1975         u32 value = 0;
1976         int count = 1;
1977         int i;
1978         int wordsize;
1979         target_t *target = get_current_target(cmd_ctx);
1980         u8 value_buf[4];
1981
1982          if ((argc < 2) || (argc > 3))
1983                 return ERROR_COMMAND_SYNTAX_ERROR;
1984
1985         address = strtoul(args[0], NULL, 0);
1986         value = strtoul(args[1], NULL, 0);
1987         if (argc == 3)
1988                 count = strtoul(args[2], NULL, 0);
1989         
1990         switch (cmd[2])
1991         {
1992                 case 'w':
1993                         wordsize = 4;
1994                         target_buffer_set_u32(target, value_buf, value);
1995                         break;
1996                 case 'h':
1997                         wordsize = 2;
1998                         target_buffer_set_u16(target, value_buf, value);
1999                         break;
2000                 case 'b':
2001                         wordsize = 1;
2002                         value_buf[0] = value;
2003                         break;
2004                 default:
2005                         return ERROR_COMMAND_SYNTAX_ERROR;
2006         }
2007         for (i=0; i<count; i++)
2008         {
2009                 int retval;
2010                 switch (wordsize)
2011                 {
2012                         case 4:
2013                                 retval = target->type->write_memory(target, address + i*wordsize, 4, 1, value_buf);
2014                                 break;
2015                         case 2:
2016                                 retval = target->type->write_memory(target, address + i*wordsize, 2, 1, value_buf);
2017                                 break;
2018                         case 1:
2019                                 retval = target->type->write_memory(target, address + i*wordsize, 1, 1, value_buf);
2020                         break;
2021                         default:
2022                         return ERROR_OK;
2023                 }
2024                 if (retval!=ERROR_OK)
2025                 {
2026                         return retval;
2027                 }
2028         }
2029
2030         return ERROR_OK;
2031
2032 }
2033
2034 int handle_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2035 {
2036         u8 *buffer;
2037         u32 buf_cnt;
2038         u32 image_size;
2039         int i;
2040         int retval;
2041
2042         image_t image;  
2043         
2044         duration_t duration;
2045         char *duration_text;
2046         
2047         target_t *target = get_current_target(cmd_ctx);
2048
2049         if (argc < 1)
2050         {
2051                 command_print(cmd_ctx, "usage: load_image <filename> [address] [type]");
2052                 return ERROR_OK;
2053         }
2054         
2055         /* a base address isn't always necessary, default to 0x0 (i.e. don't relocate) */
2056         if (argc >= 2)
2057         {
2058                 image.base_address_set = 1;
2059                 image.base_address = strtoul(args[1], NULL, 0);
2060         }
2061         else
2062         {
2063                 image.base_address_set = 0;
2064         }
2065         
2066         image.start_address_set = 0;
2067
2068         duration_start_measure(&duration);
2069         
2070         if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
2071         {
2072                 return ERROR_OK;
2073         }
2074         
2075         image_size = 0x0;
2076         retval = ERROR_OK;
2077         for (i = 0; i < image.num_sections; i++)
2078         {
2079                 buffer = malloc(image.sections[i].size);
2080                 if (buffer == NULL)
2081                 {
2082                         command_print(cmd_ctx, "error allocating buffer for section (%d bytes)", image.sections[i].size);
2083                         break;
2084                 }
2085                 
2086                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2087                 {
2088                         free(buffer);
2089                         break;
2090                 }
2091                 if ((retval = target_write_buffer(target, image.sections[i].base_address, buf_cnt, buffer)) != ERROR_OK)
2092                 {
2093                         free(buffer);
2094                         break;
2095                 }
2096                 image_size += buf_cnt;
2097                 command_print(cmd_ctx, "%u byte written at address 0x%8.8x", buf_cnt, image.sections[i].base_address);
2098                 
2099                 free(buffer);
2100         }
2101
2102         duration_stop_measure(&duration, &duration_text);
2103         if (retval==ERROR_OK)
2104         {
2105                 command_print(cmd_ctx, "downloaded %u byte in %s", image_size, duration_text);
2106         }
2107         free(duration_text);
2108         
2109         image_close(&image);
2110
2111         return retval;
2112
2113 }
2114
2115 int handle_dump_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2116 {
2117         fileio_t fileio;
2118         
2119         u32 address;
2120         u32 size;
2121         u8 buffer[560];
2122         int retval=ERROR_OK;
2123         
2124         duration_t duration;
2125         char *duration_text;
2126         
2127         target_t *target = get_current_target(cmd_ctx);
2128
2129         if (argc != 3)
2130         {
2131                 command_print(cmd_ctx, "usage: dump_image <filename> <address> <size>");
2132                 return ERROR_OK;
2133         }
2134
2135         address = strtoul(args[1], NULL, 0);
2136         size = strtoul(args[2], NULL, 0);
2137
2138         if ((address & 3) || (size & 3))
2139         {
2140                 command_print(cmd_ctx, "only 32-bit aligned address and size are supported");
2141                 return ERROR_OK;
2142         }
2143         
2144         if (fileio_open(&fileio, args[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
2145         {
2146                 return ERROR_OK;
2147         }
2148         
2149         duration_start_measure(&duration);
2150         
2151         while (size > 0)
2152         {
2153                 u32 size_written;
2154                 u32 this_run_size = (size > 560) ? 560 : size;
2155                 
2156                 retval = target->type->read_memory(target, address, 4, this_run_size / 4, buffer);
2157                 if (retval != ERROR_OK)
2158                 {
2159                         break;
2160                 }
2161                 
2162                 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2163                 if (retval != ERROR_OK)
2164                 {
2165                         break;
2166                 }
2167                 
2168                 size -= this_run_size;
2169                 address += this_run_size;
2170         }
2171
2172         fileio_close(&fileio);
2173
2174         duration_stop_measure(&duration, &duration_text);
2175         if (retval==ERROR_OK)
2176         {
2177                 command_print(cmd_ctx, "dumped %"PRIi64" byte in %s", fileio.size, duration_text);
2178         }
2179         free(duration_text);
2180         
2181         return ERROR_OK;
2182 }
2183
2184 int handle_verify_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2185 {
2186         u8 *buffer;
2187         u32 buf_cnt;
2188         u32 image_size;
2189         int i;
2190         int retval;
2191         u32 checksum = 0;
2192         u32 mem_checksum = 0;
2193
2194         image_t image;  
2195         
2196         duration_t duration;
2197         char *duration_text;
2198         
2199         target_t *target = get_current_target(cmd_ctx);
2200         
2201         if (argc < 1)
2202         {
2203                 return ERROR_COMMAND_SYNTAX_ERROR;
2204         }
2205         
2206         if (!target)
2207         {
2208                 LOG_ERROR("no target selected");
2209                 return ERROR_FAIL;
2210         }
2211         
2212         duration_start_measure(&duration);
2213         
2214         if (argc >= 2)
2215         {
2216                 image.base_address_set = 1;
2217                 image.base_address = strtoul(args[1], NULL, 0);
2218         }
2219         else
2220         {
2221                 image.base_address_set = 0;
2222                 image.base_address = 0x0;
2223         }
2224
2225         image.start_address_set = 0;
2226
2227         if ((retval=image_open(&image, args[0], (argc == 3) ? args[2] : NULL)) != ERROR_OK)
2228         {
2229                 return retval;
2230         }
2231         
2232         image_size = 0x0;
2233         retval=ERROR_OK;
2234         for (i = 0; i < image.num_sections; i++)
2235         {
2236                 buffer = malloc(image.sections[i].size);
2237                 if (buffer == NULL)
2238                 {
2239                         command_print(cmd_ctx, "error allocating buffer for section (%d bytes)", image.sections[i].size);
2240                         break;
2241                 }
2242                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2243                 {
2244                         free(buffer);
2245                         break;
2246                 }
2247                 
2248                 /* calculate checksum of image */
2249                 image_calculate_checksum( buffer, buf_cnt, &checksum );
2250                 
2251                 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2252                 if( retval != ERROR_OK )
2253                 {
2254                         free(buffer);
2255                         break;
2256                 }
2257                 
2258                 if( checksum != mem_checksum )
2259                 {
2260                         /* failed crc checksum, fall back to a binary compare */
2261                         u8 *data;
2262                         
2263                         command_print(cmd_ctx, "checksum mismatch - attempting binary compare");
2264                         
2265                         data = (u8*)malloc(buf_cnt);
2266                         
2267                         /* Can we use 32bit word accesses? */
2268                         int size = 1;
2269                         int count = buf_cnt;
2270                         if ((count % 4) == 0)
2271                         {
2272                                 size *= 4;
2273                                 count /= 4;
2274                         }
2275                         retval = target->type->read_memory(target, image.sections[i].base_address, size, count, data);
2276                         if (retval == ERROR_OK)
2277                         {
2278                                 int t;
2279                                 for (t = 0; t < buf_cnt; t++)
2280                                 {
2281                                         if (data[t] != buffer[t])
2282                                         {
2283                                                 command_print(cmd_ctx, "Verify operation failed address 0x%08x. Was 0x%02x instead of 0x%02x\n", t + image.sections[i].base_address, data[t], buffer[t]);
2284                                                 free(data);
2285                                                 free(buffer);
2286                                                 retval=ERROR_FAIL;
2287                                                 goto done;
2288                                         }
2289                                 }
2290                         }
2291                         
2292                         free(data);
2293                 }
2294                 
2295                 free(buffer);
2296                 image_size += buf_cnt;
2297         }
2298 done:   
2299         duration_stop_measure(&duration, &duration_text);
2300         if (retval==ERROR_OK)
2301         {
2302                 command_print(cmd_ctx, "verified %u bytes in %s", image_size, duration_text);
2303         }
2304         free(duration_text);
2305         
2306         image_close(&image);
2307         
2308         return retval;
2309 }
2310
2311 int handle_bp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2312 {
2313         int retval;
2314         target_t *target = get_current_target(cmd_ctx);
2315
2316         if (argc == 0)
2317         {
2318                 breakpoint_t *breakpoint = target->breakpoints;
2319
2320                 while (breakpoint)
2321                 {
2322                         if (breakpoint->type == BKPT_SOFT)
2323                         {
2324                                 char* buf = buf_to_str(breakpoint->orig_instr, breakpoint->length, 16);
2325                                 command_print(cmd_ctx, "0x%8.8x, 0x%x, %i, 0x%s", breakpoint->address, breakpoint->length, breakpoint->set, buf);
2326                                 free(buf);
2327                         }
2328                         else
2329                         {
2330                                 command_print(cmd_ctx, "0x%8.8x, 0x%x, %i", breakpoint->address, breakpoint->length, breakpoint->set);
2331                         }
2332                         breakpoint = breakpoint->next;
2333                 }
2334         }
2335         else if (argc >= 2)
2336         {
2337                 int hw = BKPT_SOFT;
2338                 u32 length = 0;
2339
2340                 length = strtoul(args[1], NULL, 0);
2341                 
2342                 if (argc >= 3)
2343                         if (strcmp(args[2], "hw") == 0)
2344                                 hw = BKPT_HARD;
2345
2346                 if ((retval = breakpoint_add(target, strtoul(args[0], NULL, 0), length, hw)) != ERROR_OK)
2347                 {
2348                         LOG_ERROR("Failure setting breakpoints");
2349                 }
2350                 else
2351                 {
2352                         command_print(cmd_ctx, "breakpoint added at address 0x%8.8x", strtoul(args[0], NULL, 0));
2353                 }
2354         }
2355         else
2356         {
2357                 command_print(cmd_ctx, "usage: bp <address> <length> ['hw']");
2358         }
2359
2360         return ERROR_OK;
2361 }
2362
2363 int handle_rbp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2364 {
2365         target_t *target = get_current_target(cmd_ctx);
2366
2367         if (argc > 0)
2368                 breakpoint_remove(target, strtoul(args[0], NULL, 0));
2369
2370         return ERROR_OK;
2371 }
2372
2373 int handle_wp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2374 {
2375         target_t *target = get_current_target(cmd_ctx);
2376         int retval;
2377
2378         if (argc == 0)
2379         {
2380                 watchpoint_t *watchpoint = target->watchpoints;
2381
2382                 while (watchpoint)
2383                 {
2384                         command_print(cmd_ctx, "address: 0x%8.8x, len: 0x%8.8x, r/w/a: %i, value: 0x%8.8x, mask: 0x%8.8x", watchpoint->address, watchpoint->length, watchpoint->rw, watchpoint->value, watchpoint->mask);
2385                         watchpoint = watchpoint->next;
2386                 }
2387         } 
2388         else if (argc >= 2)
2389         {
2390                 enum watchpoint_rw type = WPT_ACCESS;
2391                 u32 data_value = 0x0;
2392                 u32 data_mask = 0xffffffff;
2393                 
2394                 if (argc >= 3)
2395                 {
2396                         switch(args[2][0])
2397                         {
2398                                 case 'r':
2399                                         type = WPT_READ;
2400                                         break;
2401                                 case 'w':
2402                                         type = WPT_WRITE;
2403                                         break;
2404                                 case 'a':
2405                                         type = WPT_ACCESS;
2406                                         break;
2407                                 default:
2408                                         command_print(cmd_ctx, "usage: wp <address> <length> [r/w/a] [value] [mask]");
2409                                         return ERROR_OK;
2410                         }
2411                 }
2412                 if (argc >= 4)
2413                 {
2414                         data_value = strtoul(args[3], NULL, 0);
2415                 }
2416                 if (argc >= 5)
2417                 {
2418                         data_mask = strtoul(args[4], NULL, 0);
2419                 }
2420                 
2421                 if ((retval = watchpoint_add(target, strtoul(args[0], NULL, 0),
2422                                 strtoul(args[1], NULL, 0), type, data_value, data_mask)) != ERROR_OK)
2423                 {
2424                         LOG_ERROR("Failure setting breakpoints");
2425                 }
2426         }
2427         else
2428         {
2429                 command_print(cmd_ctx, "usage: wp <address> <length> [r/w/a] [value] [mask]");
2430         }
2431                 
2432         return ERROR_OK;
2433 }
2434
2435 int handle_rwp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2436 {
2437         target_t *target = get_current_target(cmd_ctx);
2438
2439         if (argc > 0)
2440                 watchpoint_remove(target, strtoul(args[0], NULL, 0));
2441         
2442         return ERROR_OK;
2443 }
2444
2445 int handle_virt2phys_command(command_context_t *cmd_ctx, char *cmd, char **args, int argc)
2446 {
2447         int retval;
2448         target_t *target = get_current_target(cmd_ctx);
2449         u32 va;
2450         u32 pa;
2451
2452         if (argc != 1)
2453         {
2454                 return ERROR_COMMAND_SYNTAX_ERROR;
2455         }
2456         va = strtoul(args[0], NULL, 0);
2457
2458         retval = target->type->virt2phys(target, va, &pa);
2459         if (retval == ERROR_OK)
2460         {
2461                 command_print(cmd_ctx, "Physical address 0x%08x", pa);
2462         }
2463         else
2464         {
2465                 /* lower levels will have logged a detailed error which is 
2466                  * forwarded to telnet/GDB session.  
2467                  */
2468         }
2469         return retval;
2470 }
2471 static void writeLong(FILE *f, int l)
2472 {
2473         int i;
2474         for (i=0; i<4; i++)
2475         {
2476                 char c=(l>>(i*8))&0xff;
2477                 fwrite(&c, 1, 1, f); 
2478         }
2479         
2480 }
2481 static void writeString(FILE *f, char *s)
2482 {
2483         fwrite(s, 1, strlen(s), f); 
2484 }
2485
2486
2487
2488 // Dump a gmon.out histogram file.
2489 static void writeGmon(u32 *samples, int sampleNum, char *filename)
2490 {
2491         int i;
2492         FILE *f=fopen(filename, "w");
2493         if (f==NULL)
2494                 return;
2495         fwrite("gmon", 1, 4, f);
2496         writeLong(f, 0x00000001); // Version
2497         writeLong(f, 0); // padding
2498         writeLong(f, 0); // padding
2499         writeLong(f, 0); // padding
2500                                 
2501         fwrite("", 1, 1, f);  // GMON_TAG_TIME_HIST 
2502
2503         // figure out bucket size
2504         u32 min=samples[0];
2505         u32 max=samples[0];
2506         for (i=0; i<sampleNum; i++)
2507         {
2508                 if (min>samples[i])
2509                 {
2510                         min=samples[i];
2511                 }
2512                 if (max<samples[i])
2513                 {
2514                         max=samples[i];
2515                 }
2516         }
2517
2518         int addressSpace=(max-min+1);
2519         
2520         static int const maxBuckets=256*1024; // maximum buckets.
2521         int length=addressSpace;
2522         if (length > maxBuckets)
2523         {
2524                 length=maxBuckets; 
2525         }
2526         int *buckets=malloc(sizeof(int)*length);
2527         if (buckets==NULL)
2528         {
2529                 fclose(f);
2530                 return;
2531         }
2532         memset(buckets, 0, sizeof(int)*length);
2533         for (i=0; i<sampleNum;i++)
2534         {
2535                 u32 address=samples[i];
2536                 long long a=address-min;
2537                 long long b=length-1;
2538                 long long c=addressSpace-1;
2539                 int index=(a*b)/c; // danger!!!! int32 overflows 
2540                 buckets[index]++;
2541         }
2542         
2543         //                         append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr))
2544         writeLong(f, min);                                      // low_pc
2545         writeLong(f, max);              // high_pc
2546         writeLong(f, length);           // # of samples
2547         writeLong(f, 64000000);                         // 64MHz
2548         writeString(f, "seconds");
2549         for (i=0; i<(15-strlen("seconds")); i++)
2550         {
2551                 fwrite("", 1, 1, f);  // padding
2552         }
2553         writeString(f, "s");
2554                 
2555 //                         append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size)
2556         
2557         char *data=malloc(2*length);
2558         if (data!=NULL)
2559         {
2560                 for (i=0; i<length;i++)
2561                 {
2562                         int val;
2563                         val=buckets[i];
2564                         if (val>65535)
2565                         {
2566                                 val=65535;
2567                         }
2568                         data[i*2]=val&0xff;
2569                         data[i*2+1]=(val>>8)&0xff;
2570                 }
2571                 free(buckets);
2572                 fwrite(data, 1, length*2, f);
2573                 free(data);
2574         } else
2575         {
2576                 free(buckets);
2577         }
2578
2579         fclose(f);
2580 }
2581
2582 /* profiling samples the CPU PC as quickly as OpenOCD is able, which will be used as a random sampling of PC */
2583 int handle_profile_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2584 {
2585         target_t *target = get_current_target(cmd_ctx);
2586         struct timeval timeout, now;
2587         
2588         gettimeofday(&timeout, NULL);
2589         if (argc!=2)
2590         {
2591                 return ERROR_COMMAND_SYNTAX_ERROR;
2592         }
2593         char *end;
2594         timeval_add_time(&timeout, strtoul(args[0], &end, 0), 0);
2595         if (*end) 
2596         {
2597                 return ERROR_OK;
2598         }
2599         
2600         command_print(cmd_ctx, "Starting profiling. Halting and resuming the target as often as we can...");
2601
2602         static const int maxSample=10000;
2603         u32 *samples=malloc(sizeof(u32)*maxSample);
2604         if (samples==NULL)
2605                 return ERROR_OK;
2606         
2607         int numSamples=0;
2608         int retval=ERROR_OK;
2609         // hopefully it is safe to cache! We want to stop/restart as quickly as possible.
2610         reg_t *reg = register_get_by_name(target->reg_cache, "pc", 1);
2611         
2612         for (;;)
2613         {
2614                 target_poll(target);
2615                 if (target->state == TARGET_HALTED)
2616                 {
2617                         u32 t=*((u32 *)reg->value);
2618                         samples[numSamples++]=t;
2619                         retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
2620                         target_poll(target);
2621                         usleep(10*1000); // sleep 10ms, i.e. <100 samples/second.
2622                 } else if (target->state == TARGET_RUNNING)
2623                 {
2624                         // We want to quickly sample the PC.
2625                         target_halt(target);
2626                 } else
2627                 {
2628                         command_print(cmd_ctx, "Target not halted or running");
2629                         retval=ERROR_OK;
2630                         break;
2631                 }
2632                 if (retval!=ERROR_OK)
2633                 {
2634                         break;
2635                 }
2636                 
2637                 gettimeofday(&now, NULL);
2638                 if ((numSamples>=maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
2639                 {
2640                         command_print(cmd_ctx, "Profiling completed. %d samples.", numSamples);
2641                         target_poll(target);
2642                         if (target->state == TARGET_HALTED)
2643                         {
2644                                 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
2645                         }
2646                         target_poll(target);
2647                         writeGmon(samples, numSamples, args[1]);
2648                         command_print(cmd_ctx, "Wrote %s", args[1]);
2649                         break;
2650                 }
2651         }
2652         free(samples);
2653         
2654         return ERROR_OK;
2655 }
2656
2657 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, u32 val)
2658 {
2659         char *namebuf;
2660         Jim_Obj *nameObjPtr, *valObjPtr;
2661         int result;
2662
2663         namebuf = alloc_printf("%s(%d)", varname, idx);
2664         if (!namebuf)
2665                 return JIM_ERR;
2666         
2667         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
2668         valObjPtr = Jim_NewIntObj(interp, val);
2669         if (!nameObjPtr || !valObjPtr)
2670         {
2671                 free(namebuf);
2672                 return JIM_ERR;
2673         }
2674
2675         Jim_IncrRefCount(nameObjPtr);
2676         Jim_IncrRefCount(valObjPtr);
2677         result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
2678         Jim_DecrRefCount(interp, nameObjPtr);
2679         Jim_DecrRefCount(interp, valObjPtr);
2680         free(namebuf);
2681         /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
2682         return result;
2683 }
2684
2685 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
2686 {
2687         target_t *target;
2688         command_context_t *context;
2689         long l;
2690         u32 width;
2691         u32 len;
2692         u32 addr;
2693         u32 count;
2694         u32 v;
2695         const char *varname;
2696         u8 buffer[4096];
2697         int  i, n, e, retval;
2698
2699         /* argv[1] = name of array to receive the data
2700          * argv[2] = desired width
2701          * argv[3] = memory address 
2702          * argv[4] = count of times to read
2703          */
2704         if (argc != 5) {
2705                 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
2706                 return JIM_ERR;
2707         }
2708         varname = Jim_GetString(argv[1], &len);
2709         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
2710
2711         e = Jim_GetLong(interp, argv[2], &l);
2712         width = l;
2713         if (e != JIM_OK) {
2714                 return e;
2715         }
2716         
2717         e = Jim_GetLong(interp, argv[3], &l);
2718         addr = l;
2719         if (e != JIM_OK) {
2720                 return e;
2721         }
2722         e = Jim_GetLong(interp, argv[4], &l);
2723         len = l;
2724         if (e != JIM_OK) {
2725                 return e;
2726         }
2727         switch (width) {
2728                 case 8:
2729                         width = 1;
2730                         break;
2731                 case 16:
2732                         width = 2;
2733                         break;
2734                 case 32:
2735                         width = 4;
2736                         break;
2737                 default:
2738                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2739                         Jim_AppendStrings( interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL );
2740                         return JIM_ERR;
2741         }
2742         if (len == 0) {
2743                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2744                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
2745                 return JIM_ERR;
2746         }
2747         if ((addr + (len * width)) < addr) {
2748                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2749                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
2750                 return JIM_ERR;
2751         }
2752         /* absurd transfer size? */
2753         if (len > 65536) {
2754                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2755                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
2756                 return JIM_ERR;
2757         }               
2758                 
2759         if ((width == 1) ||
2760                 ((width == 2) && ((addr & 1) == 0)) ||
2761                 ((width == 4) && ((addr & 3) == 0))) {
2762                 /* all is well */
2763         } else {
2764                 char buf[100];
2765                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2766                 sprintf(buf, "mem2array address: 0x%08x is not aligned for %d byte reads", addr, width); 
2767                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
2768                 return JIM_ERR;
2769         }
2770
2771         context = Jim_GetAssocData(interp, "context");
2772         if (context == NULL)
2773         {
2774                 LOG_ERROR("mem2array: no command context");
2775                 return JIM_ERR;
2776         }
2777         target = get_current_target(context);
2778         if (target == NULL)
2779         {
2780                 LOG_ERROR("mem2array: no current target");
2781                 return JIM_ERR;
2782         }
2783         
2784         /* Transfer loop */
2785
2786         /* index counter */
2787         n = 0;
2788         /* assume ok */
2789         e = JIM_OK;
2790         while (len) {
2791                 /* Slurp... in buffer size chunks */
2792                 
2793                 count = len; /* in objects.. */
2794                 if (count > (sizeof(buffer)/width)) {
2795                         count = (sizeof(buffer)/width);
2796                 }
2797                 
2798                 retval = target->type->read_memory( target, addr, width, count, buffer );
2799                 if (retval != ERROR_OK) {
2800                         /* BOO !*/
2801                         LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed", addr, width, count);
2802                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2803                         Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
2804                         e = JIM_ERR;
2805                         len = 0;
2806                 } else {
2807                         v = 0; /* shut up gcc */
2808                         for (i = 0 ;i < count ;i++, n++) {
2809                                 switch (width) {
2810                                         case 4:
2811                                                 v = target_buffer_get_u32(target, &buffer[i*width]);
2812                                                 break;
2813                                         case 2:
2814                                                 v = target_buffer_get_u16(target, &buffer[i*width]);
2815                                                 break;
2816                                         case 1:
2817                                                 v = buffer[i] & 0x0ff;
2818                                                 break;
2819                                 }
2820                                 new_int_array_element(interp, varname, n, v);
2821                         }
2822                         len -= count;
2823                 }
2824         }
2825         
2826         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2827
2828         return JIM_OK;
2829 }
2830
2831 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, u32 *val)
2832 {
2833         char *namebuf;
2834         Jim_Obj *nameObjPtr, *valObjPtr;
2835         int result;
2836         long l;
2837
2838         namebuf = alloc_printf("%s(%d)", varname, idx);
2839         if (!namebuf)
2840                 return JIM_ERR;
2841
2842         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
2843         if (!nameObjPtr)
2844         {
2845                 free(namebuf);
2846                 return JIM_ERR;
2847         }
2848
2849         Jim_IncrRefCount(nameObjPtr);
2850         valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
2851         Jim_DecrRefCount(interp, nameObjPtr);
2852         free(namebuf);
2853         if (valObjPtr == NULL)
2854                 return JIM_ERR;
2855
2856         result = Jim_GetLong(interp, valObjPtr, &l);
2857         /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
2858         *val = l;
2859         return result;
2860 }
2861
2862 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
2863 {
2864         target_t *target;
2865         command_context_t *context;
2866         long l;
2867         u32 width;
2868         u32 len;
2869         u32 addr;
2870         u32 count;
2871         u32 v;
2872         const char *varname;
2873         u8 buffer[4096];
2874         int  i, n, e, retval;
2875
2876         /* argv[1] = name of array to get the data
2877          * argv[2] = desired width
2878          * argv[3] = memory address 
2879          * argv[4] = count to write
2880          */
2881         if (argc != 5) {
2882                 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
2883                 return JIM_ERR;
2884         }
2885         varname = Jim_GetString(argv[1], &len);
2886         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
2887
2888         e = Jim_GetLong(interp, argv[2], &l);
2889         width = l;
2890         if (e != JIM_OK) {
2891                 return e;
2892         }
2893         
2894         e = Jim_GetLong(interp, argv[3], &l);
2895         addr = l;
2896         if (e != JIM_OK) {
2897                 return e;
2898         }
2899         e = Jim_GetLong(interp, argv[4], &l);
2900         len = l;
2901         if (e != JIM_OK) {
2902                 return e;
2903         }
2904         switch (width) {
2905                 case 8:
2906                         width = 1;
2907                         break;
2908                 case 16:
2909                         width = 2;
2910                         break;
2911                 case 32:
2912                         width = 4;
2913                         break;
2914                 default:
2915                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2916                         Jim_AppendStrings( interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL );
2917                         return JIM_ERR;
2918         }
2919         if (len == 0) {
2920                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2921                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
2922                 return JIM_ERR;
2923         }
2924         if ((addr + (len * width)) < addr) {
2925                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2926                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
2927                 return JIM_ERR;
2928         }
2929         /* absurd transfer size? */
2930         if (len > 65536) {
2931                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2932                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
2933                 return JIM_ERR;
2934         }               
2935                 
2936         if ((width == 1) ||
2937                 ((width == 2) && ((addr & 1) == 0)) ||
2938                 ((width == 4) && ((addr & 3) == 0))) {
2939                 /* all is well */
2940         } else {
2941                 char buf[100];
2942                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2943                 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads", addr, width); 
2944                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
2945                 return JIM_ERR;
2946         }
2947
2948         context = Jim_GetAssocData(interp, "context");
2949         if (context == NULL)
2950         {
2951                 LOG_ERROR("array2mem: no command context");
2952                 return JIM_ERR;
2953         }
2954         target = get_current_target(context);
2955         if (target == NULL)
2956         {
2957                 LOG_ERROR("array2mem: no current target");
2958                 return JIM_ERR;
2959         }
2960         
2961         /* Transfer loop */
2962
2963         /* index counter */
2964         n = 0;
2965         /* assume ok */
2966         e = JIM_OK;
2967         while (len) {
2968                 /* Slurp... in buffer size chunks */
2969                 
2970                 count = len; /* in objects.. */
2971                 if (count > (sizeof(buffer)/width)) {
2972                         count = (sizeof(buffer)/width);
2973                 }
2974
2975                 v = 0; /* shut up gcc */
2976                 for (i = 0 ;i < count ;i++, n++) {
2977                         get_int_array_element(interp, varname, n, &v);
2978                         switch (width) {
2979                         case 4:
2980                                 target_buffer_set_u32(target, &buffer[i*width], v);
2981                                 break;
2982                         case 2:
2983                                 target_buffer_set_u16(target, &buffer[i*width], v);
2984                                 break;
2985                         case 1:
2986                                 buffer[i] = v & 0x0ff;
2987                                 break;
2988                         }
2989                 }
2990                 len -= count;
2991
2992                 retval = target->type->write_memory(target, addr, width, count, buffer);
2993                 if (retval != ERROR_OK) {
2994                         /* BOO !*/
2995                         LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed", addr, width, count);
2996                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2997                         Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
2998                         e = JIM_ERR;
2999                         len = 0;
3000                 }
3001         }
3002         
3003         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3004
3005         return JIM_OK;
3006 }