09909696be1df467585471e1fd021565220088ab
[yosys.git] / kernel / yosys.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 *
18 */
19
20 #include "kernel/yosys.h"
21 #include "kernel/celltypes.h"
22
23 #ifdef YOSYS_ENABLE_READLINE
24 # include <readline/readline.h>
25 # include <readline/history.h>
26 #endif
27
28 #ifdef YOSYS_ENABLE_EDITLINE
29 # include <editline/readline.h>
30 #endif
31
32 #ifdef YOSYS_ENABLE_PLUGINS
33 # include <dlfcn.h>
34 #endif
35
36 #if defined(_WIN32)
37 # include <windows.h>
38 # include <io.h>
39 #elif defined(__APPLE__)
40 # include <mach-o/dyld.h>
41 # include <unistd.h>
42 # include <dirent.h>
43 # include <sys/stat.h>
44 #else
45 # include <unistd.h>
46 # include <dirent.h>
47 # include <sys/types.h>
48 # include <sys/stat.h>
49 # if !defined(YOSYS_DISABLE_SPAWN)
50 # include <sys/wait.h>
51 # endif
52 #endif
53
54 #if !defined(_WIN32) && defined(YOSYS_ENABLE_GLOB)
55 # include <glob.h>
56 #endif
57
58 #ifdef __FreeBSD__
59 # include <sys/sysctl.h>
60 #endif
61
62 #ifdef WITH_PYTHON
63 #if PY_MAJOR_VERSION >= 3
64 # define INIT_MODULE PyInit_libyosys
65 extern "C" PyObject* INIT_MODULE();
66 #else
67 # define INIT_MODULE initlibyosys
68 extern "C" void INIT_MODULE();
69 #endif
70 #include <signal.h>
71 #endif
72
73 #include <limits.h>
74 #include <errno.h>
75
76 YOSYS_NAMESPACE_BEGIN
77
78 int autoidx = 1;
79 int yosys_xtrace = 0;
80 RTLIL::Design *yosys_design = NULL;
81 CellTypes yosys_celltypes;
82
83 #ifdef YOSYS_ENABLE_TCL
84 Tcl_Interp *yosys_tcl_interp = NULL;
85 #endif
86
87 std::set<std::string> yosys_input_files, yosys_output_files;
88
89 bool memhasher_active = false;
90 uint32_t memhasher_rng = 123456;
91 std::vector<void*> memhasher_store;
92
93 std::string yosys_share_dirname;
94 std::string yosys_abc_executable;
95
96 void init_share_dirname();
97 void init_abc_executable_name();
98
99 void memhasher_on()
100 {
101 #if defined(__linux__) || defined(__FreeBSD__)
102 memhasher_rng += time(NULL) << 16 ^ getpid();
103 #endif
104 memhasher_store.resize(0x10000);
105 memhasher_active = true;
106 }
107
108 void memhasher_off()
109 {
110 for (auto p : memhasher_store)
111 if (p) free(p);
112 memhasher_store.clear();
113 memhasher_active = false;
114 }
115
116 void memhasher_do()
117 {
118 memhasher_rng ^= memhasher_rng << 13;
119 memhasher_rng ^= memhasher_rng >> 17;
120 memhasher_rng ^= memhasher_rng << 5;
121
122 int size, index = (memhasher_rng >> 4) & 0xffff;
123 switch (memhasher_rng & 7) {
124 case 0: size = 16; break;
125 case 1: size = 256; break;
126 case 2: size = 1024; break;
127 case 3: size = 4096; break;
128 default: size = 0;
129 }
130 if (index < 16) size *= 16;
131 memhasher_store[index] = realloc(memhasher_store[index], size);
132 }
133
134 void yosys_banner()
135 {
136 log("\n");
137 log(" /----------------------------------------------------------------------------\\\n");
138 log(" | |\n");
139 log(" | yosys -- Yosys Open SYnthesis Suite |\n");
140 log(" | |\n");
141 log(" | Copyright (C) 2012 - 2020 Claire Xenia Wolf <claire@yosyshq.com> |\n");
142 log(" | |\n");
143 log(" | Permission to use, copy, modify, and/or distribute this software for any |\n");
144 log(" | purpose with or without fee is hereby granted, provided that the above |\n");
145 log(" | copyright notice and this permission notice appear in all copies. |\n");
146 log(" | |\n");
147 log(" | THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES |\n");
148 log(" | WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |\n");
149 log(" | MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR |\n");
150 log(" | ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |\n");
151 log(" | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |\n");
152 log(" | ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF |\n");
153 log(" | OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |\n");
154 log(" | |\n");
155 log(" \\----------------------------------------------------------------------------/\n");
156 log("\n");
157 log(" %s\n", yosys_version_str);
158 log("\n");
159 }
160
161 int ceil_log2(int x)
162 {
163 #if defined(__GNUC__)
164 return x > 1 ? (8*sizeof(int)) - __builtin_clz(x-1) : 0;
165 #else
166 if (x <= 0)
167 return 0;
168 for (int i = 0; i < 32; i++)
169 if (((x-1) >> i) == 0)
170 return i;
171 log_abort();
172 #endif
173 }
174
175 std::string stringf(const char *fmt, ...)
176 {
177 std::string string;
178 va_list ap;
179
180 va_start(ap, fmt);
181 string = vstringf(fmt, ap);
182 va_end(ap);
183
184 return string;
185 }
186
187 std::string vstringf(const char *fmt, va_list ap)
188 {
189 std::string string;
190 char *str = NULL;
191
192 #if defined(_WIN32 )|| defined(__CYGWIN__)
193 int sz = 64, rc;
194 while (1) {
195 va_list apc;
196 va_copy(apc, ap);
197 str = (char*)realloc(str, sz);
198 rc = vsnprintf(str, sz, fmt, apc);
199 va_end(apc);
200 if (rc >= 0 && rc < sz)
201 break;
202 sz *= 2;
203 }
204 #else
205 if (vasprintf(&str, fmt, ap) < 0)
206 str = NULL;
207 #endif
208
209 if (str != NULL) {
210 string = str;
211 free(str);
212 }
213
214 return string;
215 }
216
217 int readsome(std::istream &f, char *s, int n)
218 {
219 int rc = int(f.readsome(s, n));
220
221 // f.readsome() sometimes returns 0 on a non-empty stream..
222 if (rc == 0) {
223 int c = f.get();
224 if (c != EOF) {
225 *s = c;
226 rc = 1;
227 }
228 }
229
230 return rc;
231 }
232
233 std::string next_token(std::string &text, const char *sep, bool long_strings)
234 {
235 size_t pos_begin = text.find_first_not_of(sep);
236
237 if (pos_begin == std::string::npos)
238 pos_begin = text.size();
239
240 if (long_strings && pos_begin != text.size() && text[pos_begin] == '"') {
241 string sep_string = sep;
242 for (size_t i = pos_begin+1; i < text.size(); i++) {
243 if (text[i] == '"' && (i+1 == text.size() || sep_string.find(text[i+1]) != std::string::npos)) {
244 std::string token = text.substr(pos_begin, i-pos_begin+1);
245 text = text.substr(i+1);
246 return token;
247 }
248 if (i+1 < text.size() && text[i] == '"' && text[i+1] == ';' && (i+2 == text.size() || sep_string.find(text[i+2]) != std::string::npos)) {
249 std::string token = text.substr(pos_begin, i-pos_begin+1);
250 text = text.substr(i+2);
251 return token + ";";
252 }
253 }
254 }
255
256 size_t pos_end = text.find_first_of(sep, pos_begin);
257
258 if (pos_end == std::string::npos)
259 pos_end = text.size();
260
261 std::string token = text.substr(pos_begin, pos_end-pos_begin);
262 text = text.substr(pos_end);
263 return token;
264 }
265
266 std::vector<std::string> split_tokens(const std::string &text, const char *sep)
267 {
268 std::vector<std::string> tokens;
269 std::string current_token;
270 for (char c : text) {
271 if (strchr(sep, c)) {
272 if (!current_token.empty()) {
273 tokens.push_back(current_token);
274 current_token.clear();
275 }
276 } else
277 current_token += c;
278 }
279 if (!current_token.empty()) {
280 tokens.push_back(current_token);
281 current_token.clear();
282 }
283 return tokens;
284 }
285
286 // this is very similar to fnmatch(). the exact rules used by this
287 // function are:
288 //
289 // ? matches any character except
290 // * matches any sequence of characters
291 // [...] matches any of the characters in the list
292 // [!..] matches any of the characters not in the list
293 //
294 // a backslash may be used to escape the next characters in the
295 // pattern. each special character can also simply match itself.
296 //
297 bool patmatch(const char *pattern, const char *string)
298 {
299 if (*pattern == 0)
300 return *string == 0;
301
302 if (*pattern == '\\') {
303 if (pattern[1] == string[0] && patmatch(pattern+2, string+1))
304 return true;
305 }
306
307 if (*pattern == '?') {
308 if (*string == 0)
309 return false;
310 return patmatch(pattern+1, string+1);
311 }
312
313 if (*pattern == '*') {
314 while (*string) {
315 if (patmatch(pattern+1, string++))
316 return true;
317 }
318 return pattern[1] == 0;
319 }
320
321 if (*pattern == '[') {
322 bool found_match = false;
323 bool inverted_list = pattern[1] == '!';
324 const char *p = pattern + (inverted_list ? 1 : 0);
325
326 while (*++p) {
327 if (*p == ']') {
328 if (found_match != inverted_list && patmatch(p+1, string+1))
329 return true;
330 break;
331 }
332
333 if (*p == '\\') {
334 if (*++p == *string)
335 found_match = true;
336 } else
337 if (*p == *string)
338 found_match = true;
339 }
340 }
341
342 if (*pattern == *string)
343 return patmatch(pattern+1, string+1);
344
345 return false;
346 }
347
348 #if !defined(YOSYS_DISABLE_SPAWN)
349 int run_command(const std::string &command, std::function<void(const std::string&)> process_line)
350 {
351 if (!process_line)
352 return system(command.c_str());
353
354 FILE *f = popen(command.c_str(), "r");
355 if (f == nullptr)
356 return -1;
357
358 std::string line;
359 char logbuf[128];
360 while (fgets(logbuf, 128, f) != NULL) {
361 line += logbuf;
362 if (!line.empty() && line.back() == '\n')
363 process_line(line), line.clear();
364 }
365 if (!line.empty())
366 process_line(line);
367
368 int ret = pclose(f);
369 if (ret < 0)
370 return -1;
371 #ifdef _WIN32
372 return ret;
373 #else
374 return WEXITSTATUS(ret);
375 #endif
376 }
377 #endif
378
379 std::string make_temp_file(std::string template_str)
380 {
381 #if defined(__wasm)
382 size_t pos = template_str.rfind("XXXXXX");
383 log_assert(pos != std::string::npos);
384 static size_t index = 0;
385 template_str.replace(pos, 6, stringf("%06zu", index++));
386 #elif defined(_WIN32)
387 if (template_str.rfind("/tmp/", 0) == 0) {
388 # ifdef __MINGW32__
389 char longpath[MAX_PATH + 1];
390 char shortpath[MAX_PATH + 1];
391 # else
392 WCHAR longpath[MAX_PATH + 1];
393 TCHAR shortpath[MAX_PATH + 1];
394 # endif
395 if (!GetTempPath(MAX_PATH+1, longpath))
396 log_error("GetTempPath() failed.\n");
397 if (!GetShortPathName(longpath, shortpath, MAX_PATH + 1))
398 log_error("GetShortPathName() failed.\n");
399 std::string path;
400 for (int i = 0; shortpath[i]; i++)
401 path += char(shortpath[i]);
402 template_str = stringf("%s\\%s", path.c_str(), template_str.c_str() + 5);
403 }
404
405 size_t pos = template_str.rfind("XXXXXX");
406 log_assert(pos != std::string::npos);
407
408 while (1) {
409 for (int i = 0; i < 6; i++) {
410 static std::string y = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
411 static uint32_t x = 314159265 ^ uint32_t(time(NULL));
412 x ^= x << 13, x ^= x >> 17, x ^= x << 5;
413 template_str[pos+i] = y[x % y.size()];
414 }
415 if (_access(template_str.c_str(), 0) != 0)
416 break;
417 }
418 #else
419 size_t pos = template_str.rfind("XXXXXX");
420 log_assert(pos != std::string::npos);
421
422 int suffixlen = GetSize(template_str) - pos - 6;
423
424 char *p = strdup(template_str.c_str());
425 close(mkstemps(p, suffixlen));
426 template_str = p;
427 free(p);
428 #endif
429
430 return template_str;
431 }
432
433 std::string make_temp_dir(std::string template_str)
434 {
435 #if defined(_WIN32)
436 template_str = make_temp_file(template_str);
437 mkdir(template_str.c_str());
438 return template_str;
439 #elif defined(__wasm)
440 template_str = make_temp_file(template_str);
441 mkdir(template_str.c_str(), 0777);
442 return template_str;
443 #else
444 # ifndef NDEBUG
445 size_t pos = template_str.rfind("XXXXXX");
446 log_assert(pos != std::string::npos);
447
448 int suffixlen = GetSize(template_str) - pos - 6;
449 log_assert(suffixlen == 0);
450 # endif
451
452 char *p = strdup(template_str.c_str());
453 p = mkdtemp(p);
454 log_assert(p != NULL);
455 template_str = p;
456 free(p);
457
458 return template_str;
459 #endif
460 }
461
462 #ifdef _WIN32
463 bool check_file_exists(std::string filename, bool)
464 {
465 return _access(filename.c_str(), 0) == 0;
466 }
467 #else
468 bool check_file_exists(std::string filename, bool is_exec)
469 {
470 return access(filename.c_str(), is_exec ? X_OK : F_OK) == 0;
471 }
472 #endif
473
474 bool is_absolute_path(std::string filename)
475 {
476 #ifdef _WIN32
477 return filename[0] == '/' || filename[0] == '\\' || (filename[0] != 0 && filename[1] == ':');
478 #else
479 return filename[0] == '/';
480 #endif
481 }
482
483 void remove_directory(std::string dirname)
484 {
485 #ifdef _WIN32
486 run_command(stringf("rmdir /s /q \"%s\"", dirname.c_str()));
487 #else
488 struct stat stbuf;
489 struct dirent **namelist;
490 int n = scandir(dirname.c_str(), &namelist, nullptr, alphasort);
491 log_assert(n >= 0);
492 for (int i = 0; i < n; i++) {
493 if (strcmp(namelist[i]->d_name, ".") && strcmp(namelist[i]->d_name, "..")) {
494 std::string buffer = stringf("%s/%s", dirname.c_str(), namelist[i]->d_name);
495 if (!stat(buffer.c_str(), &stbuf) && S_ISREG(stbuf.st_mode)) {
496 remove(buffer.c_str());
497 } else
498 remove_directory(buffer);
499 }
500 free(namelist[i]);
501 }
502 free(namelist);
503 rmdir(dirname.c_str());
504 #endif
505 }
506
507 std::string escape_filename_spaces(const std::string& filename)
508 {
509 std::string out;
510 out.reserve(filename.size());
511 for (auto c : filename)
512 {
513 if (c == ' ')
514 out += "\\ ";
515 else
516 out.push_back(c);
517 }
518 return out;
519 }
520
521 int GetSize(RTLIL::Wire *wire)
522 {
523 return wire->width;
524 }
525
526 bool already_setup = false;
527
528 void yosys_setup()
529 {
530 if(already_setup)
531 return;
532 already_setup = true;
533 init_share_dirname();
534 init_abc_executable_name();
535
536 #define X(_id) RTLIL::ID::_id = "\\" # _id;
537 #include "kernel/constids.inc"
538 #undef X
539
540 #ifdef WITH_PYTHON
541 PyImport_AppendInittab((char*)"libyosys", INIT_MODULE);
542 Py_Initialize();
543 PyRun_SimpleString("import sys");
544 signal(SIGINT, SIG_DFL);
545 #endif
546
547 Pass::init_register();
548 yosys_design = new RTLIL::Design;
549 yosys_celltypes.setup();
550 log_push();
551 }
552
553 bool yosys_already_setup()
554 {
555 return already_setup;
556 }
557
558 bool already_shutdown = false;
559
560 void yosys_shutdown()
561 {
562 if(already_shutdown)
563 return;
564 already_shutdown = true;
565 log_pop();
566
567 Pass::done_register();
568
569 delete yosys_design;
570 yosys_design = NULL;
571
572 for (auto f : log_files)
573 if (f != stderr)
574 fclose(f);
575 log_errfile = NULL;
576 log_files.clear();
577
578 yosys_celltypes.clear();
579
580 #ifdef YOSYS_ENABLE_TCL
581 if (yosys_tcl_interp != NULL) {
582 Tcl_DeleteInterp(yosys_tcl_interp);
583 Tcl_Finalize();
584 yosys_tcl_interp = NULL;
585 }
586 #endif
587
588 #ifdef YOSYS_ENABLE_PLUGINS
589 for (auto &it : loaded_plugins)
590 dlclose(it.second);
591
592 loaded_plugins.clear();
593 #ifdef WITH_PYTHON
594 loaded_python_plugins.clear();
595 #endif
596 loaded_plugin_aliases.clear();
597 #endif
598
599 #ifdef WITH_PYTHON
600 Py_Finalize();
601 #endif
602 }
603
604 RTLIL::IdString new_id(std::string file, int line, std::string func)
605 {
606 #ifdef _WIN32
607 size_t pos = file.find_last_of("/\\");
608 #else
609 size_t pos = file.find_last_of('/');
610 #endif
611 if (pos != std::string::npos)
612 file = file.substr(pos+1);
613
614 pos = func.find_last_of(':');
615 if (pos != std::string::npos)
616 func = func.substr(pos+1);
617
618 return stringf("$auto$%s:%d:%s$%d", file.c_str(), line, func.c_str(), autoidx++);
619 }
620
621 RTLIL::IdString new_id_suffix(std::string file, int line, std::string func, std::string suffix)
622 {
623 #ifdef _WIN32
624 size_t pos = file.find_last_of("/\\");
625 #else
626 size_t pos = file.find_last_of('/');
627 #endif
628 if (pos != std::string::npos)
629 file = file.substr(pos+1);
630
631 pos = func.find_last_of(':');
632 if (pos != std::string::npos)
633 func = func.substr(pos+1);
634
635 return stringf("$auto$%s:%d:%s$%s$%d", file.c_str(), line, func.c_str(), suffix.c_str(), autoidx++);
636 }
637
638 RTLIL::Design *yosys_get_design()
639 {
640 return yosys_design;
641 }
642
643 const char *create_prompt(RTLIL::Design *design, int recursion_counter)
644 {
645 static char buffer[100];
646 std::string str = "\n";
647 if (recursion_counter > 1)
648 str += stringf("(%d) ", recursion_counter);
649 str += "yosys";
650 if (!design->selected_active_module.empty())
651 str += stringf(" [%s]", RTLIL::unescape_id(design->selected_active_module).c_str());
652 if (!design->selection_stack.empty() && !design->selection_stack.back().full_selection) {
653 if (design->selected_active_module.empty())
654 str += "*";
655 else if (design->selection_stack.back().selected_modules.size() != 1 || design->selection_stack.back().selected_members.size() != 0 ||
656 design->selection_stack.back().selected_modules.count(design->selected_active_module) == 0)
657 str += "*";
658 }
659 snprintf(buffer, 100, "%s> ", str.c_str());
660 return buffer;
661 }
662
663 std::vector<std::string> glob_filename(const std::string &filename_pattern)
664 {
665 std::vector<std::string> results;
666
667 #if defined(_WIN32) || !defined(YOSYS_ENABLE_GLOB)
668 results.push_back(filename_pattern);
669 #else
670 glob_t globbuf;
671
672 int err = glob(filename_pattern.c_str(), 0, NULL, &globbuf);
673
674 if(err == 0) {
675 for (size_t i = 0; i < globbuf.gl_pathc; i++)
676 results.push_back(globbuf.gl_pathv[i]);
677 globfree(&globbuf);
678 } else {
679 results.push_back(filename_pattern);
680 }
681 #endif
682
683 return results;
684 }
685
686 void rewrite_filename(std::string &filename)
687 {
688 if (filename.compare(0, 1, "\"") == 0 && filename.compare(GetSize(filename)-1, std::string::npos, "\"") == 0)
689 filename = filename.substr(1, GetSize(filename)-2);
690 if (filename.compare(0, 2, "+/") == 0)
691 filename = proc_share_dirname() + filename.substr(2);
692 #ifndef _WIN32
693 if (filename.compare(0, 2, "~/") == 0)
694 filename = filename.replace(0, 1, getenv("HOME"));
695 #endif
696 }
697
698 #ifdef YOSYS_ENABLE_TCL
699 static int tcl_yosys_cmd(ClientData, Tcl_Interp *interp, int argc, const char *argv[])
700 {
701 std::vector<std::string> args;
702 for (int i = 1; i < argc; i++)
703 args.push_back(argv[i]);
704
705 if (args.size() >= 1 && args[0] == "-import") {
706 for (auto &it : pass_register) {
707 std::string tcl_command_name = it.first;
708 if (tcl_command_name == "proc")
709 tcl_command_name = "procs";
710 else if (tcl_command_name == "rename")
711 tcl_command_name = "renames";
712 Tcl_CmdInfo info;
713 if (Tcl_GetCommandInfo(interp, tcl_command_name.c_str(), &info) != 0) {
714 log("[TCL: yosys -import] Command name collision: found pre-existing command `%s' -> skip.\n", it.first.c_str());
715 } else {
716 std::string tcl_script = stringf("proc %s args { yosys %s {*}$args }", tcl_command_name.c_str(), it.first.c_str());
717 Tcl_Eval(interp, tcl_script.c_str());
718 }
719 }
720 return TCL_OK;
721 }
722
723 if (args.size() == 1) {
724 Pass::call(yosys_get_design(), args[0]);
725 return TCL_OK;
726 }
727
728 Pass::call(yosys_get_design(), args);
729 return TCL_OK;
730 }
731
732 extern Tcl_Interp *yosys_get_tcl_interp()
733 {
734 if (yosys_tcl_interp == NULL) {
735 yosys_tcl_interp = Tcl_CreateInterp();
736 Tcl_CreateCommand(yosys_tcl_interp, "yosys", tcl_yosys_cmd, NULL, NULL);
737 }
738 return yosys_tcl_interp;
739 }
740
741 struct TclPass : public Pass {
742 TclPass() : Pass("tcl", "execute a TCL script file") { }
743 void help() override {
744 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
745 log("\n");
746 log(" tcl <filename> [args]\n");
747 log("\n");
748 log("This command executes the tcl commands in the specified file.\n");
749 log("Use 'yosys cmd' to run the yosys command 'cmd' from tcl.\n");
750 log("\n");
751 log("The tcl command 'yosys -import' can be used to import all yosys\n");
752 log("commands directly as tcl commands to the tcl shell. Yosys commands\n");
753 log("'proc' and 'rename' are wrapped to tcl commands 'procs' and 'renames'\n");
754 log("in order to avoid a name collision with the built in commands.\n");
755 log("\n");
756 log("If any arguments are specified, these arguments are provided to the script via\n");
757 log("the standard $argc and $argv variables.\n");
758 log("\n");
759 }
760 void execute(std::vector<std::string> args, RTLIL::Design *) override {
761 if (args.size() < 2)
762 log_cmd_error("Missing script file.\n");
763
764 std::vector<Tcl_Obj*> script_args;
765 for (auto it = args.begin() + 2; it != args.end(); ++it)
766 script_args.push_back(Tcl_NewStringObj((*it).c_str(), (*it).size()));
767
768 Tcl_Interp *interp = yosys_get_tcl_interp();
769 Tcl_ObjSetVar2(interp, Tcl_NewStringObj("argc", 4), NULL, Tcl_NewIntObj(script_args.size()), 0);
770 Tcl_ObjSetVar2(interp, Tcl_NewStringObj("argv", 4), NULL, Tcl_NewListObj(script_args.size(), script_args.data()), 0);
771 Tcl_ObjSetVar2(interp, Tcl_NewStringObj("argv0", 5), NULL, Tcl_NewStringObj(args[1].c_str(), args[1].size()), 0);
772 if (Tcl_EvalFile(interp, args[1].c_str()) != TCL_OK)
773 log_cmd_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(interp));
774 }
775 } TclPass;
776 #endif
777
778 #if defined(__linux__) || defined(__CYGWIN__)
779 std::string proc_self_dirname()
780 {
781 char path[PATH_MAX];
782 ssize_t buflen = readlink("/proc/self/exe", path, sizeof(path));
783 if (buflen < 0) {
784 log_error("readlink(\"/proc/self/exe\") failed: %s\n", strerror(errno));
785 }
786 while (buflen > 0 && path[buflen-1] != '/')
787 buflen--;
788 return std::string(path, buflen);
789 }
790 #elif defined(__FreeBSD__)
791 std::string proc_self_dirname()
792 {
793 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
794 size_t buflen;
795 char *buffer;
796 std::string path;
797 if (sysctl(mib, 4, NULL, &buflen, NULL, 0) != 0)
798 log_error("sysctl failed: %s\n", strerror(errno));
799 buffer = (char*)malloc(buflen);
800 if (buffer == NULL)
801 log_error("malloc failed: %s\n", strerror(errno));
802 if (sysctl(mib, 4, buffer, &buflen, NULL, 0) != 0)
803 log_error("sysctl failed: %s\n", strerror(errno));
804 while (buflen > 0 && buffer[buflen-1] != '/')
805 buflen--;
806 path.assign(buffer, buflen);
807 free(buffer);
808 return path;
809 }
810 #elif defined(__APPLE__)
811 std::string proc_self_dirname()
812 {
813 char *path = NULL;
814 uint32_t buflen = 0;
815 while (_NSGetExecutablePath(path, &buflen) != 0)
816 path = (char *) realloc((void *) path, buflen);
817 while (buflen > 0 && path[buflen-1] != '/')
818 buflen--;
819 std::string str(path, buflen);
820 free(path);
821 return str;
822 }
823 #elif defined(_WIN32)
824 std::string proc_self_dirname()
825 {
826 int i = 0;
827 # ifdef __MINGW32__
828 char longpath[MAX_PATH + 1];
829 char shortpath[MAX_PATH + 1];
830 # else
831 WCHAR longpath[MAX_PATH + 1];
832 TCHAR shortpath[MAX_PATH + 1];
833 # endif
834 if (!GetModuleFileName(0, longpath, MAX_PATH+1))
835 log_error("GetModuleFileName() failed.\n");
836 if (!GetShortPathName(longpath, shortpath, MAX_PATH+1))
837 log_error("GetShortPathName() failed.\n");
838 while (shortpath[i] != 0)
839 i++;
840 while (i > 0 && shortpath[i-1] != '/' && shortpath[i-1] != '\\')
841 shortpath[--i] = 0;
842 std::string path;
843 for (i = 0; shortpath[i]; i++)
844 path += char(shortpath[i]);
845 return path;
846 }
847 #elif defined(EMSCRIPTEN) || defined(__wasm)
848 std::string proc_self_dirname()
849 {
850 return "/";
851 }
852 #else
853 #error "Don't know how to determine process executable base path!"
854 #endif
855
856 #if defined(EMSCRIPTEN) || defined(__wasm)
857 void init_share_dirname()
858 {
859 yosys_share_dirname = "/share/";
860 }
861 #else
862 void init_share_dirname()
863 {
864 std::string proc_self_path = proc_self_dirname();
865 # if defined(_WIN32) && !defined(YOSYS_WIN32_UNIX_DIR)
866 std::string proc_share_path = proc_self_path + "share\\";
867 if (check_file_exists(proc_share_path, true)) {
868 yosys_share_dirname = proc_share_path;
869 return;
870 }
871 proc_share_path = proc_self_path + "..\\share\\";
872 if (check_file_exists(proc_share_path, true)) {
873 yosys_share_dirname = proc_share_path;
874 return;
875 }
876 # else
877 std::string proc_share_path = proc_self_path + "share/";
878 if (check_file_exists(proc_share_path, true)) {
879 yosys_share_dirname = proc_share_path;
880 return;
881 }
882 proc_share_path = proc_self_path + "../share/" + proc_program_prefix()+ "yosys/";
883 if (check_file_exists(proc_share_path, true)) {
884 yosys_share_dirname = proc_share_path;
885 return;
886 }
887 # ifdef YOSYS_DATDIR
888 proc_share_path = YOSYS_DATDIR "/";
889 if (check_file_exists(proc_share_path, true)) {
890 yosys_share_dirname = proc_share_path;
891 return;
892 }
893 # endif
894 # endif
895 }
896 #endif
897
898 void init_abc_executable_name()
899 {
900 #ifdef ABCEXTERNAL
901 std::string exe_file;
902 if (std::getenv("ABC")) {
903 yosys_abc_executable = std::getenv("ABC");
904 } else {
905 yosys_abc_executable = ABCEXTERNAL;
906 }
907 #else
908 yosys_abc_executable = proc_self_dirname() + proc_program_prefix()+ "yosys-abc";
909 #endif
910 #ifdef _WIN32
911 #ifndef ABCEXTERNAL
912 if (!check_file_exists(yosys_abc_executable + ".exe") && check_file_exists(proc_self_dirname() + "..\\" + proc_program_prefix() + "yosys-abc.exe"))
913 yosys_abc_executable = proc_self_dirname() + "..\\" + proc_program_prefix() + "yosys-abc";
914 #endif
915 #endif
916 }
917
918 std::string proc_share_dirname()
919 {
920 if (yosys_share_dirname.empty())
921 log_error("init_share_dirname: unable to determine share/ directory!\n");
922 return yosys_share_dirname;
923 }
924
925 std::string proc_program_prefix()
926 {
927 std::string program_prefix;
928 #ifdef YOSYS_PROGRAM_PREFIX
929 program_prefix = YOSYS_PROGRAM_PREFIX;
930 #endif
931 return program_prefix;
932 }
933
934 bool fgetline(FILE *f, std::string &buffer)
935 {
936 buffer = "";
937 char block[4096];
938 while (1) {
939 if (fgets(block, 4096, f) == NULL)
940 return false;
941 buffer += block;
942 if (buffer.size() > 0 && (buffer[buffer.size()-1] == '\n' || buffer[buffer.size()-1] == '\r')) {
943 while (buffer.size() > 0 && (buffer[buffer.size()-1] == '\n' || buffer[buffer.size()-1] == '\r'))
944 buffer.resize(buffer.size()-1);
945 return true;
946 }
947 }
948 }
949
950 static void handle_label(std::string &command, bool &from_to_active, const std::string &run_from, const std::string &run_to)
951 {
952 int pos = 0;
953 std::string label;
954
955 while (pos < GetSize(command) && (command[pos] == ' ' || command[pos] == '\t'))
956 pos++;
957
958 if (pos < GetSize(command) && command[pos] == '#')
959 return;
960
961 while (pos < GetSize(command) && command[pos] != ' ' && command[pos] != '\t' && command[pos] != '\r' && command[pos] != '\n')
962 label += command[pos++];
963
964 if (GetSize(label) > 1 && label.back() == ':')
965 {
966 label = label.substr(0, GetSize(label)-1);
967 command = command.substr(pos);
968
969 if (label == run_from)
970 from_to_active = true;
971 else if (label == run_to || (run_from == run_to && !run_from.empty()))
972 from_to_active = false;
973 }
974 }
975
976 bool run_frontend(std::string filename, std::string command, RTLIL::Design *design, std::string *from_to_label)
977 {
978 if (design == nullptr)
979 design = yosys_design;
980
981 if (command == "auto") {
982 std::string filename_trim = filename;
983 if (filename_trim.size() > 3 && filename_trim.compare(filename_trim.size()-3, std::string::npos, ".gz") == 0)
984 filename_trim.erase(filename_trim.size()-3);
985 if (filename_trim.size() > 2 && filename_trim.compare(filename_trim.size()-2, std::string::npos, ".v") == 0)
986 command = " -vlog2k";
987 else if (filename_trim.size() > 2 && filename_trim.compare(filename_trim.size()-3, std::string::npos, ".sv") == 0)
988 command = " -sv";
989 else if (filename_trim.size() > 3 && filename_trim.compare(filename_trim.size()-4, std::string::npos, ".vhd") == 0)
990 command = " -vhdl";
991 else if (filename_trim.size() > 4 && filename_trim.compare(filename_trim.size()-5, std::string::npos, ".blif") == 0)
992 command = "blif";
993 else if (filename_trim.size() > 5 && filename_trim.compare(filename_trim.size()-6, std::string::npos, ".eblif") == 0)
994 command = "blif";
995 else if (filename_trim.size() > 4 && filename_trim.compare(filename_trim.size()-5, std::string::npos, ".json") == 0)
996 command = "json";
997 else if (filename_trim.size() > 3 && filename_trim.compare(filename_trim.size()-3, std::string::npos, ".il") == 0)
998 command = "rtlil";
999 else if (filename_trim.size() > 3 && filename_trim.compare(filename_trim.size()-3, std::string::npos, ".ys") == 0)
1000 command = "script";
1001 else if (filename_trim.size() > 3 && filename_trim.compare(filename_trim.size()-4, std::string::npos, ".tcl") == 0)
1002 command = "tcl";
1003 else if (filename == "-")
1004 command = "script";
1005 else
1006 log_error("Can't guess frontend for input file `%s' (missing -f option)!\n", filename.c_str());
1007 }
1008
1009 if (command == "script")
1010 {
1011 std::string run_from, run_to;
1012 bool from_to_active = true;
1013
1014 if (from_to_label != NULL) {
1015 size_t pos = from_to_label->find(':');
1016 if (pos == std::string::npos) {
1017 run_from = *from_to_label;
1018 run_to = *from_to_label;
1019 } else {
1020 run_from = from_to_label->substr(0, pos);
1021 run_to = from_to_label->substr(pos+1);
1022 }
1023 from_to_active = run_from.empty();
1024 }
1025
1026 log("\n-- Executing script file `%s' --\n", filename.c_str());
1027
1028 FILE *f = stdin;
1029
1030 if (filename != "-") {
1031 f = fopen(filename.c_str(), "r");
1032 yosys_input_files.insert(filename);
1033 }
1034
1035 if (f == NULL)
1036 log_error("Can't open script file `%s' for reading: %s\n", filename.c_str(), strerror(errno));
1037
1038 FILE *backup_script_file = Frontend::current_script_file;
1039 Frontend::current_script_file = f;
1040
1041 try {
1042 std::string command;
1043 while (fgetline(f, command)) {
1044 while (!command.empty() && command[command.size()-1] == '\\') {
1045 std::string next_line;
1046 if (!fgetline(f, next_line))
1047 break;
1048 command.resize(command.size()-1);
1049 command += next_line;
1050 }
1051 handle_label(command, from_to_active, run_from, run_to);
1052 if (from_to_active) {
1053 Pass::call(design, command);
1054 design->check();
1055 }
1056 }
1057
1058 if (!command.empty()) {
1059 handle_label(command, from_to_active, run_from, run_to);
1060 if (from_to_active) {
1061 Pass::call(design, command);
1062 design->check();
1063 }
1064 }
1065 }
1066 catch (...) {
1067 Frontend::current_script_file = backup_script_file;
1068 throw;
1069 }
1070
1071 Frontend::current_script_file = backup_script_file;
1072
1073 if (filename != "-")
1074 fclose(f);
1075
1076 return true;
1077 }
1078
1079 if (command == "tcl") {
1080 Pass::call(design, vector<string>({command, filename}));
1081 return true;
1082 }
1083
1084 if (filename == "-") {
1085 log("\n-- Parsing stdin using frontend `%s' --\n", command.c_str());
1086 } else {
1087 log("\n-- Parsing `%s' using frontend `%s' --\n", filename.c_str(), command.c_str());
1088 }
1089
1090 if (command[0] == ' ') {
1091 auto argv = split_tokens("read" + command);
1092 argv.push_back(filename);
1093 Pass::call(design, argv);
1094 } else
1095 Frontend::frontend_call(design, NULL, filename, command);
1096
1097 design->check();
1098 return false;
1099 }
1100
1101 void run_pass(std::string command, RTLIL::Design *design)
1102 {
1103 if (design == nullptr)
1104 design = yosys_design;
1105
1106 log("\n-- Running command `%s' --\n", command.c_str());
1107
1108 Pass::call(design, command);
1109 }
1110
1111 void run_backend(std::string filename, std::string command, RTLIL::Design *design)
1112 {
1113 if (design == nullptr)
1114 design = yosys_design;
1115
1116 if (command == "auto") {
1117 if (filename.size() > 2 && filename.compare(filename.size()-2, std::string::npos, ".v") == 0)
1118 command = "verilog";
1119 else if (filename.size() > 3 && filename.compare(filename.size()-3, std::string::npos, ".sv") == 0)
1120 command = "verilog -sv";
1121 else if (filename.size() > 3 && filename.compare(filename.size()-3, std::string::npos, ".il") == 0)
1122 command = "rtlil";
1123 else if (filename.size() > 3 && filename.compare(filename.size()-3, std::string::npos, ".cc") == 0)
1124 command = "cxxrtl";
1125 else if (filename.size() > 4 && filename.compare(filename.size()-4, std::string::npos, ".aig") == 0)
1126 command = "aiger";
1127 else if (filename.size() > 5 && filename.compare(filename.size()-5, std::string::npos, ".blif") == 0)
1128 command = "blif";
1129 else if (filename.size() > 5 && filename.compare(filename.size()-5, std::string::npos, ".edif") == 0)
1130 command = "edif";
1131 else if (filename.size() > 5 && filename.compare(filename.size()-5, std::string::npos, ".json") == 0)
1132 command = "json";
1133 else if (filename == "-")
1134 command = "rtlil";
1135 else if (filename.empty())
1136 return;
1137 else
1138 log_error("Can't guess backend for output file `%s' (missing -b option)!\n", filename.c_str());
1139 }
1140
1141 if (filename.empty())
1142 filename = "-";
1143
1144 if (filename == "-") {
1145 log("\n-- Writing to stdout using backend `%s' --\n", command.c_str());
1146 } else {
1147 log("\n-- Writing to `%s' using backend `%s' --\n", filename.c_str(), command.c_str());
1148 }
1149
1150 Backend::backend_call(design, NULL, filename, command);
1151 }
1152
1153 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1154 static char *readline_cmd_generator(const char *text, int state)
1155 {
1156 static std::map<std::string, Pass*>::iterator it;
1157 static int len;
1158
1159 if (!state) {
1160 it = pass_register.begin();
1161 len = strlen(text);
1162 }
1163
1164 for (; it != pass_register.end(); it++) {
1165 if (it->first.compare(0, len, text) == 0)
1166 return strdup((it++)->first.c_str());
1167 }
1168 return NULL;
1169 }
1170
1171 static char *readline_obj_generator(const char *text, int state)
1172 {
1173 static std::vector<char*> obj_names;
1174 static size_t idx;
1175
1176 if (!state)
1177 {
1178 idx = 0;
1179 obj_names.clear();
1180
1181 RTLIL::Design *design = yosys_get_design();
1182 int len = strlen(text);
1183
1184 if (design->selected_active_module.empty())
1185 {
1186 for (auto mod : design->modules())
1187 if (RTLIL::unescape_id(mod->name).compare(0, len, text) == 0)
1188 obj_names.push_back(strdup(log_id(mod->name)));
1189 }
1190 else if (design->module(design->selected_active_module) != nullptr)
1191 {
1192 RTLIL::Module *module = design->module(design->selected_active_module);
1193
1194 for (auto w : module->wires())
1195 if (RTLIL::unescape_id(w->name).compare(0, len, text) == 0)
1196 obj_names.push_back(strdup(log_id(w->name)));
1197
1198 for (auto &it : module->memories)
1199 if (RTLIL::unescape_id(it.first).compare(0, len, text) == 0)
1200 obj_names.push_back(strdup(log_id(it.first)));
1201
1202 for (auto cell : module->cells())
1203 if (RTLIL::unescape_id(cell->name).compare(0, len, text) == 0)
1204 obj_names.push_back(strdup(log_id(cell->name)));
1205
1206 for (auto &it : module->processes)
1207 if (RTLIL::unescape_id(it.first).compare(0, len, text) == 0)
1208 obj_names.push_back(strdup(log_id(it.first)));
1209 }
1210
1211 std::sort(obj_names.begin(), obj_names.end());
1212 }
1213
1214 if (idx < obj_names.size())
1215 return strdup(obj_names[idx++]);
1216
1217 idx = 0;
1218 obj_names.clear();
1219 return NULL;
1220 }
1221
1222 static char **readline_completion(const char *text, int start, int)
1223 {
1224 if (start == 0)
1225 return rl_completion_matches(text, readline_cmd_generator);
1226 if (strncmp(rl_line_buffer, "read_", 5) && strncmp(rl_line_buffer, "write_", 6))
1227 return rl_completion_matches(text, readline_obj_generator);
1228 return NULL;
1229 }
1230 #endif
1231
1232 void shell(RTLIL::Design *design)
1233 {
1234 static int recursion_counter = 0;
1235
1236 recursion_counter++;
1237 log_cmd_error_throw = true;
1238
1239 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1240 rl_readline_name = (char*)"yosys";
1241 rl_attempted_completion_function = readline_completion;
1242 rl_basic_word_break_characters = (char*)" \t\n";
1243 #endif
1244
1245 char *command = NULL;
1246 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1247 while ((command = readline(create_prompt(design, recursion_counter))) != NULL)
1248 {
1249 #else
1250 char command_buffer[4096];
1251 while (1)
1252 {
1253 fputs(create_prompt(design, recursion_counter), stdout);
1254 fflush(stdout);
1255 if ((command = fgets(command_buffer, 4096, stdin)) == NULL)
1256 break;
1257 #endif
1258 if (command[strspn(command, " \t\r\n")] == 0)
1259 continue;
1260 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1261 add_history(command);
1262 #endif
1263
1264 char *p = command + strspn(command, " \t\r\n");
1265 if (!strncmp(p, "exit", 4)) {
1266 p += 4;
1267 p += strspn(p, " \t\r\n");
1268 if (*p == 0)
1269 break;
1270 }
1271
1272 try {
1273 log_assert(design->selection_stack.size() == 1);
1274 Pass::call(design, command);
1275 } catch (log_cmd_error_exception) {
1276 while (design->selection_stack.size() > 1)
1277 design->selection_stack.pop_back();
1278 log_reset_stack();
1279 }
1280 design->check();
1281 }
1282 if (command == NULL)
1283 printf("exit\n");
1284
1285 recursion_counter--;
1286 log_cmd_error_throw = false;
1287 }
1288
1289 struct ShellPass : public Pass {
1290 ShellPass() : Pass("shell", "enter interactive command mode") { }
1291 void help() override {
1292 log("\n");
1293 log(" shell\n");
1294 log("\n");
1295 log("This command enters the interactive command mode. This can be useful\n");
1296 log("in a script to interrupt the script at a certain point and allow for\n");
1297 log("interactive inspection or manual synthesis of the design at this point.\n");
1298 log("\n");
1299 log("The command prompt of the interactive shell indicates the current\n");
1300 log("selection (see 'help select'):\n");
1301 log("\n");
1302 log(" yosys>\n");
1303 log(" the entire design is selected\n");
1304 log("\n");
1305 log(" yosys*>\n");
1306 log(" only part of the design is selected\n");
1307 log("\n");
1308 log(" yosys [modname]>\n");
1309 log(" the entire module 'modname' is selected using 'select -module modname'\n");
1310 log("\n");
1311 log(" yosys [modname]*>\n");
1312 log(" only part of current module 'modname' is selected\n");
1313 log("\n");
1314 log("When in interactive shell, some errors (e.g. invalid command arguments)\n");
1315 log("do not terminate yosys but return to the command prompt.\n");
1316 log("\n");
1317 log("This command is the default action if nothing else has been specified\n");
1318 log("on the command line.\n");
1319 log("\n");
1320 log("Press Ctrl-D or type 'exit' to leave the interactive shell.\n");
1321 log("\n");
1322 }
1323 void execute(std::vector<std::string> args, RTLIL::Design *design) override {
1324 extra_args(args, 1, design, false);
1325 shell(design);
1326 }
1327 } ShellPass;
1328
1329 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1330 struct HistoryPass : public Pass {
1331 HistoryPass() : Pass("history", "show last interactive commands") { }
1332 void help() override {
1333 log("\n");
1334 log(" history\n");
1335 log("\n");
1336 log("This command prints all commands in the shell history buffer. This are\n");
1337 log("all commands executed in an interactive session, but not the commands\n");
1338 log("from executed scripts.\n");
1339 log("\n");
1340 }
1341 void execute(std::vector<std::string> args, RTLIL::Design *design) override {
1342 extra_args(args, 1, design, false);
1343 #ifdef YOSYS_ENABLE_READLINE
1344 for(HIST_ENTRY **list = history_list(); *list != NULL; list++)
1345 log("%s\n", (*list)->line);
1346 #else
1347 for (int i = where_history(); history_get(i); i++)
1348 log("%s\n", history_get(i)->line);
1349 #endif
1350 }
1351 } HistoryPass;
1352 #endif
1353
1354 struct ScriptCmdPass : public Pass {
1355 ScriptCmdPass() : Pass("script", "execute commands from file or wire") { }
1356 void help() override {
1357 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
1358 log("\n");
1359 log(" script <filename> [<from_label>:<to_label>]\n");
1360 log(" script -scriptwire [selection]\n");
1361 log("\n");
1362 log("This command executes the yosys commands in the specified file (default\n");
1363 log("behaviour), or commands embedded in the constant text value connected to the\n");
1364 log("selected wires.\n");
1365 log("\n");
1366 log("In the default (file) case, the 2nd argument can be used to only execute the\n");
1367 log("section of the file between the specified labels. An empty from label is\n");
1368 log("synonymous with the beginning of the file and an empty to label is synonymous\n");
1369 log("with the end of the file.\n");
1370 log("\n");
1371 log("If only one label is specified (without ':') then only the block\n");
1372 log("marked with that label (until the next label) is executed.\n");
1373 log("\n");
1374 log("In \"-scriptwire\" mode, the commands on the selected wire(s) will be executed\n");
1375 log("in the scope of (and thus, relative to) the wires' owning module(s). This\n");
1376 log("'-module' mode can be exited by using the 'cd' command.\n");
1377 log("\n");
1378 }
1379 void execute(std::vector<std::string> args, RTLIL::Design *design) override
1380 {
1381 bool scriptwire = false;
1382
1383 size_t argidx;
1384 for (argidx = 1; argidx < args.size(); argidx++) {
1385 if (args[argidx] == "-scriptwire") {
1386 scriptwire = true;
1387 continue;
1388 }
1389 break;
1390 }
1391 if (scriptwire) {
1392 extra_args(args, argidx, design);
1393
1394 for (auto mod : design->selected_modules())
1395 for (auto &c : mod->connections()) {
1396 if (!c.first.is_wire())
1397 continue;
1398 auto w = c.first.as_wire();
1399 if (!mod->selected(w))
1400 continue;
1401 if (!c.second.is_fully_const())
1402 log_error("RHS of selected wire %s.%s is not constant.\n", log_id(mod), log_id(w));
1403 auto v = c.second.as_const();
1404 Pass::call_on_module(design, mod, v.decode_string());
1405 }
1406 }
1407 else if (args.size() < 2)
1408 log_cmd_error("Missing script file.\n");
1409 else if (args.size() == 2)
1410 run_frontend(args[1], "script", design);
1411 else if (args.size() == 3)
1412 run_frontend(args[1], "script", design, &args[2]);
1413 else
1414 extra_args(args, 2, design, false);
1415 }
1416 } ScriptCmdPass;
1417
1418 YOSYS_NAMESPACE_END