# pyOCD debugger
# Copyright (c) 2006-2013 Arm Limited
# Copyright (c) 2019 Monadnock Systems Ltd.
# Copyright (c) 2023 Nordic Semiconductor ASA
# 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.
import logging
from time import sleep
import os
import re
from zipfile import ZipFile
from tempfile import TemporaryDirectory
from intelhex import IntelHex

from ...core import exceptions
from ...core.memory_map import FlashRegion
from ...core.target import Target
from ...coresight.coresight_target import CoreSightTarget
from ...flash.eraser import FlashEraser
from ...flash.file_programmer import FileProgrammer
from ...utility.timeout import Timeout
from ...utility.progress import print_progress
from ...commands.base import CommandBase
from ...commands.execution_context import CommandSet

from typing import (Callable, Optional, TYPE_CHECKING, Union)
ProgressCallback = Callable[[Union[int, float]], None]

if TYPE_CHECKING:
    from ...core.session import Session

AHB_AP_NUM = 0x0
APB_AP_NUM = 0x3
CTRL_AP_NUM = 0x4

CTRL_AP_RESET = 0x000
CTRL_AP_ERASEALL = 0x004
CTRL_AP_ERASEALLSTATUS = 0x008
CTRL_AP_APPROTECTSTATUS = 0x00C
CTRL_AP_ERASEPROTECTSTATUS = 0x018
CTRL_AP_ERASEPROTECTDISABLE = 0x01C
CTRL_AP_MAILBOX_TXDATA = 0x020
CTRL_AP_MAILBOX_TXSTATUS = 0x024
CTRL_AP_MAILBOX_RXDATA = 0x028
CTRL_AP_MAILBOX_RXSTATUS = 0x02C
CTRL_AP_IDR = 0x0FC

CTRL_AP_ERASEALLSTATUS_READY = 0x0
CTRL_AP_ERASEALLSTATUS_BUSY = 0x1

CTRL_AP_APPROTECTSTATUS_APPROTECT_MSK = 0x1
CTRL_AP_APPROTECTSTATUS_SECUREAPPROTECT_MSK = 0x2
CTRL_AP_ERASEPROTECTSTATUS_MSK = 0x1

CTRL_AP_MAILBOX_STATUS_NODATAPENDING = 0x0
CTRL_AP_MAILBOX_STATUS_DATAPENDING = 0x1

CTRL_AP_RESET_NORESET = 0x0
CTRL_AP_RESET_RESET = 0x1

CTRL_AP_ERASEALL_NOOPERATION = 0x0
CTRL_AP_ERASEALL_ERASE = 0x1

CTRL_IDR_EXPECTED = 0x12880000

MASS_ERASE_TIMEOUT = 30.0

FAULT_EVENT = 0x4002A100
COMMAND_EVENT = 0x4002A108
DATA_EVENT = 0x4002A110
IPC_PIPELINED_MAX_BUFFER_SIZE = 0xE000
IPC_MAX_BUFFER_SIZE = 0x10000

CSW_DEVICEEN =  0x00000040

