def test_remap(self):
     pyficache.remap_file(__file__, 'another-name')
     line1 = pyficache.getline('another-name', 1)
     line2 = pyficache.getline(__file__, 1)
     self.assertEqual(line1, line2,
                      'Both lines should be the same via remap_file')
     filename = pyficache.remove_remap_file('another-name')
     self.assertEqual(filename, __file__)
     filename = pyficache.remove_remap_file('another-name')
     self.assertEqual(filename, None)
     return
    def test_remap_lines(self):
        pyficache.remap_file_lines(__file__, 'test2', list(range(10, 12)), 6)

        line5 = pyficache.getline(__file__, 5)
        pyficache.remap_file_lines(__file__, 'test2', 9, 5)
        rline9 = pyficache.getline('test2', 9)
        self.assertEqual(
            line5, rline9, 'lines should be the same via remap_file_line - '
            'remap integer')

        line6 = pyficache.getline(__file__, 6)
        rline10 = pyficache.getline('test2', 10)
        self.assertEqual(
            line6, rline10, 'lines should be the same via remap_file_line - '
            'range')

        line7 = pyficache.getline(__file__, 7)
        rline11 = pyficache.getline('test2', 11)
        self.assertEqual(
            line7, rline11, 'lines should be the same via remap_file_line - '
            'range')

        line8 = pyficache.getline(__file__, 8)
        pyficache.remap_file_lines(__file__, None, 20, 8)
        rline20 = pyficache.getline(__file__, 20)
        self.assertEqual(
            line8, rline20, 'lines should be the same via remap_file_line - '
            'None file')
        return
Example #3
0
    def event_processor(self, frame, event, event_arg, prompt='trepan2'):
        'command event processor: reading a commands do something with them.'
        self.frame     = frame
        self.event     = event
        self.event_arg = event_arg

        filename = frame.f_code.co_filename
        lineno   = frame.f_lineno
        if sys.version_info[0] == 2 and sys.version_info[1] <= 4:
            line = None
        else:
            line = linecache.getline(filename, lineno, frame.f_globals)
            pass
        if not line:
            opts = {'output': 'plain',
                    'reload_on_change': self.settings('reload'),
                    'strip_nl': False}
            line = pyficache.getline(filename, lineno, opts)
        self.current_source_text = line
        if self.settings('skip'):
            if Mbytecode.is_def_stmt(line, frame):
                return True
            if Mbytecode.is_class_def(line, frame):
                return True
            pass
        self.thread_name = Mthread.current_thread_name()
        self.frame_thread_name = self.thread_name
        if self.thread_name != 'MainThread':
            prompt += ':' + self.thread_name
            pass
        self.prompt_str = '%s%s%s ' % ('(' * self.debug_nest,
                                       prompt,
                                       ')' * self.debug_nest)
        self.process_commands()
        return True
Example #4
0
    def event_processor(self, frame, event, event_arg, prompt='Trepan'):
        'command event processor: reading a commands do something with them.'
        self.frame = frame
        self.event = event
        self.event_arg = event_arg

        filename = frame.f_code.co_filename
        lineno = frame.f_lineno
        line = linecache.getline(filename, lineno, frame.f_globals)
        if not line:
            opts = {
                'output': 'plain',
                'reload_on_change': self.settings('reload'),
                'strip_nl': False
            }
            line = pyficache.getline(filename, lineno, opts)
        self.current_source_text = line
        if self.settings('skip') is not None:
            if Mbytecode.is_def_stmt(line, frame):
                return True
            if Mbytecode.is_class_def(line, frame):
                return True
            pass
        self.thread_name = Mthread.current_thread_name()
        self.frame_thread_name = self.thread_name
        self.process_commands()
        return True
Example #5
0
    def event_processor(self, frame, event, event_arg, prompt='trepan2'):
        'command event processor: reading a commands do something with them.'
        self.frame = frame
        self.event = event
        self.event_arg = event_arg

        filename = frame.f_code.co_filename
        lineno = frame.f_lineno
        if sys.version_info[0] == 2 and sys.version_info[1] <= 4:
            line = None
        else:
            line = linecache.getline(filename, lineno, frame.f_globals)
            pass
        if not line:
            opts = {
                'output': 'plain',
                'reload_on_change': self.settings('reload'),
                'strip_nl': False
            }
            line = pyficache.getline(filename, lineno, opts)
        self.current_source_text = line
        if self.settings('skip') is not None:
            if Mbytecode.is_def_stmt(line, frame):
                return True
            if Mbytecode.is_class_def(line, frame):
                return True
            pass
        self.thread_name = Mthread.current_thread_name()
        self.frame_thread_name = self.thread_name
        self.set_prompt(prompt)
        self.process_commands()
        if filename == '<string>': pyficache.remove_remap_file('<string>')
        return True
Example #6
0
    def event_processor(self, frame, event, event_arg, prompt="Trepan"):
        "command event processor: reading a commands do something with them."
        self.frame = frame
        self.event = event
        self.event_arg = event_arg

        filename = frame.f_code.co_filename
        lineno = frame.f_lineno
        line = linecache.getline(filename, lineno, frame.f_globals)
        if not line:
            opts = {
                "output": "plain",
                "reload_on_change": self.settings("reload"),
                "strip_nl": False,
            }
            line = pyficache.getline(filename, lineno, opts)
        self.current_source_text = line
        if self.settings("skip") is not None:
            if Mbytecode.is_def_stmt(line, frame):
                return True
            if Mbytecode.is_class_def(line, frame):
                return True
            pass
        self.thread_name = Mthread.current_thread_name()
        self.frame_thread_name = self.thread_name
        self.process_commands()
        return True
Example #7
0
    def event_processor(self, frame, event, event_arg, prompt='Trepan'):
        'command event processor: reading a commands do something with them.'
        self.frame     = frame
        self.event     = event
        self.event_arg = event_arg

        filename = frame.f_code.co_filename
        lineno   = frame.f_lineno
        line     = linecache.getline(filename, lineno, frame.f_globals)
        if not line:
            opts = {'output': 'plain',
                    'reload_on_change': self.settings('reload'),
                    'strip_nl': False}
            line = pyficache.getline(filename, lineno, opts)
        self.current_source_text = line
        if self.settings('skip') is not None:
            if Mbytecode.is_def_stmt(line, frame):
                return True
            if Mbytecode.is_class_def(line, frame):
                return True
            pass
        self.thread_name = Mthread.current_thread_name()
        self.frame_thread_name = self.thread_name
        self.process_commands()
        return True
Example #8
0
    def event_processor(self, frame, event, event_arg, prompt="trepan2"):
        "command event processor: reading a commands do something with them."
        self.frame = frame
        self.event = event
        self.event_arg = event_arg

        filename = frame.f_code.co_filename
        lineno = frame.f_lineno
        if sys.version_info[0] == 2 and sys.version_info[1] <= 4:
            line = None
        else:
            line = linecache.getline(filename, lineno, frame.f_globals)
            pass
        if not line:
            opts = {
                "output": "plain",
                "reload_on_change": self.settings("reload"),
                "strip_nl": False,
            }
            line = pyficache.getline(filename, lineno, opts)
        self.current_source_text = line
        if self.settings("skip") is not None:
            if Mbytecode.is_def_stmt(line, frame):
                return True
            if Mbytecode.is_class_def(line, frame):
                return True
            pass
        self.thread_name = Mthread.current_thread_name()
        self.frame_thread_name = self.thread_name
        self.set_prompt(prompt)
        self.process_commands()
        if filename == "<string>":
            pyficache.remove_remap_file("<string>")
        return True
