/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf * * 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. * */ #include "kernel/rtlil.h" #include "kernel/register.h" #include "kernel/sigtools.h" #include "kernel/celltypes.h" #include "kernel/cellaigs.h" #include "kernel/log.h" #include USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct JsonWriter { std::ostream &f; bool use_selection; bool aig_mode; Design *design; Module *module; SigMap sigmap; int sigidcounter; dict sigids; pool aig_models; JsonWriter(std::ostream &f, bool use_selection, bool aig_mode) : f(f), use_selection(use_selection), aig_mode(aig_mode) { } string get_string(string str) { string newstr = "\""; for (char c : str) { if (c == '\\') newstr += c; newstr += c; } return newstr + "\""; } string get_name(IdString name) { return get_string(RTLIL::unescape_id(name)); } string get_bits(SigSpec sig) { bool first = true; string str = "["; for (auto bit : sigmap(sig)) { str += first ? " " : ", "; first = false; if (sigids.count(bit) == 0) { string &s = sigids[bit]; if (bit.wire == nullptr) { if (bit == State::S0) s = "\"0\""; else if (bit == State::S1) s = "\"1\""; else if (bit == State::Sz) s = "\"z\""; else s = "\"x\""; } else s = stringf("%d", sigidcounter++); } str += sigids[bit]; } return str + " ]"; } void write_parameters(const dict ¶meters, bool for_module=false) { bool first = true; for (auto ¶m : parameters) { f << stringf("%s\n", first ? "" : ","); f << stringf(" %s%s: ", for_module ? "" : " ", get_name(param.first).c_str()); if ((param.second.flags & RTLIL::ConstFlags::CONST_FLAG_STRING) != 0) f << get_string(param.second.decode_string()); else if (GetSize(param.second.bits) > 32) f << get_string(param.second.as_string()); else f << stringf("%d", param.second.as_int()); first = false; } } void write_module(Module *module_) { module = module_; log_assert(module->design == design); sigmap.set(module); sigids.clear(); // reserve 0 and 1 to avoid confusion with "0" and "1" sigidcounter = 2; f << stringf(" %s: {\n", get_name(module->name).c_str()); f << stringf(" \"attributes\": {"); write_parameters(module->attributes, /*for_module=*/true); f << stringf("\n },\n"); f << stringf(" \"ports\": {"); bool first = true; for (auto n : module->ports) { Wire *w = module->wire(n); if (use_selection && !module->selected(w)) continue; f << stringf("%s\n", first ? "" : ","); f << stringf(" %s: {\n", get_name(n).c_str()); f << stringf(" \"direction\": \"%s\",\n", w->port_input ? w->port_output ? "inout" : "input" : "output"); f << stringf(" \"bits\": %s\n", get_bits(w).c_str()); f << stringf(" }"); first = false; } f << stringf("\n },\n"); f << stringf(" \"cells\": {"); first = true; for (auto c : module->cells()) { if (use_selection && !module->selected(c)) continue; f << stringf("%s\n", first ? "" : ","); f << stringf(" %s: {\n", get_name(c->name).c_str()); f << stringf(" \"hide_name\": %s,\n", c->name[0] == '$' ? "1" : "0"); f << stringf(" \"type\": %s,\n", get_name(c->type).c_str()); if (aig_mode) { Aig aig(c); if (!aig.name.empty()) { f << stringf(" \"model\": \"%s\",\n", aig.name.c_str()); aig_models.insert(aig); } } f << stringf(" \"parameters\": {"); write_parameters(c->parameters); f << stringf("\n },\n"); f << stringf(" \"attributes\": {"); write_parameters(c->attributes); f << stringf("\n },\n"); if (c->known()) { f << stringf(" \"port_directions\": {"); bool first2 = true; for (auto &conn : c->connections()) { string direction = "output"; if (c->input(conn.first)) direction = c->output(conn.first) ? "inout" : "input"; f << stringf("%s\n", first2 ? "" : ","); f << stringf(" %s: \"%s\"", get_name(conn.first).c_str(), direction.c_str()); first2 = false; } f << stringf("\n },\n"); } f << stringf(" \"connections\": {"); bool first2 = true; for (auto &conn : c->connections()) { f << stringf("%s\n", first2 ? "" : ","); f << stringf(" %s: %s", get_name(conn.first).c_str(), get_bits(conn.second).c_str()); first2 = false; } f << stringf("\n }\n"); f << stringf(" }"); first = false; } f << stringf("\n },\n"); f << stringf(" \"netnames\": {"); first = true; for (auto w : module->wires()) { if (use_selection && !module->selected(w)) continue; f << stringf("%s\n", first ? "" : ","); f << stringf(" %s: {\n", get_name(w->name).c_str()); f << stringf(" \"hide_name\": %s,\n", w->name[0] == '$' ? "1" : "0"); f << stringf(" \"bits\": %s,\n", get_bits(w).c_str()); f << stringf(" \"attributes\": {"); write_parameters(w->attributes); f << stringf("\n }\n"); f << stringf(" }"); first = false; } f << stringf("\n }\n"); f << stringf(" }"); } void write_design(Design *design_) { design = design_; design->sort(); f << stringf("{\n"); f << stringf(" \"creator\": %s,\n", get_string(yosys_version_str).c_str()); f << stri
from __future__ import absolute_import
import select
import socket
from .primitives import ProtocolHandler
from netlib.utils import cleanBin
from netlib.tcp import NetLibError


