#!/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.  The DWARF walkers
# (_check_debug_info/_check_debug_line/_check_debug_list and the .debug_addr/
# .debug_str_offsets entry checks) enforce the relocation coverage instead of
# assuming it.
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)."""


# -- DWARF input-gate constants ---------------------------------------------
#
# The multi-object merge copies each object's debug bytes verbatim, so every
# field whose value is relative to the start of a debug section must be
# rewritten by a relocation.  ``_check_debug_references`` walks the sections
# and requires that coverage; the one exception is the CU header's
# ``debug_abbrev_offset``, which ``_patch_raw_debug_offsets`` patches in place.

DW_UT_COMPILE = 0x01
DW_UT_PARTIAL = 0x03

DW_FORM_ADDR = 0x01
DW_FORM_BLOCK2 = 0x03
DW_FORM_BLOCK4 = 0x04
DW_FORM_DATA2 = 0x05
DW_FORM_DATA4 = 0x06
DW_FORM_DATA8 = 0x07
DW_FORM_STRING = 0x08
DW_FORM_BLOCK = 0x09
DW_FORM_BLOCK1 = 0x0A
DW_FORM_DATA1 = 0x0B
DW_FORM_FLAG = 0x0C
DW_FORM_SDATA = 0x0D
DW_FORM_STRP = 0x0E
DW_FORM_UDATA = 0x0F
DW_FORM_REF_ADDR = 0x10
DW_FORM_REF1 = 0x11
DW_FORM_REF2 = 0x12
DW_FORM_REF4 = 0x13
DW_FORM_REF8 = 0x14
DW_FORM_REF_UDATA = 0x15
DW_FORM_INDIRECT = 0x16
DW_FORM_SEC_OFFSET = 0x17
DW_FORM_EXPRLOC = 0x18
DW_FORM_FLAG_PRESENT = 0x19
DW_FORM_STRX = 0x1A
DW_FORM_ADDRX = 0x1B
DW_FORM_REF_SUP4 = 0x1C
DW_FORM_STRP_SUP = 0x1D
DW_FORM_DATA16 = 0x1E
DW_FORM_LINE_STRP = 0x1F
DW_FORM_REF_SIG8 = 0x20
DW_FORM_IMPLICIT_CONST = 0x21
DW_FORM_LOCLISTX = 0x22
DW_FORM_RNGLISTX = 0x23
DW_FORM_REF_SUP8 = 0x24
DW_FORM_STRX1 = 0x25
DW_FORM_STRX2 = 0x26
DW_FORM_STRX3 = 0x27
DW_FORM_STRX4 = 0x28
DW_FORM_ADDRX1 = 0x29
DW_FORM_ADDRX2 = 0x2A
DW_FORM_ADDRX3 = 0x2B
DW_FORM_ADDRX4 = 0x2C
# GNU extensions seen in the wild (.debug_info only).
DW_FORM_GNU_REF_ALT = 0x1F20
DW_FORM_GNU_STRP_ALT = 0x1F21

# Forms that must be covered by a relocation in a multi-object merge:
# `DW_FORM_addr` is an absolute address and the rest are offsets from the
# start of another debug section.  Concatenating debug sections changes those
# bases (and the linked image changes addresses), so a raw field is silently
# wrong.  The CU abbrev offset is the separate documented exception.
# `DW_FORM_ref_sup*`/`strp_sup`/GNU `*_alt` are deliberately absent: they
# reference the supplementary/alternate object file, not the sections being
# concatenated, so they need no rehoming here (and non-compile unit types,
# where they can appear, are refused below).
REQUIRED_RELOC_FORMS = {
    DW_FORM_ADDR: "DW_FORM_addr",
    DW_FORM_STRP: "DW_FORM_strp",
    DW_FORM_REF_ADDR: "DW_FORM_ref_addr",
    DW_FORM_SEC_OFFSET: "DW_FORM_sec_offset",
    DW_FORM_LINE_STRP: "DW_FORM_line_strp",
}


ATTR_NAMES = {
    0x03: "DW_AT_name",
    0x10: "DW_AT_stmt_list",
    0x11: "DW_AT_low_pc",
    0x12: "DW_AT_high_pc",
    0x1B: "DW_AT_comp_dir",
    0x25: "DW_AT_producer",
    0x31: "DW_AT_abstract_origin",
    0x40: "DW_AT_frame_base",
    0x55: "DW_AT_ranges",
    0x72: "DW_AT_str_offsets_base",
    0x73: "DW_AT_addr_base",
    0x74: "DW_AT_rnglists_base",
    0x8C: "DW_AT_loclists_base",
}

DW_RLE_BASE_ADDRESSX = 0x01
DW_RLE_STARTX_ENDX = 0x02
DW_RLE_STARTX_LENGTH = 0x03
DW_RLE_OFFSET_PAIR = 0x04
DW_RLE_BASE_ADDRESS = 0x05
DW_RLE_START_END = 0x06
DW_RLE_START_LENGTH = 0x07

DW_LLE_BASE_ADDRESSX = 0x01
DW_LLE_STARTX_ENDX = 0x02
DW_LLE_STARTX_LENGTH = 0x03
DW_LLE_OFFSET_PAIR = 0x04
DW_LLE_DEFAULT_LOCATION = 0x05
DW_LLE_BASE_ADDRESS = 0x06
DW_LLE_START_END = 0x07
DW_LLE_START_LENGTH = 0x08
DW_LLE_GNU_VIEW_PAIR = 0x09


class _DwarfReader:
    """A bounded, little-endian DWARF byte reader with loud truncation."""

    __slots__ = ("data", "pos", "end", "where")

    def __init__(self, data, pos, end, where):
        self.data = data
        self.pos = pos
        self.end = end
        self.where = where

    def fail(self, msg):
        raise LinkError("%s at byte %#x: %s" % (self.where, self.pos, msg))

    def need(self, n):
        if self.pos + n > self.end:
            self.fail("truncated (need %d byte(s), %d remain)"
                      % (n, self.end - self.pos))

    def skip(self, n):
        self.need(n)
        self.pos += n

    def u8(self):
        self.need(1)
        value = self.data[self.pos]
        self.pos += 1
        return value

    def u16(self):
        self.need(2)
        value = struct.unpack_from("<H", self.data, self.pos)[0]
        self.pos += 2
        return value

    def u32(self):
        self.need(4)
        value = struct.unpack_from("<I", self.data, self.pos)[0]
        self.pos += 4
        return value

    def cstr(self):
        end = self.data.find(b"\0", self.pos, self.end)
        if end < 0:
            self.fail("unterminated string")
        self.pos = end + 1

    def uleb(self):
        value = 0
        shift = 0
        while True:
            byte = self.u8()
            value |= (byte & 0x7F) << shift
            if not byte & 0x80:
                return value
            shift += 7
            if shift > 63:
                self.fail("overlong LEB128 value")

    def sleb(self):
        value = 0
        shift = 0
        while True:
            byte = self.u8()
            value |= (byte & 0x7F) << shift
            shift += 7
            if not byte & 0x80:
                if byte & 0x40:
                    value -= 1 << shift
                return value
            if shift > 63:
                self.fail("overlong SLEB128 value")


def _read_form(reader, form, address_size):
    """Consume one attribute value.

    Returns ``(resolved_form, value_start, value_size)``.  ``DW_FORM_indirect``
    resolves to the inner form; the returned span is the value itself, not the
    form selector, so a relocation must cover that span's start.
    """
    if form == DW_FORM_INDIRECT:
        return _read_form(reader, reader.uleb(), address_size)
    start = reader.pos
    if form == DW_FORM_ADDR:
        reader.skip(address_size)
    elif form == DW_FORM_BLOCK2:
        reader.skip(reader.u16())
    elif form == DW_FORM_BLOCK4:
        reader.skip(reader.u32())
    elif form == DW_FORM_BLOCK:
        reader.skip(reader.uleb())
    elif form == DW_FORM_BLOCK1:
        reader.skip(reader.u8())
    elif form == DW_FORM_EXPRLOC:
        reader.skip(reader.uleb())
    elif form == DW_FORM_DATA2:
        reader.skip(2)
    elif form == DW_FORM_DATA4:
        reader.skip(4)
    elif form in (DW_FORM_DATA8, DW_FORM_REF_SIG8):
        reader.skip(8)
    elif form == DW_FORM_DATA16:
        reader.skip(16)
    elif form in (DW_FORM_DATA1, DW_FORM_FLAG, DW_FORM_REF1, DW_FORM_STRX1,
                  DW_FORM_ADDRX1):
        reader.skip(1)
    elif form in (DW_FORM_REF2, DW_FORM_STRX2, DW_FORM_ADDRX2):
        reader.skip(2)
    elif form in (DW_FORM_REF4, DW_FORM_STRP, DW_FORM_REF_ADDR,
                  DW_FORM_SEC_OFFSET, DW_FORM_STRP_SUP, DW_FORM_LINE_STRP,
                  DW_FORM_REF_SUP4, DW_FORM_STRX4, DW_FORM_ADDRX4,
                  DW_FORM_GNU_REF_ALT, DW_FORM_GNU_STRP_ALT):
        reader.skip(4)
    elif form in (DW_FORM_REF8, DW_FORM_REF_SUP8):
        reader.skip(8)
    elif form in (DW_FORM_STRX3, DW_FORM_ADDRX3):
        reader.skip(3)
    elif form == DW_FORM_STRING:
        reader.cstr()
    elif form == DW_FORM_SDATA:
        reader.sleb()
    elif form in (DW_FORM_UDATA, DW_FORM_REF_UDATA, DW_FORM_STRX,
                  DW_FORM_ADDRX, DW_FORM_LOCLISTX, DW_FORM_RNGLISTX):
        reader.uleb()
    elif form in (DW_FORM_FLAG_PRESENT, DW_FORM_IMPLICIT_CONST):
        pass
    else:
        reader.fail("unsupported DWARF form %#x" % form)
    return form, start, reader.pos - start


def _parse_abbreviations(data, offset, where):
    """Parse one abbreviation table; ``offset`` is section-relative."""
    if offset > len(data):
        raise LinkError("%s: abbreviation offset %#x is past the %d-byte "
                        "section" % (where, offset, len(data)))
    reader = _DwarfReader(data, offset, len(data), where)
    table = {}
    while True:
        code = reader.uleb()
        if code == 0:
            break
        if code in table:
            reader.fail("duplicate abbreviation code %d" % code)
        tag = reader.uleb()
        children = reader.u8()
        attrs = []
        while True:
            attr = reader.uleb()
            form = reader.uleb()
            if attr == 0 and form == 0:
                break
            implicit = None
            if form == DW_FORM_IMPLICIT_CONST:
                implicit = reader.sleb()
            attrs.append((attr, form, implicit))
        table[code] = (tag, children, attrs)
    return table


def _dwarf_unit(data, pos, where):
    """Return ``(unit_length, unit_end)`` for a bounded DWARF32 unit."""
    if pos + 4 > len(data):
        raise LinkError("%s: truncated unit header at %#x" % (where, pos))
    unit_length = struct.unpack_from("<I", data, pos)[0]
    if unit_length == 0xFFFFFFFF:
        raise LinkError("%s: 64-bit DWARF units are not supported in a "
                        "multi-object link" % where)
    unit_end = pos + 4 + unit_length
    if unit_end > len(data):
        raise LinkError("%s: unit at %#x ends past the section"
                        % (where, pos))
    return unit_length, unit_end


def _require_relocation(relocated, start, size, where, what):
    """Every required field must be covered by whole 4-byte relocation(s)."""
    covered = (size > 0 and size % 4 == 0 and
               all(start + offset in relocated
                   for offset in range(0, size, 4)))
    if covered:
        return
    raise LinkError(
        "%s: unrelocated %s at byte %#x; the multi-object debug merge cannot "
        "rehome it (the producer must emit an R-RELLONG relocation for every "
        "section-relative field)" % (where, what, start))


def _check_debug_info(obj, sec, relocated):
    """Walk each CU's DIEs and require relocations on required fields."""
    data = sec.data
    abbrev = obj.section_by_name.get(".debug_abbrev")
    where = "%s: %s" % (obj.path, sec.name)
    pos = 0
    while pos < len(data):
        _unit_length, unit_end = _dwarf_unit(data, pos, where)
        header = _DwarfReader(data, pos + 4, unit_end, where)
        version = header.u16()
        if version < 5:
            raise LinkError(
                "%s: unit at %#x has DWARF version %d; a multi-object "
                "--keep-debug link requires DWARF v5 (a pre-v5 "
                "DW_AT_stmt_list uses DW_FORM_data4/data8, which the merge "
                "cannot rehome)" % (where, pos, version))
        unit_type = header.u8()
        address_size = header.u8()
        if unit_type not in (DW_UT_COMPILE, DW_UT_PARTIAL):
            raise LinkError(
                "%s: unit at %#x has unsupported DWARF unit type %#x"
                % (where, pos, unit_type))
        abbrev_offset = header.u32()
        if address_size != 4:
            raise LinkError(
                "%s: unit at %#x has address size %d; the link format only "
                "represents 32-bit DWARF addresses"
                % (where, pos, address_size))
        if abbrev is None:
            raise LinkError("%s: unit at %#x has no .debug_abbrev section"
                            % (where, pos))
        table = _parse_abbreviations(
            abbrev.data, abbrev_offset,
            "%s: .debug_abbrev" % obj.path)
        reader = _DwarfReader(data, header.pos, unit_end,
                              "%s (unit at %#x)" % (where, pos))
        while reader.pos < unit_end:
            die_offset = reader.pos
            code = reader.uleb()
            if code == 0:
                continue
            entry = table.get(code)
            if entry is None:
                raise LinkError(
                    "%s: DIE at %#x uses undefined abbreviation code %d"
                    % (where, die_offset, code))
            _tag, _children, attrs = entry
            for attr, form, _implicit in attrs:
                form, start, size = _read_form(reader, form, address_size)
                if form not in REQUIRED_RELOC_FORMS:
                    continue
                what = "%s for %s" % (
                    REQUIRED_RELOC_FORMS[form],
                    ATTR_NAMES.get(attr, "DW_AT_%#x" % attr))
                _require_relocation(relocated, start, size,
                                    "%s (DIE at %#x)" % (where, die_offset),
                                    what)
        pos = unit_end