Example #9
0
    def event_processor(self, frame, event, event_arg, prompt='trepan3k'):
        'command event processor: reading a commands do something with them.'
        self.frame = frame
        self.event = event
        self.event_arg = event_arg

        filename = frame.f_code.co_filename
        lineno = frame.f_lineno
        line = linecache.getline(filename, lineno, frame.f_globals)
        if not line:
            opts = {
                'output': 'plain',
                'reload_on_change': self.settings('reload'),
                'strip_nl': False
            }
            m = re.search('^<frozen (.*)>', filename)
            if m and m.group(1):
                filename = pyficache.unmap_file(m.group(1))
            line = pyficache.getline(filename, lineno, opts)
        self.current_source_text = line
        if self.settings('skip') is not None:
            if Mbytecode.is_def_stmt(line, frame):
                return True
            if Mbytecode.is_class_def(line, frame):
                return True
            pass
        self.thread_name = Mthread.current_thread_name()
        self.frame_thread_name = self.thread_name
        self.set_prompt(prompt)
        self.process_commands()
        if filename == '<string>': pyficache.remove_remap_file('<string>')
        return True
Example #10
0
def format_location(proc_obj):
    """Show where we are. GUI's and front-end interfaces often
    use this to update displays. So it is helpful to make sure
    we give at least some place that's located in a file.
    """
    i_stack = proc_obj.curindex
    if i_stack is None or proc_obj.stack is None:
        return False
    location = {}
    core_obj = proc_obj.core
    dbgr_obj = proc_obj.debugger

    # Evaluation routines like "exec" don't show useful location
    # info. In these cases, we will use the position before that in
    # the stack.  Hence the looping below which in practices loops
    # once and sometimes twice.
    remapped_file = None
    while i_stack >= 0:
        frame_lineno = proc_obj.stack[i_stack]
        i_stack -= 1
        frame, lineno = frame_lineno

        filename = Mstack.frame2file(core_obj, frame)

        location['filename'] = filename
        location['fn_name']  = frame.f_code.co_name
        location['lineno']   = lineno

        if '<string>' == filename and dbgr_obj.eval_string:
            remapped_file = filename
            filename = pyficache.unmap_file(filename)
            if '<string>' == filename:
                fd = tempfile.NamedTemporaryFile(suffix='.py',
                                                 prefix='eval_string',
                                                 delete=False)
                fd.write(bytes(dbgr_obj.eval_string, 'UTF-8'))
                fd.close()
                pyficache.remap_file(fd.name, '<string>')
                filename = fd.name
                pass
            pass

        opts = {
            'reload_on_change' : proc_obj.settings('reload'),
            'output'           : 'plain'
            }
        line = pyficache.getline(filename, lineno, opts)
        if not line:
            line = linecache.getline(filename, lineno,
                                     proc_obj.curframe.f_globals)
            pass

        if line and len(line.strip()) != 0:
            location['text'] = line
            pass
        if '<string>' != filename: break
        pass

    return location
Example #11
0
def format_location(proc_obj):
    """Show where we are. GUI's and front-end interfaces often
    use this to update displays. So it is helpful to make sure
    we give at least some place that's located in a file.
    """
    i_stack = proc_obj.curindex
    if i_stack is None or proc_obj.stack is None:
        return False
    location = {}
    core_obj = proc_obj.core
    dbgr_obj = proc_obj.debugger

    # Evaluation routines like "exec" don't show useful location
    # info. In these cases, we will use the position before that in
    # the stack.  Hence the looping below which in practices loops
    # once and sometimes twice.
    remapped_file = None
    while i_stack >= 0:
        frame_lineno = proc_obj.stack[i_stack]
        i_stack -= 1
        frame, lineno = frame_lineno

        filename = Mstack.frame2file(core_obj, frame)

        location['filename'] = filename
        location['fn_name'] = frame.f_code.co_name
        location['lineno'] = lineno

        if '<string>' == filename and dbgr_obj.eval_string:
            remapped_file = filename
            filename = pyficache.unmap_file(filename)
            if '<string>' == filename:
                fd = tempfile.NamedTemporaryFile(suffix='.py',
                                                 prefix='eval_string',
                                                 delete=False)
                fd.write(bytes(dbgr_obj.eval_string, 'UTF-8'))
                fd.close()
                pyficache.remap_file(fd.name, '<string>')
                filename = fd.name
                pass
            pass

        opts = {
            'reload_on_change': proc_obj.settings('reload'),
            'output': 'plain'
        }
        line = pyficache.getline(filename, lineno, opts)
        if not line:
            line = linecache.getline(filename, lineno,
                                     proc_obj.curframe.f_globals)
            pass

        if line and len(line.strip()) != 0:
            location['text'] = line
            pass
        if '<string>' != filename: break
        pass

    return location
 def test_stat(self):
     self.assertEqual(None, pyficache.stat(__file__, use_cache_only=True),
                      ("stat for %s should be None - "
                       "just cleared cache." % __file__))
     line = pyficache.getline(__file__, 1)
     self.assertTrue(line)
     self.assertTrue(pyficache.stat(__file__),
                     "file %s should now have a stat" % __file__)
     return
Example #13
0
    def event_processor(self, frame, event, event_arg, prompt="trepan3k"):
        """
        command event processor: reading a commands do something with them.

        See https://docs.python.org/3/library/sys.html#sys.settrace
        for how this protocol works and what the events means.

        Of particular note those is what we return:

            The local trace function should return a reference to
            itself (or to another function for further tracing in that
            scope), or None to turn off tracing in that scope.

            If there is any error occurred in the trace function, it
            will be unset, just like settrace(None) is called.
        """

        self.frame = frame
        self.event = event
        self.event_arg = event_arg

        filename = frame.f_code.co_filename
        lineno = frame.f_lineno
        line = linecache.getline(filename, lineno, frame.f_globals)
        if not line:
            opts = {
                "output": "plain",
                "reload_on_change": self.settings("reload"),
                "strip_nl": False,
            }
            m = re.search("^<frozen (.*)>", filename)
            if m and m.group(1):
                filename = pyficache.unmap_file(m.group(1))
            line = pyficache.getline(filename, lineno, opts)
        self.current_source_text = line
        if self.settings("skip") is not None:
            if is_def_stmt(line, frame):
                return self.event_processor
            if is_class_def(line, frame):
                return self.event_processor
            pass
        self.thread_name = Mthread.current_thread_name()
        self.frame_thread_name = self.thread_name
        self.set_prompt(prompt)
        self.process_commands()
        if filename == "<string>":
            pyficache.remove_remap_file("<string>")
        return self.event_processor
Example #14
0
 def frame_setup(frame):
     filename = frame.f_code.co_filename
     lineno = frame.f_lineno
     line = linecache.getline(filename, lineno, frame.f_globals)
     if not line:
         opts = {
             "output": "plain",
             "reload_on_change": self.settings("reload"),
             "strip_nl": False,
         }
         m = re.search("^<frozen (.*)>", filename)
         if m and m.group(1):
             filename = pyficache.unmap_file(m.group(1))
         line = pyficache.getline(filename, lineno, opts)
     self.current_source_text = line
     return line, filename
Example #15
0
def deparse_getline(code, filename, line_number, opts):
    # Would love to figure out how to deparse the entire module
    # but with all many-time rewritten import stuff, I still
    # can't figure out how to get from "<frozen importlib>" to
    # the module's code.
    # So for now, we'll have to do this on a function by function
    # bases. Fortunately pyficache has the ability to remap line
    # numbers
    text = deparse_fn(code)
    if text:
        prefix = os.path.basename(filename) + "_"
        remapped_filename = source_tempfile_remap(prefix, text)
        lines = text.split("\n")
        first_line = code.co_firstlineno
        pyficache.remap_file_lines(filename, remapped_filename, range(first_line, first_line + len(lines)), 1)
        return remapped_filename, pyficache.getline(filename, line_number, opts)
    return None, None
