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