aboutsummaryrefslogtreecommitdiffstats
path: root/tools
diff options
context:
space:
mode:
Diffstat (limited to 'tools')
-rw-r--r--tools/firmware-utils/Makefile1
-rw-r--r--tools/firmware-utils/src/mkrtn56uimg.c294
2 files changed, 295 insertions, 0 deletions
diff --git a/tools/firmware-utils/Makefile b/tools/firmware-utils/Makefile
index 3be80e77ab..8f17c3e923 100644
--- a/tools/firmware-utils/Makefile
+++ b/tools/firmware-utils/Makefile
@@ -67,6 +67,7 @@ define Host/Compile
#$(call cc,mkhilinkfw, -lcrypto)
$(call cc,mkdcs932, -Wall)
$(call cc,mkheader_gemtek,-lz)
+ $(call cc,mkrtn56uimg, -lz)
endef
define Host/Install
diff --git a/tools/firmware-utils/src/mkrtn56uimg.c b/tools/firmware-utils/src/mkrtn56uimg.c
new file mode 100644
index 0000000000..973ab28d06
--- /dev/null
+++ b/tools/firmware-utils/src/mkrtn56uimg.c
@@ -0,0 +1,294 @@
+/*
+ *
+ * Copyright (C) 2014 OpenWrt.org
+ * Copyright (C) 2014 Mikko Hissa <mikko.hissa@werzek.com>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 as published
+ * by the Free Software Foundation.
+ *
+ */
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <netinet/in.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <time.h>
+#include <unistd.h>
+#include <zlib.h>
+
+#define IH_MAGIC 0x27051956
+#define IH_NMLEN 32
+#define IH_PRODLEN 23
+
+#define IH_TYPE_INVALID 0
+#define IH_TYPE_STANDALONE 1
+#define IH_TYPE_KERNEL 2
+#define IH_TYPE_RAMDISK 3
+#define IH_TYPE_MULTI 4
+#define IH_TYPE_FIRMWARE 5
+#define IH_TYPE_SCRIPT 6
+#define IH_TYPE_FILESYSTEM 7
+
+/*
+ * Compression Types
+ */
+#define IH_COMP_NONE 0
+#define IH_COMP_GZIP 1
+#define IH_COMP_BZIP2 2
+#define IH_COMP_LZMA 3
+
+typedef struct {
+ uint8_t major;
+ uint8_t minor;
+} version_t;
+
+typedef struct {
+ version_t kernel;
+ version_t fs;
+ uint8_t productid[IH_PRODLEN];
+ uint8_t sub_fs;
+ uint32_t ih_ksz;
+} asus_t;
+
+typedef struct image_header {
+ uint32_t ih_magic;
+ uint32_t ih_hcrc;
+ uint32_t ih_time;
+ uint32_t ih_size;
+ uint32_t ih_load;
+ uint32_t ih_ep;
+ uint32_t ih_dcrc;
+ uint8_t ih_os;
+ uint8_t ih_arch;
+ uint8_t ih_type;
+ uint8_t ih_comp;
+ union {
+ uint8_t ih_name[IH_NMLEN];
+ asus_t asus;
+ } tail;
+} image_header_t;
+
+typedef struct squashfs_sb {
+ uint32_t s_magic;
+ uint32_t pad0[9];
+ uint64_t bytes_used;
+} squashfs_sb_t;
+
+typedef enum {
+ NONE, FACTORY, SYSUPGRADE,
+} op_mode_t;
+
+void
+calc_crc(image_header_t *hdr, void *data, uint32_t len)
+{
+ /*
+ * Calculate payload checksum
+ */
+ hdr->ih_dcrc = htonl(crc32(0, data, len));
+ hdr->ih_size = htonl(len);
+ /*
+ * Calculate header checksum
+ */
+ hdr->ih_hcrc = 0;
+ hdr->ih_hcrc = htonl(crc32(0, hdr, sizeof(image_header_t)));
+}
+
+
+static void
+usage(const char *progname, int status)
+{
+ FILE *stream = (status != EXIT_SUCCESS) ? stderr : stdout;
+ int i;
+
+ fprintf(stream, "Usage: %s [OPTIONS...]\n", progname);
+ fprintf(stream, "\n"
+ "Options:\n"
+ " -f <file> generate a factory flash image <file>\n"
+ " -s <file> generate a sysupgrade flash image <file>\n"
+ " -h show this screen\n");
+ exit(status);
+}
+
+int
+process_image(char *progname, char *filename, op_mode_t opmode)
+{
+ int fd, len;
+ void *data, *ptr;
+ char namebuf[IH_NMLEN];
+ struct stat sbuf;
+ uint32_t checksum, offset_kernel, offset_sqfs, offset_end,
+ offset_sec_header, offset_eb, offset_image_end;
+ squashfs_sb_t *sqs;
+ image_header_t *hdr;
+
+ if ((fd = open(filename, O_RDWR, 0666)) < 0) {
+ fprintf (stderr, "%s: Can't open %s: %s\n",
+ progname, filename, strerror(errno));
+ return (EXIT_FAILURE);
+ }
+
+ if (fstat(fd, &sbuf) < 0) {
+ fprintf (stderr, "%s: Can't stat %s: %s\n",
+ progname, filename, strerror(errno));
+ return (EXIT_FAILURE);
+ }
+
+ if ((unsigned)sbuf.st_size < sizeof(image_header_t)) {
+ fprintf (stderr,
+ "%s: Bad size: \"%s\" is no valid image\n",
+ progname, filename);
+ return (EXIT_FAILURE);
+ }
+
+ ptr = (void *)mmap(0, sbuf.st_size,
+ PROT_READ | PROT_WRITE,
+ MAP_SHARED,
+ fd, 0);
+
+ if ((caddr_t)ptr == (caddr_t)-1) {
+ fprintf (stderr, "%s: Can't read %s: %s\n",
+ progname, filename, strerror(errno));
+ return (EXIT_FAILURE);
+ }
+
+ hdr = ptr;
+
+ if (ntohl(hdr->ih_magic) != IH_MAGIC) {
+ fprintf (stderr,
+ "%s: Bad Magic Number: \"%s\" is no valid image\n",
+ progname, filename);
+ return (EXIT_FAILURE);
+ }
+
+ if (opmode == FACTORY) {
+ strncpy(&namebuf, (char *)&hdr->tail.ih_name, IH_NMLEN);
+ hdr->tail.asus.kernel.major = 0;
+ hdr->tail.asus.kernel.minor = 0;
+ hdr->tail.asus.fs.major = 0;
+ hdr->tail.asus.fs.minor = 0;
+ strncpy((char *)&hdr->tail.asus.productid, "RT-N56U", IH_PRODLEN);
+ }
+
+ if (hdr->tail.asus.ih_ksz == 0)
+ hdr->tail.asus.ih_ksz = htonl(ntohl(hdr->ih_size) + sizeof(image_header_t));
+
+ offset_kernel = sizeof(image_header_t);
+ offset_sqfs = ntohl(hdr->tail.asus.ih_ksz);
+ sqs = ptr + offset_sqfs;
+ offset_sec_header = offset_sqfs + sqs->bytes_used;
+
+ /*
+ * Reserve space for the second header.
+ */
+ offset_end = offset_sec_header + sizeof(image_header_t);
+ offset_eb = ((offset_end>>16)+1)<<16;
+
+ if (opmode == FACTORY)
+ offset_image_end = offset_eb + 4;
+ else
+ offset_image_end = sbuf.st_size;
+ /*
+ * Move the second header at the end of the image.
+ */
+ offset_end = offset_sec_header;
+ offset_sec_header = offset_eb - sizeof(image_header_t);
+
+ /*
+ * Remove jffs2 markers between squashfs and eb boundary.
+ */
+ if (opmode == FACTORY)
+ memset(ptr+offset_end, 0xff ,offset_eb - offset_end);
+
+ /*
+ * Grow the image if needed.
+ */
+ if (offset_image_end > sbuf.st_size) {
+ (void) munmap((void *)ptr, sbuf.st_size);
+ ftruncate(fd, offset_image_end);
+ ptr = (void *)mmap(0, offset_image_end,
+ PROT_READ | PROT_WRITE,
+ MAP_SHARED,
+ fd, 0);
+ /*
+ * jffs2 marker
+ */
+ if (opmode == FACTORY) {
+ *(uint8_t *)(ptr+offset_image_end-4) = 0xde;
+ *(uint8_t *)(ptr+offset_image_end-3) = 0xad;
+ *(uint8_t *)(ptr+offset_image_end-2) = 0xc0;
+ *(uint8_t *)(ptr+offset_image_end-1) = 0xde;
+ }
+ }
+
+ /*
+ * Calculate checksums for the second header to be used after flashing.
+ */
+ if (opmode == FACTORY) {
+ hdr = ptr+offset_sec_header;
+ memcpy(hdr, ptr, sizeof(image_header_t));
+ strncpy((char *)&hdr->tail.ih_name, &namebuf, IH_NMLEN);
+ calc_crc(hdr, ptr+offset_kernel, offset_sqfs - offset_kernel);
+ calc_crc((image_header_t *)ptr, ptr+offset_kernel, offset_image_end - offset_kernel);
+ } else {
+ calc_crc((image_header_t *)ptr, ptr+offset_kernel, offset_sqfs - offset_kernel);
+ }
+
+ if (sbuf.st_size > offset_image_end)
+ (void) munmap((void *)ptr, sbuf.st_size);
+ else
+ (void) munmap((void *)ptr, offset_image_end);
+
+ ftruncate(fd, offset_image_end);
+ (void) close (fd);
+
+ return EXIT_SUCCESS;
+}
+
+int
+main(int argc, char **argv)
+{
+ int opt;
+ char *filename, *progname;
+ op_mode_t opmode = NONE;
+
+ progname = argv[0];
+
+ while ((opt = getopt(argc, argv,":s:f:h?")) != -1) {
+ switch (opt) {
+ case 's':
+ opmode = SYSUPGRADE;
+ filename = optarg;
+ break;
+ case 'f':
+ opmode = FACTORY;
+ filename = optarg;
+ break;
+ case 'h':
+ opmode = NONE;
+ default:
+ usage(progname, EXIT_FAILURE);
+ opmode = NONE;
+ }
+ }
+
+ if(filename == NULL)
+ opmode = NONE;
+
+ switch (opmode) {
+ case NONE:
+ usage(progname, EXIT_FAILURE);
+ break;
+ case FACTORY:
+ case SYSUPGRADE:
+ return process_image(progname, filename, opmode);
+ break;
+ }
+
+ return EXIT_SUCCESS;
+}
+
href='#n534'>534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *  
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

