def on_attach_request(self, py_db, request): ''' :param AttachRequest request: ''' self._set_debug_options(py_db, request.arguments.kwargs) response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_variables_request(self, py_db, request): ''' Variables can be asked whenever some place returned a variables reference (so, it can be a scope gotten from on_scopes_request, the result of some evaluation, etc.). Note that in the DAP the variables reference requires a unique int... the way this works for pydevd is that an instance is generated for that specific variable reference and we use its id(instance) to identify it to make sure all items are unique (and the actual {id->instance} is added to a dict which is only valid while the thread is suspended and later cleared when the related thread resumes execution). see: SuspendedFramesManager :param VariablesRequest request: ''' arguments = request.arguments # : :type arguments: VariablesArguments variables_reference = arguments.variablesReference thread_id = py_db.suspended_frames_manager.get_thread_id_for_variable_reference( variables_reference) if thread_id is not None: self.api.request_get_variable_json(py_db, request, thread_id) else: variables = [] body = VariablesResponseBody(variables) variables_response = pydevd_base_schema.build_response(request, kwargs={ 'body': body, 'success': False, 'message': 'Unable to find thread to evaluate variable reference.' }) return NetCommand(CMD_RETURN, 0, variables_response, is_json=True)
def on_completions_request(self, py_db, request): ''' :param CompletionsRequest request: ''' arguments = request.arguments # : :type arguments: CompletionsArguments seq = request.seq text = arguments.text frame_id = arguments.frameId thread_id = py_db.suspended_frames_manager.get_thread_id_for_variable_reference( frame_id) if thread_id is None: body = CompletionsResponseBody([]) variables_response = pydevd_base_schema.build_response( request, kwargs={ 'body': body, 'success': False, 'message': 'Thread to get completions seems to have resumed already.' }) return NetCommand(CMD_RETURN, 0, variables_response, is_json=True) # Note: line and column are 1-based (convert to 0-based for pydevd). column = arguments.column - 1 if arguments.line is None: # line is optional line = -1 else: line = arguments.line - 1 self.api.request_completions(py_db, seq, thread_id, frame_id, text, line=line, column=column)
def on_configurationdone_request(self, py_db, request): ''' :param ConfigurationDoneRequest request: ''' self.api.run(py_db) configuration_done_response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, configuration_done_response, is_json=True)
def _handle_launch_or_attach_request(self, py_db, request, start_reason): self._send_process_event(py_db, start_reason) self._launch_or_attach_request_done = True self.api.set_enable_thread_notifications(py_db, True) self._set_debug_options(py_db, request.arguments.kwargs, start_reason=start_reason) response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_setdebuggerproperty_request(self, py_db, request): args = request.arguments if args.ideOS is not None: self.api.set_ide_os(args.ideOS) if args.dontTraceStartPatterns is not None and args.dontTraceEndPatterns is not None: start_patterns = tuple(args.dontTraceStartPatterns) end_patterns = tuple(args.dontTraceEndPatterns) self.api.set_dont_trace_start_end_patterns(py_db, start_patterns, end_patterns) if args.skipSuspendOnBreakpointException is not None: py_db.skip_suspend_on_breakpoint_exception = tuple( get_exception_class(x) for x in args.skipSuspendOnBreakpointException) if args.skipPrintBreakpointException is not None: py_db.skip_print_breakpoint_exception = tuple( get_exception_class(x) for x in args.skipPrintBreakpointException) if args.multiThreadsSingleNotification is not None: py_db.multi_threads_single_notification = args.multiThreadsSingleNotification # TODO: Support other common settings. Note that not all of these might be relevant to python. # JustMyCodeStepping: 0 or 1 # AllowOutOfProcessSymbols: 0 or 1 # DisableJITOptimization: 0 or 1 # InterpreterOptions: 0 or 1 # StopOnExceptionCrossingManagedBoundary: 0 or 1 # WarnIfNoUserCodeOnLaunch: 0 or 1 # EnableStepFiltering: true of false response = pydevd_base_schema.build_response(request, kwargs={'body': {}}) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def test_schema_translation_thread(): from _pydevd_bundle._debug_adapter.pydevd_schema import ThreadsRequest pydevd_base_schema.BaseSchema.initialize_ids_translation() threads = [ pydevd_schema.Thread(id=2 ** 45, name='foo').to_dict(), pydevd_schema.Thread(id=2 ** 46, name='bar').to_dict(), ] body = pydevd_schema.ThreadsResponseBody(threads) threads_request = ThreadsRequest() threads_response = pydevd_base_schema.build_response(threads_request, kwargs=dict(body=body)) as_dict = threads_response.to_dict(update_ids_to_dap=True) assert as_dict == { 'type': 'response', 'request_seq':-1, 'success': True, 'command': 'threads', 'body': {'threads': [ {'id': 1, 'name': 'foo'}, {'id': 2, 'name': 'bar'}, ]}, 'seq':-1} reconstructed = pydevd_base_schema.from_dict(as_dict, update_ids_from_dap=True) assert reconstructed.to_dict() == { 'type': 'response', 'request_seq':-1, 'success': True, 'command': 'threads', 'body': {'threads': [ {'id': 2 ** 45, 'name': 'foo'}, {'id': 2 ** 46, 'name': 'bar'} ]}, 'seq':-1 }
def test_schema_translation_frame(): pydevd_base_schema.BaseSchema.initialize_ids_translation() stack_trace_arguments = pydevd_schema.StackTraceArguments(threadId=1) stack_trace_request = pydevd_schema.StackTraceRequest(stack_trace_arguments) stackFrames = [ pydevd_schema.StackFrame(id=2 ** 45, name='foo', line=1, column=1).to_dict(), pydevd_schema.StackFrame(id=2 ** 46, name='bar', line=1, column=1).to_dict(), ] body = pydevd_schema.StackTraceResponseBody(stackFrames) stack_trace_response = pydevd_base_schema.build_response(stack_trace_request, kwargs=dict(body=body)) as_dict = stack_trace_response.to_dict(update_ids_to_dap=True) assert as_dict == { 'type': 'response', 'request_seq':-1, 'success': True, 'command': 'stackTrace', 'body': {'stackFrames': [ {'id': 1, 'name': 'foo', 'line': 1, 'column': 1, 'source': {}}, {'id': 2, 'name': 'bar', 'line': 1, 'column': 1, 'source': {}}, ]}, 'seq':-1} reconstructed = pydevd_base_schema.from_dict(as_dict, update_ids_from_dap=True) assert reconstructed.to_dict() == { 'type': 'response', 'request_seq':-1, 'success': True, 'command': 'stackTrace', 'body': {'stackFrames': [ {'id': 2 ** 45, 'name': 'foo', 'line': 1, 'column': 1, 'source': {}}, {'id': 2 ** 46, 'name': 'bar', 'line': 1, 'column': 1, 'source': {}} ]}, 'seq':-1 }
def on_goto_request(self, py_db, request): target_id = int(request.arguments.targetId) thread_id = request.arguments.threadId try: _, line = self._goto_targets_map.obtain_value(target_id) except KeyError: response = pydevd_base_schema.build_response(request, kwargs={ 'body': {}, 'success': False, 'message': 'Unknown goto target id: %d' % (target_id,), }) return NetCommand(CMD_RETURN, 0, response, is_json=True) self.api.request_set_next(py_db, thread_id, CMD_SET_NEXT_STATEMENT, line, '*') response = pydevd_base_schema.build_response(request, kwargs={'body': {}}) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_launch_request(self, py_db, request): ''' :param LaunchRequest request: ''' self.api.set_enable_thread_notifications(py_db, True) self._set_debug_options(py_db, request.arguments.kwargs) response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_pydevdauthorize_request(self, py_db, request): ide_access_token = py_db.authentication.ide_access_token body = {'clientAccessToken': None} if ide_access_token: body['clientAccessToken'] = ide_access_token response = pydevd_base_schema.build_response(request, kwargs={'body': body}) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_initialize_request(self, py_db, request): body = Capabilities( # Supported. supportsConfigurationDoneRequest=True, supportsConditionalBreakpoints=True, supportsHitConditionalBreakpoints=True, supportsEvaluateForHovers=True, supportsSetVariable=True, supportsGotoTargetsRequest=True, supportsCompletionsRequest=True, supportsModulesRequest=True, supportsExceptionOptions=True, supportsValueFormattingOptions=True, supportsExceptionInfoRequest=True, supportTerminateDebuggee=True, supportsDelayedStackTraceLoading=True, supportsLogPoints=True, supportsSetExpression=True, supportsTerminateRequest=True, exceptionBreakpointFilters=[ { 'filter': 'raised', 'label': 'Raised Exceptions', 'default': False }, { 'filter': 'uncaught', 'label': 'Uncaught Exceptions', 'default': True }, ], # Not supported. supportsFunctionBreakpoints=False, supportsStepBack=False, supportsRestartFrame=False, supportsStepInTargetsRequest=False, supportsRestartRequest=False, supportsLoadedSourcesRequest=False, supportsTerminateThreadsRequest=False, supportsDataBreakpoints=False, supportsReadMemoryRequest=False, supportsDisassembleRequest=False, additionalModuleColumns=[], completionTriggerCharacters=[], supportedChecksumAlgorithms=[], ).to_dict() # Non-standard capabilities/info below. body['supportsDebuggerProperties'] = True body['pydevd'] = pydevd_info = {} pydevd_info['processId'] = os.getpid() self.api.notify_initialize(py_db) response = pydevd_base_schema.build_response(request, kwargs={'body': body}) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def _handle_launch_or_attach_request(self, py_db, request, start_reason): self._send_process_event(py_db, start_reason) self._launch_or_attach_request_done = True self.api.set_enable_thread_notifications(py_db, True) self._set_debug_options(py_db, request.arguments.kwargs, start_reason=start_reason) response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_disconnect_request(self, py_db, request): ''' :param DisconnectRequest request: ''' self.api.remove_all_breakpoints(py_db, filename='*') self.api.request_resume_thread(thread_id='*') response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, response.to_dict(), is_json=True)
def on_source_request(self, py_db, request): ''' :param SourceRequest request: ''' source_reference = request.arguments.sourceReference server_filename = None content = None if source_reference != 0: server_filename = pydevd_file_utils.get_server_filename_from_source_reference(source_reference) if not server_filename: server_filename = pydevd_file_utils.get_source_reference_filename_from_linecache(source_reference) if server_filename: # Try direct file access first - it's much faster when available. try: with open(server_filename, 'r') as stream: content = stream.read() except: pass if content is None: # File might not exist at all, or we might not have a permission to read it, # but it might also be inside a zipfile, or an IPython cell. In this case, # linecache might still be able to retrieve the source. lines = (linecache.getline(server_filename, i) for i in itertools.count(1)) lines = itertools.takewhile(bool, lines) # empty lines are '\n', EOF is '' # If we didn't get at least one line back, reset it to None so that it's # reported as error below, and not as an empty file. content = ''.join(lines) or None if content is None: frame_id = pydevd_file_utils.get_frame_id_from_source_reference(source_reference) pydev_log.debug('Found frame id: %s for source reference: %s', frame_id, source_reference) if frame_id is not None: try: content = self.api.get_decompiled_source_from_frame_id(py_db, frame_id) except Exception: pydev_log.exception('Error getting source for frame id: %s', frame_id) content = None body = SourceResponseBody(content or '') response_args = {'body': body} if content is None: if source_reference == 0: message = 'Source unavailable' elif server_filename: message = 'Unable to retrieve source for %s' % (server_filename,) else: message = 'Invalid sourceReference %d' % (source_reference,) response_args.update({'success': False, 'message': message}) response = pydevd_base_schema.build_response(request, kwargs=response_args) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_disconnect_request(self, py_db, request): ''' :param DisconnectRequest request: ''' self._launch_or_attach_request_done = False py_db.enable_output_redirection(False, False) self.api.request_disconnect(py_db, resume_threads=True) response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_disconnect_request(self, py_db, request): ''' :param DisconnectRequest request: ''' self._launch_or_attach_request_done = False py_db.enable_output_redirection(False, False) self.api.request_disconnect(py_db, resume_threads=True) response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_disconnect_request(self, py_db, request): ''' :param DisconnectRequest request: ''' self.api.remove_all_breakpoints(py_db, filename='*') self.api.remove_all_exception_breakpoints(py_db) self.api.request_resume_thread(thread_id='*') response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_setbreakpoints_request(self, py_db, request): ''' :param SetBreakpointsRequest request: ''' arguments = request.arguments # : :type arguments: SetBreakpointsArguments filename = arguments.source.path filename = self.api.filename_to_server(filename) func_name = 'None' self.api.remove_all_breakpoints(py_db, filename) btype = 'python-line' suspend_policy = 'ALL' if not filename.lower().endswith('.py'): if self._debug_options.get('DJANGO_DEBUG', False): btype = 'django-line' elif self._debug_options.get('FLASK_DEBUG', False): btype = 'jinja2-line' breakpoints_set = [] for source_breakpoint in arguments.breakpoints: source_breakpoint = SourceBreakpoint(**source_breakpoint) line = source_breakpoint.line condition = source_breakpoint.condition breakpoint_id = line hit_condition = self._get_hit_condition_expression(source_breakpoint.hitCondition) log_message = source_breakpoint.logMessage if not log_message: is_logpoint = None expression = None else: is_logpoint = True expressions = re.findall(r'\{.*?\}', log_message) if len(expressions) == 0: expression = '{}'.format(repr(log_message)) # noqa else: raw_text = reduce(lambda a, b: a.replace(b, '{}'), expressions, log_message) raw_text = raw_text.replace('"', '\\"') expression_list = ', '.join([s.strip('{').strip('}').strip() for s in expressions]) expression = '"{}".format({})'.format(raw_text, expression_list) self.api.add_breakpoint( py_db, filename, btype, breakpoint_id, line, condition, func_name, expression, suspend_policy, hit_condition, is_logpoint) # Note that the id is made up (the id for pydevd is unique only within a file, so, the # line is used for it). # Also, the id is currently not used afterwards, so, we don't even keep a mapping. breakpoints_set.append({'id':self._next_breakpoint_id(), 'verified': True, 'line': line}) body = {'breakpoints': breakpoints_set} set_breakpoints_response = pydevd_base_schema.build_response(request, kwargs={'body':body}) return NetCommand(CMD_RETURN, 0, set_breakpoints_response.to_dict(), is_json=True)
def on_pause_request(self, py_db, request): ''' :param PauseRequest request: ''' arguments = request.arguments # : :type arguments: PauseArguments thread_id = arguments.threadId self.api.request_suspend_thread(py_db, thread_id=thread_id) response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_configurationdone_request(self, py_db, request): ''' :param ConfigurationDoneRequest request: ''' self.api.run(py_db) configuration_done_response = pydevd_base_schema.build_response( request) return NetCommand(CMD_RETURN, 0, configuration_done_response, is_json=True)
def on_pause_request(self, py_db, request): ''' :param PauseRequest request: ''' arguments = request.arguments # : :type arguments: PauseArguments thread_id = arguments.threadId self.api.request_suspend_thread(py_db, thread_id=thread_id) response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_disconnect_request(self, py_db, request): ''' :param DisconnectRequest request: ''' self.api.set_enable_thread_notifications(py_db, False) self.api.remove_all_breakpoints(py_db, filename='*') self.api.remove_all_exception_breakpoints(py_db) self.api.request_resume_thread(thread_id='*') response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_goto_request(self, py_db, request): target_id = int(request.arguments.targetId) thread_id = request.arguments.threadId try: _, line = self._goto_targets_map.obtain_value(target_id) except KeyError: response = pydevd_base_schema.build_response( request, kwargs={ 'body': {}, 'success': False, 'message': 'Unknown goto target id: %d' % (target_id, ), }) return NetCommand(CMD_RETURN, 0, response, is_json=True) self.api.request_set_next(py_db, thread_id, CMD_SET_NEXT_STATEMENT, line, '*') response = pydevd_base_schema.build_response(request, kwargs={'body': {}}) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_configurationdone_request(self, py_db, request): ''' :param ConfigurationDoneRequest request: ''' if not self._launch_or_attach_request_done: pydev_log.critical('Missing launch request or attach request before configuration done request.') self.api.run(py_db) self.api.notify_configuration_done(py_db) configuration_done_response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, configuration_done_response, is_json=True)
def on_configurationdone_request(self, py_db, request): ''' :param ConfigurationDoneRequest request: ''' if not self._launch_or_attach_request_done: pydev_log.critical('Missing launch request or attach request before configuration done request.') self.api.run(py_db) self.api.notify_configuration_done(py_db) configuration_done_response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, configuration_done_response, is_json=True)
def on_gototargets_request(self, py_db, request): path = request.arguments.source.path line = request.arguments.line target_id = self._goto_targets_map.obtain_key((path, line)) target = { 'id': target_id, 'label': '%s:%s' % (path, line), 'line': line } body = GotoTargetsResponseBody(targets=[target]) response_args = {'body': body} response = pydevd_base_schema.build_response(request, kwargs=response_args) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_gototargets_request(self, py_db, request): path = request.arguments.source.path line = request.arguments.line target_id = self._goto_targets_map.obtain_key((path, line)) target = { 'id': target_id, 'label': '%s:%s' % (path, line), 'line': line } body = GotoTargetsResponseBody(targets=[target]) response_args = {'body': body} response = pydevd_base_schema.build_response(request, kwargs=response_args) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def test_schema_translation_thread(): from _pydevd_bundle._debug_adapter.pydevd_schema import ThreadsRequest pydevd_base_schema.BaseSchema.initialize_ids_translation() threads = [ pydevd_schema.Thread(id=2**45, name='foo').to_dict(), pydevd_schema.Thread(id=2**46, name='bar').to_dict(), ] body = pydevd_schema.ThreadsResponseBody(threads) threads_request = ThreadsRequest() threads_response = pydevd_base_schema.build_response( threads_request, kwargs=dict(body=body)) as_dict = threads_response.to_dict(update_ids_to_dap=True) assert as_dict == { 'type': 'response', 'request_seq': -1, 'success': True, 'command': 'threads', 'body': { 'threads': [ { 'id': 1, 'name': 'foo' }, { 'id': 2, 'name': 'bar' }, ] }, 'seq': -1 } reconstructed = pydevd_base_schema.from_dict(as_dict, update_ids_from_dap=True) assert reconstructed.to_dict() == { 'type': 'response', 'request_seq': -1, 'success': True, 'command': 'threads', 'body': { 'threads': [{ 'id': 2**45, 'name': 'foo' }, { 'id': 2**46, 'name': 'bar' }] }, 'seq': -1 }
def on_scopes_request(self, py_db, request): ''' Scopes are the top-level items which appear for a frame (so, we receive the frame id and provide the scopes it has). :param ScopesRequest request: ''' frame_id = request.arguments.frameId variables_reference = frame_id scopes = [Scope('Locals', int(variables_reference), False).to_dict()] body = ScopesResponseBody(scopes) scopes_response = pydevd_base_schema.build_response(request, kwargs={'body': body}) return NetCommand(CMD_RETURN, 0, scopes_response, is_json=True)
def on_scopes_request(self, py_db, request): ''' Scopes are the top-level items which appear for a frame (so, we receive the frame id and provide the scopes it has). :param ScopesRequest request: ''' frame_id = request.arguments.frameId variables_reference = frame_id scopes = [Scope('Locals', int(variables_reference), False).to_dict()] body = ScopesResponseBody(scopes) scopes_response = pydevd_base_schema.build_response(request, kwargs={'body': body}) return NetCommand(CMD_RETURN, 0, scopes_response, is_json=True)
def on_setdebuggerproperty_request(self, py_db, request): args = request.arguments.kwargs if 'dontTraceStartPatterns' in args and 'dontTraceEndPatterns' in args: start_patterns = tuple(args['dontTraceStartPatterns']) end_patterns = tuple(args['dontTraceEndPatterns']) if self._can_set_dont_trace_pattern(py_db, start_patterns, end_patterns): def dont_trace_files_property_request(abs_path): result = abs_path.startswith(start_patterns) or \ abs_path.endswith(end_patterns) return result dont_trace_files_property_request.start_patterns = start_patterns dont_trace_files_property_request.end_patterns = end_patterns py_db.dont_trace_external_files = dont_trace_files_property_request else: # Don't trace pattern cannot be changed after it is set once. There are caches # throughout the debugger which rely on always having the same file type. message = ("Calls to set or change don't trace patterns (via setDebuggerProperty) are not " "allowed since debugging has already started or don't trace patterns are already set.") pydev_log.critical(message) response_args = {'success':False, 'body': {}, 'message': message} response = pydevd_base_schema.build_response(request, kwargs=response_args) return NetCommand(CMD_RETURN, 0, response, is_json=True) # TODO: Support other common settings. Note that not all of these might be relevant to python. # JustMyCodeStepping: 0 or 1 # AllowOutOfProcessSymbols: 0 or 1 # DisableJITOptimization: 0 or 1 # InterpreterOptions: 0 or 1 # StopOnExceptionCrossingManagedBoundary: 0 or 1 # WarnIfNoUserCodeOnLaunch: 0 or 1 # EnableStepFiltering: true of false response = pydevd_base_schema.build_response(request, kwargs={'body': {}}) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_setbreakpoints_request(self, py_db, request): ''' :param SetBreakpointsRequest request: ''' arguments = request.arguments # : :type arguments: SetBreakpointsArguments filename = arguments.source.path filename = self.api.filename_to_server(filename) func_name = 'None' self.api.remove_all_breakpoints(py_db, filename) btype = 'python-line' suspend_policy = 'ALL' if not filename.lower().endswith('.py'): if self._debug_options.get('DJANGO_DEBUG', False): btype = 'django-line' elif self._debug_options.get('FLASK_DEBUG', False): btype = 'jinja2-line' breakpoints_set = [] for source_breakpoint in arguments.breakpoints: source_breakpoint = SourceBreakpoint(**source_breakpoint) line = source_breakpoint.line condition = source_breakpoint.condition breakpoint_id = line hit_condition = self._get_hit_condition_expression(source_breakpoint.hitCondition) log_message = source_breakpoint.logMessage if not log_message: is_logpoint = None expression = None else: is_logpoint = True expression = convert_dap_log_message_to_expression(log_message) self.api.add_breakpoint( py_db, filename, btype, breakpoint_id, line, condition, func_name, expression, suspend_policy, hit_condition, is_logpoint) # Note that the id is made up (the id for pydevd is unique only within a file, so, the # line is used for it). # Also, the id is currently not used afterwards, so, we don't even keep a mapping. breakpoints_set.append({'id':self._next_breakpoint_id(), 'verified': True, 'line': line}) body = {'breakpoints': breakpoints_set} set_breakpoints_response = pydevd_base_schema.build_response(request, kwargs={'body':body}) return NetCommand(CMD_RETURN, 0, set_breakpoints_response, is_json=True)
def on_stepout_request(self, py_db, request): ''' :param StepOutRequest request: ''' arguments = request.arguments # : :type arguments: StepOutArguments thread_id = arguments.threadId if py_db.get_use_libraries_filter(): step_cmd_id = CMD_STEP_RETURN_MY_CODE else: step_cmd_id = CMD_STEP_RETURN self.api.request_step(py_db, thread_id, step_cmd_id) response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_stepout_request(self, py_db, request): ''' :param StepOutRequest request: ''' arguments = request.arguments # : :type arguments: StepOutArguments thread_id = arguments.threadId if py_db.get_use_libraries_filter(): step_cmd_id = CMD_STEP_RETURN_MY_CODE else: step_cmd_id = CMD_STEP_RETURN self.api.request_step(py_db, thread_id, step_cmd_id) response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_pydevdsysteminfo_request(self, py_db, request): try: pid = os.getpid() except AttributeError: pid = None # It's possible to have the ppid reported from args. In this case, use that instead of the # real ppid (athough we're using `ppid`, what we want in meaning is the `launcher_pid` -- # so, if a python process is launched from another python process, consider that process the # parent and not any intermediary stubs). ppid = py_db.get_arg_ppid() or self.api.get_ppid() try: impl_desc = platform.python_implementation() except AttributeError: impl_desc = PY_IMPL_NAME py_info = pydevd_schema.PydevdPythonInfo( version=PY_VERSION_STR, implementation=pydevd_schema.PydevdPythonImplementationInfo( name=PY_IMPL_NAME, version=PY_IMPL_VERSION_STR, description=impl_desc, )) platform_info = pydevd_schema.PydevdPlatformInfo(name=sys.platform) process_info = pydevd_schema.PydevdProcessInfo( pid=pid, ppid=ppid, executable=sys.executable, bitness=64 if IS_64BIT_PROCESS else 32, ) pydevd_info = pydevd_schema.PydevdInfo( usingCython=USING_CYTHON, usingFrameEval=USING_FRAME_EVAL, ) body = { 'python': py_info, 'platform': platform_info, 'process': process_info, 'pydevd': pydevd_info, } response = pydevd_base_schema.build_response(request, kwargs={'body': body}) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_setvariable_request(self, py_db, request): arguments = request.arguments # : :type arguments: SetVariableArguments variables_reference = arguments.variablesReference thread_id = py_db.suspended_frames_manager.get_thread_id_for_variable_reference( variables_reference) if thread_id is not None: self.api.request_change_variable_json(py_db, request, thread_id) else: body = SetVariableResponseBody('') variables_response = pydevd_base_schema.build_response( request, kwargs={ 'body': body, 'success': False, 'message': 'Unable to find thread to evaluate variable reference.' }) return NetCommand(CMD_RETURN, 0, variables_response, is_json=True)
def on_setvariable_request(self, py_db, request): arguments = request.arguments # : :type arguments: SetVariableArguments variables_reference = arguments.variablesReference thread_id = py_db.suspended_frames_manager.get_thread_id_for_variable_reference( variables_reference) if thread_id is not None: self.api.request_change_variable_json(py_db, request, thread_id) else: body = SetVariableResponseBody('') variables_response = pydevd_base_schema.build_response( request, kwargs={ 'body': body, 'success': False, 'message': 'Unable to find thread to evaluate variable reference.' }) return NetCommand(CMD_RETURN, 0, variables_response, is_json=True)
def on_source_request(self, py_db, request): ''' :param SourceRequest request: ''' source_reference = request.arguments.sourceReference server_filename = None content = None if source_reference != 0: server_filename = pydevd_file_utils.get_server_filename_from_source_reference(source_reference) if server_filename: # Try direct file access first - it's much faster when available. try: with open(server_filename, 'r') as stream: content = stream.read() except: pass if content is None: # File might not exist at all, or we might not have a permission to read it, # but it might also be inside a zipfile, or an IPython cell. In this case, # linecache might still be able to retrieve the source. lines = (linecache.getline(server_filename, i) for i in itertools.count(1)) lines = itertools.takewhile(bool, lines) # empty lines are '\n', EOF is '' # If we didn't get at least one line back, reset it to None so that it's # reported as error below, and not as an empty file. content = ''.join(lines) or None body = SourceResponseBody(content or '') response_args = {'body': body} if content is None: if source_reference == 0: message = 'Source unavailable' elif server_filename: message = 'Unable to retrieve source for %s' % (server_filename,) else: message = 'Invalid sourceReference %d' % (source_reference,) response_args.update({'success': False, 'message': message}) response = pydevd_base_schema.build_response(request, kwargs=response_args) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_setexpression_request(self, py_db, request): # : :type arguments: SetExpressionArguments arguments = request.arguments thread_id = py_db.suspended_frames_manager.get_thread_id_for_variable_reference( arguments.frameId) if thread_id is not None: self.api.request_set_expression_json(py_db, request, thread_id) else: body = SetExpressionResponseBody('') response = pydevd_base_schema.build_response( request, kwargs={ 'body': body, 'success': False, 'message': 'Unable to find thread to set expression.' }) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_setexpression_request(self, py_db, request): # : :type arguments: SetExpressionArguments arguments = request.arguments thread_id = py_db.suspended_frames_manager.get_thread_id_for_variable_reference( arguments.frameId) if thread_id is not None: self.api.request_set_expression_json(py_db, request, thread_id) else: body = SetExpressionResponseBody('') response = pydevd_base_schema.build_response( request, kwargs={ 'body': body, 'success': False, 'message': 'Unable to find thread to set expression.' }) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_setdebuggerproperty_request(self, py_db, request): args = request.arguments.kwargs if 'dontTraceStartPatterns' in args and 'dontTraceEndPatterns' in args: start_patterns = tuple(args['dontTraceStartPatterns']) end_patterns = tuple(args['dontTraceEndPatterns']) self.api.set_dont_trace_start_end_patterns(py_db, start_patterns, end_patterns) # TODO: Support other common settings. Note that not all of these might be relevant to python. # JustMyCodeStepping: 0 or 1 # AllowOutOfProcessSymbols: 0 or 1 # DisableJITOptimization: 0 or 1 # InterpreterOptions: 0 or 1 # StopOnExceptionCrossingManagedBoundary: 0 or 1 # WarnIfNoUserCodeOnLaunch: 0 or 1 # EnableStepFiltering: true of false response = pydevd_base_schema.build_response(request, kwargs={'body': {}}) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_completions_request(self, py_db, request): ''' :param CompletionsRequest request: ''' arguments = request.arguments # : :type arguments: CompletionsArguments seq = request.seq text = arguments.text frame_id = arguments.frameId thread_id = py_db.suspended_frames_manager.get_thread_id_for_variable_reference( frame_id) if thread_id is None: body = CompletionsResponseBody([]) variables_response = pydevd_base_schema.build_response( request, kwargs={ 'body': body, 'success': False, 'message': 'Thread to get completions seems to have resumed already.' }) return NetCommand(CMD_RETURN, 0, variables_response, is_json=True) # Note: line and column are 1-based (convert to 0-based for pydevd). column = arguments.column - 1 if arguments.line is None: # line is optional line = -1 else: line = arguments.line - 1 self.api.request_completions(py_db, seq, thread_id, frame_id, text, line=line, column=column)
def on_pydevdsysteminfo_request(self, py_db, request): try: pid = os.getpid() except AttributeError: pid = None ppid = self.api.get_ppid() try: impl_desc = platform.python_implementation() except AttributeError: impl_desc = PY_IMPL_NAME py_info = pydevd_schema.PydevdPythonInfo( version=PY_VERSION_STR, implementation=pydevd_schema.PydevdPythonImplementationInfo( name=PY_IMPL_NAME, version=PY_IMPL_VERSION_STR, description=impl_desc, ) ) platform_info = pydevd_schema.PydevdPlatformInfo(name=sys.platform) process_info = pydevd_schema.PydevdProcessInfo( pid=pid, ppid=ppid, executable=sys.executable, bitness=64 if IS_64BIT_PROCESS else 32, ) pydevd_info = pydevd_schema.PydevdInfo( usingCython=USING_CYTHON, usingFrameEval=USING_FRAME_EVAL, ) body = { 'python': py_info, 'platform': platform_info, 'process': process_info, 'pydevd': pydevd_info, } response = pydevd_base_schema.build_response(request, kwargs={'body': body}) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_variables_request(self, py_db, request): ''' Variables can be asked whenever some place returned a variables reference (so, it can be a scope gotten from on_scopes_request, the result of some evaluation, etc.). Note that in the DAP the variables reference requires a unique int... the way this works for pydevd is that an instance is generated for that specific variable reference and we use its id(instance) to identify it to make sure all items are unique (and the actual {id->instance} is added to a dict which is only valid while the thread is suspended and later cleared when the related thread resumes execution). see: SuspendedFramesManager :param VariablesRequest request: ''' arguments = request.arguments # : :type arguments: VariablesArguments variables_reference = arguments.variablesReference if isinstance(variables_reference, ScopeRequest): variables_reference = variables_reference.variable_reference thread_id = py_db.suspended_frames_manager.get_thread_id_for_variable_reference( variables_reference) if thread_id is not None: self.api.request_get_variable_json(py_db, request, thread_id) else: variables = [] body = VariablesResponseBody(variables) variables_response = pydevd_base_schema.build_response( request, kwargs={ 'body': body, 'success': False, 'message': 'Unable to find thread to evaluate variable reference.' }) return NetCommand(CMD_RETURN, 0, variables_response, is_json=True)
def on_evaluate_request(self, py_db, request): ''' :param EvaluateRequest request: ''' # : :type arguments: EvaluateArguments arguments = request.arguments thread_id = py_db.suspended_frames_manager.get_thread_id_for_variable_reference( arguments.frameId) if thread_id is not None: self.api.request_exec_or_evaluate_json(py_db, request, thread_id) else: body = EvaluateResponseBody('', 0) response = pydevd_base_schema.build_response( request, kwargs={ 'body': body, 'success': False, 'message': 'Unable to find thread for evaluation.' }) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_evaluate_request(self, py_db, request): ''' :param EvaluateRequest request: ''' # : :type arguments: EvaluateArguments arguments = request.arguments thread_id = py_db.suspended_frames_manager.get_thread_id_for_variable_reference( arguments.frameId) if thread_id is not None: self.api.request_exec_or_evaluate_json( py_db, request, thread_id) else: body = EvaluateResponseBody('', 0) response = pydevd_base_schema.build_response( request, kwargs={ 'body': body, 'success': False, 'message': 'Unable to find thread for evaluation.' }) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_setdebuggerproperty_request(self, py_db, request): args = request.arguments # : :type args: SetDebuggerPropertyArguments if args.ideOS is not None: self.api.set_ide_os(args.ideOS) if args.dontTraceStartPatterns is not None and args.dontTraceEndPatterns is not None: start_patterns = tuple(args.dontTraceStartPatterns) end_patterns = tuple(args.dontTraceEndPatterns) self.api.set_dont_trace_start_end_patterns(py_db, start_patterns, end_patterns) if args.skipSuspendOnBreakpointException is not None: py_db.skip_suspend_on_breakpoint_exception = tuple( get_exception_class(x) for x in args.skipSuspendOnBreakpointException) if args.skipPrintBreakpointException is not None: py_db.skip_print_breakpoint_exception = tuple( get_exception_class(x) for x in args.skipPrintBreakpointException) if args.multiThreadsSingleNotification is not None: py_db.multi_threads_single_notification = args.multiThreadsSingleNotification # TODO: Support other common settings. Note that not all of these might be relevant to python. # JustMyCodeStepping: 0 or 1 # AllowOutOfProcessSymbols: 0 or 1 # DisableJITOptimization: 0 or 1 # InterpreterOptions: 0 or 1 # StopOnExceptionCrossingManagedBoundary: 0 or 1 # WarnIfNoUserCodeOnLaunch: 0 or 1 # EnableStepFiltering: true of false response = pydevd_base_schema.build_response(request, kwargs={'body': {}}) return NetCommand(CMD_RETURN, 0, response, is_json=True)
def on_setbreakpoints_request(self, py_db, request): ''' :param SetBreakpointsRequest request: ''' arguments = request.arguments # : :type arguments: SetBreakpointsArguments # TODO: Path is optional here it could be source reference. filename = arguments.source.path filename = self.api.filename_to_server(filename) func_name = 'None' self.api.remove_all_breakpoints(py_db, filename) # Validate breakpoints and adjust their positions. try: lines = sorted(_get_code_lines(filename)) except Exception: pass else: for bp in arguments.breakpoints: line = bp['line'] if line not in lines: # Adjust to the first preceding valid line. idx = bisect.bisect_left(lines, line) if idx > 0: bp['line'] = lines[idx - 1] btype = 'python-line' suspend_policy = 'ALL' if not filename.lower().endswith('.py'): if self._debug_options.get('DJANGO_DEBUG', False): btype = 'django-line' elif self._debug_options.get('FLASK_DEBUG', False): btype = 'jinja2-line' breakpoints_set = [] for source_breakpoint in arguments.breakpoints: source_breakpoint = SourceBreakpoint(**source_breakpoint) line = source_breakpoint.line condition = source_breakpoint.condition breakpoint_id = line hit_condition = self._get_hit_condition_expression( source_breakpoint.hitCondition) log_message = source_breakpoint.logMessage if not log_message: is_logpoint = None expression = None else: is_logpoint = True expression = convert_dap_log_message_to_expression(log_message) self.api.add_breakpoint(py_db, filename, btype, breakpoint_id, line, condition, func_name, expression, suspend_policy, hit_condition, is_logpoint) # Note that the id is made up (the id for pydevd is unique only within a file, so, the # line is used for it). # Also, the id is currently not used afterwards, so, we don't even keep a mapping. breakpoints_set.append({ 'id': self._next_breakpoint_id(), 'verified': True, 'line': line }) body = {'breakpoints': breakpoints_set} set_breakpoints_response = pydevd_base_schema.build_response( request, kwargs={'body': body}) return NetCommand(CMD_RETURN, 0, set_breakpoints_response, is_json=True)
def test_schema(): json_msg = ''' { "arguments": { "adapterID": "pydevd", "clientID": "vscode", "clientName": "Visual Studio Code", "columnsStartAt1": true, "linesStartAt1": true, "locale": "en-us", "pathFormat": "path", "supportsRunInTerminalRequest": true, "supportsVariablePaging": true, "supportsVariableType": true }, "command": "initialize", "seq": 1, "type": "request" }''' initialize_request = pydevd_base_schema.from_json(json_msg) assert initialize_request.__class__ == InitializeRequest assert initialize_request.arguments.__class__ == InitializeRequestArguments assert initialize_request.arguments.adapterID == 'pydevd' assert initialize_request.command == 'initialize' assert initialize_request.type == 'request' assert initialize_request.seq == 1 response = pydevd_base_schema.build_response(initialize_request) assert response.__class__ == InitializeResponse assert response.seq == -1 # Must be set before sending assert response.command == 'initialize' assert response.type == 'response' assert response.body.__class__ == Capabilities assert response.to_dict() == { "seq":-1, "type": "response", "request_seq": 1, "success": True, "command": "initialize", "body": {} } capabilities = response.body # : :type capabilities: Capabilities capabilities.supportsCompletionsRequest = True assert response.to_dict() == { "seq":-1, "type": "response", "request_seq": 1, "success": True, "command": "initialize", "body": {'supportsCompletionsRequest':True} } initialize_event = pydevd_schema.InitializedEvent() assert initialize_event.to_dict() == { "seq":-1, "type": "event", "event": "initialized" }
def on_setbreakpoints_request(self, py_db, request): ''' :param SetBreakpointsRequest request: ''' arguments = request.arguments # : :type arguments: SetBreakpointsArguments # TODO: Path is optional here it could be source reference. filename = arguments.source.path filename = self.api.filename_to_server(filename) func_name = 'None' self.api.remove_all_breakpoints(py_db, filename) # Validate breakpoints and adjust their positions. try: lines = sorted(_get_code_lines(filename)) except Exception: pass else: for bp in arguments.breakpoints: line = bp['line'] if line not in lines: # Adjust to the first preceding valid line. idx = bisect.bisect_left(lines, line) if idx > 0: bp['line'] = lines[idx - 1] btype = 'python-line' suspend_policy = 'ALL' if not filename.lower().endswith('.py'): if self._debug_options.get('DJANGO_DEBUG', False): btype = 'django-line' elif self._debug_options.get('FLASK_DEBUG', False): btype = 'jinja2-line' breakpoints_set = [] for source_breakpoint in arguments.breakpoints: source_breakpoint = SourceBreakpoint(**source_breakpoint) line = source_breakpoint.line condition = source_breakpoint.condition breakpoint_id = line hit_condition = self._get_hit_condition_expression(source_breakpoint.hitCondition) log_message = source_breakpoint.logMessage if not log_message: is_logpoint = None expression = None else: is_logpoint = True expression = convert_dap_log_message_to_expression(log_message) self.api.add_breakpoint( py_db, filename, btype, breakpoint_id, line, condition, func_name, expression, suspend_policy, hit_condition, is_logpoint) # Note that the id is made up (the id for pydevd is unique only within a file, so, the # line is used for it). # Also, the id is currently not used afterwards, so, we don't even keep a mapping. breakpoints_set.append({'id': self._next_breakpoint_id(), 'verified': True, 'line': line}) body = {'breakpoints': breakpoints_set} set_breakpoints_response = pydevd_base_schema.build_response(request, kwargs={'body': body}) return NetCommand(CMD_RETURN, 0, set_breakpoints_response, is_json=True)
def test_schema(): json_msg = ''' { "arguments": { "adapterID": "pydevd", "clientID": "vscode", "clientName": "Visual Studio Code", "columnsStartAt1": true, "linesStartAt1": true, "locale": "en-us", "pathFormat": "path", "supportsRunInTerminalRequest": true, "supportsVariablePaging": true, "supportsVariableType": true }, "command": "initialize", "seq": 1, "type": "request" }''' initialize_request = pydevd_base_schema.from_json(json_msg) assert initialize_request.__class__ == InitializeRequest assert initialize_request.arguments.__class__ == InitializeRequestArguments assert initialize_request.arguments.adapterID == 'pydevd' assert initialize_request.command == 'initialize' assert initialize_request.type == 'request' assert initialize_request.seq == 1 response = pydevd_base_schema.build_response(initialize_request) assert response.__class__ == InitializeResponse assert response.seq == -1 # Must be set before sending assert response.command == 'initialize' assert response.type == 'response' assert response.body.__class__ == Capabilities assert response.to_dict() == { "seq": -1, "type": "response", "request_seq": 1, "success": True, "command": "initialize", "body": {} } capabilities = response.body # : :type capabilities: Capabilities capabilities.supportsCompletionsRequest = True assert response.to_dict() == { "seq": -1, "type": "response", "request_seq": 1, "success": True, "command": "initialize", "body": { 'supportsCompletionsRequest': True } } initialize_event = pydevd_schema.InitializedEvent() assert initialize_event.to_dict() == { "seq": -1, "type": "event", "event": "initialized" }
def on_setexceptionbreakpoints_request(self, py_db, request): ''' :param SetExceptionBreakpointsRequest request: ''' # : :type arguments: SetExceptionBreakpointsArguments arguments = request.arguments filters = arguments.filters exception_options = arguments.exceptionOptions self.api.remove_all_exception_breakpoints(py_db) # Can't set these in the DAP. condition = None expression = None notify_on_first_raise_only = False ignore_libraries = 1 if py_db.get_use_libraries_filter() else 0 if exception_options: break_raised = True break_uncaught = True for option in exception_options: option = ExceptionOptions(**option) if not option.path: continue notify_on_handled_exceptions = 1 if option.breakMode == 'always' else 0 notify_on_unhandled_exceptions = 1 if option.breakMode in ( 'unhandled', 'userUnhandled') else 0 exception_paths = option.path exception_names = [] if len(exception_paths) == 0: continue elif len(exception_paths) == 1: if 'Python Exceptions' in exception_paths[0]['names']: exception_names = ['BaseException'] else: path_iterator = iter(exception_paths) if 'Python Exceptions' in next(path_iterator)['names']: for path in path_iterator: for ex_name in path['names']: exception_names.append(ex_name) for exception_name in exception_names: self.api.add_python_exception_breakpoint( py_db, exception_name, condition, expression, notify_on_handled_exceptions, notify_on_unhandled_exceptions, notify_on_first_raise_only, ignore_libraries) else: break_raised = 'raised' in filters break_uncaught = 'uncaught' in filters if break_raised or break_uncaught: notify_on_handled_exceptions = 1 if break_raised else 0 notify_on_unhandled_exceptions = 1 if break_uncaught else 0 exception = 'BaseException' self.api.add_python_exception_breakpoint( py_db, exception, condition, expression, notify_on_handled_exceptions, notify_on_unhandled_exceptions, notify_on_first_raise_only, ignore_libraries) if break_raised or break_uncaught: btype = None if self._debug_options.get('DJANGO_DEBUG', False): btype = 'django' elif self._debug_options.get('FLASK_DEBUG', False): btype = 'jinja2' if btype: self.api.add_plugins_exception_breakpoint( py_db, btype, 'BaseException' ) # Note: Exception name could be anything here. # Note: no body required on success. set_breakpoints_response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, set_breakpoints_response, is_json=True)
def on_setbreakpoints_request(self, py_db, request): ''' :param SetBreakpointsRequest request: ''' if not self._launch_or_attach_request_done: # Note that to validate the breakpoints we need the launch request to be done already # (otherwise the filters wouldn't be set for the breakpoint validation). body = SetBreakpointsResponseBody([]) response = pydevd_base_schema.build_response( request, kwargs={ 'body': body, 'success': False, 'message': 'Breakpoints may only be set after the launch request is received.' }) return NetCommand(CMD_RETURN, 0, response, is_json=True) arguments = request.arguments # : :type arguments: SetBreakpointsArguments # TODO: Path is optional here it could be source reference. filename = self.api.filename_to_str(arguments.source.path) func_name = 'None' self.api.remove_all_breakpoints(py_db, filename) btype = 'python-line' suspend_policy = 'ALL' if not filename.lower().endswith( '.py'): # Note: check based on original file, not mapping. if self._debug_options.get('DJANGO_DEBUG', False): btype = 'django-line' elif self._debug_options.get('FLASK_DEBUG', False): btype = 'jinja2-line' breakpoints_set = [] for source_breakpoint in arguments.breakpoints: source_breakpoint = SourceBreakpoint(**source_breakpoint) line = source_breakpoint.line condition = source_breakpoint.condition breakpoint_id = line hit_condition = self._get_hit_condition_expression( source_breakpoint.hitCondition) log_message = source_breakpoint.logMessage if not log_message: is_logpoint = None expression = None else: is_logpoint = True expression = convert_dap_log_message_to_expression(log_message) result = self.api.add_breakpoint(py_db, filename, btype, breakpoint_id, line, condition, func_name, expression, suspend_policy, hit_condition, is_logpoint, adjust_line=True) error_code = result.error_code if error_code: if error_code == self.api.ADD_BREAKPOINT_FILE_NOT_FOUND: error_msg = 'Breakpoint in file that does not exist.' elif error_code == self.api.ADD_BREAKPOINT_FILE_EXCLUDED_BY_FILTERS: error_msg = 'Breakpoint in file excluded by filters.' if py_db.get_use_libraries_filter(): error_msg += ( '\nNote: may be excluded because of "justMyCode" option (default == true).' 'Try setting \"justMyCode\": false in the debug configuration (e.g., launch.json).' ) else: # Shouldn't get here. error_msg = 'Breakpoint not validated (reason unknown -- please report as bug).' breakpoints_set.append( pydevd_schema.Breakpoint( verified=False, line=result.translated_line, message=error_msg, source=arguments.source).to_dict()) else: # Note that the id is made up (the id for pydevd is unique only within a file, so, the # line is used for it). # Also, the id is currently not used afterwards, so, we don't even keep a mapping. breakpoints_set.append( pydevd_schema.Breakpoint( verified=True, id=self._next_breakpoint_id(), line=result.translated_line, source=arguments.source).to_dict()) body = {'breakpoints': breakpoints_set} set_breakpoints_response = pydevd_base_schema.build_response( request, kwargs={'body': body}) return NetCommand(CMD_RETURN, 0, set_breakpoints_response, is_json=True)
def on_modules_request(self, py_db, request): modules_manager = py_db.cmd_factory.modules_manager # : :type modules_manager: ModulesManager modules_info = modules_manager.get_modules_info() body = ModulesResponseBody(modules_info) variables_response = pydevd_base_schema.build_response(request, kwargs={'body': body}) return NetCommand(CMD_RETURN, 0, variables_response, is_json=True)
def on_resumed(): body = {'allThreadsContinued': thread_id == '*'} response = pydevd_base_schema.build_response(request, kwargs={'body': body}) cmd = NetCommand(CMD_RETURN, 0, response, is_json=True) py_db.writer.add_command(cmd)
def on_setexceptionbreakpoints_request(self, py_db, request): ''' :param SetExceptionBreakpointsRequest request: ''' # : :type arguments: SetExceptionBreakpointsArguments arguments = request.arguments filters = arguments.filters exception_options = arguments.exceptionOptions self.api.remove_all_exception_breakpoints(py_db) # Can't set these in the DAP. condition = None expression = None notify_on_first_raise_only = False ignore_libraries = 1 if py_db.get_use_libraries_filter() else 0 if exception_options: break_raised = True break_uncaught = True for option in exception_options: option = ExceptionOptions(**option) if not option.path: continue notify_on_handled_exceptions = 1 if option.breakMode == 'always' else 0 notify_on_unhandled_exceptions = 1 if option.breakMode in ('unhandled', 'userUnhandled') else 0 exception_paths = option.path exception_names = [] if len(exception_paths) == 0: continue elif len(exception_paths) == 1: if 'Python Exceptions' in exception_paths[0]['names']: exception_names = ['BaseException'] else: path_iterator = iter(exception_paths) if 'Python Exceptions' in next(path_iterator)['names']: for path in path_iterator: for ex_name in path['names']: exception_names.append(ex_name) for exception_name in exception_names: self.api.add_python_exception_breakpoint( py_db, exception_name, condition, expression, notify_on_handled_exceptions, notify_on_unhandled_exceptions, notify_on_first_raise_only, ignore_libraries ) else: break_raised = 'raised' in filters break_uncaught = 'uncaught' in filters if break_raised or break_uncaught: notify_on_handled_exceptions = 1 if break_raised else 0 notify_on_unhandled_exceptions = 1 if break_uncaught else 0 exception = 'BaseException' self.api.add_python_exception_breakpoint( py_db, exception, condition, expression, notify_on_handled_exceptions, notify_on_unhandled_exceptions, notify_on_first_raise_only, ignore_libraries ) if break_raised or break_uncaught: btype = None if self._debug_options.get('DJANGO_DEBUG', False): btype = 'django' elif self._debug_options.get('FLASK_DEBUG', False): btype = 'jinja2' if btype: self.api.add_plugins_exception_breakpoint( py_db, btype, 'BaseException') # Note: Exception name could be anything here. # Note: no body required on success. set_breakpoints_response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, set_breakpoints_response, is_json=True)
def on_resumed(): body = {'allThreadsContinued': thread_id == '*'} response = pydevd_base_schema.build_response(request, kwargs={'body': body}) cmd = NetCommand(CMD_RETURN, 0, response, is_json=True) py_db.writer.add_command(cmd)
def on_setbreakpoints_request(self, py_db, request): ''' :param SetBreakpointsRequest request: ''' if not self._launch_or_attach_request_done: # Note that to validate the breakpoints we need the launch request to be done already # (otherwise the filters wouldn't be set for the breakpoint validation). body = SetBreakpointsResponseBody([]) response = pydevd_base_schema.build_response( request, kwargs={ 'body': body, 'success': False, 'message': 'Breakpoints may only be set after the launch request is received.' }) return NetCommand(CMD_RETURN, 0, response, is_json=True) arguments = request.arguments # : :type arguments: SetBreakpointsArguments # TODO: Path is optional here it could be source reference. filename = arguments.source.path filename = self.api.filename_to_server(filename) func_name = 'None' self.api.remove_all_breakpoints(py_db, filename) # Validate breakpoints and adjust their positions. try: lines = sorted(_get_code_lines(filename)) except Exception: pass else: for bp in arguments.breakpoints: line = bp['line'] if line not in lines: # Adjust to the first preceding valid line. idx = bisect.bisect_left(lines, line) if idx > 0: bp['line'] = lines[idx - 1] btype = 'python-line' suspend_policy = 'ALL' if not filename.lower().endswith('.py'): if self._debug_options.get('DJANGO_DEBUG', False): btype = 'django-line' elif self._debug_options.get('FLASK_DEBUG', False): btype = 'jinja2-line' breakpoints_set = [] for source_breakpoint in arguments.breakpoints: source_breakpoint = SourceBreakpoint(**source_breakpoint) line = source_breakpoint.line condition = source_breakpoint.condition breakpoint_id = line hit_condition = self._get_hit_condition_expression(source_breakpoint.hitCondition) log_message = source_breakpoint.logMessage if not log_message: is_logpoint = None expression = None else: is_logpoint = True expression = convert_dap_log_message_to_expression(log_message) error_code = self.api.add_breakpoint( py_db, filename, btype, breakpoint_id, line, condition, func_name, expression, suspend_policy, hit_condition, is_logpoint) if error_code: if error_code == self.api.ADD_BREAKPOINT_FILE_NOT_FOUND: error_msg = 'Breakpoint in file that does not exist.' elif error_code == self.api.ADD_BREAKPOINT_FILE_EXCLUDED_BY_FILTERS: error_msg = 'Breakpoint in file excluded by filters.' if py_db.get_use_libraries_filter(): error_msg += '\nNote: may be excluded because of "justMyCode" option (default == true).' else: # Shouldn't get here. error_msg = 'Breakpoint not validated (reason unknown -- please report as bug).' breakpoints_set.append(pydevd_schema.Breakpoint( verified=False, line=line, message=error_msg).to_dict()) else: # Note that the id is made up (the id for pydevd is unique only within a file, so, the # line is used for it). # Also, the id is currently not used afterwards, so, we don't even keep a mapping. breakpoints_set.append(pydevd_schema.Breakpoint( verified=True, id=self._next_breakpoint_id(), line=line).to_dict()) body = {'breakpoints': breakpoints_set} set_breakpoints_response = pydevd_base_schema.build_response(request, kwargs={'body': body}) return NetCommand(CMD_RETURN, 0, set_breakpoints_response, is_json=True)