Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 34 additions & 6 deletions sof-builder/sof_builder/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,7 +426,32 @@ def _find_alsatplg(self) -> str:
return c
return "alsatplg"

def _ensure_abi_conf(self) -> str:
@staticmethod
def _format_abi_conf_from_bytes_str(bytes_str: str) -> str:
cleaned = ",".join(part.strip() for part in (bytes_str or "").split(",") if part.strip())
return (
"Object.Base.manifest.1 {\n"
"\tname \"sof_manifest\"\n"
"\tObject.Base.data.1 {\n"
"\t\tname \"SOF ABI\"\n"
f"\t\tbytes\t\"{cleaned}\"\n"
"\t}\n"
"}\n"
)

def _ensure_abi_conf(self, vm: Optional[GraphViewModel] = None) -> str:
# Preserve binary SOF ABI bytes when recompiling a decoded or versioned GraphViewModel
if vm is not None and vm.root_config is not None:
manifest_node = vm.root_config.get_child("Object.Base.manifest")
if manifest_node is not None:
bytes_str = str(manifest_node.get_scalar("sof_abi_bytes", "") or "").strip()
if bytes_str:
os.makedirs(self.build_dir, exist_ok=True)
bin_abi_path = os.path.join(self.build_dir, "abi_binary.conf")
with open(bin_abi_path, "w", encoding="utf-8") as f:
f.write(self._format_abi_conf_from_bytes_str(bytes_str))
return bin_abi_path

abi_path = os.path.join(self.build_dir, "abi.conf")
if os.path.isfile(abi_path):
return abi_path
Expand All @@ -435,10 +460,10 @@ def _ensure_abi_conf(self) -> str:
sof_root, _ = resolve_sof_and_workspace_roots(self.topology2_root)
tplg_repo_root = os.path.abspath(os.path.join(self.topology2_root, ".."))
abi_source = ""
if sof_root and os.path.isdir(os.path.join(sof_root, "src")):
abi_source = sof_root
elif os.path.isfile(os.path.join(tplg_repo_root, "include", "kernel", "abi.h")):
if os.path.isfile(os.path.join(tplg_repo_root, "include", "kernel", "abi.h")):
abi_source = tplg_repo_root
elif sof_root and os.path.isdir(os.path.join(sof_root, "src")):
abi_source = sof_root

if os.path.isfile(get_abi) and abi_source:
try:
Expand All @@ -464,10 +489,12 @@ def compile_graph(
self,
vm: GraphViewModel,
extra_defines: str = "",
prefer_full_topology: bool = False,
output_tplg_path: Optional[str] = None,
) -> CompileResult:
"""Serialize vm to .conf, prepend abi.conf, and compile to .tplg with alsatplg -p."""
os.makedirs(self.build_dir, exist_ok=True)
abi_path = self._ensure_abi_conf()
abi_path = self._ensure_abi_conf(vm)
with open(abi_path, "r", encoding="utf-8") as f:
abi_text = f.read()

Expand All @@ -477,13 +504,14 @@ def compile_graph(
target_platform=self.target_platform,
target_harness=self.target_harness,
extra_platform_conf=self.extra_platform_conf,
prefer_full_topology=prefer_full_topology,
)
if extra_defines.strip():
defines_str = f"{defines_str},{extra_defines.strip()}" if defines_str else extra_defines.strip()

safe_name = re.sub(r"[^A-Za-z0-9_\-]", "_", vm.title) or "custom_topology"
conf_path = os.path.join(self.build_dir, f"{safe_name}.conf")
tplg_path = os.path.join(self.build_dir, f"{safe_name}.tplg")
tplg_path = os.path.abspath(output_tplg_path) if output_tplg_path else os.path.join(self.build_dir, f"{safe_name}.tplg")

