Merge pull request #203 from cr1901/master
[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 - 2016 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__) || defined(__CYGWIN__)
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 # if defined(_WIN32) && !defined(YOSYS_WIN32_UNIX_DIR)
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() > 2 && filename.substr(filename.size()-4) == ".vhd")
767 command = "vhdl";
768 else if (filename.size() > 4 && filename.substr(filename.size()-5) == ".blif")
769 command = "blif";
770 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".il")
771 command = "ilang";
772 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".ys")
773 command = "script";
774 else if (filename == "-")
775 command = "script";
776 else
777 log_error("Can't guess frontend for input file `%s' (missing -f option)!\n", filename.c_str());
778 }
779
780 if (command == "script")
781 {
782 std::string run_from, run_to;
783 bool from_to_active = true;
784
785 if (from_to_label != NULL) {
786 size_t pos = from_to_label->find(':');
787 if (pos == std::string::npos) {
788 run_from = *from_to_label;
789 run_to = *from_to_label;
790 } else {
791 run_from = from_to_label->substr(0, pos);
792 run_to = from_to_label->substr(pos+1);
793 }
794 from_to_active = run_from.empty();
795 }
796
797 log("\n-- Executing script file `%s' --\n", filename.c_str());
798
799 FILE *f = stdin;
800
801 if (filename != "-")
802 f = fopen(filename.c_str(), "r");
803
804 if (f == NULL)
805 log_error("Can't open script file `%s' for reading: %s\n", filename.c_str(), strerror(errno));
806
807 FILE *backup_script_file = Frontend::current_script_file;
808 Frontend::current_script_file = f;
809
810 try {
811 std::string command;
812 while (fgetline(f, command)) {
813 while (!command.empty() && command[command.size()-1] == '\\') {
814 std::string next_line;
815 if (!fgetline(f, next_line))
816 break;
817 command.resize(command.size()-1);
818 command += next_line;
819 }
820 handle_label(command, from_to_active, run_from, run_to);
821 if (from_to_active)
822 Pass::call(design, command);
823 }
824
825 if (!command.empty()) {
826 handle_label(command, from_to_active, run_from, run_to);
827 if (from_to_active)
828 Pass::call(design, command);
829 }
830 }
831 catch (...) {
832 Frontend::current_script_file = backup_script_file;
833 throw;
834 }
835
836 Frontend::current_script_file = backup_script_file;
837
838 if (filename != "-")
839 fclose(f);
840
841 if (backend_command != NULL && *backend_command == "auto")
842 *backend_command = "";
843
844 return;
845 }
846
847 if (filename == "-") {
848 log("\n-- Parsing stdin using frontend `%s' --\n", command.c_str());
849 } else {
850 log("\n-- Parsing `%s' using frontend `%s' --\n", filename.c_str(), command.c_str());
851 }
852
853 Frontend::frontend_call(design, NULL, filename, command);
854 }
855
856 void run_frontend(std::string filename, std::string command, RTLIL::Design *design)
857 {
858 run_frontend(filename, command, nullptr, nullptr, design);
859 }
860
861 void run_pass(std::string command, RTLIL::Design *design)
862 {
863 if (design == nullptr)
864 design = yosys_design;
865
866 log("\n-- Running command `%s' --\n", command.c_str());
867
868 Pass::call(design, command);
869 }
870
871 void run_backend(std::string filename, std::string command, RTLIL::Design *design)
872 {
873 if (design == nullptr)
874 design = yosys_design;
875
876 if (command == "auto") {
877 if (filename.size() > 2 && filename.substr(filename.size()-2) == ".v")
878 command = "verilog";
879 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".il")
880 command = "ilang";
881 else if (filename.size() > 5 && filename.substr(filename.size()-5) == ".blif")
882 command = "blif";
883 else if (filename.size() > 5 && filename.substr(filename.size()-5) == ".edif")
884 command = "edif";
885 else if (filename.size() > 5 && filename.substr(filename.size()-5) == ".json")
886 command = "json";
887 else if (filename == "-")
888 command = "ilang";
889 else if (filename.empty())
890 return;
891 else
892 log_error("Can't guess backend for output file `%s' (missing -b option)!\n", filename.c_str());
893 }
894
895 if (filename.empty())
896 filename = "-";
897
898 if (filename == "-") {
899 log("\n-- Writing to stdout using backend `%s' --\n", command.c_str());
900 } else {
901 log("\n-- Writing to `%s' using backend `%s' --\n", filename.c_str(), command.c_str());
902 }
903
904 Backend::backend_call(design, NULL, filename, command);
905 }
906
907 #ifdef YOSYS_ENABLE_READLINE
908 static char *readline_cmd_generator(const char *text, int state)
909 {
910 static std::map<std::string, Pass*>::iterator it;
911 static int len;
912
913 if (!state) {
914 it = pass_register.begin();
915 len = strlen(text);
916 }
917
918 for (; it != pass_register.end(); it++) {
919 if (it->first.substr(0, len) == text)
920 return strdup((it++)->first.c_str());
921 }
922 return NULL;
923 }
924
925 static char *readline_obj_generator(const char *text, int state)
926 {
927 static std::vector<char*> obj_names;
928 static size_t idx;
929
930 if (!state)
931 {
932 idx = 0;
933 obj_names.clear();
934
935 RTLIL::Design *design = yosys_get_design();
936 int len = strlen(text);
937
938 if (design->selected_active_module.empty())
939 {
940 for (auto &it : design->modules_)
941 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
942 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
943 }
944 else
945 if (design->modules_.count(design->selected_active_module) > 0)
946 {
947 RTLIL::Module *module = design->modules_.at(design->selected_active_module);
948
949 for (auto &it : module->wires_)
950 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
951 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
952
953 for (auto &it : module->memories)
954 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
955 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
956
957 for (auto &it : module->cells_)
958 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
959 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
960
961 for (auto &it : module->processes)
962 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
963 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
964 }
965
966 std::sort(obj_names.begin(), obj_names.end());
967 }
968
969 if (idx < obj_names.size())
970 return strdup(obj_names[idx++]);
971
972 idx = 0;
973 obj_names.clear();
974 return NULL;
975 }
976
977 static char **readline_completion(const char *text, int start, int)
978 {
979 if (start == 0)
980 return rl_completion_matches(text, readline_cmd_generator);
981 if (strncmp(rl_line_buffer, "read_", 5) && strncmp(rl_line_buffer, "write_", 6))
982 return rl_completion_matches(text, readline_obj_generator);
983 return NULL;
984 }
985 #endif
986
987 void shell(RTLIL::Design *design)
988 {
989 static int recursion_counter = 0;
990
991 recursion_counter++;
992 log_cmd_error_throw = true;
993
994 #ifdef YOSYS_ENABLE_READLINE
995 rl_readline_name = "yosys";
996 rl_attempted_completion_function = readline_completion;
997 rl_basic_word_break_characters = " \t\n";
998 #endif
999
1000 char *command = NULL;
1001 #ifdef YOSYS_ENABLE_READLINE
1002 while ((command = readline(create_prompt(design, recursion_counter))) != NULL)
1003 {
1004 #else
1005 char command_buffer[4096];
1006 while (1)
1007 {
1008 fputs(create_prompt(design, recursion_counter), stdout);
1009 fflush(stdout);
1010 if ((command = fgets(command_buffer, 4096, stdin)) == NULL)
1011 break;
1012 #endif
1013 if (command[strspn(command, " \t\r\n")] == 0)
1014 continue;
1015 #ifdef YOSYS_ENABLE_READLINE
1016 add_history(command);
1017 #endif
1018
1019 char *p = command + strspn(command, " \t\r\n");
1020 if (!strncmp(p, "exit", 4)) {
1021 p += 4;
1022 p += strspn(p, " \t\r\n");
1023 if (*p == 0)
1024 break;
1025 }
1026
1027 try {
1028 log_assert(design->selection_stack.size() == 1);
1029 Pass::call(design, command);
1030 } catch (log_cmd_error_exception) {
1031 while (design->selection_stack.size() > 1)
1032 design->selection_stack.pop_back();
1033 log_reset_stack();
1034 }
1035 }
1036 if (command == NULL)
1037 printf("exit\n");
1038
1039 recursion_counter--;
1040 log_cmd_error_throw = false;
1041 }
1042
1043 struct ShellPass : public Pass {
1044 ShellPass() : Pass("shell", "enter interactive command mode") { }
1045 virtual void help() {
1046 log("\n");
1047 log(" shell\n");
1048 log("\n");
1049 log("This command enters the interactive command mode. This can be useful\n");
1050 log("in a script to interrupt the script at a certain point and allow for\n");
1051 log("interactive inspection or manual synthesis of the design at this point.\n");
1052 log("\n");
1053 log("The command prompt of the interactive shell indicates the current\n");
1054 log("selection (see 'help select'):\n");
1055 log("\n");
1056 log(" yosys>\n");
1057 log(" the entire design is selected\n");
1058 log("\n");
1059 log(" yosys*>\n");
1060 log(" only part of the design is selected\n");
1061 log("\n");
1062 log(" yosys [modname]>\n");
1063 log(" the entire module 'modname' is selected using 'select -module modname'\n");
1064 log("\n");
1065 log(" yosys [modname]*>\n");
1066 log(" only part of current module 'modname' is selected\n");
1067 log("\n");
1068 log("When in interactive shell, some errors (e.g. invalid command arguments)\n");
1069 log("do not terminate yosys but return to the command prompt.\n");
1070 log("\n");
1071 log("This command is the default action if nothing else has been specified\n");
1072 log("on the command line.\n");
1073 log("\n");
1074 log("Press Ctrl-D or type 'exit' to leave the interactive shell.\n");
1075 log("\n");
1076 }
1077 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
1078 extra_args(args, 1, design, false);
1079 shell(design);
1080 }
1081 } ShellPass;
1082
1083 #ifdef YOSYS_ENABLE_READLINE
1084 struct HistoryPass : public Pass {
1085 HistoryPass() : Pass("history", "show last interactive commands") { }
1086 virtual void help() {
1087 log("\n");
1088 log(" history\n");
1089 log("\n");
1090 log("This command prints all commands in the shell history buffer. This are\n");
1091 log("all commands executed in an interactive session, but not the commands\n");
1092 log("from executed scripts.\n");
1093 log("\n");
1094 }
1095 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
1096 extra_args(args, 1, design, false);
1097 for(HIST_ENTRY **list = history_list(); *list != NULL; list++)
1098 log("%s\n", (*list)->line);
1099 }
1100 } HistoryPass;
1101 #endif
1102
1103 struct ScriptCmdPass : public Pass {
1104 ScriptCmdPass() : Pass("script", "execute commands from script file") { }
1105 virtual void help() {
1106 log("\n");
1107 log(" script <filename> [<from_label>:<to_label>]\n");
1108 log("\n");
1109 log("This command executes the yosys commands in the specified file.\n");
1110 log("\n");
1111 log("The 2nd argument can be used to only execute the section of the\n");
1112 log("file between the specified labels. An empty from label is synonymous\n");
1113 log("for the beginning of the file and an empty to label is synonymous\n");
1114 log("for the end of the file.\n");
1115 log("\n");
1116 log("If only one label is specified (without ':') then only the block\n");
1117 log("marked with that label (until the next label) is executed.\n");
1118 log("\n");
1119 }
1120 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
1121 if (args.size() < 2)
1122 log_cmd_error("Missing script file.\n");
1123 else if (args.size() == 2)
1124 run_frontend(args[1], "script", design);
1125 else if (args.size() == 3)
1126 run_frontend(args[1], "script", NULL, &args[2], design);
1127 else
1128 extra_args(args, 2, design, false);
1129 }
1130 } ScriptCmdPass;
1131
1132 YOSYS_NAMESPACE_END