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