# just an empty program compiled with the Nordic MDK without ENABLE_APPROTECT set
nrf91_empty_image = [
    0x00, 0xe0, 0x03, 0x20, 0xe1, 0x04, 0x00, 0x00, 0x09, 0x05, 0x00, 0x00, 0x0b, 0x05, 0x00, 0x00, \
    0x0d, 0x05, 0x00, 0x00, 0x0f, 0x05, 0x00, 0x00, 0x11, 0x05, 0x00, 0x00, 0x13, 0x05, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x15, 0x05, 0x00, 0x00, \
    0x17, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x19, 0x05, 0x00, 0x00, 0x1b, 0x05, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1d, 0x05, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x1d, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x1d, 0x05, 0x00, 0x00, 0x1d, 0x05, 0x00, 0x00, 0x1d, 0x05, 0x00, 0x00, 0x1d, 0x05, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x1d, 0x05, 0x00, 0x00, 0x1d, 0x05, 0x00, 0x00, 0x1d, 0x05, 0x00, 0x00, \
    0x1d, 0x05, 0x00, 0x00, 0x1d, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x1d, 0x05, 0x00, 0x00, 0x1d, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x1d, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1d, 0x05, 0x00, 0x00, \
    0x1d, 0x05, 0x00, 0x00, 0x1d, 0x05, 0x00, 0x00, 0x1d, 0x05, 0x00, 0x00, 0x1d, 0x05, 0x00, 0x00, \
    0x1d, 0x05, 0x00, 0x00, 0x1d, 0x05, 0x00, 0x00, 0x1d, 0x05, 0x00, 0x00, 0x1d, 0x05, 0x00, 0x00, \
    0x1d, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1d, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x1d, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1d, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x1d, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x1d, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x1d, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x1d, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x10, 0xb5, 0x05, 0x4c, 0x23, 0x78, 0x33, 0xb9, 0x04, 0x4b, 0x13, 0xb1, \
    0x04, 0x48, 0x00, 0xe0, 0x00, 0xbf, 0x01, 0x23, 0x23, 0x70, 0x10, 0xbd, 0x3c, 0x04, 0x00, 0x20, \
    0x00, 0x00, 0x00, 0x00, 0x44, 0x07, 0x00, 0x00, 0x08, 0xb5, 0x03, 0x4b, 0x1b, 0xb1, 0x03, 0x49, \
    0x03, 0x48, 0x00, 0xe0, 0x00, 0xbf, 0x08, 0xbd, 0x00, 0x00, 0x00, 0x00, 0x40, 0x04, 0x00, 0x20, \
    0x44, 0x07, 0x00, 0x00, 0xa3, 0xf5, 0x80, 0x3a, 0x70, 0x47, 0x00, 0xbf, 0x17, 0x4b, 0x00, 0x2b, \
    0x08, 0xbf, 0x13, 0x4b, 0x9d, 0x46, 0xff, 0xf7, 0xf5, 0xff, 0x00, 0x21, 0x8b, 0x46, 0x0f, 0x46, \
    0x13, 0x48, 0x14, 0x4a, 0x12, 0x1a, 0x00, 0xf0, 0x5f, 0xf8, 0x0e, 0x4b, 0x00, 0x2b, 0x00, 0xd0, \
    0x98, 0x47, 0x0d, 0x4b, 0x00, 0x2b, 0x00, 0xd0, 0x98, 0x47, 0x00, 0x20, 0x00, 0x21, 0x04, 0x00, \
    0x0d, 0x00, 0x0d, 0x48, 0x00, 0x28, 0x02, 0xd0, 0x0c, 0x48, 0x00, 0xf0, 0x0d, 0xf9, 0x00, 0xf0, \
    0x27, 0xf8, 0x20, 0x00, 0x29, 0x00, 0x00, 0xf0, 0x71, 0xf9, 0x00, 0xf0, 0x11, 0xf8, 0x00, 0xbf, \
    0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x03, 0x20, \
    0x3c, 0x04, 0x00, 0x20, 0x5c, 0x04, 0x00, 0x20, 0xf9, 0x03, 0x00, 0x00, 0x05, 0x04, 0x00, 0x00, \
    0x08, 0xb5, 0x00, 0x21, 0x04, 0x46, 0x00, 0xf0, 0x8b, 0xf8, 0x04, 0x4b, 0x18, 0x68, 0xc3, 0x6b, \
    0x03, 0xb1, 0x98, 0x47, 0x20, 0x46, 0x00, 0xf0, 0x4f, 0xf9, 0x00, 0xbf, 0x40, 0x07, 0x00, 0x00, \
    0x70, 0xb5, 0x0d, 0x4e, 0x0d, 0x4d, 0x76, 0x1b, 0xb6, 0x10, 0x06, 0xd0, 0x00, 0x24, 0x01, 0x34, \
    0x55, 0xf8, 0x04, 0x3b, 0x98, 0x47, 0xa6, 0x42, 0xf9, 0xd1, 0x09, 0x4e, 0x00, 0xf0, 0x6c, 0xfa, \
    0x08, 0x4d, 0x76, 0x1b, 0xb6, 0x10, 0x06, 0xd0, 0x00, 0x24, 0x01, 0x34, 0x55, 0xf8, 0x04, 0x3b, \
    0x98, 0x47, 0xa6, 0x42, 0xf9, 0xd1, 0x70, 0xbd, 0x30, 0x04, 0x00, 0x20, 0x30, 0x04, 0x00, 0x20, \
    0x38, 0x04, 0x00, 0x20, 0x30, 0x04, 0x00, 0x20, 0x70, 0xb5, 0x86, 0x07, 0x48, 0xd0, 0x54, 0x1e, \
    0x00, 0x2a, 0x3f, 0xd0, 0xca, 0xb2, 0x03, 0x46, 0x01, 0xe0, 0x01, 0x3c, 0x3a, 0xd3, 0x03, 0xf8, \
    0x01, 0x2b, 0x9d, 0x07, 0xf9, 0xd1, 0x03, 0x2c, 0x2d, 0xd9, 0xcd, 0xb2, 0x0f, 0x2c, 0x45, 0xea, \
    0x05, 0x25, 0x45, 0xea, 0x05, 0x45, 0x36, 0xd9, 0xa4, 0xf1, 0x10, 0x0c, 0x03, 0xf1, 0x20, 0x0e, \
    0x03, 0xf1, 0x10, 0x02, 0x2c, 0xf0, 0x0f, 0x06, 0x4f, 0xea, 0x1c, 0x1c, 0xb6, 0x44, 0x42, 0xe9, \
    0x04, 0x55, 0x42, 0xe9, 0x02, 0x55, 0x10, 0x32, 0x72, 0x45, 0xf8, 0xd1, 0x0c, 0xf1, 0x01, 0x02, \
    0x14, 0xf0, 0x0c, 0x0f, 0x04, 0xf0, 0x0f, 0x0c, 0x03, 0xeb, 0x02, 0x12, 0x13, 0xd0, 0xac, 0xf1, \
    0x04, 0x03, 0x23, 0xf0, 0x03, 0x03, 0x04, 0x33, 0x13, 0x44, 0x42, 0xf8, 0x04, 0x5b, 0x93, 0x42, \
    0xfb, 0xd1, 0x0c, 0xf0, 0x03, 0x04, 0x2c, 0xb1, 0xca, 0xb2, 0x1c, 0x44, 0x03, 0xf8, 0x01, 0x2b, \
    0x9c, 0x42, 0xfb, 0xd1, 0x70, 0xbd, 0x64, 0x46, 0x13, 0x46, 0x00, 0x2c, 0xf4, 0xd1, 0xf9, 0xe7, \
    0x03, 0x46, 0x14, 0x46, 0xbf, 0xe7, 0x1a, 0x46, 0xa4, 0x46, 0xe0, 0xe7, 0x02, 0x4b, 0x13, 0xb1, \
    0x02, 0x48, 0x00, 0xf0, 0x69, 0xb8, 0x70, 0x47, 0x00, 0x00, 0x00, 0x00, 0x05, 0x04, 0x00, 0x00, \
    0x2d, 0xe9, 0xf8, 0x4f, 0x2e, 0x4b, 0x83, 0x46, 0x0f, 0x46, 0x18, 0x68, 0x2d, 0xed, 0x02, 0x8b, \
    0x00, 0xf0, 0x76, 0xf8, 0x2b, 0x4b, 0xd3, 0xf8, 0x00, 0x80, 0xd8, 0xf8, 0x48, 0x61, 0xa6, 0xb1, \
    0x08, 0xee, 0x10, 0xba, 0x4f, 0xf0, 0x01, 0x09, 0x4f, 0xf0, 0x00, 0x0a, 0x74, 0x68, 0x65, 0x1e, \
    0x0b, 0xd4, 0x01, 0x34, 0x06, 0xeb, 0x84, 0x04, 0x7f, 0xb1, 0xd4, 0xf8, 0x00, 0x31, 0xbb, 0x42, \
    0x0b, 0xd0, 0x01, 0x3d, 0x04, 0x3c, 0x6b, 0x1c, 0xf6, 0xd1, 0x1d, 0x4b, 0xbd, 0xec, 0x02, 0x8b, \
    0x18, 0x68, 0xbd, 0xe8, 0xf8, 0x4f, 0x00, 0xf0, 0x55, 0xb8, 0x73, 0x68, 0x22, 0x68, 0x01, 0x3b, \
    0xab, 0x42, 0x0c, 0xbf, 0x75, 0x60, 0xc4, 0xf8, 0x00, 0xa0, 0x00, 0x2a, 0xe9, 0xd0, 0x09, 0xfa, \
    0x05, 0xf1, 0xd6, 0xf8, 0x88, 0x01, 0xd6, 0xf8, 0x04, 0xb0, 0x01, 0x42, 0x0b, 0xd1, 0x90, 0x47, \
    0x72, 0x68, 0x5a, 0x45, 0x13, 0xd1, 0xd8, 0xf8, 0x48, 0x31, 0xb3, 0x42, 0xd9, 0xd0, 0x1e, 0x46, \
    0x00, 0x2e, 0xcb, 0xd1, 0xd9, 0xe7, 0xd6, 0xf8, 0x8c, 0x01, 0x01, 0x42, 0x0c, 0xd1, 0xd4, 0xf8, \
    0x80, 0x10, 0x18, 0xee, 0x10, 0x0a, 0x90, 0x47, 0x72, 0x68, 0x5a, 0x45, 0xeb, 0xd0, 0xd8, 0xf8, \
    0x48, 0x61, 0x00, 0x2e, 0xba, 0xd1, 0xc8, 0xe7, 0xd4, 0xf8, 0x80, 0x00, 0x90, 0x47, 0xdf, 0xe7, \
    0x28, 0x04, 0x00, 0x20, 0x40, 0x07, 0x00, 0x00, 0x00, 0x23, 0x01, 0x46, 0x1a, 0x46, 0x18, 0x46, \
    0x00, 0xf0, 0x1a, 0xb8, 0x38, 0xb5, 0x08, 0x4b, 0x08, 0x4d, 0x5b, 0x1b, 0x9c, 0x10, 0x07, 0xd0, \
    0x04, 0x3b, 0x1d, 0x44, 0x01, 0x3c, 0x55, 0xf8, 0x04, 0x39, 0x98, 0x47, 0x00, 0x2c, 0xf9, 0xd1, \
    0xbd, 0xe8, 0x38, 0x40, 0x00, 0xf0, 0x86, 0xb9, 0x3c, 0x04, 0x00, 0x20, 0x38, 0x04, 0x00, 0x20, \
    0x70, 0x47, 0x00, 0xbf, 0x70, 0x47, 0x00, 0xbf, 0x2d, 0xe9, 0xf0, 0x47, 0xdf, 0xf8, 0x84, 0xa0, \
    0x06, 0x46, 0x98, 0x46, 0x0f, 0x46, 0xda, 0xf8, 0x00, 0x00, 0x91, 0x46, 0xff, 0xf7, 0xf0, 0xff, \
    0x1b, 0x4b, 0x1b, 0x68, 0xd3, 0xf8, 0x48, 0x41, 0x34, 0xb3, 0x65, 0x68, 0x1f, 0x2d, 0x28, 0xdc, \
    0x5e, 0xb9, 0x6b, 0x1c, 0x02, 0x35, 0xda, 0xf8, 0x00, 0x00, 0x63, 0x60, 0x44, 0xf8, 0x25, 0x70, \
    0xff, 0xf7, 0xe0, 0xff, 0x00, 0x20, 0xbd, 0xe8, 0xf0, 0x87, 0x04, 0xeb, 0x85, 0x01, 0x01, 0x23, \
    0x02, 0x2e, 0xc1, 0xf8, 0x88, 0x90, 0x03, 0xfa, 0x05, 0xf3, 0xd4, 0xf8, 0x88, 0x21, 0x42, 0xea, \
    0x03, 0x02, 0xc4, 0xf8, 0x88, 0x21, 0xc1, 0xf8, 0x08, 0x81, 0xe2, 0xd1, 0xd4, 0xf8, 0x8c, 0x21, \
    0x13, 0x43, 0xc4, 0xf8, 0x8c, 0x31, 0xdc, 0xe7, 0x03, 0xf5, 0xa6, 0x74, 0xc3, 0xf8, 0x48, 0x41, \
    0xd3, 0xe7, 0xda, 0xf8, 0x00, 0x00, 0xff, 0xf7, 0xbd, 0xff, 0x4f, 0xf0, 0xff, 0x30, 0xda, 0xe7, \
    0x40, 0x07, 0x00, 0x00, 0x28, 0x04, 0x00, 0x20, 0xfe, 0xe7, 0x00, 0xbf, 0x5a, 0x22, 0x03, 0x4b, \
    0xc3, 0xf8, 0x10, 0x2e, 0xc3, 0xf8, 0x00, 0x2e, 0xfe, 0xe7, 0x00, 0xbf, 0x00, 0x90, 0x03, 0x50, \
    0x06, 0x49, 0x07, 0x4a, 0x07, 0x4b, 0x9b, 0x1a, 0x03, 0xdd, 0x04, 0x3b, 0xc8, 0x58, 0xd0, 0x50, \
    0xfb, 0xdc, 0x00, 0xf0, 0x15, 0xf8, 0xff, 0xf7, 0x51, 0xfe, 0x00, 0x00, 0x68, 0x07, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x20, 0x3c, 0x04, 0x00, 0x20, 0xfe, 0xe7, 0xfe, 0xe7, 0xfe, 0xe7, 0xfe, 0xe7, \
    0xfe, 0xe7, 0xfe, 0xe7, 0xfe, 0xe7, 0xfe, 0xe7, 0xfe, 0xe7, 0xfe, 0xe7, 0xfe, 0xe7, 0x00, 0xbf, \
    0x4f, 0xf4, 0x7f, 0x03, 0xd3, 0xf8, 0x30, 0x21, 0xd3, 0xf8, 0x34, 0x31, 0xbf, 0xf3, 0x4f, 0x8f, \
    0x09, 0x2a, 0x06, 0xd1, 0x4f, 0xf0, 0x50, 0x23, 0x00, 0x22, 0xc3, 0xf8, 0x14, 0x21, 0xc3, 0xf8, \
    0x18, 0x21, 0x4f, 0xf4, 0x7f, 0x03, 0xd3, 0xf8, 0x30, 0x21, 0xd3, 0xf8, 0x34, 0x31, 0xbf, 0xf3, \
    0x4f, 0x8f, 0x09, 0x2a, 0x7e, 0xd0, 0x4f, 0xf4, 0x7f, 0x03, 0xd3, 0xf8, 0x30, 0x21, 0xd3, 0xf8, \
    0x34, 0x31, 0xbf, 0xf3, 0x4f, 0x8f, 0x09, 0x2a, 0x6d, 0xd0, 0x4f, 0xf4, 0x7f, 0x03, 0xd3, 0xf8, \
    0x30, 0x21, 0xd3, 0xf8, 0x34, 0x31, 0xbf, 0xf3, 0x4f, 0x8f, 0x09, 0x2a, 0x5c, 0xd0, 0x4f, 0xf4, \
    0x7f, 0x03, 0xd3, 0xf8, 0x30, 0x21, 0xd3, 0xf8, 0x34, 0x31, 0xbf, 0xf3, 0x4f, 0x8f, 0x09, 0x2a, \
    0x06, 0xd1, 0x00, 0x21, 0x01, 0x22, 0x58, 0x4b, 0xc3, 0xf8, 0x0c, 0x17, 0xc3, 0xf8, 0x10, 0x27, \
    0x56, 0x4b, 0x57, 0x48, 0x19, 0x46, 0x03, 0xf1, 0xf8, 0x52, 0x09, 0x68, 0x04, 0x3b, 0x02, 0xf5, \
    0x9c, 0x22, 0x83, 0x42, 0x11, 0x60, 0xf5, 0xd1, 0xbf, 0xf3, 0x4f, 0x8f, 0x51, 0x48, 0x00, 0x22, \
    0xd0, 0xf8, 0x7c, 0x37, 0x50, 0x49, 0x23, 0xf0, 0x10, 0x03, 0xc0, 0xf8, 0x7c, 0x37, 0x07, 0xe0, \
    0xd3, 0xf8, 0x00, 0x03, 0xd3, 0xf8, 0x04, 0x33, 0xb2, 0xf5, 0x80, 0x7f, 0x03, 0x60, 0x0b, 0xd0, \
    0x08, 0x68, 0xbf, 0xf3, 0x4f, 0x8f, 0xd3, 0x00, 0x01, 0x30, 0x03, 0xf5, 0x7f, 0x03, 0x02, 0xf1, \
    0x01, 0x02, 0x01, 0xf1, 0x08, 0x01, 0xeb, 0xd1, 0x44, 0x4b, 0xda, 0x69, 0xbf, 0xf3, 0x4f, 0x8f, \
    0xd1, 0x07, 0x30, 0xd4, 0x1b, 0x6a, 0xbf, 0xf3, 0x4f, 0x8f, 0x01, 0x33, 0x2b, 0xd0, 0x40, 0x4b, \
    0xd3, 0xf8, 0x8c, 0x20, 0x42, 0xf4, 0x40, 0x62, 0xc3, 0xf8, 0x8c, 0x20, 0xd3, 0xf8, 0x88, 0x20, \
    0x42, 0xf4, 0x70, 0x02, 0xc3, 0xf8, 0x88, 0x20, 0xbf, 0xf3, 0x4f, 0x8f, 0xbf, 0xf3, 0x6f, 0x8f, \
    0x38, 0x4b, 0x39, 0x4a, 0x1a, 0x60, 0x70, 0x47, 0x01, 0x2b, 0xa0, 0xd1, 0x0e, 0x22, 0x37, 0x4b, \
    0xc3, 0xf8, 0xe4, 0x2e, 0x9b, 0xe7, 0x01, 0x2b, 0x8f, 0xd0, 0x01, 0x22, 0x2a, 0x4b, 0xc3, 0xf8, \
    0x78, 0x25, 0x8a, 0xe7, 0x01, 0x2b, 0x7f, 0xf4, 0x7e, 0xaf, 0x27, 0x4a, 0xc2, 0xf8, 0x38, 0x3a, \
    0xc2, 0xf8, 0x78, 0x35, 0x77, 0xe7, 0xbf, 0xf3, 0x4f, 0x8f, 0x2d, 0x4a, 0xd2, 0xf8, 0x00, 0x34, \
    0x01, 0x2b, 0xfb, 0xd1, 0x2a, 0x49, 0xc2, 0xf8, 0x04, 0x35, 0xd1, 0xf8, 0x00, 0x34, 0x01, 0x2b, \
    0xfb, 0xd1, 0x22, 0x4b, 0xda, 0x69, 0xbf, 0xf3, 0x4f, 0x8f, 0xd2, 0x07, 0x0a, 0xd5, 0xda, 0x69, \
    0x22, 0xf0, 0x01, 0x02, 0xda, 0x61, 0xbf, 0xf3, 0x4f, 0x8f, 0x21, 0x4a, 0xd2, 0xf8, 0x00, 0x34, \
    0x01, 0x2b, 0xfb, 0xd1, 0x19, 0x4b, 0x1a, 0x6a, 0xbf, 0xf3, 0x4f, 0x8f, 0x01, 0x32, 0x14, 0xd0, \
    0x00, 0x23, 0x1b, 0x4a, 0xc2, 0xf8, 0x04, 0x35, 0xd2, 0xf8, 0x00, 0x34, 0x01, 0x2b, 0xfb, 0xd1, \
    0xbf, 0xf3, 0x4f, 0x8f, 0x12, 0x49, 0x17, 0x4b, 0xca, 0x68, 0x02, 0xf4, 0xe0, 0x62, 0x13, 0x43, \
    0xcb, 0x60, 0xbf, 0xf3, 0x4f, 0x8f, 0x00, 0xbf, 0xfd, 0xe7, 0x1a, 0x6a, 0x22, 0xf0, 0xff, 0x02, \
    0x42, 0xf0, 0x20, 0x02, 0x1a, 0x62, 0xbf, 0xf3, 0x4f, 0x8f, 0x0d, 0x4a, 0xd2, 0xf8, 0x00, 0x34, \
    0x01, 0x2b, 0xfb, 0xd1, 0xdc, 0xe7, 0x00, 0xbf, 0x00, 0x40, 0x00, 0x50, 0xfc, 0x0f, 0xff, 0x00, \
    0xfc, 0xff, 0xfe, 0x00, 0x00, 0x30, 0x00, 0x50, 0x00, 0x03, 0xff, 0x00, 0x00, 0x80, 0xff, 0x00, \
    0x00, 0xed, 0x00, 0xe0, 0x2c, 0x04, 0x00, 0x20, 0x00, 0x90, 0xd0, 0x03, 0x00, 0xa0, 0x03, 0x50, \
    0x00, 0x90, 0x03, 0x50, 0x04, 0x00, 0xfa, 0x05, 0xf8, 0xb5, 0x00, 0xbf, 0xf8, 0xbc, 0x08, 0xbc, \
    0x9e, 0x46, 0x70, 0x47, 0xf8, 0xb5, 0x00, 0xbf, 0xf8, 0xbc, 0x08, 0xbc, 0x9e, 0x46, 0x70, 0x47, \
    0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x34, 0xfa, 0xff, 0x7f, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xec, 0x02, 0x00, 0x20, \
    0x54, 0x03, 0x00, 0x20, 0xbc, 0x03, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x33, 0xcd, 0xab, 0x34, 0x12, 0x6d, 0xe6, \
    0xec, 0xde, 0x05, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
    0x58, 0x04, 0x00, 0x20, 0x00, 0x90, 0xd0, 0x03, 0x1d, 0x03, 0x00, 0x00, 0x79, 0x01, 0x00, 0x00, \
    0x55, 0x01, 0x00, 0x00
]

