<commit_before>"""
mbed SDK
Copyright (c) 2011-2016 ARM Limited

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, division, absolute_import

import re
import tempfile
import datetime
import uuid
import struct
import zlib
import hashlib
from shutil import rmtree
from os.path import join, exists, dirname, basename, abspath, normpath, splitext
from os.path import relpath
from os import linesep, remove, makedirs
from time import time
from intelhex import IntelHex
from json import load, dump
from jinja2 import FileSystemLoader
from jinja2.environment import Environment

from .arm_pack_manager import Cache
from .utils import (mkdir, run_cmd, run_cmd_ext, NotSupportedException,
                    ToolException, InvalidReleaseTargetException,
                    intelhex_offset, integer)
from .paths import (MBED_CMSIS_PATH, MBED_TARGETS_PATH, MBED_LIBRARIES,
                    MBED_HEADER, MBED_DRIVERS, MBED_PLATFORM, MBED_HAL,
                    MBED_CONFIG_FILE, MBED_LIBRARIES_DRIVERS,
                    MBED_LIBRARIES_PLATFORM, MBED_LIBRARIES_HAL,
                    BUILD_DIR)
from .resources import Resources, FileType, FileRef
from .notifier.mock import MockNotifier
from .targets import TARGET_NAMES, TARGET_MAP, CORE_ARCH
from .libraries import Library
from .toolchains import TOOLCHAIN_CLASSES
from .config import Config

RELEASE_VERSIONS = ['2', '5']

def prep_report(report, target_name, toolchain_name, id_name):
    """Setup report keys

    Positional arguments:
    report - the report to fill
    target_name - the target being used
    toolchain_name - the toolchain being used
    id_name - the name of the executable or library being built
    """
    if not target_name in report:
        report[target_name] = {}

    if not toolchain_name in report[target_name]:
        report[target_name][toolchain_name] = {}

    if not id_name in report[target_name][toolchain_name]:
        report[target_name][toolchain_name][id_name] = []

def prep_properties(properties, target_name, toolchain_name, vendor_label):
    """Setup test properties

    Positional arguments:
    properties - the dict to fill
    target_name - the target the test is targeting
    toolchain_name - the toolchain that will compile the test
    vendor_label - the vendor
    """
    if not target_name in properties:
        properties[target_name] = {}

    if not toolchain_name in properties[target_name]:
        properties[target_name][toolchain_name] = {}

    properties[target_name][toolchain_name]["target"] = target_name
    properties[target_name][toolchain_name]["vendor"] = vendor_label
    properties[target_name][toolchain_name]["toolchain"] = toolchain_name

def create_result(target_name, toolchain_name, id_name, description):
    """Create a result dictionary

    Positional arguments:
    target_name - the target being built for
    toolchain_name - the toolchain doing the building
    id_name - the name of the executable or library being built
    description - a human readable description of what's going on
    """
    cur_result = {}
    cur_result["target_name"] = target_name
    cur_result["toolchain_name"] = toolchain_name
    cur_result["id"] = id_name
    cur_result["description"] = description
    cur_result["elapsed_time"] = 0
    cur_result["output"] = ""

    return cur_result

def add_result_to_report(report, result):
    """Add a single result to a report dictionary

    Positional arguments:
    report - the report to append to
    result - the result to append
    """
    result["date"] = datetime.datetime.utcnow().isoformat()
    result["uuid"] = str(uuid.uuid1())
    target = result["target_name"]
    toolchain = result["toolchain_name"]
    id_name = result['id']
    result_wrap = {0: result}
    report[target][toolchain][id_name].append(result_wrap)

def get_config(src_paths, target, toolchain_name=None, app_config=None):
    """Get the configuration object for a target-toolchain combination

    Positional arguments:
    src_paths - paths to scan for the configuration files
    target - the device we are building for
    toolchain_name - the string that identifies the build tools
    """
    # Convert src_paths to a list if needed
    if not isinstance(src_paths, list):
        src_paths = [src_paths]

    res = Resources(MockNotifier())
    if toolchain_name:
        toolchain = prepare_toolchain(src_paths, None, target, toolchain_name,
                                      app_config=app_config)
        config = toolchain.config
        res.scan_with_toolchain(src_paths, toolchain, exclude=False)
    else:
        config = Config(target, src_paths, app_config=app_config)
        res.scan_with_config(src_paths, config)
    if config.has_regions:
        _ = list(config.regions)

    cfg, macros = config.get_config_data()
    features = config.get_features()
    return cfg, macros, features

def is_official_target(target_name, version):
    """ Returns True, None if a target is part of the official release for the
    given version. Return False, 'reason' if a target is not part of the
    official release for the given version.

    Positional arguments:
    target_name - Name if the target (ex. 'K64F')
    version - The release version string. Should be a string contained within
              RELEASE_VERSIONS
    """

    result = True
    reason = None
    target = TARGET_MAP[target_name]

    if hasattr(target, 'release_versions') \
       and version in target.release_versions:
        if version == '2':
            # For version 2, either ARM or uARM toolchain support is required
            required_toolchains = set(['ARM', 'uARM'])

            if not len(required_toolchains.intersection(
                    set(target.supported_toolchains))) > 0:
                result = False
                reason = ("Target '%s' must support " % target.name) + \
                    ("one of the folowing toolchains to be included in the") + \
                    ((" mbed 2.0 official release: %s" + linesep) %
                     ", ".join(required_toolchains)) + \
                    ("Currently it is only configured to support the ") + \
                    ("following toolchains: %s" %
                     ", ".join(target.supported_toolchains))

        elif version == '5':
            # For version 5, ARM, GCC_ARM, and IAR toolchain support is required
            required_toolchains = [
                set(['ARM', 'GCC_ARM', 'IAR']),
                set(['ARMC6'])
            ]
            supported_toolchains = set(target.supported_toolchains)

            if not any(r.issubset(supported_toolchains)
                       for r in required_toolchains):
                result = False
                reason = ("Target '%s' must support " % target.name) + \
                    ("ALL of the folowing toolchains to be included in the") + \
                    ((" mbed OS 5.0 official release: %s" + linesep) %
                     ", ".join(sorted(required_toolchains[0]))) + \
                    ("Currently it is only configured to support the ") + \
                    ("following toolchains: %s" %
                     ", ".join(sorted(supported_toolchains)))

            elif not target.default_lib == 'std':
                result = False
                reason = ("Target '%s' must set the " % target.name) + \
                    ("'default_lib' to 'std' to be included in the ") + \
                    ("mbed OS 5.0 official release." + linesep) + \
                    ("Currently it is set to '%s'" % target.default_lib)

        else:
            result = False
            reason = ("Target '%s' has set an invalid release version of '%s'" %
                      version) + \
                ("Please choose from the following release versions: %s" %
                 ', '.join(RELEASE_VERSIONS))

    else:
        result = False
        if not hasattr(target, 'release_versions'):
            reason = "Target '%s' " % target.name
            reason += "does not have the 'release_versions' key set"
        elif not version in target.release_versions:
            reason = "Target '%s' does not contain the version '%s' " % \
                     (target.name, version)
            reason += "in its 'release_versions' key"

    return result, reason

def transform_release_toolchains(toolchains, version):
    """ Given a list of toolchains and a release version, return a list of
    only the supported toolchains for that release

    Positional arguments:
    toolchains - The list of toolchains
    version - The release version string. Should be a string contained within
              RELEASE_VERSIONS
    """
    if version == '5':
        return ['ARM', 'GCC_ARM', 'IAR']
    else:
        return toolchains


def get_mbed_official_release(version):
    """ Given a release version string, return a tuple that contains a target
    and the supported toolchains for that release.
    Ex. Given '2', return (('LPC1768', ('ARM', 'GCC_ARM')),
                           ('K64F', ('ARM', 'GCC_ARM')), ...)

    Positional arguments:
    version - The version string. Should be a string contained within
              RELEASE_VERSIONS
    """

    mbed_official_release = (
        tuple(
            tuple(
                [
                    TARGET_MAP[target].name,
                    tuple(transform_release_toolchains(
                        TARGET_MAP[target].supported_toolchains, version))
                ]
            ) for target in TARGET_NAMES \
            if (hasattr(TARGET_MAP[target], 'release_versions')
                and version in TARGET_MAP[target].release_versions)
        )
    )

    for target in mbed_official_release:
        is_official, reason = is_official_target(target[0], version)

        if not is_official:
            raise InvalidReleaseTargetException(reason)

    return mbed_official_release

ARM_COMPILERS = ("ARM", "ARMC6", "uARM")
def target_supports_toolchain(target, toolchain_name):
    if toolchain_name in ARM_COMPILERS:
        return any(tc in target.supported_toolchains for tc in ARM_COMPILERS)
    else:
        return toolchain_name in target.supported_toolchains


def prepare_toolchain(src_paths, build_dir, target, toolchain_name,
                      macros=None, clean=False, jobs=1,
                      notify=None, config=None, app_config=None,
                      build_profile=None, ignore=None):
    """ Prepares resource related objects - toolchain, target, config

    Positional arguments:
    src_paths - the paths to source directories
    target - ['LPC1768', 'LPC11U24', etc.]
    toolchain_name - ['ARM', 'uARM', 'GCC_ARM', 'GCC_CR']

    Keyword arguments:
    macros - additional macros
    clean - Rebuild everything if True
    jobs - how many compilers we can run at once
    notify - Notify function for logs
    config - a Config object to use instead of creating one
    app_config - location of a chosen mbed_app.json file
    build_profile - a list of mergeable build profiles
    ignore - list of paths to add to mbedignore
    """

    # We need to remove all paths which are repeated to avoid
    # multiple compilations and linking with the same objects
    src_paths = [src_paths[0]] + list(set(src_paths[1:]))

    # If the configuration object was not yet created, create it now
    config = config or Config(target, src_paths, app_config=app_config)
    target = config.target
    if not target_supports_toolchain(target, toolchain_name):
        raise NotSupportedException(
            "Target {} is not supported by toolchain {}".format(
                target.name, toolchain_name))
    if (toolchain_name == "ARM" and CORE_ARCH[target.core] == 8):
        toolchain_name = "ARMC6"

    try:
        cur_tc = TOOLCHAIN_CLASSES[toolchain_name]
    except KeyError:
        raise KeyError("Toolchain %s not supported" % toolchain_name)

    profile = {'c': [], 'cxx': [], 'common': [], 'asm': [], 'ld': []}
    for contents in build_profile or []:
        for key in profile:
            profile[key].extend(contents[toolchain_name].get(key, []))

    toolchain = cur_tc(
        target, notify, macros, build_dir=build_dir, build_profile=profile)

    toolchain.config = config
    toolchain.jobs = jobs
    toolchain.build_all = clean

    if ignore:
        toolchain.add_ignore_patterns(root=".", base_path=".", patterns=ignore)

    return toolchain

def _printihex(ihex):
    import pprint
    pprint.PrettyPrinter().pprint(ihex.todict())

def _real_region_size(region):
    try:
        part = intelhex_offset(region.filename, offset=region.start)
        return (part.maxaddr() - part.minaddr()) + 1
    except AttributeError:
        return region.size


def _fill_header(region_list, current_region):
    """Fill an application header region

    This is done it three steps:
     * Fill the whole region with zeros
     * Fill const, timestamp and size entries with their data
     * Fill the digests using this header as the header region
    """
    region_dict = {r.name: r for r in region_list}
    header = IntelHex()
    header.puts(current_region.start, b'\x00' * current_region.size)
    start = current_region.start
    for member in current_region.filename:
        _, type, subtype, data = member
        member_size = Config.header_member_size(member)
        if type == "const":
            fmt = {
                "8le": ">B", "16le": "<H", "32le": "<L", "64le": "<Q",
                "8be": "<B", "16be": ">H", "32be": ">L", "64be": ">Q"
            }[subtype]
            header.puts(start, struct.pack(fmt, integer(data, 0)))
        elif type == "timestamp":
            fmt = {"32le": "<L", "64le": "<Q",
                   "32be": ">L", "64be": ">Q"}[subtype]
            header.puts(start, struct.pack(fmt, time()))
        elif type == "size":
            fmt = {"32le": "<L", "64le": "<Q",
                   "32be": ">L", "64be": ">Q"}[subtype]
            size = sum(_real_region_size(region_dict[r]) for r in data)
            header.puts(start, struct.pack(fmt, size))
        elif type  == "digest":
            if data == "header":
                ih = header[:start]
            else:
                ih = intelhex_offset(region_dict[data].filename, offset=region_dict[data].start)
            if subtype.startswith("CRCITT32"):
                fmt = {"CRCITT32be": ">l", "CRCITT32le": "<l"}[subtype]
                header.puts(start, struct.pack(fmt, zlib.crc32(ih.tobinarray())))
            elif subtype.startswith("SHA"):
                if subtype == "SHA256":
                    hash = hashlib.sha256()
                elif subtype == "SHA512":
                    hash = hashlib.sha512()
                hash.update(ih.tobinarray())
                header.puts(start, hash.digest())
        start += Config.header_member_size(member)
    return header

def merge_region_list(region_list, destination, notify, padding=b'\xFF'):
    """Merge the region_list into a single image

    Positional Arguments:
    region_list - list of regions, which should contain filenames
    destination - file name to write all regions to
    padding - bytes to fill gapps with
    """
    merged = IntelHex()
    _, format = splitext(destination)

    notify.info("Merging Regions")

    for region in region_list:
        if region.active and not region.filename:
            raise ToolException("Active region has no contents: No file found.")
        if isinstance(region.filename, list):
            header_basename, _ = splitext(destination)
            header_filename = header_basename + "_header.hex"
            _fill_header(region_list, region).tofile(header_filename, format='hex')
            region = region._replace(filename=header_filename)
        if region.filename:
            notify.info("  Filling region %s with %s" % (region.name, region.filename))
            part = intelhex_offset(region.filename, offset=region.start)
            part.start_addr = None
            part_size = (part.maxaddr() - part.minaddr()) + 1
            if part_size > region.size:
                raise ToolException("Contents of region %s does not fit"
                                    % region.name)
            merged.merge(part)
            pad_size = region.size - part_size
            if pad_size > 0 and region != region_list[-1]:
                notify.info("  Padding region %s with 0x%x bytes" %
                            (region.name, pad_size))
                if format is ".hex":
                    """The offset will be in the hex file generated when we're done,
                    so we can skip padding here"""
                else:
                    merged.puts(merged.maxaddr() + 1, padding * pad_size)

    if not exists(dirname(destination)):
        makedirs(dirname(destination))
    notify.info("Space used after regions merged: 0x%x" %
                (merged.maxaddr() - merged.minaddr() + 1))
    merged.tofile(destination, format=format.strip("."))


UPDATE_WHITELIST = (
    "application",
)


def build_project(src_paths, build_path, target, toolchain_name,
                  libraries_paths=None, linker_script=None, clean=False,
                  notify=None, name=None, macros=None, inc_dirs=None, jobs=1,
                  report=None, properties=None, project_id=None,
                  project_description=None, config=None,
                  app_config=None, build_profile=None, stats_depth=None, ignore=None):
    """ Build a project. A project may be a test or a user program.

    Positional arguments:
    src_paths - a path or list of paths that contain all files needed to build
                the project
    build_path - the directory where all of the object files will be placed
    target - the MCU or board that the project will compile for
    toolchain_name - the name of the build tools

    Keyword arguments:
    libraries_paths - The location of libraries to include when linking
    linker_script - the file that drives the linker to do it's job
    clean - Rebuild everything if True
    notify - Notify function for logs
    name - the name of the project
    macros - additional macros
    inc_dirs - additional directories where include files may be found
    jobs - how many compilers we can run at once
    report - a dict where a result may be appended
    properties - UUUUHHHHH beats me
    project_id - the name put in the report
    project_description - the human-readable version of what this thing does
    config - a Config object to use instead of creating one
    app_config - location of a chosen mbed_app.json file
    build_profile - a dict of flags that will be passed to the compiler
    stats_depth - depth level for memap to display file/dirs
    ignore - list of paths to add to mbedignore
    """
    # Convert src_path to a list if needed
    if not isinstance(src_paths, list):
        src_paths = [src_paths]
    # Extend src_paths wiht libraries_paths
    if libraries_paths is not None:
        src_paths.extend(libraries_paths)
        inc_dirs.extend(map(dirname, libraries_paths))

    if clean and exists(build_path):
        rmtree(build_path)
    mkdir(build_path)

    toolchain = prepare_toolchain(
        src_paths, build_path, target, toolchain_name, macros=macros,
        clean=clean, jobs=jobs, notify=notify, config=config,
        app_config=app_config, build_profile=build_profile, ignore=ignore)
    toolchain.version_check()

    # The first path will give the name to the library
    name = (name or toolchain.config.name or
            basename(normpath(abspath(src_paths[0]))))
    notify.info("Building project %s (%s, %s)" %
                (name, toolchain.target.name, toolchain_name))

    # Initialize reporting
    if report != None:
        start = time()
        # If project_id is specified, use that over the default name
        id_name = project_id.upper() if project_id else name.upper()
        description = project_description if project_description else name
        vendor_label = toolchain.target.extra_labels[0]
        prep_report(report, toolchain.target.name, toolchain_name, id_name)
        cur_result = create_result(toolchain.target.name, toolchain_name,
                                   id_name, description)
        if properties != None:
            prep_properties(properties, toolchain.target.name, toolchain_name,
                            vendor_label)

    try:
        resources = Resources(notify).scan_with_toolchain(
            src_paths, toolchain, inc_dirs=inc_dirs)

        # Change linker script if specified
        if linker_script is not None:
            resources.add_file_ref(linker_script, linker_script)
        if not resources.get_file_refs(FileType.LD_SCRIPT):
            raise NotSupportedException("No Linker Script found!")

        # Compile Sources
        objects = toolchain.compile_sources(resources, sorted(resources.get_file_paths(FileType.INC_DIR)))
        resources.add_files_to_type(FileType.OBJECT, objects)

        # Link Program
        if toolchain.config.has_regions:
            binary, _ = toolchain.link_program(resources, build_path, name + "_application")
            region_list = list(toolchain.config.regions)
            region_list = [r._replace(filename=binary) if r.active else r
                           for r in region_list]
            res = "%s.%s" % (join(build_path, name),
                             getattr(toolchain.target, "OUTPUT_EXT", "bin"))
            merge_region_list(region_list, res, notify)
            update_regions = [
                r for r in region_list if r.name in UPDATE_WHITELIST
            ]
            if update_regions:
                update_res = "%s_update.%s" % (
                    join(build_path, name),
                    getattr(toolchain.target, "OUTPUT_EXT", "bin")
                )
                merge_region_list(update_regions, update_res, notify)
                res = (res, update_res)
            else:
                res = (res, None)
        else:
            res, _ = toolchain.link_program(resources, build_path, name)
            res = (res, None)

        memap_instance = getattr(toolchain, 'memap_instance', None)<commit_msg>Stop shouting at users in error messages<commit_after>"""
