Example #1
0
    def __init__(self,
                 inp=None,
                 out=None,
                 inout=None,
                 user_opts=None,
                 connection_opts=None):
        get_connection_option = lambda key: \
            Mmisc.option_set(connection_opts, key,
                             self.DEFAULT_INIT_CONNECTION_OPTS)
        Muser.UserInterface.__init__(self, inp, out, user_opts)

        self.inout = None  # initialize in case assignment below fails
        if inout:
            self.inout = inout
        else:
            self.server_type = get_connection_option('IO')
            if 'FIFO' == self.server_type:
                # print(connection_opts)
                self.inout = Mfifoclient.FIFOClient(opts=connection_opts)
            elif 'TCP' == self.server_type:
                self.inout = Mtcpclient.TCPClient(opts=connection_opts)
            else:
                self.errmsg("Expecting server type TCP or FIFO. Got: %s." %
                            self.server_type)
                return
            pass
        return
Example #2
0
    def open(self, inp, opts={}):
        """Use this to set where to read from.

        Set opts['try_lineedit'] if you want this input to interact
        with GNU-like readline library. By default, we will assume to
        try importing and using readline. If readline is not
        importable, line editing is not available whether or not
        opts['try_readline'] is set.

        Set opts['use_raw'] if input should use Python's use_raw(). If
        however 'inp' is a string and opts['use_raw'] is not set, we
        will assume no raw output. Note that an individual readline
        may override the setting.
        """
        get_option = lambda key: Mmisc.option_set(opts, key, self.
                                                  DEFAULT_OPEN_READ_OPTS)
        if (isinstance(inp, io.TextIOWrapper) or isinstance(inp, io.StringIO)
                or hasattr(inp, "isatty") and inp.isatty()):
            self.use_raw = get_option("use_raw")
        elif isinstance(inp, "string".__class__):  # FIXME
            if opts is None:
                self.use_raw = False
            else:
                self.use_raw = get_option("use_raw")
                pass
            inp = open(inp, "r")
        else:
            raise IOError("Invalid input type (%s) for %s" % (type(inp), inp))
        self.input = inp
        self.line_edit = get_option("try_readline") and readline_importable()
        self.closed = False
        return
Example #3
0
    def open(self, opts=None):

        get_option = lambda key: option_set(opts, key, Mdefault.
                                            CLIENT_SOCKET_OPTS)

        HOST = get_option('HOST')
        PORT = get_option('PORT')
        self.inout = None
        for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,
                                      socket.SOCK_STREAM):
            af, socktype, proto, canonname, sa = res
            try:
                self.inout = socket.socket(af, socktype, proto)
                self.state = 'connected'
            except socket.error:
                self.inout = None
                self.state = 'disconnected'
                continue
            try:
                self.inout.connect(sa)
            except socket.error:
                self.inout.close()
                self.inout = None
                continue
                break
        if self.inout is None:
            raise IOError('could not open client socket on port %s' % PORT)
        return
Example #4
0
    def open(self, opts=None):

        get_option = lambda key: option_set(opts, key,
                                            Mdefault.CLIENT_SOCKET_OPTS)

        HOST = get_option('HOST')
        PORT = get_option('PORT')
        self.inout = None
        for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,
                                      socket.SOCK_STREAM):
            af, socktype, proto, canonname, sa = res
            try:
                self.inout = socket.socket(af, socktype, proto)
                self.state = 'connected'
            except socket.error:
                self.inout = None
                self.state = 'disconnected'
                continue
            try:
                self.inout.connect(sa)
            except socket.error:
                self.inout.close()
                self.inout = None
                continue
                break
        if self.inout is None:
            raise IOError('could not open client socket on port %s' %
                          PORT)
        return
Example #5
0
    def open(self, inp, opts={}):
        """Use this to set where to read from.

        Set opts['try_lineedit'] if you want this input to interact
        with GNU-like readline library. By default, we will assume to
        try importing and using readline. If readline is not
        importable, line editing is not available whether or not
        opts['try_readline'] is set.

        Set opts['use_raw'] if input should use Python's use_raw(). If
        however 'inp' is a string and opts['use_raw'] is not set, we
        will assume no raw output. Note that an individual readline
        may override the setting.
        """
        get_option = lambda key: Mmisc.option_set(opts, key,
                                                  self.DEFAULT_OPEN_READ_OPTS)
        if (isinstance(inp, types.FileType) or
            isinstance(inp, StringIO.StringIO) or
            hasattr(inp, 'isatty') and inp.isatty()):
            self.use_raw = get_option('use_raw')
        elif isinstance(inp, types.StringType):
            if opts is None:
                self.use_raw = False
            else:
                self.use_raw = get_option('use_raw')
                pass
            inp = open(inp, 'r')
        else:
            raise IOError("Invalid input type (%s) for %s" % (type(inp),
                                                                inp))
        self.input     = inp
        self.line_edit = get_option('try_readline') and readline_importable()
        self.closed = False
        return