Example #16
0
def deparse_getline(code, filename, line_number, opts):
    # Would love to figure out how to deparse the entire module
    # but with all many-time rewritten import stuff, I still
    # can't figure out how to get from "<frozen importlib>" to
    # the module's code.
    # So for now, we'll have to do this on a function by function
    # bases. Fortunately pyficache has the ability to remap line
    # numbers
    text = deparse_fn(code)
    if text:
        prefix = os.path.basename(filename) + "_"
        remapped_filename = source_tempfile_remap(prefix, text)
        lines = text.split("\n")
        first_line = code.co_firstlineno
        pyficache.remap_file_lines(filename, remapped_filename,
                                   range(first_line, first_line+len(lines)),
                                   1)
        return remapped_filename, pyficache.getline(filename, line_number, opts)
    return None, None
    def test_cached(self):
        myfile = __file__
        self.assertEqual(
            False, pyficache.is_cached(myfile),
            ("file %s shouldn't be cached - just cleared cache." % myfile))
        line = pyficache.getline(__file__, 1)
        assert line
        self.assertEqual(True, pyficache.is_cached(__file__),
                         "file %s should now be cached" % __file__)
        # self.assertEqual(false, pyficache.cached_script?('./short-file'),
        #              "Should not find './short-file' in SCRIPT_LINES__")
        # self.assertEqual(True, 78 < pyficache.size(__file__))

        # Unlike Ruby, Python doesn't have SCRIPT_LINES__
        # old_dir = os.getcwd()
        # os.chdir(os.path.dirname(os.path.abspath((__file__))))
        # load('./short-file', 0)
        # self.assertEqual(True, pyficache.cached_script?('./short-file'),
        #                "Should be able to find './short-file' "
        #                "in SCRIPT_LINES__")
        # os.chdir(old_dir)
        return
Example #18
0
def deparse_getline(code, filename, line_number, opts):
    # I Would like to figure out how to deparse the entire module,
    # instead doing this on a line-by-line basis.
    # But because th Python import library routines have been rewritten many times, I
    # can't figure out how to get from "<frozen importlib>" to
    # the module's code.
    # So for now, we'll have to do this on a function by function
    # bases. Fortunately pyficache has the ability to remap line
    # numbers
    deparsed = deparse_fn(code)
    text = deparsed.text.strip()
    if text:
        prefix = os.path.basename(filename) + "_"
        remapped_filename = source_tempfile_remap(prefix, text)
        lines = text.split("\n")
        first_line = code.co_firstlineno
        linemap = [(line_no, deparsed.source_linemap[line_no])
                   for line_no in sorted(deparsed.source_linemap.keys())]
        print("XXXX", linemap)
        pyficache.remap_file_lines(filename, remapped_filename, linemap)
        return remapped_filename, pyficache.getline(filename, line_number,
                                                    opts)
    return None, None
Example #19
0
    def run(self, args):
        proc = self.proc
        dbg_obj = self.core.debugger
        listsize = dbg_obj.settings["listsize"]
        filename, first, last = parse_list_cmd(proc, args, listsize)
        curframe = proc.curframe
        if filename is None:
            return
        filename = pyficache.unmap_file(
            pyficache.resolve_name_to_path(filename))

        # We now have range information. Do the listing.
        max_line = pyficache.size(filename)
        if max_line is None:
            bytecode = curframe.f_code

            if bytecode not in deparse_cache.keys():
                self.errmsg(
                    'No file %s found; using "deparse" command instead to show source'
                    % filename)
            proc.commands["deparse"].run(["deparse"])
            return

        canonic_filename = osp.realpath(osp.normcase(filename))

        if first > max_line:
            self.errmsg('Bad start line %d - file "%s" has only %d lines' %
                        (first, filename, max_line))
            return

        if last > max_line:
            self.msg("End position changed to last line %d " % max_line)
            last = max_line

        bplist = self.core.bpmgr.bplist
        opts = {
            "reload_on_change": self.settings["reload"],
            "output": self.settings["highlight"],
            "strip_nl": False,
        }

        if "style" in self.settings:
            opts["style"] = self.settings["style"]

        if first <= 0:
            first = 1
        try:
            for lineno in range(first, last + 1):
                line = pyficache.getline(filename, lineno, opts)
                if line is None:
                    line = linecache.getline(filename, lineno,
                                             proc.frame.f_globals)
                    pass
                if line is None:
                    self.msg("[EOF]")
                    break
                else:
                    line = line.rstrip("\n")
                    s = proc._saferepr(lineno).rjust(3)
                    if len(s) < 5:
                        s += " "
                    if (
                            canonic_filename,
                            lineno,
                    ) in list(bplist.keys()):
                        bp = bplist[(
                            canonic_filename,
                            lineno,
                        )][0]
                        a_pad = "%02d" % bp.number
                        s += bp.icon_char()
                    else:
                        s += " "
                        a_pad = "  "
                        pass
                    if curframe and lineno == inspect.getlineno(curframe):
                        s += "->"
                        if "plain" != self.settings["highlight"]:
                            s = colorize("bold", s)
                    else:
                        s += a_pad
                        pass
                    self.msg(s + "\t" + line)
                    proc.list_lineno = lineno
                    pass
                pass
            pass
        except KeyboardInterrupt:
            pass
        return False
    def test_basic(self):
        filename = __file__
        if '.pyc' == filename[-4:]:
            filename = filename[:-1]
            pass

        fp = open(filename, 'r')
        compare_lines = fp.readlines()
        self.assertTrue(
            compare_lines,
            "Should have been able to read %s for comparing" % filename)
        fp.close()

        # Test getlines to read this file.
        lines = pyficache.getlines(__file__)
        self.assertEqual(
            compare_lines, lines, 'We should get exactly the same lines as '
            'reading this file.')

        # Test getline to read this file. The file should now be cached,
        # so internally a different set of routines are used.
        test_line = 2
        line = pyficache.getline(__file__, test_line, {'strip_nl': False})
        self.assertEqual(
            compare_lines[test_line - 1], line,
            'We should get exactly the same line as reading '
            'this file.')
        line = pyficache.getline(__file__, test_line, {'output': 'light'})
        self.assertTrue(
            line.index('Unit test for pyficache') > 0,
            'Terminal formatted line 2 should have '
            '"Unit test for pyficache"')

        # Test getting the line via a relative file name
        old_dir = os.getcwd()
        os.chdir(os.path.dirname(os.path.abspath((__file__))))
        short_file = os.path.basename(__file__)
        test_line = 10
        line = pyficache.getline(short_file, test_line, {'strip_nl': False})
        self.assertEqual(
            compare_lines[test_line - 1], line,
            'Short filename lookup on %s should work' % short_file)
        os.chdir(old_dir)

        # Write a temporary file; read contents, rewrite it and check that
        # we get a change when calling getline.
        (fd, path) = mkstemp(prefix="pyfcache", suffix='.txt')
        test_string = "Now is the time.\n"
        with open(path, 'w') as f:
            f.write(test_string)
            f.close()
            pass
        line = pyficache.getline(path, 1, {'strip_nl': False})
        self.assertEqual(
            test_string, line, "C'mon - a simple line test like this worked "
            "before.")
        with open(path, 'w') as f:
            test_string = "Now is another time."
            f.write(test_string)
            f.close()
            pass

        pyficache.checkcache()
        line = pyficache.getline(path, 1)
        self.assertEqual(test_string, line,
                         "checkcache should have reread the temporary file.")
        try:
            os.remove(path)
        except:
            pass
        return