mbed SDK
Copyright (c) 2011-2016 ARM Limited

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, division, absolute_import

import re
import tempfile
import datetime
import uuid
import struct
import zlib
import hashlib
from shutil import rmtree
from os.path import join, exists, dirname, basename, abspath, normpath, splitext
from os.path import relpath
from os import linesep, remove, makedirs
from time import time
from intelhex import IntelHex
from json import load, dump
from jinja2 import FileSystemLoader
from jinja2.environment import Environment

from .arm_pack_manager import Cache
from .utils import (mkdir, run_cmd, run_cmd_ext, NotSupportedException,
                    ToolException, InvalidReleaseTargetException,
                    intelhex_offset, integer)
from .paths import (MBED_CMSIS_PATH, MBED_TARGETS_PATH, MBED_LIBRARIES,
                    MBED_HEADER, MBED_DRIVERS, MBED_PLATFORM, MBED_HAL,
                    MBED_CONFIG_FILE, MBED_LIBRARIES_DRIVERS,
                    MBED_LIBRARIES_PLATFORM, MBED_LIBRARIES_HAL,
                    BUILD_DIR)
from .resources import Resources, FileType, FileRef
from .notifier.mock import MockNotifier
from .targets import TARGET_NAMES, TARGET_MAP, CORE_ARCH
from .libraries import Library
from .toolchains import TOOLCHAIN_CLASSES
from .config import Config