Example #6
0
    def start(self, opts=None):
        """ We've already created a debugger object, but here we start
        debugging in earnest. We can also turn off debugging (but have
        the hooks suspended or not) using 'stop'.

        'opts' is a hash of every known value you might want to set when
        starting the debugger. See START_OPTS of module default.
        """

        # The below is our fancy equivalent of:
        #    sys.settrace(self._trace_dispatch)
        try:
            self.trace_hook_suspend = True
            get_option = lambda key: Mmisc.option_set(opts, key,
                                                      default.START_OPTS)

            add_hook_opts = get_option('add_hook_opts')

            # Has tracer been started?
            if not tracer.is_started() or get_option('force'):
                # FIXME: should filter out opts not for tracer

                tracer_start_opts = default.START_OPTS.copy()
                if opts:
                    tracer_start_opts.update(opts.get('tracer_start', {}))
                tracer_start_opts['trace_fn'] = self.trace_dispatch
                tracer_start_opts['add_hook_opts'] = add_hook_opts
                tracer.start(tracer_start_opts)
            elif not tracer.find_hook(self.trace_dispatch):
                tracer.add_hook(self.trace_dispatch, add_hook_opts)
                pass
            self.execution_status = 'Running'
        finally:
            self.trace_hook_suspend = False
        return
Example #7
0
    def __init__(self, inp=None, out=None, opts={}):
        get_option = lambda key: Mmisc.option_set(opts, key,
                                                  DEFAULT_USER_SETTINGS)

        from trepan.inout import input as Minput, output as Moutput

        atexit.register(self.finalize)
        self.interactive = True  # Or at least so we think initially
        self.input = inp or Minput.DebuggerUserInput()
        self.output = out or Moutput.DebuggerUserOutput()

        if self.input.use_history():
            self.complete = get_option('complete')
            if self.complete:
                parse_and_bind("tab: complete")
                set_completer(self.complete)
                pass
            self.histfile = get_option('histfile')
            if self.histfile:
                try:
                    read_history_file(histfile)
                except IOError:
                    pass
                except:
                    # PyPy read_history_file fails
                    return
                set_history_length(50)
                atexit.register(write_history_file, self.histfile)
                pass
        return
Example #8
0
    def __init__(self, inp=None, out=None, opts={}):
        get_option = lambda key: Mmisc.option_set(opts, key,
                                                  DEFAULT_USER_SETTINGS)

        from trepan.inout import input as Minput, output as Moutput

        atexit.register(self.finalize)
        self.interactive = True  # Or at least so we think initially
        self.input       = inp or Minput.DebuggerUserInput()
        self.output      = out or Moutput.DebuggerUserOutput()

        if self.input.use_history():
            self.complete = get_option('complete')
            if self.complete:
                parse_and_bind("tab: complete")
                set_completer(self.complete)
                pass
            self.histfile = get_option('histfile')
            if self.histfile:
                try:
                    read_history_file(histfile)
                except IOError:
                    pass
                set_history_length(50)
                atexit.register(write_history_file, self.histfile)
                pass
        return
Example #9
0
    def start(self, opts=None):
        """ We've already created a debugger object, but here we start
        debugging in earnest. We can also turn off debugging (but have
        the hooks suspended or not) using 'stop'.

        'opts' is a hash of every known value you might want to set when
        starting the debugger. See START_OPTS of module default.
        """

        # The below is our fancy equivalent of:
        #    sys.settrace(self._trace_dispatch)
        try:
            self.trace_hook_suspend = True
            get_option = lambda key: Mmisc.option_set(opts, key,
                                                      default.START_OPTS)

            add_hook_opts = get_option('add_hook_opts')

            # Has tracer been started?
            if not tracer.is_started() or get_option('force'):
                # FIXME: should filter out opts not for tracer
                # Also, if we use opts.copy we need to check for 'None'.
                tracer_start_opts = default.START_OPTS.copy()
                tracer_start_opts['trace_fn'] = self.trace_dispatch
                tracer_start_opts['add_hook_opts'] = add_hook_opts
                tracer.start(tracer_start_opts)
            elif not tracer.find_hook(self.trace_dispatch):
                tracer.add_hook(self.trace_dispatch, add_hook_opts)
                pass
            self.execution_status = 'Running'
        finally:
            self.trace_hook_suspend = False
        return
Example #10
0
 def test_option_set(self):
     TEST_OPTS = {'a': True, 'b': 5, 'c': None}
     get_option = lambda key: Mmisc.option_set(opts, key, TEST_OPTS)
     opts = {'d': 6, 'a': False}
     for opt, expect in [('a', False), ('b', 5), ('c', None), ('d', 6)]:
         self.assertEqual(expect, get_option(opt))
     opts = None
     for opt, expect in [('a', True), ('b', 5), ('c', None), ('d', None)]:
         self.assertEqual(expect, get_option(opt))
     pass
Example #11
0
    def open(self, opts=None):
        get_option = lambda key: Mmisc.option_set(opts, key, Mdefault.
                                                  SERVER_SOCKET_OPTS)

        self.HOST = get_option("HOST")
        self.PORT = get_option("PORT")
        self.reuse = get_option("reuse")
        self.search_limit = get_option("search_limit")
        self.inout = None

        this_port = self.PORT - 1
        for i in range(self.search_limit):
            this_port += 1
            for res in socket.getaddrinfo(
                    self.HOST,
                    this_port,
                    socket.AF_UNSPEC,
                    socket.SOCK_STREAM,
                    0,
                    socket.AI_PASSIVE,
            ):
                af, socktype, proto, canonname, sa = res
                try:
                    self.inout = socket.socket(af, socktype, proto)
                except socket.error:
                    self.inout = None
                    continue
                try:
                    if get_option("reuse"):
                        # The following socket option allows the OS to reclaim
                        # The address faster on termination.
                        self.inout.setsockopt(socket.SOL_SOCKET,
                                              socket.SO_REUSEADDR, 1)

                        pass
                    self.inout.bind(sa)
                    self.inout.listen(1)
                    self.state = "listening"
                    break
                except socket.error as exc:
                    if exc.errno in [errno.EADDRINUSE, errno.EINVAL]:
                        self.inout.close()
                        self.inout = None
                        continue
                    raise
                pass
            if self.state == "listening":
                break
        if self.inout is None:
            raise IOError("could not open server socket after trying ports "
                          "%s..%s" % (self.PORT, this_port))
        self.PORT = this_port
        return