class TCPHandler(ProtocolHandler):
    """
    TCPHandler acts as a generic TCP forwarder.
    Data will be .log()ed, but not stored any further.
    """

    chunk_size = 4096

    def __init__(self, c, log=True):
        super(TCPHandler, self).__init__(c)
        self.log = log

    def handle_messages(self):
        self.c.establish_server_connection()

        server = "%s:%s" % self.c.server_conn.address()[:2]
        buf = memoryview(bytearray(self.chunk_size))
        conns = [self.c.client_conn.rfile, self.c.server_conn.rfile]

        try:
            while True:
                r, _, _ = select.select(conns, [], [], 10)
                for rfile in r:
                    if self.c.client_conn.rfile == rfile:
                        src, dst = self.c.client_conn, self.c.server_conn
                        direction = "-> tcp ->"
                        src_str, dst_str = "client", server
                    else:
                        dst, src = self.c.client_conn, self.c.server_conn
                        direction = "<- tcp <-"
                        dst_str, src_str = "client", server

                    closed = False
                    if src.ssl_established:
                        # Unfortunately, pyOpenSSL lacks a recv_into function.
                        # We need to read a single byte before .pending()
                        # becomes usable
                        contents = src.rfile.read(1)
                        contents += src.rfile.read(src.connection.pending())
                        if not contents:
                            closed = True
                    else:
                        size = src.connection.recv_into(buf)
                        if not size:
                            closed = True

                    if closed:
                        conns.remove(src.rfile)
                        # Shutdown connection to the other peer
                        if dst.ssl_established:
                            # We can't half-close a connection, so we just close everything here.
                            # Sockets will be cleaned up on a higher level.
                            return
                        else:
                            dst.connection.shutdown(socket.SHUT_WR)

                        if len(conns) == 0:
                            return
                        continue

                    if src.ssl_established or dst.ssl_established:
                        # if one of the peers is over SSL, we need to send
                        # bytes/strings
                        if not src.ssl_established:
                            # we revc'd into buf but need bytes/string now.
                            contents = buf[:size].tobytes()
                        if self.log:
                            self.c.log(
                                "%s %s\r\n%s" % (
                                    direction, dst_str, cleanBin(contents)
                                ),
                                "info"
                            )
                        # Do not use dst.connection.send here, which may raise OpenSSL-specific errors.
                        dst.send(contents)
                    else:
                        # socket.socket.send supports raw bytearrays/memoryviews
                        if self.log:
                            self.c.log(
                                "%s %s\r\n%s" % (
                                    direction, dst_str, cleanBin(buf.tobytes())
                                ),
                                "info"
                            )
                        dst.connection.send(buf[:size])
        except (socket.error, NetLibError) as e:
            self.c.log("TCP connection closed unexpectedly.", "debug")
            return