LOG = logging.getLogger(__name__)


def change_endianness(x: int, n=4) -> int:
    return sum(((x >> 8*i) & 0xFF) << 8*(n-i-1) for i in range(n))

def bytes_to_word(bts):
    result = 0
    for i, b in enumerate(bts):
        result |= b << (8*i)
    return result

def word_to_bytes(wrd):
    result = []
    for i in range(4):
        result.append((wrd >> (8*i)) & 0xFF)
    return bytes(result)

def split_addr_range_into_chunks(range, chunk_size):
    chunks = []
    addr = range[0]
    while True:
        c = (addr, min(range[1], addr + chunk_size))
        chunks.append(c)
        addr = c[1]
        if addr == range[1]:
            break
    return chunks

FLASH_ALGO_UICR = {
    'load_address' : 0x20000000,

    # Flash algorithm as a hex string
    'instructions': [
    0xe7fdbe00,
    0xf240b570, 0xf2c00604, 0x25000600, 0x0006eb09, 0x5006f849, 0x5501e9c0, 0xb2d060c5, 0xf0004614,
    0x2800f9c9, 0xeb09bf1e, 0xe9c10106, 0x46050402, 0xbd704628, 0x4604b510, 0xf0002000, 0xf240f9bb,
    0x28000104, 0x0100f2c0, 0xeb09bf1c, 0xe9c20201, 0xeb090402, 0x68920201, 0xbf082a00, 0xf244bd10,
    0xf2c20200, 0x23010200, 0xf8596013, 0x44493001, 0x684b6053, 0x688b6093, 0x68c960d3, 0xbd106111,
    0xf240b580, 0xf2c00004, 0x21010000, 0x1000f849, 0x21004448, 0x1101e9c0, 0xf00060c1, 0x2000f9ad,
    0xbf00bd80, 0xf240b510, 0xf2c00004, 0x21020000, 0x1000f849, 0x24004448, 0x4401e9c0, 0xf00060c4,
    0x4601f93b, 0x0000f248, 0x00fff2c0, 0xf00022ff, 0xb138f80f, 0xf9a6f000, 0xd0052869, 0x28004604,
    0x2400bf08, 0xbd104620, 0x46202400, 0xbf00bd10, 0xf240b570, 0xf2c00c04, 0x23050c00, 0x300cf849,
    0x030ceb09, 0x0e00f04f, 0xe9c30784, 0xf8c3ee01, 0xd006e00c, 0x010ceb09, 0xe9c12203, 0x20652002,
    0xeb09bd70, 0xf04f030c, 0x078c0e01, 0xe004f8c3, 0xeb09d006, 0x2203000c, 0x2102e9c0, 0xbd702065,
    0x7efff648, 0x0efff2c0, 0x030ceb09, 0x45702402, 0xd906605c, 0x010ceb09, 0xe9c12204, 0x20662002,
    0x180bbd70, 0x0501f10e, 0x040ceb09, 0x42ab2603, 0xd9066066, 0x000ceb09, 0xe9c02104, 0x20661302,
    0x2900bd70, 0x2000bf04, 0xbf00bd70, 0x42937803, 0x3001d105, 0xf04f3901, 0xd1f70300, 0xeb09e005,
    0x2205010c, 0xe9c12301, 0x46182002, 0xbf00bd70, 0xf240b570, 0xf2c00304, 0xf04f0300, 0xeb090c03,
    0x24000503, 0xf849078e, 0xe9c5c003, 0x60ec4401, 0xeb09d005, 0xe9c00003, 0x2065c102, 0xf648bd70,
    0xf2c076ff, 0xeb0906ff, 0x24020503, 0x606c42b0, 0xeb09d906, 0x22040103, 0x2002e9c1, 0xbd702066,
    0x3601180d, 0x0403eb09, 0x0c03f04f, 0xf8c442b5, 0xd906c004, 0x0003eb09, 0xe9c02104, 0x20661502,
    0x2300bd70, 0x0f91ebb3, 0x088cd00b, 0x1f161f05, 0x0f04f856, 0x0f04f845, 0xf8d6f000, 0xd1f73c01,
    0x46182300, 0xbf00bd70, 0xf240b570, 0xf2c00c04, 0x23040c00, 0x300cf849, 0x030ceb09, 0x0e00f04f,
    0xe9c30784, 0xf8c3ee01, 0xd006e00c, 0x010ceb09, 0xe9c12203, 0x20652002, 0xeb09bd70, 0xf04f030c,
    0x078c0e01, 0xe004f8c3, 0xeb09d006, 0x2203000c, 0x2102e9c0, 0xbd702065, 0x7efff648, 0x0efff2c0,
    0x030ceb09, 0x45702402, 0xd906605c, 0x010ceb09, 0xe9c12204, 0x20662002, 0x180bbd70, 0x0501f10e,
    0x040ceb09, 0x42ab2603, 0xd9066066, 0x000ceb09, 0xe9c02104, 0x20661302, 0x2500bd70, 0x0f91ebb5,
    0x060ceb09, 0x0504f04f, 0xd0116075, 0xbf000889, 0x68156806, 0xd10542ae, 0x39013004, 0x0204f102,
    0xe005d1f6, 0x010ceb09, 0x46032206, 0x2002e9c1, 0xbd704618, 0x1030f240, 0x00fff2c0, 0x31016801,
    0x6800bf1c, 0xf6404770, 0xf2cf71e0, 0x78080100, 0xf3616849, 0x4770200b, 0x2020f240, 0x00fff2c0,
    0x31016801, 0x6800bf14, 0x5080f44f, 0xbf004770, 0x2024f240, 0x00fff2c0, 0x31016801, 0x6800bf14,
    0x7000f44f, 0xbf004770, 0x47702000, 0x47702000, 0xf7ffb510, 0x4604ffe1, 0xffeaf7ff, 0xf004fb00,
    0xbf00bd10, 0x42814401, 0x2001bf9c, 0xbf004770, 0x2b04f850, 0xbf1c3201, 0x47702000, 0xbf244288,
    0x47702001, 0xbf00e7f4, 0xbf004770, 0x47702000, 0x47702003, 0xbf842803, 0x47702069, 0xb240b580,
    0xf851a105, 0xf2490020, 0xf2c55104, 0x60080103, 0xf80af000, 0xbd802000, 0x00000000, 0x00000002,
    0x00000001, 0x00000000, 0x4000f249, 0x0003f2c5, 0x29006801, 0x4770d0fc, 0xf249b580, 0xf2c5500c,
    0x21010003, 0xf7ff6001, 0xbd80ffef, 0xb082b580, 0x98019001, 0x31fff04f, 0xf7ff6001, 0xb002ffe5,
    0xbf00bd80, 0x47702069, 0xf7ffb5b0, 0xb148ffa1, 0x25004604, 0xf7ff4628, 0xf7ffffe9, 0x4405ff7d,
    0xd3f742a5, 0xbdb02000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000
    ],

    # Relative function addresses
    'pc_init': 0x20000005,
    'pc_unInit': 0x20000039,
    'pc_program_page': 0x200001b5,
    'pc_erase_sector': 0x200000a9,
    'pc_eraseAll': 0x20000085,

    'static_base' : 0x20000000 + 0x00000004 + 0x00000448,
    'begin_stack' : 0x20003460,
    'end_stack' : 0x20002460,
    'begin_data' : 0x20000000 + 0x1000,
    'page_size' : 0x1000,
    'analyzer_supported' : False,
    'analyzer_address' : 0x00000000,
    # Enable double buffering
    'page_buffers' : [
        0x20000460,
        0x20001460
    ],
    'min_program_length' : 0x1000,

    # Relative region addresses and sizes
    'ro_start': 0x4,
    'ro_size': 0x448,
    'rw_start': 0x44c,
    'rw_size': 0x4,
    'zi_start': 0x450,
    'zi_size': 0x10,

    # Flash information
    'flash_start': 0xff8000,
    'flash_size': 0x1000,
    'sector_sizes': (
        (0x0, 0x1000),
    )
}