Example #12
0
 def __init__(self, inp=None, opts=None):
     get_option = lambda key: Mmisc.option_set(opts, key, Mdefault.CLIENT_SOCKET_OPTS)
     self.state = "disconnected"
     self.flush_after_write = True
     self.input = None
     self.output = None
     self.line_edit = False  # Our name for GNU readline capability
     self.state = "disconnected"
     open_pid = get_option("open")
     if open_pid:
         self.open(open_pid)
         pass
     return
Example #13
0
 def __init__(self, inout=None, opts=None):
     get_option = lambda key: option_set(opts, key,
                                         Mdefault.CLIENT_SOCKET_OPTS)
     self.inout = None
     self.addr = None
     self.buf = ''
     self.line_edit = False  # Our name for GNU readline capability
     self.state = 'disconnected'
     if inout:
         self.inout = inout
     elif get_option('open'):
         self.open(opts)
         pass
     return
Example #14
0
 def __init__(self, inout=None, opts=None):
     get_option = lambda key: option_set(opts, key, Mdefault.
                                         CLIENT_SOCKET_OPTS)
     self.inout = None
     self.addr = None
     self.buf = ''
     self.line_edit = False  # Our name for GNU readline capability
     self.state = 'disconnected'
     if inout:
         self.inout = inout
     elif get_option('open'):
         self.open(opts)
         pass
     return
Example #15
0
 def __init__(self, inp=None, opts=None):
     get_option = lambda key: Mmisc.option_set(opts, key, Mdefault.
                                               CLIENT_SOCKET_OPTS)
     self.state = 'disconnected'
     self.flush_after_write = True
     self.input = None
     self.output = None
     self.line_edit = False  # Our name for GNU readline capability
     self.state = 'disconnected'
     open_pid = get_option('open')
     if open_pid:
         self.open(open_pid)
         pass
     return
 def __init__(self, opts=None):
     get_option = lambda key: Mmisc.option_set(opts, key,
                                               self.DEFAULT_INIT_OPTS)
     atexit.register(self.close)
     self.flush_after_write = True
     self.line_edit = False  # Our name for GNU readline capability
     self.in_name   = None   # String: input file name
     self.input     = None   # File Descriptor
     self.out_name  = None   # String: output file name
     self.output    = None   # String: output file name
     self.state     = 'disconnected'
     if get_option('open'):
         self.open(opts)
         pass
     return
Example #17
0
 def __init__(self, opts=None):
     get_option = lambda key: Mmisc.option_set(opts, key, self.
                                               DEFAULT_INIT_OPTS)
     atexit.register(self.close)
     self.flush_after_write = True
     self.line_edit = False  # Our name for GNU readline capability
     self.in_name = None  # String: input file name
     self.input = None  # File Descriptor
     self.out_name = None  # String: output file name
     self.output = None  # String: output file name
     self.state = 'disconnected'
     if get_option('open'):
         self.open(opts)
         pass
     return
Example #18
0
    def open(self, opts=None):
        get_option = lambda key: Mmisc.option_set(opts, key,
                                                  Mdefault.SERVER_SOCKET_OPTS)

        self.HOST  = get_option('HOST')
        self.PORT  = get_option('PORT')
        self.reuse = get_option('reuse')
        self.search_limit = get_option('search_limit')
        self.inout = None

        this_port = self.PORT - 1
        for i in range(self.search_limit):
            this_port += 1
            for res in socket.getaddrinfo(self.HOST, this_port, socket.AF_UNSPEC,
                                          socket.SOCK_STREAM, 0,
                                          socket.AI_PASSIVE):
                af, socktype, proto, canonname, sa = res
                try:
                    self.inout = socket.socket(af, socktype, proto)
                except socket.error:
                    self.inout = None
                    continue
                try:
                    if get_option('reuse'):
                        # The following socket option allows the OS to reclaim
                        # The address faster on termination.
                        self.inout.setsockopt(socket.SOL_SOCKET,
                                              socket.SO_REUSEADDR, 1)

                        pass
                    self.inout.bind(sa)
                    self.inout.listen(1)
                    self.state = 'listening'
                    break
                except socket.error as exc:
                    if exc.errno in [errno.EADDRINUSE, errno.EINVAL]:
                        self.inout.close()
                        self.inout = None
                        continue
                    raise
                pass
            if self.state == 'listening':
                break
        if self.inout is None:
            raise IOError('could not open server socket after trying ports '
                          '%s..%s' % (self.PORT, this_port))
        self.PORT = this_port
        return
Example #19
0
 def test_option_set(self):
     TEST_OPTS = {'a': True, 'b': 5, 'c': None}
     get_option = lambda key: Mmisc.option_set(opts, key, TEST_OPTS)
     opts={'d': 6, 'a': False}
     for opt, expect in [('a', False),
                         ('b', 5),
                         ('c', None),
                         ('d', 6)]:
         self.assertEqual(expect, get_option(opt))
     opts=None
     for opt, expect in [('a', True),
                         ('b', 5),
                         ('c', None),
                         ('d', None)]:
         self.assertEqual(expect, get_option(opt))
     pass