RELEASE_VERSIONS = ['2', '5']

def prep_report(report, target_name, toolchain_name, id_name):
    """Setup report keys

    Positional arguments:
    report - the report to fill
    target_name - the target being used
    toolchain_name - the toolchain being used
    id_name - the name of the executable or library being built
    """
    if not target_name in report:
        report[target_name] = {}

    if not toolchain_name in report[target_name]:
        report[target_name][toolchain_name] = {}

    if not id_name in report[target_name][toolchain_name]:
        report[target_name][toolchain_name][id_name] = []

def prep_properties(properties, target_name, toolchain_name, vendor_label):
    """Setup test properties

    Positional arguments:
    properties - the dict to fill
    target_name - the target the test is targeting
    toolchain_name - the toolchain that will compile the test
    vendor_label - the vendor
    """
    if not target_name in properties:
        properties[target_name] = {}

    if not toolchain_name in properties[target_name]:
        properties[target_name][toolchain_name] = {}

    properties[target_name][toolchain_name]["target"] = target_name
    properties[target_name][toolchain_name]["vendor"] = vendor_label
    properties[target_name][toolchain_name]["toolchain"] = toolchain_name

def create_result(target_name, toolchain_name, id_name, description):
    """Create a result dictionary

    Positional arguments:
    target_name - the target being built for
    toolchain_name - the toolchain doing the building
    id_name - the name of the executable or library being built
    description - a human readable description of what's going on
    """
    cur_result = {}
    cur_result["target_name"] = target_name
    cur_result["toolchain_name"] = toolchain_name
    cur_result["id"] = id_name
    cur_result["description"] = description
    cur_result["elapsed_time"] = 0
    cur_result["output"] = ""

    return cur_result

