diff --git a/docs/contrib/MakefileContract.md b/docs/contrib/MakefileContract.md index 15dbc49f0d..1e632039eb 100644 --- a/docs/contrib/MakefileContract.md +++ b/docs/contrib/MakefileContract.md @@ -103,6 +103,13 @@ Several of the rules exist for them. unsets it before the sub-make, and the fallback fires there with an in-tree path that a flow supplying its own tools does not have (the "HERE BE DRAGONS" comment in `flow/scripts/variables.mk`). +- **`OPENROAD_EXE` and `YOSYS_EXE` are commands, never assumed to be a + single path.** A wrapper can come first: `OPENROAD_EXE="gdb --args + openroad"`. A recipe or shell script runs the value as the shell splits + it, Python splits it with `shlex.split`, and a check looks at its first + word. + *Breaks:* running a tool under a debugger, valgrind or perf needs a + switch of its own for each tool. - **Only the Makefile sets `RESULTS_DIR`, `LOG_DIR`, `REPORTS_DIR` and `OBJECTS_DIR`.** It derives them from `WORK_HOME`, which a flow sets. A variable a flow adds never reuses one of these names. diff --git a/docs/user/FAQS.md b/docs/user/FAQS.md index 54be879234..2bb4756262 100644 --- a/docs/user/FAQS.md +++ b/docs/user/FAQS.md @@ -48,6 +48,34 @@ For development purposes, it is a good practice to work on branches and leave ma See how to update using the Metrics [guide](../contrib/Metrics.md). +## How do I run OpenROAD under gdb, valgrind or perf? + +Put the tool in front of the binary in `OPENROAD_EXE`. Every rule runs +`OPENROAD_EXE` as a command, sub-makes included, so it reaches every +stage and the `open_*`, `gui_*` and `web_*` targets. Below, `openroad` +stands for the binary the flow would run otherwise. The binary is the +last word of `OPENROAD_EXE`: the flow asks it alone for its version when +it writes the metrics, so the tool in front is not run for that. + +```shell +# a backtrace when OpenROAD crashes, its own exit code otherwise +make DESIGN_CONFIG=./designs/nangate45/gcd/config.mk OPENROAD_EXE="gdb -batch -return-child-result -ex run -ex 'thread apply all bt' --args openroad" floorplan + +# memory errors +make DESIGN_CONFIG=./designs/nangate45/gcd/config.mk OPENROAD_EXE="valgrind openroad" floorplan + +# a profile, written to perf.data +make DESIGN_CONFIG=./designs/nangate45/gcd/config.mk OPENROAD_EXE="perf record -g -- openroad" floorplan + +# an interactive debugger on a result +make DESIGN_CONFIG=./designs/nangate45/gcd/config.mk OPENROAD_EXE="gdb --args openroad" open_floorplan +``` + +A stage logs OpenROAD's output through a pipe, so use gdb in batch mode +for a stage, as in the first example; an interactive session suits +`open_*`, `gui_*` and `command`. `OPENROAD_EXE` can also come from the +environment. + ## How do I get better search results? As quoted from [ReadTheDocs](https://docs.readthedocs.io/en/stable/server-side-search/syntax.html#special-queries), this documentation is powered by [Simple Query String](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-simple-query-string-query.html#) from [Elasticsearch](https://www.elastic.co/elasticsearch/). Here are some helpful patterns: diff --git a/flow/Makefile b/flow/Makefile index fe78dbb261..28ba53bd29 100644 --- a/flow/Makefile +++ b/flow/Makefile @@ -275,7 +275,7 @@ do-auto-memories: $(RESULTS_DIR)/memories_inferred.json $(foreach file,$(ADDITIONAL_MEMORIES),--memories $(file)) \ $(foreach file,$(AUTO_MEMORIES_REGFILES),--regfile-spec $(file)) \ $(foreach m,$(AUTO_MEMORIES_MACRO_PLACE),--macro-place $(m)) \ - $(if $(AUTO_MEMORIES_REGFILES),--openroad $(OPENROAD_EXE)) \ + $(if $(AUTO_MEMORIES_REGFILES),--openroad '$(subst ','\'',$(OPENROAD_EXE))') \ $(foreach file,$(TECH_LEF) $(SC_LEF),--lef $(file)) $(RESULTS_DIR)/memories.json: $(RESULTS_DIR)/memories_inferred.json $(ADDITIONAL_MEMORIES) \ @@ -366,8 +366,15 @@ UNSET_VARS = for var in $(UNSET_VARIABLES_NAMES); do unset $$var; done # However, on some versions of make, MAKEFILE_LIST can be empty, so # don't expand it in that case. FILE_MAKEFILE ?= $(if $(firstword $(MAKEFILE_LIST)),--file=$(firstword $(MAKEFILE_LIST)),) -SUB_MAKE = $(MAKE) $(foreach V,$(COMMAND_LINE_ARGS), $(if $($V),$V=$(shell echo "$($V)" | $(FLOW_HOME)/scripts/escape.sh),$V='')) --no-print-directory $(FILE_MAKEFILE) DESIGN_CONFIG=$(DESIGN_CONFIG) -UNSET_AND_MAKE = @bash -c '$(UNSET_VARS); $(SUB_MAKE) $$@' -- + +# UNSET_VARS clears MAKEFLAGS too, so the sub-make gets the command-line +# variables from SUB_MAKE, as command-line variables again. Each one is a +# single shell word holding the value this make sees: single-quoted, with +# ' escaped for the shell and $ for the sub-make. Only the shell running +# the recipe parses it, so quotes, $ and spaces reach the sub-make intact. +SUB_MAKE_ARG = '$(subst ','\'',$1=$(subst $$,$$$$,$($1)))' +SUB_MAKE = $(MAKE) $(foreach V,$(COMMAND_LINE_ARGS),$(call SUB_MAKE_ARG,$V)) --no-print-directory $(FILE_MAKEFILE) DESIGN_CONFIG=$(DESIGN_CONFIG) +UNSET_AND_MAKE = @bash -c '$(UNSET_VARS); "$$@"' -- $(SUB_MAKE) $(OBJECTS_DIR)/copyright.txt: @$(OPENROAD_CMD) $(SCRIPTS_DIR)/noop.tcl diff --git a/flow/scripts/escape.sh b/flow/scripts/escape.sh deleted file mode 100755 index 7b9e4260de..0000000000 --- a/flow/scripts/escape.sh +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env bash -sed -e 's/ /\\ /g' -e 's/(/\\(/g' -e 's/|/\\|/g' -e 's/)/\\)/g' diff --git a/flow/scripts/flow.sh b/flow/scripts/flow.sh index eac5f8f14b..a10bd529c4 100755 --- a/flow/scripts/flow.sh +++ b/flow/scripts/flow.sh @@ -21,8 +21,14 @@ rm -f "$RESULTS_DIR/$1-failed.odb" "$RESULTS_DIR/$1-failed.sdc" eval "$OPENROAD_EXE $OPENROAD_ARGS -exit \"$SCRIPTS_DIR/noop.tcl\"" \ >"$LOG_DIR/$1.tmp.log" 2>&1 - $RUN_CMD --log "$(realpath "$LOG_DIR/$1.tmp.log")" --append --tee -- \ - $OPENROAD_CMD -no_splash "$SCRIPTS_DIR/run_step.tcl" -metrics "$LOG_DIR/$1.json" + # OPENROAD_CMD is a command line, quotes included: a wrapper in + # OPENROAD_EXE can have a quoted argument of its own, as in + # gdb -ex 'thread apply all bt' --args openroad. The shell parses it, + # as it does in a make recipe; plain word splitting would hand the + # wrapper the quotes and the pieces. + log="$(realpath "$LOG_DIR/$1.tmp.log")" + eval "$RUN_CMD --log \"\$log\" --append --tee -- $OPENROAD_CMD" \ + '-no_splash "$SCRIPTS_DIR/run_step.tcl" -metrics "$LOG_DIR/$1.json"' ) # Log the hash for this step. The summary "make elapsed" in "make finish", diff --git a/flow/scripts/memories/gen_memories.py b/flow/scripts/memories/gen_memories.py index 4cab002582..d697c14b91 100644 --- a/flow/scripts/memories/gen_memories.py +++ b/flow/scripts/memories/gen_memories.py @@ -351,7 +351,8 @@ def main(argv: list[str] | None = None) -> int: p.add_argument( "--openroad", default=None, - help="The openroad that runs generate_ram (OPENROAD_EXE).", + help="The openroad command that runs generate_ram (OPENROAD_EXE), " + "a wrapper first if any: gdb --args openroad.", ) p.add_argument( "--lef", diff --git a/flow/scripts/memories/gen_memories_test.py b/flow/scripts/memories/gen_memories_test.py index 8ba89d70e8..5023d57a4b 100644 --- a/flow/scripts/memories/gen_memories_test.py +++ b/flow/scripts/memories/gen_memories_test.py @@ -404,7 +404,14 @@ def test_fold_rule(self): # never an empty fold: 3 bits fold at most in two self.assertEqual(folds(600, 17.6, 600, 3), 2) - def _generate(self, bit_folds, outline): + def test_openroad_is_a_command(self): + # OPENROAD_EXE can start with a wrapper; generate_ram runs under it + self._generate(8, "140000 140000 1000\n", "valgrind -q /opt/bin/openroad") + self.assertEqual(len(self.argvs), 2) + for argv in self.argvs: + self.assertEqual(argv[:4], ["valgrind", "-q", "/opt/bin/openroad", "-exit"]) + + def _generate(self, bit_folds, outline, command="openroad"): # generate() with generate_ram stubbed: the generate script writes # the outline (dx dy dbu), the views script stops the run d = Path(self.tmp.name) @@ -418,8 +425,10 @@ class Views(Exception): pass scripts = [] + self.argvs = [] def openroad(cmd): + self.argvs.append(cmd) script = Path(cmd[-1]) scripts.append(script.name) if script.name.endswith(".generate.tcl"): @@ -433,7 +442,7 @@ def openroad(cmd): ): with self.assertRaises((Views, SystemExit)) as stop: gen_memories.regfile_ram.generate( - spec, "rf", "inline", "openroad", [], d + spec, "rf", "inline", command, [], d ) return stop.exception, scripts diff --git a/flow/scripts/memories/regfile_ram.py b/flow/scripts/memories/regfile_ram.py index 44ac053757..dc04d3a1ef 100644 --- a/flow/scripts/memories/regfile_ram.py +++ b/flow/scripts/memories/regfile_ram.py @@ -25,6 +25,7 @@ import json import math import os +import shlex import subprocess from pathlib import Path @@ -593,7 +594,9 @@ def build(spec_lines: list[list[str]]) -> tuple[float, float]: + 'puts $f "[$die dx] [$die dy] [[ord::get_db_tech] getDbUnitsPerMicron]"\n' + "close $f\n" ) - subprocess.check_call([openroad, "-exit", "-no_init", "-no_splash", str(gen)]) + subprocess.check_call( + [*shlex.split(openroad), "-exit", "-no_init", "-no_splash", str(gen)] + ) width, height, _ = outline.read_text().split() return float(width), float(height) @@ -662,7 +665,9 @@ def build(spec_lines: list[list[str]]) -> tuple[float, float]: else: tcl += _MACRO_TCL.format(out=out_dir, block=block) views.write_text(tcl) - subprocess.check_call([openroad, "-exit", "-no_init", "-no_splash", str(views)]) + subprocess.check_call( + [*shlex.split(openroad), "-exit", "-no_init", "-no_splash", str(views)] + ) core_ports = _buses((out_dir / f"{block}.ports").read_text().splitlines()) ram_ports = core_ports periphery = "" diff --git a/flow/scripts/synth.sh b/flow/scripts/synth.sh index 37bde9baf1..fc03429905 100755 --- a/flow/scripts/synth.sh +++ b/flow/scripts/synth.sh @@ -2,9 +2,12 @@ set -u -eo pipefail mkdir -p $RESULTS_DIR $LOG_DIR $REPORTS_DIR $OBJECTS_DIR touch $2 -$YOSYS_EXE -V > $(realpath $2) -$PYTHON_EXE "$SCRIPTS_DIR/run_command.py" --log "$(realpath $2)" --append --tee -- \ - $YOSYS_EXE $YOSYS_FLAGS -c $1 +# YOSYS_EXE is a command line, quotes included: a wrapper in it can have +# a quoted argument of its own. The shell parses it, as it does in a make +# recipe. +eval "$YOSYS_EXE -V" > "$(realpath $2)" +eval '$PYTHON_EXE "$SCRIPTS_DIR/run_command.py" --log "$(realpath $2)" --append --tee --' \ + "$YOSYS_EXE $YOSYS_FLAGS" '-c "$1"' # Log result hash, mirroring flow.sh's epilogue for OpenROAD stages. # genElapsedTime.py understands .odb/.rtlil/.v so it hashes the yosys diff --git a/flow/scripts/variables.mk b/flow/scripts/variables.mk index 7c607fc375..7d05dc3553 100644 --- a/flow/scripts/variables.mk +++ b/flow/scripts/variables.mk @@ -127,7 +127,14 @@ export RUN_CMD = $(PYTHON_EXE) $(FLOW_HOME)/scripts/run_command.py export OPENROAD_EXE ?= $(abspath $(FLOW_HOME)/../tools/install/OpenROAD/bin/openroad) export OPENSTA_EXE ?= $(abspath $(FLOW_HOME)/../tools/install/OpenROAD/bin/sta) -OPENROAD_IS_VALID := $(if $(OPENROAD_EXE),$(shell test -x $(OPENROAD_EXE) && echo "true"),) +# OPENROAD_EXE and YOSYS_EXE are commands, not only paths: a wrapper can +# come first, as in OPENROAD_EXE="gdb --args openroad" or +# OPENROAD_EXE="valgrind openroad". The check is on the program the command +# starts with, a path or a name on PATH. The binary is the last word. +# The shell splits the command, as a recipe does, so a quoted path with +# spaces in it is one program: OPENROAD_EXE="'/opt/my tools/openroad'". +command_is_valid = $(if $(1),$(shell set -- $(1) && command -v "$$1" >/dev/null && echo "true"),) +OPENROAD_IS_VALID := $(call command_is_valid,$(OPENROAD_EXE)) export OPENROAD_ARGS = -no_init -threads $(NUM_CORES) $(OR_ARGS) export OPENROAD_CMD = $(OPENROAD_EXE) -exit $(OPENROAD_ARGS) @@ -137,7 +144,7 @@ export OPENROAD_WEB_CMD = $(OPENROAD_EXE) -web -threads $(NUM_CORES) $(OR_ARGS) export YOSYS_EXE ?= $(abspath $(FLOW_HOME)/../tools/install/yosys/bin/yosys) -YOSYS_IS_VALID := $(if $(YOSYS_EXE),$(shell test -x $(YOSYS_EXE) && echo "true"),) +YOSYS_IS_VALID := $(call command_is_valid,$(YOSYS_EXE)) KEPLER_FORMAL_EXE ?= $(abspath $(FLOW_HOME)/../tools/install/kepler-formal/bin/kepler-formal) export KEPLER_FORMAL_EXE @@ -191,7 +198,7 @@ export RESULTS_V = $(notdir $(sort $(wildcard $(RESULTS_DIR)/*.v))) export GDS_MERGED_FILE = $(RESULTS_DIR)/6_1_merged.$(STREAM_SYSTEM_EXT) define get_variables -$(foreach V, $(.VARIABLES),$(if $(filter-out $(1), $(origin $V)), $(if $(filter-out .% %QT_QPA_PLATFORM% KLAYOUT% OPENROAD_EXE OPENROAD_ARGS OPENROAD_CMD OPENROAD_NO_EXIT_CMD OPENROAD_GUI_CMD OPENROAD_WEB_CMD OPENROAD_IS_VALID OPENSTA% PYTHON% YOSYS% GENERATE_ABSTRACT_RULE% do-step% do-copy% OPEN_GUI% OPEN_GUI_SHORTCUT% SUB_MAKE% UNSET_VARS% export%, $(V)), $V$ ))) +$(foreach V, $(.VARIABLES),$(if $(filter-out $(1), $(origin $V)), $(if $(filter-out .% %QT_QPA_PLATFORM% KLAYOUT% OPENROAD_EXE OPENROAD_ARGS OPENROAD_CMD OPENROAD_NO_EXIT_CMD OPENROAD_GUI_CMD OPENROAD_WEB_CMD OPENROAD_IS_VALID command_is_valid OPENSTA% PYTHON% YOSYS% GENERATE_ABSTRACT_RULE% do-step% do-copy% OPEN_GUI% OPEN_GUI_SHORTCUT% SUB_MAKE% UNSET_VARS% export%, $(V)), $V$ ))) endef export UNSET_VARIABLES_NAMES := $(call get_variables,command% line environment% default automatic) diff --git a/flow/test/test_flow_sh.py b/flow/test/test_flow_sh.py index 0ab5bf4c2a..1cc0d598f3 100644 --- a/flow/test/test_flow_sh.py +++ b/flow/test/test_flow_sh.py @@ -95,6 +95,32 @@ def test_run_cmd_runs_the_stage(self): self.assertIn("Elapsed time:", log) self.assert_summary(log) + def test_quoted_wrapper_argument_stays_one_argument(self): + # OPENROAD_EXE="gdb -ex 'thread apply all bt' --args openroad": the + # quoted argument reaches the wrapper whole, not split with its quotes. + argv_log = os.path.join(self.tmp_dir.name, "argv.log") + wrapper = os.path.join(self.tmp_dir.name, "wrapper") + with open(wrapper, "w") as f: + f.write("#!/usr/bin/env bash\n" 'printf "%s\\n" "$@" > "$ARGV_LOG"\n') + os.chmod(wrapper, 0o755) + self.env["ARGV_LOG"] = argv_log + self.env["OPENROAD_EXE"] = "true" + self.env["OPENROAD_CMD"] = ( + f"{wrapper} -ex 'thread apply all bt' --args openroad -exit" + ) + + self.run_stage() + + with open(argv_log) as f: + argv = f.read().splitlines() + self.assertEqual( + argv[:5], + ["-ex", "thread apply all bt", "--args", "openroad", "-exit"], + argv, + ) + self.assertEqual(argv[5], "-no_splash", argv) + self.assertEqual(argv[7], "-metrics", argv) + if __name__ == "__main__": unittest.main() diff --git a/flow/test/test_openroad_exe.py b/flow/test/test_openroad_exe.py new file mode 100644 index 0000000000..869a2d6572 --- /dev/null +++ b/flow/test/test_openroad_exe.py @@ -0,0 +1,260 @@ +#!/usr/bin/env python3 +"""OPENROAD_EXE is a command, not only a path: a wrapper such as a debugger +or a profiler goes in front of the binary in it, as in +`make OPENROAD_EXE="gdb --args openroad" ...`. + +The wrapped command passes the flow's check, and every rule runs it as +given: at the top level, through a sub-make, and in the generated +open_/gui_/web_ rules. The wrapper runs once per call, never twice. +GDB and VALGRIND are not switches: a debugger goes in OPENROAD_EXE. + +The tools are stubbed: `openroad` and the wrapper only log their argv, so +make runs in well under a second and needs nothing installed. +""" + +import os +import subprocess +import sys +import tempfile +import unittest + +FLOW_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +DESIGN_CONFIG = "designs/nangate45/gcd/config.mk" + + +class TestOpenroadExe(unittest.TestCase): + def setUp(self): + self.tmp_dir = tempfile.TemporaryDirectory() + tmp = self.tmp_dir.name + self.log = os.path.join(tmp, "argv.log") + self.openroad = self.script("openroad", 'echo "openroad $*" >> "$ARGV_LOG"\n') + self.wrapper = self.script( + "wrapper", 'echo "wrapper $1" >> "$ARGV_LOG"\nexec "$@"\n' + ) + self.work_home = os.path.join(tmp, "work") + self.env = dict(os.environ, ARGV_LOG=self.log) + for name in ("OPENROAD_EXE", "YOSYS_EXE", "GDB", "VALGRIND", "MAKEFLAGS"): + self.env.pop(name, None) + + def tearDown(self): + self.tmp_dir.cleanup() + + def script(self, name, body): + path = os.path.join(self.tmp_dir.name, name) + with open(path, "w") as f: + f.write("#!/usr/bin/env bash\n" + body) + os.chmod(path, 0o755) + return path + + def make(self, target, *args, env=None): + if os.path.exists(self.log): + os.remove(self.log) + result = subprocess.run( + [ + "make", + "--no-print-directory", + f"DESIGN_CONFIG={DESIGN_CONFIG}", + f"WORK_HOME={self.work_home}", + "FLOW_VARIANT=openroad_exe", + *args, + target, + ], + cwd=FLOW_DIR, + env=dict(self.env, **(env or {})), + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + ) + calls = [] + if os.path.exists(self.log): + with open(self.log) as f: + calls = f.read().splitlines() + return result, calls + + def wrapped(self): + return f"{self.wrapper} {self.openroad}" + + def assert_wrapped_once(self, result, calls): + output = result.stdout + result.stderr + self.assertEqual(result.returncode, 0, output) + self.assertNotIn("binary operator expected", output) + # the wrapper ran once, on the binary, and the binary ran once + self.assertEqual(len(calls), 2, calls) + self.assertEqual(calls[0], f"wrapper {self.openroad}") + self.assertTrue(calls[1].startswith("openroad "), calls) + return calls[1] + + def test_wrapped_command_passes_the_check(self): + for how in ("command line", "environment"): + with self.subTest(how): + if how == "command line": + result, _ = self.make( + "check-openroad", f"OPENROAD_EXE={self.wrapped()}" + ) + else: + result, _ = self.make( + "check-openroad", env={"OPENROAD_EXE": self.wrapped()} + ) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_missing_program_fails_the_check(self): + missing = os.path.join(self.tmp_dir.name, "no-such-wrapper") + result, _ = self.make( + "check-openroad", f"OPENROAD_EXE={missing} {self.openroad}" + ) + self.assertNotEqual(result.returncode, 0) + self.assertIn("not found or not executable", result.stdout) + + def test_wrapped_yosys_passes_the_check(self): + yosys = self.script("yosys", "true\n") + result, _ = self.make("check-yosys", f"YOSYS_EXE={self.wrapper} {yosys}") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_quoted_paths_pass_the_check(self): + # the shell splits the command, so a quoted path with spaces in it + # is one program, as the executable or as the wrapper + spaced = os.path.join(self.tmp_dir.name, "with space") + os.makedirs(spaced) + openroad = os.path.join(spaced, "openroad") + yosys = os.path.join(spaced, "yosys") + wrapper = os.path.join(spaced, "wrapper") + for link, target in ((openroad, self.openroad), (wrapper, self.wrapper)): + os.symlink(target, link) + os.symlink(self.script("yosys", "true\n"), yosys) + for check, variable, binary in ( + ("check-openroad", "OPENROAD_EXE", openroad), + ("check-yosys", "YOSYS_EXE", yosys), + ): + for command in (f"'{binary}'", f"'{wrapper}' '{binary}'"): + with self.subTest(check=check, command=command): + result, _ = self.make(check, f"{variable}={command}") + self.assertEqual( + result.returncode, 0, result.stdout + result.stderr + ) + missing = command.replace("with space", "no such") + result, _ = self.make(check, f"{variable}={missing}") + self.assertNotEqual(result.returncode, 0) + + def test_quoted_path_runs(self): + # the recipe runs the quoted path the check accepted + spaced = os.path.join(self.tmp_dir.name, "with space") + os.makedirs(spaced) + wrapper = os.path.join(spaced, "wrapper") + os.symlink(self.wrapper, wrapper) + result, calls = self.make( + "command", f"OPENROAD_EXE='{wrapper}' {self.openroad}" + ) + self.assert_wrapped_once(result, calls) + + def test_top_level_rule_runs_the_command_once(self): + for how in ("command line", "environment"): + with self.subTest(how): + if how == "command line": + args, env = [f"OPENROAD_EXE={self.wrapped()}"], None + else: + args, env = [], {"OPENROAD_EXE": self.wrapped()} + call = self.assert_wrapped_once(*self.make("command", *args, env=env)) + self.assertIn("-no_init", call) + + def test_sub_make_runs_the_command_once(self): + for how in ("command line", "environment"): + with self.subTest(how): + if how == "command line": + args, env = [f"OPENROAD_EXE={self.wrapped()}"], None + else: + args, env = [], {"OPENROAD_EXE": self.wrapped()} + call = self.assert_wrapped_once( + *self.make("test-unset-and-make-command", *args, env=env) + ) + self.assertIn("-no_init", call) + + def test_generated_rules_run_the_command(self): + # open_/gui_/web_ rules are generated for each result on disk + result, _ = self.make("print-RESULTS_DIR") + results_dir = result.stdout.split("RESULTS_DIR: ")[1].strip() + os.makedirs(results_dir) + open(os.path.join(results_dir, "2_floorplan.odb"), "w").close() + for target, flag in ( + ("open_floorplan", "-no_init"), + ("gui_floorplan", "-gui"), + ("web_floorplan", "-web"), + ): + with self.subTest(target): + call = self.assert_wrapped_once( + *self.make(target, f"OPENROAD_EXE={self.wrapped()}") + ) + self.assertIn(flag, call.split()) + self.assertTrue(call.endswith("open.tcl"), call) + + def test_synth_sh_keeps_a_quoted_wrapper_argument_whole(self): + # YOSYS_EXE="wrapper -ex 'two words' yosys": synth.sh hands the + # wrapper the quoted argument as one argument, both times it runs it. + tmp = self.tmp_dir.name + wrapper = self.script( + "argv", 'printf "%s|" "$@" >> "$ARGV_LOG"\necho >> "$ARGV_LOG"\n' + ) + scripts = os.path.join(FLOW_DIR, "scripts") + env = dict( + self.env, + RESULTS_DIR=os.path.join(tmp, "results"), + LOG_DIR=os.path.join(tmp, "logs"), + REPORTS_DIR=os.path.join(tmp, "reports"), + OBJECTS_DIR=os.path.join(tmp, "objects"), + SCRIPTS_DIR=scripts, + UTILS_DIR=os.path.join(FLOW_DIR, "util"), + PYTHON_EXE=sys.executable, + YOSYS_EXE=f"{wrapper} -ex 'two words' yosys", + YOSYS_FLAGS="-v 3", + ) + result = subprocess.run( + [ + "bash", + os.path.join(scripts, "synth.sh"), + "synth.tcl", + os.path.join(tmp, "logs", "1_2_yosys.log"), + ], + cwd=tmp, + env=env, + capture_output=True, + text=True, + ) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + with open(self.log) as f: + calls = f.read().splitlines() + self.assertEqual( + calls, + ["-ex|two words|yosys|-V|", "-ex|two words|yosys|-v|3|-c|synth.tcl|"], + ) + + def test_gdb_and_valgrind_are_not_switches(self): + # a debugger or valgrind goes in OPENROAD_EXE; GDB and VALGRIND + # set to anything leave the command as it is + env = {"OPENROAD_EXE": self.openroad} + for target in ("command", "test-unset-and-make-command"): + expected, expected_calls = self.make(target, env=env) + self.assertEqual(expected.returncode, 0, expected.stderr) + self.assertEqual(len(expected_calls), 1, expected_calls) + for switch in ("GDB=1", "VALGRIND=1"): + with self.subTest(target=target, switch=switch): + result, calls = self.make(target, switch, env=env) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout, expected.stdout) + self.assertEqual(calls, expected_calls) + + def test_vars_leave_out_the_check_function(self): + # command_is_valid is a make function the check uses, not a flow + # variable: make vars writes no entry for it + result, _ = self.make("vars", env={"OPENROAD_EXE": self.openroad}) + self.assertEqual(result.returncode, 0, result.stderr) + objects = os.path.join( + self.work_home, "objects", "nangate45", "gcd", "openroad_exe" + ) + for ext in ("sh", "tcl", "gdb"): + with self.subTest(ext=ext): + with open(os.path.join(objects, f"vars.{ext}")) as f: + found = "command_is_valid" in f.read() + self.assertFalse(found, f"vars.{ext} has a command_is_valid entry") + + +if __name__ == "__main__": + unittest.main() diff --git a/flow/test/test_sub_make_args.py b/flow/test/test_sub_make_args.py new file mode 100644 index 0000000000..89e28e253a --- /dev/null +++ b/flow/test/test_sub_make_args.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python3 +"""A variable given on the make command line reaches a sub-make with the +value the top-level make sees, whatever characters are in it. + +Most steps run in a sub-make (UNSET_AND_MAKE). Quotes, `$` and spaces in a +command-line value come out of the sub-make's command exactly as they come +out of the top level's: the tool gets the same argv either way. A value +from the environment does too. + +The tool is a stub that records its argv, so make runs in well under a +second and needs nothing installed. +""" + +import json +import os +import subprocess +import sys +import tempfile +import unittest + +FLOW_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +DESIGN_CONFIG = "designs/nangate45/gcd/config.mk" + +# OR_ARGS as typed after `make OR_ARGS=`, and the arguments OpenROAD gets +VALUES = { + "single quotes": ( + "-ex 'thread apply all bt' -x", + ["-ex", "thread apply all bt", "-x"], + ), + "double quotes": ('-msg "a b" -x', ["-msg", "a b", "-x"]), + "dollar": ("'$$HOME' -x", ["$HOME", "-x"]), + "spaces": ("-a -b", ["-a", "-b"]), +} + + +class TestSubMakeArgs(unittest.TestCase): + def setUp(self): + self.tmp_dir = tempfile.TemporaryDirectory() + tmp = self.tmp_dir.name + self.log = os.path.join(tmp, "argv.jsonl") + self.openroad = os.path.join(tmp, "openroad") + with open(self.openroad, "w") as f: + f.write( + f"#!{sys.executable}\n" + "import json, os, sys\n" + "with open(os.environ['ARGV_LOG'], 'a') as f:\n" + " f.write(json.dumps(sys.argv[1:]) + '\\n')\n" + ) + os.chmod(self.openroad, 0o755) + self.env = dict(os.environ, ARGV_LOG=self.log, OPENROAD_EXE=self.openroad) + for name in ("OR_ARGS", "MAKEFLAGS"): + self.env.pop(name, None) + + def tearDown(self): + self.tmp_dir.cleanup() + + def openroad_argv(self, target, *args, env=None): + """The arguments after the flow's own, of the one OpenROAD run.""" + if os.path.exists(self.log): + os.remove(self.log) + result = subprocess.run( + [ + "make", + "--no-print-directory", + f"DESIGN_CONFIG={DESIGN_CONFIG}", + f"WORK_HOME={os.path.join(self.tmp_dir.name, 'work')}", + "NUM_CORES=1", + *args, + target, + ], + cwd=FLOW_DIR, + env=dict(self.env, **(env or {})), + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + ) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + with open(self.log) as f: + calls = [json.loads(line) for line in f] + self.assertEqual(len(calls), 1, calls) + # `command` runs $(OPENROAD_EXE) -no_init -threads 1 $(OR_ARGS) + self.assertEqual(calls[0][:3], ["-no_init", "-threads", "1"]) + return calls[0][3:] + + def test_command_line_value_reaches_sub_make(self): + for name, (value, argv) in VALUES.items(): + with self.subTest(name): + top = self.openroad_argv("command", f"OR_ARGS={value}") + self.assertEqual(top, argv) + sub = self.openroad_argv( + "test-unset-and-make-command", f"OR_ARGS={value}" + ) + self.assertEqual(sub, top) + + def test_command_line_value_reaches_nested_sub_make(self): + value, argv = VALUES["single quotes"] + sub = self.openroad_argv( + "test-unset-and-make-test-unset-and-make-command", f"OR_ARGS={value}" + ) + self.assertEqual(sub, argv) + + def test_environment_value_reaches_sub_make(self): + for name, (value, argv) in VALUES.items(): + # make expands an environment value as it does a command-line one + env = {"OR_ARGS": value} + with self.subTest(name): + top = self.openroad_argv("command", env=env) + self.assertEqual(top, argv) + sub = self.openroad_argv("test-unset-and-make-command", env=env) + self.assertEqual(sub, top) + + +if __name__ == "__main__": + unittest.main() diff --git a/flow/util/genMetrics.py b/flow/util/genMetrics.py index 0c2b94f9a3..faa33b1dd8 100755 --- a/flow/util/genMetrics.py +++ b/flow/util/genMetrics.py @@ -7,6 +7,7 @@ import hashlib import os +import shlex import shutil from datetime import datetime, timedelta from collections import defaultdict @@ -214,6 +215,16 @@ def merge_jsons(root_path, output, files): output.update(data) +def openroad_binary(): + """The binary OPENROAD_EXE runs: its last word. + + OPENROAD_EXE is a command, and a wrapper such as gdb, valgrind or perf + comes first in it. The version is asked of the binary alone: through + the wrapper, gdb's banner would be read as the version, and perf + record would overwrite perf.data with a profile of the query.""" + return shlex.split(os.environ.get("OPENROAD_EXE", "openroad"))[-1] + + def extract_metrics( cwd, platform, design, flow_variant, output, hier_json, logPath, rptPath, resultPath ): @@ -222,7 +233,7 @@ def extract_metrics( metrics_dict = defaultdict(dict) metrics_dict["run__flow__generate_date"] = datetime.now().strftime("%Y-%m-%d %H:%M") metrics_dict["run__flow__metrics_version"] = "Metrics_2.1.2" - cmdOutput = check_output([os.environ.get("OPENROAD_EXE", "openroad"), "-version"]) + cmdOutput = check_output([openroad_binary(), "-version"]) cmdFields = [x.decode("utf-8") for x in cmdOutput.split()] metrics_dict["run__flow__openroad_version"] = str(cmdFields[0]) if len(cmdFields) > 1: diff --git a/flow/util/genMetrics_test.py b/flow/util/genMetrics_test.py index fb84391e2f..4637382626 100644 --- a/flow/util/genMetrics_test.py +++ b/flow/util/genMetrics_test.py @@ -11,6 +11,41 @@ import genMetrics +class OpenroadBinaryTests(unittest.TestCase): + """The version is asked of the binary, not of a wrapper in front of + it: gdb's banner is not a version, and perf record would overwrite + perf.data with a profile of the query.""" + + def binary(self, openroad_exe): + saved = os.environ.get("OPENROAD_EXE") + try: + if openroad_exe is None: + os.environ.pop("OPENROAD_EXE", None) + else: + os.environ["OPENROAD_EXE"] = openroad_exe + return genMetrics.openroad_binary() + finally: + if saved is None: + os.environ.pop("OPENROAD_EXE", None) + else: + os.environ["OPENROAD_EXE"] = saved + + def test_a_path_is_the_binary(self): + self.assertEqual(self.binary("/opt/or/bin/openroad"), "/opt/or/bin/openroad") + + def test_unset_is_openroad_on_path(self): + self.assertEqual(self.binary(None), "openroad") + + def test_the_binary_is_the_last_word_after_a_wrapper(self): + for wrapped in ( + "valgrind /opt/or/bin/openroad", + "perf record -g -- /opt/or/bin/openroad", + "gdb -batch -ex run -ex 'thread apply all bt' --args /opt/or/bin/openroad", + ): + with self.subTest(wrapped): + self.assertEqual(self.binary(wrapped), "/opt/or/bin/openroad") + + class GitHeadCommitTests(unittest.TestCase): """Tests git_head_commit()'s fallback behavior so commit metadata extraction degrades gracefully instead of raising.""" diff --git a/flow/util/utils.mk b/flow/util/utils.mk index 15c20df73d..cb9f5d69e3 100644 --- a/flow/util/utils.mk +++ b/flow/util/utils.mk @@ -201,16 +201,6 @@ view_cells_web: command: $(OPENROAD_NO_EXIT_CMD) -## Provide easy access to debugging -ifdef GDB -export OPENROAD_EXE := gdb --args $(OPENROAD_EXE) -endif - -## Provide easy way to run valgrind -ifdef VALGRIND -export OPENROAD_EXE := valgrind $(VALGRIND_ARGS) $(OPENROAD_EXE) -endif - ## Convert RVE DRC database to JSON .PHONY: convert_rve convert_rve: $(REPORTS_DIR)/drc.json