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