class nRF91ModemFirmwareUpdateCommand(CommandBase):
    INFO = {
            'names': ['nrf91-update-modem-fw'],
            'group': 'nrf91',
            'category': 'nrf91',
            'nargs': '*',
            'usage': "[-f] mfw_nrf91xx_x.x.x.zip",
            'help': "Update modem firmware for an nRF91 target.",
            'extra_help':
                "If -f is specified, modem firmware is written to the device, "
                "even if the correct version is already present."
            }
    
    file_path = ""
    needs_update = False

    def parse(self, args):
        if len(args) == 0 or not args[-1].endswith(".zip"):
            raise exceptions.CommandError(f"invalid argument")
        self.file_path = args[-1]
        for a in args:
            if a == '-f':
                self.needs_update = True


    def execute(self):
        if not self.needs_update:
            try:
                ModemUpdater(self.context.session).verify(self.file_path)
            except:
                self.needs_update = True
        if self.needs_update:
            ModemUpdater(self.context.session).program_and_verify(self.file_path)

class NRF91(CoreSightTarget):

    VENDOR = "Nordic Semiconductor"

    def __init__(self, session, memory_map=None):
        super(NRF91, self).__init__(session, memory_map)
        if memory_map.get_region_for_address(0x00ff8000) is None:
            LOG.debug("Adding UICR region")
            memory_map.add_region(
                FlashRegion(
                    start=0x00ff8000,
                    length=0x1000,
                    blocksize=0x1000,
                    is_testable=False,
                    is_erasable=False,
                    algo=FLASH_ALGO_UICR,
                )
            )
        self.ctrl_ap = None
        self.was_locked = False

    def create_init_sequence(self):
        seq = super(NRF91, self).create_init_sequence()

        # Must check whether security is enabled, and potentially auto-unlock, before
        # any init tasks that require system bus access.
        seq.wrap_task('discovery',
            lambda seq: seq.insert_before('find_components',
                              ('check_ctrl_ap_idr', self.check_ctrl_ap_idr),
                              ('check_flash_security', self.check_flash_security),
                          )
            )
        seq.wrap_task('discovery',
            lambda seq: seq.insert_after('create_cores',
                              ('persist_unlock', self.persist_unlock),
                          )
            )
        seq.insert_before('post_connect_hook',
                          ('check_part_info', self.check_part_info))

        return seq

    def check_ctrl_ap_idr(self):
        self.ctrl_ap = self.dp.aps[CTRL_AP_NUM]

        # Check CTRL-AP ID.
        if self.ctrl_ap.idr != CTRL_IDR_EXPECTED:
            LOG.error("%s: bad CTRL-AP IDR (is 0x%08x)", self.part_number, self.ctrl_ap.idr)

    def ap_is_enabled(self):
        csw = self.dp.read_ap(AHB_AP_NUM << 24)
        return csw & CSW_DEVICEEN
    
    def persist_unlock(self):
        if self.session.options.get('auto_unlock') and self.has_hardened_approtect:
            # Write Unprotected to UICR.APPROTECT
            self.write_uicr(0x00FF8000, 0x50FA50FA)

            # Write Unprotected to UICR.SECUREAPPROTECT
            self.write_uicr(0x00FF802C, 0x50FA50FA)

        if self.session.options.get('auto_unlock') and self.has_hardened_approtect and self.was_locked:
            # write unlock image
            self.write_flash(0, nrf91_empty_image)

            self.reset()

    def check_flash_security(self):
        """@brief Check security and unlock device.

        This init task determines whether the device is locked (APPROTECT enabled). If it is,
        and if auto unlock is enabled, then perform a mass erase to unlock the device.

        This init task runs *before* cores are created.
        """

        target_id = self.dp.read_dp(0x24)
        if target_id & 0xFFF != 0x289:
            LOG.error(f"This doesn't look like a Nordic Semiconductor device!")
        if target_id & 0xF0000 != 0x90000:
            LOG.error(f"This doesn't look like an nRF91 devcice!")
        revision = target_id >> 28
        self.has_hardened_approtect = revision > 2

        if self.is_locked():
            self.was_locked = True
            if self.session.options.get('auto_unlock'):
                LOG.warning("%s APPROTECT enabled: will try to unlock via mass erase", self.part_number)

                unlock_successful = False
                for _ in range(3):
                    # Do the mass erase.
                    if not self.mass_erase():
                        continue

                    if not self.has_hardened_approtect:
                        # pin reset is needed for older versions
                        self.session.probe.reset()
                        self.pre_connect()
                        self.dp.connect()

                    # Check if AP was enabled
                    if self.ap_is_enabled():
                        unlock_successful = True
                        break
                    else:
                        LOG.debug("unlock was not successful, retrying")

                if not unlock_successful:
                    raise exceptions.TargetError("unable to unlock device")
                self._discoverer._create_1_ap(AHB_AP_NUM)
                self._discoverer._create_1_ap(APB_AP_NUM)
            else:
                LOG.warning("%s APPROTECT enabled: not automatically unlocking", self.part_number)
        else:
            LOG.info("%s not in secure state", self.part_number)

    def is_locked(self):
        status = self.ctrl_ap.read_reg(CTRL_AP_APPROTECTSTATUS)
        return (status & CTRL_AP_APPROTECTSTATUS_APPROTECT_MSK == 0) \
            or (status & CTRL_AP_APPROTECTSTATUS_SECUREAPPROTECT_MSK == 0)

    def is_eraseprotected(self):
        status = self.ctrl_ap.read_reg(CTRL_AP_ERASEPROTECTSTATUS)
        return status & CTRL_AP_ERASEPROTECTSTATUS_MSK == 0

    def mass_erase(self):
        if self.is_eraseprotected():
            LOG.warning("ERASEPROTECT is enabled.")
            if self.is_locked():
                LOG.error("If the firmware supports unlocking with a known 32-bit key,")
                LOG.error("then this is the only way to recover the device.")
                return False
            else:
                LOG.warning("Performing a chip erase instead.")
                eraser = FlashEraser(self.session, FlashEraser.Mode.CHIP)
                eraser._log_chip_erase = False
                eraser.erase()
                return True

        # See Nordic Whitepaper nWP-027 for magic numbers and order of operations from the vendor
        self.ctrl_ap.write_reg(CTRL_AP_ERASEALL, CTRL_AP_ERASEALL_ERASE)
        with Timeout(MASS_ERASE_TIMEOUT) as to:
            while to.check():
                status = self.ctrl_ap.read_reg(CTRL_AP_ERASEALLSTATUS)
                if status == CTRL_AP_ERASEALLSTATUS_READY:
                    break
                sleep(0.5)
            else:
                # Timed out
                LOG.error("Mass erase timeout waiting for ERASEALLSTATUS")
                return False
        sleep(0.01)
        self.ctrl_ap.write_reg(CTRL_AP_RESET, CTRL_AP_RESET_RESET)
        self.ctrl_ap.write_reg(CTRL_AP_RESET, CTRL_AP_RESET_NORESET)
        sleep(0.2)
        return True

    def check_part_info(self):
        partno = self.read32(0x00FF0140)
        hwrevision = self.read32(0x00FF0144)
        variant = self.read32(0x00FF0148)

        LOG.info(f"This appears to be an nRF{partno:X} " +
                 f"{word_to_bytes(variant).decode('ASCII', errors='ignore')} " +
         	 f"{word_to_bytes(hwrevision).decode('ASCII', errors='ignore')}")

    def write_uicr(self, addr: int, value: int):
        current_value = self.read32(addr)
        if ((current_value & value) != value) and (current_value != 0xFFFFFFFF):
            raise exceptions.TargetError("cannot write UICR value, mass_erase needed")

        self.write32(0x50039504, 1)  # NVMC.CONFIG = WriteEnable
        self._wait_nvmc_ready()
        self.write32(addr, value)
        self._wait_nvmc_ready()
        self.write32(0x50039504, 0)  # NVMC.CONFIG = ReadOnly
        self._wait_nvmc_ready()

    def write_flash(self, addr: int, bytes):
        assert len(bytes) % 4 == 0, "only full words can be written"
        self.write32(0x50039504, 1)  # NVMC.CONFIG = WriteEnable
        self._wait_nvmc_ready()
        for off in range(0, len(bytes), 4):
            self.write32(addr+off, bytes_to_word(bytes[off:off+4]))
            self._wait_nvmc_readynext()
        self.write32(0x50039504, 0)  # NVMC.CONFIG = ReadOnly
        self._wait_nvmc_ready()

    def add_target_command_groups(self, command_set: CommandSet) -> None:
        command_set.add_command_group('nrf91')

    def _wait_nvmc_ready(self):
        with Timeout(MASS_ERASE_TIMEOUT) as to:
            while to.check():
                if self.read32(0x50039400) != 0x00000000:  # NVMC.READY != BUSY
                    break
            else:
                raise exceptions.TargetError("wait for NVMC timed out")
            
    def _wait_nvmc_readynext(self):
        with Timeout(MASS_ERASE_TIMEOUT) as to:
            while to.check():
                if self.read32(0x50039408) != 0x00000000:  # NVMC.READYNEXT != BUSY
                    break
            else:
                raise exceptions.TargetError("wait for NVMC timed out")