with open(conf_path, "w", encoding="utf-8") as f:
f.write(abi_text + "\n" + body_text)
Expand Down
121 changes: 106 additions & 15 deletions sof-builder/sof_builder/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from dataclasses import dataclass, field
import datetime
import os
import re
import subprocess
import sys
import threading
Expand Down Expand Up @@ -442,6 +443,8 @@ class GraphViewModel:
dirty: bool = False
graph_structure_modified: bool = False
target_variant: Optional[CMakeTargetVariant] = None
source_tplg: str = ""
binary_match_summary: str = ""

def clone(self) -> "GraphViewModel":
return GraphViewModel(
Expand All @@ -457,6 +460,8 @@ def clone(self) -> "GraphViewModel":
dirty=self.dirty,
graph_structure_modified=self.graph_structure_modified,
target_variant=self.target_variant,
source_tplg=self.source_tplg,
binary_match_summary=self.binary_match_summary,
)


Expand Down Expand Up @@ -578,8 +583,8 @@ def resolve_sof_and_workspace_roots(topology2_root: str = "") -> Tuple[str, str]
break

query_cwd = topology2_root if (topology2_root and os.path.isdir(topology2_root)) else sof_utils_root
if not sof_root:
sof_root = west_project_path("sof", cwd=query_cwd) or west_project_path("sof", cwd=sof_utils_root)
if not sof_root and topology2_root:
sof_root = west_project_path("sof", cwd=query_cwd)

workspace_root = west_topdir(cwd=query_cwd) or west_topdir(cwd=sof_utils_root)

Expand All @@ -598,6 +603,9 @@ def resolve_sof_and_workspace_roots(topology2_root: str = "") -> Tuple[str, str]
if not workspace_root:
workspace_root = tplg_repo_parent

if not sof_root:
sof_root = west_project_path("sof", cwd=sof_utils_root)

if not sof_root:
sib_sof = os.path.abspath(os.path.join(sof_utils_root, "..", "sof"))
if os.path.isdir(os.path.join(sib_sof, "src")):
Expand All @@ -612,14 +620,56 @@ def resolve_sof_and_workspace_roots(topology2_root: str = "") -> Tuple[str, str]
return (sof_root, workspace_root)


def discover_topology2_dir(initial_dir: Optional[str] = None, saved_dir: str = "") -> str:
"""Locate a topology2 directory across CLI arg, env vars, west workspace, and sibling repos."""
if initial_dir:
abs_init = os.path.abspath(initial_dir)
if os.path.isdir(abs_init):
return abs_init
_ABI_MACRO_RE = re.compile(r"^\s*#\s*define\s+(SOF_ABI_(?:MAJOR|MINOR|PATCH))\s+(\d+)", re.MULTILINE)


def parse_abi_header_text(text: str) -> Optional[Tuple[int, int, int]]:
"""Parse (SOF_ABI_MAJOR, SOF_ABI_MINOR, SOF_ABI_PATCH) from kernel/abi.h text."""
vals: Dict[str, int] = {}
for m in _ABI_MACRO_RE.finditer(text or ""):
vals[m.group(1)] = int(m.group(2))
if "SOF_ABI_MAJOR" in vals and "SOF_ABI_MINOR" in vals and "SOF_ABI_PATCH" in vals:
return (vals["SOF_ABI_MAJOR"], vals["SOF_ABI_MINOR"], vals["SOF_ABI_PATCH"])
return None


def read_workspace_sof_abi(topology2_root: str) -> Optional[Tuple[int, int, int]]:
"""Read (major, minor, patch) SOF ABI version for a topology2 directory."""
if not topology2_root:
return None
norm = os.path.abspath(topology2_root)
legacy_sof = os.path.abspath(os.path.join(norm, "..", "..", ".."))
tplg_repo_root = os.path.abspath(os.path.join(norm, ".."))
sof_root, _ = resolve_sof_and_workspace_roots(norm)
candidates = [
os.path.join(tplg_repo_root, "include", "kernel", "abi.h"),
os.path.join(legacy_sof, "src", "include", "kernel", "abi.h"),
os.path.join(norm, "include", "kernel", "abi.h"),
os.path.join(norm, "abi.h"),
]
if sof_root:
candidates.extend([
os.path.join(sof_root, "src", "include", "kernel", "abi.h"),
os.path.join(sof_root, "include", "kernel", "abi.h"),
])
for cpath in candidates:
if cpath and os.path.isfile(cpath):
try:
with open(cpath, "r", encoding="utf-8", errors="replace") as fh:
parsed = parse_abi_header_text(fh.read())
if parsed is not None:
return parsed
except Exception:
pass
return None


