1 /* Copyright 2016 Fred Sundvik
3 * This program is free software: you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation, either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 #include "variable_trace.h"
22 # error "You need undef NO_PRINT to use the variable trace feature"
25 #ifndef CONSOLE_ENABLE
26 # error "The console needs to be enabled in the makefile to use the variable trace feature"
29 #define NUM_TRACED_VARIABLES 1
30 #ifndef MAX_VARIABLE_TRACE_SIZE
31 # define MAX_VARIABLE_TRACE_SIZE 4
40 uint8_t last_value[MAX_VARIABLE_TRACE_SIZE];
44 static traced_variable_t traced_variables[NUM_TRACED_VARIABLES];
46 void add_traced_variable(const char* name, void* addr, unsigned size, const char* func, int line) {
47 verify_traced_variables(func, line);
48 if (size > MAX_VARIABLE_TRACE_SIZE) {
50 xprintf("Traced variable \"%S\" exceeds the maximum size %d\n", name, size);
52 xprintf("Traced variable \"%s\" exceeds the maximum size %d\n", name, size);
54 size = MAX_VARIABLE_TRACE_SIZE;
57 for (int i = 0; i < NUM_TRACED_VARIABLES; i++) {
58 if (index == -1 && traced_variables[i].addr == NULL) {
60 } else if (strcmp_P(name, traced_variables[i].name) == 0) {
67 xprintf("You can only trace %d variables at the same time\n", NUM_TRACED_VARIABLES);
71 traced_variable_t* t = &traced_variables[index];
77 memcpy(&t->last_value[0], addr, size);
80 void remove_traced_variable(const char* name, const char* func, int line) {
81 verify_traced_variables(func, line);
82 for (int i = 0; i < NUM_TRACED_VARIABLES; i++) {
83 if (strcmp_P(name, traced_variables[i].name) == 0) {
84 traced_variables[i].name = 0;
85 traced_variables[i].addr = NULL;
91 void verify_traced_variables(const char* func, int line) {
92 for (int i = 0; i < NUM_TRACED_VARIABLES; i++) {
93 traced_variable_t* t = &traced_variables[i];
94 if (t->addr != NULL && t->name != NULL) {
95 if (memcmp(t->last_value, t->addr, t->size) != 0) {
97 xprintf("Traced variable \"%S\" has been modified\n", t->name);
98 xprintf("Between %S:%d\n", t->func, t->line);
99 xprintf("And %S:%d\n", func, line);
102 xprintf("Traced variable \"%s\" has been modified\n", t->name);
103 xprintf("Between %s:%d\n", t->func, t->line);
104 xprintf("And %s:%d\n", func, line);
106 xprintf("Previous value ");
107 for (int j = 0; j < t->size; j++) {
108 print_hex8(t->last_value[j]);
110 xprintf("\nNew value ");
111 uint8_t* addr = (uint8_t*)(t->addr);
112 for (int j = 0; j < t->size; j++) {
116 memcpy(t->last_value, addr, t->size);