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