Fixed proc_{self,share}_dirname error handling
[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
22 #include <readline/readline.h>
23 #include <readline/history.h>
24
25 #include <unistd.h>
26 #include <limits.h>
27
28 YOSYS_NAMESPACE_BEGIN
29
30 int autoidx = 1;
31 RTLIL::Design *yosys_design = NULL;
32
33 #ifdef YOSYS_ENABLE_TCL
34 Tcl_Interp *yosys_tcl_interp = NULL;
35 #endif
36
37 std::string stringf(const char *fmt, ...)
38 {
39 std::string string;
40 va_list ap;
41
42 va_start(ap, fmt);
43 string = vstringf(fmt, ap);
44 va_end(ap);
45
46 return string;
47 }
48
49 std::string vstringf(const char *fmt, va_list ap)
50 {
51 std::string string;
52 char *str = NULL;
53
54 if (vasprintf(&str, fmt, ap) < 0)
55 str = NULL;
56
57 if (str != NULL) {
58 string = str;
59 free(str);
60 }
61
62 return string;
63 }
64
65 int SIZE(RTLIL::Wire *wire)
66 {
67 return wire->width;
68 }
69
70 void yosys_setup()
71 {
72 Pass::init_register();
73
74 yosys_design = new RTLIL::Design;
75 yosys_design->selection_stack.push_back(RTLIL::Selection());
76 log_push();
77 }
78
79 void yosys_shutdown()
80 {
81 log_pop();
82
83 delete yosys_design;
84 yosys_design = NULL;
85
86 for (auto f : log_files)
87 if (f != stderr)
88 fclose(f);
89 log_errfile = NULL;
90 log_files.clear();
91
92 Pass::done_register();
93
94 #ifdef YOSYS_ENABLE_TCL
95 if (yosys_tcl_interp != NULL) {
96 Tcl_DeleteInterp(yosys_tcl_interp);
97 Tcl_Finalize();
98 yosys_tcl_interp = NULL;
99 }
100 #endif
101 }
102
103 RTLIL::IdString new_id(std::string file, int line, std::string func)
104 {
105 std::string str = "$auto$";
106 size_t pos = file.find_last_of('/');
107 str += pos != std::string::npos ? file.substr(pos+1) : file;
108 str += stringf(":%d:%s$%d", line, func.c_str(), autoidx++);
109 return str;
110 }
111
112 RTLIL::Design *yosys_get_design()
113 {
114 return yosys_design;
115 }
116
117 const char *create_prompt(RTLIL::Design *design, int recursion_counter)
118 {
119 static char buffer[100];
120 std::string str = "\n";
121 if (recursion_counter > 1)
122 str += stringf("(%d) ", recursion_counter);
123 str += "yosys";
124 if (!design->selected_active_module.empty())
125 str += stringf(" [%s]", RTLIL::unescape_id(design->selected_active_module).c_str());
126 if (!design->selection_stack.empty() && !design->selection_stack.back().full_selection) {
127 if (design->selected_active_module.empty())
128 str += "*";
129 else if (design->selection_stack.back().selected_modules.size() != 1 || design->selection_stack.back().selected_members.size() != 0 ||
130 design->selection_stack.back().selected_modules.count(design->selected_active_module) == 0)
131 str += "*";
132 }
133 snprintf(buffer, 100, "%s> ", str.c_str());
134 return buffer;
135 }
136
137 #ifdef YOSYS_ENABLE_TCL
138 static int tcl_yosys_cmd(ClientData, Tcl_Interp *interp, int argc, const char *argv[])
139 {
140 std::vector<std::string> args;
141 for (int i = 1; i < argc; i++)
142 args.push_back(argv[i]);
143
144 if (args.size() >= 1 && args[0] == "-import") {
145 for (auto &it : pass_register) {
146 std::string tcl_command_name = it.first;
147 if (tcl_command_name == "proc")
148 tcl_command_name = "procs";
149 Tcl_CmdInfo info;
150 if (Tcl_GetCommandInfo(interp, tcl_command_name.c_str(), &info) != 0) {
151 log("[TCL: yosys -import] Command name collision: found pre-existing command `%s' -> skip.\n", it.first.c_str());
152 } else {
153 std::string tcl_script = stringf("proc %s args { yosys %s {*}$args }", tcl_command_name.c_str(), it.first.c_str());
154 Tcl_Eval(interp, tcl_script.c_str());
155 }
156 }
157 return TCL_OK;
158 }
159
160 if (args.size() == 1) {
161 Pass::call(yosys_get_design(), args[0]);
162 return TCL_OK;
163 }
164
165 Pass::call(yosys_get_design(), args);
166 return TCL_OK;
167 }
168
169 extern Tcl_Interp *yosys_get_tcl_interp()
170 {
171 if (yosys_tcl_interp == NULL) {
172 yosys_tcl_interp = Tcl_CreateInterp();
173 Tcl_CreateCommand(yosys_tcl_interp, "yosys", tcl_yosys_cmd, NULL, NULL);
174 }
175 return yosys_tcl_interp;
176 }
177
178 struct TclPass : public Pass {
179 TclPass() : Pass("tcl", "execute a TCL script file") { }
180 virtual void help() {
181 log("\n");
182 log(" tcl <filename>\n");
183 log("\n");
184 log("This command executes the tcl commands in the specified file.\n");
185 log("Use 'yosys cmd' to run the yosys command 'cmd' from tcl.\n");
186 log("\n");
187 log("The tcl command 'yosys -import' can be used to import all yosys\n");
188 log("commands directly as tcl commands to the tcl shell. The yosys\n");
189 log("command 'proc' is wrapped using the tcl command 'procs' in order\n");
190 log("to avoid a name collision with the tcl builting command 'proc'.\n");
191 log("\n");
192 }
193 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
194 if (args.size() < 2)
195 log_cmd_error("Missing script file.\n");
196 if (args.size() > 2)
197 extra_args(args, 1, design, false);
198 if (Tcl_EvalFile(yosys_get_tcl_interp(), args[1].c_str()) != TCL_OK)
199 log_cmd_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(yosys_get_tcl_interp()));
200 }
201 } TclPass;
202 #endif
203
204 #if defined(__linux__)
205 std::string proc_self_dirname ()
206 {
207 char path [PATH_MAX];
208 ssize_t buflen = readlink("/proc/self/exe", path, sizeof(path));
209 if (buflen < 0) {
210 log_error("readlink(\"/proc/self/exe\") failed: %s\n", strerror(errno));
211 }
212 while (buflen > 0 && path[buflen-1] != '/')
213 buflen--;
214 return std::string(path, buflen);
215 }
216 #elif defined(__APPLE__)
217 #include <mach-o/dyld.h>
218 std::string proc_self_dirname ()
219 {
220 char * path = NULL;
221 uint32_t buflen = 0;
222 while (_NSGetExecutablePath(path, &buflen) != 0)
223 path = (char *) realloc((void *) path, buflen);
224 while (buflen > 0 && path[buflen-1] != '/')
225 buflen--;
226 return std::string(path, buflen);
227 }
228 #else
229 #error Dont know how to determine process executable base path!
230 #endif
231
232 std::string proc_share_dirname ()
233 {
234 std::string proc_self_path = proc_self_dirname();
235 std::string proc_share_path = proc_self_path + "share/";
236 if (access(proc_share_path.c_str(), X_OK) == 0)
237 return proc_share_path;
238 proc_share_path = proc_self_path + "../share/yosys/";
239 if (access(proc_share_path.c_str(), X_OK) == 0)
240 return proc_share_path;
241 log_error("proc_share_dirname: unable to determine share/ directory!\n");
242 }
243
244 bool fgetline(FILE *f, std::string &buffer)
245 {
246 buffer = "";
247 char block[4096];
248 while (1) {
249 if (fgets(block, 4096, f) == NULL)
250 return false;
251 buffer += block;
252 if (buffer.size() > 0 && (buffer[buffer.size()-1] == '\n' || buffer[buffer.size()-1] == '\r')) {
253 while (buffer.size() > 0 && (buffer[buffer.size()-1] == '\n' || buffer[buffer.size()-1] == '\r'))
254 buffer.resize(buffer.size()-1);
255 return true;
256 }
257 }
258 }
259
260 static void handle_label(std::string &command, bool &from_to_active, const std::string &run_from, const std::string &run_to)
261 {
262 int pos = 0;
263 std::string label;
264
265 while (pos < SIZE(command) && (command[pos] == ' ' || command[pos] == '\t'))
266 pos++;
267
268 while (pos < SIZE(command) && command[pos] != ' ' && command[pos] != '\t' && command[pos] != '\r' && command[pos] != '\n')
269 label += command[pos++];
270
271 if (label.back() == ':' && SIZE(label) > 1)
272 {
273 label = label.substr(0, SIZE(label)-1);
274 command = command.substr(pos);
275
276 if (label == run_from)
277 from_to_active = true;
278 else if (label == run_to || (run_from == run_to && !run_from.empty()))
279 from_to_active = false;
280 }
281 }
282
283 void run_frontend(std::string filename, std::string command, RTLIL::Design *design, std::string *backend_command, std::string *from_to_label)
284 {
285 if (command == "auto") {
286 if (filename.size() > 2 && filename.substr(filename.size()-2) == ".v")
287 command = "verilog";
288 else if (filename.size() > 2 && filename.substr(filename.size()-3) == ".sv")
289 command = "verilog -sv";
290 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".il")
291 command = "ilang";
292 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".ys")
293 command = "script";
294 else if (filename == "-")
295 command = "script";
296 else
297 log_error("Can't guess frontend for input file `%s' (missing -f option)!\n", filename.c_str());
298 }
299
300 if (command == "script")
301 {
302 std::string run_from, run_to;
303 bool from_to_active = true;
304
305 if (from_to_label != NULL) {
306 size_t pos = from_to_label->find(':');
307 if (pos == std::string::npos) {
308 run_from = *from_to_label;
309 run_to = *from_to_label;
310 } else {
311 run_from = from_to_label->substr(0, pos);
312 run_to = from_to_label->substr(pos+1);
313 }
314 from_to_active = run_from.empty();
315 }
316
317 log("\n-- Executing script file `%s' --\n", filename.c_str());
318
319 FILE *f = stdin;
320
321 if (filename != "-")
322 f = fopen(filename.c_str(), "r");
323
324 if (f == NULL)
325 log_error("Can't open script file `%s' for reading: %s\n", filename.c_str(), strerror(errno));
326
327 FILE *backup_script_file = Frontend::current_script_file;
328 Frontend::current_script_file = f;
329
330 try {
331 std::string command;
332 while (fgetline(f, command)) {
333 while (!command.empty() && command[command.size()-1] == '\\') {
334 std::string next_line;
335 if (!fgetline(f, next_line))
336 break;
337 command.resize(command.size()-1);
338 command += next_line;
339 }
340 handle_label(command, from_to_active, run_from, run_to);
341 if (from_to_active)
342 Pass::call(design, command);
343 }
344
345 if (!command.empty()) {
346 handle_label(command, from_to_active, run_from, run_to);
347 if (from_to_active)
348 Pass::call(design, command);
349 }
350 }
351 catch (log_cmd_error_expection) {
352 Frontend::current_script_file = backup_script_file;
353 throw log_cmd_error_expection();
354 }
355
356 Frontend::current_script_file = backup_script_file;
357
358 if (filename != "-")
359 fclose(f);
360
361 if (backend_command != NULL && *backend_command == "auto")
362 *backend_command = "";
363
364 return;
365 }
366
367 if (filename == "-") {
368 log("\n-- Parsing stdin using frontend `%s' --\n", command.c_str());
369 } else {
370 log("\n-- Parsing `%s' using frontend `%s' --\n", filename.c_str(), command.c_str());
371 }
372
373 Frontend::frontend_call(design, NULL, filename, command);
374 }
375
376 void run_pass(std::string command, RTLIL::Design *design)
377 {
378 log("\n-- Running pass `%s' --\n", command.c_str());
379
380 Pass::call(design, command);
381 }
382
383 void run_backend(std::string filename, std::string command, RTLIL::Design *design)
384 {
385 if (command == "auto") {
386 if (filename.size() > 2 && filename.substr(filename.size()-2) == ".v")
387 command = "verilog";
388 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".il")
389 command = "ilang";
390 else if (filename.size() > 5 && filename.substr(filename.size()-5) == ".blif")
391 command = "blif";
392 else if (filename == "-")
393 command = "ilang";
394 else if (filename.empty())
395 return;
396 else
397 log_error("Can't guess backend for output file `%s' (missing -b option)!\n", filename.c_str());
398 }
399
400 if (filename.empty())
401 filename = "-";
402
403 if (filename == "-") {
404 log("\n-- Writing to stdout using backend `%s' --\n", command.c_str());
405 } else {
406 log("\n-- Writing to `%s' using backend `%s' --\n", filename.c_str(), command.c_str());
407 }
408
409 Backend::backend_call(design, NULL, filename, command);
410 }
411
412 static char *readline_cmd_generator(const char *text, int state)
413 {
414 static std::map<std::string, Pass*>::iterator it;
415 static int len;
416
417 if (!state) {
418 it = pass_register.begin();
419 len = strlen(text);
420 }
421
422 for (; it != pass_register.end(); it++) {
423 if (it->first.substr(0, len) == text)
424 return strdup((it++)->first.c_str());
425 }
426 return NULL;
427 }
428
429 static char *readline_obj_generator(const char *text, int state)
430 {
431 static std::vector<char*> obj_names;
432 static size_t idx;
433
434 if (!state)
435 {
436 idx = 0;
437 obj_names.clear();
438
439 RTLIL::Design *design = yosys_get_design();
440 int len = strlen(text);
441
442 if (design->selected_active_module.empty())
443 {
444 for (auto &it : design->modules_)
445 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
446 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
447 }
448 else
449 if (design->modules_.count(design->selected_active_module) > 0)
450 {
451 RTLIL::Module *module = design->modules_.at(design->selected_active_module);
452
453 for (auto &it : module->wires_)
454 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
455 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
456
457 for (auto &it : module->memories)
458 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
459 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
460
461 for (auto &it : module->cells_)
462 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
463 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
464
465 for (auto &it : module->processes)
466 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
467 obj_names.push_back(strdup(RTLIL::id2cstr(it.first)));
468 }
469
470 std::sort(obj_names.begin(), obj_names.end());
471 }
472
473 if (idx < obj_names.size())
474 return strdup(obj_names[idx++]);
475
476 idx = 0;
477 obj_names.clear();
478 return NULL;
479 }
480
481 static char **readline_completion(const char *text, int start, int)
482 {
483 if (start == 0)
484 return rl_completion_matches(text, readline_cmd_generator);
485 if (strncmp(rl_line_buffer, "read_", 5) && strncmp(rl_line_buffer, "write_", 6))
486 return rl_completion_matches(text, readline_obj_generator);
487 return NULL;
488 }
489
490 void shell(RTLIL::Design *design)
491 {
492 static int recursion_counter = 0;
493
494 recursion_counter++;
495 log_cmd_error_throw = true;
496
497 rl_readline_name = "yosys";
498 rl_attempted_completion_function = readline_completion;
499 rl_basic_word_break_characters = " \t\n";
500
501 char *command = NULL;
502 while ((command = readline(create_prompt(design, recursion_counter))) != NULL)
503 {
504 if (command[strspn(command, " \t\r\n")] == 0)
505 continue;
506 add_history(command);
507
508 char *p = command + strspn(command, " \t\r\n");
509 if (!strncmp(p, "exit", 4)) {
510 p += 4;
511 p += strspn(p, " \t\r\n");
512 if (*p == 0)
513 break;
514 }
515
516 try {
517 log_assert(design->selection_stack.size() == 1);
518 Pass::call(design, command);
519 } catch (log_cmd_error_expection) {
520 while (design->selection_stack.size() > 1)
521 design->selection_stack.pop_back();
522 log_reset_stack();
523 }
524 }
525 if (command == NULL)
526 printf("exit\n");
527
528 recursion_counter--;
529 log_cmd_error_throw = false;
530 }
531
532 struct ShellPass : public Pass {
533 ShellPass() : Pass("shell", "enter interactive command mode") { }
534 virtual void help() {
535 log("\n");
536 log(" shell\n");
537 log("\n");
538 log("This command enters the interactive command mode. This can be useful\n");
539 log("in a script to interrupt the script at a certain point and allow for\n");
540 log("interactive inspection or manual synthesis of the design at this point.\n");
541 log("\n");
542 log("The command prompt of the interactive shell indicates the current\n");
543 log("selection (see 'help select'):\n");
544 log("\n");
545 log(" yosys>\n");
546 log(" the entire design is selected\n");
547 log("\n");
548 log(" yosys*>\n");
549 log(" only part of the design is selected\n");
550 log("\n");
551 log(" yosys [modname]>\n");
552 log(" the entire module 'modname' is selected using 'select -module modname'\n");
553 log("\n");
554 log(" yosys [modname]*>\n");
555 log(" only part of current module 'modname' is selected\n");
556 log("\n");
557 log("When in interactive shell, some errors (e.g. invalid command arguments)\n");
558 log("do not terminate yosys but return to the command prompt.\n");
559 log("\n");
560 log("This command is the default action if nothing else has been specified\n");
561 log("on the command line.\n");
562 log("\n");
563 log("Press Ctrl-D or type 'exit' to leave the interactive shell.\n");
564 log("\n");
565 }
566 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
567 extra_args(args, 1, design, false);
568 shell(design);
569 }
570 } ShellPass;
571
572 struct HistoryPass : public Pass {
573 HistoryPass() : Pass("history", "show last interactive commands") { }
574 virtual void help() {
575 log("\n");
576 log(" history\n");
577 log("\n");
578 log("This command prints all commands in the shell history buffer. This are\n");
579 log("all commands executed in an interactive session, but not the commands\n");
580 log("from executed scripts.\n");
581 log("\n");
582 }
583 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
584 extra_args(args, 1, design, false);
585 for(HIST_ENTRY **list = history_list(); *list != NULL; list++)
586 log("%s\n", (*list)->line);
587 }
588 } HistoryPass;
589
590 struct ScriptPass : public Pass {
591 ScriptPass() : Pass("script", "execute commands from script file") { }
592 virtual void help() {
593 log("\n");
594 log(" script <filename> [<from_label>:<to_label>]\n");
595 log("\n");
596 log("This command executes the yosys commands in the specified file.\n");
597 log("\n");
598 log("The 2nd argument can be used to only execute the section of the\n");
599 log("file between the specified labels. An empty from label is synonymous\n");
600 log("for the beginning of the file and an empty to label is synonymous\n");
601 log("for the end of the file.\n");
602 log("\n");
603 log("If only one label is specified (without ':') then only the block\n");
604 log("marked with that label (until the next label) is executed.\n");
605 log("\n");
606 }
607 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
608 if (args.size() < 2)
609 log_cmd_error("Missing script file.\n");
610 else if (args.size() == 2)
611 run_frontend(args[1], "script", design, NULL, NULL);
612 else if (args.size() == 3)
613 run_frontend(args[1], "script", design, NULL, &args[2]);
614 else
615 extra_args(args, 2, design, false);
616 }
617 } ScriptPass;
618
619 YOSYS_NAMESPACE_END
620