// [[CITE]] ABC
// Berkeley Logic Synthesis and Verification Group, ABC: A System for Sequential Synthesis and Verification
// http://www.eecs.berkeley.edu/~alanmi/abc/

// [[CITE]] Berkeley Logic Interchange Format (BLIF)
// University of California. Berkeley. July 28, 1992
// http://www.ece.cmu.edu/~ee760/760docs/blif.pdf

// [[CITE]] Kahn's Topological sorting algorithm
// Kahn, Arthur B. (1962), "Topological sorting of large networks", Communications of the ACM 5 (11): 558–562, doi:10.1145/368996.369025
// http://en.wikipedia.org/wiki/Topological_sorting

#define ABC_COMMAND_LIB "strash; scorr -v; ifraig -v; retime -v {D}; strash; dch -vf; map -v {D}"
#define ABC_COMMAND_CTR "strash; scorr -v; ifraig -v; retime -v {D}; strash; dch -vf; map -v {D}; buffer -v; upsize -v {D}; dnsize -v {D}; stime -p"
#define ABC_COMMAND_LUT "strash; scorr -v; ifraig -v; retime -v; strash; dch -vf; if -v"
#define ABC_COMMAND_DFL "strash; scorr -v; ifraig -v; retime -v; strash; dch -vf; map -v"