Example #21
0
    def run(self, args):
        proc = self.proc
        dbg_obj = self.core.debugger
        listsize = dbg_obj.settings['listsize']
        filename, first, last = parse_list_cmd(proc, args, listsize)
        curframe = proc.curframe
        if filename is None: return
        filename = pyficache.unmap_file(pyficache.pyc2py(filename))

        # We now have range information. Do the listing.
        max_line = pyficache.size(filename)
        if max_line is None:
            self.errmsg(
                'No file %s found; using "deparse" command instead to show source'
                % filename)
            proc.commands['deparse'].run(['deparse'])
            return

        canonic_filename = os.path.realpath(os.path.normcase(filename))

        if first > max_line:
            self.errmsg('Bad start line %d - file "%s" has only %d lines' %
                        (first, filename, max_line))
            return

        if last > max_line:
            self.msg('End position changed to last line %d ' % max_line)
            last = max_line

        bplist = self.core.bpmgr.bplist
        opts = {
            'reload_on_change': self.settings['reload'],
            'output': self.settings['highlight'],
            'strip_nl': False,
        }

        if 'style' in self.settings:
            opts['style'] = self.settings['style']

        if first <= 0:
            first = 1
        try:
            for lineno in range(first, last + 1):
                line = pyficache.getline(filename, lineno, opts)
                if line is None:
                    line = linecache.getline(filename, lineno,
                                             proc.frame.f_globals)
                    pass
                if line is None:
                    self.msg('[EOF]')
                    break
                else:
                    line = line.rstrip('\n')
                    s = proc._saferepr(lineno).rjust(3)
                    if len(s) < 5: s += ' '
                    if (
                            canonic_filename,
                            lineno,
                    ) in list(bplist.keys()):
                        bp = bplist[(
                            canonic_filename,
                            lineno,
                        )][0]
                        a_pad = '%02d' % bp.number
                        s += bp.icon_char()
                    else:
                        s += ' '
                        a_pad = '  '
                        pass
                    if curframe and lineno == inspect.getlineno(curframe):
                        s += '->'
                        if 'plain' != self.settings['highlight']:
                            s = colorize('bold', s)
                    else:
                        s += a_pad
                        pass
                    self.msg(s + '\t' + line)
                    proc.list_lineno = lineno
                    pass
                pass
            pass
        except KeyboardInterrupt:
            pass
        return False
Example #22
0
def print_location(proc_obj):
    """Show where we are. GUI's and front-end interfaces often
    use this to update displays. So it is helpful to make sure
    we give at least some place that's located in a file.
    """
    i_stack = proc_obj.curindex
    if i_stack is None or proc_obj.stack is None:
        return False
    core_obj = proc_obj.core
    dbgr_obj = proc_obj.debugger
    intf_obj = dbgr_obj.intf[-1]

    # Evaluation routines like "exec" don't show useful location
    # info. In these cases, we will use the position before that in
    # the stack.  Hence the looping below which in practices loops
    # once and sometimes twice.
    remapped_file = None
    source_text = None
    while i_stack >= 0:
        frame_lineno = proc_obj.stack[i_stack]
        i_stack -= 1
        frame, lineno = frame_lineno

        #         # Next check to see that local variable breadcrumb exists and
        #         # has the magic dynamic value.
        #         # If so, it's us and we don't normally show this.a
        #         if 'breadcrumb' in frame.f_locals:
        #             if self.run == frame.f_locals['breadcrumb']:
        #                 break

        filename = Mstack.frame2file(core_obj, frame, canonic=False)
        if '<string>' == filename and dbgr_obj.eval_string:
            remapped_file = filename
            filename = pyficache.unmap_file(filename)
            if '<string>' == filename:
                remapped = cmdfns.source_tempfile_remap(
                    'eval_string', dbgr_obj.eval_string)
                pyficache.remap_file(filename, remapped)
                filename = remapped
                lineno = pyficache.unmap_file_line(filename, lineno)
                pass
            pass
        elif '<string>' == filename:
            source_text = deparse_fn(frame.f_code)
            filename = "<string: '%s'>" % source_text
            pass
        else:
            m = re.search('^<frozen (.*)>', filename)
            if m and m.group(1) in pyficache.file2file_remap:
                remapped_file = pyficache.file2file_remap[m.group(1)]
                pass
            elif filename in pyficache.file2file_remap:
                remapped_file = pyficache.unmap_file(filename)
                # FIXME: a remapped_file shouldn't be the same as its unmapped version
                if remapped_file == filename:
                    remapped_file = None
                    pass
                pass
            elif m and m.group(1) in sys.modules:
                remapped_file = m.group(1)
                pyficache.remap_file(filename, remapped_file)
            pass

        opts = {
            'reload_on_change': proc_obj.settings('reload'),
            'output': proc_obj.settings('highlight')
        }

        if 'style' in proc_obj.debugger.settings:
            opts['style'] = proc_obj.settings('style')

        pyficache.update_cache(filename)
        line = pyficache.getline(filename, lineno, opts)
        if not line:
            if (not source_text and filename.startswith("<string: ")
                    and proc_obj.curframe.f_code):
                # Deparse the code object into a temp file and remap the line from code
                # into the corresponding line of the tempfile
                co = proc_obj.curframe.f_code
                temp_filename, name_for_code = deparse_and_cache(
                    co, proc_obj.errmsg)
                lineno = 1
                # _, lineno = pyficache.unmap_file_line(temp_filename, lineno, True)
                if temp_filename:
                    filename = temp_filename
                pass

            else:
                # FIXME:
                if source_text:
                    lines = source_text.split("\n")
                    temp_name = 'string-'
                else:
                    # try with good ol linecache and consider fixing pyficache
                    lines = linecache.getlines(filename)
                    temp_name = filename
                if lines:
                    # FIXME: DRY code with version in cmdproc.py print_location
                    prefix = os.path.basename(temp_name).split('.')[0]
                    fd = tempfile.NamedTemporaryFile(suffix='.py',
                                                     prefix=prefix,
                                                     delete=False)
                    with fd:
                        fd.write(''.join(lines))
                        remapped_file = fd.name
                        pyficache.remap_file(remapped_file, filename)
                    fd.close()
                    pass
            line = linecache.getline(filename, lineno,
                                     proc_obj.curframe.f_globals)
            if not line:
                m = re.search('^<frozen (.*)>', filename)
                if m and m.group(1):
                    remapped_file = m.group(1)
                    try_module = sys.modules.get(remapped_file)
                    if (try_module and inspect.ismodule(try_module)
                            and hasattr(try_module, '__file__')):
                        remapped_file = sys.modules[remapped_file].__file__
                        pyficache.remap_file(filename, remapped_file)
                        line = linecache.getline(remapped_file, lineno,
                                                 proc_obj.curframe.f_globals)
                    else:
                        remapped_file = m.group(1)
                        code = proc_obj.curframe.f_code
                        filename, line = cmdfns.deparse_getline(
                            code, remapped_file, lineno, opts)
                    pass
            pass

        try:
            match, reason = Mstack.check_path_with_frame(frame, filename)
            if not match:
                if filename not in warned_file_mismatches:
                    proc_obj.errmsg(reason)
                    warned_file_mismatches.add(filename)
        except:
            pass

        fn_name = frame.f_code.co_name
        last_i = frame.f_lasti
        print_source_location_info(intf_obj.msg,
                                   filename,
                                   lineno,
                                   fn_name,
                                   remapped_file=remapped_file,
                                   f_lasti=last_i)
        if line and len(line.strip()) != 0:
            if proc_obj.event:
                print_source_line(intf_obj.msg, lineno, line,
                                  proc_obj.event2short[proc_obj.event])
            pass
        if '<string>' != filename: break
        pass

    if proc_obj.event in ['return', 'exception']:
        val = proc_obj.event_arg
        intf_obj.msg('R=> %s' % proc_obj._saferepr(val))
        pass
    return True
