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
33 #elif defined(__APPLE__)
34 # include <mach-o/dyld.h>
36 # include <sys/types.h>
37 # include <sys/stat.h>
48 RTLIL::Design
*yosys_design
= NULL
;
50 #ifdef YOSYS_ENABLE_TCL
51 Tcl_Interp
*yosys_tcl_interp
= NULL
;
54 std::string
stringf(const char *fmt
, ...)
60 string
= vstringf(fmt
, ap
);
66 std::string
vstringf(const char *fmt
, va_list ap
)
76 str
= (char*)realloc(str
, sz
);
77 rc
= vsnprintf(str
, sz
, fmt
, apc
);
79 if (rc
>= 0 && rc
< sz
)
84 if (vasprintf(&str
, fmt
, ap
) < 0)
96 std::string
next_token(std::string
&text
, const char *sep
)
98 size_t pos_begin
= text
.find_first_not_of(sep
);
100 if (pos_begin
== std::string::npos
)
101 pos_begin
= text
.size();
103 size_t pos_end
= text
.find_first_of(sep
, pos_begin
);
105 if (pos_end
== std::string::npos
)
106 pos_end
= text
.size();
108 std::string token
= text
.substr(pos_begin
, pos_end
-pos_begin
);
109 text
= text
.substr(pos_end
);
113 // this is very similar to fnmatch(). the exact rules used by this
116 // ? matches any character except
117 // * matches any sequence of characters
118 // [...] matches any of the characters in the list
119 // [!..] matches any of the characters not in the list
121 // a backslash may be used to escape the next characters in the
122 // pattern. each special character can also simply match itself.
124 bool patmatch(const char *pattern
, const char *string
)
129 if (*pattern
== '\\') {
130 if (pattern
[1] == string
[0] && patmatch(pattern
+2, string
+1))
134 if (*pattern
== '?') {
137 return patmatch(pattern
+1, string
+1);
140 if (*pattern
== '*') {
142 if (patmatch(pattern
+1, string
++))
145 return pattern
[1] == 0;
148 if (*pattern
== '[') {
149 bool found_match
= false;
150 bool inverted_list
= pattern
[1] == '!';
151 const char *p
= pattern
+ (inverted_list
? 1 : 0);
155 if (found_match
!= inverted_list
&& patmatch(p
+1, string
+1))
169 if (*pattern
== *string
)
170 return patmatch(pattern
+1, string
+1);
175 int run_command(const std::string
&command
, std::function
<void(const std::string
&)> process_line
)
178 return system(command
.c_str());
180 FILE *f
= popen(command
.c_str(), "r");
186 while (fgets(logbuf
, 128, f
) != NULL
) {
188 if (!line
.empty() && line
.back() == '\n')
189 process_line(line
), line
.clear();
200 return WEXITSTATUS(ret
);
204 std::string
make_temp_file(std::string template_str
)
207 if (template_str
.rfind("/tmp/", 0) == 0) {
208 char path
[MAX_PATH
+1];
209 GetTempPath(MAX_PATH
+1, path
);
210 template_str
= stringf("%s\\%s", path
, template_str
.c_str() + 5);
213 size_t pos
= template_str
.rfind("XXXXXX");
214 log_assert(pos
!= std::string::npos
);
217 for (int i
= 0; i
< 6; i
++) {
218 static std::string y
= "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
219 static uint32_t x
= 314159265 ^ time(NULL
);
220 x
^= x
<< 13, x
^= x
>> 17, x
^= x
<< 5;
221 template_str
[pos
+i
] = y
[x
% y
.size()];
223 if (access(template_str
.c_str(), F_OK
) != 0)
227 size_t pos
= template_str
.rfind("XXXXXX");
228 log_assert(pos
!= std::string::npos
);
230 int suffixlen
= GetSize(template_str
) - pos
- 6;
232 char *p
= strdup(template_str
.c_str());
233 close(mkstemps(p
, suffixlen
));
241 std::string
make_temp_dir(std::string template_str
)
244 template_str
= make_temp_file(template_str
);
245 mkdir(template_str
.c_str());
248 size_t pos
= template_str
.rfind("XXXXXX");
249 log_assert(pos
!= std::string::npos
);
251 int suffixlen
= GetSize(template_str
) - pos
- 6;
252 log_assert(suffixlen
== 0);
254 char *p
= strdup(template_str
.c_str());
263 void remove_directory(std::string dirname
)
266 run_command(stringf("rmdir /s /q \"%s\"", dirname
.c_str()));
269 struct dirent
**namelist
;
270 int n
= scandir(dirname
.c_str(), &namelist
, nullptr, alphasort
);
272 for (int i
= 0; i
< n
; i
++) {
273 if (strcmp(namelist
[i
]->d_name
, ".") && strcmp(namelist
[i
]->d_name
, "..")) {
274 std::string buffer
= stringf("%s/%s", dirname
.c_str(), namelist
[i
]->d_name
);
275 if (!stat(buffer
.c_str(), &stbuf
) && S_ISREG(stbuf
.st_mode
)) {
276 log("Removing `%s'.\n", buffer
.c_str());
277 remove(buffer
.c_str());
279 remove_directory(buffer
);
284 log("Removing `%s'.\n", dirname
.c_str());
285 rmdir(dirname
.c_str());
289 int GetSize(RTLIL::Wire
*wire
)
296 Pass::init_register();
297 yosys_design
= new RTLIL::Design
;
301 void yosys_shutdown()
308 for (auto f
: log_files
)
314 Pass::done_register();
316 #ifdef YOSYS_ENABLE_TCL
317 if (yosys_tcl_interp
!= NULL
) {
318 Tcl_DeleteInterp(yosys_tcl_interp
);
320 yosys_tcl_interp
= NULL
;
324 #ifdef YOSYS_ENABLE_PLUGINS
325 for (auto &it
: loaded_plugins
)
329 loaded_plugins
.clear();
330 loaded_plugin_aliases
.clear();
333 RTLIL::IdString
new_id(std::string file
, int line
, std::string func
)
335 std::string str
= "$auto$";
336 size_t pos
= file
.find_last_of('/');
337 str
+= pos
!= std::string::npos
? file
.substr(pos
+1) : file
;
338 str
+= stringf(":%d:%s$%d", line
, func
.c_str(), autoidx
++);
342 RTLIL::Design
*yosys_get_design()
347 const char *create_prompt(RTLIL::Design
*design
, int recursion_counter
)
349 static char buffer
[100];
350 std::string str
= "\n";
351 if (recursion_counter
> 1)
352 str
+= stringf("(%d) ", recursion_counter
);
354 if (!design
->selected_active_module
.empty())
355 str
+= stringf(" [%s]", RTLIL::unescape_id(design
->selected_active_module
).c_str());
356 if (!design
->selection_stack
.empty() && !design
->selection_stack
.back().full_selection
) {
357 if (design
->selected_active_module
.empty())
359 else if (design
->selection_stack
.back().selected_modules
.size() != 1 || design
->selection_stack
.back().selected_members
.size() != 0 ||
360 design
->selection_stack
.back().selected_modules
.count(design
->selected_active_module
) == 0)
363 snprintf(buffer
, 100, "%s> ", str
.c_str());
367 #ifdef YOSYS_ENABLE_TCL
368 static int tcl_yosys_cmd(ClientData
, Tcl_Interp
*interp
, int argc
, const char *argv
[])
370 std::vector
<std::string
> args
;
371 for (int i
= 1; i
< argc
; i
++)
372 args
.push_back(argv
[i
]);
374 if (args
.size() >= 1 && args
[0] == "-import") {
375 for (auto &it
: pass_register
) {
376 std::string tcl_command_name
= it
.first
;
377 if (tcl_command_name
== "proc")
378 tcl_command_name
= "procs";
380 if (Tcl_GetCommandInfo(interp
, tcl_command_name
.c_str(), &info
) != 0) {
381 log("[TCL: yosys -import] Command name collision: found pre-existing command `%s' -> skip.\n", it
.first
.c_str());
383 std::string tcl_script
= stringf("proc %s args { yosys %s {*}$args }", tcl_command_name
.c_str(), it
.first
.c_str());
384 Tcl_Eval(interp
, tcl_script
.c_str());
390 if (args
.size() == 1) {
391 Pass::call(yosys_get_design(), args
[0]);
395 Pass::call(yosys_get_design(), args
);
399 extern Tcl_Interp
*yosys_get_tcl_interp()
401 if (yosys_tcl_interp
== NULL
) {
402 yosys_tcl_interp
= Tcl_CreateInterp();
403 Tcl_CreateCommand(yosys_tcl_interp
, "yosys", tcl_yosys_cmd
, NULL
, NULL
);
405 return yosys_tcl_interp
;
408 struct TclPass
: public Pass
{
409 TclPass() : Pass("tcl", "execute a TCL script file") { }
410 virtual void help() {
412 log(" tcl <filename>\n");
414 log("This command executes the tcl commands in the specified file.\n");
415 log("Use 'yosys cmd' to run the yosys command 'cmd' from tcl.\n");
417 log("The tcl command 'yosys -import' can be used to import all yosys\n");
418 log("commands directly as tcl commands to the tcl shell. The yosys\n");
419 log("command 'proc' is wrapped using the tcl command 'procs' in order\n");
420 log("to avoid a name collision with the tcl builting command 'proc'.\n");
423 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
425 log_cmd_error("Missing script file.\n");
427 extra_args(args
, 1, design
, false);
428 if (Tcl_EvalFile(yosys_get_tcl_interp(), args
[1].c_str()) != TCL_OK
)
429 log_cmd_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(yosys_get_tcl_interp()));
434 #if defined(__linux__)
435 std::string
proc_self_dirname()
438 ssize_t buflen
= readlink("/proc/self/exe", path
, sizeof(path
));
440 log_error("readlink(\"/proc/self/exe\") failed: %s\n", strerror(errno
));
442 while (buflen
> 0 && path
[buflen
-1] != '/')
444 return std::string(path
, buflen
);
446 #elif defined(__APPLE__)
447 std::string
proc_self_dirname()
451 while (_NSGetExecutablePath(path
, &buflen
) != 0)
452 path
= (char *) realloc((void *) path
, buflen
);
453 while (buflen
> 0 && path
[buflen
-1] != '/')
455 return std::string(path
, buflen
);
457 #elif defined(_WIN32)
458 std::string
proc_self_dirname()
460 char longpath
[MAX_PATH
+1], shortpath
[MAX_PATH
+1];
461 if (!GetModuleFileName(0, longpath
, MAX_PATH
+1))
462 log_error("GetModuleFileName() failed.\n");
463 if (!GetShortPathName(longpath
, shortpath
, MAX_PATH
+1))
464 log_error("GetShortPathName() failed.\n");
465 for (int i
= strlen(shortpath
)-1; i
>= 0 && shortpath
[i
] != '/' && shortpath
[i
] != '\\' ; i
--)
467 return std::string(shortpath
);
469 #elif defined(EMSCRIPTEN)
470 std::string
proc_self_dirname()
475 #error Dont know how to determine process executable base path!
478 std::string
proc_share_dirname()
480 std::string proc_self_path
= proc_self_dirname();
481 std::string proc_share_path
= proc_self_path
+ "share/";
482 if (access(proc_share_path
.c_str(), X_OK
) == 0)
483 return proc_share_path
;
484 proc_share_path
= proc_self_path
+ "../share/yosys/";
485 if (access(proc_share_path
.c_str(), X_OK
) == 0)
486 return proc_share_path
;
487 log_error("proc_share_dirname: unable to determine share/ directory!\n");
490 bool fgetline(FILE *f
, std::string
&buffer
)
495 if (fgets(block
, 4096, f
) == NULL
)
498 if (buffer
.size() > 0 && (buffer
[buffer
.size()-1] == '\n' || buffer
[buffer
.size()-1] == '\r')) {
499 while (buffer
.size() > 0 && (buffer
[buffer
.size()-1] == '\n' || buffer
[buffer
.size()-1] == '\r'))
500 buffer
.resize(buffer
.size()-1);
506 static void handle_label(std::string
&command
, bool &from_to_active
, const std::string
&run_from
, const std::string
&run_to
)
511 while (pos
< GetSize(command
) && (command
[pos
] == ' ' || command
[pos
] == '\t'))
514 while (pos
< GetSize(command
) && command
[pos
] != ' ' && command
[pos
] != '\t' && command
[pos
] != '\r' && command
[pos
] != '\n')
515 label
+= command
[pos
++];
517 if (label
.back() == ':' && GetSize(label
) > 1)
519 label
= label
.substr(0, GetSize(label
)-1);
520 command
= command
.substr(pos
);
522 if (label
== run_from
)
523 from_to_active
= true;
524 else if (label
== run_to
|| (run_from
== run_to
&& !run_from
.empty()))
525 from_to_active
= false;
529 void run_frontend(std::string filename
, std::string command
, RTLIL::Design
*design
, std::string
*backend_command
, std::string
*from_to_label
)
531 if (command
== "auto") {
532 if (filename
.size() > 2 && filename
.substr(filename
.size()-2) == ".v")
534 else if (filename
.size() > 2 && filename
.substr(filename
.size()-3) == ".sv")
535 command
= "verilog -sv";
536 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".il")
538 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".ys")
540 else if (filename
== "-")
543 log_error("Can't guess frontend for input file `%s' (missing -f option)!\n", filename
.c_str());
546 if (command
== "script")
548 std::string run_from
, run_to
;
549 bool from_to_active
= true;
551 if (from_to_label
!= NULL
) {
552 size_t pos
= from_to_label
->find(':');
553 if (pos
== std::string::npos
) {
554 run_from
= *from_to_label
;
555 run_to
= *from_to_label
;
557 run_from
= from_to_label
->substr(0, pos
);
558 run_to
= from_to_label
->substr(pos
+1);
560 from_to_active
= run_from
.empty();
563 log("\n-- Executing script file `%s' --\n", filename
.c_str());
568 f
= fopen(filename
.c_str(), "r");
571 log_error("Can't open script file `%s' for reading: %s\n", filename
.c_str(), strerror(errno
));
573 FILE *backup_script_file
= Frontend::current_script_file
;
574 Frontend::current_script_file
= f
;
578 while (fgetline(f
, command
)) {
579 while (!command
.empty() && command
[command
.size()-1] == '\\') {
580 std::string next_line
;
581 if (!fgetline(f
, next_line
))
583 command
.resize(command
.size()-1);
584 command
+= next_line
;
586 handle_label(command
, from_to_active
, run_from
, run_to
);
588 Pass::call(design
, command
);
591 if (!command
.empty()) {
592 handle_label(command
, from_to_active
, run_from
, run_to
);
594 Pass::call(design
, command
);
597 catch (log_cmd_error_expection
) {
598 Frontend::current_script_file
= backup_script_file
;
599 throw log_cmd_error_expection();
602 Frontend::current_script_file
= backup_script_file
;
607 if (backend_command
!= NULL
&& *backend_command
== "auto")
608 *backend_command
= "";
613 if (filename
== "-") {
614 log("\n-- Parsing stdin using frontend `%s' --\n", command
.c_str());
616 log("\n-- Parsing `%s' using frontend `%s' --\n", filename
.c_str(), command
.c_str());
619 Frontend::frontend_call(design
, NULL
, filename
, command
);
622 void run_pass(std::string command
, RTLIL::Design
*design
)
624 log("\n-- Running pass `%s' --\n", command
.c_str());
626 Pass::call(design
, command
);
629 void run_backend(std::string filename
, std::string command
, RTLIL::Design
*design
)
631 if (command
== "auto") {
632 if (filename
.size() > 2 && filename
.substr(filename
.size()-2) == ".v")
634 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".il")
636 else if (filename
.size() > 5 && filename
.substr(filename
.size()-5) == ".blif")
638 else if (filename
== "-")
640 else if (filename
.empty())
643 log_error("Can't guess backend for output file `%s' (missing -b option)!\n", filename
.c_str());
646 if (filename
.empty())
649 if (filename
== "-") {
650 log("\n-- Writing to stdout using backend `%s' --\n", command
.c_str());
652 log("\n-- Writing to `%s' using backend `%s' --\n", filename
.c_str(), command
.c_str());
655 Backend::backend_call(design
, NULL
, filename
, command
);
658 #ifdef YOSYS_ENABLE_READLINE
659 static char *readline_cmd_generator(const char *text
, int state
)
661 static std::map
<std::string
, Pass
*>::iterator it
;
665 it
= pass_register
.begin();
669 for (; it
!= pass_register
.end(); it
++) {
670 if (it
->first
.substr(0, len
) == text
)
671 return strdup((it
++)->first
.c_str());
676 static char *readline_obj_generator(const char *text
, int state
)
678 static std::vector
<char*> obj_names
;
686 RTLIL::Design
*design
= yosys_get_design();
687 int len
= strlen(text
);
689 if (design
->selected_active_module
.empty())
691 for (auto &it
: design
->modules_
)
692 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
693 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
696 if (design
->modules_
.count(design
->selected_active_module
) > 0)
698 RTLIL::Module
*module
= design
->modules_
.at(design
->selected_active_module
);
700 for (auto &it
: module
->wires_
)
701 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
702 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
704 for (auto &it
: module
->memories
)
705 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
706 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
708 for (auto &it
: module
->cells_
)
709 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
710 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
712 for (auto &it
: module
->processes
)
713 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
714 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
717 std::sort(obj_names
.begin(), obj_names
.end());
720 if (idx
< obj_names
.size())
721 return strdup(obj_names
[idx
++]);
728 static char **readline_completion(const char *text
, int start
, int)
731 return rl_completion_matches(text
, readline_cmd_generator
);
732 if (strncmp(rl_line_buffer
, "read_", 5) && strncmp(rl_line_buffer
, "write_", 6))
733 return rl_completion_matches(text
, readline_obj_generator
);
738 void shell(RTLIL::Design
*design
)
740 static int recursion_counter
= 0;
743 log_cmd_error_throw
= true;
745 #ifdef YOSYS_ENABLE_READLINE
746 rl_readline_name
= "yosys";
747 rl_attempted_completion_function
= readline_completion
;
748 rl_basic_word_break_characters
= " \t\n";
751 char *command
= NULL
;
752 #ifdef YOSYS_ENABLE_READLINE
753 while ((command
= readline(create_prompt(design
, recursion_counter
))) != NULL
)
755 char command_buffer
[4096];
756 while ((command
= fgets(command_buffer
, 4096, stdin
)) != NULL
)
759 if (command
[strspn(command
, " \t\r\n")] == 0)
761 #ifdef YOSYS_ENABLE_READLINE
762 add_history(command
);
765 char *p
= command
+ strspn(command
, " \t\r\n");
766 if (!strncmp(p
, "exit", 4)) {
768 p
+= strspn(p
, " \t\r\n");
774 log_assert(design
->selection_stack
.size() == 1);
775 Pass::call(design
, command
);
776 } catch (log_cmd_error_expection
) {
777 while (design
->selection_stack
.size() > 1)
778 design
->selection_stack
.pop_back();
786 log_cmd_error_throw
= false;
789 struct ShellPass
: public Pass
{
790 ShellPass() : Pass("shell", "enter interactive command mode") { }
791 virtual void help() {
795 log("This command enters the interactive command mode. This can be useful\n");
796 log("in a script to interrupt the script at a certain point and allow for\n");
797 log("interactive inspection or manual synthesis of the design at this point.\n");
799 log("The command prompt of the interactive shell indicates the current\n");
800 log("selection (see 'help select'):\n");
803 log(" the entire design is selected\n");
806 log(" only part of the design is selected\n");
808 log(" yosys [modname]>\n");
809 log(" the entire module 'modname' is selected using 'select -module modname'\n");
811 log(" yosys [modname]*>\n");
812 log(" only part of current module 'modname' is selected\n");
814 log("When in interactive shell, some errors (e.g. invalid command arguments)\n");
815 log("do not terminate yosys but return to the command prompt.\n");
817 log("This command is the default action if nothing else has been specified\n");
818 log("on the command line.\n");
820 log("Press Ctrl-D or type 'exit' to leave the interactive shell.\n");
823 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
824 extra_args(args
, 1, design
, false);
829 #ifdef YOSYS_ENABLE_READLINE
830 struct HistoryPass
: public Pass
{
831 HistoryPass() : Pass("history", "show last interactive commands") { }
832 virtual void help() {
836 log("This command prints all commands in the shell history buffer. This are\n");
837 log("all commands executed in an interactive session, but not the commands\n");
838 log("from executed scripts.\n");
841 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
842 extra_args(args
, 1, design
, false);
843 for(HIST_ENTRY
**list
= history_list(); *list
!= NULL
; list
++)
844 log("%s\n", (*list
)->line
);
849 struct ScriptPass
: public Pass
{
850 ScriptPass() : Pass("script", "execute commands from script file") { }
851 virtual void help() {
853 log(" script <filename> [<from_label>:<to_label>]\n");
855 log("This command executes the yosys commands in the specified file.\n");
857 log("The 2nd argument can be used to only execute the section of the\n");
858 log("file between the specified labels. An empty from label is synonymous\n");
859 log("for the beginning of the file and an empty to label is synonymous\n");
860 log("for the end of the file.\n");
862 log("If only one label is specified (without ':') then only the block\n");
863 log("marked with that label (until the next label) is executed.\n");
866 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
868 log_cmd_error("Missing script file.\n");
869 else if (args
.size() == 2)
870 run_frontend(args
[1], "script", design
, NULL
, NULL
);
871 else if (args
.size() == 3)
872 run_frontend(args
[1], "script", design
, NULL
, &args
[2]);
874 extra_args(args
, 2, design
, false);