33#include <system_error>
34#include <unordered_set>
41 #include <boost/asio/io_context.hpp>
42 #include <boost/process/v1/args.hpp>
43 #include <boost/process/v1/async.hpp>
44 #include <boost/process/v1/child.hpp>
45 #include <boost/process/v1/io.hpp>
46 #include <boost/process/v1/search_path.hpp>
47 #include <boost/uuid/random_generator.hpp>
48 #include <boost/uuid/uuid_io.hpp>
52 #elif defined(__APPLE__)
53 #include <mach-o/dyld.h>
61 const SILICON::logging::Logger yosysLog(
"yosys");
71 yosysLog.error(
"External execution is unavailable in Emscripten builds");
72 throw std::runtime_error(
73 "Yosys platform-availability phase failed: external execution is unavailable "
74 "when compiled for Emscripten. See the 'yosys' logs for details.");
79 const std::array sources{
80 SILICON::core::SourceFile{.path =
"source.v", .contents =
source}};
84std::string
readVerilog(
const std::span<const SILICON::core::SourceFile> sources,
85 const std::string_view entryPath,
const ToolOptions& options)
90 throw std::logic_error(
"Unreachable after unavailable Yosys execution");
97 throw std::logic_error(
"Unreachable after unavailable Yosys execution");
104 throw std::logic_error(
"Unreachable after unavailable Yosys execution");
111 class TemporaryWorkspace {
115 const auto temporaryRoot = std::filesystem::temp_directory_path();
116 auto generateUuid = boost::uuids::random_generator{};
118 for (
unsigned attempt = 0; attempt < 128; ++attempt) {
121 / std::format(
"silicon_yosys_{}", boost::uuids::to_string(generateUuid()));
122 std::error_code error;
123 if (std::filesystem::create_directory(directory, error))
125 if (error && error != std::errc::file_exists)
126 throw std::runtime_error(
127 std::format(
"Yosys temporary-workspace creation failed for '{}': {}",
128 directory.string(), error.message()));
130 throw std::runtime_error(
131 "Yosys temporary-workspace creation failed: no unique directory was available");
134 TemporaryWorkspace(
const TemporaryWorkspace&) =
delete;
135 TemporaryWorkspace& operator=(
const TemporaryWorkspace&) =
delete;
137 ~TemporaryWorkspace()
139 std::error_code error;
140 std::filesystem::remove_all(directory, error);
143 [[nodiscard]]
const std::filesystem::path& path()
const {
return directory; }
146 std::filesystem::path directory;
149 void writeFile(
const std::filesystem::path& path,
const std::string_view contents,
150 const std::string_view phase)
152 std::ofstream output(path, std::ios::binary);
154 throw std::runtime_error(
155 std::format(
"Yosys {} failed: could not open '{}'", phase, path.string()));
156 output.write(contents.data(),
static_cast<std::streamsize
>(contents.size()));
158 throw std::runtime_error(
159 std::format(
"Yosys {} failed: could not write '{}'", phase, path.string()));
162 [[nodiscard]]
bool isSafeRelativeSourcePath(
const std::string_view path)
164 if (path.empty() || path.front() ==
'/' || path.back() ==
'/' || path.contains(
'\\')
165 || path.contains(
"//"))
168 const std::filesystem::path filesystemPath(path);
169 if (filesystemPath.has_root_path())
171 for (
const auto& component : filesystemPath)
172 if (component ==
"." || component ==
"..")
175 return std::ranges::none_of(path, [](
const unsigned char character) {
176 return character < 0x20 || character == 0x7f;
180 [[nodiscard]] std::string readFile(
const std::filesystem::path& path,
181 const std::string_view phase)
183 std::ifstream input(path, std::ios::binary);
185 throw std::runtime_error(std::format(
186 "Yosys {} failed: could not open generated file '{}'", phase, path.string()));
187 std::string contents{std::istreambuf_iterator<char>(input),
188 std::istreambuf_iterator<char>()};
190 throw std::runtime_error(std::format(
191 "Yosys {} failed: could not read generated file '{}'", phase, path.string()));
195 [[nodiscard]] std::string quotePath(
const std::filesystem::path& path)
197 std::string result(
"\"");
198 for (
const char character : path.string()) {
199 if (character ==
'\\' || character ==
'"')
206 struct TechnologyLibrary {
207 std::filesystem::path cells;
208 std::filesystem::path technologyMap;
211 [[nodiscard]] std::optional<TechnologyLibrary>
212 libraryAt(
const std::filesystem::path& directory)
214 TechnologyLibrary result{directory /
"silicon_cells.v",
215 directory /
"silicon_techmap.v"};
216 std::error_code error;
217 for (
const auto* path : {&result.cells, &result.technologyMap}) {
218 if (!std::filesystem::is_regular_file(*path, error) || error)
224 [[nodiscard]] std::optional<std::filesystem::path> runningExecutable()
227 std::wstring path(32768, L
'\0');
229 GetModuleFileNameW(
nullptr, path.data(),
static_cast<DWORD
>(path.size()));
230 if (size == 0 || size >= path.size())
233 return std::filesystem::path(std::move(path));
234 #elif defined(__APPLE__)
235 std::uint32_t size = 0;
236 (void)_NSGetExecutablePath(
nullptr, &size);
237 std::vector<char> path(size);
238 if (_NSGetExecutablePath(path.data(), &size) != 0)
240 std::error_code error;
242 std::filesystem::weakly_canonical(std::filesystem::path(path.data()), error);
243 return error ? std::optional(std::filesystem::path(path.data()))
244 : std::optional(std::move(canonical));
246 std::error_code error;
247 auto path = std::filesystem::read_symlink(
"/proc/self/exe", error);
248 return error ? std::nullopt : std::optional(std::move(path));
252 [[nodiscard]] TechnologyLibrary technologyLibrary(
const ToolOptions& options)
254 if (options.technologyLibraryDirectory) {
255 if (
const auto result = libraryAt(*options.technologyLibraryDirectory))
257 throw std::runtime_error(std::format(
258 "Yosys resource-discovery phase failed: configured technology-library "
259 "directory '{}' does not contain silicon_cells.v and silicon_techmap.v",
260 options.technologyLibraryDirectory->string()));
263 std::vector<std::filesystem::path> candidates{
264 std::filesystem::path(SILICON_YOSYS_BUILD_RESOURCE_DIR),
265 std::filesystem::path(SILICON_YOSYS_INSTALL_RESOURCE_DIR),
267 if (
const auto executable = runningExecutable()) {
268 const auto directory = executable->parent_path();
269 candidates.push_back(
270 (directory /
".." / SILICON_YOSYS_INSTALL_RELATIVE_RESOURCE_DIR)
271 .lexically_normal());
272 #if defined(__APPLE__)
273 candidates.push_back((directory /
".." /
"Resources" /
"yosys").lexically_normal());
276 for (
const auto& candidate : candidates)
277 if (
const auto result = libraryAt(candidate))
280 throw std::runtime_error(std::format(
281 "Yosys resource-discovery phase failed: the packaged SILICON technology "
282 "library was not found at '{}' or '{}'",
283 candidates[0].
string(), candidates[1].
string()));
286 [[nodiscard]] std::optional<std::filesystem::path> verilogPlugin()
288 std::vector<std::filesystem::path> candidates;
289 #if defined(SILICON_YOSYS_BUILD_PLUGIN) && defined(SILICON_YOSYS_INSTALL_PLUGIN) \
290 && defined(SILICON_YOSYS_INSTALL_RELATIVE_PLUGIN)
291 candidates = {std::filesystem::path(SILICON_YOSYS_BUILD_PLUGIN),
292 std::filesystem::path(SILICON_YOSYS_INSTALL_PLUGIN)};
293 if (
const auto executable = runningExecutable()) {
294 candidates.push_back(
295 (executable->parent_path() /
".." / SILICON_YOSYS_INSTALL_RELATIVE_PLUGIN)
296 .lexically_normal());
299 for (
const auto& candidate : candidates) {
300 std::error_code error;
301 if (std::filesystem::is_regular_file(candidate, error) && !error)
307 void logCapturedOutput(
const ScriptResult& result,
const bool failed)
309 if (!result.standardOutput.empty())
310 yosysLog.info(std::format(
"stdout:\n{}", result.standardOutput));
311 if (!result.standardError.empty()) {
312 const auto message = std::format(
"stderr:\n{}", result.standardError);
314 yosysLog.error(message);
316 yosysLog.warning(message);
324 namespace process = boost::process::v1;
326 std::filesystem::path executable;
328 std::error_code error;
329 const auto status = std::filesystem::status(*options.
executable, error);
331 if (error || !std::filesystem::exists(status)
332 || !std::filesystem::is_regular_file(status)) {
333 throw std::runtime_error(std::format(
334 "Yosys executable-validation phase failed: configured executable '{}' is "
335 "missing or invalid. See the 'yosys' logs for details.",
340 executable = process::search_path(
"yosys").string();
341 if (executable.empty()) {
342 yosysLog.error(
"Executable 'yosys' was not found on PATH");
343 throw std::runtime_error(
344 "Yosys executable-discovery phase failed: 'yosys' was not found on PATH. "
345 "See the 'yosys' logs for details.");
349 boost::asio::io_context ioContext;
350 std::future<std::string> standardOutput;
351 std::future<std::string> standardError;
352 std::unique_ptr<process::child> child;
354 child = std::make_unique<process::child>(
355 executable.string(), process::args({
"-Q",
"-p", std::string(script)}),
356 process::std_out > standardOutput, process::std_err > standardError, ioContext);
357 }
catch (
const std::exception& error) {
358 yosysLog.error(std::format(
"Process creation failed for '{}': {}",
359 executable.string(), error.what()));
360 throw std::runtime_error(
361 "Yosys process-creation phase failed. See the 'yosys' logs for details.");
367 }
catch (
const std::exception& error) {
369 if (child->running())
372 }
catch (
const std::exception&) {
374 yosysLog.error(std::format(
"Output capture failed: {}", error.what()));
375 throw std::runtime_error(
376 "Yosys output-capture phase failed. See the 'yosys' logs for details.");
381 result = {standardOutput.get(), standardError.get()};
382 }
catch (
const std::exception& error) {
383 yosysLog.error(std::format(
"Output capture failed after exit status {}: {}",
384 child->exit_code(), error.what()));
385 throw std::runtime_error(
386 "Yosys output-capture phase failed. See the 'yosys' logs for details.");
389 const int exitStatus = child->exit_code();
390 logCapturedOutput(result, exitStatus != 0);
391 if (exitStatus != 0) {
392 yosysLog.error(std::format(
"Command failed with exit status {}", exitStatus));
393 throw std::runtime_error(std::format(
394 "Yosys script-execution phase failed with exit status {}. See the 'yosys' "
395 "logs for command output.",
403 const std::array sources{
408std::string
readVerilog(
const std::span<const SILICON::core::SourceFile> sources,
409 const std::string_view entryPath,
const ToolOptions& options)
411 if (!isSafeRelativeSourcePath(entryPath))
412 throw std::invalid_argument(
"Verilog entry path must be a safe relative path");
417 for (
const auto& source : sources) {
418 if (!isSafeRelativeSourcePath(source.path))
419 throw std::invalid_argument(std::format(
420 "Verilog source path '{}' must be a safe relative path", source.path));
421 if (!paths.emplace(source.path).second)
422 throw std::invalid_argument(
423 std::format(
"Duplicate Verilog source path: {}", source.path));
425 if (!paths.contains(entryPath))
426 throw std::invalid_argument(
427 std::format(
"Verilog entry source is missing: {}", entryPath));
429 TemporaryWorkspace workspace;
430 for (
const auto& source : sources) {
431 const auto sourcePath = workspace.path() / std::filesystem::path(source.path);
432 std::error_code error;
433 std::filesystem::create_directories(sourcePath.parent_path(), error);
435 throw std::runtime_error(std::format(
436 "Yosys Verilog-read input-writing phase failed: could not create '{}': {}",
437 sourcePath.parent_path().string(), error.message()));
438 writeFile(sourcePath, source.contents,
"Verilog-read input-writing phase");
441 const auto sourcePath = workspace.path() / std::filesystem::path(entryPath);
442 const auto jsonPath = workspace.path() /
"design.json";
444 (void)
runScript(std::format(
"read_verilog -noautowire {}\n"
456 quotePath(sourcePath), quotePath(jsonPath)),
458 return readFile(jsonPath,
"Verilog-read output-reading phase");
463 TemporaryWorkspace workspace;
464 const auto inputPath = workspace.path() /
"design.json";
465 const auto outputPath = workspace.path() /
"elaborated.json";
466 writeFile(inputPath, json,
"Yosys-elaboration input-writing phase");
468 const auto library = technologyLibrary(options);
469 const auto plugin = verilogPlugin();
471 throw std::runtime_error(
472 "SILICON Yosys legalization requires the SILICON Yosys plugin");
473 const std::string pluginLoad =
474 std::format(
"plugin -i {}\n", quotePath(*plugin));
475 const std::string legalization =
476 std::format(
"silicon_legalize {}\n", quotePath(library.technologyMap));
478 (void)
runScript(std::format(
"read_verilog -lib -D SILICON_BLACKBOX {}\n"
487 quotePath(library.cells), quotePath(inputPath), pluginLoad,
489 quotePath(outputPath)),
491 return readFile(outputPath,
"Yosys-elaboration output-reading phase");
496 TemporaryWorkspace workspace;
497 const auto library = technologyLibrary(options);
498 const auto jsonPath = workspace.path() /
"design.json";
499 const auto verilogPath = workspace.path() /
"design.v";
500 writeFile(jsonPath, json,
"Verilog-export input-writing phase");
502 const auto plugin = verilogPlugin();
503 const auto muxExport =
504 plugin ? std::format(
"plugin -i {}\nsilicon_bmux_case\n", quotePath(*plugin))
507 const std::string_view backendOptions =
509 ?
"-norename -decimal" :
"-noattr -norename -decimal";
511 (void)
runScript(std::format(
"read_verilog -lib -D SILICON_BLACKBOX {}\n"
513 "hierarchy -check -auto-top\n"
514 "techmap -autoproc -D SILICON_EXPORT_MAP -map {}\n"
520 "rename -enumerate\n"
521 "write_verilog {} {}\n",
522 quotePath(library.cells), quotePath(jsonPath),
523 quotePath(library.cells), muxExport,
524 backendOptions, quotePath(verilogPath)),
526 return readFile(verilogPath,
"Verilog-export output-reading phase");
constexpr std::string_view BINARY_DOCUMENT
std::string elaborateHierarchy(const std::string_view json, const ToolOptions &options)
ScriptResult runScript(const std::string_view script, const ToolOptions &options)
std::string writeVerilog(std::string_view json, const ToolOptions &options)
std::string readVerilog(const std::string_view source, const ToolOptions &options)
Transparent equality functor for string-like keys.
Transparent hash functor for string-like keys.