Example #23
0
    def run(self, args):
        filename, first, last = self.parse_list_cmd(args[1:])
        curframe = self.proc.curframe
        if filename is None: return
        filename = pyc2py(filename)

        # We now have range information. Do the listing.
        max_line = pyficache.size(filename)
        if max_line is None:
            self.errmsg('No file %s found' % filename)
            return

        canonic_filename = os.path.realpath(os.path.normcase(filename))
        if first > max_line:
            self.errmsg('Bad start line %d - file "%s" has only %d lines' %
                        (first, filename, max_line))
            return

        if last > max_line:
            self.msg('End position changed to last line %d ' % max_line)
            last = max_line

        bplist = self.core.bpmgr.bplist
        opts = {
            'reload_on_change': self.settings['reload'],
            'output': self.settings['highlight'],
            'strip_nl': False
        }

        try:
            for lineno in range(first, last + 1):
                line = pyficache.getline(filename, lineno, opts)
                if line is None:
                    line = linecache.getline(filename, lineno,
                                             self.proc.frame.f_globals)
                    pass
                if line is None:
                    self.msg('[EOF]')
                    break
                else:
                    line = line.rstrip('\n')
                    s = self.proc._saferepr(lineno).rjust(3)
                    if len(s) < 5: s += ' '
                    if (
                            canonic_filename,
                            lineno,
                    ) in list(bplist.keys()):
                        bp = bplist[(
                            canonic_filename,
                            lineno,
                        )][0]
                        a_pad = '%02d' % bp.number
                        s += bp.icon_char()
                    else:
                        s += ' '
                        a_pad = '  '
                        pass
                    if curframe and lineno == inspect.getlineno(curframe) \
                       and filename == curframe.f_code.co_filename:
                        s += '->'
                    else:
                        s += a_pad
                        pass
                    self.msg(s + '\t' + line)
                    self.proc.list_lineno = lineno
                    pass
                pass
        except KeyboardInterrupt:
            pass
        return False
Example #24
0
def print_location(proc_obj):
    """Show where we are. GUI's and front-end interfaces often
    use this to update displays. So it is helpful to make sure
    we give at least some place that's located in a file.
    """
    i_stack = proc_obj.curindex
    if i_stack is None or proc_obj.stack is None:
        return False
    core_obj = proc_obj.core
    dbgr_obj = proc_obj.debugger
    intf_obj = dbgr_obj.intf[-1]

    # Evaluation routines like "exec" don't show useful location
    # info. In these cases, we will use the position before that in
    # the stack.  Hence the looping below which in practices loops
    # once and sometimes twice.
    remapped_file = None
    while i_stack >= 0:
        frame_lineno = proc_obj.stack[i_stack]
        i_stack -= 1
        frame, lineno = frame_lineno

        #         # Next check to see that local variable breadcrumb exists and
        #         # has the magic dynamic value.
        #         # If so, it's us and we don't normally show this.a
        #         if 'breadcrumb' in frame.f_locals:
        #             if self.run == frame.f_locals['breadcrumb']:
        #                 break

        filename = Mstack.frame2file(core_obj, frame, canonic=False)
        if '<string>' == filename and dbgr_obj.eval_string:
            remapped_file = filename
            filename = pyficache.unmap_file(filename)
            if '<string>' == filename:
                fd = tempfile.NamedTemporaryFile(suffix='.py',
                                                 prefix='eval_string',
                                                 delete=False)
                with fd:
                    fd.write(dbgr_obj.eval_string)
                    fd.close()
                    pass
                pyficache.remap_file(fd.name, '<string>')
                filename = fd.name
                pass
            pass
        else:
            if filename in pyficache.file2file_remap:
                remapped_file = pyficache.unmap_file(filename)
                # FIXME: a remapped_file shouldn't be the same as its unmapped version
                if remapped_file == filename:
                    remapped_file = None
                    pass
                pass
            pass

        opts = {
            'reload_on_change': proc_obj.settings('reload'),
            'output': proc_obj.settings('highlight')
        }

        if 'style' in proc_obj.debugger.settings:
            opts['style'] = proc_obj.settings('style')

        pyficache.update_cache(filename)
        line = pyficache.getline(filename, lineno, opts)
        if not line:
            # FIXME:
            # try with good ol linecache and consider fixing pyficache
            lines = linecache.getlines(filename)
            if lines:
                # FIXME: DRY code with version in cmdproc.py print_location
                prefix = os.path.basename(filename).split('.')[0]
                fd = tempfile.NamedTemporaryFile(suffix='.py',
                                                 prefix=prefix,
                                                 delete=False)
                with fd:
                    fd.write(''.join(lines))
                    remapped_file = fd.name
                    pyficache.remap_file(remapped_file, filename)
                fd.close()
                pass
            line = linecache.getline(filename, lineno,
                                     proc_obj.curframe.f_globals)
            pass

        fn_name = frame.f_code.co_name
        last_i = frame.f_lasti
        print_source_location_info(intf_obj.msg,
                                   filename,
                                   lineno,
                                   fn_name,
                                   remapped_file=remapped_file,
                                   f_lasti=last_i)
        if line and len(line.strip()) != 0:
            if proc_obj.event:
                print_source_line(intf_obj.msg, lineno, line,
                                  proc_obj.event2short[proc_obj.event])
            pass
        if '<string>' != filename: break
        pass

    if proc_obj.event in ['return', 'exception']:
        val = proc_obj.event_arg
        intf_obj.msg('R=> %s' % proc_obj._saferepr(val))
        pass
    return True
Example #25
0
def print_location(proc_obj):
    """Show where we are. GUI's and front-end interfaces often
    use this to update displays. So it is helpful to make sure
    we give at least some place that's located in a file.
    """
    i_stack = proc_obj.curindex
    if i_stack is None or proc_obj.stack is None:
        return False
    core_obj = proc_obj.core
    dbgr_obj = proc_obj.debugger
    intf_obj = dbgr_obj.intf[-1]

    # Evaluation routines like "exec" don't show useful location
    # info. In these cases, we will use the position before that in
    # the stack.  Hence the looping below which in practices loops
    # once and sometimes twice.
    remapped_file = None
    while i_stack >= 0:
        frame_lineno = proc_obj.stack[i_stack]
        i_stack -= 1
        frame, lineno = frame_lineno

        #         # Next check to see that local variable breadcrumb exists and
        #         # has the magic dynamic value.
        #         # If so, it's us and we don't normally show this.a
        #         if 'breadcrumb' in frame.f_locals:
        #             if self.run == frame.f_locals['breadcrumb']:
        #                 break

        filename = Mstack.frame2file(core_obj, frame, canonic=False)
        if '<string>' == filename and dbgr_obj.eval_string:
            remapped_file = filename
            filename = pyficache.unmap_file(filename)
            if '<string>' == filename:
                remapped = cmdfns.source_tempfile_remap(
                    'eval_string', dbgr_obj.eval_string)
                pyficache.remap_file(filename, remapped)
                filename = remapped
                pass
            pass
        else:
            m = re.search('^<frozen (.*)>', filename)
            if m and m.group(1) in pyficache.file2file_remap:
                remapped_file = pyficache.file2file_remap[m.group(1)]
                pass
            elif filename in pyficache.file2file_remap:
                remapped_file = pyficache.unmap_file(filename)
                # FIXME: a remapped_file shouldn't be the same as its unmapped version
                if remapped_file == filename:
                    remapped_file = None
                    pass
                pass
            elif m and m.group(1) in sys.modules:
                remapped_file = m.group(1)
                pyficache.remap_file(filename, remapped_file)
            pass

        code = frame.f_code
        fn_name = code.co_name
        last_i = frame.f_lasti

        opts = {
            'reload_on_change': proc_obj.settings('reload'),
            'output': proc_obj.settings('highlight')
        }

        if 'style' in proc_obj.debugger.settings:
            opts['style'] = proc_obj.settings('style')

        line = pyficache.getline(filename, lineno, opts)
        if not line:
            line = linecache.getline(filename, lineno,
                                     proc_obj.curframe.f_globals)
            if not line:
                m = re.search('^<frozen (.*)>', filename)
                if m and m.group(1):
                    remapped_file = m.group(1)
                    try_module = sys.modules.get(remapped_file)
                    if (try_module and inspect.ismodule(try_module)
                            and hasattr(try_module, '__file__')):
                        remapped_file = sys.modules[remapped_file].__file__
                        pyficache.remap_file(filename, remapped_file)
                        line = linecache.getline(remapped_file, lineno,
                                                 proc_obj.curframe.f_globals)
                    else:
                        remapped_file = m.group(1)
                        filename, line = cmdfns.deparse_getline(
                            code, remapped_file, lineno, opts)
                    pass
            pass

        try:
            match, reason = Mstack.check_path_with_frame(frame, filename)
            if not match:
                if filename not in warned_file_mismatches:
                    proc_obj.errmsg(reason)
                    warned_file_mismatches.add(filename)
        except:
            pass

        print_source_location_info(intf_obj.msg,
                                   filename,
                                   lineno,
                                   fn_name,
                                   remapped_file=remapped_file,
                                   f_lasti=last_i)

        if line and len(line.strip()) != 0:
            if proc_obj.event:
                print_source_line(intf_obj.msg, lineno, line,
                                  proc_obj.event2short[proc_obj.event])
            pass
        if '<string>' != filename: break
        pass

    if proc_obj.event in ['return', 'exception']:
        val = proc_obj.event_arg
        intf_obj.msg('R=> %s' % proc_obj._saferepr(val))
        pass
    return True
