Fixed identation
[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 int GetSize(RTLIL::Wire *wire)
486 {
487 return wire->width;
488 }
489
490 bool already_setup = false;
491
492 void yosys_setup()
493 {
494 if(already_setup)
495 return;
496 already_setup = true;
497 // if there are already IdString objects then we have a global initialization order bug
498 IdString empty_id;
499 log_assert(empty_id.index_ == 0);
500 IdString::get_reference(empty_id.index_);
501
502 #ifdef WITH_PYTHON
503 PyImport_AppendInittab((char*)"libyosys", INIT_MODULE);
504 Py_Initialize();
505 PyRun_SimpleString("import sys");
506 #endif
507
508 Pass::init_register();
509 yosys_design = new RTLIL::Design;
510 yosys_celltypes.setup();
511 log_push();
512 }
513
514 bool yosys_already_setup()
515 {
516 return already_setup;
517 }
518
519 bool already_shutdown = false;
520
521 void yosys_shutdown()
522 {
523 if(already_shutdown)
524 return;
525 already_shutdown = true;
526 log_pop();
527
528 delete yosys_design;
529 yosys_design = NULL;
530
531 for (auto f : log_files)
532 if (f != stderr)
533 fclose(f);
534 log_errfile = NULL;
535 log_files.clear();
536
537 Pass::done_register();
538 yosys_celltypes.clear();
539
540 #ifdef YOSYS_ENABLE_TCL
541 if (yosys_tcl_interp != NULL) {
542 Tcl_DeleteInterp(yosys_tcl_interp);
543 Tcl_Finalize();
544 yosys_tcl_interp = NULL;
545 }
546 #endif
547
548 #ifdef YOSYS_ENABLE_PLUGINS
549 for (auto &it : loaded_plugins)
550 dlclose(it.second);
551
552 loaded_plugins.clear();
553 #ifdef WITH_PYTHON
554 loaded_python_plugins.clear();
555 #endif
556 loaded_plugin_aliases.clear();
557 #endif
558
559 #ifdef WITH_PYTHON
560 Py_Finalize();
561 #endif
562
563 IdString empty_id;
564 IdString::put_reference(empty_id.index_);
565 }
566
567 RTLIL::IdString new_id(std::string file, int line, std::string func)
568 {
569 #ifdef _WIN32
570 size_t pos = file.find_last_of("/\\");
571 #else
572 size_t pos = file.find_last_of('/');
573 #endif
574 if (pos != std::string::npos)
575 file = file.substr(pos+1);
576
577 pos = func.find_last_of(':');
578 if (pos != std::string::npos)
579 func = func.substr(pos+1);
580
581 return stringf("$auto$%s:%d:%s$%d", file.c_str(), line, func.c_str(), autoidx++);
582 }
583
584 RTLIL::Design *yosys_get_design()
585 {
586 return yosys_design;
587 }
588
589 const char *create_prompt(RTLIL::Design *design, int recursion_counter)
590 {
591 static char buffer[100];
592 std::string str = "\n";
593 if (recursion_counter > 1)
594 str += stringf("(%d) ", recursion_counter);
595 str += "yosys";
596 if (!design->selected_active_module.empty())
597 str += stringf(" [%s]", RTLIL::unescape_id(design->selected_active_module).c_str());
598 if (!design->selection_stack.empty() && !design->selection_stack.back().full_selection) {
599 if (design->selected_active_module.empty())
600 str += "*";
601 else if (design->selection_stack.back().selected_modules.size() != 1 || design->selection_stack.back().selected_members.size() != 0 ||
602 design->selection_stack.back().selected_modules.count(design->selected_active_module) == 0)
603 str += "*";
604 }
605 snprintf(buffer, 100, "%s> ", str.c_str());
606 return buffer;
607 }
608
609 std::vector<std::string> glob_filename(const std::string &filename_pattern)
610 {
611 std::vector<std::string> results;
612
613 #if defined(_WIN32) || !defined(YOSYS_ENABLE_GLOB)
614 results.push_back(filename_pattern);
615 #else
616 glob_t globbuf;
617
618 int err = glob(filename_pattern.c_str(), 0, NULL, &globbuf);
619
620 if(err == 0) {
621 for (size_t i = 0; i < globbuf.gl_pathc; i++)
622 results.push_back(globbuf.gl_pathv[i]);
623 globfree(&globbuf);
624 } else {
625 results.push_back(filename_pattern);
626 }
627 #endif
628
629 return results;
630 }
631
632 void rewrite_filename(std::string &filename)
633 {
634 if (filename.substr(0, 1) == "\"" && filename.substr(GetSize(filename)-1) == "\"")
635 filename = filename.substr(1, GetSize(filename)-2);
636 if (filename.substr(0, 2) == "+/")
637 filename = proc_share_dirname() + filename.substr(2);
638 }
639
640 #ifdef YOSYS_ENABLE_TCL
641 static int tcl_yosys_cmd(ClientData, Tcl_Interp *interp, int argc, const char *argv[])
642 {
643 std::vector<std::string> args;
644 for (int i = 1; i < argc; i++)
645 args.push_back(argv[i]);
646
647 if (args.size() >= 1 && args[0] == "-import") {
648 for (auto &it : pass_register) {
649 std::string tcl_command_name = it.first;
650 if (tcl_command_name == "proc")
651 tcl_command_name = "procs";
652 else if (tcl_command_name == "rename")
653 tcl_command_name = "renames";
654 Tcl_CmdInfo info;
655 if (Tcl_GetCommandInfo(interp, tcl_command_name.c_str(), &info) != 0) {
656 log("[TCL: yosys -import] Command name collision: found pre-existing command `%s' -> skip.\n", it.first.c_str());
657 } else {
658 std::string tcl_script = stringf("proc %s args { yosys %s {*}$args }", tcl_command_name.c_str(), it.first.c_str());
659 Tcl_Eval(interp, tcl_script.c_str());
660 }
661 }
662 return TCL_OK;
663 }
664
665 if (args.size() == 1) {
666 Pass::call(yosys_get_design(), args[0]);
667 return TCL_OK;
668 }
669
670 Pass::call(yosys_get_design(), args);
671 return TCL_OK;
672 }
673
674 extern Tcl_Interp *yosys_get_tcl_interp()
675 {
676 if (yosys_tcl_interp == NULL) {
677 yosys_tcl_interp = Tcl_CreateInterp();
678 Tcl_CreateCommand(yosys_tcl_interp, "yosys", tcl_yosys_cmd, NULL, NULL);
679 }
680 return yosys_tcl_interp;
681 }
682
683 struct TclPass : public Pass {
684 TclPass() : Pass("tcl", "execute a TCL script file") { }
685 void help() YS_OVERRIDE {
686 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
687 log("\n");
688 log(" tcl <filename> [args]\n");
689 log("\n");
690 log("This command executes the tcl commands in the specified file.\n");
691 log("Use 'yosys cmd' to run the yosys command 'cmd' from tcl.\n");
692 log("\n");
693 log("The tcl command 'yosys -import' can be used to import all yosys\n");
694 log("commands directly as tcl commands to the tcl shell. Yosys commands\n");
695 log("'proc' and 'rename' are wrapped to tcl commands 'procs' and 'renames'\n");
696 log("in order to avoid a name collision with the built in commands.\n");
697 log("\n");
698 log("If any arguments are specified, these arguments are provided to the script via\n");
699 log("the standard $argc and $argv variables.\n");
700 log("\n");
701 }
702 void execute(std::vector<std::string> args, RTLIL::Design *) YS_OVERRIDE {
703 if (args.size() < 2)
704 log_cmd_error("Missing script file.\n");
705
706 std::vector<Tcl_Obj*> script_args;
707 for (auto it = args.begin() + 2; it != args.end(); ++it)
708 script_args.push_back(Tcl_NewStringObj((*it).c_str(), (*it).size()));
709
710 Tcl_Interp *interp = yosys_get_tcl_interp();
711 Tcl_ObjSetVar2(interp, Tcl_NewStringObj("argc", 4), NULL, Tcl_NewIntObj(script_args.size()), 0);
712 Tcl_ObjSetVar2(interp, Tcl_NewStringObj("argv", 4), NULL, Tcl_NewListObj(script_args.size(), script_args.data()), 0);
713 Tcl_ObjSetVar2(interp, Tcl_NewStringObj("argv0", 5), NULL, Tcl_NewStringObj(args[1].c_str(), args[1].size()), 0);
714 if (Tcl_EvalFile(interp, args[1].c_str()) != TCL_OK)
715 log_cmd_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(interp));
716 }
717 } TclPass;
718 #endif
719
720 #if defined(__linux__) || defined(__CYGWIN__)
721 std::string proc_self_dirname()
722 {
723 char path[PATH_MAX];
724 ssize_t buflen = readlink("/proc/self/exe", path, sizeof(path));
725 if (buflen < 0) {
726 log_error("readlink(\"/proc/self/exe\") failed: %s\n", strerror(errno));
727 }
728 while (buflen > 0 && path[buflen-1] != '/')
729 buflen--;
730 return std::string(path, buflen);
731 }
732 #elif defined(__FreeBSD__)
733 std::string proc_self_dirname()
734 {
735 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
736 size_t buflen;
737 char *buffer;
738 std::string path;
739 if (sysctl(mib, 4, NULL, &buflen, NULL, 0) != 0)
740 log_error("sysctl failed: %s\n", strerror(errno));
741 buffer = (char*)malloc(buflen);
742 if (buffer == NULL)
743 log_error("malloc failed: %s\n", strerror(errno));
744 if (sysctl(mib, 4, buffer, &buflen, NULL, 0) != 0)
745 log_error("sysctl failed: %s\n", strerror(errno));
746 while (buflen > 0 && buffer[buflen-1] != '/')
747 buflen--;
748 path.assign(buffer, buflen);
749 free(buffer);
750 return path;
751 }
752 #elif defined(__APPLE__)
753 std::string proc_self_dirname()
754 {
755 char *path = NULL;
756 uint32_t buflen = 0;
757 while (_NSGetExecutablePath(path, &buflen) != 0)
758 path = (char *) realloc((void *) path, buflen);
759 while (buflen > 0 && path[buflen-1] != '/')
760 buflen--;
761 return std::string(path, buflen);
762 }
763 #elif defined(_WIN32)
764 std::string proc_self_dirname()
765 {
766 int i = 0;
767 # ifdef __MINGW32__
768 char longpath[MAX_PATH + 1];
769 char shortpath[MAX_PATH + 1];
770 # else
771 WCHAR longpath[MAX_PATH + 1];
772 TCHAR shortpath[MAX_PATH + 1];
773 # endif
774 if (!GetModuleFileName(0, longpath, MAX_PATH+1))
775 log_error("GetModuleFileName() failed.\n");
776 if (!GetShortPathName(longpath, shortpath, MAX_PATH+1))
777 log_error("GetShortPathName() failed.\n");
778 while (shortpath[i] != 0)
779 i++;
780 while (i > 0 && shortpath[i-1] != '/' && shortpath[i-1] != '\\')
781 shortpath[--i] = 0;
782 std::string path;
783 for (i = 0; shortpath[i]; i++)
784 path += char(shortpath[i]);
785 return path;
786 }
787 #elif defined(EMSCRIPTEN)
788 std::string proc_self_dirname()
789 {
790 return "/";
791 }
792 #else
793 #error "Don't know how to determine process executable base path!"
794 #endif
795
796 #ifdef EMSCRIPTEN
797 std::string proc_share_dirname()
798 {
799 return "/share/";
800 }
801 #else
802 std::string proc_share_dirname()
803 {
804 std::string proc_self_path = proc_self_dirname();
805 # if defined(_WIN32) && !defined(YOSYS_WIN32_UNIX_DIR)
806 std::string proc_share_path = proc_self_path + "share\\";
807 if (check_file_exists(proc_share_path, true))
808 return proc_share_path;
809 proc_share_path = proc_self_path + "..\\share\\";
810 if (check_file_exists(proc_share_path, true))
811 return proc_share_path;
812 # else
813 std::string proc_share_path = proc_self_path + "share/";
814 if (check_file_exists(proc_share_path, true))
815 return proc_share_path;
816 proc_share_path = proc_self_path + "../share/yosys/";
817 if (check_file_exists(proc_share_path, true))
818 return proc_share_path;
819 # ifdef YOSYS_DATDIR
820 proc_share_path = YOSYS_DATDIR "/";
821 if (check_file_exists(proc_share_path, true))
822 return proc_share_path;
823 # endif
824 # endif
825 log_error("proc_share_dirname: unable to determine share/ directory!\n");
826 }
827 #endif
828
829 bool fgetline(FILE *f, std::string &buffer)
830 {
831 buffer = "";
832 char block[4096];
833 while (1) {
834 if (fgets(block, 4096, f) == NULL)
835 return false;
836 buffer += block;
837 if (buffer.size() > 0 && (buffer[buffer.size()-1] == '\n' || buffer[buffer.size()-1] == '\r')) {
838 while (buffer.size() > 0 && (buffer[buffer.size()-1] == '\n' || buffer[buffer.size()-1] == '\r'))
839 buffer.resize(buffer.size()-1);
840 return true;
841 }
842 }
843 }
844
845 static void handle_label(std::string &command, bool &from_to_active, const std::string &run_from, const std::string &run_to)
846 {
847 int pos = 0;
848 std::string label;
849
850 while (pos < GetSize(command) && (command[pos] == ' ' || command[pos] == '\t'))
851 pos++;
852
853 if (pos < GetSize(command) && command[pos] == '#')
854 return;
855
856 while (pos < GetSize(command) && command[pos] != ' ' && command[pos] != '\t' && command[pos] != '\r' && command[pos] != '\n')
857 label += command[pos++];
858
859 if (GetSize(label) > 1 && label.back() == ':')
860 {
861 label = label.substr(0, GetSize(label)-1);
862 command = command.substr(pos);
863
864 if (label == run_from)
865 from_to_active = true;
866 else if (label == run_to || (run_from == run_to && !run_from.empty()))
867 from_to_active = false;
868 }
869 }
870
871 void run_frontend(std::string filename, std::string command, std::string *backend_command, std::string *from_to_label, RTLIL::Design *design)
872 {
873 if (design == nullptr)
874 design = yosys_design;
875
876 if (command == "auto") {
877 if (filename.size() > 2 && filename.substr(filename.size()-2) == ".v")
878 command = "verilog";
879 else if (filename.size() > 2 && filename.substr(filename.size()-3) == ".sv")
880 command = "verilog -sv";
881 else if (filename.size() > 3 && filename.substr(filename.size()-4) == ".vhd")
882 command = "vhdl";
883 else if (filename.size() > 4 && filename.substr(filename.size()-5) == ".blif")
884 command = "blif";
885 else if (filename.size() > 5 && filename.substr(filename.size()-6) == ".eblif")
886 command = "blif";
887 else if (filename.size() > 4 && filename.substr(filename.size()-5) == ".json")
888 command = "json";
889 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".il")
890 command = "ilang";
891 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".ys")
892 command = "script";
893 else if (filename.size() > 3 && filename.substr(filename.size()-4) == ".tcl")
894 command = "tcl";
895 else if (filename == "-")
896 command = "script";
897 else
898 log_error("Can't guess frontend for input file `%s' (missing -f option)!\n", filename.c_str());
899 }
900
901 if (command == "script")
902 {
903 std::string run_from, run_to;
904 bool from_to_active = true;
905
906 if (from_to_label != NULL) {
907 size_t pos = from_to_label->find(':');
908 if (pos == std::string::npos) {
909 run_from = *from_to_label;
910 run_to = *from_to_label;
911 } else {
912 run_from = from_to_label->substr(0, pos);
913 run_to = from_to_label->substr(pos+1);
914 }
915 from_to_active = run_from.empty();
916 }
917
918 log("\n-- Executing script file `%s' --\n", filename.c_str());
919
920 FILE *f = stdin;
921
922 if (filename != "-") {
923 f = fopen(filename.c_str(), "r");
924 yosys_input_files.insert(filename);
925 }
926
927 if (f == NULL)
928 log_error("Can't open script file `%s' for reading: %s\n", filename.c_str(), strerror(errno));
929
930 FILE *backup_script_file = Frontend::current_script_file;
931 Frontend::current_script_file = f;
932
933 try {
934 std::string command;
935 while (fgetline(f, command)) {
936 while (!command.empty() && command[command.size()-1] == '\\') {
937 std::string next_line;
938 if (!fgetline(f, next_line))
939 break;
940 command.resize(command.size()-1);
941 command += next_line;
942 }
943 handle_label(command, from_to_active, run_from, run_to);
944 if (from_to_active)
945 Pass::call(design, command);
946 }
947
948 if (!command.empty()) {
949 handle_label(command, from_to_active, run_from, run_to);
950 if (from_to_active)
951 Pass::call(design, command);
952 }
953 }
954 catch (...) {
955 Frontend::current_script_file = backup_script_file;
956 throw;
957 }
958
959 Frontend::current_script_file = backup_script_file;
960
961 if (filename != "-")
962 fclose(f);
963
964 if (backend_command != NULL && *backend_command == "auto")
965 *backend_command = "";
966
967 return;
968 }
969
970 if (filename == "-") {
971 log("\n-- Parsing stdin using frontend `%s' --\n", command.c_str());
972 } else {
973 log("\n-- Parsing `%s' using frontend `%s' --\n", filename.c_str(), command.c_str());
974 }
975
976 if (command == "tcl")
977 Pass::call(design, vector<string>({command, filename}));
978 else
979 Frontend::frontend_call(design, NULL, filename, command);
980 }
981
982 void run_frontend(std::string filename, std::string command, RTLIL::Design *design)
983 {
984 run_frontend(filename, command, nullptr, nullptr, design);
985 }
986
987 void run_pass(std::string command, RTLIL::Design *design)
988 {
989 if (design == nullptr)
990 design = yosys_design;
991
992 log("\n-- Running command `%s' --\n", command.c_str());
993
994 Pass::call(design, command);
995 }
996
997 void run_backend(std::string filename, std::string command, RTLIL::Design *design)
998 {
999 if (design == nullptr)
1000 design = yosys_design;
1001
1002 if (command == "auto") {
1003 if (filename.size() > 2 && filename.substr(filename.size()-2) == ".v")
1004 command = "verilog";
1005 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".il")
1006 command = "ilang";
1007 else if (filename.size() > 4 && filename.substr(filename.size()-4) == ".aig")
1008 command = "aiger";
1009 else if (filename.size() > 5 && filename.substr(filename.size()-5) == ".blif")
1010 command = "blif";
1011 else if (filename.size() > 5 && filename.substr(filename.size()-5) == ".edif")
1012 command = "edif";
1013 else if (filename.size() > 5 && filename.substr(filename.size()-5) == ".json")
1014 command = "json";
1015 else if (filename == "-")
1016 command = "ilang";
1017 else if (filename.empty())
1018 return;
1019 else
1020 log_error("Can't guess backend for output file `%s' (missing -b option)!\n", filename.c_str());
1021 }
1022
1023 if (filename.empty())
1024 filename = "-";
1025
1026 if (filename == "-") {
1027 log("\n-- Writing to stdout using backend `%s' --\n", command.c_str());
1028 } else {
1029 log("\n-- Writing to `%s' using backend `%s' --\n", filename.c_str(), command.c_str());
1030 }
1031
1032 Backend::backend_call(design, NULL, filename, command);
1033 }
1034
1035 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1036 static char *readline_cmd_generator(const char *text, int state)
1037 {
1038 static std::map<std::string, Pass*>::iterator it;
1039 static int len;
1040
1041 if (!state) {
1042 it = pass_register.begin();
1043 len = strlen(text);
1044 }
1045
1046 for (; it != pass_register.end(); it++) {
1047 if (it->first.substr(0, len) == text)
1048 return strdup((it++)->first.c_str());
1049 }
1050 return NULL;
1051 }
1052
1053 static char *readline_obj_generator(const char *text, int state)
1054 {
1055 static std::vector<char*> obj_names;
1056 static size_t idx;
1057
1058 if (!state)
1059 {
1060 idx = 0;
1061 obj_names.clear();
1062
1063 RTLIL::Design *design = yosys_get_design();
1064 int len = strlen(text);
1065
1066 if (design->selected_active_module.empty())
1067 {
1068 for (auto &it : design->modules_)
1069 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
1070 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
1071 }
1072 else
1073 if (design->modules_.count(design->selected_active_module) > 0)
1074 {
1075 RTLIL::Module *module = design->modules_.at(design->selected_active_module);
1076
1077 for (auto &it : module->wires_)
1078 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
1079 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
1080
1081 for (auto &it : module->memories)
1082 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
1083 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
1084
1085 for (auto &it : module->cells_)
1086 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
1087 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
1088
1089 for (auto &it : module->processes)
1090 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
1091 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
1092 }
1093
1094 std::sort(obj_names.begin(), obj_names.end());
1095 }
1096
1097 if (idx < obj_names.size())
1098 return strdup(obj_names[idx++]);
1099
1100 idx = 0;
1101 obj_names.clear();
1102 return NULL;
1103 }
1104
1105 static char **readline_completion(const char *text, int start, int)
1106 {
1107 if (start == 0)
1108 return rl_completion_matches(text, readline_cmd_generator);
1109 if (strncmp(rl_line_buffer, "read_", 5) && strncmp(rl_line_buffer, "write_", 6))
1110 return rl_completion_matches(text, readline_obj_generator);
1111 return NULL;
1112 }
1113 #endif
1114
1115 void shell(RTLIL::Design *design)
1116 {
1117 static int recursion_counter = 0;
1118
1119 recursion_counter++;
1120 log_cmd_error_throw = true;
1121
1122 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1123 rl_readline_name = (char*)"yosys";
1124 rl_attempted_completion_function = readline_completion;
1125 rl_basic_word_break_characters = (char*)" \t\n";
1126 #endif
1127
1128 char *command = NULL;
1129 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1130 while ((command = readline(create_prompt(design, recursion_counter))) != NULL)
1131 {
1132 #else
1133 char command_buffer[4096];
1134 while (1)
1135 {
1136 fputs(create_prompt(design, recursion_counter), stdout);
1137 fflush(stdout);
1138 if ((command = fgets(command_buffer, 4096, stdin)) == NULL)
1139 break;
1140 #endif
1141 if (command[strspn(command, " \t\r\n")] == 0)
1142 continue;
1143 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1144 add_history(command);
1145 #endif
1146
1147 char *p = command + strspn(command, " \t\r\n");
1148 if (!strncmp(p, "exit", 4)) {
1149 p += 4;
1150 p += strspn(p, " \t\r\n");
1151 if (*p == 0)
1152 break;
1153 }
1154
1155 try {
1156 log_assert(design->selection_stack.size() == 1);
1157 Pass::call(design, command);
1158 } catch (log_cmd_error_exception) {
1159 while (design->selection_stack.size() > 1)
1160 design->selection_stack.pop_back();
1161 log_reset_stack();
1162 }
1163 }
1164 if (command == NULL)
1165 printf("exit\n");
1166
1167 recursion_counter--;
1168 log_cmd_error_throw = false;
1169 }
1170
1171 struct ShellPass : public Pass {
1172 ShellPass() : Pass("shell", "enter interactive command mode") { }
1173 void help() YS_OVERRIDE {
1174 log("\n");
1175 log(" shell\n");
1176 log("\n");
1177 log("This command enters the interactive command mode. This can be useful\n");
1178 log("in a script to interrupt the script at a certain point and allow for\n");
1179 log("interactive inspection or manual synthesis of the design at this point.\n");
1180 log("\n");
1181 log("The command prompt of the interactive shell indicates the current\n");
1182 log("selection (see 'help select'):\n");
1183 log("\n");
1184 log(" yosys>\n");
1185 log(" the entire design is selected\n");
1186 log("\n");
1187 log(" yosys*>\n");
1188 log(" only part of the design is selected\n");
1189 log("\n");
1190 log(" yosys [modname]>\n");
1191 log(" the entire module 'modname' is selected using 'select -module modname'\n");
1192 log("\n");
1193 log(" yosys [modname]*>\n");
1194 log(" only part of current module 'modname' is selected\n");
1195 log("\n");
1196 log("When in interactive shell, some errors (e.g. invalid command arguments)\n");
1197 log("do not terminate yosys but return to the command prompt.\n");
1198 log("\n");
1199 log("This command is the default action if nothing else has been specified\n");
1200 log("on the command line.\n");
1201 log("\n");
1202 log("Press Ctrl-D or type 'exit' to leave the interactive shell.\n");
1203 log("\n");
1204 }
1205 void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE {
1206 extra_args(args, 1, design, false);
1207 shell(design);
1208 }
1209 } ShellPass;
1210
1211 #if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE)
1212 struct HistoryPass : public Pass {
1213 HistoryPass() : Pass("history", "show last interactive commands") { }
1214 void help() YS_OVERRIDE {
1215 log("\n");
1216 log(" history\n");
1217 log("\n");
1218 log("This command prints all commands in the shell history buffer. This are\n");
1219 log("all commands executed in an interactive session, but not the commands\n");
1220 log("from executed scripts.\n");
1221 log("\n");
1222 }
1223 void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE {
1224 extra_args(args, 1, design, false);
1225 #ifdef YOSYS_ENABLE_READLINE
1226 for(HIST_ENTRY **list = history_list(); *list != NULL; list++)
1227 log("%s\n", (*list)->line);
1228 #else
1229 for (int i = where_history(); history_get(i); i++)
1230 log("%s\n", history_get(i)->line);
1231 #endif
1232 }
1233 } HistoryPass;
1234 #endif
1235
1236 struct ScriptCmdPass : public Pass {
1237 ScriptCmdPass() : Pass("script", "execute commands from script file") { }
1238 void help() YS_OVERRIDE {
1239 log("\n");
1240 log(" script <filename> [<from_label>:<to_label>]\n");
1241 log("\n");
1242 log("This command executes the yosys commands in the specified file.\n");
1243 log("\n");
1244 log("The 2nd argument can be used to only execute the section of the\n");
1245 log("file between the specified labels. An empty from label is synonymous\n");
1246 log("for the beginning of the file and an empty to label is synonymous\n");
1247 log("for the end of the file.\n");
1248 log("\n");
1249 log("If only one label is specified (without ':') then only the block\n");
1250 log("marked with that label (until the next label) is executed.\n");
1251 log("\n");
1252 }
1253 void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE {
1254 if (args.size() < 2)
1255 log_cmd_error("Missing script file.\n");
1256 else if (args.size() == 2)
1257 run_frontend(args[1], "script", design);
1258 else if (args.size() == 3)
1259 run_frontend(args[1], "script", NULL, &args[2], design);
1260 else
1261 extra_args(args, 2, design, false);
1262 }
1263 } ScriptCmdPass;
1264
1265 YOSYS_NAMESPACE_END