def _check_debug_line(obj, sec, relocated):
    """Walk DWARF v5 line-table directory/file formats for required fields."""
    data = sec.data
    where = "%s: %s" % (obj.path, sec.name)
    pos = 0
    while pos < len(data):
        _unit_length, unit_end = _dwarf_unit(data, pos, where)
        reader = _DwarfReader(data, pos + 4, unit_end, where)
        version = reader.u16()
        if version < 5:
            raise LinkError(
                "%s: line unit at %#x has DWARF version %d; a multi-object "
                "--keep-debug link requires DWARF v5 (pre-v5 line headers "
                "have only inline strings and a data4 stmt_list)"
                % (where, pos, version))
        if version >= 5:
            address_size = reader.u8()
            reader.u8()                   # segment_selector_size
            if address_size != 4:
                raise LinkError(
                    "%s: line unit at %#x has address size %d; the link "
                    "format only represents 32-bit DWARF addresses"
                    % (where, pos, address_size))
            header_length = reader.u32()
            header_end = reader.pos + header_length
            if header_end > unit_end:
                raise LinkError("%s: unit at %#x has a header past its end"
                                % (where, pos))
            head = _DwarfReader(data, reader.pos, header_end,
                               "%s (unit at %#x)" % (where, pos))
            head.u8()                     # minimum_instruction_length
            if version >= 4:
                head.u8()                 # maximum_operations_per_instruction
            head.u8()                     # default_is_stmt
            # LLVM's MC writer emits line_base as a plain int8 (DWARF says
            # SLEB128) and its own reader consumes one byte; follow the pinned
            # producer so 0xfb means -5 rather than an overlong SLEB128.
            head.u8()                     # line_base (int8)
            head.u8()                     # line_range
            opcode_base = head.u8()
            if opcode_base < 1:
                raise LinkError("%s: line unit at %#x has opcode_base 0"
                                % (where, pos))
            head.skip(opcode_base - 1)    # standard_opcode_lengths
            for kind in ("directory", "file"):
                format_count = head.u8()
                formats = [(head.uleb(), head.uleb())
                           for _ in range(format_count)]
                entry_count = head.uleb()
                for index in range(entry_count):
                    for content_type, form in formats:
                        form, start, size = _read_form(head, form,
                                                       address_size)
                        if form not in REQUIRED_RELOC_FORMS:
                            continue
                        what = "%s for line-table %s entry %d content %#x" % (
                            REQUIRED_RELOC_FORMS[form], kind, index,
                            content_type)
                        _require_relocation(relocated, start, size,
                                            "%s (line unit at %#x)"
                                            % (where, pos), what)
            if head.pos != header_end:
                raise LinkError(
                    "%s: line unit at %#x has an inconsistent header length "
                    "(%#x bytes parsed, %#x declared)"
                    % (where, pos, head.pos, header_end))
        pos = unit_end