Example #26
0
def print_location(proc_obj):
    """Show where we are. GUI's and front-end interfaces often
    use this to update displays. So it is helpful to make sure
    we give at least some place that's located in a file.
    """
    i_stack = proc_obj.curindex
    if i_stack is None or proc_obj.stack is None:
        return False
    core_obj = proc_obj.core
    dbgr_obj = proc_obj.debugger
    intf_obj = dbgr_obj.intf[-1]

    # Evaluation routines like "exec" don't show useful location
    # info. In these cases, we will use the position before that in
    # the stack.  Hence the looping below which in practices loops
    # once and sometimes twice.
    remapped_file = None
    while i_stack >= 0:
        frame_lineno = proc_obj.stack[i_stack]
        i_stack -= 1
        frame, lineno = frame_lineno

#         # Next check to see that local variable breadcrumb exists and
#         # has the magic dynamic value.
#         # If so, it's us and we don't normally show this.a
#         if 'breadcrumb' in frame.f_locals:
#             if self.run == frame.f_locals['breadcrumb']:
#                 break

        filename = Mstack.frame2file(core_obj, frame)
        if '<string>' == filename and dbgr_obj.eval_string:
            remapped_file = filename
            filename = pyficache.unmap_file(filename)
            if '<string>' == filename:
                fd = tempfile.NamedTemporaryFile(suffix='.py',
                                                 prefix='eval_string',
                                                 delete=False)
                fd.write(dbgr_obj.eval_string)
                fd.close()
                pyficache.remap_file(fd.name, '<string>')
                filename = fd.name
                pass
            pass

        fn_name = frame.f_code.co_name
        print_source_location_info(intf_obj.msg, filename, lineno, fn_name,
                                   remapped_file = remapped_file)
                                   # proc_obj.curframe.f_lasti)

        opts = {
            'reload_on_change' : proc_obj.settings('reload'),
            'output'           : proc_obj.settings('highlight')
            }
        line = pyficache.getline(filename, lineno, opts)
        if not line:
            if sys.version_info[1] <= 4:
                # Python 2.4 and before doesn't have 3-arg getline
                line = linecache.getline(filename, lineno)
            else:
                line = linecache.getline(filename, lineno,
                                         proc_obj.curframe.f_globals)
                pass
            pass

        if line and len(line.strip()) != 0:
            if proc_obj.event:
                print_source_line(intf_obj.msg, lineno, line,
                                  proc_obj.event2short[proc_obj.event])
            pass
        if '<string>' != filename: break
        pass

    if proc_obj.event in ['return', 'exception']:
        val = proc_obj.event_arg
        intf_obj.msg('R=> %s' % proc_obj._saferepr(val))
        pass
    return True
Example #27
0
    except:
        if errmsg_fn:
            errmsg_fn(sys.exc_info()[1])
            errmsg_fn("error in deparsing code at offset %d" % last_i)

    if not nodeInfo:
        nodeInfo = deparsed_find((name, last_i), deparsed, co)
    return deparsed, nodeInfo


# Demo it
if __name__ == '__main__':
    import inspect

    def msg(msg_str):
        print(msg_str)
        return

    def errmsg(msg_str):
        msg('*** ' + msg_str)
        return

    curframe = inspect.currentframe()
    line_no = curframe.f_lineno
    mapped_name, name_for_code = deparse_and_cache(curframe.f_code, errmsg)
    print(pyficache.getline(mapped_name, 7))
    # mapped_name, name_for_code = deparse_offset(curframe.f_code,
    #                                             curframe.f_code.co_name,
    #                                             curframe.f_lasti, errmsg)
    # print(pyficache.getline(mapped_name, 7))
Example #28
0
    def run(self, args):
        filename, first, last = self.parse_list_cmd(args[1:])
        curframe = self.proc.curframe
        if filename is None: return
        m = re.search('^<frozen (.*)>', filename)
        if m and m.group(1):
            filename = m.group(1)
            canonic_filename = pyficache.unmap_file(filename)
        else:
            filename = pyc2py(filename)
            canonic_filename = os.path.realpath(os.path.normcase(filename))

        max_line = pyficache.size(filename)
        # FIXME: Should use the below:
        # max_line = pyficache.maxline(filename)

        # We now have range information. Do the listing.
        if max_line is None:
            self.errmsg('No file %s found' % filename)
            return

        if first > max_line:
            self.errmsg('Bad start line %d - file "%s" has only %d lines'
                        % (first, filename, max_line))
            return

        if last > max_line:
            self.msg('End position changed to last line %d ' % max_line)
            last = max_line

        bplist = self.core.bpmgr.bplist
        opts = {
            'reload_on_change' : self.settings['reload'],
            'output'           : self.settings['highlight'],
            'strip_nl'         : False,
            }

        if 'style' in self.settings:
            opts['style'] = self.settings['style']

        try:
            for lineno in range(first, last+1):
                line = pyficache.getline(filename, lineno, opts)
                if line is None:
                    line = linecache.getline(filename, lineno,
                                             self.proc.frame.f_globals)
                    pass
                if line is None:
                    self.msg('[EOF]')
                    break
                else:
                    line = line.rstrip('\n')
                    s = self.proc._saferepr(lineno).rjust(3)
                    if len(s) < 5: s += ' '
                    if (canonic_filename, lineno,) in list(bplist.keys()):
                        bp    = bplist[(canonic_filename, lineno,)][0]
                        a_pad = '%02d' % bp.number
                        s    += bp.icon_char()
                    else:
                        s    += ' '
                        a_pad = '  '
                        pass
                    if curframe and lineno == inspect.getlineno(curframe):
                        s += '->'
                        if 'plain' != self.settings['highlight']:
                            s = colorize('bold', s)
                    else:
                        s += a_pad
                        pass
                    self.msg(s + '\t' + line)
                    self.proc.list_lineno = lineno
                    pass
                pass
        except KeyboardInterrupt:
            pass
        return False
