Commit f0a893d1 authored by Ruud Schramp's avatar Ruud Schramp
Browse files

Add gambas-asn1 ASN.1 validation, library build and nested-codec tests

- compile_asn_gambas CI job: syntax check (asn_process_gambas.py),
  full codegen + static library build (asn_build_gambas.py) and nested
  BER roundtrip test with Annex-G zero padding (asn_testapp_gambas.py)
- testing/deps/33108_v17: release-aligned TS 33.108 modules required by
  gambas-asn1's exact-OID import resolution (existing 33108 bundle kept
  unchanged for the asn1c/pycrate checks)
- testing/gambas/pspdu-nested-codec.cpp: nested decode/re-encode test
  app with schema-generated records (RandomFiller, no wire data)
- testing/dockerfiles/Dockerfile.gambas-asn1: CI image with the
  gambas-asn1 release compiler + C++20 runtime
parent e531df05
Loading
Loading
Loading
Loading
Loading
+11
Changes for .gitlab-ci.yml: 11 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -38,6 +38,17 @@ compile_asn:
  tags:
    - docker

compile_asn_gambas:
  image: "forge.etsi.org:5050/li/schemas-definitions/gambas-asn1:latest"
  stage: compile
  interruptible: true
  script:
    - python3 testing/asn/asn_process_gambas.py
    - python3 testing/asn/asn_build_gambas.py
    - python3 testing/asn/asn_testapp_gambas.py
  tags:
    - docker

compile_xsd:
  image: "forge.etsi.org:5050/li/schemas-definitions/forgeschema:latest"
  stage: compile
+188
Changes for testing/asn/asn_build_gambas.py: 188 added lines, 0 removed lines.
Original line number Diff line number Diff line
import json
import logging
import os
import sys
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from shutil import which
from subprocess import run

# Full codegen + compile check with the gambas-asn1 compiler:
# generates C++ for every ASN.1 compile target and compiles/links it into a
# static library against the shipped C++20 runtime. This proves the schemas
# don't just parse (asn_process_gambas.py) but generate real, compilable code.
#
# The TS 33.108 modules are taken from testing/deps/33108_v17/ (aligned
# single-release copies): gambas-asn1 resolves IMPORTS by exact module OID,
# and the existing 33108 bundle mixes releases (r7..r16) whose import OIDs
# don't agree with each other.
#
# Files are passed dependencies-first (testing/deps/ first, sorted):
# gambas-asn1 resolves cross-module references against modules parsed
# earlier, so passing importers first mis-resolves some imports (see
# https://github.com/Schramp/gambas-asn1/issues).
#
# The compiler binary is found on PATH or via ASN1CPP; runtime headers via
# ASN1CPP_RUNTIME_INCLUDE (default: ../include relative to the binary, the
# layout of the release tarball). Jobs: GAMBAS_BUILD_JOBS, default nproc.

COMPILE_TARGETS_FILE = "testing/asn/asn_compile_targets.json"
BUILD_DIR = Path(os.environ.get("GAMBAS_BUILD_DIR", "build/gambas-asn1"))
DEP_REWRITES = {
    "./testing/deps/33108/": "./testing/deps/33108_v17/",
}


def buildFiles(target):
    files = []
    for f in target:
        for prefix, replacement in DEP_REWRITES.items():
            if f.startswith(prefix):
                f = replacement + f[len(prefix) :]
                break
        files.append(f)
    return sorted(files, key=lambda f: (not f.startswith("./testing/deps/"), f))


def libraryName(primary):
    return "libasn1cpp_" + Path(primary).stem.replace("-", "_") + ".a"