def _check_debug_list(obj, sec, relocated, ranges):
    """Walk .debug_rnglists/.debug_loclists entries.

    Section-relative list offsets are self-relative and stay valid when a
    whole unit is copied.  Absolute address fields, however, still need their
    relocated .text/.data value, and the indexed (``startx_*``) forms need a
    relocated .debug_addr entry (checked separately).
    """
    data = sec.data
    where = "%s: %s" % (obj.path, sec.name)
    pos = 0
    while pos < len(data):
        _unit_length, unit_end = _dwarf_unit(data, pos, where)
        reader = _DwarfReader(data, pos + 4, unit_end,
                              "%s (unit at %#x)" % (where, pos))
        version = reader.u16()
        if version != 5:
            raise LinkError("%s: unit at %#x has DWARF version %d; only v5 "
                            "list sections are supported in a multi-object "
                            "link" % (where, pos, version))
        address_size = reader.u8()
        reader.u8()                       # segment_selector_size
        if address_size != 4:
            raise LinkError(
                "%s: unit at %#x has address size %d; the link format only "
                "represents 32-bit DWARF addresses"
                % (where, pos, address_size))
        reader.skip(reader.u32() * 4)     # offset_entry_count / offset entries

        def address(kind, list_at):
            start = reader.pos
            reader.skip(address_size)
            _require_relocation(relocated, start, address_size,
                                "%s (list at %#x)" % (where, list_at),
                                "absolute address for %s" % kind)

        while reader.pos < unit_end:
            list_at = reader.pos
            kind = reader.u8()
            if kind == 0:
                continue
            if ranges:
                if kind == DW_RLE_BASE_ADDRESSX:
                    reader.uleb()
                elif kind in (DW_RLE_STARTX_ENDX, DW_RLE_OFFSET_PAIR):
                    reader.uleb()
                    reader.uleb()
                elif kind == DW_RLE_STARTX_LENGTH:
                    reader.uleb()
                    reader.uleb()
                elif kind == DW_RLE_BASE_ADDRESS:
                    address("DW_RLE_base_address", list_at)
                elif kind == DW_RLE_START_END:
                    address("DW_RLE_start_end", list_at)
                    address("DW_RLE_start_end", list_at)
                elif kind == DW_RLE_START_LENGTH:
                    address("DW_RLE_start_length", list_at)
                    reader.uleb()
                else:
                    raise LinkError(
                        "%s: unknown DW_RLE entry %#x at %#x"
                        % (where, kind, list_at))
            else:
                if kind == DW_LLE_BASE_ADDRESSX:
                    reader.uleb()
                elif kind in (DW_LLE_STARTX_ENDX, DW_LLE_STARTX_LENGTH,
                              DW_LLE_OFFSET_PAIR):
                    reader.uleb()
                    reader.uleb()
                    reader.skip(reader.uleb())    # location description
                elif kind == DW_LLE_DEFAULT_LOCATION:
                    reader.skip(reader.uleb())
                elif kind == DW_LLE_BASE_ADDRESS:
                    address("DW_LLE_base_address", list_at)
                elif kind == DW_LLE_START_END:
                    address("DW_LLE_start_end", list_at)
                    address("DW_LLE_start_end", list_at)
                    reader.skip(reader.uleb())
                elif kind == DW_LLE_START_LENGTH:
                    address("DW_LLE_start_length", list_at)
                    reader.uleb()
                    reader.skip(reader.uleb())
                elif kind == DW_LLE_GNU_VIEW_PAIR:
                    reader.uleb()
                    reader.uleb()
                else:
                    raise LinkError(
                        "%s: unknown DW_LLE entry %#x at %#x"
                        % (where, kind, list_at))
        pos = unit_end


