#!/usr/bin/env python3
"""tms-link -- native TI-COFF linker for the TMS34010.

Reads one or more relocatable TI-COFF objects produced by
``llc -march=tms34010 -filetype=obj`` (or by GSPA) and writes a
position-dependent linked image with no relocation records.  The layout and
load image match GSPLNK 2.00 closely enough for the dwt loader; the GSPLNK
output remains the oracle.

Usage:
    tms-link -o OUT [--map MAP] [--entry SYM]
             [--text ADDR] [--data ADDR] [--cinit ADDR] [--bss ADDR]
             [--prog-len BITS] [--ram-len BITS]
             [--keep-debug|--strip-debug] [-L DIR] [-l LIB] OBJ|LIB...

Inputs may be relocatable TI-COFF objects or System V ``ar`` archives
(``!<arch>``) of such objects.  Archive members are pulled in only when they
define a symbol that is still undefined, iterating to a fixpoint; a member is
never extracted twice.  ``-l LIB`` searches ``.``, ``-L`` directories and the
directories of the other inputs for ``LIB``, ``LIB.lib``, ``LIB.LIB`` or
``libLIB.a``.

Ordering: all explicit positional objects are read first, in command order;
archive members (from positional archives and ``-l`` libraries) are appended
after them in extraction order.  Archive position relative to objects therefore
does not change the image.

TI-COFF relocation fields are signed 32-bit addends.

All addresses and section sizes are in BITS.  Defaults:
    .text  018A0000
    .data  immediately after .text, 16-bit aligned
    .cinit immediately after .data, 16-bit aligned (only when it has bytes)
    .bss   01A00000

``--prog-len``/``--ram-len`` optionally bound the prog (.text/.data/.cinit)
and ram (.bss) regions in bits; overflow and region overlap are loud errors.

Debug sections are stripped by default.  ``--keep-debug`` keeps the
``.debug_*`` sections from every debug-bearing object, concatenated in object
order, with their section-relative offsets and relocations rehomed across the
merged sections.  A single debug-bearing object is copied byte-for-byte
(placements start at 0), so the M7 single-TU output is unchanged.
"""
from __future__ import annotations

import argparse
import os
import struct
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from tmscoff import (  # noqa: E402
    Archive, C_EXT, C_FILE, C_STAT, SEC_ABS, CoffError, OutSection,
    OutSymbol, S_BSS, S_DATA, S_TEXT, align16, read_input, read_object,
    write_coff,
)

DEFAULT_TEXT = 0x018A0000
DEFAULT_BSS = 0x01A00000
R_RELLONG = 0x11

# Debug sections that are safe to concatenate by appending one object's whole
# contribution to the next.  Each is a sequence of self-contained units (or a
# plain NUL-terminated string pool), and every section-relative reference is
# carried by a relocation or by the one raw field handled in
# _patch_raw_debug_offsets (the CU header's debug_abbrev_offset).  LLVM 23.1.5
# `-g` objects use exactly these shapes; anything else is refused in a
# multi-TU link rather than silently mis-merged.
DEBUG_CONCAT_SECTIONS = frozenset((
    ".debug_abbrev",
    ".debug_info",
    ".debug_str",
    ".debug_str_offsets",
    ".debug_addr",
    ".debug_line",
    ".debug_line_str",
    ".debug_loclists",
    ".debug_rnglists",
))


class LinkError(Exception):
    """A loud link failure (bad input, layout, or unresolved symbol)."""


def parse_addr(text):
    s = text.strip().lower()
    if s.endswith("h"):
        s = s[:-1]
    if s.startswith("0x"):
        s = s[2:]
    if not s:
        raise argparse.ArgumentTypeError("empty address")
    try:
        return int(s, 16)
    except ValueError as exc:
        raise argparse.ArgumentTypeError(
            "invalid hexadecimal bit address %r" % text) from exc


def _s32(data, offset):
    """A relocation addend field: two's-complement signed 32-bit."""
    return struct.unpack_from("<i", data, offset)[0]


def _put_u32(data, offset, value):
    if value < 0 or value > 0xFFFFFFFF:
        raise LinkError("relocation value %#x does not fit in 32 bits"
                        % value)
    struct.pack_into("<I", data, offset, value)


