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