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