def buildTarget(target, asn1cpp_path, runtime_include):
    """
    Generates and compiles one compile target into a static library.

    :param target: list of filenames; the first identifies the target
    :returns: dict with "ok", and "code"/"message" for failures
    """
    primary = target[0]
    targetDir = BUILD_DIR / (Path(primary).parent.name + "-" + Path(primary).stem)
    genDir = targetDir / "gen"
    objDir = targetDir / "obj"
    genDir.mkdir(parents=True, exist_ok=True)
    objDir.mkdir(parents=True, exist_ok=True)

    files = buildFiles(target)
    p = run(
        [asn1cpp_path, "-fallow-newer-modules", "--remove-stale", "-o", str(genDir)]
        + files,
        capture_output=True,
    )
    if p.returncode != 0:
        return {
            "ok": False,
            "code": p.returncode,
            "message": p.stderr.decode(errors="replace").splitlines()[:20],
        }

    sources = sorted(genDir.glob("*.cpp"))
    if not sources:
        return {"ok": False, "code": -1, "message": ["no .cpp files generated"]}

    jobs = int(os.environ.get("GAMBAS_BUILD_JOBS", 0)) or os.process_cpu_count()

    def compileOne(source):
        obj = objDir / (source.stem + ".o")
        p = run(
            [
                os.environ.get("CXX", "g++"),
                "-std=c++20",
                "-O0",
                "-c",
                "-I",
                str(genDir),
                "-I",
                str(runtime_include),
                "-o",
                str(obj),
                str(source),
            ],
            capture_output=True,
        )
        return p.returncode, source, p.stderr.decode(errors="replace")

    failures = []
    with ThreadPoolExecutor(max_workers=jobs) as pool:
        for returncode, source, stderr in pool.map(compileOne, sources):
            if returncode != 0:
                failures.append(f"{source.name}: {stderr.splitlines()[:5]}")
                if len(failures) >= 5:
                    break
    if failures:
        return {"ok": False, "code": 1, "message": failures}

    p = run(
        ["ar", "rcs", str(targetDir / libraryName(primary))]
        + [str(objDir / o) for o in sorted(x.name for x in objDir.glob("*.o"))],
        capture_output=True,
    )
    if p.returncode != 0:
        return {
            "ok": False,
            "code": p.returncode,
            "message": p.stderr.decode(errors="replace").splitlines()[:5],
        }

    logging.info(
        f"{primary}: {len(sources)} generated files -> {targetDir / libraryName(primary)}"
    )
    return {"ok": True}


def processResults(results, stageName):
    print("")
    errorCount = sum([1 for r in results.values() if not r["ok"]])
    logging.info(f"{errorCount} {stageName} errors encountered")

    print(f"{'-':-<60}")
    print(f"{stageName} results:")
    print(f"{'-':-<60}")
    for filename, result in results.items():
        print(f" {filename:.<55}{'..OK' if result['ok'] else 'FAIL'}")
        if not result["ok"]:
            if isinstance(result["message"], list):
                for message in result["message"]:
                    print(f"    {message}")
            else:
                print(f"    {result['message']}")

    print(f"{'-':-<60}")
    print(f"{stageName} errors: {errorCount}")
    print(f"{'-':-<60}")

    return errorCount


if __name__ == "__main__":
    logging.info("Searching for the gambas-asn1 compiler (asn1cpp)")
    asn1cpp_path = os.environ.get("ASN1CPP") or which("asn1cpp")
    if asn1cpp_path is None:
        raise Exception(
            "No asn1cpp executable found. Install gambas-asn1 from "
            "https://github.com/Schramp/gambas-asn1/releases or set ASN1CPP"
        )
    asn1cpp_path = str(Path(asn1cpp_path).resolve())
    logging.info(f"asn1cpp found at {asn1cpp_path}")

    runtime_include = Path(
        os.environ.get(
            "ASN1CPP_RUNTIME_INCLUDE", Path(asn1cpp_path).parent.parent / "include"
        )
    )
    if not (runtime_include / "asn1cpp" / "asn1cpp_gen.hpp").is_file():
        raise Exception(
            f"gambas-asn1 runtime headers not found under {runtime_include}. "
            "Set ASN1CPP_RUNTIME_INCLUDE to the runtime include directory"
        )
    logging.info(f"runtime headers at {runtime_include}")

    compileTargets = json.loads(Path(COMPILE_TARGETS_FILE).read_text())
    logging.info(f"{len(compileTargets)} compile targets found")

    results = {}
    for target in compileTargets:
        logging.info(f"Building {target[0]}")
        results[target[0]] = buildTarget(target, asn1cpp_path, runtime_include)

    errorCount = processResults(results, "gambas-asn1 build")
    sys.exit(1 if errorCount else 0)
+102
Changes for testing/asn/asn_process_gambas.py: 102 added lines, 0 removed lines.
Original line number Diff line number Diff line
import json
import logging
import os
import sys
from pathlib import Path
from shutil import which
from subprocess import run

# Syntax/semantic check of every ASN.1 compile target using the
# gambas-asn1 compiler (asn1cpp) in parse-and-check mode (-E), as a
# second compiler alongside the asn1c/pycrate checks in asn_process.py.
#
# The compiler binary is found on PATH, or via the ASN1CPP environment
# variable. Get it from https://github.com/Schramp/gambas-asn1/releases
# (the linux-x86_64 tarball provides bin/asn1cpp).

COMPILE_TARGETS_FILE = "testing/asn/asn_compile_targets.json"


