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