def add_result_to_report(report, result):
    """Add a single result to a report dictionary

    Positional arguments:
    report - the report to append to
    result - the result to append
    """
    result["date"] = datetime.datetime.utcnow().isoformat()
    result["uuid"] = str(uuid.uuid1())
    target = result["target_name"]
    toolchain = result["toolchain_name"]
    id_name = result['id']
    result_wrap = {0: result}
    report[target][toolchain][id_name].append(result_wrap)

def get_config(src_paths, target, toolchain_name=None, app_config=None):
    """Get the configuration object for a target-toolchain combination

    Positional arguments:
    src_paths - paths to scan for the configuration files
    target - the device we are building for
    toolchain_name - the string that identifies the build tools
    """
    # Convert src_paths to a list if needed
    if not isinstance(src_paths, list):
        src_paths = [src_paths]

    res = Resources(MockNotifier())
    if toolchain_name:
        toolchain = prepare_toolchain(src_paths, None, target, toolchain_name,
                                      app_config=app_config)
        config = toolchain.config
        res.scan_with_toolchain(src_paths, toolchain, exclude=False)
    else:
        config = Config(target, src_paths, app_config=app_config)
        res.scan_with_config(src_paths, config)
    if config.has_regions:
        _ = list(config.regions)

    cfg, macros = config.get_config_data()
    features = config.get_features()
    return cfg, macros, features

