# pyOCD debugger
# Copyright (c) 2015-2019 Arm Limited
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function

# Notes about this script
# 1. This script runs inside arm-none-eabi-gdb-py
# 2. GDB processes commands inside a queue on a worker
#    thread.  Commands that change the state of the target
#    should run from this queue via gdb.post_event(cb).
# 3. After running a command that changes the state of a target
#    in the background, like "continue&", the code needs to
#    return so the event processing that occurs on the worker
#    thread can continue.  No target state changes will be
#    seen until the worker thread gets a chance to process the data.
# 4. To make the code flow better with #3 the main test function,
#    run_test, takes advantage of the 'yield' call.  After
#    performing a background operation that causes the target run
#    'yield' must be called with a timeout value.  The code
#    will wait for the target to halt for the time specified and
#    if no signal arrives in that time the target is explicitly
#    halted.
# 5. Only use packages in the standard library in this script.
#    Since the current version of arm-none-eabi-gdb-py.exe is
#    only 32 bit on windows, there must be a 32 bit python
#    install for it to work.  If your primary version of python
#    is 64 bit, you can install the 32 bit version as a non
#    primary version.  This will allow arm-none-eabi-gdb-py.exe
#    to work.  The only problem with this is that when pyOCD
#    is installed through pip only the 64 bit version of
#    pyOCD and it's dependencies will get installed.
#    If only the standard library is used here then this
#    script will have no external dependencies.

import gdb
from time import time
from threading import Timer
from functools import partial
from random import randrange
from itertools import product
import traceback
import json
import sys
import os

# We expect arm-none-eabi-gdb-py to only run Python 2.x. If it moves
# to Python 3, we need to know about it, so print a warning.
print("arm-none-eabi-gdb-py is using Python %s" % sys.version)
if sys.version_info.major != 2:
    print("*** Unexpected arm-none-eabi-gdb-py Python version %d! ***" % sys.version_info.major)

DEFAULT_TIMEOUT = 2.0
STACK_OFFSET = 0x800
TEST_RAM_OFFSET = 0x800
MAX_TEST_SIZE = 0x1000
MAX_BKPT = 10

assert STACK_OFFSET < MAX_TEST_SIZE
assert TEST_RAM_OFFSET < MAX_TEST_SIZE

monitor_commands = [
    "help",
    "help reset",
    "help halt",
    "init",
    "reset",
    "reset halt",
    "halt",
    "arm semihosting enable",
    "arm semihosting disable",
    "set vector-catch n",
    "set vector-catch a",
    "set step-into-interrupt on",
    "set step-into-interrupt off",
    "threads status",
    "readdp 0",
    "status",
    "show fault",
    # Invalid Command
    "intentional_invalid_command_fawehfawoefhad"
]

SIZE_TO_C_TYPE = {
    1: "uint8_t*",
    2: "uint16_t*",
    4: "uint32_t*",
}

TO_GDB_ACCESS = {
    "read": gdb.WP_READ,
    "write": gdb.WP_WRITE,
    "read_write": gdb.WP_ACCESS,
}

env_name = os.environ.get('TOX_ENV_NAME', '')
env_file_name = ("_" + env_name) if env_name else ''

def gdb_execute(cmd):
    print("Executing command:", cmd)
    gdb.execute(cmd)


def test_step_type(step_type):
    step_count = 20
    start = time()
    for _ in range(step_count):
        gdb_execute(step_type)
    end = time()
    seconds_per_operation = (end - start) / step_count
    return seconds_per_operation


def is_event_breakpoint(event, bkpt=None):
    if not isinstance(event, gdb.BreakpointEvent):
        return False
    if bkpt is None:
        return True
    return event.breakpoints[-1] is bkpt


def is_event_signal(event, signal_name):
    if not isinstance(event, gdb.SignalEvent):
        return False
    return event.stop_signal == signal_name


def has_read(name):
    if name == "read":
        return True
    if name == "read_write":
        return True
    assert name == "write"
    return False


def has_write(name):
    if name == "write":
        return True
    if name == "read_write":
        return True
    assert name == "read"
    return False


def size_to_type(size):
    return SIZE_TO_C_TYPE[size]


def to_gdb_access(access):
    return TO_GDB_ACCESS[access]


def should_trigger_break(bkpt_size, bkpt_access,
                         bkpt_addr, size, access, addr):
    left_access_addr = addr
    right_access_addr = addr + size - 1
    left_bkpt_addr = bkpt_addr
    right_bkpt_addr = bkpt_addr + bkpt_size
    overlap = (left_access_addr <= right_bkpt_addr and
               right_access_addr >= left_bkpt_addr)
    read_break = has_read(bkpt_access) and has_read(access)
    write_break = has_write(bkpt_access) and has_write(access)
    should_break = overlap and (read_break or write_break)
    return should_break


def valid_watchpoint(bkpt_size, bkpt_access, bkpt_addr):
    # Unaligned breakpoints are not allowed
    return bkpt_addr % bkpt_size == 0


# Initial setup
testn = int(gdb.parse_and_eval("$testn"))

test_param_filename = "gdb_test_params%s_%d.txt" % (env_file_name, testn)
with open(test_param_filename, "rb") as f:
    test_params = json.loads(f.read())


def run_test():

    test_result = {}
    test_port = test_params["test_port"]
    rom_start = test_params['rom_start']
    ram_start = test_params['ram_start']
    ram_length = test_params['ram_length']
    invalid_addr = test_params["invalid_start"]