#define ABC_FAST_COMMAND_LIB "retime -v {D}; map -v {D}"
#define ABC_FAST_COMMAND_CTR "retime -v {D}; map -v {D}; buffer -v; upsize -v {D}; dnsize -v {D}; stime -p"
#define ABC_FAST_COMMAND_LUT "retime -v; if -v"
#define ABC_FAST_COMMAND_DFL "retime -v; map -v"

#include "kernel/register.h"
#include "kernel/sigtools.h"
#include "kernel/log.h"
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <cerrno>
#include <sstream>
#include <climits>

#include "blifparse.h"

enum class gate_type_t {
	G_NONE,
	G_FF,
	G_NOT,
	G_AND,
	G_NAND,
	G_OR,
	G_NOR,
	G_XOR,
	G_XNOR,
	G_MUX,
	G_AOI3,
	G_OAI3,
	G_AOI4,
	G_OAI4
};

#define G(_name) gate_type_t::G_ ## _name

struct gate_t
{
	int id;
	gate_type_t type;
	int in1, in2, in3, in4;
	bool is_port;
	RTLIL::SigBit bit;
};

static int map_autoidx;
static SigMap assign_map;
static RTLIL::Module *module;
static std::vector<gate_t> signal_list;
static std::map<RTLIL::SigBit, int> signal_map;

static bool clk_polarity;
static RTLIL::SigSpec clk_sig;

static int map_signal(RTLIL::SigBit bit, gate_type_t gate_type = G(NONE), int in1 = -1, int in2 = -1, int in3 = -1, int in4 = -1)
{
	assign_map.apply(bit);

	if (signal_map.count(bit) == 0) {
		gate_t gate;
		gate.id = signal_list.size();
		gate.type = G(NONE);
		gate.in1 = -1;
		gate.in2 = -1;
		gate.in3 = -1;
		gate.in4 = -1;
		gate.is_port = false;
		gate.bit = bit;
		signal_list.push_back(gate);
		signal_map[bit] = gate.id;
	}

	gate_t &gate = signal_list[signal_map[bit]];

	if (gate_type != G(NONE))
		gate.type = gate_type;
	if (in1 >= 0)
		gate.in1 = in1;
	if (in2 >= 0)
		gate.in2 = in2;
	if (in3 >= 0)
		gate.in3 = in3;
	if (in4 >= 0)
		gate.in4 = in4;

	return gate.id;
}

static void mark_port(RTLIL::SigSpec sig)
{
	for (auto &bit : assign_map(sig))
		if (bit.wire != NULL && signal_map.count(bit) > 0)
			signal_list[signal_map[bit]].is_port = true;
}