def discover_all_topology2_dirs(preferred_dir: str = "") -> List[str]:
"""Return unique existing topology2 source directories ordered by discovery priority."""
candidates: List[str] = []
if preferred_dir:
candidates.append(os.path.abspath(preferred_dir))

env_tplg2 = os.environ.get("SOF_TOPOLOGY2_DIR", "").strip()
if env_tplg2:
candidates.append(os.path.abspath(env_tplg2))
Expand All @@ -629,8 +679,6 @@ def discover_topology2_dir(initial_dir: Optional[str] = None, saved_dir: str = "
env_sof = os.environ.get("SOF_ROOT", "").strip()
if env_sof:
candidates.append(os.path.abspath(os.path.join(env_sof, "tools", "topology", "topology2")))
if saved_dir:
candidates.append(saved_dir)

sof_utils_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
for cwd_probe in (os.getcwd(), sof_utils_root):
Expand All @@ -641,7 +689,6 @@ def discover_topology2_dir(initial_dir: Optional[str] = None, saved_dir: str = "
if west_sof:
candidates.append(os.path.join(west_sof, "tools", "topology", "topology2"))

# Check current working directory and ancestors
cur = os.path.abspath(os.getcwd())
for _ in range(5):
candidates.append(os.path.join(cur, "topology2"))
Expand All @@ -653,16 +700,60 @@ def discover_topology2_dir(initial_dir: Optional[str] = None, saved_dir: str = "
break
cur = parent

# Check sibling checkouts relative to sof-utils root
pkg_root = os.path.abspath(os.path.join(sof_utils_root, ".."))
for sib in ("sof-topologies", "sof-topology"):
candidates.append(os.path.join(pkg_root, sib, "topology2"))
candidates.append(os.path.join(pkg_root, "sof", "tools", "topology", "topology2"))

# Bounded 1-level sibling checkout scan in pkg_root to discover versioned local checkouts
if os.path.isdir(pkg_root):
try:
for name in sorted(os.listdir(pkg_root)):
sub = os.path.join(pkg_root, name)
if not os.path.isdir(sub):
continue
for rel in ("topology2", os.path.join("tools", "topology", "topology2")):
cand = os.path.join(sub, rel)
if os.path.isdir(os.path.join(cand, "include")):
candidates.append(cand)
except Exception:
pass

out: List[str] = []
seen: Set[str] = set()
for c in candidates:
if not c:
continue
ap = os.path.abspath(c)
if ap not in seen and os.path.isdir(ap) and os.path.isdir(os.path.join(ap, "include")):
seen.add(ap)
out.append(ap)
return out


def discover_topology2_dir(initial_dir: Optional[str] = None, saved_dir: str = "") -> str:
"""Locate a topology2 directory across CLI arg, env vars, west workspace, and sibling repos."""
if initial_dir:
abs_init = os.path.abspath(initial_dir)
if os.path.isdir(abs_init):
return abs_init
if os.path.isfile(abs_init) and not abs_init.lower().endswith(".tplg"):
cur = os.path.dirname(abs_init)
for _ in range(6):
if os.path.isdir(os.path.join(cur, "include")) and (
os.path.basename(cur) == "topology2" or os.path.isdir(os.path.join(cur, "platform"))
):
return cur
parent = os.path.dirname(cur)
if parent == cur:
break
cur = parent

candidates: List[str] = []
if saved_dir:
candidates.append(saved_dir)
candidates.extend(discover_all_topology2_dirs())
for cand in candidates:
if cand and os.path.isdir(cand) and os.path.isdir(os.path.join(cand, "include")):
return cand
for cand in candidates:
if cand and os.path.isdir(cand):
return cand
return ""
Loading