d78f3b1607e3d9a85975a34a4579bf9d95eeb07a
[openocd.git] / src / target / target.c
1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
4 * *
5 * Copyright (C) 2007-2010 √ėyvind Harboe *
6 * oyvind.harboe@zylin.com *
7 * *
8 * Copyright (C) 2008, Duane Ellis *
9 * openocd@duaneeellis.com *
10 * *
11 * Copyright (C) 2008 by Spencer Oliver *
12 * spen@spen-soft.co.uk *
13 * *
14 * Copyright (C) 2008 by Rick Altherr *
15 * kc8apf@kc8apf.net> *
16 * *
17 * Copyright (C) 2011 by Broadcom Corporation *
18 * Evan Hunter - ehunter@broadcom.com *
19 * *
20 * Copyright (C) ST-Ericsson SA 2011 *
21 * michel.jaouen@stericsson.com : smp minimum support *
22 * *
23 * Copyright (C) 2011 Andreas Fritiofson *
24 * andreas.fritiofson@gmail.com *
25 * *
26 * This program is free software; you can redistribute it and/or modify *
27 * it under the terms of the GNU General Public License as published by *
28 * the Free Software Foundation; either version 2 of the License, or *
29 * (at your option) any later version. *
30 * *
31 * This program is distributed in the hope that it will be useful, *
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
34 * GNU General Public License for more details. *
35 * *
36 * You should have received a copy of the GNU General Public License *
37 * along with this program; if not, write to the *
38 * Free Software Foundation, Inc., *
39 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
40 ***************************************************************************/
41
42 #ifdef HAVE_CONFIG_H
43 #include "config.h"
44 #endif
45
46 #include <helper/time_support.h>
47 #include <jtag/jtag.h>
48 #include <flash/nor/core.h>
49
50 #include "target.h"
51 #include "target_type.h"
52 #include "target_request.h"
53 #include "breakpoints.h"
54 #include "register.h"
55 #include "trace.h"
56 #include "image.h"
57 #include "rtos/rtos.h"
58
59 /* default halt wait timeout (ms) */
60 #define DEFAULT_HALT_TIMEOUT 5000
61
62 static int target_read_buffer_default(struct target *target, uint32_t address,
63 uint32_t count, uint8_t *buffer);
64 static int target_write_buffer_default(struct target *target, uint32_t address,
65 uint32_t count, const uint8_t *buffer);
66 static int target_array2mem(Jim_Interp *interp, struct target *target,
67 int argc, Jim_Obj * const *argv);
68 static int target_mem2array(Jim_Interp *interp, struct target *target,
69 int argc, Jim_Obj * const *argv);
70 static int target_register_user_commands(struct command_context *cmd_ctx);
71 static int target_get_gdb_fileio_info_default(struct target *target,
72 struct gdb_fileio_info *fileio_info);
73 static int target_gdb_fileio_end_default(struct target *target, int retcode,
74 int fileio_errno, bool ctrl_c);
75 static int target_profiling_default(struct target *target, uint32_t *samples,
76 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds);
77
78 /* targets */
79 extern struct target_type arm7tdmi_target;
80 extern struct target_type arm720t_target;
81 extern struct target_type arm9tdmi_target;
82 extern struct target_type arm920t_target;
83 extern struct target_type arm966e_target;
84 extern struct target_type arm946e_target;
85 extern struct target_type arm926ejs_target;
86 extern struct target_type fa526_target;
87 extern struct target_type feroceon_target;
88 extern struct target_type dragonite_target;
89 extern struct target_type xscale_target;
90 extern struct target_type cortexm_target;
91 extern struct target_type cortexa8_target;
92 extern struct target_type cortexr4_target;
93 extern struct target_type arm11_target;
94 extern struct target_type mips_m4k_target;
95 extern struct target_type avr_target;
96 extern struct target_type dsp563xx_target;
97 extern struct target_type dsp5680xx_target;
98 extern struct target_type testee_target;
99 extern struct target_type avr32_ap7k_target;
100 extern struct target_type hla_target;
101 extern struct target_type nds32_v2_target;
102 extern struct target_type nds32_v3_target;
103 extern struct target_type nds32_v3m_target;
104 extern struct target_type or1k_target;
105
106 static struct target_type *target_types[] = {
107 &arm7tdmi_target,
108 &arm9tdmi_target,
109 &arm920t_target,
110 &arm720t_target,
111 &arm966e_target,
112 &arm946e_target,
113 &arm926ejs_target,
114 &fa526_target,
115 &feroceon_target,
116 &dragonite_target,
117 &xscale_target,
118 &cortexm_target,
119 &cortexa8_target,
120 &cortexr4_target,
121 &arm11_target,
122 &mips_m4k_target,
123 &avr_target,
124 &dsp563xx_target,
125 &dsp5680xx_target,
126 &testee_target,
127 &avr32_ap7k_target,
128 &hla_target,
129 &nds32_v2_target,
130 &nds32_v3_target,
131 &nds32_v3m_target,
132 &or1k_target,
133 NULL,
134 };
135
136 struct target *all_targets;
137 static struct target_event_callback *target_event_callbacks;
138 static struct target_timer_callback *target_timer_callbacks;
139 static const int polling_interval = 100;
140
141 static const Jim_Nvp nvp_assert[] = {
142 { .name = "assert", NVP_ASSERT },
143 { .name = "deassert", NVP_DEASSERT },
144 { .name = "T", NVP_ASSERT },
145 { .name = "F", NVP_DEASSERT },
146 { .name = "t", NVP_ASSERT },
147 { .name = "f", NVP_DEASSERT },
148 { .name = NULL, .value = -1 }
149 };
150
151 static const Jim_Nvp nvp_error_target[] = {
152 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
153 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
154 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
155 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
156 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
157 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
158 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
159 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
160 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
161 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
162 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
163 { .value = -1, .name = NULL }
164 };
165
166 static const char *target_strerror_safe(int err)
167 {
168 const Jim_Nvp *n;
169
170 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
171 if (n->name == NULL)
172 return "unknown";
173 else
174 return n->name;
175 }
176
177 static const Jim_Nvp nvp_target_event[] = {
178
179 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
180 { .value = TARGET_EVENT_HALTED, .name = "halted" },
181 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
182 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
183 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
184
185 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
186 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
187
188 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
189 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
190 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
191 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
192 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
193 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
194 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
195 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
196 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
197 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
198 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
199 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
200
201 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
202 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
203
204 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
205 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
206
207 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
208 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
209
210 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
211 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
212
213 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
214 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
215
216 { .name = NULL, .value = -1 }
217 };
218
219 static const Jim_Nvp nvp_target_state[] = {
220 { .name = "unknown", .value = TARGET_UNKNOWN },
221 { .name = "running", .value = TARGET_RUNNING },
222 { .name = "halted", .value = TARGET_HALTED },
223 { .name = "reset", .value = TARGET_RESET },
224 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
225 { .name = NULL, .value = -1 },
226 };
227
228 static const Jim_Nvp nvp_target_debug_reason[] = {
229 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
230 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
231 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
232 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
233 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
234 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
235 { .name = "program-exit" , .value = DBG_REASON_EXIT },
236 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
237 { .name = NULL, .value = -1 },
238 };
239
240 static const Jim_Nvp nvp_target_endian[] = {
241 { .name = "big", .value = TARGET_BIG_ENDIAN },
242 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
243 { .name = "be", .value = TARGET_BIG_ENDIAN },
244 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
245 { .name = NULL, .value = -1 },
246 };
247
248 static const Jim_Nvp nvp_reset_modes[] = {
249 { .name = "unknown", .value = RESET_UNKNOWN },
250 { .name = "run" , .value = RESET_RUN },
251 { .name = "halt" , .value = RESET_HALT },
252 { .name = "init" , .value = RESET_INIT },
253 { .name = NULL , .value = -1 },
254 };
255
256 const char *debug_reason_name(struct target *t)
257 {
258 const char *cp;
259
260 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
261 t->debug_reason)->name;
262 if (!cp) {
263 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
264 cp = "(*BUG*unknown*BUG*)";
265 }
266 return cp;
267 }
268
269 const char *target_state_name(struct target *t)
270 {
271 const char *cp;
272 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
273 if (!cp) {
274 LOG_ERROR("Invalid target state: %d", (int)(t->state));
275 cp = "(*BUG*unknown*BUG*)";
276 }
277 return cp;
278 }
279
280 /* determine the number of the new target */
281 static int new_target_number(void)
282 {
283 struct target *t;
284 int x;
285
286 /* number is 0 based */
287 x = -1;
288 t = all_targets;
289 while (t) {
290 if (x < t->target_number)
291 x = t->target_number;
292 t = t->next;
293 }
294 return x + 1;
295 }
296
297 /* read a uint32_t from a buffer in target memory endianness */
298 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
299 {
300 if (target->endianness == TARGET_LITTLE_ENDIAN)
301 return le_to_h_u32(buffer);
302 else
303 return be_to_h_u32(buffer);
304 }
305
306 /* read a uint24_t from a buffer in target memory endianness */
307 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
308 {
309 if (target->endianness == TARGET_LITTLE_ENDIAN)
310 return le_to_h_u24(buffer);
311 else
312 return be_to_h_u24(buffer);
313 }
314
315 /* read a uint16_t from a buffer in target memory endianness */
316 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
317 {
318 if (target->endianness == TARGET_LITTLE_ENDIAN)
319 return le_to_h_u16(buffer);
320 else
321 return be_to_h_u16(buffer);
322 }
323
324 /* read a uint8_t from a buffer in target memory endianness */
325 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
326 {
327 return *buffer & 0x0ff;
328 }
329
330 /* write a uint32_t to a buffer in target memory endianness */
331 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
332 {
333 if (target->endianness == TARGET_LITTLE_ENDIAN)
334 h_u32_to_le(buffer, value);
335 else
336 h_u32_to_be(buffer, value);
337 }
338
339 /* write a uint24_t to a buffer in target memory endianness */
340 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
341 {
342 if (target->endianness == TARGET_LITTLE_ENDIAN)
343 h_u24_to_le(buffer, value);
344 else
345 h_u24_to_be(buffer, value);
346 }
347
348 /* write a uint16_t to a buffer in target memory endianness */
349 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
350 {
351 if (target->endianness == TARGET_LITTLE_ENDIAN)
352 h_u16_to_le(buffer, value);
353 else
354 h_u16_to_be(buffer, value);
355 }
356
357 /* write a uint8_t to a buffer in target memory endianness */
358 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
359 {
360 *buffer = value;
361 }
362
363 /* write a uint32_t array to a buffer in target memory endianness */
364 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
365 {
366 uint32_t i;
367 for (i = 0; i < count; i++)
368 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
369 }
370
371 /* write a uint16_t array to a buffer in target memory endianness */
372 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
373 {
374 uint32_t i;
375 for (i = 0; i < count; i++)
376 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
377 }
378
379 /* write a uint32_t array to a buffer in target memory endianness */
380 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, uint32_t *srcbuf)
381 {
382 uint32_t i;
383 for (i = 0; i < count; i++)
384 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
385 }
386
387 /* write a uint16_t array to a buffer in target memory endianness */
388 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, uint16_t *srcbuf)
389 {
390 uint32_t i;
391 for (i = 0; i < count; i++)
392 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
393 }
394
395 /* return a pointer to a configured target; id is name or number */
396 struct target *get_target(const char *id)
397 {
398 struct target *target;
399
400 /* try as tcltarget name */
401 for (target = all_targets; target; target = target->next) {
402 if (target_name(target) == NULL)
403 continue;
404 if (strcmp(id, target_name(target)) == 0)
405 return target;
406 }
407
408 /* It's OK to remove this fallback sometime after August 2010 or so */
409
410 /* no match, try as number */
411 unsigned num;
412 if (parse_uint(id, &num) != ERROR_OK)
413 return NULL;
414
415 for (target = all_targets; target; target = target->next) {
416 if (target->target_number == (int)num) {
417 LOG_WARNING("use '%s' as target identifier, not '%u'",
418 target_name(target), num);
419 return target;
420 }
421 }
422
423 return NULL;
424 }
425
426 /* returns a pointer to the n-th configured target */
427 static struct target *get_target_by_num(int num)
428 {
429 struct target *target = all_targets;
430
431 while (target) {
432 if (target->target_number == num)
433 return target;
434 target = target->next;
435 }
436
437 return NULL;
438 }
439
440 struct target *get_current_target(struct command_context *cmd_ctx)
441 {
442 struct target *target = get_target_by_num(cmd_ctx->current_target);
443
444 if (target == NULL) {
445 LOG_ERROR("BUG: current_target out of bounds");
446 exit(-1);
447 }
448
449 return target;
450 }
451
452 int target_poll(struct target *target)
453 {
454 int retval;
455
456 /* We can't poll until after examine */
457 if (!target_was_examined(target)) {
458 /* Fail silently lest we pollute the log */
459 return ERROR_FAIL;
460 }
461
462 retval = target->type->poll(target);
463 if (retval != ERROR_OK)
464 return retval;
465
466 if (target->halt_issued) {
467 if (target->state == TARGET_HALTED)
468 target->halt_issued = false;
469 else {
470 long long t = timeval_ms() - target->halt_issued_time;
471 if (t > DEFAULT_HALT_TIMEOUT) {
472 target->halt_issued = false;
473 LOG_INFO("Halt timed out, wake up GDB.");
474 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
475 }
476 }
477 }
478
479 return ERROR_OK;
480 }
481
482 int target_halt(struct target *target)
483 {
484 int retval;
485 /* We can't poll until after examine */
486 if (!target_was_examined(target)) {
487 LOG_ERROR("Target not examined yet");
488 return ERROR_FAIL;
489 }
490
491 retval = target->type->halt(target);
492 if (retval != ERROR_OK)
493 return retval;
494
495 target->halt_issued = true;
496 target->halt_issued_time = timeval_ms();
497
498 return ERROR_OK;
499 }
500
501 /**
502 * Make the target (re)start executing using its saved execution
503 * context (possibly with some modifications).
504 *
505 * @param target Which target should start executing.
506 * @param current True to use the target's saved program counter instead
507 * of the address parameter
508 * @param address Optionally used as the program counter.
509 * @param handle_breakpoints True iff breakpoints at the resumption PC
510 * should be skipped. (For example, maybe execution was stopped by
511 * such a breakpoint, in which case it would be counterprodutive to
512 * let it re-trigger.
513 * @param debug_execution False if all working areas allocated by OpenOCD
514 * should be released and/or restored to their original contents.
515 * (This would for example be true to run some downloaded "helper"
516 * algorithm code, which resides in one such working buffer and uses
517 * another for data storage.)
518 *
519 * @todo Resolve the ambiguity about what the "debug_execution" flag
520 * signifies. For example, Target implementations don't agree on how
521 * it relates to invalidation of the register cache, or to whether
522 * breakpoints and watchpoints should be enabled. (It would seem wrong
523 * to enable breakpoints when running downloaded "helper" algorithms
524 * (debug_execution true), since the breakpoints would be set to match
525 * target firmware being debugged, not the helper algorithm.... and
526 * enabling them could cause such helpers to malfunction (for example,
527 * by overwriting data with a breakpoint instruction. On the other
528 * hand the infrastructure for running such helpers might use this
529 * procedure but rely on hardware breakpoint to detect termination.)
530 */
531 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
532 {
533 int retval;
534
535 /* We can't poll until after examine */
536 if (!target_was_examined(target)) {
537 LOG_ERROR("Target not examined yet");
538 return ERROR_FAIL;
539 }
540
541 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
542
543 /* note that resume *must* be asynchronous. The CPU can halt before
544 * we poll. The CPU can even halt at the current PC as a result of
545 * a software breakpoint being inserted by (a bug?) the application.
546 */
547 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
548 if (retval != ERROR_OK)
549 return retval;
550
551 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
552
553 return retval;
554 }
555
556 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
557 {
558 char buf[100];
559 int retval;
560 Jim_Nvp *n;
561 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
562 if (n->name == NULL) {
563 LOG_ERROR("invalid reset mode");
564 return ERROR_FAIL;
565 }
566
567 /* disable polling during reset to make reset event scripts
568 * more predictable, i.e. dr/irscan & pathmove in events will
569 * not have JTAG operations injected into the middle of a sequence.
570 */
571 bool save_poll = jtag_poll_get_enabled();
572
573 jtag_poll_set_enabled(false);
574
575 sprintf(buf, "ocd_process_reset %s", n->name);
576 retval = Jim_Eval(cmd_ctx->interp, buf);
577
578 jtag_poll_set_enabled(save_poll);
579
580 if (retval != JIM_OK) {
581 Jim_MakeErrorMessage(cmd_ctx->interp);
582 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
583 return ERROR_FAIL;
584 }
585
586 /* We want any events to be processed before the prompt */
587 retval = target_call_timer_callbacks_now();
588
589 struct target *target;
590 for (target = all_targets; target; target = target->next) {
591 target->type->check_reset(target);
592 target->running_alg = false;
593 }
594
595 return retval;
596 }
597
598 static int identity_virt2phys(struct target *target,
599 uint32_t virtual, uint32_t *physical)
600 {
601 *physical = virtual;
602 return ERROR_OK;
603 }
604
605 static int no_mmu(struct target *target, int *enabled)
606 {
607 *enabled = 0;
608 return ERROR_OK;
609 }
610
611 static int default_examine(struct target *target)
612 {
613 target_set_examined(target);
614 return ERROR_OK;
615 }
616
617 /* no check by default */
618 static int default_check_reset(struct target *target)
619 {
620 return ERROR_OK;
621 }
622
623 int target_examine_one(struct target *target)
624 {
625 return target->type->examine(target);
626 }
627
628 static int jtag_enable_callback(enum jtag_event event, void *priv)
629 {
630 struct target *target = priv;
631
632 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
633 return ERROR_OK;
634
635 jtag_unregister_event_callback(jtag_enable_callback, target);
636
637 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
638
639 int retval = target_examine_one(target);
640 if (retval != ERROR_OK)
641 return retval;
642
643 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
644
645 return retval;
646 }
647
648 /* Targets that correctly implement init + examine, i.e.
649 * no communication with target during init:
650 *
651 * XScale
652 */
653 int target_examine(void)
654 {
655 int retval = ERROR_OK;
656 struct target *target;
657
658 for (target = all_targets; target; target = target->next) {
659 /* defer examination, but don't skip it */
660 if (!target->tap->enabled) {
661 jtag_register_event_callback(jtag_enable_callback,
662 target);
663 continue;
664 }
665
666 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
667
668 retval = target_examine_one(target);
669 if (retval != ERROR_OK)
670 return retval;
671
672 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
673 }
674 return retval;
675 }
676
677 const char *target_type_name(struct target *target)
678 {
679 return target->type->name;
680 }
681
682 static int target_soft_reset_halt(struct target *target)
683 {
684 if (!target_was_examined(target)) {
685 LOG_ERROR("Target not examined yet");
686 return ERROR_FAIL;
687 }
688 if (!target->type->soft_reset_halt) {
689 LOG_ERROR("Target %s does not support soft_reset_halt",
690 target_name(target));
691 return ERROR_FAIL;
692 }
693 return target->type->soft_reset_halt(target);
694 }
695
696 /**
697 * Downloads a target-specific native code algorithm to the target,
698 * and executes it. * Note that some targets may need to set up, enable,
699 * and tear down a breakpoint (hard or * soft) to detect algorithm
700 * termination, while others may support lower overhead schemes where
701 * soft breakpoints embedded in the algorithm automatically terminate the
702 * algorithm.
703 *
704 * @param target used to run the algorithm
705 * @param arch_info target-specific description of the algorithm.
706 */
707 int target_run_algorithm(struct target *target,
708 int num_mem_params, struct mem_param *mem_params,
709 int num_reg_params, struct reg_param *reg_param,
710 uint32_t entry_point, uint32_t exit_point,
711 int timeout_ms, void *arch_info)
712 {
713 int retval = ERROR_FAIL;
714
715 if (!target_was_examined(target)) {
716 LOG_ERROR("Target not examined yet");
717 goto done;
718 }
719 if (!target->type->run_algorithm) {
720 LOG_ERROR("Target type '%s' does not support %s",
721 target_type_name(target), __func__);
722 goto done;
723 }
724
725 target->running_alg = true;
726 retval = target->type->run_algorithm(target,
727 num_mem_params, mem_params,
728 num_reg_params, reg_param,
729 entry_point, exit_point, timeout_ms, arch_info);
730 target->running_alg = false;
731
732 done:
733 return retval;
734 }
735
736 /**
737 * Downloads a target-specific native code algorithm to the target,
738 * executes and leaves it running.
739 *
740 * @param target used to run the algorithm
741 * @param arch_info target-specific description of the algorithm.
742 */
743 int target_start_algorithm(struct target *target,
744 int num_mem_params, struct mem_param *mem_params,
745 int num_reg_params, struct reg_param *reg_params,
746 uint32_t entry_point, uint32_t exit_point,
747 void *arch_info)
748 {
749 int retval = ERROR_FAIL;
750
751 if (!target_was_examined(target)) {
752 LOG_ERROR("Target not examined yet");
753 goto done;
754 }
755 if (!target->type->start_algorithm) {
756 LOG_ERROR("Target type '%s' does not support %s",
757 target_type_name(target), __func__);
758 goto done;
759 }
760 if (target->running_alg) {
761 LOG_ERROR("Target is already running an algorithm");
762 goto done;
763 }
764
765 target->running_alg = true;
766 retval = target->type->start_algorithm(target,
767 num_mem_params, mem_params,
768 num_reg_params, reg_params,
769 entry_point, exit_point, arch_info);
770
771 done:
772 return retval;
773 }
774
775 /**
776 * Waits for an algorithm started with target_start_algorithm() to complete.
777 *
778 * @param target used to run the algorithm
779 * @param arch_info target-specific description of the algorithm.
780 */
781 int target_wait_algorithm(struct target *target,
782 int num_mem_params, struct mem_param *mem_params,
783 int num_reg_params, struct reg_param *reg_params,
784 uint32_t exit_point, int timeout_ms,
785 void *arch_info)
786 {
787 int retval = ERROR_FAIL;
788
789 if (!target->type->wait_algorithm) {
790 LOG_ERROR("Target type '%s' does not support %s",
791 target_type_name(target), __func__);
792 goto done;
793 }
794 if (!target->running_alg) {
795 LOG_ERROR("Target is not running an algorithm");
796 goto done;
797 }
798
799 retval = target->type->wait_algorithm(target,
800 num_mem_params, mem_params,
801 num_reg_params, reg_params,
802 exit_point, timeout_ms, arch_info);
803 if (retval != ERROR_TARGET_TIMEOUT)
804 target->running_alg = false;
805
806 done:
807 return retval;
808 }
809
810 /**
811 * Executes a target-specific native code algorithm in the target.
812 * It differs from target_run_algorithm in that the algorithm is asynchronous.
813 * Because of this it requires an compliant algorithm:
814 * see contrib/loaders/flash/stm32f1x.S for example.
815 *
816 * @param target used to run the algorithm
817 */
818
819 int target_run_flash_async_algorithm(struct target *target,
820 uint8_t *buffer, uint32_t count, int block_size,
821 int num_mem_params, struct mem_param *mem_params,
822 int num_reg_params, struct reg_param *reg_params,
823 uint32_t buffer_start, uint32_t buffer_size,
824 uint32_t entry_point, uint32_t exit_point, void *arch_info)
825 {
826 int retval;
827 int timeout = 0;
828
829 /* Set up working area. First word is write pointer, second word is read pointer,
830 * rest is fifo data area. */
831 uint32_t wp_addr = buffer_start;
832 uint32_t rp_addr = buffer_start + 4;
833 uint32_t fifo_start_addr = buffer_start + 8;
834 uint32_t fifo_end_addr = buffer_start + buffer_size;
835
836 uint32_t wp = fifo_start_addr;
837 uint32_t rp = fifo_start_addr;
838
839 /* validate block_size is 2^n */
840 assert(!block_size || !(block_size & (block_size - 1)));
841
842 retval = target_write_u32(target, wp_addr, wp);
843 if (retval != ERROR_OK)
844 return retval;
845 retval = target_write_u32(target, rp_addr, rp);
846 if (retval != ERROR_OK)
847 return retval;
848
849 /* Start up algorithm on target and let it idle while writing the first chunk */
850 retval = target_start_algorithm(target, num_mem_params, mem_params,
851 num_reg_params, reg_params,
852 entry_point,
853 exit_point,
854 arch_info);
855
856 if (retval != ERROR_OK) {
857 LOG_ERROR("error starting target flash write algorithm");
858 return retval;
859 }
860
861 while (count > 0) {
862
863 retval = target_read_u32(target, rp_addr, &rp);
864 if (retval != ERROR_OK) {
865 LOG_ERROR("failed to get read pointer");
866 break;
867 }
868
869 LOG_DEBUG("count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32, count, wp, rp);
870
871 if (rp == 0) {
872 LOG_ERROR("flash write algorithm aborted by target");
873 retval = ERROR_FLASH_OPERATION_FAILED;
874 break;
875 }
876
877 if ((rp & (block_size - 1)) || rp < fifo_start_addr || rp >= fifo_end_addr) {
878 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
879 break;
880 }
881
882 /* Count the number of bytes available in the fifo without
883 * crossing the wrap around. Make sure to not fill it completely,
884 * because that would make wp == rp and that's the empty condition. */
885 uint32_t thisrun_bytes;
886 if (rp > wp)
887 thisrun_bytes = rp - wp - block_size;
888 else if (rp > fifo_start_addr)
889 thisrun_bytes = fifo_end_addr - wp;
890 else
891 thisrun_bytes = fifo_end_addr - wp - block_size;
892
893 if (thisrun_bytes == 0) {
894 /* Throttle polling a bit if transfer is (much) faster than flash
895 * programming. The exact delay shouldn't matter as long as it's
896 * less than buffer size / flash speed. This is very unlikely to
897 * run when using high latency connections such as USB. */
898 alive_sleep(10);
899
900 /* to stop an infinite loop on some targets check and increment a timeout
901 * this issue was observed on a stellaris using the new ICDI interface */
902 if (timeout++ >= 500) {
903 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
904 return ERROR_FLASH_OPERATION_FAILED;
905 }
906 continue;
907 }
908
909 /* reset our timeout */
910 timeout = 0;
911
912 /* Limit to the amount of data we actually want to write */
913 if (thisrun_bytes > count * block_size)
914 thisrun_bytes = count * block_size;
915
916 /* Write data to fifo */
917 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
918 if (retval != ERROR_OK)
919 break;
920
921 /* Update counters and wrap write pointer */
922 buffer += thisrun_bytes;
923 count -= thisrun_bytes / block_size;
924 wp += thisrun_bytes;
925 if (wp >= fifo_end_addr)
926 wp = fifo_start_addr;
927
928 /* Store updated write pointer to target */
929 retval = target_write_u32(target, wp_addr, wp);
930 if (retval != ERROR_OK)
931 break;
932 }
933
934 if (retval != ERROR_OK) {
935 /* abort flash write algorithm on target */
936 target_write_u32(target, wp_addr, 0);
937 }
938
939 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
940 num_reg_params, reg_params,
941 exit_point,
942 10000,
943 arch_info);
944
945 if (retval2 != ERROR_OK) {
946 LOG_ERROR("error waiting for target flash write algorithm");
947 retval = retval2;
948 }
949
950 return retval;
951 }
952
953 int target_read_memory(struct target *target,
954 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
955 {
956 if (!target_was_examined(target)) {
957 LOG_ERROR("Target not examined yet");
958 return ERROR_FAIL;
959 }
960 return target->type->read_memory(target, address, size, count, buffer);
961 }
962
963 int target_read_phys_memory(struct target *target,
964 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
965 {
966 if (!target_was_examined(target)) {
967 LOG_ERROR("Target not examined yet");
968 return ERROR_FAIL;
969 }
970 return target->type->read_phys_memory(target, address, size, count, buffer);
971 }
972
973 int target_write_memory(struct target *target,
974 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
975 {
976 if (!target_was_examined(target)) {
977 LOG_ERROR("Target not examined yet");
978 return ERROR_FAIL;
979 }
980 return target->type->write_memory(target, address, size, count, buffer);
981 }
982
983 int target_write_phys_memory(struct target *target,
984 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
985 {
986 if (!target_was_examined(target)) {
987 LOG_ERROR("Target not examined yet");
988 return ERROR_FAIL;
989 }
990 return target->type->write_phys_memory(target, address, size, count, buffer);
991 }
992
993 int target_add_breakpoint(struct target *target,
994 struct breakpoint *breakpoint)
995 {
996 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
997 LOG_WARNING("target %s is not halted", target_name(target));
998 return ERROR_TARGET_NOT_HALTED;
999 }
1000 return target->type->add_breakpoint(target, breakpoint);
1001 }
1002
1003 int target_add_context_breakpoint(struct target *target,
1004 struct breakpoint *breakpoint)
1005 {
1006 if (target->state != TARGET_HALTED) {
1007 LOG_WARNING("target %s is not halted", target_name(target));
1008 return ERROR_TARGET_NOT_HALTED;
1009 }
1010 return target->type->add_context_breakpoint(target, breakpoint);
1011 }
1012
1013 int target_add_hybrid_breakpoint(struct target *target,
1014 struct breakpoint *breakpoint)
1015 {
1016 if (target->state != TARGET_HALTED) {
1017 LOG_WARNING("target %s is not halted", target_name(target));
1018 return ERROR_TARGET_NOT_HALTED;
1019 }
1020 return target->type->add_hybrid_breakpoint(target, breakpoint);
1021 }
1022
1023 int target_remove_breakpoint(struct target *target,
1024 struct breakpoint *breakpoint)
1025 {
1026 return target->type->remove_breakpoint(target, breakpoint);
1027 }
1028
1029 int target_add_watchpoint(struct target *target,
1030 struct watchpoint *watchpoint)
1031 {
1032 if (target->state != TARGET_HALTED) {
1033 LOG_WARNING("target %s is not halted", target_name(target));
1034 return ERROR_TARGET_NOT_HALTED;
1035 }
1036 return target->type->add_watchpoint(target, watchpoint);
1037 }
1038 int target_remove_watchpoint(struct target *target,
1039 struct watchpoint *watchpoint)
1040 {
1041 return target->type->remove_watchpoint(target, watchpoint);
1042 }
1043 int target_hit_watchpoint(struct target *target,
1044 struct watchpoint **hit_watchpoint)
1045 {
1046 if (target->state != TARGET_HALTED) {
1047 LOG_WARNING("target %s is not halted", target->cmd_name);
1048 return ERROR_TARGET_NOT_HALTED;
1049 }
1050
1051 if (target->type->hit_watchpoint == NULL) {
1052 /* For backward compatible, if hit_watchpoint is not implemented,
1053 * return ERROR_FAIL such that gdb_server will not take the nonsense
1054 * information. */
1055 return ERROR_FAIL;
1056 }
1057
1058 return target->type->hit_watchpoint(target, hit_watchpoint);
1059 }
1060
1061 int target_get_gdb_reg_list(struct target *target,
1062 struct reg **reg_list[], int *reg_list_size,
1063 enum target_register_class reg_class)
1064 {
1065 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1066 }
1067 int target_step(struct target *target,
1068 int current, uint32_t address, int handle_breakpoints)
1069 {
1070 return target->type->step(target, current, address, handle_breakpoints);
1071 }
1072
1073 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1074 {
1075 if (target->state != TARGET_HALTED) {
1076 LOG_WARNING("target %s is not halted", target->cmd_name);
1077 return ERROR_TARGET_NOT_HALTED;
1078 }
1079 return target->type->get_gdb_fileio_info(target, fileio_info);
1080 }
1081
1082 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1083 {
1084 if (target->state != TARGET_HALTED) {
1085 LOG_WARNING("target %s is not halted", target->cmd_name);
1086 return ERROR_TARGET_NOT_HALTED;
1087 }
1088 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1089 }
1090
1091 int target_profiling(struct target *target, uint32_t *samples,
1092 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1093 {
1094 if (target->state != TARGET_HALTED) {
1095 LOG_WARNING("target %s is not halted", target->cmd_name);
1096 return ERROR_TARGET_NOT_HALTED;
1097 }
1098 return target->type->profiling(target, samples, max_num_samples,
1099 num_samples, seconds);
1100 }
1101
1102 /**
1103 * Reset the @c examined flag for the given target.
1104 * Pure paranoia -- targets are zeroed on allocation.
1105 */
1106 static void target_reset_examined(struct target *target)
1107 {
1108 target->examined = false;
1109 }
1110
1111 static int err_read_phys_memory(struct target *target, uint32_t address,
1112 uint32_t size, uint32_t count, uint8_t *buffer)
1113 {
1114 LOG_ERROR("Not implemented: %s", __func__);
1115 return ERROR_FAIL;
1116 }
1117
1118 static int err_write_phys_memory(struct target *target, uint32_t address,
1119 uint32_t size, uint32_t count, const uint8_t *buffer)
1120 {
1121 LOG_ERROR("Not implemented: %s", __func__);
1122 return ERROR_FAIL;
1123 }
1124
1125 static int handle_target(void *priv);
1126
1127 static int target_init_one(struct command_context *cmd_ctx,
1128 struct target *target)
1129 {
1130 target_reset_examined(target);
1131
1132 struct target_type *type = target->type;
1133 if (type->examine == NULL)
1134 type->examine = default_examine;
1135
1136 if (type->check_reset == NULL)
1137 type->check_reset = default_check_reset;
1138
1139 assert(type->init_target != NULL);
1140
1141 int retval = type->init_target(cmd_ctx, target);
1142 if (ERROR_OK != retval) {
1143 LOG_ERROR("target '%s' init failed", target_name(target));
1144 return retval;
1145 }
1146
1147 /* Sanity-check MMU support ... stub in what we must, to help
1148 * implement it in stages, but warn if we need to do so.
1149 */
1150 if (type->mmu) {
1151 if (type->write_phys_memory == NULL) {
1152 LOG_ERROR("type '%s' is missing write_phys_memory",
1153 type->name);
1154 type->write_phys_memory = err_write_phys_memory;
1155 }
1156 if (type->read_phys_memory == NULL) {
1157 LOG_ERROR("type '%s' is missing read_phys_memory",
1158 type->name);
1159 type->read_phys_memory = err_read_phys_memory;
1160 }
1161 if (type->virt2phys == NULL) {
1162 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1163 type->virt2phys = identity_virt2phys;
1164 }
1165 } else {
1166 /* Make sure no-MMU targets all behave the same: make no
1167 * distinction between physical and virtual addresses, and
1168 * ensure that virt2phys() is always an identity mapping.
1169 */
1170 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1171 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1172
1173 type->mmu = no_mmu;
1174 type->write_phys_memory = type->write_memory;
1175 type->read_phys_memory = type->read_memory;
1176 type->virt2phys = identity_virt2phys;
1177 }
1178
1179 if (target->type->read_buffer == NULL)
1180 target->type->read_buffer = target_read_buffer_default;
1181
1182 if (target->type->write_buffer == NULL)
1183 target->type->write_buffer = target_write_buffer_default;
1184
1185 if (target->type->get_gdb_fileio_info == NULL)
1186 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1187
1188 if (target->type->gdb_fileio_end == NULL)
1189 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1190
1191 if (target->type->profiling == NULL)
1192 target->type->profiling = target_profiling_default;
1193
1194 return ERROR_OK;
1195 }
1196
1197 static int target_init(struct command_context *cmd_ctx)
1198 {
1199 struct target *target;
1200 int retval;
1201
1202 for (target = all_targets; target; target = target->next) {
1203 retval = target_init_one(cmd_ctx, target);
1204 if (ERROR_OK != retval)
1205 return retval;
1206 }
1207
1208 if (!all_targets)
1209 return ERROR_OK;
1210
1211 retval = target_register_user_commands(cmd_ctx);
1212 if (ERROR_OK != retval)
1213 return retval;
1214
1215 retval = target_register_timer_callback(&handle_target,
1216 polling_interval, 1, cmd_ctx->interp);
1217 if (ERROR_OK != retval)
1218 return retval;
1219
1220 return ERROR_OK;
1221 }
1222
1223 COMMAND_HANDLER(handle_target_init_command)
1224 {
1225 int retval;
1226
1227 if (CMD_ARGC != 0)
1228 return ERROR_COMMAND_SYNTAX_ERROR;
1229
1230 static bool target_initialized;
1231 if (target_initialized) {
1232 LOG_INFO("'target init' has already been called");
1233 return ERROR_OK;
1234 }
1235 target_initialized = true;
1236
1237 retval = command_run_line(CMD_CTX, "init_targets");
1238 if (ERROR_OK != retval)
1239 return retval;
1240
1241 retval = command_run_line(CMD_CTX, "init_board");
1242 if (ERROR_OK != retval)
1243 return retval;
1244
1245 LOG_DEBUG("Initializing targets...");
1246 return target_init(CMD_CTX);
1247 }
1248
1249 int target_register_event_callback(int (*callback)(struct target *target,
1250 enum target_event event, void *priv), void *priv)
1251 {
1252 struct target_event_callback **callbacks_p = &target_event_callbacks;
1253
1254 if (callback == NULL)
1255 return ERROR_COMMAND_SYNTAX_ERROR;
1256
1257 if (*callbacks_p) {
1258 while ((*callbacks_p)->next)
1259 callbacks_p = &((*callbacks_p)->next);
1260 callbacks_p = &((*callbacks_p)->next);
1261 }
1262
1263 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1264 (*callbacks_p)->callback = callback;
1265 (*callbacks_p)->priv = priv;
1266 (*callbacks_p)->next = NULL;
1267
1268 return ERROR_OK;
1269 }
1270
1271 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
1272 {
1273 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1274 struct timeval now;
1275
1276 if (callback == NULL)
1277 return ERROR_COMMAND_SYNTAX_ERROR;
1278
1279 if (*callbacks_p) {
1280 while ((*callbacks_p)->next)
1281 callbacks_p = &((*callbacks_p)->next);
1282 callbacks_p = &((*callbacks_p)->next);
1283 }
1284
1285 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1286 (*callbacks_p)->callback = callback;
1287 (*callbacks_p)->periodic = periodic;
1288 (*callbacks_p)->time_ms = time_ms;
1289
1290 gettimeofday(&now, NULL);
1291 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
1292 time_ms -= (time_ms % 1000);
1293 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
1294 if ((*callbacks_p)->when.tv_usec > 1000000) {
1295 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
1296 (*callbacks_p)->when.tv_sec += 1;
1297 }
1298
1299 (*callbacks_p)->priv = priv;
1300 (*callbacks_p)->next = NULL;
1301
1302 return ERROR_OK;
1303 }
1304
1305 int target_unregister_event_callback(int (*callback)(struct target *target,
1306 enum target_event event, void *priv), void *priv)
1307 {
1308 struct target_event_callback **p = &target_event_callbacks;
1309 struct target_event_callback *c = target_event_callbacks;
1310
1311 if (callback == NULL)
1312 return ERROR_COMMAND_SYNTAX_ERROR;
1313
1314 while (c) {
1315 struct target_event_callback *next = c->next;
1316 if ((c->callback == callback) && (c->priv == priv)) {
1317 *p = next;
1318 free(c);
1319 return ERROR_OK;
1320 } else
1321 p = &(c->next);
1322 c = next;
1323 }
1324
1325 return ERROR_OK;
1326 }
1327
1328 static int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1329 {
1330 struct target_timer_callback **p = &target_timer_callbacks;
1331 struct target_timer_callback *c = target_timer_callbacks;
1332
1333 if (callback == NULL)
1334 return ERROR_COMMAND_SYNTAX_ERROR;
1335
1336 while (c) {
1337 struct target_timer_callback *next = c->next;
1338 if ((c->callback == callback) && (c->priv == priv)) {
1339 *p = next;
1340 free(c);
1341 return ERROR_OK;
1342 } else
1343 p = &(c->next);
1344 c = next;
1345 }
1346
1347 return ERROR_OK;
1348 }
1349
1350 int target_call_event_callbacks(struct target *target, enum target_event event)
1351 {
1352 struct target_event_callback *callback = target_event_callbacks;
1353 struct target_event_callback *next_callback;
1354
1355 if (event == TARGET_EVENT_HALTED) {
1356 /* execute early halted first */
1357 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1358 }
1359
1360 LOG_DEBUG("target event %i (%s)", event,
1361 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1362
1363 target_handle_event(target, event);
1364
1365 while (callback) {
1366 next_callback = callback->next;
1367 callback->callback(target, event, callback->priv);
1368 callback = next_callback;
1369 }
1370
1371 return ERROR_OK;
1372 }
1373
1374 static int target_timer_callback_periodic_restart(
1375 struct target_timer_callback *cb, struct timeval *now)
1376 {
1377 int time_ms = cb->time_ms;
1378 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1379 time_ms -= (time_ms % 1000);
1380 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1381 if (cb->when.tv_usec > 1000000) {
1382 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1383 cb->when.tv_sec += 1;
1384 }
1385 return ERROR_OK;
1386 }
1387
1388 static int target_call_timer_callback(struct target_timer_callback *cb,
1389 struct timeval *now)
1390 {
1391 cb->callback(cb->priv);
1392
1393 if (cb->periodic)
1394 return target_timer_callback_periodic_restart(cb, now);
1395
1396 return target_unregister_timer_callback(cb->callback, cb->priv);
1397 }
1398
1399 static int target_call_timer_callbacks_check_time(int checktime)
1400 {
1401 keep_alive();
1402
1403 struct timeval now;
1404 gettimeofday(&now, NULL);
1405
1406 struct target_timer_callback *callback = target_timer_callbacks;
1407 while (callback) {
1408 /* cleaning up may unregister and free this callback */
1409 struct target_timer_callback *next_callback = callback->next;
1410
1411 bool call_it = callback->callback &&
1412 ((!checktime && callback->periodic) ||
1413 now.tv_sec > callback->when.tv_sec ||
1414 (now.tv_sec == callback->when.tv_sec &&
1415 now.tv_usec >= callback->when.tv_usec));
1416
1417 if (call_it) {
1418 int retval = target_call_timer_callback(callback, &now);
1419 if (retval != ERROR_OK)
1420 return retval;
1421 }
1422
1423 callback = next_callback;
1424 }
1425
1426 return ERROR_OK;
1427 }
1428
1429 int target_call_timer_callbacks(void)
1430 {
1431 return target_call_timer_callbacks_check_time(1);
1432 }
1433
1434 /* invoke periodic callbacks immediately */
1435 int target_call_timer_callbacks_now(void)
1436 {
1437 return target_call_timer_callbacks_check_time(0);
1438 }
1439
1440 /* Prints the working area layout for debug purposes */
1441 static void print_wa_layout(struct target *target)
1442 {
1443 struct working_area *c = target->working_areas;
1444
1445 while (c) {
1446 LOG_DEBUG("%c%c 0x%08"PRIx32"-0x%08"PRIx32" (%"PRIu32" bytes)",
1447 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1448 c->address, c->address + c->size - 1, c->size);
1449 c = c->next;
1450 }
1451 }
1452
1453 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1454 static void target_split_working_area(struct working_area *area, uint32_t size)
1455 {
1456 assert(area->free); /* Shouldn't split an allocated area */
1457 assert(size <= area->size); /* Caller should guarantee this */
1458
1459 /* Split only if not already the right size */
1460 if (size < area->size) {
1461 struct working_area *new_wa = malloc(sizeof(*new_wa));
1462
1463 if (new_wa == NULL)
1464 return;
1465
1466 new_wa->next = area->next;
1467 new_wa->size = area->size - size;
1468 new_wa->address = area->address + size;
1469 new_wa->backup = NULL;
1470 new_wa->user = NULL;
1471 new_wa->free = true;
1472
1473 area->next = new_wa;
1474 area->size = size;
1475
1476 /* If backup memory was allocated to this area, it has the wrong size
1477 * now so free it and it will be reallocated if/when needed */
1478 if (area->backup) {
1479 free(area->backup);
1480 area->backup = NULL;
1481 }
1482 }
1483 }
1484
1485 /* Merge all adjacent free areas into one */
1486 static void target_merge_working_areas(struct target *target)
1487 {
1488 struct working_area *c = target->working_areas;
1489
1490 while (c && c->next) {
1491 assert(c->next->address == c->address + c->size); /* This is an invariant */
1492
1493 /* Find two adjacent free areas */
1494 if (c->free && c->next->free) {
1495 /* Merge the last into the first */
1496 c->size += c->next->size;
1497
1498 /* Remove the last */
1499 struct working_area *to_be_freed = c->next;
1500 c->next = c->next->next;
1501 if (to_be_freed->backup)
1502 free(to_be_freed->backup);
1503 free(to_be_freed);
1504
1505 /* If backup memory was allocated to the remaining area, it's has
1506 * the wrong size now */
1507 if (c->backup) {
1508 free(c->backup);
1509 c->backup = NULL;
1510 }
1511 } else {
1512 c = c->next;
1513 }
1514 }
1515 }
1516
1517 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1518 {
1519 /* Reevaluate working area address based on MMU state*/
1520 if (target->working_areas == NULL) {
1521 int retval;
1522 int enabled;
1523
1524 retval = target->type->mmu(target, &enabled);
1525 if (retval != ERROR_OK)
1526 return retval;
1527
1528 if (!enabled) {
1529 if (target->working_area_phys_spec) {
1530 LOG_DEBUG("MMU disabled, using physical "
1531 "address for working memory 0x%08"PRIx32,
1532 target->working_area_phys);
1533 target->working_area = target->working_area_phys;
1534 } else {
1535 LOG_ERROR("No working memory available. "
1536 "Specify -work-area-phys to target.");
1537 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1538 }
1539 } else {
1540 if (target->working_area_virt_spec) {
1541 LOG_DEBUG("MMU enabled, using virtual "
1542 "address for working memory 0x%08"PRIx32,
1543 target->working_area_virt);
1544 target->working_area = target->working_area_virt;
1545 } else {
1546 LOG_ERROR("No working memory available. "
1547 "Specify -work-area-virt to target.");
1548 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1549 }
1550 }
1551
1552 /* Set up initial working area on first call */
1553 struct working_area *new_wa = malloc(sizeof(*new_wa));
1554 if (new_wa) {
1555 new_wa->next = NULL;
1556 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
1557 new_wa->address = target->working_area;
1558 new_wa->backup = NULL;
1559 new_wa->user = NULL;
1560 new_wa->free = true;
1561 }
1562
1563 target->working_areas = new_wa;
1564 }
1565
1566 /* only allocate multiples of 4 byte */
1567 if (size % 4)
1568 size = (size + 3) & (~3UL);
1569
1570 struct working_area *c = target->working_areas;
1571
1572 /* Find the first large enough working area */
1573 while (c) {
1574 if (c->free && c->size >= size)
1575 break;
1576 c = c->next;
1577 }
1578
1579 if (c == NULL)
1580 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1581
1582 /* Split the working area into the requested size */
1583 target_split_working_area(c, size);
1584
1585 LOG_DEBUG("allocated new working area of %"PRIu32" bytes at address 0x%08"PRIx32, size, c->address);
1586
1587 if (target->backup_working_area) {
1588 if (c->backup == NULL) {
1589 c->backup = malloc(c->size);
1590 if (c->backup == NULL)
1591 return ERROR_FAIL;
1592 }
1593
1594 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
1595 if (retval != ERROR_OK)
1596 return retval;
1597 }
1598
1599 /* mark as used, and return the new (reused) area */
1600 c->free = false;
1601 *area = c;
1602
1603 /* user pointer */
1604 c->user = area;
1605
1606 print_wa_layout(target);
1607
1608 return ERROR_OK;
1609 }
1610
1611 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1612 {
1613 int retval;
1614
1615 retval = target_alloc_working_area_try(target, size, area);
1616 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1617 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
1618 return retval;
1619
1620 }
1621
1622 static int target_restore_working_area(struct target *target, struct working_area *area)
1623 {
1624 int retval = ERROR_OK;
1625
1626 if (target->backup_working_area && area->backup != NULL) {
1627 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
1628 if (retval != ERROR_OK)
1629 LOG_ERROR("failed to restore %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1630 area->size, area->address);
1631 }
1632
1633 return retval;
1634 }
1635
1636 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
1637 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1638 {
1639 int retval = ERROR_OK;
1640
1641 if (area->free)
1642 return retval;
1643
1644 if (restore) {
1645 retval = target_restore_working_area(target, area);
1646 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
1647 if (retval != ERROR_OK)
1648 return retval;
1649 }
1650
1651 area->free = true;
1652
1653 LOG_DEBUG("freed %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1654 area->size, area->address);
1655
1656 /* mark user pointer invalid */
1657 /* TODO: Is this really safe? It points to some previous caller's memory.
1658 * How could we know that the area pointer is still in that place and not
1659 * some other vital data? What's the purpose of this, anyway? */
1660 *area->user = NULL;
1661 area->user = NULL;
1662
1663 target_merge_working_areas(target);
1664
1665 print_wa_layout(target);
1666
1667 return retval;
1668 }
1669
1670 int target_free_working_area(struct target *target, struct working_area *area)
1671 {
1672 return target_free_working_area_restore(target, area, 1);
1673 }
1674
1675 /* free resources and restore memory, if restoring memory fails,
1676 * free up resources anyway
1677 */
1678 static void target_free_all_working_areas_restore(struct target *target, int restore)
1679 {
1680 struct working_area *c = target->working_areas;
1681
1682 LOG_DEBUG("freeing all working areas");
1683
1684 /* Loop through all areas, restoring the allocated ones and marking them as free */
1685 while (c) {
1686 if (!c->free) {
1687 if (restore)
1688 target_restore_working_area(target, c);
1689 c->free = true;
1690 *c->user = NULL; /* Same as above */
1691 c->user = NULL;
1692 }
1693 c = c->next;
1694 }
1695
1696 /* Run a merge pass to combine all areas into one */
1697 target_merge_working_areas(target);
1698
1699 print_wa_layout(target);
1700 }
1701
1702 void target_free_all_working_areas(struct target *target)
1703 {
1704 target_free_all_working_areas_restore(target, 1);
1705 }
1706
1707 /* Find the largest number of bytes that can be allocated */
1708 uint32_t target_get_working_area_avail(struct target *target)
1709 {
1710 struct working_area *c = target->working_areas;
1711 uint32_t max_size = 0;
1712
1713 if (c == NULL)
1714 return target->working_area_size;
1715
1716 while (c) {
1717 if (c->free && max_size < c->size)
1718 max_size = c->size;
1719
1720 c = c->next;
1721 }
1722
1723 return max_size;
1724 }
1725
1726 int target_arch_state(struct target *target)
1727 {
1728 int retval;
1729 if (target == NULL) {
1730 LOG_USER("No target has been configured");
1731 return ERROR_OK;
1732 }
1733
1734 LOG_USER("target state: %s", target_state_name(target));
1735
1736 if (target->state != TARGET_HALTED)
1737 return ERROR_OK;
1738
1739 retval = target->type->arch_state(target);
1740 return retval;
1741 }
1742
1743 static int target_get_gdb_fileio_info_default(struct target *target,
1744 struct gdb_fileio_info *fileio_info)
1745 {
1746 /* If target does not support semi-hosting function, target
1747 has no need to provide .get_gdb_fileio_info callback.
1748 It just return ERROR_FAIL and gdb_server will return "Txx"
1749 as target halted every time. */
1750 return ERROR_FAIL;
1751 }
1752
1753 static int target_gdb_fileio_end_default(struct target *target,
1754 int retcode, int fileio_errno, bool ctrl_c)
1755 {
1756 return ERROR_OK;
1757 }
1758
1759 static int target_profiling_default(struct target *target, uint32_t *samples,
1760 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1761 {
1762 struct timeval timeout, now;
1763
1764 gettimeofday(&timeout, NULL);
1765 timeval_add_time(&timeout, seconds, 0);
1766
1767 LOG_INFO("Starting profiling. Halting and resuming the"
1768 " target as often as we can...");
1769
1770 uint32_t sample_count = 0;
1771 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
1772 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
1773
1774 int retval = ERROR_OK;
1775 for (;;) {
1776 target_poll(target);
1777 if (target->state == TARGET_HALTED) {
1778 uint32_t t = *((uint32_t *)reg->value);
1779 samples[sample_count++] = t;
1780 /* current pc, addr = 0, do not handle breakpoints, not debugging */
1781 retval = target_resume(target, 1, 0, 0, 0);
1782 target_poll(target);
1783 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
1784 } else if (target->state == TARGET_RUNNING) {
1785 /* We want to quickly sample the PC. */
1786 retval = target_halt(target);
1787 } else {
1788 LOG_INFO("Target not halted or running");
1789 retval = ERROR_OK;
1790 break;
1791 }
1792
1793 if (retval != ERROR_OK)
1794 break;
1795
1796 gettimeofday(&now, NULL);
1797 if ((sample_count >= max_num_samples) ||
1798 ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec))) {
1799 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
1800 break;
1801 }
1802 }
1803
1804 *num_samples = sample_count;
1805 return retval;
1806 }
1807
1808 /* Single aligned words are guaranteed to use 16 or 32 bit access
1809 * mode respectively, otherwise data is handled as quickly as
1810 * possible
1811 */
1812 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1813 {
1814 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1815 (int)size, (unsigned)address);
1816
1817 if (!target_was_examined(target)) {
1818 LOG_ERROR("Target not examined yet");
1819 return ERROR_FAIL;
1820 }
1821
1822 if (size == 0)
1823 return ERROR_OK;
1824
1825 if ((address + size - 1) < address) {
1826 /* GDB can request this when e.g. PC is 0xfffffffc*/
1827 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1828 (unsigned)address,
1829 (unsigned)size);
1830 return ERROR_FAIL;
1831 }
1832
1833 return target->type->write_buffer(target, address, size, buffer);
1834 }
1835
1836 static int target_write_buffer_default(struct target *target, uint32_t address, uint32_t count, const uint8_t *buffer)
1837 {
1838 uint32_t size;
1839
1840 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
1841 * will have something to do with the size we leave to it. */
1842 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
1843 if (address & size) {
1844 int retval = target_write_memory(target, address, size, 1, buffer);
1845 if (retval != ERROR_OK)
1846 return retval;
1847 address += size;
1848 count -= size;
1849 buffer += size;
1850 }
1851 }
1852
1853 /* Write the data with as large access size as possible. */
1854 for (; size > 0; size /= 2) {
1855 uint32_t aligned = count - count % size;
1856 if (aligned > 0) {
1857 int retval = target_write_memory(target, address, size, aligned / size, buffer);
1858 if (retval != ERROR_OK)
1859 return retval;
1860 address += aligned;
1861 count -= aligned;
1862 buffer += aligned;
1863 }
1864 }
1865
1866 return ERROR_OK;
1867 }
1868
1869 /* Single aligned words are guaranteed to use 16 or 32 bit access
1870 * mode respectively, otherwise data is handled as quickly as
1871 * possible
1872 */
1873 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1874 {
1875 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1876 (int)size, (unsigned)address);
1877
1878 if (!target_was_examined(target)) {
1879 LOG_ERROR("Target not examined yet");
1880 return ERROR_FAIL;
1881 }
1882
1883 if (size == 0)
1884 return ERROR_OK;
1885
1886 if ((address + size - 1) < address) {
1887 /* GDB can request this when e.g. PC is 0xfffffffc*/
1888 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1889 address,
1890 size);
1891 return ERROR_FAIL;
1892 }
1893
1894 return target->type->read_buffer(target, address, size, buffer);
1895 }
1896
1897 static int target_read_buffer_default(struct target *target, uint32_t address, uint32_t count, uint8_t *buffer)
1898 {
1899 uint32_t size;
1900
1901 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
1902 * will have something to do with the size we leave to it. */
1903 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
1904 if (address & size) {
1905 int retval = target_read_memory(target, address, size, 1, buffer);
1906 if (retval != ERROR_OK)
1907 return retval;
1908 address += size;
1909 count -= size;
1910 buffer += size;
1911 }
1912 }
1913
1914 /* Read the data with as large access size as possible. */
1915 for (; size > 0; size /= 2) {
1916 uint32_t aligned = count - count % size;
1917 if (aligned > 0) {
1918 int retval = target_read_memory(target, address, size, aligned / size, buffer);
1919 if (retval != ERROR_OK)
1920 return retval;
1921 address += aligned;
1922 count -= aligned;
1923 buffer += aligned;
1924 }
1925 }
1926
1927 return ERROR_OK;
1928 }
1929
1930 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1931 {
1932 uint8_t *buffer;
1933 int retval;
1934 uint32_t i;
1935 uint32_t checksum = 0;
1936 if (!target_was_examined(target)) {
1937 LOG_ERROR("Target not examined yet");
1938 return ERROR_FAIL;
1939 }
1940
1941 retval = target->type->checksum_memory(target, address, size, &checksum);
1942 if (retval != ERROR_OK) {
1943 buffer = malloc(size);
1944 if (buffer == NULL) {
1945 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1946 return ERROR_COMMAND_SYNTAX_ERROR;
1947 }
1948 retval = target_read_buffer(target, address, size, buffer);
1949 if (retval != ERROR_OK) {
1950 free(buffer);
1951 return retval;
1952 }
1953
1954 /* convert to target endianness */
1955 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
1956 uint32_t target_data;
1957 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1958 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1959 }
1960
1961 retval = image_calculate_checksum(buffer, size, &checksum);
1962 free(buffer);
1963 }
1964
1965 *crc = checksum;
1966
1967 return retval;
1968 }
1969
1970 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1971 {
1972 int retval;
1973 if (!target_was_examined(target)) {
1974 LOG_ERROR("Target not examined yet");
1975 return ERROR_FAIL;
1976 }
1977
1978 if (target->type->blank_check_memory == 0)
1979 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1980
1981 retval = target->type->blank_check_memory(target, address, size, blank);
1982
1983 return retval;
1984 }
1985
1986 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1987 {
1988 uint8_t value_buf[4];
1989 if (!target_was_examined(target)) {
1990 LOG_ERROR("Target not examined yet");
1991 return ERROR_FAIL;
1992 }
1993
1994 int retval = target_read_memory(target, address, 4, 1, value_buf);
1995
1996 if (retval == ERROR_OK) {
1997 *value = target_buffer_get_u32(target, value_buf);
1998 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1999 address,
2000 *value);
2001 } else {
2002 *value = 0x0;
2003 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2004 address);
2005 }
2006
2007 return retval;
2008 }
2009
2010 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
2011 {
2012 uint8_t value_buf[2];
2013 if (!target_was_examined(target)) {
2014 LOG_ERROR("Target not examined yet");
2015 return ERROR_FAIL;
2016 }
2017
2018 int retval = target_read_memory(target, address, 2, 1, value_buf);
2019
2020 if (retval == ERROR_OK) {
2021 *value = target_buffer_get_u16(target, value_buf);
2022 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
2023 address,
2024 *value);
2025 } else {
2026 *value = 0x0;
2027 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2028 address);
2029 }
2030
2031 return retval;
2032 }
2033
2034 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
2035 {
2036 if (!target_was_examined(target)) {
2037 LOG_ERROR("Target not examined yet");
2038 return ERROR_FAIL;
2039 }
2040
2041 int retval = target_read_memory(target, address, 1, 1, value);
2042
2043 if (retval == ERROR_OK) {
2044 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2045 address,
2046 *value);
2047 } else {
2048 *value = 0x0;
2049 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2050 address);
2051 }
2052
2053 return retval;
2054 }
2055
2056 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
2057 {
2058 int retval;
2059 uint8_t value_buf[4];
2060 if (!target_was_examined(target)) {
2061 LOG_ERROR("Target not examined yet");
2062 return ERROR_FAIL;
2063 }
2064
2065 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
2066 address,
2067 value);
2068
2069 target_buffer_set_u32(target, value_buf, value);
2070 retval = target_write_memory(target, address, 4, 1, value_buf);
2071 if (retval != ERROR_OK)
2072 LOG_DEBUG("failed: %i", retval);
2073
2074 return retval;
2075 }
2076
2077 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
2078 {
2079 int retval;
2080 uint8_t value_buf[2];
2081 if (!target_was_examined(target)) {
2082 LOG_ERROR("Target not examined yet");
2083 return ERROR_FAIL;
2084 }
2085
2086 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
2087 address,
2088 value);
2089
2090 target_buffer_set_u16(target, value_buf, value);
2091 retval = target_write_memory(target, address, 2, 1, value_buf);
2092 if (retval != ERROR_OK)
2093 LOG_DEBUG("failed: %i", retval);
2094
2095 return retval;
2096 }
2097
2098 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
2099 {
2100 int retval;
2101 if (!target_was_examined(target)) {
2102 LOG_ERROR("Target not examined yet");
2103 return ERROR_FAIL;
2104 }
2105
2106 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2107 address, value);
2108
2109 retval = target_write_memory(target, address, 1, 1, &value);
2110 if (retval != ERROR_OK)
2111 LOG_DEBUG("failed: %i", retval);
2112
2113 return retval;
2114 }
2115
2116 static int find_target(struct command_context *cmd_ctx, const char *name)
2117 {
2118 struct target *target = get_target(name);
2119 if (target == NULL) {
2120 LOG_ERROR("Target: %s is unknown, try one of:\n", name);
2121 return ERROR_FAIL;
2122 }
2123 if (!target->tap->enabled) {
2124 LOG_USER("Target: TAP %s is disabled, "
2125 "can't be the current target\n",
2126 target->tap->dotted_name);
2127 return ERROR_FAIL;
2128 }
2129
2130 cmd_ctx->current_target = target->target_number;
2131 return ERROR_OK;
2132 }
2133
2134
2135 COMMAND_HANDLER(handle_targets_command)
2136 {
2137 int retval = ERROR_OK;
2138 if (CMD_ARGC == 1) {
2139 retval = find_target(CMD_CTX, CMD_ARGV[0]);
2140 if (retval == ERROR_OK) {
2141 /* we're done! */
2142 return retval;
2143 }
2144 }
2145
2146 struct target *target = all_targets;
2147 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
2148 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
2149 while (target) {
2150 const char *state;
2151 char marker = ' ';
2152
2153 if (target->tap->enabled)
2154 state = target_state_name(target);
2155 else
2156 state = "tap-disabled";
2157
2158 if (CMD_CTX->current_target == target->target_number)
2159 marker = '*';
2160
2161 /* keep columns lined up to match the headers above */
2162 command_print(CMD_CTX,
2163 "%2d%c %-18s %-10s %-6s %-18s %s",
2164 target->target_number,
2165 marker,
2166 target_name(target),
2167 target_type_name(target),
2168 Jim_Nvp_value2name_simple(nvp_target_endian,
2169 target->endianness)->name,
2170 target->tap->dotted_name,
2171 state);
2172 target = target->next;
2173 }
2174
2175 return retval;
2176 }
2177
2178 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2179
2180 static int powerDropout;
2181 static int srstAsserted;
2182
2183 static int runPowerRestore;
2184 static int runPowerDropout;
2185 static int runSrstAsserted;
2186 static int runSrstDeasserted;
2187
2188 static int sense_handler(void)
2189 {
2190 static int prevSrstAsserted;
2191 static int prevPowerdropout;
2192
2193 int retval = jtag_power_dropout(&powerDropout);
2194 if (retval != ERROR_OK)
2195 return retval;
2196
2197 int powerRestored;
2198 powerRestored = prevPowerdropout && !powerDropout;
2199 if (powerRestored)
2200 runPowerRestore = 1;
2201
2202 long long current = timeval_ms();
2203 static long long lastPower;
2204 int waitMore = lastPower + 2000 > current;
2205 if (powerDropout && !waitMore) {
2206 runPowerDropout = 1;
2207 lastPower = current;
2208 }
2209
2210 retval = jtag_srst_asserted(&srstAsserted);
2211 if (retval != ERROR_OK)
2212 return retval;
2213
2214 int srstDeasserted;
2215 srstDeasserted = prevSrstAsserted && !srstAsserted;
2216
2217 static long long lastSrst;
2218 waitMore = lastSrst + 2000 > current;
2219 if (srstDeasserted && !waitMore) {
2220 runSrstDeasserted = 1;
2221 lastSrst = current;
2222 }
2223
2224 if (!prevSrstAsserted && srstAsserted)
2225 runSrstAsserted = 1;
2226
2227 prevSrstAsserted = srstAsserted;
2228 prevPowerdropout = powerDropout;
2229
2230 if (srstDeasserted || powerRestored) {
2231 /* Other than logging the event we can't do anything here.
2232 * Issuing a reset is a particularly bad idea as we might
2233 * be inside a reset already.
2234 */
2235 }
2236
2237 return ERROR_OK;
2238 }
2239
2240 /* process target state changes */
2241 static int handle_target(void *priv)
2242 {
2243 Jim_Interp *interp = (Jim_Interp *)priv;
2244 int retval = ERROR_OK;
2245
2246 if (!is_jtag_poll_safe()) {
2247 /* polling is disabled currently */
2248 return ERROR_OK;
2249 }
2250
2251 /* we do not want to recurse here... */
2252 static int recursive;
2253 if (!recursive) {
2254 recursive = 1;
2255 sense_handler();
2256 /* danger! running these procedures can trigger srst assertions and power dropouts.
2257 * We need to avoid an infinite loop/recursion here and we do that by
2258 * clearing the flags after running these events.
2259 */
2260 int did_something = 0;
2261 if (runSrstAsserted) {
2262 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2263 Jim_Eval(interp, "srst_asserted");
2264 did_something = 1;
2265 }
2266 if (runSrstDeasserted) {
2267 Jim_Eval(interp, "srst_deasserted");
2268 did_something = 1;
2269 }
2270 if (runPowerDropout) {
2271 LOG_INFO("Power dropout detected, running power_dropout proc.");
2272 Jim_Eval(interp, "power_dropout");
2273 did_something = 1;
2274 }
2275 if (runPowerRestore) {
2276 Jim_Eval(interp, "power_restore");
2277 did_something = 1;
2278 }
2279
2280 if (did_something) {
2281 /* clear detect flags */
2282 sense_handler();
2283 }
2284
2285 /* clear action flags */
2286
2287 runSrstAsserted = 0;
2288 runSrstDeasserted = 0;
2289 runPowerRestore = 0;
2290 runPowerDropout = 0;
2291
2292 recursive = 0;
2293 }
2294
2295 /* Poll targets for state changes unless that's globally disabled.
2296 * Skip targets that are currently disabled.
2297 */
2298 for (struct target *target = all_targets;
2299 is_jtag_poll_safe() && target;
2300 target = target->next) {
2301 if (!target->tap->enabled)
2302 continue;
2303
2304 if (target->backoff.times > target->backoff.count) {
2305 /* do not poll this time as we failed previously */
2306 target->backoff.count++;
2307 continue;
2308 }
2309 target->backoff.count = 0;
2310
2311 /* only poll target if we've got power and srst isn't asserted */
2312 if (!powerDropout && !srstAsserted) {
2313 /* polling may fail silently until the target has been examined */
2314 retval = target_poll(target);
2315 if (retval != ERROR_OK) {
2316 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2317 if (target->backoff.times * polling_interval < 5000) {
2318 target->backoff.times *= 2;
2319 target->backoff.times++;
2320 }
2321 LOG_USER("Polling target %s failed, GDB will be halted. Polling again in %dms",
2322 target_name(target),
2323 target->backoff.times * polling_interval);
2324
2325 /* Tell GDB to halt the debugger. This allows the user to
2326 * run monitor commands to handle the situation.
2327 */
2328 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2329 return retval;
2330 }
2331 /* Since we succeeded, we reset backoff count */
2332 if (target->backoff.times > 0)
2333 LOG_USER("Polling target %s succeeded again", target_name(target));
2334 target->backoff.times = 0;
2335 }
2336 }
2337
2338 return retval;
2339 }
2340
2341 COMMAND_HANDLER(handle_reg_command)
2342 {
2343 struct target *target;
2344 struct reg *reg = NULL;
2345 unsigned count = 0;
2346 char *value;
2347
2348 LOG_DEBUG("-");
2349
2350 target = get_current_target(CMD_CTX);
2351
2352 /* list all available registers for the current target */
2353 if (CMD_ARGC == 0) {
2354 struct reg_cache *cache = target->reg_cache;
2355
2356 count = 0;
2357 while (cache) {
2358 unsigned i;
2359
2360 command_print(CMD_CTX, "===== %s", cache->name);
2361
2362 for (i = 0, reg = cache->reg_list;
2363 i < cache->num_regs;
2364 i++, reg++, count++) {
2365 /* only print cached values if they are valid */
2366 if (reg->valid) {
2367 value = buf_to_str(reg->value,
2368 reg->size, 16);
2369 command_print(CMD_CTX,
2370 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2371 count, reg->name,
2372 reg->size, value,
2373 reg->dirty
2374 ? " (dirty)"
2375 : "");
2376 free(value);
2377 } else {
2378 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2379 count, reg->name,
2380 reg->size) ;
2381 }
2382 }
2383 cache = cache->next;
2384 }
2385
2386 return ERROR_OK;
2387 }
2388
2389 /* access a single register by its ordinal number */
2390 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
2391 unsigned num;
2392 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2393
2394 struct reg_cache *cache = target->reg_cache;
2395 count = 0;
2396 while (cache) {
2397 unsigned i;
2398 for (i = 0; i < cache->num_regs; i++) {
2399 if (count++ == num) {
2400 reg = &cache->reg_list[i];
2401 break;
2402 }
2403 }
2404 if (reg)
2405 break;
2406 cache = cache->next;
2407 }
2408
2409 if (!reg) {
2410 command_print(CMD_CTX, "%i is out of bounds, the current target "
2411 "has only %i registers (0 - %i)", num, count, count - 1);
2412 return ERROR_OK;
2413 }
2414 } else {
2415 /* access a single register by its name */
2416 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2417
2418 if (!reg) {
2419 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2420 return ERROR_OK;
2421 }
2422 }
2423
2424 assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
2425
2426 /* display a register */
2427 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
2428 && (CMD_ARGV[1][0] <= '9')))) {
2429 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2430 reg->valid = 0;
2431
2432 if (reg->valid == 0)
2433 reg->type->get(reg);
2434 value = buf_to_str(reg->value, reg->size, 16);
2435 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2436 free(value);
2437 return ERROR_OK;
2438 }
2439
2440 /* set register value */
2441 if (CMD_ARGC == 2) {
2442 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2443 if (buf == NULL)
2444 return ERROR_FAIL;
2445 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2446
2447 reg->type->set(reg, buf);
2448
2449 value = buf_to_str(reg->value, reg->size, 16);
2450 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2451 free(value);
2452
2453 free(buf);
2454
2455 return ERROR_OK;
2456 }
2457
2458 return ERROR_COMMAND_SYNTAX_ERROR;
2459 }
2460
2461 COMMAND_HANDLER(handle_poll_command)
2462 {
2463 int retval = ERROR_OK;
2464 struct target *target = get_current_target(CMD_CTX);
2465
2466 if (CMD_ARGC == 0) {
2467 command_print(CMD_CTX, "background polling: %s",
2468 jtag_poll_get_enabled() ? "on" : "off");
2469 command_print(CMD_CTX, "TAP: %s (%s)",
2470 target->tap->dotted_name,
2471 target->tap->enabled ? "enabled" : "disabled");
2472 if (!target->tap->enabled)
2473 return ERROR_OK;
2474 retval = target_poll(target);
2475 if (retval != ERROR_OK)
2476 return retval;
2477 retval = target_arch_state(target);
2478 if (retval != ERROR_OK)
2479 return retval;
2480 } else if (CMD_ARGC == 1) {
2481 bool enable;
2482 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2483 jtag_poll_set_enabled(enable);
2484 } else
2485 return ERROR_COMMAND_SYNTAX_ERROR;
2486
2487 return retval;
2488 }
2489
2490 COMMAND_HANDLER(handle_wait_halt_command)
2491 {
2492 if (CMD_ARGC > 1)
2493 return ERROR_COMMAND_SYNTAX_ERROR;
2494
2495 unsigned ms = DEFAULT_HALT_TIMEOUT;
2496 if (1 == CMD_ARGC) {
2497 int retval = parse_uint(CMD_ARGV[0], &ms);
2498 if (ERROR_OK != retval)
2499 return ERROR_COMMAND_SYNTAX_ERROR;
2500 }
2501
2502 struct target *target = get_current_target(CMD_CTX);
2503 return target_wait_state(target, TARGET_HALTED, ms);
2504 }
2505
2506 /* wait for target state to change. The trick here is to have a low
2507 * latency for short waits and not to suck up all the CPU time
2508 * on longer waits.
2509 *
2510 * After 500ms, keep_alive() is invoked
2511 */
2512 int target_wait_state(struct target *target, enum target_state state, int ms)
2513 {
2514 int retval;
2515 long long then = 0, cur;
2516 int once = 1;
2517
2518 for (;;) {
2519 retval = target_poll(target);
2520 if (retval != ERROR_OK)
2521 return retval;
2522 if (target->state == state)
2523 break;
2524 cur = timeval_ms();
2525 if (once) {
2526 once = 0;
2527 then = timeval_ms();
2528 LOG_DEBUG("waiting for target %s...",
2529 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2530 }
2531
2532 if (cur-then > 500)
2533 keep_alive();
2534
2535 if ((cur-then) > ms) {
2536 LOG_ERROR("timed out while waiting for target %s",
2537 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2538 return ERROR_FAIL;
2539 }
2540 }
2541
2542 return ERROR_OK;
2543 }
2544
2545 COMMAND_HANDLER(handle_halt_command)
2546 {
2547 LOG_DEBUG("-");
2548
2549 struct target *target = get_current_target(CMD_CTX);
2550 int retval = target_halt(target);
2551 if (ERROR_OK != retval)
2552 return retval;
2553
2554 if (CMD_ARGC == 1) {
2555 unsigned wait_local;
2556 retval = parse_uint(CMD_ARGV[0], &wait_local);
2557 if (ERROR_OK != retval)
2558 return ERROR_COMMAND_SYNTAX_ERROR;
2559 if (!wait_local)
2560 return ERROR_OK;
2561 }
2562
2563 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2564 }
2565
2566 COMMAND_HANDLER(handle_soft_reset_halt_command)
2567 {
2568 struct target *target = get_current_target(CMD_CTX);
2569
2570 LOG_USER("requesting target halt and executing a soft reset");
2571
2572 target_soft_reset_halt(target);
2573
2574 return ERROR_OK;
2575 }
2576
2577 COMMAND_HANDLER(handle_reset_command)
2578 {
2579 if (CMD_ARGC > 1)
2580 return ERROR_COMMAND_SYNTAX_ERROR;
2581
2582 enum target_reset_mode reset_mode = RESET_RUN;
2583 if (CMD_ARGC == 1) {
2584 const Jim_Nvp *n;
2585 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2586 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
2587 return ERROR_COMMAND_SYNTAX_ERROR;
2588 reset_mode = n->value;
2589 }
2590
2591 /* reset *all* targets */
2592 return target_process_reset(CMD_CTX, reset_mode);
2593 }
2594
2595
2596 COMMAND_HANDLER(handle_resume_command)
2597 {
2598 int current = 1;
2599 if (CMD_ARGC > 1)
2600 return ERROR_COMMAND_SYNTAX_ERROR;
2601
2602 struct target *target = get_current_target(CMD_CTX);
2603
2604 /* with no CMD_ARGV, resume from current pc, addr = 0,
2605 * with one arguments, addr = CMD_ARGV[0],
2606 * handle breakpoints, not debugging */
2607 uint32_t addr = 0;
2608 if (CMD_ARGC == 1) {
2609 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2610 current = 0;
2611 }
2612
2613 return target_resume(target, current, addr, 1, 0);
2614 }
2615
2616 COMMAND_HANDLER(handle_step_command)
2617 {
2618 if (CMD_ARGC > 1)
2619 return ERROR_COMMAND_SYNTAX_ERROR;
2620
2621 LOG_DEBUG("-");
2622
2623 /* with no CMD_ARGV, step from current pc, addr = 0,
2624 * with one argument addr = CMD_ARGV[0],
2625 * handle breakpoints, debugging */
2626 uint32_t addr = 0;
2627 int current_pc = 1;
2628 if (CMD_ARGC == 1) {
2629 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2630 current_pc = 0;
2631 }
2632
2633 struct target *target = get_current_target(CMD_CTX);
2634
2635 return target->type->step(target, current_pc, addr, 1);
2636 }
2637
2638 static void handle_md_output(struct command_context *cmd_ctx,
2639 struct target *target, uint32_t address, unsigned size,
2640 unsigned count, const uint8_t *buffer)
2641 {
2642 const unsigned line_bytecnt = 32;
2643 unsigned line_modulo = line_bytecnt / size;
2644
2645 char output[line_bytecnt * 4 + 1];
2646 unsigned output_len = 0;
2647
2648 const char *value_fmt;
2649 switch (size) {
2650 case 4:
2651 value_fmt = "%8.8x ";
2652 break;
2653 case 2:
2654 value_fmt = "%4.4x ";
2655 break;
2656 case 1:
2657 value_fmt = "%2.2x ";
2658 break;
2659 default:
2660 /* "can't happen", caller checked */
2661 LOG_ERROR("invalid memory read size: %u", size);
2662 return;
2663 }
2664
2665 for (unsigned i = 0; i < count; i++) {
2666 if (i % line_modulo == 0) {
2667 output_len += snprintf(output + output_len,
2668 sizeof(output) - output_len,
2669 "0x%8.8x: ",
2670 (unsigned)(address + (i*size)));
2671 }
2672
2673 uint32_t value = 0;
2674 const uint8_t *value_ptr = buffer + i * size;
2675 switch (size) {
2676 case 4:
2677 value = target_buffer_get_u32(target, value_ptr);
2678 break;
2679 case 2:
2680 value = target_buffer_get_u16(target, value_ptr);
2681 break;
2682 case 1:
2683 value = *value_ptr;
2684 }
2685 output_len += snprintf(output + output_len,
2686 sizeof(output) - output_len,
2687 value_fmt, value);
2688
2689 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
2690 command_print(cmd_ctx, "%s", output);
2691 output_len = 0;
2692 }
2693 }
2694 }
2695
2696 COMMAND_HANDLER(handle_md_command)
2697 {
2698 if (CMD_ARGC < 1)
2699 return ERROR_COMMAND_SYNTAX_ERROR;
2700
2701 unsigned size = 0;
2702 switch (CMD_NAME[2]) {
2703 case 'w':
2704 size = 4;
2705 break;
2706 case 'h':
2707 size = 2;
2708 break;
2709 case 'b':
2710 size = 1;
2711 break;
2712 default:
2713 return ERROR_COMMAND_SYNTAX_ERROR;
2714 }
2715
2716 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2717 int (*fn)(struct target *target,
2718 uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2719 if (physical) {
2720 CMD_ARGC--;
2721 CMD_ARGV++;
2722 fn = target_read_phys_memory;
2723 } else
2724 fn = target_read_memory;
2725 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2726 return ERROR_COMMAND_SYNTAX_ERROR;
2727
2728 uint32_t address;
2729 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2730
2731 unsigned count = 1;
2732 if (CMD_ARGC == 2)
2733 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2734
2735 uint8_t *buffer = calloc(count, size);
2736
2737 struct target *target = get_current_target(CMD_CTX);
2738 int retval = fn(target, address, size, count, buffer);
2739 if (ERROR_OK == retval)
2740 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2741
2742 free(buffer);
2743
2744 return retval;
2745 }
2746
2747 typedef int (*target_write_fn)(struct target *target,
2748 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
2749
2750 static int target_fill_mem(struct target *target,
2751 uint32_t address,
2752 target_write_fn fn,
2753 unsigned data_size,
2754 /* value */
2755 uint32_t b,
2756 /* count */
2757 unsigned c)
2758 {
2759 /* We have to write in reasonably large chunks to be able
2760 * to fill large memory areas with any sane speed */
2761 const unsigned chunk_size = 16384;
2762 uint8_t *target_buf = malloc(chunk_size * data_size);
2763 if (target_buf == NULL) {
2764 LOG_ERROR("Out of memory");
2765 return ERROR_FAIL;
2766 }
2767
2768 for (unsigned i = 0; i < chunk_size; i++) {
2769 switch (data_size) {
2770 case 4:
2771 target_buffer_set_u32(target, target_buf + i * data_size, b);
2772 break;
2773 case 2:
2774 target_buffer_set_u16(target, target_buf + i * data_size, b);
2775 break;
2776 case 1:
2777 target_buffer_set_u8(target, target_buf + i * data_size, b);
2778 break;
2779 default:
2780 exit(-1);
2781 }
2782 }
2783
2784 int retval = ERROR_OK;
2785
2786 for (unsigned x = 0; x < c; x += chunk_size) {
2787 unsigned current;
2788 current = c - x;
2789 if (current > chunk_size)
2790 current = chunk_size;
2791 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2792 if (retval != ERROR_OK)
2793 break;
2794 /* avoid GDB timeouts */
2795 keep_alive();
2796 }
2797 free(target_buf);
2798
2799 return retval;
2800 }
2801
2802
2803 COMMAND_HANDLER(handle_mw_command)
2804 {
2805 if (CMD_ARGC < 2)
2806 return ERROR_COMMAND_SYNTAX_ERROR;
2807 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2808 target_write_fn fn;
2809 if (physical) {
2810 CMD_ARGC--;
2811 CMD_ARGV++;
2812 fn = target_write_phys_memory;
2813 } else
2814 fn = target_write_memory;
2815 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2816 return ERROR_COMMAND_SYNTAX_ERROR;
2817
2818 uint32_t address;
2819 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2820
2821 uint32_t value;
2822 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2823
2824 unsigned count = 1;
2825 if (CMD_ARGC == 3)
2826 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2827
2828 struct target *target = get_current_target(CMD_CTX);
2829 unsigned wordsize;
2830 switch (CMD_NAME[2]) {
2831 case 'w':
2832 wordsize = 4;
2833 break;
2834 case 'h':
2835 wordsize = 2;
2836 break;
2837 case 'b':
2838 wordsize = 1;
2839 break;
2840 default:
2841 return ERROR_COMMAND_SYNTAX_ERROR;
2842 }
2843
2844 return target_fill_mem(target, address, fn, wordsize, value, count);
2845 }
2846
2847 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2848 uint32_t *min_address, uint32_t *max_address)
2849 {
2850 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2851 return ERROR_COMMAND_SYNTAX_ERROR;
2852
2853 /* a base address isn't always necessary,
2854 * default to 0x0 (i.e. don't relocate) */
2855 if (CMD_ARGC >= 2) {
2856 uint32_t addr;
2857 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2858 image->base_address = addr;
2859 image->base_address_set = 1;
2860 } else
2861 image->base_address_set = 0;
2862
2863 image->start_address_set = 0;
2864
2865 if (CMD_ARGC >= 4)
2866 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2867 if (CMD_ARGC == 5) {
2868 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2869 /* use size (given) to find max (required) */
2870 *max_address += *min_address;
2871 }
2872
2873 if (*min_address > *max_address)
2874 return ERROR_COMMAND_SYNTAX_ERROR;
2875
2876 return ERROR_OK;
2877 }
2878
2879 COMMAND_HANDLER(handle_load_image_command)
2880 {
2881 uint8_t *buffer;
2882 size_t buf_cnt;
2883 uint32_t image_size;
2884 uint32_t min_address = 0;
2885 uint32_t max_address = 0xffffffff;
2886 int i;
2887 struct image image;
2888
2889 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2890 &image, &min_address, &max_address);
2891 if (ERROR_OK != retval)
2892 return retval;
2893
2894 struct target *target = get_current_target(CMD_CTX);
2895
2896 struct duration bench;
2897 duration_start(&bench);
2898
2899 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2900 return ERROR_OK;
2901
2902 image_size = 0x0;
2903 retval = ERROR_OK;
2904 for (i = 0; i < image.num_sections; i++) {
2905 buffer = malloc(image.sections[i].size);
2906 if (buffer == NULL) {
2907 command_print(CMD_CTX,
2908 "error allocating buffer for section (%d bytes)",
2909 (int)(image.sections[i].size));
2910 break;
2911 }
2912
2913 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
2914 if (retval != ERROR_OK) {
2915 free(buffer);
2916 break;
2917 }
2918
2919 uint32_t offset = 0;
2920 uint32_t length = buf_cnt;
2921
2922 /* DANGER!!! beware of unsigned comparision here!!! */
2923
2924 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
2925 (image.sections[i].base_address < max_address)) {
2926
2927 if (image.sections[i].base_address < min_address) {
2928 /* clip addresses below */
2929 offset += min_address-image.sections[i].base_address;
2930 length -= offset;
2931 }
2932
2933 if (image.sections[i].base_address + buf_cnt > max_address)
2934 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2935
2936 retval = target_write_buffer(target,
2937 image.sections[i].base_address + offset, length, buffer + offset);
2938 if (retval != ERROR_OK) {
2939 free(buffer);
2940 break;
2941 }
2942 image_size += length;
2943 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2944 (unsigned int)length,
2945 image.sections[i].base_address + offset);
2946 }
2947
2948 free(buffer);
2949 }
2950
2951 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
2952 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2953 "in %fs (%0.3f KiB/s)", image_size,
2954 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2955 }
2956
2957 image_close(&image);
2958
2959 return retval;
2960
2961 }
2962
2963 COMMAND_HANDLER(handle_dump_image_command)
2964 {
2965 struct fileio fileio;
2966 uint8_t *buffer;
2967 int retval, retvaltemp;
2968 uint32_t address, size;
2969 struct duration bench;
2970 struct target *target = get_current_target(CMD_CTX);
2971
2972 if (CMD_ARGC != 3)
2973 return ERROR_COMMAND_SYNTAX_ERROR;
2974
2975 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2976 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2977
2978 uint32_t buf_size = (size > 4096) ? 4096 : size;
2979 buffer = malloc(buf_size);
2980 if (!buffer)
2981 return ERROR_FAIL;
2982
2983 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
2984 if (retval != ERROR_OK) {
2985 free(buffer);
2986 return retval;
2987 }
2988
2989 duration_start(&bench);
2990
2991 while (size > 0) {
2992 size_t size_written;
2993 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
2994 retval = target_read_buffer(target, address, this_run_size, buffer);
2995 if (retval != ERROR_OK)
2996 break;
2997
2998 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2999 if (retval != ERROR_OK)
3000 break;
3001
3002 size -= this_run_size;
3003 address += this_run_size;
3004 }
3005
3006 free(buffer);
3007
3008 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3009 int filesize;
3010 retval = fileio_size(&fileio, &filesize);
3011 if (retval != ERROR_OK)
3012 return retval;
3013 command_print(CMD_CTX,
3014 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
3015 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3016 }
3017
3018 retvaltemp = fileio_close(&fileio);
3019 if (retvaltemp != ERROR_OK)
3020 return retvaltemp;
3021
3022 return retval;
3023 }
3024
3025 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
3026 {
3027 uint8_t *buffer;
3028 size_t buf_cnt;
3029 uint32_t image_size;
3030 int i;
3031 int retval;
3032 uint32_t checksum = 0;
3033 uint32_t mem_checksum = 0;
3034
3035 struct image image;
3036
3037 struct target *target = get_current_target(CMD_CTX);
3038
3039 if (CMD_ARGC < 1)
3040 return ERROR_COMMAND_SYNTAX_ERROR;
3041
3042 if (!target) {
3043 LOG_ERROR("no target selected");
3044 return ERROR_FAIL;
3045 }
3046
3047 struct duration bench;
3048 duration_start(&bench);
3049
3050 if (CMD_ARGC >= 2) {
3051 uint32_t addr;
3052 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
3053 image.base_address = addr;
3054 image.base_address_set = 1;
3055 } else {
3056 image.base_address_set = 0;
3057 image.base_address = 0x0;
3058 }
3059
3060 image.start_address_set = 0;
3061
3062 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3063 if (retval != ERROR_OK)
3064 return retval;
3065
3066 image_size = 0x0;
3067 int diffs = 0;
3068 retval = ERROR_OK;
3069 for (i = 0; i < image.num_sections; i++) {
3070 buffer = malloc(image.sections[i].size);
3071 if (buffer == NULL) {
3072 command_print(CMD_CTX,
3073 "error allocating buffer for section (%d bytes)",
3074 (int)(image.sections[i].size));
3075 break;
3076 }
3077 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3078 if (retval != ERROR_OK) {
3079 free(buffer);
3080 break;
3081 }
3082
3083 if (verify) {
3084 /* calculate checksum of image */
3085 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3086 if (retval != ERROR_OK) {
3087 free(buffer);
3088 break;
3089 }
3090
3091 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3092 if (retval != ERROR_OK) {
3093 free(buffer);
3094 break;
3095 }
3096
3097 if (checksum != mem_checksum) {
3098 /* failed crc checksum, fall back to a binary compare */
3099 uint8_t *data;
3100
3101 if (diffs == 0)
3102 LOG_ERROR("checksum mismatch - attempting binary compare");
3103
3104 data = (uint8_t *)malloc(buf_cnt);
3105
3106 /* Can we use 32bit word accesses? */
3107 int size = 1;
3108 int count = buf_cnt;
3109 if ((count % 4) == 0) {
3110 size *= 4;
3111 count /= 4;
3112 }
3113 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
3114 if (retval == ERROR_OK) {
3115 uint32_t t;
3116 for (t = 0; t < buf_cnt; t++) {
3117 if (data[t] != buffer[t]) {
3118 command_print(CMD_CTX,
3119 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3120 diffs,
3121 (unsigned)(t + image.sections[i].base_address),
3122 data[t],
3123 buffer[t]);
3124 if (diffs++ >= 127) {
3125 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
3126 free(data);
3127 free(buffer);
3128 goto done;
3129 }
3130 }
3131 keep_alive();
3132 }
3133 }
3134 free(data);
3135 }
3136 } else {
3137 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
3138 image.sections[i].base_address,
3139 buf_cnt);
3140 }
3141
3142 free(buffer);
3143 image_size += buf_cnt;
3144 }
3145 if (diffs > 0)
3146 command_print(CMD_CTX, "No more differences found.");
3147 done:
3148 if (diffs > 0)
3149 retval = ERROR_FAIL;
3150 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3151 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
3152 "in %fs (%0.3f KiB/s)", image_size,
3153 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3154 }
3155
3156 image_close(&image);
3157
3158 return retval;
3159 }
3160
3161 COMMAND_HANDLER(handle_verify_image_command)
3162 {
3163 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
3164 }
3165
3166 COMMAND_HANDLER(handle_test_image_command)
3167 {
3168 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
3169 }
3170
3171 static int handle_bp_command_list(struct command_context *cmd_ctx)
3172 {
3173 struct target *target = get_current_target(cmd_ctx);
3174 struct breakpoint *breakpoint = target->breakpoints;
3175 while (breakpoint) {
3176 if (breakpoint->type == BKPT_SOFT) {
3177 char *buf = buf_to_str(breakpoint->orig_instr,
3178 breakpoint->length, 16);
3179 command_print(cmd_ctx, "IVA breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
3180 breakpoint->address,
3181 breakpoint->length,
3182 breakpoint->set, buf);
3183 free(buf);
3184 } else {
3185 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3186 command_print(cmd_ctx, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3187 breakpoint->asid,
3188 breakpoint->length, breakpoint->set);
3189 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3190 command_print(cmd_ctx, "Hybrid breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3191 breakpoint->address,
3192 breakpoint->length, breakpoint->set);
3193 command_print(cmd_ctx, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3194 breakpoint->asid);
3195 } else
3196 command_print(cmd_ctx, "Breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3197 breakpoint->address,
3198 breakpoint->length, breakpoint->set);
3199 }
3200
3201 breakpoint = breakpoint->next;
3202 }
3203 return ERROR_OK;
3204 }
3205
3206 static int handle_bp_command_set(struct command_context *cmd_ctx,
3207 uint32_t addr, uint32_t asid, uint32_t length, int hw)
3208 {
3209 struct target *target = get_current_target(cmd_ctx);
3210
3211 if (asid == 0) {
3212 int retval = breakpoint_add(target, addr, length, hw);
3213 if (ERROR_OK == retval)
3214 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
3215 else {
3216 LOG_ERROR("Failure setting breakpoint, the same address(IVA) is already used");
3217 return retval;
3218 }
3219 } else if (addr == 0) {
3220 int retval = context_breakpoint_add(target, asid, length, hw);
3221 if (ERROR_OK == retval)
3222 command_print(cmd_ctx, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3223 else {
3224 LOG_ERROR("Failure setting breakpoint, the same address(CONTEXTID) is already used");
3225 return retval;
3226 }
3227 } else {
3228 int retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3229 if (ERROR_OK == retval)
3230 command_print(cmd_ctx, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3231 else {
3232 LOG_ERROR("Failure setting breakpoint, the same address is already used");
3233 return retval;
3234 }
3235 }
3236 return ERROR_OK;
3237 }
3238
3239 COMMAND_HANDLER(handle_bp_command)
3240 {
3241 uint32_t addr;
3242 uint32_t asid;
3243 uint32_t length;
3244 int hw = BKPT_SOFT;
3245
3246 switch (CMD_ARGC) {
3247 case 0:
3248 return handle_bp_command_list(CMD_CTX);
3249
3250 case 2:
3251 asid = 0;
3252 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3253 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3254 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3255
3256 case 3:
3257 if (strcmp(CMD_ARGV[2], "hw") == 0) {
3258 hw = BKPT_HARD;
3259 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3260
3261 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3262
3263 asid = 0;
3264 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3265 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
3266 hw = BKPT_HARD;
3267 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
3268 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3269 addr = 0;
3270 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3271 }
3272
3273 case 4:
3274 hw = BKPT_HARD;
3275 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3276 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
3277 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
3278 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3279
3280 default:
3281 return ERROR_COMMAND_SYNTAX_ERROR;
3282 }
3283 }
3284
3285 COMMAND_HANDLER(handle_rbp_command)
3286 {
3287 if (CMD_ARGC != 1)
3288 return ERROR_COMMAND_SYNTAX_ERROR;
3289
3290 uint32_t addr;
3291 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3292
3293 struct target *target = get_current_target(CMD_CTX);
3294 breakpoint_remove(target, addr);
3295
3296 return ERROR_OK;
3297 }
3298
3299 COMMAND_HANDLER(handle_wp_command)
3300 {
3301 struct target *target = get_current_target(CMD_CTX);
3302
3303 if (CMD_ARGC == 0) {
3304 struct watchpoint *watchpoint = target->watchpoints;
3305
3306 while (watchpoint) {
3307 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
3308 ", len: 0x%8.8" PRIx32
3309 ", r/w/a: %i, value: 0x%8.8" PRIx32
3310 ", mask: 0x%8.8" PRIx32,
3311 watchpoint->address,
3312 watchpoint->length,
3313 (int)watchpoint->rw,
3314 watchpoint->value,
3315 watchpoint->mask);
3316 watchpoint = watchpoint->next;
3317 }
3318 return ERROR_OK;
3319 }
3320
3321 enum watchpoint_rw type = WPT_ACCESS;
3322 uint32_t addr = 0;
3323 uint32_t length = 0;
3324 uint32_t data_value = 0x0;
3325 uint32_t data_mask = 0xffffffff;
3326
3327 switch (CMD_ARGC) {
3328 case 5:
3329 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
3330 /* fall through */
3331 case 4:
3332 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
3333 /* fall through */
3334 case 3:
3335 switch (CMD_ARGV[2][0]) {
3336 case 'r':
3337 type = WPT_READ;
3338 break;
3339 case 'w':
3340 type = WPT_WRITE;
3341 break;
3342 case 'a':
3343 type = WPT_ACCESS;
3344 break;
3345 default:
3346 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3347 return ERROR_COMMAND_SYNTAX_ERROR;
3348 }
3349 /* fall through */
3350 case 2:
3351 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3352 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3353 break;
3354
3355 default:
3356 return ERROR_COMMAND_SYNTAX_ERROR;
3357 }
3358
3359 int retval = watchpoint_add(target, addr, length, type,
3360 data_value, data_mask);
3361 if (ERROR_OK != retval)
3362 LOG_ERROR("Failure setting watchpoints");
3363
3364 return retval;
3365 }
3366
3367 COMMAND_HANDLER(handle_rwp_command)
3368 {
3369 if (CMD_ARGC != 1)
3370 return ERROR_COMMAND_SYNTAX_ERROR;
3371
3372 uint32_t addr;
3373 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3374
3375 struct target *target = get_current_target(CMD_CTX);
3376 watchpoint_remove(target, addr);
3377
3378 return ERROR_OK;
3379 }
3380
3381 /**
3382 * Translate a virtual address to a physical address.
3383 *
3384 * The low-level target implementation must have logged a detailed error
3385 * which is forwarded to telnet/GDB session.
3386 */
3387 COMMAND_HANDLER(handle_virt2phys_command)
3388 {
3389 if (CMD_ARGC != 1)
3390 return ERROR_COMMAND_SYNTAX_ERROR;
3391
3392 uint32_t va;
3393 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3394 uint32_t pa;
3395
3396 struct target *target = get_current_target(CMD_CTX);
3397 int retval = target->type->virt2phys(target, va, &pa);
3398 if (retval == ERROR_OK)
3399 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3400
3401 return retval;
3402 }
3403
3404 static void writeData(FILE *f, const void *data, size_t len)
3405 {
3406 size_t written = fwrite(data, 1, len, f);
3407 if (written != len)
3408 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3409 }
3410
3411 static void writeLong(FILE *f, int l)
3412 {
3413 int i;
3414 for (i = 0; i < 4; i++) {
3415 char c = (l >> (i*8))&0xff;
3416 writeData(f, &c, 1);
3417 }
3418
3419 }
3420
3421 static void writeString(FILE *f, char *s)
3422 {
3423 writeData(f, s, strlen(s));
3424 }
3425
3426 typedef unsigned char UNIT[2]; /* unit of profiling */
3427
3428 /* Dump a gmon.out histogram file. */
3429 static void write_gmon(uint32_t *samples, uint32_t sampleNum, const char *filename,
3430 bool with_range, uint32_t start_address, uint32_t end_address)
3431 {
3432 uint32_t i;
3433 FILE *f = fopen(filename, "w");
3434 if (f == NULL)
3435 return;
3436 writeString(f, "gmon");
3437 writeLong(f, 0x00000001); /* Version */
3438 writeLong(f, 0); /* padding */
3439 writeLong(f, 0); /* padding */
3440 writeLong(f, 0); /* padding */
3441
3442 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3443 writeData(f, &zero, 1);
3444
3445 /* figure out bucket size */
3446 uint32_t min;
3447 uint32_t max;
3448 if (with_range) {
3449 min = start_address;
3450 max = end_address;
3451 } else {
3452 min = samples[0];
3453 max = samples[0];
3454 for (i = 0; i < sampleNum; i++) {
3455 if (min > samples[i])
3456 min = samples[i];
3457 if (max < samples[i])
3458 max = samples[i];
3459 }
3460
3461 /* max should be (largest sample + 1)
3462 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
3463 max++;
3464 }
3465
3466 int addressSpace = max - min;
3467 assert(addressSpace >= 2);
3468
3469 /* FIXME: What is the reasonable number of buckets?
3470 * The profiling result will be more accurate if there are enough buckets. */
3471 static const uint32_t maxBuckets = 128 * 1024; /* maximum buckets. */
3472 uint32_t numBuckets = addressSpace / sizeof(UNIT);
3473 if (numBuckets > maxBuckets)
3474 numBuckets = maxBuckets;
3475 int *buckets = malloc(sizeof(int) * numBuckets);
3476 if (buckets == NULL) {
3477 fclose(f);
3478 return;
3479 }
3480 memset(buckets, 0, sizeof(int) * numBuckets);
3481 for (i = 0; i < sampleNum; i++) {
3482 uint32_t address = samples[i];
3483
3484 if ((address < min) || (max <= address))
3485 continue;
3486
3487 long long a = address - min;
3488 long long b = numBuckets;
3489 long long c = addressSpace;
3490 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
3491 buckets[index_t]++;
3492 }
3493
3494 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3495 writeLong(f, min); /* low_pc */
3496 writeLong(f, max); /* high_pc */
3497 writeLong(f, numBuckets); /* # of buckets */
3498 writeLong(f, 100); /* KLUDGE! We lie, ca. 100Hz best case. */
3499 writeString(f, "seconds");
3500 for (i = 0; i < (15-strlen("seconds")); i++)
3501 writeData(f, &zero, 1);
3502 writeString(f, "s");
3503
3504 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3505
3506 char *data = malloc(2 * numBuckets);
3507 if (data != NULL) {
3508 for (i = 0; i < numBuckets; i++) {
3509 int val;
3510 val = buckets[i];
3511 if (val > 65535)
3512 val = 65535;
3513 data[i * 2] = val&0xff;
3514 data[i * 2 + 1] = (val >> 8) & 0xff;
3515 }
3516 free(buckets);
3517 writeData(f, data, numBuckets * 2);
3518 free(data);
3519 } else
3520 free(buckets);
3521
3522 fclose(f);
3523 }
3524
3525 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3526 * which will be used as a random sampling of PC */
3527 COMMAND_HANDLER(handle_profile_command)
3528 {
3529 struct target *target = get_current_target(CMD_CTX);
3530
3531 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
3532 return ERROR_COMMAND_SYNTAX_ERROR;
3533
3534 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
3535 uint32_t offset;
3536 uint32_t num_of_sampels;
3537 int retval = ERROR_OK;
3538 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
3539 if (samples == NULL) {
3540 LOG_ERROR("No memory to store samples.");
3541 return ERROR_FAIL;
3542 }
3543
3544 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
3545
3546 /**
3547 * Some cores let us sample the PC without the
3548 * annoying halt/resume step; for example, ARMv7 PCSR.
3549 * Provide a way to use that more efficient mechanism.
3550 */
3551 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
3552 &num_of_sampels, offset);
3553 if (retval != ERROR_OK) {
3554 free(samples);
3555 return retval;
3556 }
3557
3558 assert(num_of_sampels <= MAX_PROFILE_SAMPLE_NUM);
3559
3560 retval = target_poll(target);
3561 if (retval != ERROR_OK) {
3562 free(samples);
3563 return retval;
3564 }
3565 if (target->state == TARGET_RUNNING) {
3566 retval = target_halt(target);
3567 if (retval != ERROR_OK) {
3568 free(samples);
3569 return retval;
3570 }
3571 }
3572
3573 retval = target_poll(target);
3574 if (retval != ERROR_OK) {
3575 free(samples);
3576 return retval;
3577 }
3578
3579 uint32_t start_address = 0;
3580 uint32_t end_address = 0;
3581 bool with_range = false;
3582 if (CMD_ARGC == 4) {
3583 with_range = true;
3584 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
3585 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
3586 }
3587
3588 write_gmon(samples, num_of_sampels, CMD_ARGV[1],
3589 with_range, start_address, end_address);
3590 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3591
3592 free(samples);
3593 return retval;
3594 }
3595
3596 static int new_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t val)
3597 {
3598 char *namebuf;
3599 Jim_Obj *nameObjPtr, *valObjPtr;
3600 int result;
3601
3602 namebuf = alloc_printf("%s(%d)", varname, idx);
3603 if (!namebuf)
3604 return JIM_ERR;
3605
3606 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3607 valObjPtr = Jim_NewIntObj(interp, val);
3608 if (!nameObjPtr || !valObjPtr) {
3609 free(namebuf);
3610 return JIM_ERR;
3611 }
3612
3613 Jim_IncrRefCount(nameObjPtr);
3614 Jim_IncrRefCount(valObjPtr);
3615 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3616 Jim_DecrRefCount(interp, nameObjPtr);
3617 Jim_DecrRefCount(interp, valObjPtr);
3618 free(namebuf);
3619 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3620 return result;
3621 }
3622
3623 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3624 {
3625 struct command_context *context;
3626 struct target *target;
3627
3628 context = current_command_context(interp);
3629 assert(context != NULL);
3630
3631 target = get_current_target(context);
3632 if (target == NULL) {
3633 LOG_ERROR("mem2array: no current target");
3634 return JIM_ERR;
3635 }
3636
3637 return target_mem2array(interp, target, argc - 1, argv + 1);
3638 }
3639
3640 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3641 {
3642 long l;
3643 uint32_t width;
3644 int len;
3645 uint32_t addr;
3646 uint32_t count;
3647 uint32_t v;
3648 const char *varname;
3649 int n, e, retval;
3650 uint32_t i;
3651
3652 /* argv[1] = name of array to receive the data
3653