Example #29
0
def print_location(proc_obj):
    """Show where we are. GUI's and front-end interfaces often
    use this to update displays. So it is helpful to make sure
    we give at least some place that's located in a file.
    """
    i_stack = proc_obj.curindex
    if i_stack is None or proc_obj.stack is None:
        return False
    core_obj = proc_obj.core
    dbgr_obj = proc_obj.debugger
    intf_obj = dbgr_obj.intf[-1]

    # Evaluation routines like "exec" don't show useful location
    # info. In these cases, we will use the position before that in
    # the stack.  Hence the looping below which in practices loops
    # once and sometimes twice.
    remapped_file = None
    source_text = None
    while i_stack >= 0:
        frame_lineno = proc_obj.stack[i_stack]
        i_stack -= 1
        frame, lineno = frame_lineno

        #         # Next check to see that local variable breadcrumb exists and
        #         # has the magic dynamic value.
        #         # If so, it's us and we don't normally show this.a
        #         if 'breadcrumb' in frame.f_locals:
        #             if self.run == frame.f_locals['breadcrumb']:
        #                 break

        filename = Mstack.frame2file(core_obj, frame, canonic=False)
        if "<string>" == filename and dbgr_obj.eval_string:
            remapped_file = filename
            filename = pyficache.unmap_file(filename)
            if "<string>" == filename:
                remapped = source_tempfile_remap(
                    "eval_string",
                    dbgr_obj.eval_string,
                    tempdir=proc_obj.settings("tempdir"))
                pyficache.remap_file(filename, remapped)
                filename = remapped
                lineno = pyficache.unmap_file_line(filename, lineno)
                pass
            pass
        elif "<string>" == filename:
            source_text = deparse_fn(frame.f_code)
            filename = "<string: '%s'>" % source_text
            pass
        elif filename in proc_obj.file2file_remap:
            remapped_file = proc_obj.file2file_remap[filename]
        elif filename in pyficache.file2file_remap:
            remapped_file = pyficache.unmap_file(filename)
            # FIXME: a remapped_file shouldn't be the same as its unmapped version
            if remapped_file == filename:
                remapped_file = None
                pass
            pass
        elif pyficache.main.remap_re_hash:
            remapped_file = pyficache.remap_file_pat(
                filename, pyficache.main.remap_re_hash)

        opts = {
            "reload_on_change": proc_obj.settings("reload"),
            "output": proc_obj.settings("highlight"),
        }

        if "style" in proc_obj.debugger.settings:
            opts["style"] = proc_obj.settings("style")

        pyficache.update_cache(filename)
        line = pyficache.getline(filename, lineno, opts)
        if not line:
            if (not source_text and filename.startswith("<string: ")
                    and proc_obj.curframe.f_code):
                # Deparse the code object into a temp file and remap the line from code
                # into the corresponding line of the tempfile
                co = proc_obj.curframe.f_code
                tempdir = proc_obj.settings("tempdir")
                temp_filename, name_for_code = deparse_and_cache(
                    co, proc_obj.errmsg, tempdir=tempdir)
                lineno = 1
                # _, lineno = pyficache.unmap_file_line(temp_filename, lineno, True)
                if temp_filename:
                    filename = temp_filename
                pass

            else:
                # FIXME:
                if source_text:
                    lines = source_text.split("\n")
                    temp_name = "string-"
                else:
                    # try with good ol linecache and consider fixing pyficache
                    lines = linecache.getlines(filename)
                    temp_name = filename
                if lines:
                    # FIXME: DRY code with version in cmdproc.py print_location
                    prefix = osp.basename(temp_name).split(".")[0]
                    fd = tempfile.NamedTemporaryFile(
                        suffix=".py",
                        prefix=prefix,
                        delete=False,
                        dir=proc_obj.settings("tempdir"),
                    )
                    with fd:
                        fd.write("".join(lines))
                        remapped_file = fd.name
                        pyficache.remap_file(remapped_file, filename)
                    fd.close()
                    pass
                line = linecache.getline(filename, lineno,
                                         proc_obj.curframe.f_globals)
            pass

        fn_name = frame.f_code.co_name
        last_i = frame.f_lasti
        print_source_location_info(
            intf_obj.msg,
            filename,
            lineno,
            fn_name,
            remapped_file=remapped_file,
            f_lasti=last_i,
        )
        if line and len(line.strip()) != 0:
            if proc_obj.event:
                print_source_line(intf_obj.msg, lineno, line,
                                  proc_obj.event2short[proc_obj.event])
            pass
        if "<string>" != filename:
            break
        pass

    if proc_obj.event in ["return", "exception"]:
        val = proc_obj.event_arg
        intf_obj.msg("R=> %s" % proc_obj._saferepr(val))
        pass
    return True
Example #30
0
    def run(self, args):
        proc = self.proc
        dbg_obj  = self.core.debugger
        listsize = dbg_obj.settings['listsize']
        filename, first, last = parse_list_cmd(proc, args, listsize)
        curframe = proc.curframe

        if filename is None: return

        # Sometimes such as due to decompilation we might not really
        # have an idea based on the listing where we really are.
        # Setting "show_marks" to false will disable marking breakpoint
        # and current line numbers.
        show_marks = True

        filename = pyficache.unmap_file(pyficache.pyc2py(filename))

        if filename == "<string>" and proc.curframe.f_code:
            # Deparse the code object into a temp file and remap the line from code
            # into the corresponding line of the tempfile
            co = proc.curframe.f_code
            temp_filename, name_for_code = deparse_and_cache(co, proc.errmsg)
            if temp_filename:
                filename = temp_filename
                show_marks = False
            pass

        # We now have range information. Do the listing.
        max_line = pyficache.size(filename)
        if max_line is None:
            self.errmsg('No file %s found; using "deparse" command instead to show source' %
                        filename)
            proc.commands['deparse'].run(['deparse'])
            return

        canonic_filename = os.path.realpath(os.path.normcase(filename))

        if first > max_line:
            self.errmsg('Bad start line %d - file "%s" has only %d lines'
                        % (first, filename, max_line))
            return

        if last > max_line:
            self.msg('End position changed to last line %d ' % max_line)
            last = max_line

        bplist = self.core.bpmgr.bplist
        opts = {
            'reload_on_change' : self.settings['reload'],
            'output'           : self.settings['highlight'],
            'strip_nl'         : False,
            }

        if 'style' in self.settings:
            opts['style'] = self.settings['style']

        if first <= 0:
            first = 1
        try:
            for lineno in range(first, last+1):
                line = pyficache.getline(filename, lineno, opts)
                if line is None:
                    line = linecache.getline(filename, lineno,
                                             proc.frame.f_globals)
                    pass
                if line is None:
                    self.msg('[EOF]')
                    break
                else:
                    line = line.rstrip('\n')
                    s = proc._saferepr(lineno).rjust(3)
                    if len(s) < 5: s += ' '
                    if (show_marks and
                        (canonic_filename, lineno,) in list(bplist.keys())):
                        bp    = bplist[(canonic_filename, lineno,)][0]
                        a_pad = '%02d' % bp.number
                        s    += bp.icon_char()
                    else:
                        s    += ' '
                        a_pad = '  '
                        pass
                    if (curframe and lineno == inspect.getlineno(curframe)
                        and show_marks):
                        s += '->'
                        if 'plain' != self.settings['highlight']:
                            s = colorize('bold', s)
                    else:
                        s += a_pad
                        pass
                    self.msg(s + '\t' + line)
                    proc.list_lineno = lineno
                    pass
                pass
            pass
        except KeyboardInterrupt:
            pass
        return False
