File size: 20,376 Bytes
f61bac1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 | // 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.");
}
|