static void extract_cell(RTLIL::Cell *cell, bool keepff)
{
	if (cell->type == "$_DFF_N_" || cell->type == "$_DFF_P_")
	{
		if (clk_polarity != (cell->type == "$_DFF_P_"))
			return;
		if (clk_sig != assign_map(cell->getPort("\\C")))
			return;

		RTLIL::SigSpec sig_d = cell->getPort("\\D");
		RTLIL::SigSpec sig_q = cell->getPort("\\Q");

		if (keepff)
			for (auto &c : sig_q.chunks())
				if (c.wire != NULL)
					c.wire->attributes["\\keep"] = 1;

		assign_map.apply(sig_d);
		assign_map.apply(sig_q);

		map_signal(sig_q, G(FF), map_signal(sig_d));

		module->remove(cell);
		return;
	}

	if (cell->type == "$_NOT_")
	{
		RTLIL::SigSpec sig_a = cell->getPort("\\A");
		RTLIL::SigSpec sig_y = cell->getPort("\\Y");

		assign_map.apply(sig_a);
		assign_map.apply(sig_y);

		map_signal(sig_y, G(NOT), map_signal(sig_a));

		module->remove(cell);
		return;
	}

	if (cell->type.in("$_AND_", "$_NAND_", "$_OR_", "$_NOR_", "$_XOR_", "$_XNOR_"))
	{
		RTLIL::SigSpec sig_a = cell->getPort("\\A");
		RTLIL::SigSpec sig_b = cell->getPort("\\B");
		RTLIL::SigSpec sig_y = cell->getPort("\\Y");

		assign_map.apply(sig_a);
		assign_map.apply(sig_b);
		assign_map.apply(sig_y);

		int mapped_a = map_signal(sig_a);
		int mapped_b = map_signal(sig_b);

		if (cell->type == "$_AND_")
			map_signal(sig_y, G(AND), mapped_a, mapped_b);
		else if (cell->type == "$_NAND_")
			map_signal(sig_y, G(NAND), mapped_a, mapped_b);
		else if (cell->type == "$_OR_")
			map_signal(sig_y, G(OR), mapped_a, mapped_b);
		else if (cell->type == "$_NOR_")
			map_signal(sig_y, G(NOR), mapped_a, mapped_b);
		else if (cell->type == "$_XOR_")
			map_signal(sig_y, G(XOR), mapped_a, mapped_b);
		else if (cell->type == "$_XNOR_")
			map_signal(sig_y, G(XNOR), mapped_a, mapped_b);
		else
			log_abort();

		module->remove(cell);
		return;
	}

	if (cell->type == "$_MUX_")
	{
		RTLIL::SigSpec sig_a = cell->getPort("\\A");
		RTLIL::SigSpec sig_b = cell->getPort("\\B");
		RTLIL::SigSpec sig_s = cell->getPort("\\S");
		RTLIL::SigSpec sig_y = cell->getPort("\\Y");

		assign_map.apply(sig_a);
		assign_map.apply(sig_b);
		assign_map.apply(sig_s);
		assign_map.apply(sig_y);

		int mapped_a = map_signal(sig_a);
		int mapped_b = map_signal(sig_b);
		int mapped_s = map_signal(sig_s);

		map_signal(sig_y, G(MUX), mapped_a, mapped_b, mapped_s);

		module->remove(cell);
		return;
	}

	if (cell->type.in("$_AOI3_", "$_OAI3_"))
	{
		RTLIL::SigSpec sig_a = cell->getPort("\\A");
		RTLIL::SigSpec sig_b = cell->getPort("\\B");
		RTLIL::SigSpec sig_c = cell->getPort("\\C");
		RTLIL::SigSpec sig_y = cell->getPort("\\Y");

		assign_map.apply(sig_a);
		assign_map.apply(sig_b);
		assign_map.apply(sig_c);
		assign_map.apply(sig_y);

		int mapped_a = map_signal(sig_a);
		int mapped_b = map_signal(sig_b);
		int mapped_c = map_signal(sig_c);

		map_signal(sig_y, cell->type == "$_AOI3_" ? G(AOI3) : G(OAI3), mapped_a, mapped_b, mapped_c);

		module->remove(cell);
		return;
	}

	if (cell->type.in("$_AOI4_", "$_OAI4_"))
	{
		RTLIL::SigSpec sig_a = cell->getPort("\\A");
		RTLIL::SigSpec sig_b = cell->getPort("\\B");
		RTLIL::SigSpec sig_c = cell->getPort("\\C");
		RTLIL::SigSpec sig_d = cell->getPort("\\D");
		RTLIL::SigSpec sig_y = cell->getPort("\\Y");

		assign_map.apply(sig_a);
		assign_map.apply(sig_b);
		assign_map.apply(sig_c);
		assign_map.apply(sig_d);
		assign_map.apply(sig_y);

		int mapped_a = map_signal(sig_a);
		int mapped_b = map_signal(sig_b);
		int mapped_c = map_signal(sig_c);
		int mapped_d = map_signal(sig_d);

		map_signal(sig_y, cell->type == "$_AOI4_" ? G(AOI4) : G(OAI4), mapped_a, mapped_b, mapped_c, mapped_d);

		module->remove(cell);
		return;
	}
}

static std::string remap_name(RTLIL::IdString abc_name)
{
	std::stringstream sstr;
	sstr << "$abc$" << map_autoidx << "$" << abc_name.substr(1);
	return sstr.str();
}

