SAIFIINDUSTRIES's picture
Add batch 1 (YosysHQ_picorv32, alexforencich_verilog-ethernet, The-OpenROAD-Project_OpenROAD, darklife_darkriscv, corundum_corundum)
f61bac1 verified
Raw History Blame Contribute Delete
20.4 kB
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2019-2025, The OpenROAD Authors
#include <stdlib.h> // NOLINT(modernize-deprecated-headers): for setenv()
#include <strings.h>
#include <array>
#include <charconv>
#include <climits>
#include <clocale>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <iostream>
#include <memory>
#include <string>
#include <system_error>
#include "absl/base/no_destructor.h"
#include "boost/stacktrace/stacktrace.hpp"
#include "tcl.h"
#include "tclDecls.h"
#ifdef ENABLE_PYTHON3
#define PY_SSIZE_T_CLEAN
#include "Python.h"
#endif
#ifdef ENABLE_TCLX
#include <tclExtend.h>
#endif
#include "cut/abc_init.h"
#include "gui/gui.h"
#include "ord/Design.h"
#include "ord/InitOpenRoad.hh"
#include "ord/OpenRoad.hh"
#include "ord/Tech.h"
#include "sta/StaMain.hh"
#include "sta/StringUtil.hh"
#include "utl/Logger.h"
#include "utl/decode.h"
#include "web/web.h"
#ifdef BAZEL_BUILD
#include "bazel/tcl_library_init.h"
#endif
#include "tcl_readline_setup.h"
using sta::findCmdLineFlag;
using sta::findCmdLineKey;
using sta::sourceTclFile;
using sta::stringEq;
using std::string;
#ifdef ENABLE_PYTHON3
#define FOREACH_TOOL_WITHOUT_OPENROAD(X) \
X(ifp) \
X(utl) \
X(ant) \
X(grt) \
X(gpl) \
X(dpl) \
X(exa) \
X(web) \
X(ppl) \
X(tap) \
X(cts) \
X(drt) \
X(fin) \
X(par) \
X(rcx) \
X(rmp) \
X(cgt) \
X(stt) \
X(syn) \
X(psm) \
X(pdn) \
X(rsz) \
X(odb) \
X(ord)
#define FOREACH_TOOL(X) FOREACH_TOOL_WITHOUT_OPENROAD(X)
extern "C" {
#define X(name) extern PyObject* PyInit__##name##_py();
FOREACH_TOOL(X)
#undef X
}
#endif
int cmd_argc;
char** cmd_argv;
static const char* log_filename = nullptr;
static const char* metrics_filename = nullptr;
static const char* read_odb_filename = nullptr;
static bool no_settings = false;
static bool minimize = false;
static bool web_enabled = false;
static const char* web_port_arg = nullptr;
static const char* init_filename = ".openroad";
static void showUsage(const char* prog, const char* init_filename);
static void showSplash();
#ifdef ENABLE_PYTHON3
#define X(name) \
namespace name { \
extern const char* name##_py_python_inits[]; \
}
FOREACH_TOOL(X)
#undef X
#if PY_VERSION_HEX >= 0x03080000
static void initPython(int argc, char* argv[], const bool exit_after_cmd_file)
#else
static void initPython()
#endif
{
#define X(name) \
if (PyImport_AppendInittab("_" #name "_py", PyInit__##name##_py) == -1) { \
fprintf(stderr, "Error: could not add module _" #name "_py\n"); \
exit(1); \
}
FOREACH_TOOL(X)
#undef X
#if PY_VERSION_HEX >= 0x03080000
PyConfig config;
PyConfig_InitPythonConfig(&config);
PyConfig_SetBytesArgv(&config, argc, argv);
config.inspect = !exit_after_cmd_file;
Py_InitializeFromConfig(&config);
PyConfig_Clear(&config);
#else
Py_Initialize();
#endif
#define X(name) \
{ \
std::string unencoded = utl::base64_decode(name::name##_py_python_inits); \
PyObject* code \
= Py_CompileString(unencoded.c_str(), #name "_py.py", Py_file_input); \
if (code == nullptr) { \
PyErr_Print(); \
fprintf(stderr, "Error: could not compile " #name "_py\n"); \
exit(1); \
} \
if (PyImport_ExecCodeModule(#name, code) == nullptr) { \
PyErr_Print(); \
fprintf(stderr, "Error: could not add module " #name "\n"); \
exit(1); \
} \
}
FOREACH_TOOL_WITHOUT_OPENROAD(X)
#undef X
#undef FOREACH_TOOL
#undef FOREACH_TOOL_WITHOUT_OPENROAD
#undef FOREACH_SYN_PYTHON_TOOL
// Need to separately handle openroad here because we need both
// the names "openroad_swig" and "openroad".
{
std::string unencoded = utl::base64_decode(ord::ord_py_python_inits);
PyObject* code
= Py_CompileString(unencoded.c_str(), "openroad.py", Py_file_input);
if (code == nullptr) {
PyErr_Print();
fprintf(stderr, "Error: could not compile openroad.py\n");
exit(1);
}
if (PyImport_ExecCodeModule("openroad", code) == nullptr) {
PyErr_Print();
fprintf(stderr, "Error: could not add module openroad\n");
exit(1);
}
}
}
#endif
static volatile sig_atomic_t fatal_error_in_progress = 0;
// When we enter through main() we have a single tech and design.
// Custom applications using OR as a library might define multiple.
// Such applications won't allocate or use these objects.
// Use a wrapper struct to hold the objects. They are wrapped in
// absl::NoDestructor below to intentionally leak them and avoid
// static destruction order issues.
struct TechAndDesign
{
std::unique_ptr<ord::Tech> tech;
std::unique_ptr<ord::Design> design;
};
static absl::NoDestructor<TechAndDesign> the_tech_and_design;
static void handler(int sig)
{
if (fatal_error_in_progress) {
raise(sig);
}
fatal_error_in_progress = 1;
std::cerr << "Signal " << sig << " received\n";
std::cerr << "Stack trace:\n";
std::cerr << boost::stacktrace::stacktrace();
signal(sig, SIG_DFL);
raise(sig);
}
int main(int argc, char* argv[])
{
// This avoids problems with locale setting dependent
// C functions like strtod (e.g. 0.5 vs 0,5).
std::array locales = {"en_US.UTF-8", "C.UTF-8", "C"};
for (auto locale : locales) {
if (std::setlocale(LC_ALL, locale) != nullptr) {
setenv("LC_ALL", locale, /* override */ 1);
break;
}
}
// Generate a stacktrace on crash
signal(SIGABRT, handler);
signal(SIGBUS, handler);
signal(SIGFPE, handler);
signal(SIGILL, handler);
signal(SIGSEGV, handler);
if (argc == 2 && stringEq(argv[1], "-help")) {
showUsage(argv[0], init_filename);
return 0;
}
if (argc == 2 && stringEq(argv[1], "-version")) {
printf("%s %s\n",
ord::OpenRoad::getVersion(),
ord::OpenRoad::getGitDescribe());
return 0;
}
log_filename = findCmdLineKey(argc, argv, "-log");
if (log_filename) {
std::error_code err_ignore;
std::filesystem::remove(log_filename, err_ignore);
}
metrics_filename = findCmdLineKey(argc, argv, "-metrics");
if (metrics_filename) {
std::error_code err_ignored;
std::filesystem::remove(metrics_filename, err_ignored);
}
read_odb_filename = findCmdLineKey(argc, argv, "-db");
no_settings = findCmdLineFlag(argc, argv, "-no_settings");
minimize = findCmdLineFlag(argc, argv, "-minimize");
web_enabled = findCmdLineFlag(argc, argv, "-web");
web_port_arg = findCmdLineKey(argc, argv, "-web_port");
cmd_argc = argc;
cmd_argv = argv;
#ifdef ENABLE_PYTHON3
if (findCmdLineFlag(cmd_argc, cmd_argv, "-python")) {
// Setup the app with tcl
auto* interp = Tcl_CreateInterp();
Tcl_Init(interp);
the_tech_and_design->tech = std::make_unique<ord::Tech>(interp);
the_tech_and_design->design
= std::make_unique<ord::Design>(the_tech_and_design->tech.get());
const bool exit = findCmdLineFlag(cmd_argc, cmd_argv, "-exit");
ord::initOpenRoad(interp, log_filename, metrics_filename, exit);
if (!findCmdLineFlag(cmd_argc, cmd_argv, "-no_splash")) {
showSplash();
}
utl::Logger* logger = ord::OpenRoad::openRoad()->getLogger();
if (findCmdLineFlag(cmd_argc, cmd_argv, "-gui")) {
logger->warn(utl::ORD, 38, "-gui is not yet supported with -python");
}
if (!findCmdLineFlag(cmd_argc, cmd_argv, "-no_init")) {
logger->warn(utl::ORD, 39, ".openroad ignored with -python");
}
const char* threads = findCmdLineKey(cmd_argc, cmd_argv, "-threads");
if (threads) {
ord::OpenRoad::openRoad()->setThreadCount(threads);
} else {
// set to default number of threads
ord::OpenRoad::openRoad()->setThreadCount(
ord::OpenRoad::openRoad()->getThreadCount(), false);
}
#if PY_VERSION_HEX >= 0x03080000
initPython(cmd_argc, cmd_argv, exit);
return Py_RunMain();
#else
initPython();
std::vector<wchar_t*> args;
args.push_back(Py_DecodeLocale(cmd_argv[0], nullptr));
if (!exit) {
args.push_back(Py_DecodeLocale("-i", nullptr));
}
for (int i = 1; i < cmd_argc; i++) {
args.push_back(Py_DecodeLocale(cmd_argv[i], nullptr));
}
return Py_Main(args.size(), args.data());
#endif // PY_VERSION_HEX >= 0x03080000
}
#endif // ENABLE_PYTHON3
// Set argc to 1 so Tcl_Main doesn't source any files.
// Tcl_Main never returns.
Tcl_Main(1, argv, ord::tclAppInit);
cut::abcStop();
return 0;
}
static int tclOrdReplInit(Tcl_Interp* interp)
{
// SetupTclReadlineLibrary has already registered ::tclreadline::Loop
// (linenoise-backed REPL). Hand control over; the loop never returns.
return Tcl_Eval(interp, "::tclreadline::Loop");
}
// Tcl init executed inside Tcl_Main.
static int tclAppInit(int& argc,
char* argv[],
const char* init_filename,
Tcl_Interp* interp)
{
bool exit_after_cmd_file = false;
// first check if gui was requested and launch.
// gui will call this function again as part of setup
// ensuring the else {} will be utilized to initialize tcl and OR.
if (findCmdLineFlag(argc, argv, "-gui")) {
// gobble up remaining -gui flags if present, since this could result in
// second invocation of the GUI
while (findCmdLineFlag(argc, argv, "-gui")) {
;
}
gui::startGui(argc, argv, interp, "", true, !no_settings, minimize);
} else {
// Initialize tcl interpreter and readline.
exit_after_cmd_file = findCmdLineFlag(argc, argv, "-exit");
#ifdef BAZEL_BUILD
if (in_bazel::SetupTclEnvironment(interp) == TCL_ERROR) {
return TCL_ERROR;
}
#endif
if (Tcl_Init(interp) == TCL_ERROR) {
return TCL_ERROR;
}
#ifdef ENABLE_TCLX
if (Tclx_Init(interp) == TCL_ERROR) {
return TCL_ERROR;
}
#endif
// Register the ::tclreadline namespace shim unconditionally: it's
// cheap, and Tcl scripts (including non-interactive ones) may probe
// [info exists tclreadline::version] or call ::tclreadline::complete.
if (ord::SetupTclReadlineLibrary(interp) == TCL_ERROR) {
printf("Failed to set up tclreadline shim\n");
}
ord::initOpenRoad(
interp, log_filename, metrics_filename, exit_after_cmd_file);
// Register the web server's log sink early (before splash/thread output
// and read_db) so the WebLogSink captures all startup messages for the
// browser console. The network and browser are NOT opened here — that
// happens later in serve(), just before waitForStop(), once the database
// is fully loaded. Opening them here would let a connecting client run
// Search::eagerInit on the I/O worker threads while read_db is still
// mutating the db on this thread — a coredump in
// odb::dbBPinItr::getObject(). See issue #10576.
int web_port = 0;
if (web_enabled) {
if (web_port_arg) {
const char* end = web_port_arg + std::strlen(web_port_arg);
auto [ptr, ec] = std::from_chars(web_port_arg, end, web_port);
if (ec != std::errc{} || ptr != end || web_port < 0
|| web_port > 65535) {
fprintf(
stderr, "Error: invalid -web_port value '%s'\n", web_port_arg);
exit(EXIT_FAILURE);
}
}
ord::OpenRoad::openRoad()->getWebServer()->initLogger();
}
bool no_splash = findCmdLineFlag(argc, argv, "-no_splash");
if (!no_splash) {
showSplash();
}
const char* threads = findCmdLineKey(argc, argv, "-threads");
if (threads) {
ord::OpenRoad::openRoad()->setThreadCount(threads, !no_splash);
} else {
// set to default number of threads
ord::OpenRoad::openRoad()->setThreadCount(
ord::OpenRoad::openRoad()->getThreadCount(), false);
}
// The web server now installs its HeadlessViewer late, in serve() (just
// before waitForStop), so gui::Gui::enabled() is still false here in the
// web path. The `&& !web_enabled` is kept defensively: even with a
// viewer installed, the web server executes scripts directly on the main
// thread (like the non-GUI path), and addRestoreStateCommand() only
// works with the Qt event loop.
const bool gui_enabled = gui::Gui::enabled() && !web_enabled;
if (read_odb_filename) {
std::string cmd = fmt::format("read_db {{{}}}", read_odb_filename);
if (!gui_enabled) {
if (Tcl_Eval(interp, cmd.c_str()) != TCL_OK) {
fprintf(stderr,
"Error: failed to read_db %s: %s\n",
read_odb_filename,
Tcl_GetStringResult(interp));
exit(1);
}
} else {
gui::Gui::get()->addRestoreStateCommand(cmd);
}
}
const char* home = getenv("HOME");
if (!findCmdLineFlag(argc, argv, "-no_init") && home) {
const char* restore_state_cmd = "include -echo -verbose {{{}}}";
std::filesystem::path init(home);
init /= init_filename;
if (std::filesystem::is_regular_file(init)) {
if (!gui_enabled) {
sourceTclFile(init.c_str(), true, true, interp);
} else {
// need to delay loading of file until after GUI is completed
// initialized
gui::Gui::get()->addRestoreStateCommand(
fmt::format(FMT_RUNTIME(restore_state_cmd), init.string()));
}
}
}
if (argc > 2 || (argc > 1 && argv[1][0] == '-')) {
showUsage(argv[0], init_filename);
Tcl_Exit(1);
} else {
if (argc == 2) {
char* cmd_file = argv[1];
if (cmd_file) {
if (!gui_enabled) {
int result = sourceTclFile(cmd_file, false, false, interp);
if (exit_after_cmd_file) {
int exit_code = (result == TCL_OK) ? EXIT_SUCCESS : EXIT_FAILURE;
Tcl_Exit(exit_code);
}
} else {
// need to delay loading of file until after GUI is completed
// initialized
gui::Gui::get()->addRestoreStateCommand(
fmt::format("source {{{}}}", cmd_file));
if (exit_after_cmd_file) {
gui::Gui::get()->addRestoreStateCommand("exit");
}
}
}
}
}
// read_db and any startup scripts have now run to completion on this
// thread, so the database is fully loaded and stable. Open the network
// and browser now: a connecting client's Search::eagerInit will index a
// settled db instead of racing read_db (the issue #10576 coredump).
// Then block until the web server is stopped (like QApplication::exec()
// for the GUI). After this returns, fall through to readline.
if (web_enabled) {
auto* server = ord::OpenRoad::openRoad()->getWebServer();
server->serve(web_port);
server->waitForStop();
// `exit` typed in the browser Tcl widget signalled stop; do the
// real process exit now from the main thread (worker threads are
// already joined by stop()).
if (server->exitRequested()) {
Tcl_Exit(EXIT_SUCCESS);
}
}
}
// Enter the linenoise REPL unless the Qt GUI is active (it has its
// own script widget). The web viewer's headless mode still needs the
// terminal prompt.
if (!gui::Gui::hasUI() && !exit_after_cmd_file) {
return tclOrdReplInit(interp);
}
return TCL_OK;
}
[[noreturn]] static void exitTclAppInitError(Tcl_Interp* interp)
{
fprintf(stderr,
"application-specific initialization failed: %s\n",
Tcl_GetStringResult(interp));
exit(EXIT_FAILURE);
}
int ord::tclAppInit(Tcl_Interp* interp)
{
the_tech_and_design->tech = std::make_unique<ord::Tech>(interp);
the_tech_and_design->design
= std::make_unique<ord::Design>(the_tech_and_design->tech.get());
// This is to enable Design.i where a design arg can be
// retrieved from the interpreter. This is necessary for
// cases with more than one interpreter (ie more than one Design).
// This should replace the use of the singleton OpenRoad::openRoad().
Tcl_SetAssocData(
interp, "design", nullptr, the_tech_and_design->design.get());
const int result = ord::tclInit(interp);
if (result != TCL_OK) {
exitTclAppInitError(interp);
}
return TCL_OK;
}
int ord::tclInit(Tcl_Interp* interp)
{
return tclAppInit(cmd_argc, cmd_argv, init_filename, interp);
}
static void showUsage(const char* prog, const char* init_filename)
{
printf("Usage: %s [-help] [-version] [-no_init] [-no_splash] [-exit] ", prog);
printf("[-gui] [-web] [-threads count|max] [-log file_name] ");
printf("[-metrics file_name] [-db file_name] [-no_settings] [-minimize] ");
printf("cmd_file\n");
printf(" -help show help and exit\n");
printf(" -version show version and exit\n");
printf(" -no_init do not read %s init file\n", init_filename);
printf(" -threads count|max use count threads\n");
printf(" -no_splash do not show the license splash at startup\n");
printf(" -exit exit after reading cmd_file\n");
printf(" -gui start in gui mode\n");
printf(" -web start in web viewer mode\n");
printf(" -web_port port web server port (default auto-assigned)\n");
printf(" -minimize start the gui minimized\n");
printf(" -no_settings do not load the previous gui settings\n");
#ifdef ENABLE_PYTHON3
printf(
" -python start with python interpreter [limited to db "
"operations]\n");
#endif
printf(" -log <file_name> write a log in <file_name>\n");
printf(
" -metrics <file_name> write metrics in <file_name> in JSON format\n");
printf(" -db <file_name> open a .odb database at startup\n");
printf(" cmd_file source cmd_file\n");
}
static void showSplash()
{
utl::Logger* logger = ord::OpenRoad::openRoad()->getLogger();
logger->report("OpenROAD {} {}",
ord::OpenRoad::getVersion(),
ord::OpenRoad::getGitDescribe());
logger->report(
"Features included (+) or not (-): "
"{}GPU {}GUI {}Python{}",
ord::OpenRoad::getGPUCompileOption() ? "+" : "-",
ord::OpenRoad::getGUICompileOption() ? "+" : "-",
ord::OpenRoad::getPythonCompileOption() ? "+" : "-",
#ifdef BAZEL_BUILD
strcasecmp(BUILD_TYPE, "opt") == 0
#else
strcasecmp(BUILD_TYPE, "release") == 0
#endif
? ""
: fmt::format(" : {}", BUILD_TYPE));
logger->report(
"This program is licensed under the BSD-3 license. See the LICENSE file "
"for details.");
logger->report(
"Components of this program may be licensed under more restrictive "
"licenses which must be honored.");
}