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