def is_official_target(target_name, version):
    """ Returns True, None if a target is part of the official release for the
    given version. Return False, 'reason' if a target is not part of the
    official release for the given version.

    Positional arguments:
    target_name - Name if the target (ex. 'K64F')
    version - The release version string. Should be a string contained within
              RELEASE_VERSIONS
    """

    result = True
    reason = None
    target = TARGET_MAP[target_name]

    if hasattr(target, 'release_versions') \
       and version in target.release_versions:
        if version == '2':
            # For version 2, either ARM or uARM toolchain support is required
            required_toolchains = set(['ARM', 'uARM'])

            if not len(required_toolchains.intersection(
                    set(target.supported_toolchains))) > 0:
                result = False
                reason = ("Target '%s' must support " % target.name) + \
                    ("one of the folowing toolchains to be included in the") + \
                    ((" mbed 2.0 official release: %s" + linesep) %
                     ", ".join(required_toolchains)) + \
                    ("Currently it is only configured to support the ") + \
                    ("following toolchains: %s" %
                     ", ".join(target.supported_toolchains))

        elif version == '5':
            # For version 5, ARM, GCC_ARM, and IAR toolchain support is required
            required_toolchains = [
                set(['ARM', 'GCC_ARM', 'IAR']),
                set(['ARMC6'])
            ]
            supported_toolchains = set(target.supported_toolchains)

            if not any(r.issubset(supported_toolchains)
                       for r in required_toolchains):
                result = False
                reason = ("Target '%s' must support " % target.name) + \
                    ("ALL of the folowing toolchains to be included in the") + \
                    ((" mbed OS 5.0 official release: %s" + linesep) %
                     ", ".join(sorted(required_toolchains[0]))) + \
                    ("Currently it is only configured to support the ") + \
                    ("following toolchains: %s" %
                     ", ".join(sorted(supported_toolchains)))

            elif not target.default_lib == 'std':
                result = False
                reason = ("Target '%s' must set the " % target.name) + \
                    ("'default_lib' to 'std' to be included in the ") + \
                    ("mbed OS 5.0 official release." + linesep) + \
                    ("Currently it is set to '%s'" % target.default_lib)

        else:
            result = False
            reason = ("Target '%s' has set an invalid release version of '%s'" %
                      version) + \
                ("Please choose from the following release versions: %s" %
                 ', '.join(RELEASE_VERSIONS))

    else:
        result = False
        if not hasattr(target, 'release_versions'):
            reason = "Target '%s' " % target.name
            reason += "does not have the 'release_versions' key set"
        elif not version in target.release_versions:
            reason = "Target '%s' does not contain the version '%s' " % \
                     (target.name, version)
            reason += "in its 'release_versions' key"

    return result, reason