Example #20
0
    def __init__(self, script_name, out=None, opts=None):
        get_option = lambda key: Mmisc.option_set(opts, key,
                                                  self.DEFAULT_INIT_OPTS)

        atexit.register(self.finalize)
        self.script_name     = script_name
        self.histfile        = None
        self.input_lineno    = 0
        self.input           = Mscriptin.ScriptInput(script_name)
        self.interactive     = False
        self.output          = out or Moutput.DebuggerUserOutput()

        self.abort_on_error  = get_option('abort_on_error')
        self.default_confirm = get_option('confirm_val')
        self.verbose         = get_option('verbose')

        return
Example #21
0
    def __init__(self, script_name, out=None, opts=None):
        get_option = lambda key: Mmisc.option_set(opts, key, self.
                                                  DEFAULT_INIT_OPTS)

        atexit.register(self.finalize)
        self.script_name = script_name
        self.histfile = None
        self.input_lineno = 0
        self.input = Mscriptin.ScriptInput(script_name)
        self.interactive = False
        self.output = out or Moutput.DebuggerUserOutput()

        self.abort_on_error = get_option("abort_on_error")
        self.default_confirm = get_option("confirm_val")
        self.verbose = get_option("verbose")

        return
Example #22
0
    def __init__(self, inout=None, opts=None):
        get_option = lambda key: Mmisc.option_set(opts, key, self.
                                                  DEFAULT_INIT_OPTS)

        self.inout = None
        self.conn = None
        self.addr = None
        self.buf = ''  # Read buffer
        self.state = 'disconnected'
        self.PORT = None
        self.HOST = None
        if inout:
            self.inout = inout
        elif get_option('open'):
            self.open(opts)
            pass
        return
Example #23
0
    def __init__(self, inout=None, opts=None):
        get_option = lambda key: Mmisc.option_set(opts, key,
                                                  self.DEFAULT_INIT_OPTS)

        self.inout = None
        self.conn = None
        self.addr = None
        self.buf = ''    # Read buffer
        self.state = 'disconnected'
        self.PORT = None
        self.HOST = None
        if inout:
            self.inout = inout
        elif get_option('open'):
            self.open(opts)
            pass
        return
Example #24
0
 def stop(self, options=None):
     # Our version of:
     #    pdb.set_trace(None)
     try:
         self.trace_hook_suspend = True
         get_option = lambda key: Mmisc.option_set(options, key,
                                                   default.STOP_OPTS)
         args = [self.trace_dispatch]
         remove = get_option('remove')
         if remove:
             args.append(remove)
             pass
         if tracer.is_started():
             try:
                 tracer.remove_hook(*args)
             except LookupError:
                 pass
             pass
     finally:
         self.trace_hook_suspend = False
     return
Example #25
0
 def stop(self, options=None):
     # Our version of:
     #    sys.settrace(None)
     try:
         self.trace_hook_suspend = True
         get_option = lambda key: Mmisc.option_set(options, key,
                                                   default.STOP_OPTS)
         args = [self.trace_dispatch]
         remove = get_option('remove')
         if remove:
             args.append(remove)
             pass
         if tracer.is_started():
             try:
                 tracer.remove_hook(*args)
             except LookupError:
                 pass
             pass
     finally:
         self.trace_hook_suspend = False
     return
Example #26
0
 def __init__(self, inout=None, out=None, connection_opts=None):
     get_option = lambda key: \
         Mmisc.option_set(connection_opts, key,
                          self.DEFAULT_INIT_CONNECTION_OPTS)
     atexit.register(self.finalize)
     self.inout = None  # initialize in case assignment below fails
     if inout:
         self.inout = inout
     else:
         self.server_type = get_option('IO')
         if 'FIFO' == self.server_type:
             self.inout = Mfifoserver.FIFOServer()
         else:
             self.inout = Mtcpserver.TCPServer(opts=connection_opts)
             pass
         pass
     # For Compatability
     self.output = inout
     self.input  = inout
     self.interactive = True  # Or at least so we think initially
     self.histfile = None
     return
Example #27
0
 def __init__(self, inout=None, out=None, connection_opts=None):
     get_option = lambda key: \
         Mmisc.option_set(connection_opts, key,
                          self.DEFAULT_INIT_CONNECTION_OPTS)
     atexit.register(self.finalize)
     self.inout = None  # initialize in case assignment below fails
     if inout:
         self.inout = inout
     else:
         self.server_type = get_option('IO')
         if 'FIFO' == self.server_type:
             self.inout = Mfifoserver.FIFOServer()
         else:
             self.inout = Mtcpserver.TCPServer(opts=connection_opts)
             pass
         pass
     # For Compatability
     self.output = inout
     self.input = inout
     self.interactive = True  # Or at least so we think initially
     self.histfile = None
     return
Example #28
0
    def __init__(self, inout=None, opts=None):
        get_option = lambda key: Mmisc.option_set(opts, key, self.
                                                  DEFAULT_INIT_OPTS)

        self.inout = None
        self.conn = None
        self.addr = None
        self.remote_addr = ""
        self.buf = ""  # Read buffer
        self.line_edit = False  # Our name for GNU readline capability
        self.state = "disconnected"
        self.PORT = None
        self.HOST = None
        if inout:
            self.inout = inout
        if get_option("socket"):
            self.inout = opts["socket"]
            self.inout.listen(1)
            self.state = "listening"
        elif get_option("open"):
            self.open(opts)
            pass
        return
