From 35c8ad61ac9baaacf7919359b63b930e37d21b09 Mon Sep 17 00:00:00 2001 From: Mohamed Gaber Date: Mon, 30 Sep 2024 17:38:43 +0300 Subject: [PATCH] cli/python: error-checking, python interpreter bugfix * Less brittle method of adding script dirname to sys.path * Check if scriptfp successfully opens before using it * Move `log_error` to after `PyErr_Print()` is called --- kernel/driver.cc | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/kernel/driver.cc b/kernel/driver.cc index d30b19c96fe..53608c260e4 100644 --- a/kernel/driver.cc +++ b/kernel/driver.cc @@ -665,13 +665,19 @@ int main(int argc, char **argv) PyObject_SetAttrString(sys, "argv", new_argv); Py_DECREF(old_argv); - PyRun_SimpleString(("import os;sys.path.insert(0, os.path.dirname(os.path.abspath(\""+scriptfile+"\")))").c_str()); + PyObject *py_path = PyUnicode_FromString(scriptfile.c_str()); + PyObject_SetAttrString(sys, "_yosys_script_path", py_path); + Py_DECREF(py_path); + PyRun_SimpleString("import os, sys; sys.path.insert(0, os.path.dirname(os.path.abspath(sys._yosys_script_path)))"); FILE *scriptfp = fopen(scriptfile.c_str(), "r"); + if (scriptfp == nullptr) { + log_error("Failed to open file '%s' for reading.\n", scriptfile.c_str()); + } if (PyRun_SimpleFile(scriptfp, scriptfile.c_str()) != 0) { - log_error("Python interpreter encountered an error:\n"); log_flush(); PyErr_Print(); + log_error("Python interpreter encountered an exception."); } #else log_error("Can't execute Python script: this version of yosys is not built with Python support enabled.\n");