def transform_release_toolchains(toolchains, version):
    """ Given a list of toolchains and a release version, return a list of
    only the supported toolchains for that release

    Positional arguments:
    toolchains - The list of toolchains
    version - The release version string. Should be a string contained within
              RELEASE_VERSIONS
    """
    if version == '5':
        return ['ARM', 'GCC_ARM', 'IAR']
    else:
        return toolchains


def get_mbed_official_release(version):
    """ Given a release version string, return a tuple that contains a target
    and the supported toolchains for that release.
    Ex. Given '2', return (('LPC1768', ('ARM', 'GCC_ARM')),
                           ('K64F', ('ARM', 'GCC_ARM')), ...)

    Positional arguments:
    version - The version string. Should be a string contained within
              RELEASE_VERSIONS
    """

    mbed_official_release = (
        tuple(
            tuple(
                [
                    TARGET_MAP[target].name,
                    tuple(transform_release_toolchains(
                        TARGET_MAP[target].supported_toolchains, version))
                ]
            ) for target in TARGET_NAMES \
            if (hasattr(TARGET_MAP[target], 'release_versions')
                and version in TARGET_MAP[target].release_versions)
        )
    )

    for target in mbed_official_release:
        is_official, reason = is_official_target(target[0], version)

        if not is_official:
            raise InvalidReleaseTargetException(reason)

    return mbed_official_release

ARM_COMPILERS = ("ARM", "ARMC6", "uARM")
def target_supports_toolchain(target, toolchain_name):
    if toolchain_name in ARM_COMPILERS:
        return any(tc in target.supported_toolchains for tc in ARM_COMPILERS)
    else:
        return toolchain_name in target.supported_toolchains


def prepare_toolchain(src_paths, build_dir, target, toolchain_name,
                      macros=None, clean=False, jobs=1,
                      notify=None, config=None, app_config=None,
                      build_profile=None, ignore=None):
    """ Prepares resource related objects - toolchain, target, config

    Positional arguments:
    src_paths - the paths to source directories
    target - ['LPC1768', 'LPC11U24', etc.]
    toolchain_name - ['ARM', 'uARM', 'GCC_ARM', 'GCC_CR']

    Keyword arguments:
    macros - additional macros
    clean - Rebuild everything if True
    jobs - how many compilers we can run at once
    notify - Notify function for logs
    config - a Config object to use instead of creating one
    app_config - location of a chosen mbed_app.json file
    build_profile - a list of mergeable build profiles
    ignore - list of paths to add to mbedignore
    """

    # We need to remove all paths which are repeated to avoid
    # multiple compilations and linking with the same objects
    src_paths = [src_paths[0]] + list(set(src_paths[1:]))

    # If the configuration object was not yet created, create it now
    config = config or Config(target, src_paths, app_config=app_config)
    target = config.target
    if not target_supports_toolchain(target, toolchain_name):
        raise NotSupportedException(
            "Target {} is not supported by toolchain {}".format(
                target.name, toolchain_name))
    if (toolchain_name == "ARM" and CORE_ARCH[target.core] == 8):
        toolchain_name = "ARMC6"

    try:
        cur_tc = TOOLCHAIN_CLASSES[toolchain_name]
    except KeyError:
        raise KeyError("Toolchain %s not supported" % toolchain_name)

    profile = {'c': [], 'cxx': [], 'common': [], 'asm': [], 'ld': []}
    for contents in build_profile or []:
        for key in profile:
            profile[key].extend(contents[toolchain_name].get(key, []))

    toolchain = cur_tc(
        target, notify, macros, build_dir=build_dir, build_profile=profile)

    toolchain.config = config
    toolchain.jobs = jobs
    toolchain.build_all = clean

    if ignore:
        toolchain.add_ignore_patterns(root=".", base_path=".", patterns=ignore)

    return toolchain

