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