Example #29
0
    def __init__(self, inout=None, opts=None):
        get_option = lambda key: Mmisc.option_set(opts, key,
                                                  self.DEFAULT_INIT_OPTS)

        self.inout = None
        self.conn = None
        self.addr = None
        self.remote_addr = ''
        self.buf = ''    # Read buffer
        self.line_edit = False  # Our name for GNU readline capability
        self.state = 'disconnected'
        self.PORT = None
        self.HOST = None
        if inout:
            self.inout = inout
        if get_option('socket'):
            self.inout = opts['socket']
            self.inout.listen(1)
            self.state = 'listening'
        elif get_option('open'):
            self.open(opts)
            pass
        return
Example #30
0
    def __init__(self, inp=None, out=None, inout=None, user_opts=None,
                 connection_opts=None):
        get_connection_option = lambda key: \
            Mmisc.option_set(connection_opts, key,
                             self.DEFAULT_INIT_CONNECTION_OPTS)
        Muser.UserInterface.__init__(self, inp, out, user_opts)

        self.inout = None  # initialize in case assignment below fails
        if inout:
            self.inout = inout
        else:
            self.server_type = get_connection_option('IO')
            if 'FIFO' == self.server_type:
                # print(connection_opts)
                self.inout = Mfifoclient.FIFOClient(opts=connection_opts)
            elif 'TCP' == self.server_type:
                self.inout = Mtcpclient.TCPClient(opts=connection_opts)
            else:
                self.errmsg("Expecting server type TCP or FIFO. Got: %s." %
                            self.server_type)
                return
            pass
        return
Example #31
0
    def open(self, opts=None):
        get_option = lambda key: Mmisc.option_set(opts, key, Mdefault.
                                                  SERVER_SOCKET_OPTS)

        self.HOST = get_option('HOST')
        self.PORT = get_option('PORT')
        self.inout = None
        for res in socket.getaddrinfo(self.HOST, self.PORT, socket.AF_UNSPEC,
                                      socket.SOCK_STREAM, 0,
                                      socket.AI_PASSIVE):
            af, socktype, proto, canonname, sa = res
            try:
                self.inout = socket.socket(af, socktype, proto)
            except socket.error:
                self.inout = None
                continue
            try:
                if get_option('reuse'):
                    # The following socket option allows the OS to reclaim
                    # The address faster on termination.
                    self.inout.setsockopt(socket.SOL_SOCKET,
                                          socket.SO_REUSEADDR, 1)

                    pass
                self.inout.bind(sa)
                self.inout.listen(1)
                self.state = 'listening'
            except socket.error:
                self.inout.close()
                self.inout = None
                continue
            break
        if self.inout is None:
            raise IOError('could not open server socket on port %s' %
                          self.PORT)
        return
Example #32
0
    def open(self, opts=None):
        get_option = lambda key: Mmisc.option_set(opts, key,
                                                  Mdefault.SERVER_SOCKET_OPTS)

        self.HOST = get_option('HOST')
        self.PORT = get_option('PORT')
        self.inout = None
        for res in socket.getaddrinfo(self.HOST, self.PORT, socket.AF_UNSPEC,
                                      socket.SOCK_STREAM, 0,
                                      socket.AI_PASSIVE):
            af, socktype, proto, canonname, sa = res
            try:
                self.inout = socket.socket(af, socktype, proto)
            except socket.error:
                self.inout = None
                continue
            try:
                if get_option('reuse'):
                    # The following socket option allows the OS to reclaim
                    # The address faster on termination.
                    self.inout.setsockopt(socket.SOL_SOCKET,
                                          socket.SO_REUSEADDR, 1)

                    pass
                self.inout.bind(sa)
                self.inout.listen(1)
                self.state = 'listening'
            except socket.error:
                self.inout.close()
                self.inout = None
                continue
            break
        if self.inout is None:
            raise IOError('could not open server socket on port %s' %
                            self.PORT)
        return
Example #33
0
    def __init__(self, debugger, opts=None):
        """ Create a debugger object. But depending on the value of
        key 'start' inside hash `opts', we may or may not initially
        start tracing events (i.e. enter the debugger).

        See also `start' and `stop'.
        """

        import trepan.bwprocessor as Mbwproc

        get_option       = lambda key: Mmisc.option_set(opts, key,
                                                        self.DEFAULT_INIT_OPTS)

        self.bpmgr           = breakpoint.BreakpointManager()
        self.current_bp      = None
        self.debugger        = debugger

        # Threading lock ensures that we don't have other traced threads
        # running when we enter the debugger. Later we may want to have
        # a switch to control.
        self.debugger_lock   = threading.Lock()

        self.filename_cache  = {}

        # Initially the event parameter of the event hook.
        # We can however modify it, such as for breakpoints
        self.event           = None

        # Is debugged program currently under execution?
        self.execution_status = 'Pre-execution'

        # main_dirname is the directory where the script resides.
        # Filenames in co_filename are often relative to this.
        self.main_dirname    = os.curdir

        # What event processor and processor options do we use?
        self.processor = get_option('processor')
        proc_opts      = get_option('proc_opts')
        if not self.processor:
            self.processor   = Mcmdproc.CommandProcessor(self, opts=proc_opts)
        elif self.processor == 'bullwinkle':
            self.processor   = Mbwproc.BWProcessor(self, opts=proc_opts)
            pass
        # What events are considered in stepping. Note: 'None' means *all*.
        self.step_events     = None
        # How many line events to skip before entering event processor?
        # If stop_level is None all breaks are counted otherwise just
        # those which less than or equal to stop_level.
        self.step_ignore     = get_option('step_ignore')

        # If stop_level is not None, then we are next'ing or
        # finish'ing and will ignore frames greater than stop_level.
        # We also will cache the last frame and thread number encountered
        # so we don't have to compute the current level all the time.
        self.last_frame      = None
        self.last_level      = 10000
        self.last_thread     = None
        self.stop_level      = None
        self.stop_on_finish  = False

        self.last_lineno     = None
        self.last_filename   = None
        self.different_line  = None

        # The reason we have stopped, e.g. 'breakpoint hit', 'next',
        # 'finish', 'step', or 'exception'.
        self.stop_reason     = ''

        self.trace_processor = Mtrace.PrintProcessor(self)

        # What routines (keyed by f_code) will we not trace into?
        self.ignore_filter = get_option('ignore_filter')

        self.search_path     = sys.path  # Source filename search path

        # When trace_hook_suspend is set True, we'll suspend
        # debugging.
        self.trace_hook_suspend = False

        self.until_condition = get_option('until_condition')

        return