def checkTarget(target, asn1cpp_path):
    """
    Runs the gambas-asn1 compiler over one compile target (a list of
    filenames forming a single compilation unit) in check-only mode.

    :param target: list of filenames; the first is used as the identifier
    :param asn1cpp_path: path to the asn1cpp executable
    :returns: dict with "ok", and "code"/"message" for failures
    """
    command = [asn1cpp_path, "-E", "-fallow-newer-modules"] + [
        fix_path(filename) for filename in target
    ]
    try:
        p = run(command, capture_output=True)
    except Exception as ex:
        return {"ok": False, "code": -1, "message": f"{ex!r}"}
    if p.returncode != 0:
        errorLines = p.stderr.decode(errors="replace").splitlines()
        return {
            "ok": False,
            "code": p.returncode,
            "message": errorLines if errorLines else [f"exit code {p.returncode}"],
        }
    return {"ok": True}


def fix_path(path):
    return path.replace("\\", "/")


def processResults(results, stageName):
    """
    Counts the number of errors and writes out the output per filename

    :param results: Dict of result dicts against the primary filename
    :param stageName: Name to decorate the output with
    :returns: The number of targets which had errors
    """
    print("")
    errorCount = sum([1 for r in results.values() if not r["ok"]])
    logging.info(f"{errorCount} {stageName} errors encountered")

    print(f"{'-':-<60}")
    print(f"{stageName} results:")
    print(f"{'-':-<60}")
    for filename, result in results.items():
        print(f" {filename:.<55}{'..OK' if result['ok'] else 'FAIL'}")
        if not result["ok"]:
            if isinstance(result["message"], list):
                for message in result["message"]:
                    print(f"    {message}")
            else:
                print(f"    {result['message']}")

    print(f"{'-':-<60}")
    print(f"{stageName} errors: {errorCount}")
    print(f"{'-':-<60}")

    return errorCount


if __name__ == "__main__":
    logging.info("Searching for the gambas-asn1 compiler (asn1cpp)")
    asn1cpp_path = os.environ.get("ASN1CPP") or which("asn1cpp")
    if asn1cpp_path is None:
        raise Exception(
            "No asn1cpp executable found. Install gambas-asn1 from "
            "https://github.com/Schramp/gambas-asn1/releases or set ASN1CPP"
        )
    logging.info(f"asn1cpp found at {asn1cpp_path}")
    version = run([asn1cpp_path, "--version"], capture_output=True)
    logging.info(version.stdout.decode(errors="replace").strip())

    compileTargets = json.loads(Path(COMPILE_TARGETS_FILE).read_text())
    logging.info(f"{len(compileTargets)} compile targets found")

    results = {}
    for target in compileTargets:
        logging.debug(f"Checking {target[0]}")
        results[target[0]] = checkTarget(target, asn1cpp_path)

    errorCount = processResults(results, "gambas-asn1 syntax check")
    sys.exit(1 if errorCount else 0)
+84
Changes for testing/asn/asn_testapp_gambas.py: 84 added lines, 0 removed lines.
Original line number Diff line number Diff line
import logging
import os
import sys
from pathlib import Path
from shutil import which
from subprocess import run

# Compile and run testing/gambas/pspdu-nested-codec.cpp against the
# libraries produced by asn_build_gambas.py: a nested BER roundtrip over
# real PS-PDU wire data, checking the EncryptionContainer zero padding is
# decoded, re-applied to the cipher block size (TS 102 232-1 Annex G,
# default 16 = AES), and idempotent. Run after asn_build_gambas.py.

APP_SRC = Path("testing/gambas/pspdu-nested-codec.cpp")


def runChecked(cmd, **kwargs):
    logging.info(" ".join(str(c) for c in cmd))
    p = run(cmd, capture_output=True, text=True, **kwargs)
    for line in (p.stdout + "\n" + p.stderr).splitlines():
        if line.strip():
            print(f"  {line}")
    return p.returncode