class ModemUpdater(object):
    """@brief Implements the nRF91 Modem Update procedure like described in nAN-41"""
    _target: "Target"
    _session: "Session"
    _progress: Optional[ProgressCallback]
    _total_data_size: int
    _progress_offset: float
    _current_progress_fraction: float
    _chunk_size: int
    _pipelined: bool
    _segments: list
    _firmware_update_digest: str

    def __init__(self,
                 session: "Session",
                 progress: Optional[ProgressCallback] = None,
                 ):
        self._session = session
        self._target = session.board.target
        self._total_data_size = 0
        self._pipelined = False
        self._segments = []
        self._firmware_update_digest = None

        if progress is not None:
            self._progress = progress
        elif session.options.get('hide_programming_progress'):
            self._progress = None
        else:
            self._progress = print_progress()

        self._reset_state()

    def program_and_verify(self, mfw_zip: str):
        """@brief Program and verify modem firmware from ZIP file."""
        self._setup_device()
        self._process_zip_file(mfw_zip)

        LOG.info("programming modem firmware..")
        self._total_data_size = sum(r[1]-r[0] for s in self._segments for r in s.segments())
        for s in self._segments:
            self._program_segment(s)
        self._progress(1.0)
        LOG.info("modem firmware programmed.")

        LOG.info("verifying modem firmware..")
        self._verify()
        LOG.info("modem firmware verified.")

    def verify(self, mfw_zip: str):
        """@brief Just verify modem firmware from ZIP file."""
        self._setup_device()
        self._process_zip_file(mfw_zip)

        LOG.info("verifying modem firmware..")
        self._verify()
        LOG.info("modem firmware verified.")

    def _setup_device(self):
        """@brief initialize device to use modem DFU"""
        # init UICR.HFXOSR if necessary
        if self._target.read32(0x00FF801C) == 0xFFFFFFFF:
            LOG.warning("UICR.HFXOSR is not set, setting it to 0x0E")
            self._target.write_uicr(addr=0x00FF801C, value=0x0000000E)

        # init UICR.HFXOCNT if necessary
        if self._target.read32(0x00FF8020) == 0xFFFFFFFF:
            LOG.warning("UICR.HFXOCNT is not set, setting it to 0x20")
            self._target.write_uicr(addr=0x00FF8020, value=0x00000020)

        self._target.reset_and_halt(reset_type=Target.ResetType.SW)

        # 1. configure IPC to be in non-secure mode
        self._target.write32(addr=0x500038A8, value=0x00000002)

        # 2. configure IPC HW for DFU
        self._target.write32(addr=0x4002A514, value=0x00000002)
        self._target.write32(addr=0x4002A51C, value=0x00000008)
        self._target.write32(addr=0x4002A610, value=0x21000000)
        self._target.write32(addr=0x4002A614, value=0x00000000)
        self._target.write32(addr=0x4002A590, value=0x00000001)
        self._target.write32(addr=0x4002A598, value=0x00000004)
        self._target.write32(addr=0x4002A5A0, value=0x00000010)

        # 3. configure RAM as non-secure
        for n in range(32):
            self._target.write32(addr=0x50003700+(n*4), value=0x00000007)

        # 4. allocate memory in RAM
        self._target.write32(addr=0x20000000, value=0x80010000)
        self._target.write32(addr=0x20000004, value=0x2100000C)
        self._target.write32(addr=0x20000008, value=0x0003FC00)

        # 5. reset the modem
        self._target.write32(addr=0x50005610, value=0)
        self._target.write32(addr=0x50005614, value=1)
        self._target.write32(addr=0x50005610, value=1)
        self._target.write32(addr=0x50005614, value=0)
        self._target.write32(addr=0x50005610, value=0)

    def _process_zip_file(self, mfw_zip: str):
        """@brief extract the mfw ZIP file and load DFU loader"""
        digest_id = self._read_key_digest()
        modem_firmware_loader = None

        with TemporaryDirectory() as tmpdir:
            with ZipFile(mfw_zip, 'r') as zip_ref:
                zip_ref.extractall(tmpdir)
            files = os.listdir(tmpdir)

            # find modem firmware loader
            for f in files:
                if f.startswith(f"{digest_id}.ipc_dfu.signed_") and f.endswith(".ihex"):
                    modem_firmware_loader = os.path.join(tmpdir, f)
                    m = re.match(r"\.ipc_dfu\.signed_(\d+)\.(\d+)\.(\d+)\.ihex", f[7:])
                    if m:
                        loader_version = tuple(int(x) for x in m.groups())
                        LOG.info("modem_firmware_loader version: {}.{}.{}".format(
                            *loader_version))
                        if loader_version > (1, 1, 2):
                            LOG.info("using pipelined method")
                            self._pipelined = True
                    break
            if not modem_firmware_loader:
                raise exceptions.TargetError(
                    f"No compatible loader {digest_id}.ipc_dfu.signed_x.x.x.ihex found.")

            # find modem firmware segments
            for f in files:
                m = re.match(r"firmware\.update\.image\.segments\.(\d+).hex", f)
                if m:
                    self._segments.append(
                        (m.group(1), os.path.join(tmpdir, f)))
            self._segments.sort()
            self._segments = [IntelHex(s[1]) for s in self._segments]

            if len(self._segments) == 0:
                raise exceptions.TargetError("No modem firmware segments found")

            # parse segment digests
            with open(os.path.join(tmpdir, "firmware.update.image.digest.txt"), "r") as f:
                for line in f:
                    m = re.match(r"SHA256 of all ranges in ascending address order:\s*(\w{64})",
                                 line)
                    if m:
                        self._firmware_update_digest = m.group(1)
            if not self._firmware_update_digest:
                raise exceptions.TargetError("no firmware digest found")

            LOG.info("loading modem firmware loader..")
            FileProgrammer(self._session).program(
                modem_firmware_loader, file_format='hex')
            self._target.write32(0x4002A004, 0x00000001)  # start IPC task
            self._wait_and_ack_events()
            LOG.info("modem_firmware_loader started.")

    def _read_key_digest(self) -> str:
        """@brief read first word of modem key digest for choosing a loader"""
        self._wait_and_ack_events()
        digest_data = change_endianness(self._target.read32(0x20000010))
        return (f"{digest_data:08X}")[:7]

    def _program_segment(self, segment: IntelHex):
        """@brief program contents of segment HEX file using DFU loader"""
        if self._pipelined:
            bufsz = IPC_PIPELINED_MAX_BUFFER_SIZE
        else:
            bufsz = IPC_MAX_BUFFER_SIZE

        chunks = []
        for s in segment.segments():
            chunks += split_addr_range_into_chunks(s, bufsz)

        if self._pipelined:
            self._write_chunk(segment, chunks[0], 0)

            for i, c in enumerate(chunks):
                self._commit_chunk(c, i % 2)

                # write next chunk while current one is processed
                if (i + 1) < len(chunks):
                    self._write_chunk(segment, chunks[i + 1], (i + 1) % 2)

                self._wait_and_ack_events()
        else:
            for i, c in enumerate(chunks):
                self._write_chunk(segment, c, 0)
                self._commit_chunk(c, 0)
                self._wait_and_ack_events()

    def _write_chunk(self, segment: IntelHex, chunk, bank):
        """@brief write a chunk of the current segment to RAM"""
        start = chunk[0]
        size = chunk[1]-chunk[0]
        if self._pipelined:
            ram_address = 0x2000001C + IPC_PIPELINED_MAX_BUFFER_SIZE * bank
        else:
            ram_address = 0x20000018

        data = list(segment.tobinarray(start=start, size=size))
        data_words = [bytes_to_word(data[i:i+4])
                      for i in range(0, len(data), 4)]
        self._target.write_memory_block32(ram_address, data_words)
        self._current_progress_fraction = size / float(self._total_data_size)
        self._progress_cb(1.0)
        self._progress_offset += self._current_progress_fraction

    def _commit_chunk(self, chunk, bank):
        """@brief signal DFU loader that chunk is ready to be programmed"""
        buffer_offset = bank * IPC_PIPELINED_MAX_BUFFER_SIZE
        self._target.write32(0x20000010, chunk[0])
        self._target.write32(0x20000014, chunk[1]-chunk[0])
        if self._pipelined:
            self._target.write32(0x20000018, buffer_offset)
        if self._pipelined:
            # command = PIPELINE_WRITE
            self._target.write32(0x2000000C, 0x9)
        else:
            # command = WRITE
            self._target.write32(0x2000000C, 0x3)
        # start IPC task
        self._target.write32(0x4002A004, 1)

    def _verify(self):
        """@brief verify programmed modem firmware"""
        ranges_to_verify = []
        for s in self._segments:
            for r in s.segments():
                if r[0] < 0x1000000:
                    ranges_to_verify.append(r)

        # write given start, size pairs and number of entries
        self._target.write32(0x20000010, len(ranges_to_verify))
        for i, (start, end) in enumerate(ranges_to_verify):
            self._target.write32(0x20000014 + (8 * i), start)
            self._target.write32(0x20000018 + (8 * i), end-start)

        # command = VERIFY
        self._target.write32(0x2000000C, 0x7)
        # start IPC task
        self._target.write32(0x4002A004, 1)

        self._wait_and_ack_events()

        response = self._target.read32(0x2000000C)
        if (response & 0xFF000000) == 0x5A000000:
            raise exceptions.TargetError(f"Error while verifying: {response & 0xFFFFFF:X}")

        digest_data = [self._target.read32(x) for x in range(0x20000010, 0x2000002D, 0x4)]
        digest_str = "".join(f"{x:08X}" for x in digest_data)

        if digest_str != self._firmware_update_digest:
            raise exceptions.TargetError(
                f"checksum mismatch: {digest_str} != {self._firmware_update_digest}"
            )

    def _wait_and_ack_events(self):
        """@brief wait for and acknowledge DFU events"""
        fault = False

        # poll for events
        with Timeout(MASS_ERASE_TIMEOUT) as to:
            while to.check():
                if self._target.read32(FAULT_EVENT) != 0:
                    fault = True
                    break
                if self._target.read32(COMMAND_EVENT) != 0:
                    break
                if self._target.read32(DATA_EVENT) != 0:
                    break
            else:
                raise exceptions.TargetError("wait for events timed out")

        # reset events
        for reg in [FAULT_EVENT, COMMAND_EVENT, DATA_EVENT]:
            self._target.write32(reg, 0)

        response = self._target.read32(0x2000000C)
        if (response & 0xFF000000) == 0xA5000000:
            LOG.debug(f"ACK response, code {response:08X}")
        elif (response & 0xFF000000) == 0x5A000000:
            raise exceptions.TargetError(f"NACK response, code {response:08X}")

        if fault:
            raise exceptions.TargetError("modem triggered FAULT_EVENT")

    def _reset_state(self):
        """@brief Clear all state variables. """
        self._total_data_size = 0
        self._progress_offset = 0.0
        self._current_progress_fraction = 0.0

    def _progress_cb(self, amount):
        """@brief callback for updating the progress bar"""
        if self._progress is not None:
            self._progress((amount * self._current_progress_fraction) + self._progress_offset)
