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"
30 #define NUM_TRACED_VARIABLES 1
31 #ifndef MAX_VARIABLE_TRACE_SIZE
32 #define MAX_VARIABLE_TRACE_SIZE 4
41 uint8_t last_value[MAX_VARIABLE_TRACE_SIZE];
45 static traced_variable_t traced_variables[NUM_TRACED_VARIABLES];
47 void add_traced_variable(const char* name, void* addr, unsigned size, const char* func, int line) {
48 verify_traced_variables(func, line);
49 if (size > MAX_VARIABLE_TRACE_SIZE) {
51 xprintf("Traced variable \"%S\" exceeds the maximum size %d\n", name, size);
53 xprintf("Traced variable \"%s\" exceeds the maximum size %d\n", name, size);
55 size = MAX_VARIABLE_TRACE_SIZE;
58 for (int i = 0; i < NUM_TRACED_VARIABLES; i++) {
59 if (index == -1 && traced_variables[i].addr == NULL){
62 else if (strcmp_P(name, traced_variables[i].name)==0) {
69 xprintf("You can only trace %d variables at the same time\n", NUM_TRACED_VARIABLES);
73 traced_variable_t* t = &traced_variables[index];
79 memcpy(&t->last_value[0], addr, size);
83 void remove_traced_variable(const char* name, const char* func, int line) {
84 verify_traced_variables(func, line);
85 for (int i = 0; i < NUM_TRACED_VARIABLES; i++) {
86 if (strcmp_P(name, traced_variables[i].name)==0) {
87 traced_variables[i].name = 0;
88 traced_variables[i].addr = NULL;
94 void verify_traced_variables(const char* func, int line) {
95 for (int i = 0; i < NUM_TRACED_VARIABLES; i++) {
96 traced_variable_t* t = &traced_variables[i];
97 if (t->addr != NULL && t->name != NULL) {
98 if (memcmp(t->last_value, t->addr, t->size)!=0){
100 xprintf("Traced variable \"%S\" has been modified\n", t->name);
101 xprintf("Between %S:%d\n", t->func, t->line);
102 xprintf("And %S:%d\n", func, line);
105 xprintf("Traced variable \"%s\" has been modified\n", t->name);
106 xprintf("Between %s:%d\n", t->func, t->line);
107 xprintf("And %s:%d\n", func, line);
109 xprintf("Previous value ");
110 for (int j=0; j<t->size;j++) {
111 print_hex8(t->last_value[j]);
113 xprintf("\nNew value ");
114 uint8_t* addr = (uint8_t*)(t->addr);
115 for (int j=0; j<t->size;j++) {
119 memcpy(t->last_value, addr, t->size);