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