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