if __name__ == "__main__":
    buildDir = Path(os.environ.get("GAMBAS_BUILD_DIR", "build/gambas-asn1"))
    libDir = buildDir / "102232-1-LI-PS-PDU"
    genDir = libDir / "gen"
    libFile = libDir / "libasn1cpp_LI_PS_PDU.a"
    if not libFile.is_file():
        raise Exception(f"{libFile} not found — run asn_build_gambas.py first")

    asn1cpp_path = os.environ.get("ASN1CPP") or which("asn1cpp")
    if asn1cpp_path is None:
        raise Exception("No asn1cpp executable found (set ASN1CPP or install it)")
    prefix = Path(str(Path(asn1cpp_path).resolve())).parent.parent
    runtime_include = Path(
        os.environ.get("ASN1CPP_RUNTIME_INCLUDE", prefix / "include")
    )
    runtime_lib = Path(os.environ.get("ASN1CPP_RUNTIME_LIB", prefix / "lib" / "libasn1cpp_runtime.a"))
    if not runtime_lib.is_file():
        raise Exception(f"{runtime_lib} not found (set ASN1CPP_RUNTIME_LIB)")

    exe = buildDir / "pspdu-nested-codec"
    rc = runChecked(
        [
            os.environ.get("CXX", "g++"),
            "-std=c++20",
            "-O1",
            "-o",
            str(exe),
            str(APP_SRC),
            str(libFile),
            str(runtime_lib),
            f"-I{genDir}",
            f"-I{runtime_include}",
        ]
    )
    failures = 0 if rc == 0 else 1

    if failures == 0:
        out1 = buildDir / "roundtrip1.etsi"
        out2 = buildDir / "roundtrip2.etsi"
        rc = runChecked([str(exe), "--generate", "12", "--seed", "42", str(out1)])
        if rc != 0:
            failures += 1
        else:
            rc = runChecked([str(exe), str(out1), str(out2)])
            if rc != 0:
                failures += 1
            elif out1.read_bytes() != out2.read_bytes():
                print("  FAIL: re-encoding the output changed it (padding not idempotent)")
                failures += 1
        rc = runChecked([str(exe), "--generate", "12", "--seed", "7", "--pad-block", "8"])
        if rc != 0:
            failures += 1

    print("")
    if failures:
        print(f"gambas-asn1 nested codec test: {failures} failure(s)")
    else:
        print("gambas-asn1 nested codec test: OK")
    sys.exit(1 if failures else 0)
+64
Changes for testing/deps/33108_v17/CSVoiceHI3IP.asn: 64 added lines, 0 removed lines.
Original line number Diff line number Diff line
CSvoice-HI3-IP {itu-t(0) identified-organization(4) etsi(0) securityDomain(2) lawfulIntercept(2) threeGPP(4) hi3CSvoice(18)  r17 (17) version-0 (0)}

DEFINITIONS IMPLICIT TAGS ::=

BEGIN


IMPORTS

	-- from ETSI HI2Operations TS 101 671, version 3.12.1
	CC-Link-Identifier,
	CommunicationIdentifier,
	LawfulInterceptionIdentifier,
	TimeStamp
		FROM HI2Operations
		{itu-t(0) identified-organization(4) etsi(0) securityDomain(2) lawfulIntercept(2) hi2(1) version18(18)}

	-- from 3GPPEps-HI3-PS TS 33.108
	National-HI3-ASN1parameters
		FROM Eps-HI3-PS {itu-t(0) identified-organization(4) etsi(0) securityDomain(2) lawfulintercept(2) threeGPP(4) hi3eps(9) r17 (17) version-0 (0)}

	-- from VoIP-HI3-IMS TS 33.108
	Payload-description,
	TPDU-direction
		FROM VoIP-HI3-IMS {itu-t(0) identified-organization(4) etsi(0) securityDomain(2) lawfulIntercept(2) threeGPP(4) hi3voip(12) r17(17) version-0(0)};

-- Object Identifier Definitions

-- Security DomainId
lawfulInterceptDomainId OBJECT IDENTIFIER ::= {itu-t(0) identified-organization(4) etsi(0)
securityDomain(2) lawfulIntercept(2)}

-- Security Subdomains
threeGPPSUBDomainId OBJECT IDENTIFIER ::= {lawfulInterceptDomainId threeGPP(4)}
hi3CSvoiceDomainId OBJECT IDENTIFIER  ::= {threeGPPSUBDomainId hi3CSvoice(18) r17(17) version-0 (0)}

CSvoice-CC-PDU	::= SEQUENCE
{
 	cSvoiceLIC-header	[0] CSvoiceLIC-header,
	payload				[1] OCTET STRING,
	...
}

CSvoiceLIC-header ::= SEQUENCE
{
	hi3CSvoiceDomainId			[0]	OBJECT IDENTIFIER,  -- 3GPP IP-based delivery for CS HI3 Domain
	lIID						[1] LawfulInterceptionIdentifier OPTIONAL,
	communicationIdentifier		[2]	CommunicationIdentifier,
		-- contents same as the contents of similar field sent in the linked IRI messages
	ccLID						[3]	CC-Link-Identifier	OPTIONAL,
		-- Included only if the linked IRI messages have the similar field. When included,
		-- the content is same as the content of similar field sent in the linked IRI messages.
	timeStamp					[4]	TimeStamp OPTIONAL,
	sequence-number				[5]	INTEGER (0..65535),
	t-PDU-direction				[6] TPDU-direction,
	national-HI3-ASN1parameters	[7] National-HI3-ASN1parameters OPTIONAL,
		--  encoded per national requirements
	payload-description			[8] Payload-description,
		-- used to provide the codec information of the CC (as RTP payload) delivered over HI3
 	...
}


END
Loading