static void dump_loop_graph(FILE *f, int &nr, std::map<int, std::set<int>> &edges, std::set<int> &workpool, std::vector<int> &in_counts)
{
	if (f == NULL)
		return;

	log("Dumping loop state graph to slide %d.\n", ++nr);

	fprintf(f, "digraph \"slide%d\" {\n", nr);
	fprintf(f, "  label=\"slide%d\";\n", nr);
	fprintf(f, "  rankdir=\"TD\";\n");

	std::set<int> nodes;
	for (auto &e : edges) {
		nodes.insert(e.first);
		for (auto n : e.second)
			nodes.insert(n);
	}

	for (auto n : nodes)
		fprintf(f, "  n%d [label=\"%s\\nid=%d, count=%d\"%s];\n", n, log_signal(signal_list[n].bit),
				n, in_counts[n], workpool.count(n) ? ", shape=box" : "");

	for (auto &e : edges)
	for (auto n : e.second)
		fprintf(f, "  n%d -> n%d;\n", e.first, n);

	fprintf(f, "}\n");
}

static void handle_loops()
{
	// http://en.wikipedia.org/wiki/Topological_sorting
	// (Kahn, Arthur B. (1962), "Topological sorting of large networks")

	std::map<int, std::set<int>> edges;
	std::vector<int> in_edges_count(signal_list.size());
	std::set<int> workpool;

	FILE *dot_f = NULL;
	int dot_nr = 0;

	// uncomment for troubleshooting the loop detection code
	// dot_f = fopen("test.dot", "w");

	for (auto &g : signal_list) {
		if (g.type == G(NONE) || g.type == G(FF)) {
			workpool.insert(g.id);
		} else {
			if (g.in1 >= 0) {
				edges[g.in1].insert(g.id);
				in_edges_count[g.id]++;
			}
			if (g.in2 >= 0 && g.in2 != g.in1) {
				edges[g.in2].insert(g.id);
				in_edges_count[g.id]++;
			}
			if (g.in3 >= 0 && g.in3 != g.in2 && g.in3 != g.in1) {
				edges[g.in3].insert(g.id);
				in_edges_count[g.id]++;
			}
			if (g.in4 >= 0 && g.in4 != g.in3 && g.in4 != g.in2 && g.in4 != g.in1) {
				edges[g.in4].insert(g.id);
				in_edges_count[g.id]++;
			}
		}
	}

	dump_loop_graph(dot_f, dot_nr, edges, workpool, in_edges_count);

	while (workpool.size() > 0)
	{
		int id = *workpool.begin();
		workpool.erase(id);

		// log("Removing non-loop node %d from graph: %s\n", id, log_signal(signal_list[id].bit));

		for (int id2 : edges[id]) {
			log_assert(in_edges_count[id2] > 0);
			if (--in_edges_count[id2] == 0)
				workpool.insert(id2);
		}
		edges.erase(id);

		dump_loop_graph(dot_f, dot_nr, edges, workpool, in_edges_count);

		while (workpool.size() == 0)
		{
			if (edges.size() == 0)
				break;

			int id1 = edges.begin()->first;

			for (auto &edge_it : edges) {
				int id2 = edge_it.first;
				RTLIL::Wire *w1 = signal_list[id1].bit.wire;
				RTLIL::Wire *w2 = signal_list[id2].bit.wire;
				if (w1 == NULL)
					id1 = id2;
				else if (w2 == NULL)
					continue;
				else if (w1->name[0] == '$' && w2->name[0] == '\\')
					id1 = id2;
				else if (w1->name[0] == '\\' && w2->name[0] == '$')
					continue;
				else if (edges[id1].size() < edges[id2].size())
					id1 = id2;
				else if (edges[id1].size() > edges[id2].size())
					continue;
				else if (w2->name.str() < w1->name.str())
					id1 = id2;
			}

			if (edges[id1].size() == 0) {
				edges.erase(id1);
				continue;
			}

			log_assert(signal_list[id1].bit.wire != NULL);

			std::stringstream sstr;
			sstr << "$abcloop$" << (autoidx++);
			RTLIL::Wire *wire = module->addWire(sstr.str());

			bool first_line = true;
			for (int id2 : edges[id1]) {
				if (first_line)
					log("Breaking loop using new signal %s: %s -> %s\n", log_signal(RTLIL::SigSpec(wire)),
							log_signal(signal_list[id1].bit), log_signal(signal_list[id2].bit));
				else
					log("                               %*s  %s -> %s\n", int(strlen(log_signal(RTLIL::SigSpec(wire)))), "",
							log_signal(signal_list[id1].bit), log_signal(signal_list[id2].bit));
				first_line = false;
			}

			int id3 = map_signal(RTLIL::SigSpec(wire));
			signal_list[id1].is_port = true;
			signal_list[id3].is_port = true;
			log_assert(id3 == int(in_edges_count.size()));
			in_edges_count.push_back(0);
			workpool.insert(id3);

			for (int id2 : edges[id1]) {
				if (signal_list[id2].in1 == id1)
					signal_list[id2].in1 = id3;
				if (signal_list[id2].in2 == id1)
					signal_list[id2].in2 = id3;
				if (signal_list[id2].in3 == id1)
					signal_list[id2].in3 = id3;
				if (signal_list[id2].in4 == id1)
					signal_list[id2].in4 = id3;
			}
			edges[id1].swap(edges[id3]);

			module->connect(RTLIL::SigSig(signal_list[id3].bit, signal_list[id1].bit));
			dump_loop_graph(dot_f, dot_nr, edges, workpool, in_edges_count);
		}
	}

	if (dot_f != NULL)
		fclose(dot_f);
}