def _printihex(ihex):
    import pprint
    pprint.PrettyPrinter().pprint(ihex.todict())

def _real_region_size(region):
    try:
        part = intelhex_offset(region.filename, offset=region.start)
        return (part.maxaddr() - part.minaddr()) + 1
    except AttributeError:
        return region.size


def _fill_header(region_list, current_region):
    """Fill an application header region

    This is done it three steps:
     * Fill the whole region with zeros
     * Fill const, timestamp and size entries with their data
     * Fill the digests using this header as the header region
    """
    region_dict = {r.name: r for r in region_list}
    header = IntelHex()
    header.puts(current_region.start, b'\x00' * current_region.size)
    start = current_region.start
    for member in current_region.filename:
        _, type, subtype, data = member
        member_size = Config.header_member_size(member)
        if type == "const":
            fmt = {
                "8le": ">B", "16le": "<H", "32le": "<L", "64le": "<Q",
                "8be": "<B", "16be": ">H", "32be": ">L", "64be": ">Q"
            }[subtype]
            header.puts(start, struct.pack(fmt, integer(data, 0)))
        elif type == "timestamp":
            fmt = {"32le": "<L", "64le": "<Q",
                   "32be": ">L", "64be": ">Q"}[subtype]
            header.puts(start, struct.pack(fmt, time()))
        elif type == "size":
            fmt = {"32le": "<L", "64le": "<Q",
                   "32be": ">L", "64be": ">Q"}[subtype]
            size = sum(_real_region_size(region_dict[r]) for r in data)
            header.puts(start, struct.pack(fmt, size))
        elif type  == "digest":
            if data == "header":
                ih = header[:start]
            else:
                ih = intelhex_offset(region_dict[data].filename, offset=region_dict[data].start)
            if subtype.startswith("CRCITT32"):
                fmt = {"CRCITT32be": ">l", "CRCITT32le": "<l"}[subtype]
                header.puts(start, struct.pack(fmt, zlib.crc32(ih.tobinarray())))
            elif subtype.startswith("SHA"):
                if subtype == "SHA256":
                    hash = hashlib.sha256()
                elif subtype == "SHA512":
                    hash = hashlib.sha512()
                hash.update(ih.tobinarray())
                header.puts(start, hash.digest())
        start += Config.header_member_size(member)
    return header

def merge_region_list(region_list, destination, notify, padding=b'\xFF'):
    """Merge the region_list into a single image

    Positional Arguments:
    region_list - list of regions, which should contain filenames
    destination - file name to write all regions to
    padding - bytes to fill gapps with
    """
    merged = IntelHex()
    _, format = splitext(destination)

    notify.info("Merging Regions")

    for region in region_list:
        if region.active and not region.filename:
            raise ToolException("Active region has no contents: No file found.")
        if isinstance(region.filename, list):
            header_basename, _ = splitext(destination)
            header_filename = header_basename + "_header.hex"
            _fill_header(region_list, region).tofile(header_filename, format='hex')
            region = region._replace(filename=header_filename)
        if region.filename:
            notify.info("  Filling region %s with %s" % (region.name, region.filename))
            part = intelhex_offset(region.filename, offset=region.start)
            part.start_addr = None
            part_size = (part.maxaddr() - part.minaddr()) + 1
            if part_size > region.size:
                raise ToolException("Contents of region %s does not fit"
                                    % region.name)
            merged.merge(part)
            pad_size = region.size - part_size
            if pad_size > 0 and region != region_list[-1]:
                notify.info("  Padding region %s with 0x%x bytes" %
                            (region.name, pad_size))
                if format is ".hex":
                    """The offset will be in the hex file generated when we're done,
                    so we can skip padding here"""
                else:
                    merged.puts(merged.maxaddr() + 1, padding * pad_size)

    if not exists(dirname(destination)):
        makedirs(dirname(destination))
    notify.info("Space used after regions merged: 0x%x" %
                (merged.maxaddr() - merged.minaddr() + 1))
    merged.tofile(destination, format=format.strip("."))