Example #34
0
    def __init__(self, core_obj, opts=None):
        super().__init__(core_obj, opts)
        self.core = core_obj
        self.debugger = core_obj.debugger

        self.continue_running = False  # True if we should leave command loop
        self.event2short = dict(EVENT2SHORT)
        self.event2short["signal"] = "?!"
        self.event2short["brkpt"] = "xx"

        self.optional_modules = ()

        # command argument string. Is like current_command, but the part
        # after cmd_name has been removed.
        self.cmd_argstr = ""

        # command name before alias or macro resolution
        self.cmd_name = ""
        self.cmd_queue = []  # Queued debugger commands
        self.completer = lambda text, state: Mcomplete.completer(
            self, text, state)
        self.current_command = ""  # Current command getting run
        self.debug_nest = 1
        self.display_mgr = Mdisplay.DisplayMgr()
        self.intf = core_obj.debugger.intf
        self.last_command = None  # Initially a no-op
        self.precmd_hooks = []

        # FIXME: can we adjust this to also show the instruction?
        self.location = lambda: self

        self.preloop_hooks = []
        self.postcmd_hooks = []

        # Note: prompt_str's value set below isn't used. It is
        # computed dynamically. The value is suggestive of what it
        # looks like.
        self.prompt_str = "(trepan-xpy) "

        # Stop only if line/file is different from last time
        self.different_line = None

        # These values updated on entry. Set initial values.
        self.curframe = None
        self.event = None
        self.event_arg = None
        self.frame = None
        self.list_lineno = 0  # last list number used in "list"
        self.list_offset = -1  # last list number used in "disassemble"
        self.list_obj = None
        self.list_filename = None  # last filename used in list
        self.list_orig_lineno = 0  # line number of frame or exception on setup
        self.list_filename = None  # filename of frame or exception on setup

        self.macros = {}  # Debugger Macros

        # Create a custom safe Repr instance and increase its maxstring.
        # The default of 30 truncates error messages too easily.
        self._repr = Repr()
        self._repr.maxstring = 100
        self._repr.maxother = 60
        self._repr.maxset = 10
        self._repr.maxfrozen = 10
        self._repr.array = 10
        self.stack = []
        self.thread_name = None
        self.frame_thread_name = None

        get_option = lambda key: option_set(opts, key, DEFAULT_PROC_OPTS)
        initfile_list = get_option("initfile_list")
        for init_cmdfile in initfile_list:
            self.queue_startfile(init_cmdfile)

        # FIXME: This doesn't work
        # # Delegate functions here:
        # self.cmdproc = CommandProcessor(self)
        # for method in (
        #         "_saferepr",
        #         "add_preloop_hook",
        #         "defaultFile",
        #         "eval",
        #         "exec_line",
        #         "forget",
        #         "get_an_int",
        #         "get_int_noerr",
        #         "getval",
        #         "ok_for_running",
        #         "process_commands",
        #         "queue_startfile",
        #         "remove_preloop_hook",
        #         "setup",
        #         "undefined_cmd",
        #         "read_history_file",
        #         "write_history_file",
        #         ):
        #     setattr(self, method, getattr(cmdproc, method))

        # Remove trepan3k commands which aren't valid here, and those specific to trepan-xpy
        remove_commands = (
            "continue",
            "finish",
            "next",
            "quit",
            "set",
            "step",
        )
        new_instances = []
        for cmd in self.cmd_instances:
            if cmd.name in remove_commands:
                del self.commands[cmd.name]
            else:
                new_instances.append(cmd)
                pass
            pass
        self.cmd_instances = new_instances

        new_commands = self._update_commands()
        for new_command in new_commands:
            self.commands[new_command.name] = new_command
        self.cmd_instances += new_commands
        self._populate_cmd_lists()

        if self.debugger.settings["autopc"]:
            self.commands["set"].run(["set", "autopc"])
        return
