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