1#
2# Copyright 2021 Espressif Systems (Shanghai) CO., LTD
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#     http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16
17from construct import Int16ul, Int32ul, Padding, Struct
18from corefile import BaseArchMethodsMixin, BaseTargetMethods, ESPCoreDumpLoaderError
19
20try:
21    from typing import Any, Optional, Tuple
22except ImportError:
23    pass
24
25RISCV_GP_REGS_COUNT = 32
26PRSTATUS_SIZE = 204
27PRSTATUS_OFFSET_PR_CURSIG = 12
28PRSTATUS_OFFSET_PR_PID = 24
29PRSTATUS_OFFSET_PR_REG = 72
30ELF_GREGSET_T_SIZE = 128
31
32PrStruct = Struct(
33    Padding(PRSTATUS_OFFSET_PR_CURSIG),
34    'pr_cursig' / Int16ul,
35    Padding(PRSTATUS_OFFSET_PR_PID - PRSTATUS_OFFSET_PR_CURSIG - Int16ul.sizeof()),
36    'pr_pid' / Int32ul,
37    Padding(PRSTATUS_OFFSET_PR_REG - PRSTATUS_OFFSET_PR_PID - Int32ul.sizeof()),
38    'regs' / Int32ul[RISCV_GP_REGS_COUNT],
39    Padding(PRSTATUS_SIZE - PRSTATUS_OFFSET_PR_REG - ELF_GREGSET_T_SIZE)
40)
41
42
43class RiscvMethodsMixin(BaseArchMethodsMixin):
44    @staticmethod
45    def get_registers_from_stack(data, grows_down):
46        # type: (bytes, bool) -> Tuple[list[int], Optional[dict[int, int]]]
47        regs = Int32ul[RISCV_GP_REGS_COUNT].parse(data)
48        if not grows_down:
49            raise ESPCoreDumpLoaderError('Growing up stacks are not supported for now!')
50        return regs, None
51
52    @staticmethod
53    def build_prstatus_data(tcb_addr, task_regs):  # type: (int, list[int]) -> Any
54        return PrStruct.build({
55            'pr_cursig': 0,
56            'pr_pid': tcb_addr,
57            'regs': task_regs,
58        })
59
60
61class Esp32c3Methods(BaseTargetMethods, RiscvMethodsMixin):
62    TARGET = 'esp32c3'
63