def _check_debug_str_offsets(obj, sec, relocated):
    """Every .debug_str_offsets entry is an offset into .debug_str."""
    data = sec.data
    where = "%s: %s" % (obj.path, sec.name)
    pos = 0
    while pos < len(data):
        _unit_length, unit_end = _dwarf_unit(data, pos, where)
        reader = _DwarfReader(data, pos + 4, unit_end, where)
        version = reader.u16()
        if version != 5:
            raise LinkError("%s: unit at %#x has DWARF version %d; only v5 "
                            "string-offset tables are supported"
                            % (where, pos, version))
        reader.u16()                      # padding
        if (unit_end - reader.pos) % 4:
            raise LinkError("%s: unit at %#x has a partial entry"
                            % (where, pos))
        while reader.pos < unit_end:
            start = reader.pos
            reader.u32()
            _require_relocation(relocated, start, 4,
                                "%s (unit at %#x)" % (where, pos),
                                "entry offset into .debug_str")
        pos = unit_end


def _check_debug_addr(obj, sec, relocated):
    """Every .debug_addr entry is an absolute address."""
    data = sec.data
    where = "%s: %s" % (obj.path, sec.name)
    pos = 0
    while pos < len(data):
        _unit_length, unit_end = _dwarf_unit(data, pos, where)
        reader = _DwarfReader(data, pos + 4, unit_end, where)
        version = reader.u16()
        if version != 5:
            raise LinkError("%s: unit at %#x has DWARF version %d; only v5 "
                            "address tables are supported"
                            % (where, pos, version))
        address_size = reader.u8()
        reader.u8()                       # segment_selector_size
        if address_size != 4:
            raise LinkError(
                "%s: unit at %#x has address size %d; the link format only "
                "represents 32-bit DWARF addresses"
                % (where, pos, address_size))
        while reader.pos < unit_end:
            start = reader.pos
            reader.skip(address_size)
            _require_relocation(relocated, start, address_size,
                                "%s (unit at %#x)" % (where, pos),
                                "address entry")
        pos = unit_end


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")
        # The dwt loader requires a whole 16-bit .bss; GSPA may emit an odd
        # .bss (e.g. a single 8-bit symbol) and GSPLNK forwards it unrounded,
        # which the loader rejects.  Round only .bss up to a whole word here
        # (the trailing bits stay allocated, matching scripts/m4/coff-check.py
        # --repair); .text/.data/.cinit, relocations and the entry point are
        # untouched.
        self.bss_size = align16(self.bss_size)
        # 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._total_size(".bss"):
            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.

        In a multi-object keep-debug link the inputs are also walked (see
        ``_check_debug_references``), because concatenation is only correct
        when every section-relative field carries a relocation.  The raw
        CU ``debug_abbrev_offset`` is the one exception and is patched.
        """
        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._check_debug_references(objects)
            self._patch_raw_debug_offsets(objects)
        if self.args.keep_debug:
            for out in order:
                self._register(out)

    @staticmethod
    def _check_debug_references(objects):
        """Refuse an input whose section-relative fields are not relocated.

        The merge assumes each object's debug bytes can be copied verbatim and
        then fixed up through its relocation records.  A raw (non-relocated)
        ``DW_FORM_strp``/``line_strp``/``sec_offset``/``ref_addr``/
        ``DW_FORM_addr`` or list/address/string-offset entry would be silently
        wrong after the merge, so the walkers below require a relocation on
        every such field.

        Bound: line-program ``DW_LNE_set_address`` operands and ``DW_OP_addr``
        inside location expressions are not decoded; the pinned producer
        covers those addresses with relocations, but this gate only inspects
        the DIE/header/list/tables it parses.
        """
        for obj in objects:
            for sec in obj.sections:
                if not sec.is_debug:
                    continue
                relocated = sec.reloc_offsets
                if sec.name == ".debug_info":
                    _check_debug_info(obj, sec, relocated)
                elif sec.name == ".debug_line":
                    _check_debug_line(obj, sec, relocated)
                elif sec.name == ".debug_rnglists":
                    _check_debug_list(obj, sec, relocated, True)
                elif sec.name == ".debug_loclists":
                    _check_debug_list(obj, sec, relocated, False)
                elif sec.name == ".debug_str_offsets":
                    _check_debug_str_offsets(obj, sec, relocated)
                elif sec.name == ".debug_addr":
                    _check_debug_addr(obj, sec, relocated)

    @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())
