1 // Copyright 2015-2020 Espressif Systems (Shanghai) PTE LTD
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "soc/uart_periph.h"
16 #include "soc/gpio_periph.h"
17 #include "soc/soc.h"
18 #include "esp_gdbstub_common.h"
19 #include "sdkconfig.h"
20 
21 #define UART_NUM CONFIG_ESP_CONSOLE_UART_NUM
22 
23 #define GDBSTUB_MEM_REGION_COUNT 9
24 
25 #define UART_REG_FIELD_LEN 0x84
26 
27 typedef struct {
28     intptr_t lower;
29     intptr_t upper;
30 } mem_bound_t;
31 
32 static const mem_bound_t mem_region_table [GDBSTUB_MEM_REGION_COUNT] =
33 {
34     {SOC_DROM_LOW, SOC_DROM_HIGH},
35     {SOC_IROM_LOW, SOC_IROM_HIGH},
36     {SOC_IRAM_LOW, SOC_IRAM_HIGH},
37     {SOC_DRAM_LOW, SOC_DRAM_HIGH},
38     {SOC_IROM_MASK_LOW, SOC_IROM_MASK_HIGH},
39     {SOC_DROM_MASK_LOW, SOC_DROM_MASK_HIGH},
40     {SOC_RTC_IRAM_LOW, SOC_RTC_IRAM_HIGH},
41     // RTC DRAM and RTC DATA are identical with RTC IRAM, hence we skip them
42     // We shouldn't read the uart registers since it will disturb the debugging via UART,
43     // so skip UART part of the peripheral registers.
44     {DR_REG_UART_BASE + UART_REG_FIELD_LEN, SOC_PERIPHERAL_HIGH},
45     {SOC_DEBUG_LOW, SOC_DEBUG_HIGH},
46 };
47 
check_inside_valid_region(intptr_t addr)48 static inline bool check_inside_valid_region(intptr_t addr)
49 {
50     for (size_t i = 0; i < GDBSTUB_MEM_REGION_COUNT; i++) {
51         if (addr >= mem_region_table[i].lower && addr < mem_region_table[i].upper) {
52             return true;
53         }
54     }
55 
56     return false;
57 }
58 
esp_gdbstub_target_init()59 void esp_gdbstub_target_init()
60 {
61 }
62 
esp_gdbstub_getchar()63 int esp_gdbstub_getchar()
64 {
65     while (REG_GET_FIELD(UART_STATUS_REG(UART_NUM), UART_RXFIFO_CNT) == 0) {
66         ;
67     }
68     return REG_READ(UART_FIFO_AHB_REG(UART_NUM));
69 }
70 
esp_gdbstub_putchar(int c)71 void esp_gdbstub_putchar(int c)
72 {
73     while (REG_GET_FIELD(UART_STATUS_REG(UART_NUM), UART_TXFIFO_CNT) >= 126) {
74         ;
75     }
76     REG_WRITE(UART_FIFO_AHB_REG(UART_NUM), c);
77 }
78 
esp_gdbstub_readmem(intptr_t addr)79 int esp_gdbstub_readmem(intptr_t addr)
80 {
81     if (!check_inside_valid_region(addr)) {
82         /* see esp_cpu_configure_region_protection */
83         return -1;
84     }
85     uint32_t val_aligned = *(uint32_t *)(addr & (~3));
86     uint32_t shift = (addr & 3) * 8;
87     return (val_aligned >> shift) & 0xff;
88 }
89