UPDATE_WHITELIST = (
    "application",
)


def build_project(src_paths, build_path, target, toolchain_name,
                  libraries_paths=None, linker_script=None, clean=False,
                  notify=None, name=None, macros=None, inc_dirs=None, jobs=1,
                  report=None, properties=None, project_id=None,
                  project_description=None, config=None,
                  app_config=None, build_profile=None, stats_depth=None, ignore=None):
    """ Build a project. A project may be a test or a user program.

    Positional arguments:
    src_paths - a path or list of paths that contain all files needed to build
                the project
    build_path - the directory where all of the object files will be placed
    target - the MCU or board that the project will compile for
    toolchain_name - the name of the build tools

    Keyword arguments:
    libraries_paths - The location of libraries to include when linking
    linker_script - the file that drives the linker to do it's job
    clean - Rebuild everything if True
    notify - Notify function for logs
    name - the name of the project
    macros - additional macros
    inc_dirs - additional directories where include files may be found
    jobs - how many compilers we can run at once
    report - a dict where a result may be appended
    properties - UUUUHHHHH beats me
    project_id - the name put in the report
    project_description - the human-readable version of what this thing does
    config - a Config object to use instead of creating one
    app_config - location of a chosen mbed_app.json file
    build_profile - a dict of flags that will be passed to the compiler
    stats_depth - depth level for memap to display file/dirs
    ignore - list of paths to add to mbedignore
    """
    # Convert src_path to a list if needed
    if not isinstance(src_paths, list):
        src_paths = [src_paths]
    # Extend src_paths wiht libraries_paths
    if libraries_paths is not None:
        src_paths.extend(libraries_paths)
        inc_dirs.extend(map(dirname, libraries_paths))

    if clean and exists(build_path):
        rmtree(build_path)
    mkdir(build_path)

    toolchain = prepare_toolchain(
        src_paths, build_path, target, toolchain_name, macros=macros,
        clean=clean, jobs=jobs, notify=notify, config=config,
        app_config=app_config, build_profile=build_profile, ignore=ignore)
    toolchain.version_check()

    # The first path will give the name to the library
    name = (name or toolchain.config.name or
            basename(normpath(abspath(src_paths[0]))))
    notify.info("Building project %s (%s, %s)" %
                (name, toolchain.target.name, toolchain_name))

    # Initialize reporting
    if report != None:
        start = time()
        # If project_id is specified, use that over the default name
        id_name = project_id.upper() if project_id else name.upper()
        description = project_description if project_description else name
        vendor_label = toolchain.target.extra_labels[0]
        prep_report(report, toolchain.target.name, toolchain_name, id_name)
        cur_result = create_result(toolchain.target.name, toolchain_name,
                                   id_name, description)
        if properties != None:
            prep_properties(properties, toolchain.target.name, toolchain_name,
                            vendor_label)

    try:
        resources = Resources(notify).scan_with_toolchain(
            src_paths, toolchain, inc_dirs=inc_dirs)

        # Change linker script if specified
        if linker_script is not None:
            resources.add_file_ref(linker_script, linker_script)
        if not resources.get_file_refs(FileType.LD_SCRIPT):
            raise NotSupportedException("No Linker Script found")

        # Compile Sources
        objects = toolchain.compile_sources(resources, sorted(resources.get_file_paths(FileType.INC_DIR)))
        resources.add_files_to_type(FileType.OBJECT, objects)

        # Link Program
        if toolchain.config.has_regions:
            binary, _ = toolchain.link_program(resources, build_path, name + "_application")
            region_list = list(toolchain.config.regions)
            region_list = [r._replace(filename=binary) if r.active else r
                           for r in region_list]
            res = "%s.%s" % (join(build_path, name),
                             getattr(toolchain.target, "OUTPUT_EXT", "bin"))
            merge_region_list(region_list, res, notify)
            update_regions = [
                r for r in region_list if r.name in UPDATE_WHITELIST
            ]
            if update_regions:
                update_res = "%s_update.%s" % (
                    join(build_path, name),
                    getattr(toolchain.target, "OUTPUT_EXT", "bin")
                )
                merge_region_list(update_regions, update_res, notify)
                res = (res, update_res)
            else:
                res = (res, None)
        else:
            res, _ = toolchain.link_program(resources, build_path, name)
            res = (res, None)

        memap_instance = getattr(toolchain, 'memap_instance', None)
{'fraction_non_alphanumeric': 0.0893949394939494, 'fraction_numerical': 0.005324532453245325, 'mean_word_length': 2.457138510686849, 'pattern_counts': {'":': 52, '<': 21, '<?xml version=': 0, '>': 27, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7443243', 'n_tokens_mistral': 12968, 'n_tokens_neox': 12272, 'n_words': 3879}