Example #31
0
    def run(self, args):
        filename, first, last = self.parse_list_cmd(args[1:])
        curframe = self.proc.curframe
        if filename is None: return
        filename = pyc2py(filename)

        # We now have range information. Do the listing.
        max_line = pyficache.size(filename)
        if max_line is None:
            self.errmsg('No file %s found' % filename)
            return

        canonic_filename = os.path.realpath(os.path.normcase(filename))
        if first > max_line:
            self.errmsg('Bad start line %d - file "%s" has only %d lines'
                        % (first, filename, max_line))
            return

        if last > max_line:
            self.msg('End position changed to last line %d ' % max_line)
            last = max_line

        bplist = self.core.bpmgr.bplist
        opts = {
            'reload_on_change' : self.settings['reload'],
            'output'           : self.settings['highlight'],
            'strip_nl'         : False
            }

        try:
            for lineno in range(first, last+1):
                line = pyficache.getline(filename, lineno, opts)
                if line is None:
                    line = linecache.getline(filename, lineno,
                                             self.proc.frame.f_globals)
                    pass
                if line is None:
                    self.msg('[EOF]')
                    break
                else:
                    line = line.rstrip('\n')
                    s = self.proc._saferepr(lineno).rjust(3)
                    if len(s) < 5: s += ' '
                    if (canonic_filename, lineno,) in list(bplist.keys()):
                        bp    = bplist[(canonic_filename, lineno,)][0]
                        a_pad = '%02d' % bp.number
                        s    += bp.icon_char()
                    else:
                        s    += ' '
                        a_pad = '  '
                        pass
                    if curframe and lineno == inspect.getlineno(curframe) \
                       and filename == curframe.f_code.co_filename:
                        s += '->'
                        if 'plain' != self.settings['highlight']:
                            s = colorize('bold', s)
                    else:
                        s += a_pad
                        pass
                    self.msg(s + '\t' + line)
                    self.proc.list_lineno = lineno
                    pass
                pass
        except KeyboardInterrupt:
            pass
        return False
Example #32
0
def print_location(proc_obj):
    """Show where we are. GUI's and front-end interfaces often
    use this to update displays. So it is helpful to make sure
    we give at least some place that's located in a file.
    """
    i_stack = proc_obj.curindex
    if i_stack is None or proc_obj.stack is None:
        return False
    core_obj = proc_obj.core
    dbgr_obj = proc_obj.debugger
    intf_obj = dbgr_obj.intf[-1]

    # Evaluation routines like "exec" don't show useful location
    # info. In these cases, we will use the position before that in
    # the stack.  Hence the looping below which in practices loops
    # once and sometimes twice.
    remapped_file = None
    while i_stack >= 0:
        frame_lineno = proc_obj.stack[i_stack]
        i_stack -= 1
        frame, lineno = frame_lineno

#         # Next check to see that local variable breadcrumb exists and
#         # has the magic dynamic value.
#         # If so, it's us and we don't normally show this.a
#         if 'breadcrumb' in frame.f_locals:
#             if self.run == frame.f_locals['breadcrumb']:
#                 break

        filename = Mstack.frame2file(core_obj, frame, canonic=False)
        if '<string>' == filename and dbgr_obj.eval_string:
            remapped_file = filename
            filename = pyficache.unmap_file(filename)
            if '<string>' == filename:
                fd = tempfile.NamedTemporaryFile(suffix='.py',
                                                 prefix='eval_string',
                                                 delete=False)
                with fd:
                    fd.write(dbgr_obj.eval_string)
                    fd.close()
                    pass
                pyficache.remap_file(fd.name, '<string>')
                filename = fd.name
                pass
            pass
        else:
            if filename in pyficache.file2file_remap:
                remapped_file = pyficache.unmap_file(filename)
                # FIXME: a remapped_file shouldn't be the same as its unmapped version
                if remapped_file == filename:
                    remapped_file = None
                    pass
                pass
            pass

        opts = {
            'reload_on_change' : proc_obj.settings('reload'),
            'output'           : proc_obj.settings('highlight')
            }

        if 'style' in proc_obj.debugger.settings:
            opts['style'] = proc_obj.settings('style')

        pyficache.update_cache(filename)
        line = pyficache.getline(filename, lineno, opts)
        if not line:
            # FIXME:
            # try with good ol linecache and consider fixing pyficache
            lines = linecache.getlines(filename)
            if lines:
                # FIXME: DRY code with version in cmdproc.py print_location
                prefix = os.path.basename(filename).split('.')[0]
                fd = tempfile.NamedTemporaryFile(suffix='.py',
                                                 prefix=prefix,
                                                 delete=False)
                with fd:
                    fd.write(''.join(lines))
                    remapped_file = fd.name
                    pyficache.remap_file(remapped_file, filename)
                fd.close()
                pass
            line = linecache.getline(filename, lineno,
                                     proc_obj.curframe.f_globals)
            pass

        fn_name = frame.f_code.co_name
        last_i  = frame.f_lasti
        print_source_location_info(intf_obj.msg, filename, lineno, fn_name,
                                   remapped_file = remapped_file,
                                   f_lasti = last_i)
        if line and len(line.strip()) != 0:
            if proc_obj.event:
                print_source_line(intf_obj.msg, lineno, line,
                                  proc_obj.event2short[proc_obj.event])
            pass
        if '<string>' != filename: break
        pass

    if proc_obj.event in ['return', 'exception']:
        val = proc_obj.event_arg
        intf_obj.msg('R=> %s' % proc_obj._saferepr(val))
        pass
    return True
Example #33
0
def print_location(proc_obj):
    """Show where we are. GUI's and front-end interfaces often
    use this to update displays. So it is helpful to make sure
    we give at least some place that's located in a file.
    """
    i_stack = proc_obj.curindex
    if i_stack is None or proc_obj.stack is None:
        return False
    core_obj = proc_obj.core
    dbgr_obj = proc_obj.debugger
    intf_obj = dbgr_obj.intf[-1]

    # Evaluation routines like "exec" don't show useful location
    # info. In these cases, we will use the position before that in
    # the stack.  Hence the looping below which in practices loops
    # once and sometimes twice.
    remapped_file = None
    while i_stack >= 0:
        frame_lineno = proc_obj.stack[i_stack]
        i_stack -= 1
        frame, lineno = frame_lineno

        #         # Next check to see that local variable breadcrumb exists and
        #         # has the magic dynamic value.
        #         # If so, it's us and we don't normally show this.a
        #         if 'breadcrumb' in frame.f_locals:
        #             if self.run == frame.f_locals['breadcrumb']:
        #                 break

        filename = Mstack.frame2file(core_obj, frame)
        if '<string>' == filename and dbgr_obj.eval_string:
            remapped_file = filename
            filename = pyficache.unmap_file(filename)
            if '<string>' == filename:
                fd = tempfile.NamedTemporaryFile(suffix='.py',
                                                 prefix='eval_string',
                                                 delete=False)
                fd.write(dbgr_obj.eval_string)
                fd.close()
                pyficache.remap_file(fd.name, '<string>')
                filename = fd.name
                pass
            pass

        fn_name = frame.f_code.co_name
        print_source_location_info(intf_obj.msg,
                                   filename,
                                   lineno,
                                   fn_name,
                                   remapped_file=remapped_file)
        # proc_obj.curframe.f_lasti)

        opts = {
            'reload_on_change': proc_obj.settings('reload'),
            'output': proc_obj.settings('highlight')
        }
        line = pyficache.getline(filename, lineno, opts)
        if not line:
            if sys.version_info[1] <= 4:
                # Python 2.4 and before doesn't have 3-arg getline
                line = linecache.getline(filename, lineno)
            else:
                line = linecache.getline(filename, lineno,
                                         proc_obj.curframe.f_globals)
                pass
            pass

        if line and len(line.strip()) != 0:
            if proc_obj.event:
                print_source_line(intf_obj.msg, lineno, line,
                                  proc_obj.event2short[proc_obj.event])
            pass
        if '<string>' != filename: break
        pass

    if proc_obj.event in ['return', 'exception']:
        val = proc_obj.event_arg
        intf_obj.msg('R=> %s' % proc_obj._saferepr(val))
        pass
    return True