Python sys.trace() Examples

The following are code examples for showing how to use sys.trace(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: ironpython2   Author: IronLanguages   File: adb.py    Apache License 2.0 6 votes vote down vote up
def dispatch_line(self, frame):
        traceenter("dispatch_line", _dumpf(frame), _dumpf(self.botframe))
#               trace("logbotframe is", _dumpf(self.logicalbotframe), "botframe is", self.botframe)
        if frame is self.logicalbotframe:
            trace("dispatch_line", _dumpf(frame), "for bottom frame returing tracer")
            # The next code executed in the frame above may be a builtin (eg, apply())
            # in which sys.trace needs to be set.
            sys.settrace(self.trace_dispatch)
            # And return the tracer incase we are about to execute Python code,
            # in which case sys tracer is ignored!
            return self.trace_dispatch

        if self.codeContainerProvider.FromFileName(frame.f_code.co_filename) is None:
            trace("dispatch_line has no document for", _dumpf(frame), "- skipping trace!")
            return None
        self.currentframe = frame # So the stack sniffer knows our most recent, debuggable code.
        return bdb.Bdb.dispatch_line(self, frame) 
Example 2
Project: ironpython2   Author: IronLanguages   File: adb.py    Apache License 2.0 6 votes vote down vote up
def dispatch_call(self, frame, arg):
        traceenter("dispatch_call",_dumpf(frame))
        frame.f_locals['__axstack_address__'] = axdebug.GetStackAddress()
        if frame is self.botframe:
            trace("dispatch_call is self.botframe - returning tracer")
            return self.trace_dispatch
        # Not our bottom frame.  If we have a document for it,
        # then trace it, otherwise run at full speed.
        if self.codeContainerProvider.FromFileName(frame.f_code.co_filename) is None:
            trace("dispatch_call has no document for", _dumpf(frame), "- skipping trace!")
##                      sys.settrace(None)
            return None
        return self.trace_dispatch

#               rc =  bdb.Bdb.dispatch_call(self, frame, arg)
#               trace("dispatch_call", _dumpf(frame),"returned",rc)
#               return rc 
Example 3
Project: ironpython2   Author: IronLanguages   File: adb.py    Apache License 2.0 6 votes vote down vote up
def CloseApp(self):
        traceenter("ClosingApp")
        self.reset()
        self.logicalbotframe = None
        if self.stackSnifferCookie is not None:
            try:
                self.debugApplication.RemoveStackFrameSniffer(self.stackSnifferCookie)

            except pythoncom.com_error:
                trace("*** Could not RemoveStackFrameSniffer %d" % (self.stackSnifferCookie))
        if self.stackSniffer:
            _wrap_remove(self.stackSniffer)
        self.stackSnifferCookie = self.stackSniffer = None

        if self.appEventConnection is not None:
            self.appEventConnection.Disconnect()
            self.appEventConnection = None
        self.debugApplication = None
        self.appDebugger = None
        if self.codeContainerProvider is not None:
            self.codeContainerProvider.Close()
            self.codeContainerProvider = None 
Example 4
Project: ironpython2   Author: IronLanguages   File: adb.py    Apache License 2.0 6 votes vote down vote up
def ResetAXDebugging(self):
        traceenter("ResetAXDebugging", self, "with refcount", len(self.recursiveData))
        if win32api.GetCurrentThreadId()!=self.debuggingThread:
            trace("ResetAXDebugging called on other thread")
            return

        if len(self.recursiveData)==0:
#                       print "ResetAXDebugging called for final time."
            self.logicalbotframe = None
            self.debuggingThread = None
            self.currentframe = None
            self.debuggingThreadStateHandle = None
            return

        self.logbotframe, self.stopframe, self.currentframe, self.debuggingThreadStateHandle = self.recursiveData[0]
        self.recursiveData = self.recursiveData[1:] 
Example 5
Project: open-recipe   Author: dspray95   File: adb.py    The Unlicense 6 votes vote down vote up
def dispatch_line(self, frame):
        traceenter("dispatch_line", _dumpf(frame), _dumpf(self.botframe))
#               trace("logbotframe is", _dumpf(self.logicalbotframe), "botframe is", self.botframe)
        if frame is self.logicalbotframe:
            trace("dispatch_line", _dumpf(frame), "for bottom frame returing tracer")
            # The next code executed in the frame above may be a builtin (eg, apply())
            # in which sys.trace needs to be set.
            sys.settrace(self.trace_dispatch)
            # And return the tracer incase we are about to execute Python code,
            # in which case sys tracer is ignored!
            return self.trace_dispatch

        if self.codeContainerProvider.FromFileName(frame.f_code.co_filename) is None:
            trace("dispatch_line has no document for", _dumpf(frame), "- skipping trace!")
            return None
        self.currentframe = frame # So the stack sniffer knows our most recent, debuggable code.
        return bdb.Bdb.dispatch_line(self, frame) 
Example 6
Project: open-recipe   Author: dspray95   File: adb.py    The Unlicense 6 votes vote down vote up
def dispatch_call(self, frame, arg):
        traceenter("dispatch_call",_dumpf(frame))
        frame.f_locals['__axstack_address__'] = axdebug.GetStackAddress()
        if frame is self.botframe:
            trace("dispatch_call is self.botframe - returning tracer")
            return self.trace_dispatch
        # Not our bottom frame.  If we have a document for it,
        # then trace it, otherwise run at full speed.
        if self.codeContainerProvider.FromFileName(frame.f_code.co_filename) is None:
            trace("dispatch_call has no document for", _dumpf(frame), "- skipping trace!")
##                      sys.settrace(None)
            return None
        return self.trace_dispatch

#               rc =  bdb.Bdb.dispatch_call(self, frame, arg)
#               trace("dispatch_call", _dumpf(frame),"returned",rc)
#               return rc 
Example 7
Project: open-recipe   Author: dspray95   File: adb.py    The Unlicense 6 votes vote down vote up
def CloseApp(self):
        traceenter("ClosingApp")
        self.reset()
        self.logicalbotframe = None
        if self.stackSnifferCookie is not None:
            try:
                self.debugApplication.RemoveStackFrameSniffer(self.stackSnifferCookie)

            except pythoncom.com_error:
                trace("*** Could not RemoveStackFrameSniffer %d" % (self.stackSnifferCookie))
        if self.stackSniffer:
            _wrap_remove(self.stackSniffer)
        self.stackSnifferCookie = self.stackSniffer = None

        if self.appEventConnection is not None:
            self.appEventConnection.Disconnect()
            self.appEventConnection = None
        self.debugApplication = None
        self.appDebugger = None
        if self.codeContainerProvider is not None:
            self.codeContainerProvider.Close()
            self.codeContainerProvider = None 
Example 8
Project: open-recipe   Author: dspray95   File: adb.py    The Unlicense 6 votes vote down vote up
def ResetAXDebugging(self):
        traceenter("ResetAXDebugging", self, "with refcount", len(self.recursiveData))
        if win32api.GetCurrentThreadId()!=self.debuggingThread:
            trace("ResetAXDebugging called on other thread")
            return

        if len(self.recursiveData)==0:
#                       print "ResetAXDebugging called for final time."
            self.logicalbotframe = None
            self.debuggingThread = None
            self.currentframe = None
            self.debuggingThreadStateHandle = None
            return

        self.logbotframe, self.stopframe, self.currentframe, self.debuggingThreadStateHandle = self.recursiveData[0]
        self.recursiveData = self.recursiveData[1:] 
Example 9
Project: AsemanOs   Author: AsemanOS   File: visualstudio_py_debugger.py    GNU General Public License v3.0 6 votes vote down vote up
def should_break(self, thread, ex_type, ex_value, trace):
        probe_stack()
        name = get_exception_name(ex_type)
        mode = self.break_on.get(name, self.default_mode)
        break_type = BREAK_TYPE_NONE
        if mode & BREAK_MODE_ALWAYS:
            if self.is_handled(thread, ex_type, ex_value, trace):
                break_type = BREAK_TYPE_HANDLED
            else:
                break_type = BREAK_TYPE_UNHANDLED
        elif (mode & BREAK_MODE_UNHANDLED) and not self.is_handled(thread, ex_type, ex_value, trace):
            break_type = BREAK_TYPE_UNHANDLED

        if break_type:
            if issubclass(ex_type, SystemExit):
                if not BREAK_ON_SYSTEMEXIT_ZERO:
                    if not ex_value or (isinstance(ex_value, SystemExit) and not ex_value.code):
                        break_type = BREAK_TYPE_NONE

        return break_type 
Example 10
Project: AsemanOs   Author: AsemanOS   File: visualstudio_py_debugger.py    GNU General Public License v3.0 6 votes vote down vote up
def handle_exception(self, frame, arg):
        if self.stepping == STEPPING_ATTACH_BREAK:
            self.block_maybe_attach()

        if not DETACHED and should_debug_code(frame.f_code):
            break_type = BREAK_ON.should_break(self, *arg)
            if break_type:
                update_all_thread_stacks(self)
                self.block(lambda: report_exception(frame, arg, self.id, break_type))

        # forward call to previous trace function, if any, updating the current trace function
        # with a new one if available
        old_trace_func = self.prev_trace_func
        if old_trace_func is not None:
            self.prev_trace_func = old_trace_func(frame, 'exception', arg)

        return self.trace_func 
Example 11
Project: AsemanOs   Author: AsemanOS   File: visualstudio_py_debugger.py    GNU General Public License v3.0 6 votes vote down vote up
def should_break(self, thread, ex_type, ex_value, trace):
        probe_stack()
        name = get_exception_name(ex_type)
        mode = self.break_on.get(name, self.default_mode)
        break_type = BREAK_TYPE_NONE
        if mode & BREAK_MODE_ALWAYS:
            if self.is_handled(thread, ex_type, ex_value, trace):
                break_type = BREAK_TYPE_HANDLED
            else:
                break_type = BREAK_TYPE_UNHANDLED
        elif (mode & BREAK_MODE_UNHANDLED) and not self.is_handled(thread, ex_type, ex_value, trace):
            break_type = BREAK_TYPE_UNHANDLED

        if break_type:
            if issubclass(ex_type, SystemExit):
                if not BREAK_ON_SYSTEMEXIT_ZERO:
                    if not ex_value or (isinstance(ex_value, SystemExit) and not ex_value.code):
                        break_type = BREAK_TYPE_NONE

        return break_type 
Example 12
Project: arkScript   Author: akbchris   File: adb.py    MIT License 6 votes vote down vote up
def dispatch_line(self, frame):
        traceenter("dispatch_line", _dumpf(frame), _dumpf(self.botframe))
#               trace("logbotframe is", _dumpf(self.logicalbotframe), "botframe is", self.botframe)
        if frame is self.logicalbotframe:
            trace("dispatch_line", _dumpf(frame), "for bottom frame returing tracer")
            # The next code executed in the frame above may be a builtin (eg, apply())
            # in which sys.trace needs to be set.
            sys.settrace(self.trace_dispatch)
            # And return the tracer incase we are about to execute Python code,
            # in which case sys tracer is ignored!
            return self.trace_dispatch

        if self.codeContainerProvider.FromFileName(frame.f_code.co_filename) is None:
            trace("dispatch_line has no document for", _dumpf(frame), "- skipping trace!")
            return None
        self.currentframe = frame # So the stack sniffer knows our most recent, debuggable code.
        return bdb.Bdb.dispatch_line(self, frame) 
Example 13
Project: arkScript   Author: akbchris   File: adb.py    MIT License 6 votes vote down vote up
def dispatch_call(self, frame, arg):
        traceenter("dispatch_call",_dumpf(frame))
        frame.f_locals['__axstack_address__'] = axdebug.GetStackAddress()
        if frame is self.botframe:
            trace("dispatch_call is self.botframe - returning tracer")
            return self.trace_dispatch
        # Not our bottom frame.  If we have a document for it,
        # then trace it, otherwise run at full speed.
        if self.codeContainerProvider.FromFileName(frame.f_code.co_filename) is None:
            trace("dispatch_call has no document for", _dumpf(frame), "- skipping trace!")
##                      sys.settrace(None)
            return None
        return self.trace_dispatch

#               rc =  bdb.Bdb.dispatch_call(self, frame, arg)
#               trace("dispatch_call", _dumpf(frame),"returned",rc)
#               return rc 
Example 14
Project: arkScript   Author: akbchris   File: adb.py    MIT License 6 votes vote down vote up
def CloseApp(self):
        traceenter("ClosingApp")
        self.reset()
        self.logicalbotframe = None
        if self.stackSnifferCookie is not None:
            try:
                self.debugApplication.RemoveStackFrameSniffer(self.stackSnifferCookie)

            except pythoncom.com_error:
                trace("*** Could not RemoveStackFrameSniffer %d" % (self.stackSnifferCookie))
        if self.stackSniffer:
            _wrap_remove(self.stackSniffer)
        self.stackSnifferCookie = self.stackSniffer = None

        if self.appEventConnection is not None:
            self.appEventConnection.Disconnect()
            self.appEventConnection = None
        self.debugApplication = None
        self.appDebugger = None
        if self.codeContainerProvider is not None:
            self.codeContainerProvider.Close()
            self.codeContainerProvider = None 
Example 15
Project: arkScript   Author: akbchris   File: adb.py    MIT License 6 votes vote down vote up
def ResetAXDebugging(self):
        traceenter("ResetAXDebugging", self, "with refcount", len(self.recursiveData))
        if win32api.GetCurrentThreadId()!=self.debuggingThread:
            trace("ResetAXDebugging called on other thread")
            return

        if len(self.recursiveData)==0:
#                       print "ResetAXDebugging called for final time."
            self.logicalbotframe = None
            self.debuggingThread = None
            self.currentframe = None
            self.debuggingThreadStateHandle = None
            return

        self.logbotframe, self.stopframe, self.currentframe, self.debuggingThreadStateHandle = self.recursiveData[0]
        self.recursiveData = self.recursiveData[1:] 
Example 16
Project: ironpython2   Author: IronLanguages   File: adb.py    Apache License 2.0 5 votes vote down vote up
def _dumpf(frame):
    if frame is None:
        return "<None>"
    else:
        addn = "(with trace!)"
        if frame.f_trace is None:
            addn = " **No Trace Set **"
        return "Frame at %d, file %s, line: %d%s" % (id(frame), frame.f_code.co_filename, frame.f_lineno, addn) 
Example 17
Project: ironpython2   Author: IronLanguages   File: adb.py    Apache License 2.0 5 votes vote down vote up
def dispatch_return(self, frame, arg):
        traceenter("dispatch_return", _dumpf(frame), arg)
        if self.logicalbotframe is frame:
            # We dont want to debug parent frames.
            tracev("dispatch_return resetting sys.trace")
            sys.settrace(None)
            return
#                       self.bSetTrace = 0
        self.currentframe = frame.f_back
        return bdb.Bdb.dispatch_return(self, frame, arg) 
Example 18
Project: ironpython2   Author: IronLanguages   File: adb.py    Apache License 2.0 5 votes vote down vote up
def trace_dispatch(self, frame, event, arg):
        traceenter("trace_dispatch", _dumpf(frame), event, arg)
        if self.debugApplication is None:
            trace("trace_dispatch has no application!")
            return # None
        return bdb.Bdb.trace_dispatch(self, frame, event, arg)


    #
    # The user functions do bugger all!
    #
#       def user_call(self, frame, argument_list):
#               traceenter("user_call",_dumpf(frame)) 
Example 19
Project: ironpython2   Author: IronLanguages   File: adb.py    Apache License 2.0 5 votes vote down vote up
def AttachApp(self, debugApplication, codeContainerProvider):
#               traceenter("AttachApp", debugApplication, codeContainerProvider)
        self.codeContainerProvider = codeContainerProvider
        self.debugApplication = debugApplication
        self.stackSniffer = _wrap(stackframe.DebugStackFrameSniffer(self), axdebug.IID_IDebugStackFrameSniffer)
        self.stackSnifferCookie = debugApplication.AddStackFrameSniffer(self.stackSniffer)
#               trace("StackFrameSniffer added (%d)" % self.stackSnifferCookie)

        # Connect to the application events.
        self.appEventConnection = win32com.client.connect.SimpleConnection(self.debugApplication, self, axdebug.IID_IRemoteDebugApplicationEvents) 
Example 20
Project: ironpython2   Author: IronLanguages   File: adb.py    Apache License 2.0 5 votes vote down vote up
def SetupAXDebugging(self, baseFrame = None, userFrame = None):
        """Get ready for potential debugging.  Must be called on the thread
        that is being debugged.
        """
        # userFrame is for non AXScript debugging.  This is the first frame of the
        # users code.
        if userFrame is None:
            userFrame = baseFrame
        else:
            # We have missed the "dispatch_call" function, so set this up now!
            userFrame.f_locals['__axstack_address__'] = axdebug.GetStackAddress()

        traceenter("SetupAXDebugging", self)
        self._threadprotectlock.acquire()
        try:
            thisThread = win32api.GetCurrentThreadId()
            if self.debuggingThread is None:
                self.debuggingThread = thisThread
            else:
                if self.debuggingThread!=thisThread:
                    trace("SetupAXDebugging called on other thread - ignored!")
                    return
                # push our context.
                self.recursiveData.insert(0, (self.logicalbotframe,self.stopframe, self.currentframe,self.debuggingThreadStateHandle))
        finally:
            self._threadprotectlock.release()

        trace("SetupAXDebugging has base frame as", _dumpf(baseFrame))
        self.botframe = baseFrame
        self.stopframe = userFrame
        self.logicalbotframe = baseFrame
        self.currentframe = None
        self.debuggingThreadStateHandle = axdebug.GetThreadStateHandle()

        self._BreakFlagsChanged()

    # RemoteDebugApplicationEvents 
Example 21
Project: ironpython2   Author: IronLanguages   File: adb.py    Apache License 2.0 5 votes vote down vote up
def _BreakFlagsChanged(self):
        traceenter("_BreakFlagsChanged to %s with our thread = %s, and debugging thread = %s" % (self.breakFlags, self.debuggingThread, win32api.GetCurrentThreadId()))
        trace("_BreakFlagsChanged has breaks", self.breaks)
        # If a request comes on our debugging thread, then do it now!
#               if self.debuggingThread!=win32api.GetCurrentThreadId():
#                       return

        if len(self.breaks) or self.breakFlags:

            if self.logicalbotframe:
                trace("BreakFlagsChange with bot frame", _dumpf(self.logicalbotframe))
                # We have frames not to be debugged (eg, Scripting engine frames
                # (sys.settrace will be set when out logicalbotframe is hit -
                #  this may not be the right thing to do, as it may not cause the
                #  immediate break we desire.)
                self.logicalbotframe.f_trace = self.trace_dispatch
            else:
                trace("BreakFlagsChanged, but no bottom frame")
                if self.stopframe is not None:
                    self.stopframe.f_trace = self.trace_dispatch
            # If we have the thread-state for the thread being debugged, then
            # we dynamically set its trace function - it is possible that the thread
            # being debugged is in a blocked call (eg, a message box) and we
            # want to hit the debugger the instant we return
        if self.debuggingThreadStateHandle is not None and \
                self.breakFlags and \
                self.debuggingThread != win32api.GetCurrentThreadId():
            axdebug.SetThreadStateTrace(self.debuggingThreadStateHandle, self.trace_dispatch) 
Example 22
Project: open-recipe   Author: dspray95   File: adb.py    The Unlicense 5 votes vote down vote up
def _dumpf(frame):
    if frame is None:
        return "<None>"
    else:
        addn = "(with trace!)"
        if frame.f_trace is None:
            addn = " **No Trace Set **"
        return "Frame at %d, file %s, line: %d%s" % (id(frame), frame.f_code.co_filename, frame.f_lineno, addn) 
Example 23
Project: open-recipe   Author: dspray95   File: adb.py    The Unlicense 5 votes vote down vote up
def dispatch_return(self, frame, arg):
        traceenter("dispatch_return", _dumpf(frame), arg)
        if self.logicalbotframe is frame:
            # We dont want to debug parent frames.
            tracev("dispatch_return resetting sys.trace")
            sys.settrace(None)
            return
#                       self.bSetTrace = 0
        self.currentframe = frame.f_back
        return bdb.Bdb.dispatch_return(self, frame, arg) 
Example 24
Project: open-recipe   Author: dspray95   File: adb.py    The Unlicense 5 votes vote down vote up
def trace_dispatch(self, frame, event, arg):
        traceenter("trace_dispatch", _dumpf(frame), event, arg)
        if self.debugApplication is None:
            trace("trace_dispatch has no application!")
            return # None
        return bdb.Bdb.trace_dispatch(self, frame, event, arg)


    #
    # The user functions do bugger all!
    #
#       def user_call(self, frame, argument_list):
#               traceenter("user_call",_dumpf(frame)) 
Example 25
Project: open-recipe   Author: dspray95   File: adb.py    The Unlicense 5 votes vote down vote up
def AttachApp(self, debugApplication, codeContainerProvider):
#               traceenter("AttachApp", debugApplication, codeContainerProvider)
        self.codeContainerProvider = codeContainerProvider
        self.debugApplication = debugApplication
        self.stackSniffer = _wrap(stackframe.DebugStackFrameSniffer(self), axdebug.IID_IDebugStackFrameSniffer)
        self.stackSnifferCookie = debugApplication.AddStackFrameSniffer(self.stackSniffer)
#               trace("StackFrameSniffer added (%d)" % self.stackSnifferCookie)

        # Connect to the application events.
        self.appEventConnection = win32com.client.connect.SimpleConnection(self.debugApplication, self, axdebug.IID_IRemoteDebugApplicationEvents) 
Example 26
Project: open-recipe   Author: dspray95   File: adb.py    The Unlicense 5 votes vote down vote up
def SetupAXDebugging(self, baseFrame = None, userFrame = None):
        """Get ready for potential debugging.  Must be called on the thread
        that is being debugged.
        """
        # userFrame is for non AXScript debugging.  This is the first frame of the
        # users code.
        if userFrame is None:
            userFrame = baseFrame
        else:
            # We have missed the "dispatch_call" function, so set this up now!
            userFrame.f_locals['__axstack_address__'] = axdebug.GetStackAddress()

        traceenter("SetupAXDebugging", self)
        self._threadprotectlock.acquire()
        try:
            thisThread = win32api.GetCurrentThreadId()
            if self.debuggingThread is None:
                self.debuggingThread = thisThread
            else:
                if self.debuggingThread!=thisThread:
                    trace("SetupAXDebugging called on other thread - ignored!")
                    return
                # push our context.
                self.recursiveData.insert(0, (self.logicalbotframe,self.stopframe, self.currentframe,self.debuggingThreadStateHandle))
        finally:
            self._threadprotectlock.release()

        trace("SetupAXDebugging has base frame as", _dumpf(baseFrame))
        self.botframe = baseFrame
        self.stopframe = userFrame
        self.logicalbotframe = baseFrame
        self.currentframe = None
        self.debuggingThreadStateHandle = axdebug.GetThreadStateHandle()

        self._BreakFlagsChanged()

    # RemoteDebugApplicationEvents 
Example 27
Project: open-recipe   Author: dspray95   File: adb.py    The Unlicense 5 votes vote down vote up
def _BreakFlagsChanged(self):
        traceenter("_BreakFlagsChanged to %s with our thread = %s, and debugging thread = %s" % (self.breakFlags, self.debuggingThread, win32api.GetCurrentThreadId()))
        trace("_BreakFlagsChanged has breaks", self.breaks)
        # If a request comes on our debugging thread, then do it now!
#               if self.debuggingThread!=win32api.GetCurrentThreadId():
#                       return

        if len(self.breaks) or self.breakFlags:

            if self.logicalbotframe:
                trace("BreakFlagsChange with bot frame", _dumpf(self.logicalbotframe))
                # We have frames not to be debugged (eg, Scripting engine frames
                # (sys.settrace will be set when out logicalbotframe is hit -
                #  this may not be the right thing to do, as it may not cause the
                #  immediate break we desire.)
                self.logicalbotframe.f_trace = self.trace_dispatch
            else:
                trace("BreakFlagsChanged, but no bottom frame")
                if self.stopframe is not None:
                    self.stopframe.f_trace = self.trace_dispatch
            # If we have the thread-state for the thread being debugged, then
            # we dynamically set its trace function - it is possible that the thread
            # being debugged is in a blocked call (eg, a message box) and we
            # want to hit the debugger the instant we return
        if self.debuggingThreadStateHandle is not None and \
                self.breakFlags and \
                self.debuggingThread != win32api.GetCurrentThreadId():
            axdebug.SetThreadStateTrace(self.debuggingThreadStateHandle, self.trace_dispatch) 
Example 28
Project: AsemanOs   Author: AsemanOS   File: visualstudio_py_debugger.py    GNU General Public License v3.0 5 votes vote down vote up
def _stackless_attach(self):
        try:
            stackless.tasklet.trace_function
        except AttributeError:
            # the tasklets need to be traced on a case by case basis
            # sys.trace needs to be called within their calling context
            def __call__(tsk, *args, **kwargs):
                f = tsk.tempval
                def new_f(old_f, args, kwargs):
                    sys.settrace(self.trace_func)
                    try:
                        if old_f is not None:
                            return old_f(*args, **kwargs)
                    finally:
                        sys.settrace(None)

                tsk.tempval = new_f
                stackless.tasklet.setup(tsk, f, args, kwargs)
                return tsk
    
            def settrace(tsk, tb):
                if hasattr(tsk.frame, "f_trace"):
                    tsk.frame.f_trace = tb
                sys.settrace(tb)

            self.__oldstacklesscall__ = stackless.tasklet.__call__
            stackless.tasklet.settrace = settrace
            stackless.tasklet.__call__ = __call__
        if sys.platform == 'cli':
            self.frames = [] 
Example 29
Project: AsemanOs   Author: AsemanOS   File: visualstudio_py_debugger.py    GNU General Public License v3.0 5 votes vote down vote up
def context_dispatcher(self, old, new):
        self.stepping = STEPPING_NONE
        # for those tasklets that started before we started tracing
        # we need to make sure that the trace is set by patching
        # it in the context switch
        if old and new:
            if hasattr(new.frame, "f_trace") and not new.frame.f_trace:
                sys.call_tracing(new.settrace,(self.trace_func,)) 
Example 30
Project: AsemanOs   Author: AsemanOS   File: visualstudio_py_debugger.py    GNU General Public License v3.0 5 votes vote down vote up
def _stackless_schedule_cb(self, prev, next):
        current = stackless.getcurrent()
        if not current:
            return
        current_tf = current.trace_function
        
        try:
            current.trace_function = None
            self.stepping = STEPPING_NONE
            
            # If the current frame has no trace function, we may need to get it
            # from the previous frame, depending on how we ended up in the
            # callback.
            if current_tf is None:
                f_back = current.frame.f_back
                if f_back is not None:
                    current_tf = f_back.f_trace

            if next is not None:
                # Assign our trace function to the current stack
                f = next.frame
                if next is current:
                    f = f.f_back
                while f:
                    if isinstance(f, types.FrameType):
                        f.f_trace = self.trace_func
                    f = f.f_back
                next.trace_function = self.trace_func
        finally:
            current.trace_function = current_tf 
Example 31
Project: AsemanOs   Author: AsemanOS   File: visualstudio_py_debugger.py    GNU General Public License v3.0 5 votes vote down vote up
def handle_return(self, frame, arg):
        self.pop_frame()

        if not DETACHED:
            stepping = self.stepping
            # only update stepping state when this frame is debuggable (matching handle_call)
            if stepping is not STEPPING_NONE and should_debug_code(frame.f_code):
                if stepping > STEPPING_OVER:
                    self.stepping -= 1
                elif stepping < STEPPING_OUT:
                    self.stepping += 1
                elif stepping in USER_STEPPING:
                    if self.cur_frame is None or frame.f_code.co_name == "<module>" :
                        # only return to user code modules
                        if self.should_block_on_frame(frame):
                            # restore back the module frame for the step out of a module
                            self.push_frame(ModuleExitFrame(frame))
                            self.stepping = STEPPING_NONE
                            update_all_thread_stacks(self)
                            self.block(lambda: (report_step_finished(self.id), mark_all_threads_for_break(skip_thread = self)))
                            self.pop_frame()
                    elif self.should_block_on_frame(self.cur_frame):
                        # if we're returning into non-user code then don't block in the
                        # non-user code, wait until we hit user code again
                        self.stepping = STEPPING_NONE
                        update_all_thread_stacks(self)
                        self.block(lambda: (report_step_finished(self.id), mark_all_threads_for_break(skip_thread = self)))

        # forward call to previous trace function, if any
        old_trace_func = self.prev_trace_func
        if old_trace_func is not None:
            old_trace_func(frame, 'return', arg)

        # restore previous frames trace function if there is one
        if self.trace_func_stack:
            self.prev_trace_func = self.trace_func_stack.pop() 
Example 32
Project: AsemanOs   Author: AsemanOS   File: visualstudio_py_debugger.py    GNU General Public License v3.0 5 votes vote down vote up
def _stackless_attach(self):
        try:
            stackless.tasklet.trace_function
        except AttributeError:
            # the tasklets need to be traced on a case by case basis
            # sys.trace needs to be called within their calling context
            def __call__(tsk, *args, **kwargs):
                f = tsk.tempval
                def new_f(old_f, args, kwargs):
                    sys.settrace(self.trace_func)
                    try:
                        if old_f is not None:
                            return old_f(*args, **kwargs)
                    finally:
                        sys.settrace(None)

                tsk.tempval = new_f
                stackless.tasklet.setup(tsk, f, args, kwargs)
                return tsk
    
            def settrace(tsk, tb):
                if hasattr(tsk.frame, "f_trace"):
                    tsk.frame.f_trace = tb
                sys.settrace(tb)

            self.__oldstacklesscall__ = stackless.tasklet.__call__
            stackless.tasklet.settrace = settrace
            stackless.tasklet.__call__ = __call__
        if sys.platform == 'cli':
            self.frames = [] 
Example 33
Project: AsemanOs   Author: AsemanOS   File: visualstudio_py_debugger.py    GNU General Public License v3.0 5 votes vote down vote up
def context_dispatcher(self, old, new):
        self.stepping = STEPPING_NONE
        # for those tasklets that started before we started tracing
        # we need to make sure that the trace is set by patching
        # it in the context switch
        if old and new:
            if hasattr(new.frame, "f_trace") and not new.frame.f_trace:
                sys.call_tracing(new.settrace,(self.trace_func,)) 
Example 34
Project: AsemanOs   Author: AsemanOS   File: visualstudio_py_debugger.py    GNU General Public License v3.0 5 votes vote down vote up
def _stackless_schedule_cb(self, prev, next):
        current = stackless.getcurrent()
        if not current:
            return
        current_tf = current.trace_function
        
        try:
            current.trace_function = None
            self.stepping = STEPPING_NONE
            
            # If the current frame has no trace function, we may need to get it
            # from the previous frame, depending on how we ended up in the
            # callback.
            if current_tf is None:
                f_back = current.frame.f_back
                if f_back is not None:
                    current_tf = f_back.f_trace

            if next is not None:
                # Assign our trace function to the current stack
                f = next.frame
                if next is current:
                    f = f.f_back
                while f:
                    if isinstance(f, types.FrameType):
                        f.f_trace = self.trace_func
                    f = f.f_back
                next.trace_function = self.trace_func
        finally:
            current.trace_function = current_tf 
Example 35
Project: AsemanOs   Author: AsemanOS   File: visualstudio_py_debugger.py    GNU General Public License v3.0 5 votes vote down vote up
def trace_func(self, frame, event, arg):
        # If we're so far into process shutdown that sys is already gone, just stop tracing.
        if sys is None:
            return None
        elif self.is_sending:
            # https://pytools.codeplex.com/workitem/1864 
            # we're currently doing I/O w/ the socket, we don't want to deliver
            # any breakpoints or async breaks because we'll deadlock.  Continue
            # to return the trace function so all of our frames remain
            # balanced.  A better way to deal with this might be to do
            # sys.settrace(None) when we take the send lock, but that's much
            # more difficult because our send context manager is used both
            # inside and outside of the trace function, and so is used when
            # tracing is enabled and disabled, and so it's very easy to get our
            # current frame tracking to be thrown off...
            return self.trace_func

        try:
            # if should_debug_code(frame.f_code) is not true during attach
            # the current frame is None and a pop_frame will cause an exception and 
            # break the debugger
            if self.cur_frame is None:
                # happens during attach, we need frame for blocking
                self.push_frame(frame)
            if self.stepping == STEPPING_BREAK and should_debug_code(frame.f_code):
                if self.detach:
                    if stackless is not None:
                        stackless.set_schedule_callback(None)
                        stackless.tasklet.__call__ = self.__oldstacklesscall__
                    sys.settrace(None)
                    return None

                self.async_break()

            return self._events[event](frame, arg)
        except (StackOverflowException, KeyboardInterrupt):
            # stack overflow, disable tracing
            return self.trace_func 
Example 36
Project: AsemanOs   Author: AsemanOS   File: visualstudio_py_debugger.py    GNU General Public License v3.0 5 votes vote down vote up
def handle_return(self, frame, arg):
        self.pop_frame()

        if not DETACHED:
            stepping = self.stepping
            # only update stepping state when this frame is debuggable (matching handle_call)
            if stepping is not STEPPING_NONE and should_debug_code(frame.f_code):
                if stepping > STEPPING_OVER:
                    self.stepping -= 1
                elif stepping < STEPPING_OUT:
                    self.stepping += 1
                elif stepping in USER_STEPPING:
                    if self.cur_frame is None or frame.f_code.co_name == "<module>" :
                        # only return to user code modules
                        if self.should_block_on_frame(frame):
                            # restore back the module frame for the step out of a module
                            self.push_frame(ModuleExitFrame(frame))
                            self.stepping = STEPPING_NONE
                            update_all_thread_stacks(self)
                            self.block(lambda: (report_step_finished(self.id), mark_all_threads_for_break(skip_thread = self)))
                            self.pop_frame()
                    elif self.should_block_on_frame(self.cur_frame):
                        # if we're returning into non-user code then don't block in the
                        # non-user code, wait until we hit user code again
                        self.stepping = STEPPING_NONE
                        update_all_thread_stacks(self)
                        self.block(lambda: (report_step_finished(self.id), mark_all_threads_for_break(skip_thread = self)))

        # forward call to previous trace function, if any
        old_trace_func = self.prev_trace_func
        if old_trace_func is not None:
            old_trace_func(frame, 'return', arg)

        # restore previous frames trace function if there is one
        if self.trace_func_stack:
            self.prev_trace_func = self.trace_func_stack.pop() 
Example 37
Project: arkScript   Author: akbchris   File: adb.py    MIT License 5 votes vote down vote up
def _dumpf(frame):
    if frame is None:
        return "<None>"
    else:
        addn = "(with trace!)"
        if frame.f_trace is None:
            addn = " **No Trace Set **"
        return "Frame at %d, file %s, line: %d%s" % (id(frame), frame.f_code.co_filename, frame.f_lineno, addn) 
Example 38
Project: arkScript   Author: akbchris   File: adb.py    MIT License 5 votes vote down vote up
def dispatch_return(self, frame, arg):
        traceenter("dispatch_return", _dumpf(frame), arg)
        if self.logicalbotframe is frame:
            # We dont want to debug parent frames.
            tracev("dispatch_return resetting sys.trace")
            sys.settrace(None)
            return
#                       self.bSetTrace = 0
        self.currentframe = frame.f_back
        return bdb.Bdb.dispatch_return(self, frame, arg) 
Example 39
Project: arkScript   Author: akbchris   File: adb.py    MIT License 5 votes vote down vote up
def trace_dispatch(self, frame, event, arg):
        traceenter("trace_dispatch", _dumpf(frame), event, arg)
        if self.debugApplication is None:
            trace("trace_dispatch has no application!")
            return # None
        return bdb.Bdb.trace_dispatch(self, frame, event, arg)


    #
    # The user functions do bugger all!
    #
#       def user_call(self, frame, argument_list):
#               traceenter("user_call",_dumpf(frame)) 
Example 40
Project: arkScript   Author: akbchris   File: adb.py    MIT License 5 votes vote down vote up
def AttachApp(self, debugApplication, codeContainerProvider):
#               traceenter("AttachApp", debugApplication, codeContainerProvider)
        self.codeContainerProvider = codeContainerProvider
        self.debugApplication = debugApplication
        self.stackSniffer = _wrap(stackframe.DebugStackFrameSniffer(self), axdebug.IID_IDebugStackFrameSniffer)
        self.stackSnifferCookie = debugApplication.AddStackFrameSniffer(self.stackSniffer)
#               trace("StackFrameSniffer added (%d)" % self.stackSnifferCookie)

        # Connect to the application events.
        self.appEventConnection = win32com.client.connect.SimpleConnection(self.debugApplication, self, axdebug.IID_IRemoteDebugApplicationEvents) 
Example 41
Project: arkScript   Author: akbchris   File: adb.py    MIT License 5 votes vote down vote up
def SetupAXDebugging(self, baseFrame = None, userFrame = None):
        """Get ready for potential debugging.  Must be called on the thread
        that is being debugged.
        """
        # userFrame is for non AXScript debugging.  This is the first frame of the
        # users code.
        if userFrame is None:
            userFrame = baseFrame
        else:
            # We have missed the "dispatch_call" function, so set this up now!
            userFrame.f_locals['__axstack_address__'] = axdebug.GetStackAddress()

        traceenter("SetupAXDebugging", self)
        self._threadprotectlock.acquire()
        try:
            thisThread = win32api.GetCurrentThreadId()
            if self.debuggingThread is None:
                self.debuggingThread = thisThread
            else:
                if self.debuggingThread!=thisThread:
                    trace("SetupAXDebugging called on other thread - ignored!")
                    return
                # push our context.
                self.recursiveData.insert(0, (self.logicalbotframe,self.stopframe, self.currentframe,self.debuggingThreadStateHandle))
        finally:
            self._threadprotectlock.release()

        trace("SetupAXDebugging has base frame as", _dumpf(baseFrame))
        self.botframe = baseFrame
        self.stopframe = userFrame
        self.logicalbotframe = baseFrame
        self.currentframe = None
        self.debuggingThreadStateHandle = axdebug.GetThreadStateHandle()

        self._BreakFlagsChanged()

    # RemoteDebugApplicationEvents 
Example 42
Project: arkScript   Author: akbchris   File: adb.py    MIT License 5 votes vote down vote up
def _BreakFlagsChanged(self):
        traceenter("_BreakFlagsChanged to %s with our thread = %s, and debugging thread = %s" % (self.breakFlags, self.debuggingThread, win32api.GetCurrentThreadId()))
        trace("_BreakFlagsChanged has breaks", self.breaks)
        # If a request comes on our debugging thread, then do it now!
#               if self.debuggingThread!=win32api.GetCurrentThreadId():
#                       return

        if len(self.breaks) or self.breakFlags:

            if self.logicalbotframe:
                trace("BreakFlagsChange with bot frame", _dumpf(self.logicalbotframe))
                # We have frames not to be debugged (eg, Scripting engine frames
                # (sys.settrace will be set when out logicalbotframe is hit -
                #  this may not be the right thing to do, as it may not cause the
                #  immediate break we desire.)
                self.logicalbotframe.f_trace = self.trace_dispatch
            else:
                trace("BreakFlagsChanged, but no bottom frame")
                if self.stopframe is not None:
                    self.stopframe.f_trace = self.trace_dispatch
            # If we have the thread-state for the thread being debugged, then
            # we dynamically set its trace function - it is possible that the thread
            # being debugged is in a blocked call (eg, a message box) and we
            # want to hit the debugger the instant we return
        if self.debuggingThreadStateHandle is not None and \
                self.breakFlags and \
                self.debuggingThread != win32api.GetCurrentThreadId():
            axdebug.SetThreadStateTrace(self.debuggingThreadStateHandle, self.trace_dispatch) 
Example 43
Project: AsemanOs   Author: AsemanOS   File: visualstudio_py_debugger.py    GNU General Public License v3.0 4 votes vote down vote up
def is_handled(self, thread, ex_type, ex_value, trace):
        if trace is None:
            # get out if we didn't get a traceback
            return False

        if trace.tb_next is not None:
            if should_send_frame(trace.tb_next.tb_frame) and should_debug_code(trace.tb_next.tb_frame.f_code):
                # don't break if this is not the top of the traceback,
                # unless the previous frame was not debuggable
                return True
            
        cur_frame = trace.tb_frame
        
        while should_send_frame(cur_frame) and cur_frame.f_code is not None and cur_frame.f_code.co_filename is not None:
            filename = path.normcase(cur_frame.f_code.co_filename)
            if is_file_in_zip(filename):
                # File is in a zip, so assume it handles exceptions
                return True

            if not is_same_py_file(filename, __file__):
                handlers = self.handler_cache.get(filename)
            
                if handlers is None:
                    # req handlers for this file from the debug engine
                    self.handler_lock.acquire()
                
                    with _SendLockCtx:
                        write_bytes(conn, REQH)
                        write_string(conn, filename)

                    # wait for the handler data to be received
                    self.handler_lock.acquire()
                    self.handler_lock.release()

                    handlers = self.handler_cache.get(filename)

                if handlers is None:
                    # no code available, so assume unhandled
                    return False

                line = cur_frame.f_lineno
                for line_start, line_end, expressions in handlers:
                    if line_start is None or line_start <= line < line_end:
                        if '*' in expressions:
                            return True

                        for text in expressions:
                            try:
                                res = lookup_local(cur_frame, text)
                                if res is not None and issubclass(ex_type, res):
                                    return True
                            except:
                                pass

            cur_frame = cur_frame.f_back

        return False 
Example 44
Project: AsemanOs   Author: AsemanOS   File: visualstudio_py_debugger.py    GNU General Public License v3.0 4 votes vote down vote up
def report_exception(frame, exc_info, tid, break_type):
    exc_type = exc_info[0]
    exc_name = get_exception_name(exc_type)
    exc_value = exc_info[1]
    tb_value = exc_info[2]
    
    if type(exc_value) is tuple:
        # exception object hasn't been created yet, create it now 
        # so we can get the correct msg.
        exc_value = exc_type(*exc_value)
    
    data = {
        'typename': get_exception_name(exc_type),
        'message': str(exc_value),
    }
    if break_type == 1:
        data['breaktype'] = 'unhandled'
    if tb_value:
        try:
            data['trace'] = '\n'.join(','.join(repr(v) for v in line) for line in traceback.extract_tb(tb_value))
        except:
            pass
    if not DJANGO_DEBUG or get_django_frame_source(frame) is None:
        data['excvalue'] = '__exception_info'
        i = 0
        while data['excvalue'] in frame.f_locals:
            i += 1
            data['excvalue'] = '__exception_info_%d' % i
        frame.f_locals[data['excvalue']] = {
            'exception': exc_value,
            'exception_type': exc_type,
            'message': data['message'],
        }

    with _SendLockCtx:
        if RICH_EXCEPTIONS:
            write_bytes(conn, EXC2)
            write_int(conn, tid)
            write_int(conn, len(data))
            for key, value in data.items():
                write_string(conn, key)
                write_string(conn, str(value))
        else:
            # Old message is fixed format. If RichExceptions is not passed in
            # debug options, we'll send this format.
            write_bytes(conn, EXCP)
            write_string(conn, str(data['typename']))
            write_int(conn, tid)
            write_int(conn, 1 if 'breaktype' in data else 0)
            write_string(conn, str(data['message'])) 
Example 45
Project: AsemanOs   Author: AsemanOS   File: visualstudio_py_debugger.py    GNU General Public License v3.0 4 votes vote down vote up
def debug(file, port_num, debug_id, debug_options, currentPid, run_as = 'script'):
    # remove us from modules so there's no trace of us
    sys.modules['$visualstudio_py_debugger'] = sys.modules['visualstudio_py_debugger']
    __name__ = '$visualstudio_py_debugger'
    del sys.modules['visualstudio_py_debugger']

    wait_on_normal_exit = 'WaitOnNormalExit' in debug_options

    ## Begin modification by Don Jayamanne
    # Pass current Process id to pass back to debugger
    attach_process(port_num, debug_id, debug_options, currentPid, report = True)
    ## End Modification by Don Jayamanne

    # setup the current thread
    cur_thread = new_thread()
    cur_thread.stepping = STEPPING_LAUNCH_BREAK

    # start tracing on this thread
    sys.settrace(cur_thread.trace_func)

    # now execute main file
    globals_obj = {'__name__': '__main__'}
    try:
        if run_as == 'module':
            exec_module(file, globals_obj)
        elif run_as == 'code':
            exec_code(file, '<string>', globals_obj)
        else:
            exec_file(file, globals_obj)
    finally:
        sys.settrace(None)
        THREADS_LOCK.acquire()
        del THREADS[cur_thread.id]
        THREADS_LOCK.release()
        report_thread_exit(cur_thread)

        # Give VS debugger a chance to process commands
        # by waiting for ack of "last" command
        global _threading
        if _threading is None:
            import threading
            _threading = threading
        global last_ack_event
        last_ack_event = _threading.Event()
        with _SendLockCtx:
            write_bytes(conn, LAST)
        last_ack_event.wait(5)

    if wait_on_normal_exit:
        do_wait()

# Code objects for functions which are going to be at the bottom of the stack, right below the first
# stack frame for user code. When we walk the stack to determine whether to report or block on a given
# frame, hitting any of these means that we walked all the frames that we needed to look at. 
Example 46
Project: AsemanOs   Author: AsemanOS   File: visualstudio_py_debugger.py    GNU General Public License v3.0 4 votes vote down vote up
def report_exception(frame, exc_info, tid, break_type):
    exc_type = exc_info[0]
    exc_name = get_exception_name(exc_type)
    exc_value = exc_info[1]
    tb_value = exc_info[2]
    
    if type(exc_value) is tuple:
        # exception object hasn't been created yet, create it now 
        # so we can get the correct msg.
        exc_value = exc_type(*exc_value)
    
    data = {
        'typename': get_exception_name(exc_type),
        'message': str(exc_value),
    }
    if break_type == 1:
        data['breaktype'] = 'unhandled'
    if tb_value:
        try:
            data['trace'] = '\n'.join(','.join(repr(v) for v in line) for line in traceback.extract_tb(tb_value))
        except:
            pass
    if not DJANGO_DEBUG or get_django_frame_source(frame) is None:
        data['excvalue'] = '__exception_info'
        i = 0
        while data['excvalue'] in frame.f_locals:
            i += 1
            data['excvalue'] = '__exception_info_%d' % i
        frame.f_locals[data['excvalue']] = {
            'exception': exc_value,
            'exception_type': exc_type,
            'message': data['message'],
        }

    with _SendLockCtx:
        if RICH_EXCEPTIONS:
            write_bytes(conn, EXC2)
            write_int(conn, tid)
            write_int(conn, len(data))
            for key, value in data.items():
                write_string(conn, key)
                write_string(conn, str(value))
        else:
            # Old message is fixed format. If RichExceptions is not passed in
            # debug options, we'll send this format.
            write_bytes(conn, EXCP)
            write_string(conn, str(data['typename']))
            write_int(conn, tid)
            write_int(conn, 1 if 'breaktype' in data else 0)
            write_string(conn, str(data['message'])) 
Example 47
Project: AsemanOs   Author: AsemanOS   File: visualstudio_py_debugger.py    GNU General Public License v3.0 4 votes vote down vote up
def debug(file, port_num, debug_id, debug_options, currentPid, run_as = 'script'):
    # remove us from modules so there's no trace of us
    sys.modules['$visualstudio_py_debugger'] = sys.modules['visualstudio_py_debugger']
    __name__ = '$visualstudio_py_debugger'
    del sys.modules['visualstudio_py_debugger']

    wait_on_normal_exit = 'WaitOnNormalExit' in debug_options

    ## Begin modification by Don Jayamanne
    # Pass current Process id to pass back to debugger
    attach_process(port_num, debug_id, debug_options, currentPid, report = True)
    ## End Modification by Don Jayamanne

    # setup the current thread
    cur_thread = new_thread()
    cur_thread.stepping = STEPPING_LAUNCH_BREAK

    # start tracing on this thread
    sys.settrace(cur_thread.trace_func)

    # now execute main file
    globals_obj = {'__name__': '__main__'}
    try:
        if run_as == 'module':
            exec_module(file, globals_obj)
        elif run_as == 'code':
            exec_code(file, '<string>', globals_obj)
        else:
            exec_file(file, globals_obj)
    finally:
        sys.settrace(None)
        THREADS_LOCK.acquire()
        del THREADS[cur_thread.id]
        THREADS_LOCK.release()
        report_thread_exit(cur_thread)

        # Give VS debugger a chance to process commands
        # by waiting for ack of "last" command
        global _threading
        if _threading is None:
            import threading
            _threading = threading
        global last_ack_event
        last_ack_event = _threading.Event()
        with _SendLockCtx:
            write_bytes(conn, LAST)
        last_ack_event.wait(5)

    if wait_on_normal_exit:
        do_wait()

# Code objects for functions which are going to be at the bottom of the stack, right below the first
# stack frame for user code. When we walk the stack to determine whether to report or block on a given
# frame, hitting any of these means that we walked all the frames that we needed to look at.