Example #35
0
    def __init__(self, debugger, opts=None):
        """ Create a debugger object. But depending on the value of
        key 'start' inside hash `opts', we may or may not initially
        start tracing events (i.e. enter the debugger).

        See also `start' and `stop'.
        """

        import trepan.processor
        import trepan.bwprocessor as Mbwproc

        get_option       = lambda key: Mmisc.option_set(opts, key,
                                                        self.DEFAULT_INIT_OPTS)

        self.bpmgr           = breakpoint.BreakpointManager()
        self.current_bp      = None
        self.debugger        = debugger

        # Threading lock ensures that we don't have other traced threads
        # running when we enter the debugger. Later we may want to have
        # a switch to control.
        self.debugger_lock   = threading.Lock()

        self.filename_cache  = {}

        # Initially the event parameter of the event hook.
        # We can however modify it, such as for breakpoints
        self.event           = None

        # Is debugged program currently under execution?
        self.execution_status = 'Pre-execution'

        # main_dirname is the directory where the script resides.
        # Filenames in co_filename are often relative to this.
        self.main_dirname    = os.curdir

        # What event processor and processor options do we use?
        self.processor = get_option('processor')
        proc_opts      = get_option('proc_opts')
        if not self.processor:
            self.processor   = Mcmdproc.CommandProcessor(self, opts=proc_opts)
        elif self.processor == 'bullwinkle':
            self.processor   = Mbwproc.BWProcessor(self, opts=proc_opts)
            pass
        # What events are considered in stepping. Note: 'None' means *all*.
        self.step_events     = None
        # How many line events to skip before entering event processor?
        # If stop_level is None all breaks are counted otherwise just
        # those which less than or equal to stop_level.
        self.step_ignore     = get_option('step_ignore')

        # If stop_level is not None, then we are next'ing or
        # finish'ing and will ignore frames greater than stop_level.
        # We also will cache the last frame and thread number encountered
        # so we don't have to compute the current level all the time.
        self.last_frame      = None
        self.last_level      = 10000
        self.last_thread     = None
        self.stop_level      = None
        self.stop_on_finish  = False

        self.last_lineno     = None
        self.last_filename   = None
        self.different_line  = None

        # The reason we have stopped, e.g. 'breakpoint hit', 'next',
        # 'finish', 'step', or 'exception'.
        self.stop_reason     = ''

        self.trace_processor = Mtrace.PrintProcessor(self)

        # What routines (keyed by f_code) will we not trace into?
        self.ignore_filter = get_option('ignore_filter')

        self.search_path     = sys.path  # Source filename search path

        # When trace_hook_suspend is set True, we'll suspend
        # debugging.
        self.trace_hook_suspend = False

        self.until_condition = get_option('until_condition')

        return
Example #36
0
    def __init__(self, core_obj, opts=None):
        get_option = lambda key: Mmisc.option_set(opts, key, DEFAULT_PROC_OPTS)
        super().__init__(core_obj)

        self.continue_running = False  # True if we should leave command loop
        self.event2short = dict(EVENT2SHORT)
        self.event2short["signal"] = "?!"
        self.event2short["brkpt"] = "xx"

        self.optional_modules = ("ipython", "bpy")
        self.cmd_instances = self._populate_commands()

        # command argument string. Is like current_command, but the part
        # after cmd_name has been removed.
        self.cmd_argstr = ""

        # command name before alias or macro resolution
        self.cmd_name = ""
        self.cmd_queue = []  # Queued debugger commands
        self.completer = lambda text, state: Mcomplete.completer(
            self, text, state)
        self.current_command = ""  # Current command getting run
        self.debug_nest = 1
        self.display_mgr = Mdisplay.DisplayMgr()
        self.intf = core_obj.debugger.intf
        self.last_command = None  # Initially a no-op
        self.precmd_hooks = []

        self.location = lambda: print_location(self)

        self.preloop_hooks = []
        self.postcmd_hooks = []
        self.remap_file_re = None

        self._populate_cmd_lists()

        # Note: prompt_str's value set below isn't used. It is
        # computed dynamically. The value is suggestive of what it
        # looks like.
        self.prompt_str = "(trepan3k) "

        # Stop only if line/file is different from last time
        self.different_line = None

        # These values updated on entry. Set initial values.
        self.curframe = None
        self.event = None
        self.event_arg = None
        self.frame = None
        self.list_lineno = 0  # last list number used in "list"
        self.list_offset = -1  # last list number used in "disassemble"
        self.list_obj = None
        self.list_filename = None  # last filename used in list
        self.list_orig_lineno = 0  # line number of frame or exception on setup
        self.list_filename = None  # filename of frame or exception on setup

        self.macros = {}  # Debugger Macros

        # Create a custom safe Repr instance and increase its maxstring.
        # The default of 30 truncates error messages too easily.
        self._repr = Repr()
        self._repr.maxstring = 100
        self._repr.maxother = 60
        self._repr.maxset = 10
        self._repr.maxfrozen = 10
        self._repr.array = 10
        self.stack = []
        self.thread_name = None
        self.frame_thread_name = None

        initfile_list = get_option("initfile_list")
        for init_cmdfile in initfile_list:
            self.queue_startfile(init_cmdfile)
        return
Example #37
0
    def __init__(self, opts=None):
        """Create a debugger object. But depending on the value of
        key 'start' inside hash 'opts', we may or may not initially
        start debugging.

        See also Debugger.start and Debugger.stop.
        """

        import trepan.lib.core as Mcore

        self.mainpyfile  = None
        self.thread      = None
        self.eval_string = None
        get_option = lambda key: option_set(opts, key,
                                            self.DEFAULT_INIT_OPTS)
        completer  = lambda text, state: self.complete(text, state)

        # set the instance variables that come directly from options.
        for opt in ('settings', 'orig_sys_argv', 'from_ipython'):
            setattr(self, opt, get_option(opt))
            pass

        core_opts = {}
        for opt in ('ignore_filter', 'proc_opts', 'processor', 'step_ignore',
                    'processor',):
            core_opts[opt] = get_option(opt)
            pass

        # How is I/O for this debugger handled? This should
        # be set before calling DebuggerCore.
        interface_opts={'complete': completer}
        # FIXME when I pass in opts=opts things break
        interface = (get_option('interface') or
                     Muser.UserInterface(opts=interface_opts))
        self.intf = [interface]

        inp = get_option('input')
        if inp:
            self.intf[-1].input = inp
            pass

        out = get_option('output')
        if out:
            self.intf[-1].output = out
            pass

        self.core = Mcore.DebuggerCore(self, core_opts)
        self.core.add_ignore(self.core.stop)

        # When set True, we'll also suspend our debug-hook tracing.
        # This gives us a way to prevent or allow self debugging.
        self.core.trace_hook_suspend = False

        if get_option('save_sys_argv'):
            # Save the debugged program's sys.argv? We do this so that
            # when the debugged script munges these, we have a good
            # copy to use for an exec restart
            self.program_sys_argv = list(sys.argv)
        else:
            self.program_sys_argv = None
            pass

        self.sigmgr = Msig.SignalManager(self)

        # Were we requested to activate immediately?
        if get_option('activate'):
            self.core.start(get_option('start_opts'))
            pass
        return