static std::string add_echos_to_abc_cmd(std::string str)
{
	std::string new_str, token;
	for (size_t i = 0; i < str.size(); i++) {
		token += str[i];
		if (str[i] == ';') {
			while (i+1 < str.size() && str[i+1] == ' ')
				i++;
			if (!new_str.empty())
				new_str += "echo; ";
			new_str += "echo + " + token + " " + token + " ";
			token.clear();
		}
	}

	if (!token.empty()) {
		if (!new_str.empty())
			new_str += "echo; echo + " + token + "; ";
		new_str += token;
	}

	return new_str;
}

static std::string fold_abc_cmd(std::string str)
{
	std::string token, new_str = "          ";
	int char_counter = 10;

	for (size_t i = 0; i <= str.size(); i++) {
		if (i < str.size())
			token += str[i];
		if (i == str.size() || str[i] == ';') {
			if (char_counter + token.size() > 75)
				new_str += "\n              ", char_counter = 14;
			new_str += token, char_counter += token.size();
			token.clear();
		}
	}

	return new_str;
}

static void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::string script_file, std::string exe_file,
		std::string liberty_file, std::string constr_file, bool cleanup, int lut_mode, bool dff_mode, std::string clk_str,
		bool keepff, std::string delay_target, bool fast_mode)
{
	module = current_module;
	map_autoidx = autoidx++;

	signal_map.clear();
	signal_list.clear();
	assign_map.set(module);

	clk_polarity = true;
	clk_sig = RTLIL::SigSpec();

	char tempdir_name[] = "/tmp/yosys-abc-XXXXXX";
	if (!cleanup)
		tempdir_name[0] = tempdir_name[4] = '_';
	char *p = mkdtemp(tempdir_name);
	log_header("Extracting gate netlist of module `%s' to `%s/input.blif'..\n", module->name.c_str(), tempdir_name);
	if (p == NULL)
		log_error("For some reason mkdtemp() failed!\n");

	std::string abc_command;
	if (!script_file.empty()) {
		if (script_file[0] == '+') {
			for (size_t i = 1; i < script_file.size(); i++)
				if (script_file[i] == '\'')
					abc_command += "'\\''";
				else if (script_file[i] == ',')
					abc_command += " ";
				else
					abc_command += script_file[i];
		} else
			abc_command = stringf("source %s", script_file.c_str());
	} else if (lut_mode)
		abc_command = fast_mode ? ABC_FAST_COMMAND_LUT : ABC_COMMAND_LUT;
	else if (!liberty_file.empty())
		abc_command = constr_file.empty() ? (fast_mode ? ABC_FAST_COMMAND_LIB : ABC_COMMAND_LIB) : (fast_mode ? ABC_FAST_COMMAND_CTR : ABC_COMMAND_CTR);
	else
		abc_command = fast_mode ? ABC_FAST_COMMAND_DFL : ABC_COMMAND_DFL;

	for (size_t pos = abc_command.find("{D}"); pos != std::string::npos; pos = abc_command.find("{D}", pos))
		abc_command = abc_command.substr(0, pos) + delay_target + abc_command.substr(pos+3);

	abc_command = add_echos_to_abc_cmd(abc_command);

	if (abc_command.size() > 128) {
		for (size_t i = 0; i+1 < abc_command.size(); i++)
			if (abc_command[i] == ';' && abc_command[i+1] == ' ')
				abc_command[i+1] = '\n';
		FILE *f = fopen(stringf("%s/abc.script", tempdir_name).c_str(), "wt");
		fprintf(f, "%s\n", abc_command.c_str());
		fclose(f);
		abc_command = stringf("source %s/abc.script", tempdir_name);
	}

	if (clk_str.empty()) {
		if (clk_str[0] == '!') {
			clk_polarity = false;
			clk_str = clk_str.substr(1);
		}
		if (module->wires_.count(RTLIL::escape_id(clk_str)) != 0)
			clk_sig = assign_map(RTLIL::SigSpec(module->wires_.at(RTLIL::escape_id(clk_str)), 0));
	}

	if (dff_mode && clk_sig.size() == 0)
	{
		int best_dff_counter = 0;
		std::map<std::pair<bool, RTLIL::SigSpec>, int> dff_counters;

		for (auto &it : module->cells_)
		{
			RTLIL::Cell *cell = it.second;
			if (cell->type != "$_DFF_N_" && cell->type != "$_DFF_P_")
				continue;

			std::pair<bool, RTLIL::SigSpec> key(cell->type == "$_DFF_P_", assign_map(cell->getPort("\\C")));
			if (++dff_counters[key] > best_dff_counter) {
				best_dff_counter = dff_counters[key];
				clk_polarity = key.first;
				clk_sig = key.second;
			}
		}
	}

	if (dff_mode || !clk_str.empty()) {
		if (clk_sig.size() == 0)
			log("No (matching) clock domain found. Not extracting any FF cells.\n");
		else
			log("Found (matching) %s clock domain: %s\n", clk_polarity ? "posedge" : "negedge", log_signal(clk_sig));
	}

	if (clk_sig.size() != 0)
		mark_port(clk_sig);

	std::vector<RTLIL::Cell*> cells;
	cells.reserve(module->cells_.size());
	for (auto &it : module->cells_)
		if (design->selected(current_module, it.second))
			cells.push_back(it.second);
	for (auto c : cells)
		extract_cell(c, keepff);

	for (auto &wire_it : module->wires_) {
		if (wire_it.second->port_id > 0 || wire_it.second->get_bool_attribute("\\keep"))
			mark_port(RTLIL::SigSpec(wire_it.second));
	}

	for (auto &cell_it : module->cells_)
	for (auto &port_it : cell_it.second->connections())
		mark_port(port_it.second);
	
	handle_loops();

	if (asprintf(&p, "%s/input.blif", tempdir_name) < 0) log_abort();
	FILE *f = fopen(p, "wt");
	if (f == NULL)
		log_error("Opening %s for writing failed: %s\n", p, strerror(errno));
	free(p);

	fprintf(f, ".model netlist\n");

	int count_input = 0;
	fprintf(f, ".inputs");
	for (auto &si : signal_list) {
		if (!si.is_port || si.type != G(NONE))
			continue;
		fprintf(f, " n%d", si.id);
		count_input++;
	}
	if (count_input == 0)
		fprintf(f, " dummy_input\n");
	fprintf(f, "\n");

	int count_output = 0;
	fprintf(f, ".outputs");
	for (auto &si : signal_list) {
		if (!si.is_port || si.type == G(NONE))
			continue;
		fprintf(f, " n%d", si.id);
		count_output++;
	}
	fprintf(f, "\n");

	for (auto &si : signal_list)
		fprintf(f, "# n%-5d %s\n", si.id, log_signal(si.bit));

	for (auto &si : signal_list) {
		if (si.bit.wire == NULL) {
			fprintf(f, ".names n%d\n", si.id);
			if (si.bit == RTLIL::State::S1)
				fprintf(f, "1\n");
		}
	}

	int count_gates = 0;
	for (auto &si : signal_list) {
		if (si.type == G(NOT)) {
			fprintf(f, ".names n%d n%d\n", si.in1, si.id);
			fprintf(f, "0 1\n");
		} else if (si.type == G(AND)) {
			fprintf(f, ".names n%d n%d n%d\n", si.in1, si.in2, si.id);
			fprintf(f, "11 1\n");
		} else if (si.type == G(NAND)) {
			fprintf(f, ".names n%d n%d n%d\n", si.in1, si.in2, si.id);
			fprintf(f, "0- 1\n");
			fprintf(f, "-0 1\n");
		} else if (si.type == G(OR)) {
			fprintf(f, ".names n%d n%d n%d\n", si.in1, si.in2, si.id);
			fprintf(f, "-1 1\n");
			fprintf(f, "1- 1\n");
		} else if (si.type == G(NOR)) {
			fprintf(f, ".names n%d n%d n%d\n", si.in1, si.in2, si.id);
			fprintf(f, "00 1\n");
		} else if (si.type == G(XOR)) {
			fprintf(f, ".names n%d n%d n%d\n", si.in1, si.in2, si.id);
			fprintf(f, "01 1\n");
			fprintf(f, "10 1\n");
		} else if (si.type == G(XNOR)) {
			fprintf(f, ".names n%d n%d n%d\n", si.in1, si.in2, si.id);
			fprintf(f, "00 1\n");
			fprintf(f, "11 1\n");
		} else if (si.type == G(MUX)) {
			fprintf(f, ".names n%d n%d n%d n%d\n", si.in1, si.in2, si.in3, si.id);
			fprintf(f, "1-0 1\n");
			fprintf(f, "-11 1\n");
		} else if (si.type == G(AOI3)) {
			fprintf(f, ".names n%d n%d n%d n%d\n", si.in1, si.in2, si.in3, si.id);
			fprintf(f, "-00 1\n");
			fprintf(f, "0-0 1\n");
		} else if (si.type == G(OAI3)) {
			fprintf(f, ".names n%d n%d n%d n%d\n", si.in1, si.in2, si.in3, si.id);
			fprintf(f, "00- 1\n");
			fprintf(f, "--0 1\n");
		} else if (si.type == G(AOI4)) {
			fprintf(f, ".names n%d n%d n%d n%d n%d\n", si.in1, si.in2, si.in3, si.in4, si.id);
			fprintf(f, "-0-0 1\n");
			fprintf(f, "-00- 1\n");
			fprintf(f, "0--0 1\n");
			fprintf(f, "0-0- 1\n");
		} else if (si.type == G(OAI4)) {
			fprintf(f, ".names n%d n%d n%d n%d n%d\n", si.in1, si.in2, si.in3, si.in4, si.id);
			fprintf(f, "00-- 1\n");
			fprintf(f, "--00 1\n");
		} else if (si.type == G(FF)) {
			fprintf(f, ".latch n%d n%d\n", si.in1, si.id);
		} else if (si.type != G(NONE))
			log_abort();
		if (si.type != G(NONE))
			count_gates++;
	}

	fprintf(f, ".end\n");
	fclose(f);

	log("Extracted %d gates and %zd wires to a netlist network with %d inputs and %d outputs.\n",
			count_gates, signal_list.size(), count_input, count_output);
	log_push();
	
	if (count_output > 0)
	{
		log_header("Executing ABC.\n");

		if (asprintf(&p, "%s/stdcells.genlib", tempdir_name) < 0) log_abort();
		f = fopen(p, "wt");
		if (f == NULL)
			log_error("Opening %s for writing failed: %s\n", p, strerror(errno));
		fprintf(f, "GATE ZERO 1 Y=CONST0;\n");
		fprintf(f, "GATE ONE  1 Y=CONST1;\n");
		fprintf(f, "GATE BUF  1 Y=A;                  PIN * NONINV  1 999 1 0 1 0\n");
		fprintf(f, "GATE NOT  1 Y=!A;                 PIN * INV     1 999 1 0 1 0\n");
		fprintf(f, "GATE AND  1 Y=A*B;                PIN * NONINV  1 999 1 0 1 0\n");
		fprintf(f, "GATE NAND 1 Y=!(A*B);             PIN * INV     1 999 1 0 1 0\n");
		fprintf(f, "GATE OR   1 Y=A+B;                PIN * NONINV  1 999 1 0 1 0\n");
		fprintf(f, "GATE NOR  1 Y=!(A+B);             PIN * INV     1 999 1 0 1 0\n");
		fprintf(f, "GATE XOR  1 Y=(A*!B)+(!A*B);      PIN * UNKNOWN 1 999 1 0 1 0\n");
		fprintf(f, "GATE XNOR 1 Y=(A*B)+(!A*!B);      PIN * UNKNOWN 1 999 1 0 1 0\n");
		fprintf(f, "GATE MUX  1 Y=(A*B)+(S*B)+(!S*A); PIN * UNKNOWN 1 999 1 0 1 0\n");
		fprintf(f, "GATE AOI3 1 Y=!((A*B)+C);         PIN * INV     1 999 1 0 1 0\n");
		fprintf(f, "GATE OAI3 1 Y=!((A+B)*C);         PIN * INV     1 999 1 0 1 0\n");
		fprintf(f, "GATE AOI4 1 Y=!((A*B)+(C*D));     PIN * INV     1 999 1 0 1 0\n");
		fprintf(f, "GATE OAI4 1 Y=!((A+B)*(C+D));     PIN * INV     1 999 1 0 1 0\n");
		fclose(f);
		free(p);

		if (lut_mode) {
			if (asprintf(&p, "%s/lutdefs.txt", tempdir_name) < 0) log_abort();
			f = fopen(p, "wt");
			if (f == NULL)
				log_error("Opening %s for writing failed: %s\n", p, strerror(errno));
			for (int i = 0; i < lut_mode; i++)
				fprintf(f, "%d 1.00 1.00\n", i+1);
			fclose(f);
			free(p);
		}

		std::string buffer;
		if (!liberty_file.empty()) {
			buffer += stringf("%s -s -c 'read_blif %s/input.blif; read_lib -w %s; ",
					exe_file.c_str(), tempdir_name, liberty_file.c_str());
			if (!constr_file.empty())
				buffer += stringf("read_constr -v %s; ", constr_file.c_str());
			buffer += abc_command + "; ";
		} else
		if (lut_mode)
			buffer += stringf("%s -s -c 'read_blif %s/input.blif; read_lut %s/lutdefs.txt; %s; ",
					exe_file.c_str(), tempdir_name, tempdir_name, abc_command.c_str());
		else
			buffer += stringf("%s -s -c 'read_blif %s/input.blif; read_library %s/stdcells.genlib; %s; ",
					exe_file.c_str(), tempdir_name, tempdir_name, abc_command.c_str());
		buffer += stringf("write_blif %s/output.blif' 2>&1", tempdir_name);

		log("%s\n", buffer.c_str());

		errno = ENOMEM;  // popen does not set errno if memory allocation fails, therefore set it by hand
		f = popen(buffer.c_str(), "r");
		if (f == NULL)
			log_error("Opening pipe to `%s' for reading failed: %s\n", buffer.c_str(), strerror(errno));
#if 0
		char logbuf[1024];
		while (fgets(logbuf, 1024, f) != NULL)
			log("ABC: %s", logbuf);
#else
		bool got_cr = false;
		int escape_seq_state = 0;
		std::string linebuf;
		char logbuf[1024];
		while (fgets(logbuf, 1024, f) != NULL)
			for (char *p = logbuf; *p; p++) {
				if (escape_seq_state == 0 && *p == '\033') {
					escape_seq_state = 1;
					continue;
				}
				if (escape_seq_state == 1) {
					escape_seq_state = *p == '[' ? 2 : 0;
					continue;
				}
				if (escape_seq_state == 2) {
					if ((*p < '0' || '9' < *p) && *p != ';')
						escape_seq_state = 0;
					continue;
				}
				escape_seq_state = 0;
				if (*p == '\r') {
					got_cr = true;
					continue;
				}
				if (*p == '\n') {
					log("ABC: %s\n", linebuf.c_str());
					got_cr = false, linebuf.clear();
					continue;
				}
				if (got_cr)
					got_cr = false, linebuf.clear();
				linebuf += *p;