2 * yosys -- Yosys Open SYnthesis Suite
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
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.
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.
20 #include "kernel/yosys.h"
22 #ifdef YOSYS_ENABLE_READLINE
23 # include <readline/readline.h>
24 # include <readline/history.h>
27 #ifdef YOSYS_ENABLE_PLUGINS
34 #elif defined(__APPLE__)
35 # include <mach-o/dyld.h>
39 # include <sys/types.h>
40 # include <sys/stat.h>
48 #if defined(_WIN32) && !defined(__MINGW32__)
49 const char *yosys_version_str
= "Windows";
53 RTLIL::Design
*yosys_design
= NULL
;
55 #ifdef YOSYS_ENABLE_TCL
56 Tcl_Interp
*yosys_tcl_interp
= NULL
;
59 std::string
stringf(const char *fmt
, ...)
65 string
= vstringf(fmt
, ap
);
71 std::string
vstringf(const char *fmt
, va_list ap
)
81 str
= (char*)realloc(str
, sz
);
82 rc
= vsnprintf(str
, sz
, fmt
, apc
);
84 if (rc
>= 0 && rc
< sz
)
89 if (vasprintf(&str
, fmt
, ap
) < 0)
101 std::string
next_token(std::string
&text
, const char *sep
)
103 size_t pos_begin
= text
.find_first_not_of(sep
);
105 if (pos_begin
== std::string::npos
)
106 pos_begin
= text
.size();
108 size_t pos_end
= text
.find_first_of(sep
, pos_begin
);
110 if (pos_end
== std::string::npos
)
111 pos_end
= text
.size();
113 std::string token
= text
.substr(pos_begin
, pos_end
-pos_begin
);
114 text
= text
.substr(pos_end
);
118 // this is very similar to fnmatch(). the exact rules used by this
121 // ? matches any character except
122 // * matches any sequence of characters
123 // [...] matches any of the characters in the list
124 // [!..] matches any of the characters not in the list
126 // a backslash may be used to escape the next characters in the
127 // pattern. each special character can also simply match itself.
129 bool patmatch(const char *pattern
, const char *string
)
134 if (*pattern
== '\\') {
135 if (pattern
[1] == string
[0] && patmatch(pattern
+2, string
+1))
139 if (*pattern
== '?') {
142 return patmatch(pattern
+1, string
+1);
145 if (*pattern
== '*') {
147 if (patmatch(pattern
+1, string
++))
150 return pattern
[1] == 0;
153 if (*pattern
== '[') {
154 bool found_match
= false;
155 bool inverted_list
= pattern
[1] == '!';
156 const char *p
= pattern
+ (inverted_list
? 1 : 0);
160 if (found_match
!= inverted_list
&& patmatch(p
+1, string
+1))
174 if (*pattern
== *string
)
175 return patmatch(pattern
+1, string
+1);
180 int run_command(const std::string
&command
, std::function
<void(const std::string
&)> process_line
)
183 return system(command
.c_str());
185 FILE *f
= popen(command
.c_str(), "r");
191 while (fgets(logbuf
, 128, f
) != NULL
) {
193 if (!line
.empty() && line
.back() == '\n')
194 process_line(line
), line
.clear();
205 return WEXITSTATUS(ret
);
209 std::string
make_temp_file(std::string template_str
)
212 if (template_str
.rfind("/tmp/", 0) == 0) {
213 char path
[MAX_PATH
+1];
214 GetTempPath(MAX_PATH
+1, path
);
215 template_str
= stringf("%s\\%s", path
, template_str
.c_str() + 5);
218 size_t pos
= template_str
.rfind("XXXXXX");
219 log_assert(pos
!= std::string::npos
);
222 for (int i
= 0; i
< 6; i
++) {
223 static std::string y
= "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
224 static uint32_t x
= 314159265 ^ time(NULL
);
225 x
^= x
<< 13, x
^= x
>> 17, x
^= x
<< 5;
226 template_str
[pos
+i
] = y
[x
% y
.size()];
228 if (_access(template_str
.c_str(), 0) != 0)
232 size_t pos
= template_str
.rfind("XXXXXX");
233 log_assert(pos
!= std::string::npos
);
235 int suffixlen
= GetSize(template_str
) - pos
- 6;
237 char *p
= strdup(template_str
.c_str());
238 close(mkstemps(p
, suffixlen
));
246 std::string
make_temp_dir(std::string template_str
)
249 template_str
= make_temp_file(template_str
);
250 mkdir(template_str
.c_str());
253 size_t pos
= template_str
.rfind("XXXXXX");
254 log_assert(pos
!= std::string::npos
);
256 int suffixlen
= GetSize(template_str
) - pos
- 6;
257 log_assert(suffixlen
== 0);
259 char *p
= strdup(template_str
.c_str());
261 log_assert(p
!= NULL
);
270 bool check_file_exists(std::string filename
, bool)
272 return _access(filename
.c_str(), 0) == 0;
275 bool check_file_exists(std::string filename
, bool is_exec
)
277 return access(filename
.c_str(), is_exec
? X_OK
: F_OK
) == 0;
281 void remove_directory(std::string dirname
)
284 run_command(stringf("rmdir /s /q \"%s\"", dirname
.c_str()));
287 struct dirent
**namelist
;
288 int n
= scandir(dirname
.c_str(), &namelist
, nullptr, alphasort
);
290 for (int i
= 0; i
< n
; i
++) {
291 if (strcmp(namelist
[i
]->d_name
, ".") && strcmp(namelist
[i
]->d_name
, "..")) {
292 std::string buffer
= stringf("%s/%s", dirname
.c_str(), namelist
[i
]->d_name
);
293 if (!stat(buffer
.c_str(), &stbuf
) && S_ISREG(stbuf
.st_mode
)) {
294 log("Removing `%s'.\n", buffer
.c_str());
295 remove(buffer
.c_str());
297 remove_directory(buffer
);
302 log("Removing `%s'.\n", dirname
.c_str());
303 rmdir(dirname
.c_str());
307 int GetSize(RTLIL::Wire
*wire
)
314 Pass::init_register();
315 yosys_design
= new RTLIL::Design
;
319 void yosys_shutdown()
326 for (auto f
: log_files
)
332 Pass::done_register();
334 #ifdef YOSYS_ENABLE_TCL
335 if (yosys_tcl_interp
!= NULL
) {
336 Tcl_DeleteInterp(yosys_tcl_interp
);
338 yosys_tcl_interp
= NULL
;
342 #ifdef YOSYS_ENABLE_PLUGINS
343 for (auto &it
: loaded_plugins
)
346 loaded_plugins
.clear();
347 loaded_plugin_aliases
.clear();
351 RTLIL::IdString
new_id(std::string file
, int line
, std::string func
)
353 std::string str
= "$auto$";
354 size_t pos
= file
.find_last_of('/');
355 str
+= pos
!= std::string::npos
? file
.substr(pos
+1) : file
;
356 str
+= stringf(":%d:%s$%d", line
, func
.c_str(), autoidx
++);
360 RTLIL::Design
*yosys_get_design()
365 const char *create_prompt(RTLIL::Design
*design
, int recursion_counter
)
367 static char buffer
[100];
368 std::string str
= "\n";
369 if (recursion_counter
> 1)
370 str
+= stringf("(%d) ", recursion_counter
);
372 if (!design
->selected_active_module
.empty())
373 str
+= stringf(" [%s]", RTLIL::unescape_id(design
->selected_active_module
).c_str());
374 if (!design
->selection_stack
.empty() && !design
->selection_stack
.back().full_selection
) {
375 if (design
->selected_active_module
.empty())
377 else if (design
->selection_stack
.back().selected_modules
.size() != 1 || design
->selection_stack
.back().selected_members
.size() != 0 ||
378 design
->selection_stack
.back().selected_modules
.count(design
->selected_active_module
) == 0)
381 snprintf(buffer
, 100, "%s> ", str
.c_str());
385 #ifdef YOSYS_ENABLE_TCL
386 static int tcl_yosys_cmd(ClientData
, Tcl_Interp
*interp
, int argc
, const char *argv
[])
388 std::vector
<std::string
> args
;
389 for (int i
= 1; i
< argc
; i
++)
390 args
.push_back(argv
[i
]);
392 if (args
.size() >= 1 && args
[0] == "-import") {
393 for (auto &it
: pass_register
) {
394 std::string tcl_command_name
= it
.first
;
395 if (tcl_command_name
== "proc")
396 tcl_command_name
= "procs";
398 if (Tcl_GetCommandInfo(interp
, tcl_command_name
.c_str(), &info
) != 0) {
399 log("[TCL: yosys -import] Command name collision: found pre-existing command `%s' -> skip.\n", it
.first
.c_str());
401 std::string tcl_script
= stringf("proc %s args { yosys %s {*}$args }", tcl_command_name
.c_str(), it
.first
.c_str());
402 Tcl_Eval(interp
, tcl_script
.c_str());
408 if (args
.size() == 1) {
409 Pass::call(yosys_get_design(), args
[0]);
413 Pass::call(yosys_get_design(), args
);
417 extern Tcl_Interp
*yosys_get_tcl_interp()
419 if (yosys_tcl_interp
== NULL
) {
420 yosys_tcl_interp
= Tcl_CreateInterp();
421 Tcl_CreateCommand(yosys_tcl_interp
, "yosys", tcl_yosys_cmd
, NULL
, NULL
);
423 return yosys_tcl_interp
;
426 struct TclPass
: public Pass
{
427 TclPass() : Pass("tcl", "execute a TCL script file") { }
428 virtual void help() {
430 log(" tcl <filename>\n");
432 log("This command executes the tcl commands in the specified file.\n");
433 log("Use 'yosys cmd' to run the yosys command 'cmd' from tcl.\n");
435 log("The tcl command 'yosys -import' can be used to import all yosys\n");
436 log("commands directly as tcl commands to the tcl shell. The yosys\n");
437 log("command 'proc' is wrapped using the tcl command 'procs' in order\n");
438 log("to avoid a name collision with the tcl builting command 'proc'.\n");
441 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
443 log_cmd_error("Missing script file.\n");
445 extra_args(args
, 1, design
, false);
446 if (Tcl_EvalFile(yosys_get_tcl_interp(), args
[1].c_str()) != TCL_OK
)
447 log_cmd_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(yosys_get_tcl_interp()));
452 #if defined(__linux__)
453 std::string
proc_self_dirname()
456 ssize_t buflen
= readlink("/proc/self/exe", path
, sizeof(path
));
458 log_error("readlink(\"/proc/self/exe\") failed: %s\n", strerror(errno
));
460 while (buflen
> 0 && path
[buflen
-1] != '/')
462 return std::string(path
, buflen
);
464 #elif defined(__APPLE__)
465 std::string
proc_self_dirname()
469 while (_NSGetExecutablePath(path
, &buflen
) != 0)
470 path
= (char *) realloc((void *) path
, buflen
);
471 while (buflen
> 0 && path
[buflen
-1] != '/')
473 return std::string(path
, buflen
);
475 #elif defined(_WIN32)
476 std::string
proc_self_dirname()
478 char longpath
[MAX_PATH
+1], shortpath
[MAX_PATH
+1];
479 if (!GetModuleFileName(0, longpath
, MAX_PATH
+1))
480 log_error("GetModuleFileName() failed.\n");
481 if (!GetShortPathName(longpath
, shortpath
, MAX_PATH
+1))
482 log_error("GetShortPathName() failed.\n");
483 for (int i
= strlen(shortpath
)-1; i
>= 0 && shortpath
[i
] != '/' && shortpath
[i
] != '\\' ; i
--)
485 return std::string(shortpath
);
487 #elif defined(EMSCRIPTEN)
488 std::string
proc_self_dirname()
493 #error Dont know how to determine process executable base path!
496 std::string
proc_share_dirname()
498 std::string proc_self_path
= proc_self_dirname();
499 std::string proc_share_path
= proc_self_path
+ "share/";
500 if (check_file_exists(proc_share_path
, true))
501 return proc_share_path
;
502 proc_share_path
= proc_self_path
+ "../share/yosys/";
503 if (check_file_exists(proc_share_path
, true))
504 return proc_share_path
;
505 log_error("proc_share_dirname: unable to determine share/ directory!\n");
508 bool fgetline(FILE *f
, std::string
&buffer
)
513 if (fgets(block
, 4096, f
) == NULL
)
516 if (buffer
.size() > 0 && (buffer
[buffer
.size()-1] == '\n' || buffer
[buffer
.size()-1] == '\r')) {
517 while (buffer
.size() > 0 && (buffer
[buffer
.size()-1] == '\n' || buffer
[buffer
.size()-1] == '\r'))
518 buffer
.resize(buffer
.size()-1);
524 static void handle_label(std::string
&command
, bool &from_to_active
, const std::string
&run_from
, const std::string
&run_to
)
529 while (pos
< GetSize(command
) && (command
[pos
] == ' ' || command
[pos
] == '\t'))
532 while (pos
< GetSize(command
) && command
[pos
] != ' ' && command
[pos
] != '\t' && command
[pos
] != '\r' && command
[pos
] != '\n')
533 label
+= command
[pos
++];
535 if (label
.back() == ':' && GetSize(label
) > 1)
537 label
= label
.substr(0, GetSize(label
)-1);
538 command
= command
.substr(pos
);
540 if (label
== run_from
)
541 from_to_active
= true;
542 else if (label
== run_to
|| (run_from
== run_to
&& !run_from
.empty()))
543 from_to_active
= false;
547 void run_frontend(std::string filename
, std::string command
, RTLIL::Design
*design
, std::string
*backend_command
, std::string
*from_to_label
)
549 if (command
== "auto") {
550 if (filename
.size() > 2 && filename
.substr(filename
.size()-2) == ".v")
552 else if (filename
.size() > 2 && filename
.substr(filename
.size()-3) == ".sv")
553 command
= "verilog -sv";
554 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".il")
556 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".ys")
558 else if (filename
== "-")
561 log_error("Can't guess frontend for input file `%s' (missing -f option)!\n", filename
.c_str());
564 if (command
== "script")
566 std::string run_from
, run_to
;
567 bool from_to_active
= true;
569 if (from_to_label
!= NULL
) {
570 size_t pos
= from_to_label
->find(':');
571 if (pos
== std::string::npos
) {
572 run_from
= *from_to_label
;
573 run_to
= *from_to_label
;
575 run_from
= from_to_label
->substr(0, pos
);
576 run_to
= from_to_label
->substr(pos
+1);
578 from_to_active
= run_from
.empty();
581 log("\n-- Executing script file `%s' --\n", filename
.c_str());
586 f
= fopen(filename
.c_str(), "r");
589 log_error("Can't open script file `%s' for reading: %s\n", filename
.c_str(), strerror(errno
));
591 FILE *backup_script_file
= Frontend::current_script_file
;
592 Frontend::current_script_file
= f
;
596 while (fgetline(f
, command
)) {
597 while (!command
.empty() && command
[command
.size()-1] == '\\') {
598 std::string next_line
;
599 if (!fgetline(f
, next_line
))
601 command
.resize(command
.size()-1);
602 command
+= next_line
;
604 handle_label(command
, from_to_active
, run_from
, run_to
);
606 Pass::call(design
, command
);
609 if (!command
.empty()) {
610 handle_label(command
, from_to_active
, run_from
, run_to
);
612 Pass::call(design
, command
);
615 catch (log_cmd_error_expection
) {
616 Frontend::current_script_file
= backup_script_file
;
617 throw log_cmd_error_expection();
620 Frontend::current_script_file
= backup_script_file
;
625 if (backend_command
!= NULL
&& *backend_command
== "auto")
626 *backend_command
= "";
631 if (filename
== "-") {
632 log("\n-- Parsing stdin using frontend `%s' --\n", command
.c_str());
634 log("\n-- Parsing `%s' using frontend `%s' --\n", filename
.c_str(), command
.c_str());
637 Frontend::frontend_call(design
, NULL
, filename
, command
);
640 void run_pass(std::string command
, RTLIL::Design
*design
)
642 log("\n-- Running pass `%s' --\n", command
.c_str());
644 Pass::call(design
, command
);
647 void run_backend(std::string filename
, std::string command
, RTLIL::Design
*design
)
649 if (command
== "auto") {
650 if (filename
.size() > 2 && filename
.substr(filename
.size()-2) == ".v")
652 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".il")
654 else if (filename
.size() > 5 && filename
.substr(filename
.size()-5) == ".blif")
656 else if (filename
== "-")
658 else if (filename
.empty())
661 log_error("Can't guess backend for output file `%s' (missing -b option)!\n", filename
.c_str());
664 if (filename
.empty())
667 if (filename
== "-") {
668 log("\n-- Writing to stdout using backend `%s' --\n", command
.c_str());
670 log("\n-- Writing to `%s' using backend `%s' --\n", filename
.c_str(), command
.c_str());
673 Backend::backend_call(design
, NULL
, filename
, command
);
676 #ifdef YOSYS_ENABLE_READLINE
677 static char *readline_cmd_generator(const char *text
, int state
)
679 static std::map
<std::string
, Pass
*>::iterator it
;
683 it
= pass_register
.begin();
687 for (; it
!= pass_register
.end(); it
++) {
688 if (it
->first
.substr(0, len
) == text
)
689 return strdup((it
++)->first
.c_str());
694 static char *readline_obj_generator(const char *text
, int state
)
696 static std::vector
<char*> obj_names
;
704 RTLIL::Design
*design
= yosys_get_design();
705 int len
= strlen(text
);
707 if (design
->selected_active_module
.empty())
709 for (auto &it
: design
->modules_
)
710 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
711 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
714 if (design
->modules_
.count(design
->selected_active_module
) > 0)
716 RTLIL::Module
*module
= design
->modules_
.at(design
->selected_active_module
);
718 for (auto &it
: module
->wires_
)
719 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
720 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
722 for (auto &it
: module
->memories
)
723 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
724 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
726 for (auto &it
: module
->cells_
)
727 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
728 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
730 for (auto &it
: module
->processes
)
731 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
732 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
735 std::sort(obj_names
.begin(), obj_names
.end());
738 if (idx
< obj_names
.size())
739 return strdup(obj_names
[idx
++]);
746 static char **readline_completion(const char *text
, int start
, int)
749 return rl_completion_matches(text
, readline_cmd_generator
);
750 if (strncmp(rl_line_buffer
, "read_", 5) && strncmp(rl_line_buffer
, "write_", 6))
751 return rl_completion_matches(text
, readline_obj_generator
);
756 void shell(RTLIL::Design
*design
)
758 static int recursion_counter
= 0;
761 log_cmd_error_throw
= true;
763 #ifdef YOSYS_ENABLE_READLINE
764 rl_readline_name
= "yosys";
765 rl_attempted_completion_function
= readline_completion
;
766 rl_basic_word_break_characters
= " \t\n";
769 char *command
= NULL
;
770 #ifdef YOSYS_ENABLE_READLINE
771 while ((command
= readline(create_prompt(design
, recursion_counter
))) != NULL
)
773 char command_buffer
[4096];
774 while ((command
= fgets(command_buffer
, 4096, stdin
)) != NULL
)
777 if (command
[strspn(command
, " \t\r\n")] == 0)
779 #ifdef YOSYS_ENABLE_READLINE
780 add_history(command
);
783 char *p
= command
+ strspn(command
, " \t\r\n");
784 if (!strncmp(p
, "exit", 4)) {
786 p
+= strspn(p
, " \t\r\n");
792 log_assert(design
->selection_stack
.size() == 1);
793 Pass::call(design
, command
);
794 } catch (log_cmd_error_expection
) {
795 while (design
->selection_stack
.size() > 1)
796 design
->selection_stack
.pop_back();
804 log_cmd_error_throw
= false;
807 struct ShellPass
: public Pass
{
808 ShellPass() : Pass("shell", "enter interactive command mode") { }
809 virtual void help() {
813 log("This command enters the interactive command mode. This can be useful\n");
814 log("in a script to interrupt the script at a certain point and allow for\n");
815 log("interactive inspection or manual synthesis of the design at this point.\n");
817 log("The command prompt of the interactive shell indicates the current\n");
818 log("selection (see 'help select'):\n");
821 log(" the entire design is selected\n");
824 log(" only part of the design is selected\n");
826 log(" yosys [modname]>\n");
827 log(" the entire module 'modname' is selected using 'select -module modname'\n");
829 log(" yosys [modname]*>\n");
830 log(" only part of current module 'modname' is selected\n");
832 log("When in interactive shell, some errors (e.g. invalid command arguments)\n");
833 log("do not terminate yosys but return to the command prompt.\n");
835 log("This command is the default action if nothing else has been specified\n");
836 log("on the command line.\n");
838 log("Press Ctrl-D or type 'exit' to leave the interactive shell.\n");
841 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
842 extra_args(args
, 1, design
, false);
847 #ifdef YOSYS_ENABLE_READLINE
848 struct HistoryPass
: public Pass
{
849 HistoryPass() : Pass("history", "show last interactive commands") { }
850 virtual void help() {
854 log("This command prints all commands in the shell history buffer. This are\n");
855 log("all commands executed in an interactive session, but not the commands\n");
856 log("from executed scripts.\n");
859 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
860 extra_args(args
, 1, design
, false);
861 for(HIST_ENTRY
**list
= history_list(); *list
!= NULL
; list
++)
862 log("%s\n", (*list
)->line
);
867 struct ScriptPass
: public Pass
{
868 ScriptPass() : Pass("script", "execute commands from script file") { }
869 virtual void help() {
871 log(" script <filename> [<from_label>:<to_label>]\n");
873 log("This command executes the yosys commands in the specified file.\n");
875 log("The 2nd argument can be used to only execute the section of the\n");
876 log("file between the specified labels. An empty from label is synonymous\n");
877 log("for the beginning of the file and an empty to label is synonymous\n");
878 log("for the end of the file.\n");
880 log("If only one label is specified (without ':') then only the block\n");
881 log("marked with that label (until the next label) is executed.\n");
884 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
886 log_cmd_error("Missing script file.\n");
887 else if (args
.size() == 2)
888 run_frontend(args
[1], "script", design
, NULL
, NULL
);
889 else if (args
.size() == 3)
890 run_frontend(args
[1], "script", design
, NULL
, &args
[2]);
892 extra_args(args
, 2, design
, false);