Example #38
0
    def __init__(self, core_obj, opts=None):
        get_option = lambda key: \
            Mmisc.option_set(opts, key, DEFAULT_PROC_OPTS)
        Mprocessor.Processor.__init__(self, core_obj)

        self.continue_running = False  # True if we should leave command loop
        self.event2short = dict(EVENT2SHORT)
        self.event2short['signal'] = '?!'
        self.event2short['brkpt'] = 'xx'

        self.optional_modules = ('ipython', 'bpy')
        self.cmd_instances = self._populate_commands()

        # command argument string. Is like current_command, but the part
        # after cmd_name has been removed.
        self.cmd_argstr = ''

        # command name before alias or macro resolution
        self.cmd_name = ''
        self.cmd_queue = []  # Queued debugger commands
        self.completer        = lambda text, state: \
          Mcomplete.completer(self, text, state)
        self.current_command = ''  # Current command getting run
        self.debug_nest = 1
        self.display_mgr = Mdisplay.DisplayMgr()
        self.intf = core_obj.debugger.intf
        self.last_command = None  # Initially a no-op
        self.precmd_hooks = []

        self.location = lambda: print_location(self)

        self.preloop_hooks = []
        self.postcmd_hooks = []

        self._populate_cmd_lists()
        self.prompt_str = '(trepan3k) '

        # Stop only if line/file is different from last time
        self.different_line = None

        # These values updated on entry. Set initial values.
        self.curframe = None
        self.event = None
        self.event_arg = None
        self.frame = None
        self.list_lineno = 0  # last list number used in "list"
        self.list_filename = None  # last filename used in list

        self.macros = {}  # Debugger Macros

        # Create a custom safe Repr instance and increase its maxstring.
        # The default of 30 truncates error messages too easily.
        self._repr = Repr()
        self._repr.maxstring = 100
        self._repr.maxother = 60
        self._repr.maxset = 10
        self._repr.maxfrozen = 10
        self._repr.array = 10
        self.stack = []
        self.thread_name = None
        self.frame_thread_name = None
        initfile_list = get_option('initfile_list')
        for init_cmdfile in initfile_list:
            self.queue_startfile(init_cmdfile)
        return
Example #39
0
    def __init__(self, core_obj, opts=None):
        get_option = lambda key: \
            Mmisc.option_set(opts, key, DEFAULT_PROC_OPTS)
        Mprocessor.Processor.__init__(self, core_obj)

        self.continue_running = False  # True if we should leave command loop
        self.event2short      = dict(EVENT2SHORT)
        self.event2short['signal'] = '?!'
        self.event2short['brkpt']  = 'xx'

        self.optional_modules = ('ipython', 'bpy', 'deparse')
        self.optional_modules = ('ipython', 'bpy')
        self.cmd_instances    = self._populate_commands()

        # command argument string. Is like current_command, but the part
        # after cmd_name has been removed.
        self.cmd_argstr       = ''

        # command name before alias or macro resolution
        self.cmd_name         = ''
        self.cmd_queue        = []     # Queued debugger commands
        self.completer        = lambda text, state: \
          Mcomplete.completer(self, text, state)
        self.current_command  = ''     # Current command getting run
        self.debug_nest       = 1
        self.display_mgr      = Mdisplay.DisplayMgr()
        self.intf             = core_obj.debugger.intf
        self.last_command     = None   # Initially a no-op
        self.precmd_hooks     = []

        self.location         = lambda : print_location(self)

        self.preloop_hooks    = []
        self.postcmd_hooks    = []

        self._populate_cmd_lists()

        # Note: prompt_str's value set below isn't used. It is
        # computed dynamically. The value is suggestive of what it
        # looks like.
        self.prompt_str     = '(trepan2) '

        # Stop only if line/file is different from last time
        self.different_line = None

        # These values updated on entry. Set initial values.
        self.curframe       = None
        self.event          = None
        self.event_arg      = None
        self.frame          = None
        self.list_lineno    = 0      # last list number used in "list"
        self.list_filename  = None   # last filename used in list

        self.macros         = {}     # Debugger Macros

        # Create a custom safe Repr instance and increase its maxstring.
        # The default of 30 truncates error messages too easily.
        self._repr             = Repr()
        self._repr.maxstring   = 100
        self._repr.maxother    = 60
        self._repr.maxset      = 10
        self._repr.maxfrozen   = 10
        self._repr.array       = 10
        self.stack             = []
        self.thread_name       = None
        self.frame_thread_name = None
        initfile_list          = get_option('initfile_list')
        for init_cmdfile in initfile_list:
            self.queue_startfile(init_cmdfile)
        return