class Linker:
    def __init__(self, args):
        self.args = args
        self.objects = []
        self.libraries = []
        self.global_defs = {}
        self.out_sections = []
        self.out_index = {}
        # (object path, section name) -> (OutSection, bit offset in it)
        self.placements = {}
        self._extracted = set()       # (archive path, member offset)
        self._member_objects = {}     # same key -> parsed ObjectFile

    # -- loading ---------------------------------------------------------

    def _resolve_library(self, name):
        """Resolve a -l argument to an existing archive path."""
        if os.path.isfile(name):
            return name
        candidates = [name]
        lower = name.lower()
        if not (lower.endswith(".lib") or lower.endswith(".a")):
            candidates.extend([name + ".lib", name + ".LIB",
                               "lib" + name + ".a"])
        search = list(self.args.lib_dirs or [])
        search.append(".")
        for path in self.args.objects:
            directory = os.path.dirname(path)
            if directory and directory not in search:
                search.append(directory)
        for directory in search:
            for candidate in candidates:
                path = os.path.join(directory, candidate)
                if os.path.isfile(path):
                    return path
        raise LinkError("cannot find library '%s' (searched %s)"
                        % (name, ", ".join(search)))

    def _input_paths(self):
        paths = list(self.args.objects)
        for lib in self.args.libraries:
            paths.append(self._resolve_library(lib))
        return paths

    def load(self):
        for path in self._input_paths():
            try:
                item = read_input(path)
            except CoffError as exc:
                raise LinkError(str(exc)) from exc
            if isinstance(item, Archive):
                self.libraries.append(item)
            else:
                self.objects.append(item)

    def _collect_object_globals(self, obj):
        for sym in obj.symbols:
            if not sym.is_global or sym.is_section:
                continue
            if sym.secno > 0 or sym.is_absolute:
                if sym.name in self.global_defs:
                    other_obj, other_sym = self.global_defs[sym.name]
                    raise LinkError(
                        "duplicate definition of '%s' in %s (record %d) "
                        "and %s (record %d)"
                        % (sym.name, other_obj.path, other_sym.index,
                           obj.path, sym.index))
                self.global_defs[sym.name] = (obj, sym)

    def _collect_globals(self):
        for obj in self.objects:
            self._collect_object_globals(obj)

    # -- archive extraction ----------------------------------------------

    def _undefined_names(self):
        """Undefined external names in first-reference order."""
        seen = set()
        names = []
        for obj in self.objects:
            for sym in obj.symbols:
                if not sym.is_global or sym.is_section:
                    continue
                if sym.is_defined or sym.is_absolute:
                    continue
                if sym.name in self.global_defs or sym.name in seen:
                    continue
                seen.add(sym.name)
                names.append(sym.name)
        return names

    @staticmethod
    def _member_label(archive, member):
        # The offset makes labels unique even when an archive contains two
        # members with the same name; placement keys use this label.
        return "%s(%s@%#x)" % (archive.path, member.name, member.offset)

    def _member_object(self, archive, member):
        key = (archive.path, member.offset)
        obj = self._member_objects.get(key)
        if obj is None:
            try:
                obj = read_object(data=member.data,
                                  label=self._member_label(archive, member))
            except CoffError as exc:
                raise LinkError(str(exc)) from exc
            self._member_objects[key] = obj
        return obj

    @staticmethod
    def _defines(obj, name):
        for sym in obj.symbols:
            if (sym.name == name and sym.is_global and not sym.is_section and
                    (sym.secno > 0 or sym.is_absolute)):
                return True
        return False

    def _archive_candidates(self, archive, name):
        if archive.symbols is not None:
            candidates = []
            seen = set()
            for member in archive.symbols.get(name, ()):
                if member.offset in seen:
                    continue
                seen.add(member.offset)
                candidates.append(member)
        else:
            # A no-index archive has to be scanned member by member.
            candidates = []
            for member in archive.members:
                if self._defines(self._member_object(archive, member), name):
                    candidates.append(member)
        if not candidates:
            return []
        # Validate the index before choosing, so a corrupt table is loud.
        for member in candidates:
            if not self._defines(self._member_object(archive, member), name):
                raise LinkError(
                    "%s: symbol table says member defines '%s' but it does "
                    "not" % (self._member_label(archive, member), name))
        return candidates

    def _check_duplicate_candidates(self, archive, names):
        for name in names:
            candidates = self._archive_candidates(archive, name)
            if len(candidates) > 1:
                labels = ", ".join(self._member_label(archive, m)
                                   for m in candidates)
                raise LinkError("duplicate definition of '%s' in %s"
                                % (name, labels))

    def _process_archive(self, archive):
        """Scan the archive in its index order, pulling needed members.

        This is the GSPLNK 2.00 behaviour: the library's own symbol-table
        order (which is member order for the 1990 TI archives) drives the
        layout, not the caller's symbol-table order.  A pass may add new
        undefined names; repeat until a pass extracts nothing.
        """
        progress = False
        while True:
            extracted = False
            undefined = set(self._undefined_names())
            for member in archive.scan_members():
                key = (archive.path, member.offset)
                if key in self._extracted:
                    continue
                if archive.symbols is not None:
                    names = archive.member_symbols.get(member.offset, ())
                    needed = [name for name in names if name in undefined]
                    if not needed:
                        continue
                    obj = self._member_object(archive, member)
                    for name in needed:
                        if not self._defines(obj, name):
                            raise LinkError(
                                "%s: symbol table says member defines '%s' "
                                "but it does not"
                                % (self._member_label(archive, member), name))
                else:
                    # No index: every member has to be inspected to learn
                    # its definitions.
                    obj = self._member_object(archive, member)
                    needed = [name for name in self._undefined_names()
                              if self._defines(obj, name)]
                    if not needed:
                        continue
                self._check_duplicate_candidates(archive, needed)
                self.objects.append(obj)
                self._extracted.add(key)
                self._collect_object_globals(obj)
                extracted = True
                progress = True
                undefined = set(self._undefined_names())
            if not extracted:
                return progress

    def _extract_archive_members(self):
        for archive in self.libraries:
            self._process_archive(archive)
        # Backward references between libraries (and references discovered
        # after a later archive was scanned) still reach a fixpoint.
        changed = True
        while changed:
            changed = False
            for archive in self.libraries:
                if self._process_archive(archive):
                    changed = True

    # -- layout ----------------------------------------------------------

    def _total_size(self, name):
        total = 0
        for obj in self.objects:
            sec = obj.section_by_name.get(name)
            if sec is not None:
                total += sec.size
        return total

    def layout(self):
        args = self.args
        self.text_size = self._total_size(".text")
        self.data_size = self._total_size(".data")
        self.cinit_size = self._total_size(".cinit")
        self.bss_size = self._total_size(".bss")
        # An input may contain a listed-but-empty .cinit (GSPA/GSPLNK shape).
        # It contributes no bytes and must not create an output section or the
        # public cinit symbol, matching GSPLNK's empty flags-0 section.
        self.has_cinit = self.cinit_size > 0

        self.text_paddr = args.text
        self.data_paddr = (args.data if args.data is not None
                           else align16(self.text_paddr + self.text_size))
        self.cinit_paddr = (args.cinit if args.cinit is not None
                            else align16(self.data_paddr + self.data_size))
        self.bss_paddr = args.bss

        origins = [(".text", self.text_paddr), (".data", self.data_paddr),
                   (".bss", self.bss_paddr)]
        if self.has_cinit:
            origins.append((".cinit", self.cinit_paddr))
        for label, value in origins:
            if value % 16:
                raise LinkError("%s origin %#x is not 16-bit word aligned"
                                % (label, value))

        if self.data_paddr < self.text_paddr + self.text_size:
            raise LinkError(
                "unmappable layout: .data at %#x overlaps .text ending at %#x"
                % (self.data_paddr, self.text_paddr + self.text_size))
        if self.has_cinit and self.cinit_paddr < self.data_paddr + self.data_size:
            raise LinkError(
                "unmappable layout: .cinit at %#x overlaps .data ending at %#x"
                % (self.cinit_paddr, self.data_paddr + self.data_size))
        prog_end = ((self.cinit_paddr + self.cinit_size)
                    if self.has_cinit
                    else (self.data_paddr + self.data_size))
        if self.bss_paddr < prog_end:
            raise LinkError(
                "unmappable layout: .bss at %#x overlaps the program sections "
                "ending at %#x" % (self.bss_paddr, prog_end))

        self.text_end = self.text_paddr + self.text_size
        self.data_end = self.data_paddr + self.data_size
        self.cinit_end = self.cinit_paddr + self.cinit_size
        self.bss_end = self.bss_paddr + self.bss_size

        if args.prog_len is not None:
            prog_limit = self.text_paddr + args.prog_len
            if prog_end > prog_limit:
                raise LinkError(
                    ".text/.data/.cinit end at %#x, beyond the prog region "
                    "[%#x, %#x) (length %#x bits)"
                    % (prog_end, self.text_paddr, prog_limit,
                       args.prog_len))
        if args.ram_len is not None:
            ram_limit = self.bss_paddr + args.ram_len
            if self.bss_end > ram_limit:
                raise LinkError(
                    ".bss ends at %#x, beyond the ram region [%#x, %#x) "
                    "(length %#x bits)"
                    % (self.bss_end, self.bss_paddr, ram_limit,
                       args.ram_len))
        if args.prog_len is not None and args.ram_len is not None:
            prog_limit = self.text_paddr + args.prog_len
            ram_limit = self.bss_paddr + args.ram_len
            if (self.text_paddr < ram_limit and
                    self.bss_paddr < prog_limit):
                raise LinkError(
                    "unmappable layout: prog region [%#x, %#x) overlaps ram "
                    "region [%#x, %#x)"
                    % (self.text_paddr, prog_limit, self.bss_paddr,
                       ram_limit))

        # Build the output sections in the TI order.
        self._add_alloc(".text", self.text_paddr, S_TEXT)
        self._add_alloc(".data", self.data_paddr, S_DATA)
        if self.has_cinit:
            self._add_alloc(".cinit", self.cinit_paddr, S_DATA)
        self._add_bss()

        debug_objects = [obj for obj in self.objects
                         if any(s.is_debug for s in obj.sections)]
        if debug_objects:
            # Build the merged debug sections (and their placements) in every
            # mode: with --strip-debug the relocation pass still resolves the
            # debug references so a dangling one stays loud, it just does not
            # write the discarded section bytes.
            self._add_debug(debug_objects)

    def _add_alloc(self, name, paddr, flags):
        data = bytearray()
        bitoff = 0
        for obj in self.objects:
            sec = obj.section_by_name.get(name)
            if sec is None:
                continue
            if bitoff % 16:
                raise LinkError("%s concatenation offset %d is not word "
                                "aligned" % (name, bitoff))
            out = OutSection(name, paddr, b"", size=self._total_size(name),
                             flags=flags)
            # Fill after all placements are known; count input bytes now.
            self.placements[(obj.path, name)] = (out, bitoff)
            data.extend(sec.data)
            bitoff += sec.size
        if bitoff != self._total_size(name):
            raise LinkError("internal: %s size mismatch" % name)
        out = OutSection(name, paddr, data, size=bitoff, flags=flags)
        self._register(out)
        # Replace the placeholder OutSection so every placement points at the
        # final object (it has the data).
        for obj in self.objects:
            key = (obj.path, name)
            if key in self.placements:
                _old, off = self.placements[key]
                self.placements[key] = (out, off)

    def _add_bss(self):
        out = OutSection(".bss", self.bss_paddr, b"", size=self.bss_size,
                         flags=S_BSS)
        self._register(out)
        bitoff = 0
        for obj in self.objects:
            sec = obj.section_by_name.get(".bss")
            if sec is None:
                continue
            self.placements[(obj.path, ".bss")] = (out, bitoff)
            bitoff += sec.size
        if bitoff != self.bss_size:
            raise LinkError("internal: .bss size mismatch")

    def _add_debug(self, objects):
        """Merge every debug-bearing object's ``.debug_*`` sections.

        Each output section is the concatenation of the inputs' same-named
        sections in object order.  The placement recorded for an object is its
        byte base inside the merged section (in bits), which is what
        ``_reloc_value`` adds to a section-relative debug reference.  With one
        object every base is 0, so the M7 single-TU bytes are unchanged.
        """
        merged = {}
        order = []
        multi = len(objects) > 1
        validate = multi and self.args.keep_debug
        for obj in objects:
            for sec in obj.sections:
                if not sec.is_debug or sec.name in merged:
                    continue
                if validate and sec.name not in DEBUG_CONCAT_SECTIONS:
                    raise LinkError(
                        "%s: cannot merge debug section %s from multiple "
                        "objects (unsupported shape)" % (obj.path, sec.name))
                out = OutSection(sec.name, 0, b"", size=0, flags=0, vaddr=0,
                                 debug=True)
                merged[sec.name] = out
                order.append(out)
        for obj in objects:
            for sec in obj.sections:
                if not sec.is_debug:
                    continue
                if validate and sec.name in (".debug_str",
                                             ".debug_line_str") \
                        and sec.data and not sec.data.endswith(b"\0"):
                    raise LinkError(
                        "%s: %s does not end with NUL; concatenating it "
                        "would merge strings" % (obj.path, sec.name))
                out = merged[sec.name]
                if len(out.data) * 8 != out.size:
                    raise LinkError("internal: %s merge size mismatch"
                                    % sec.name)
                base = len(out.data)
                self.placements[(obj.path, sec.name)] = (out, base * 8)
                out.data.extend(sec.data)
                out.size = len(out.data) * 8
        if validate:
            for obj in objects:
                for sec in obj.sections:
                    if sec.is_debug and sec.name in (
                            ".debug_info", ".debug_line", ".debug_str_offsets",
                            ".debug_addr", ".debug_loclists",
                            ".debug_rnglists"):
                        self._check_debug_unit_chain(obj, sec)
            self._patch_raw_debug_offsets(objects)
        if self.args.keep_debug:
            for out in order:
                self._register(out)

    @staticmethod
    def _check_debug_unit_chain(obj, sec):
        """Every unit in a concatenated debug section must be self-contained."""
        data = sec.data
        pos = 0
        while pos < len(data):
            if pos + 4 > len(data):
                raise LinkError("%s: %s has a truncated unit header at %#x"
                                % (obj.path, sec.name, pos))
            unit_length = struct.unpack_from("<I", data, pos)[0]
            if unit_length == 0xFFFFFFFF:
                raise LinkError(
                    "%s: 64-bit DWARF %s is not supported in a multi-object "
                    "link" % (obj.path, sec.name))
            unit_end = pos + 4 + unit_length
            if unit_end > len(data):
                raise LinkError(
                    "%s: %s unit at %#x has length %d, past the %d-byte "
                    "section" % (obj.path, sec.name, pos, unit_length,
                                 len(data)))
            pos = unit_end

    def _patch_raw_debug_offsets(self, objects):
        """Patch raw (non-relocated) CU debug_abbrev_offset fields.

        LLVM 23.1.5 objects relocate the field, but a producer may leave it
        raw as the section-relative offset 0.  When a CU header field has no
        relocation covering it, add the object's merged .debug_abbrev base.
        DWARF64 units are refused: they are not the inspected shape.
        """
        for obj in objects:
            info = obj.section_by_name.get(".debug_info")
            if info is None:
                continue
            info_out, info_base = self.placements[(obj.path, ".debug_info")]
            abbrev = obj.section_by_name.get(".debug_abbrev")
            if abbrev is None:
                continue
            _, abbrev_base = self.placements[(obj.path, ".debug_abbrev")]
            if info_base % 8 or abbrev_base % 8:
                raise LinkError("internal: debug section base is not byte "
                                "aligned")
            relocated = {rel.raddr // 8 for rel in info.relocs}
            data = info.data
            pos = 0
            while pos < len(data):
                if pos + 4 > len(data):
                    raise LinkError("%s: .debug_info unit header is truncated"
                                    % obj.path)
                unit_length = struct.unpack_from("<I", data, pos)[0]
                if unit_length == 0xFFFFFFFF:
                    raise LinkError(
                        "%s: 64-bit DWARF .debug_info is not supported in a "
                        "multi-object link" % obj.path)
                unit_end = pos + 4 + unit_length
                if unit_length < 6 or unit_end > len(data):
                    raise LinkError("%s: .debug_info unit at %#x has invalid "
                                    "length %d" % (obj.path, pos, unit_length))
                version = struct.unpack_from("<H", data, pos + 4)[0]
                if version >= 5:
                    field = pos + 8          # unit_type, address_size first
                elif version >= 2:
                    field = pos + 6
                else:
                    raise LinkError("%s: .debug_info unit at %#x has "
                                    "unsupported DWARF version %d"
                                    % (obj.path, pos, version))
                if field + 4 > unit_end:
                    raise LinkError("%s: .debug_info unit at %#x is too short "
                                    "for its CU header" % (obj.path, pos))
                if field not in relocated and abbrev_base:
                    old = struct.unpack_from("<I", data, field)[0]
                    _put_u32(info_out.data, info_base // 8 + field,
                             old + abbrev_base // 8)
                pos = unit_end

    def _register(self, sec):
        self.out_sections.append(sec)
        self.out_index[sec.name] = len(self.out_sections)

    # -- symbol helpers --------------------------------------------------

    def _section_of(self, obj, sym):
        sec = obj.section_by_no.get(sym.secno)
        if sec is None:
            raise LinkError("%s: symbol '%s' has section number %d, which "
                            "does not exist" % (obj.path, sym.name, sym.secno))
        return sec

    def _definition_bits(self, obj, sym):
        """Absolute bit value of a defined symbol, or DebugValue for debug."""
        if sym.is_absolute:
            return ("absolute", sym.value)
        sec = self._section_of(obj, sym)
        if sec.is_debug:
            key = (obj.path, sec.name)
            if key not in self.placements:
                raise LinkError(
                    "symbol '%s' is in debug section %s, which has no merged "
                    "placement (was it stripped?)" % (sym.name, sec.name))
            _out, base = self.placements[key]
            return ("debug", base + sym.value)
        key = (obj.path, sec.name)
        if key not in self.placements:
            raise LinkError(
                "symbol '%s' is in section %s, which was omitted because it "
                "is an empty .cinit" % (sym.name, sec.name))
        out, bitoff = self.placements[key]
        return ("allocated", out.paddr + bitoff + sym.value)

    def _resolve_definition(self, obj, sym, containing_debug, addend):
        kind, base = self._definition_bits(obj, sym)
        if kind == "debug":
            if not containing_debug:
                raise LinkError(
                    "allocated relocation cannot target debug symbol '%s' in "
                    "%s" % (sym.name, obj.path))
            # Debug sections are section-relative: the target's merged base
            # (0 for the first/single object) plus the field's byte addend,
            # which already includes any symbol offset.
            if base % 8:
                raise LinkError(
                    "cannot represent bit offset %#x of debug symbol '%s' "
                    "in a debug section (not byte aligned)"
                    % (base, sym.name))
            return base // 8 + addend
        bits = base
        if containing_debug:
            if bits % 8:
                raise LinkError(
                    "cannot represent bit address %#x of '%s' in a debug "
                    "section (not byte aligned)" % (bits, sym.name))
            return bits // 8 + addend
        return bits + addend

    def _resolve_external(self, obj, sym, containing_debug, addend):
        if sym.name not in self.global_defs:
            raise LinkError("undefined external '%s' referenced by %s"
                            % (sym.name, obj.path))
        dobj, dsym = self.global_defs[sym.name]
        return self._resolve_definition(dobj, dsym, containing_debug, addend)

    def _reloc_value(self, obj, sec, rel, containing_debug):
        # TI-COFF relocation fields carry a signed 32-bit addend; negative
        # offsets occur for e.g. a pointer to an array element before a symbol.
        addend = _s32(sec.data, rel.raddr // 8)
        if rel.symidx == 0xFFFF:
            if containing_debug:
                _out, off = self.placements[(obj.path, sec.name)]
                return off // 8 + addend
            out, off = self.placements[(obj.path, sec.name)]
            return out.paddr + off + addend

        sym = obj.symbols_by_index.get(rel.symidx)
        if sym is None:
            raise LinkError("%s: %s relocation refers to missing symbol "
                            "record %d" % (obj.path, sec.name, rel.symidx))

        if sym.is_section:
            tsec = self._section_of(obj, sym)
            if containing_debug:
                if tsec.is_debug:
                    _out, off = self.placements[(obj.path, tsec.name)]
                    if off % 8 or sym.value % 8:
                        raise LinkError(
                            "cannot represent debug target section %s at "
                            "bit offset %#x (not byte aligned)"
                            % (tsec.name, off + sym.value))
                    return off // 8 + sym.value // 8 + addend
                out, off = self.placements[(obj.path, tsec.name)]
                base = out.paddr + off
                if base % 8:
                    raise LinkError(
                        "section %s origin %#x is not byte aligned"
                        % (tsec.name, base))
                return base // 8 + addend
            if tsec.is_debug:
                raise LinkError(
                    "allocated relocation cannot target debug section '%s' "
                    "in %s" % (tsec.name, obj.path))
            out, off = self.placements[(obj.path, tsec.name)]
            return out.paddr + off + addend

        if sym.is_defined or sym.is_absolute:
            return self._resolve_definition(obj, sym, containing_debug, addend)
        if sym.secno == 0:
            return self._resolve_external(obj, sym, containing_debug, addend)
        raise LinkError("%s: symbol '%s' has unsupported section number %d"
                        % (obj.path, sym.name, sym.secno))

    # -- relocation application -----------------------------------------

    def apply_relocations(self):
        for obj in self.objects:
            for sec in obj.sections:
                if not sec.relocs:
                    continue
                containing_debug = sec.is_debug
                if containing_debug and not self.args.keep_debug:
                    # Still resolve to catch a dangling reference, but do not
                    # write into a discarded section.
                    target_data = None
                else:
                    out, bitoff = self.placements[(obj.path, sec.name)]
                    target_data = out.data
                    if bitoff % 8:
                        raise LinkError(
                            "internal: %s input offset %d is not byte aligned"
                            % (sec.name, bitoff))
                for rel in sec.relocs:
                    value = self._reloc_value(obj, sec, rel, containing_debug)
                    if target_data is not None:
                        off = bitoff // 8 + rel.raddr // 8
                        _put_u32(target_data, off, value)

    # -- output symbols and map -----------------------------------------

    def _section_symbols(self):
        syms = []
        for sec in self.out_sections:
            aux = struct.pack("<III", sec.size, 0, 0)
            aux = aux.ljust(18, b"\0")
            value = 0 if sec.debug else sec.paddr
            syms.append(OutSymbol(sec.name, value, self.out_index[sec.name],
                                  C_STAT, naux=1, aux=aux))
        return syms

    def build_symbols(self):
        out = []
        # Preserve .file records if an input has them.  No current llc/GSPA
        # fixture emits C_FILE, so this copy is untested (and GSPLNK itself
        # does not synthesize .file records).
        for obj in self.objects:
            for sym in obj.symbols:
                if sym.is_file:
                    out.append(OutSymbol(sym.name, sym.value, sym.secno,
                                         sym.sclass, sym.type, sym.naux,
                                         sym.aux))

        out.extend(self._section_symbols())

        seen_global = set()
        for obj in self.objects:
            for sym in obj.symbols:
                if sym.is_section or sym.is_file:
                    continue
                if sym.secno <= 0 and not sym.is_absolute:
                    continue
                if sym.is_global and sym.name in seen_global:
                    continue
                if sym.is_global:
                    seen_global.add(sym.name)
                if sym.is_absolute:
                    if sym.is_global:
                        out.append(OutSymbol(sym.name, sym.value, SEC_ABS,
                                             C_EXT, sym.type))
                    continue
                sec = self._section_of(obj, sym)
                if sec.is_debug and not self.args.keep_debug:
                    continue
                if sec.is_debug:
                    outsec = None
                    for cand in self.out_sections:
                        if cand.name == sec.name:
                            outsec = cand
                            break
                    if outsec is None:
                        continue
                    secno = self.out_index[outsec.name]
                    _osc, base = self.placements[(obj.path, sec.name)]
                    value = base + sym.value
                else:
                    key = (obj.path, sec.name)
                    if key not in self.placements:
                        # A symbol in a listed-but-empty .cinit whose section
                        # was omitted (GSPLNK emits no such symbol either).
                        continue
                    osc, bitoff = self.placements[key]
                    value = osc.paddr + bitoff + sym.value
                    secno = self.out_index[osc.name]
                sclass = C_EXT if sym.is_global else sym.sclass
                out.append(OutSymbol(sym.name, value, secno, sclass,
                                     sym.type))

        def ensure(name, value, secno):
            if name in seen_global:
                return
            seen_global.add(name)
            out.append(OutSymbol(name, value, secno, C_EXT))

        text_idx = self.out_index[".text"]
        data_idx = self.out_index[".data"]
        bss_idx = self.out_index[".bss"]
        ensure(".text", self.text_paddr, text_idx)
        ensure("etext", self.text_end, text_idx)
        ensure(".data", self.data_paddr, data_idx)
        ensure("edata", self.data_end, data_idx)
        ensure(".bss", self.bss_paddr, bss_idx)
        ensure("end", self.bss_end, bss_idx)
        if self.has_cinit:
            # The spec makes the linker define the public cinit symbol; a real
            # definition in the input wins.
            ensure("cinit", self.cinit_paddr, self.out_index[".cinit"])

        self.out_symbols = out

    def entry(self):
        name = self.args.entry

        def find(want):
            for sym in self.out_symbols:
                if (sym.name == want and sym.sclass != C_FILE and
                        sym.secno > 0):
                    return sym
            return None

        if name is not None:
            found = find(name)
            if found is None:
                raise LinkError("entry symbol '%s' is not defined" % name)
            return found.name, found.value
        # No explicit entry: use _start if present, else the text origin.
        found = find("_start")
        if found is not None:
            return "_start", found.value
        return "", self.text_paddr

    def write_map(self, path, entry_name, entry_value):
        lines = []
        lines.append("OUTPUT FILE NAME:   <%s>" % os.path.basename(self.args.out))
        lines.append('ENTRY POINT SYMBOL: "%s"  address: %08X'
                     % (entry_name, entry_value))
        lines.append("")
        lines.append("SECTION ALLOCATION MAP")
        for sec in self.out_sections:
            lines.append("%08X %s" % (sec.paddr, sec.name))
            if sec.debug and sec.size:
                lines.append("%08X %s.size.bits"
                             % (sec.size, sec.name))
        lines.append("")
        lines.append("GLOBAL SYMBOLS")
        for sym in self.out_symbols:
            if sym.sclass != C_EXT or sym.secno == 0:
                continue
            lines.append("%08X %s" % (sym.value & 0xFFFFFFFF, sym.name))
        lines.append("")
        try:
            with open(path, "w", encoding="latin1", newline="\n") as fh:
                fh.write("\n".join(lines))
        except OSError as exc:
            raise LinkError("%s: cannot write map: %s" % (path, exc)) from exc

    # -- top level -------------------------------------------------------

    def run(self):
        self.load()
        self._collect_globals()
        self._extract_archive_members()
        self.layout()
        self.apply_relocations()
        self.build_symbols()
        entry_name, entry_value = self.entry()
        try:
            write_coff(self.args.out, self.out_sections, self.out_symbols,
                       entry=entry_value, text_size=self.text_size,
                       data_size=self.data_size, bss_size=self.bss_size,
                       text_start=self.text_paddr,
                       data_start=self.data_paddr)
        except CoffError as exc:
            raise LinkError(str(exc)) from exc
        if self.args.map:
            self.write_map(self.args.map, entry_name, entry_value)
        return 0


def build_parser():
    p = argparse.ArgumentParser(
        prog="tms-link",
        description="Native TI-COFF linker for the TMS34010 (M7.2)"
    )
    p.add_argument("-o", "--output", dest="out", required=True,
                   metavar="OUT", help="linked COFF output")
    p.add_argument("--map", dest="map", metavar="MAP",
                   help="write a GSPLNK-style map")
    p.add_argument("--entry", dest="entry", metavar="SYM",
                   help="entry point symbol (default: _start if defined)")
    p.add_argument("--text", dest="text", type=parse_addr, default=DEFAULT_TEXT,
                   metavar="ADDR", help=".text bit origin (default 018A0000)")
    p.add_argument("--data", dest="data", type=parse_addr, default=None,
                   metavar="ADDR",
                   help=".data bit origin (default: after .text)")
    p.add_argument("--cinit", dest="cinit", type=parse_addr, default=None,
                   metavar="ADDR",
                   help=".cinit bit origin (default: after .data)")
    p.add_argument("--bss", dest="bss", type=parse_addr, default=DEFAULT_BSS,
                   metavar="ADDR", help=".bss bit origin (default 01A00000)")
    p.add_argument("--prog-len", dest="prog_len", type=parse_addr,
                   default=None, metavar="BITS",
                   help="prog region length in bits, starting at --text "
                        "(bounds .text/.data/.cinit)")
    p.add_argument("--ram-len", dest="ram_len", type=parse_addr,
                   default=None, metavar="BITS",
                   help="ram region length in bits, starting at --bss "
                        "(bounds .bss)")
    dbg = p.add_mutually_exclusive_group()
    dbg.add_argument("--keep-debug", dest="keep_debug", action="store_true",
                     help="keep .debug_* sections from every debug-bearing "
                          "object, merged in object order")
    dbg.add_argument("--strip-debug", dest="keep_debug", action="store_false",
                     help="strip .debug_* sections (default)")
    p.set_defaults(keep_debug=False)
    p.add_argument("-L", dest="lib_dirs", action="append", default=[],
                   metavar="DIR", help="add DIR to the -l library search path")
    p.add_argument("-l", dest="libraries", action="append", default=[],
                   metavar="LIB",
                   help="link archive LIB (also -lLIB); searched in ., -L "
                        "directories and beside the other inputs.  Archives "
                        "and libraries are processed after all explicit "
                        "positional objects, whatever their order")
    p.add_argument("objects", nargs="+", metavar="OBJ|LIB",
                   help="relocatable TI-COFF objects or ar archives")
    return p


def main(argv=None):
    args = build_parser().parse_args(argv)
    try:
        return Linker(args).run()
    except LinkError as exc:
        print("tms-link: error: %s" % exc, file=sys.stderr)
        return 1
    except CoffError as exc:
        print("tms-link: error: %s" % exc, file=sys.stderr)
        return 1


if __name__ == "__main__":
    sys.exit(main())
