diff --git a/.github/actions/launchable/setup/action.yaml b/.github/actions/launchable/setup/action.yaml new file mode 100644 index 000000000..b5c0c920f --- /dev/null +++ b/.github/actions/launchable/setup/action.yaml @@ -0,0 +1,79 @@ +name: Set up Launchable +description: >- + Install the required dependencies and execute the necessary Launchable commands for test recording + +inputs: + report-path: + default: launchable_reports.json + required: true + description: The file path of the test report for uploading to Launchable + + test-task: + default: none + required: true + description: >- + Test task that determine how tests are run. + This value is used in the Launchable flavor. + +runs: + using: composite + + steps: + - name: Enable Launchable conditionally + id: enable-launchable + run: echo "enable-launchable=true" >> $GITHUB_OUTPUT + shell: bash + if: ${{ github.repository == 'ruby/debug' }} + + # Launchable CLI requires Python and Java. + # https://www.launchableinc.com/docs/resources/cli-reference/ + - name: Set up Python + uses: actions/setup-python@871daa956ca9ea99f3c3e30acb424b7960676734 # v5.0.0 + with: + python-version: "3.x" + if: ${{ steps.enable-launchable.outputs.enable-launchable }} + + - name: Set up Java + uses: actions/setup-java@7a445ee88d4e23b52c33fdc7601e40278616c7f8 # v4.0.0 + with: + distribution: 'temurin' + java-version: '17' + if: ${{ steps.enable-launchable.outputs.enable-launchable }} + + - name: Set environment variables for Launchable + shell: bash + run: | + : # GITHUB_PULL_REQUEST_URL are used for commenting test reports in Launchable Github App. + : # https://github.com/launchableinc/cli/blob/v1.80.1/launchable/utils/link.py#L42 + echo "GITHUB_PULL_REQUEST_URL=${{ github.event.pull_request.html_url }}" >> $GITHUB_ENV + : # The following envs are necessary in Launchable tokenless authentication. + : # https://github.com/launchableinc/cli/blob/v1.80.1/launchable/utils/authentication.py#L20 + echo "LAUNCHABLE_ORGANIZATION=${{ github.repository_owner }}" >> $GITHUB_ENV + echo "LAUNCHABLE_WORKSPACE=${{ github.event.repository.name }}" >> $GITHUB_ENV + : # https://github.com/launchableinc/cli/blob/v1.80.1/launchable/utils/authentication.py#L71 + echo "GITHUB_PR_HEAD_SHA=${{ github.event.pull_request.head.sha || github.sha }}" >> $GITHUB_ENV + if: ${{ steps.enable-launchable.outputs.enable-launchable }} + + - name: Set up Launchable + shell: bash + run: | + set -x + PATH=$PATH:$(python -msite --user-base)/bin + echo "PATH=$PATH" >> $GITHUB_ENV + pip install --user launchable + launchable verify + : # The build name cannot include a slash, so we replace the string here. + github_ref="${{ github.ref }}" + github_ref="${github_ref//\//_}" + launchable record build --name ${github_ref}_${GITHUB_PR_HEAD_SHA} + echo "TESTOPTS=${TESTOPTS} --runner=launchable --launchable-test-report-json=${{ inputs.report-path }}" >> $GITHUB_ENV + if: ${{ steps.enable-launchable.outputs.enable-launchable }} + + - name: Record test results in Launchable + uses: gacts/run-and-post-run@674528335da98a7afc80915ff2b4b860a0b3553a # v1.4.0 + with: + shell: bash + post: | + launchable record tests --flavor os=${{ inputs.os }} --flavor test_task=${{ inputs.test-task }} raw ${{ inputs.report-path }} + rm -f ${{ inputs.report-path }} + if: ${{ always() && steps.enable-launchable.outputs.enable-launchable }} diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..b18fd2935 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,6 @@ +version: 2 +updates: + - package-ecosystem: 'github-actions' + directory: '/' + schedule: + interval: 'weekly' diff --git a/.github/workflows/protocol.yml b/.github/workflows/protocol.yml index c756a0538..666ab4375 100644 --- a/.github/workflows/protocol.yml +++ b/.github/workflows/protocol.yml @@ -1,10 +1,3 @@ -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. -# This workflow will download a prebuilt Ruby version, install dependencies and run tests with Rake -# For more information see: https://github.com/marketplace/actions/setup-ruby-jruby-and-truffleruby - name: Protocol on: @@ -13,27 +6,44 @@ on: pull_request: branches: [ master ] +permissions: + contents: read + jobs: - test: + ruby-versions: + uses: ruby/actions/.github/workflows/ruby_versions.yml@master + with: + engine: cruby + min_version: 2.7 + versions: '["debug"]' + test: + needs: ruby-versions runs-on: ubuntu-latest timeout-minutes: 10 strategy: fail-fast: false matrix: - ruby-version: ['2.6', '2.7', '3.0', '3.1', 'head', 'debug'] + ruby-version: ${{ fromJson(needs.ruby-versions.outputs.versions) }} steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 + with: + # Set fetch-depth: 10 so that Launchable can receive commits information. + fetch-depth: 10 + - name: Set up Launchable + uses: ./.github/actions/launchable/setup + with: + os: ubuntu-latest + test-task: test_protocol - name: Set up Ruby - # To automatically get bug fixes and new Ruby versions for ruby/setup-ruby, - # change this to (see https://github.com/ruby/setup-ruby#versioning): uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby-version }} - bundler-cache: true # runs 'bundle install' and caches installed gems automatically - - name: Run tests + bundler-cache: true + - name: Set up tests run: | bundle exec rake clobber bundle exec rake compile - bundle exec rake test_protocol + - name: Run tests + run: bundle exec rake test_protocol diff --git a/.github/workflows/ruby-macos.yaml b/.github/workflows/ruby-macos.yaml index cdf21efe8..e48eeb2cf 100644 --- a/.github/workflows/ruby-macos.yaml +++ b/.github/workflows/ruby-macos.yaml @@ -1,10 +1,3 @@ -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. -# This workflow will download a prebuilt Ruby version, install dependencies and run tests with Rake -# For more information see: https://github.com/marketplace/actions/setup-ruby-jruby-and-truffleruby - name: Ruby(macOS) on: @@ -13,27 +6,43 @@ on: pull_request: branches: [ master ] +permissions: + contents: read + jobs: - test: + ruby-versions: + uses: ruby/actions/.github/workflows/ruby_versions.yml@master + with: + engine: cruby + min_version: 3.2 + test: + needs: ruby-versions runs-on: macos-latest timeout-minutes: 15 strategy: fail-fast: false matrix: - ruby-version: ['3.1', 'head'] + ruby-version: ${{ fromJson(needs.ruby-versions.outputs.versions) }} steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 + with: + # Set fetch-depth: 10 so that Launchable can receive commits information. + fetch-depth: 10 + - name: Set up Launchable + uses: ./.github/actions/launchable/setup + with: + os: macos-latest + test-task: test_console - name: Set up Ruby - # To automatically get bug fixes and new Ruby versions for ruby/setup-ruby, - # change this to (see https://github.com/ruby/setup-ruby#versioning): uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby-version }} - bundler-cache: true # runs 'bundle install' and caches installed gems automatically - - name: Run tests + bundler-cache: true + - name: Set up tests run: | bundle exec rake clobber bundle exec rake compile - bundle exec rake test_console + - name: Run tests + run: bundle exec rake test_console diff --git a/.github/workflows/ruby.yml b/.github/workflows/ruby.yml index 66172942a..f53c61da7 100644 --- a/.github/workflows/ruby.yml +++ b/.github/workflows/ruby.yml @@ -1,10 +1,3 @@ -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. -# This workflow will download a prebuilt Ruby version, install dependencies and run tests with Rake -# For more information see: https://github.com/marketplace/actions/setup-ruby-jruby-and-truffleruby - name: Ruby on: @@ -13,27 +6,44 @@ on: pull_request: branches: [ master ] +permissions: + contents: read + jobs: - test: + ruby-versions: + uses: ruby/actions/.github/workflows/ruby_versions.yml@master + with: + engine: cruby + min_version: 2.7 + versions: '["debug"]' + test: + needs: ruby-versions runs-on: ubuntu-latest timeout-minutes: 30 strategy: fail-fast: false matrix: - ruby-version: ['2.6', '2.7', '3.0', '3.1', 'head', 'debug'] + ruby-version: ${{ fromJson(needs.ruby-versions.outputs.versions) }} steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 + with: + # Set fetch-depth: 10 so that Launchable can receive commits information. + fetch-depth: 10 + - name: Set up Launchable + uses: ./.github/actions/launchable/setup + with: + os: ubuntu-latest + test-task: test_console - name: Set up Ruby - # To automatically get bug fixes and new Ruby versions for ruby/setup-ruby, - # change this to (see https://github.com/ruby/setup-ruby#versioning): uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby-version }} - bundler-cache: true # runs 'bundle install' and caches installed gems automatically - - name: Run tests + bundler-cache: true + - name: Set up tests run: | bundle exec rake clobber bundle exec rake compile - bundle exec rake test_console + - name: Run tests + run: bundle exec rake test_console diff --git a/.github/workflows/test_test.yml b/.github/workflows/test_test.yml new file mode 100644 index 000000000..72e31affb --- /dev/null +++ b/.github/workflows/test_test.yml @@ -0,0 +1,49 @@ +name: TestTestFramework + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +permissions: + contents: read + +jobs: + ruby-versions: + uses: ruby/actions/.github/workflows/ruby_versions.yml@master + with: + engine: cruby + min_version: 3.0 + versions: '["debug"]' + + test: + needs: ruby-versions + runs-on: ubuntu-latest + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + ruby-version: ${{ fromJson(needs.ruby-versions.outputs.versions) }} + + steps: + - uses: actions/checkout@v4 + with: + # Set fetch-depth: 10 so that Launchable can receive commits information. + fetch-depth: 10 + - name: Set up Launchable + uses: ./.github/actions/launchable/setup + with: + os: ubuntu-latest + test-task: test_test + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby-version }} + bundler-cache: true + - name: Set up tests + run: | + bundle exec rake clobber + bundle exec rake compile + - name: Run tests + run: bundle exec rake test_test diff --git a/.github/workflows/truffleruby.yml b/.github/workflows/truffleruby.yml new file mode 100644 index 000000000..a3ec885bd --- /dev/null +++ b/.github/workflows/truffleruby.yml @@ -0,0 +1,27 @@ +name: TruffleRuby + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +permissions: + contents: read + +jobs: + truffleruby: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: truffleruby-head + bundler-cache: true + - name: Test installing the gem on TruffleRuby + run: | + bundle exec rake compile + bundle exec rake build + gem install pkg/debug-*.gem diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1ab97e0e0..68ca46798 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -149,10 +149,10 @@ If the file already exists, **only method** will be added to it. ```ruby # frozen_string_literal: true -require_relative '../support/test_case' +require_relative '../support/console_test_case' module DEBUGGER__ - class FooTest < TestCase + class FooTest < ConsoleTestCase def program <<~RUBY 1| module Foo @@ -166,7 +166,7 @@ module DEBUGGER__ 9| end RUBY end - + def test_1629720194 debug_code(program) do type 's' @@ -272,7 +272,7 @@ To run the test generator, you can enter `$ bin/gentest target.rb --open=vscode` Also, if you enter `$ bin/gentest target.rb --open=chrome` there, Chrome will be executed. If you need to modify existing tests, it is basically a good idea to regenerate them by the test generator instead of rewriting them directly. Please refer to [the Microsoft "Debug Adapter Protocol" article](https://microsoft.github.io/debug-adapter-protocol/specification) to learn more about DAP formats. -Please refer to [Procol viewer for "Chrome DevTools Protocol"](https://chromedevtools.github.io/devtools-protocol/) to learn more about CDP formats. +Please refer to [the "Chrome DevTools Protocol" official documentation](https://chromedevtools.github.io/devtools-protocol/) to learn more about CDP formats. 2. High-level tests @@ -352,7 +352,7 @@ Sends request to rdbg to set exception breakpoints. e.g. req_set_exception_breakpoints([{ name: "RuntimeError", condition: "a == 1" }]) ``` -Please note that `setExceptionBreakpoints` resets all exception breakpoints in every request. +Please note that `setExceptionBreakpoints` resets all exception breakpoints in every request. So the following code will only set breakpoint for `Exception`. diff --git a/Gemfile b/Gemfile index c59ccbe1a..ae1e1228c 100644 --- a/Gemfile +++ b/Gemfile @@ -7,3 +7,4 @@ gem "rake-compiler" gem "test-unit", "~> 3.0" gem "test-unit-rr" gem "json-schema" +gem "test-unit-launchable" diff --git a/README.md b/README.md index 8ca1f7a1a..4d9dc631a 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,9 @@ # debug.rb -This library provides debugging functionality to Ruby (MRI) 2.6 and later. +This library provides debugging functionality to Ruby (MRI) 2.7 and later. -This debug.rb is replacement of traditional lib/debug.rb standard library which is implemented by `set_trace_func`. +This debug.rb is the replacement of traditional lib/debug.rb standard library, which is implemented by `set_trace_func`. New debug.rb has several advantages: * Fast: No performance penalty on non-stepping mode and non-breakpoints. @@ -13,41 +13,41 @@ New debug.rb has several advantages: * TCP/IP * Integration with rich debugger frontends - Frontend | [Console](https://github.com/ruby/debug#invoke-as-a-remote-debuggee) | [VSCode](https://github.com/ruby/debug#vscode-integration) | [Chrome DevTool](#chrome-devtool-integration) | - ---|---|---|---| - Connection | UDS, TCP/IP | UDS, TCP/IP | TCP/IP | - Requirement | No | [vscode-rdbg](https://marketplace.visualstudio.com/items?itemName=KoichiSasada.vscode-rdbg) | Chrome | + | Frontend | [Console](https://github.com/ruby/debug#invoke-as-a-remote-debuggee) | [VSCode](https://github.com/ruby/debug#vscode-integration) | [Chrome DevTool](#chrome-devtool-integration) | + | ----------- | -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | --------------------------------------------- | + | Connection | UDS, TCP/IP | UDS, TCP/IP | TCP/IP | + | Requirement | None | [vscode-rdbg](https://marketplace.visualstudio.com/items?itemName=KoichiSasada.vscode-rdbg) | Chrome | -* Extensible: application can introduce debugging support with several ways: +* Extensible: application can introduce debugging support in several ways: * By `rdbg` command * By loading libraries with `-r` command line option * By calling Ruby's method explicitly * Misc - * Support threads (almost done) and ractors (TODO). - * Support suspending and entering to the console debugging with `Ctrl-C` at most of timing. + * Support threads (almost done) and Ractors (TODO). + * Support suspending and entering the debug console with `Ctrl-C` at most of timing. * Show parameters on backtrace command. - * Support recording & reply debugging. + * Support recording and replay debugging. # Installation -``` +```console $ gem install debug ``` -or specify `-Ipath/to/debug/lib` in `RUBYOPT` or each ruby command-line option, especially for debug this gem development. +Alternatively, specify `-Ipath/to/debug/lib` in `RUBYOPT`, or as a Ruby command-line option +This is especially useful for debugging this gem during development. -If you use Bundler, write the following line to your Gemfile. +If using Bundler, add the following to your Gemfile: -``` +```ruby gem "debug", ">= 1.0.0" ``` -(The version constraint is important; `debug < 1.0.0` is an older, -abandoned gem that is completely different from this product.) +(The version constraint is important; `debug < 1.0.0` is an older, abandoned gem that is completely different from this product.) # HOW TO USE -To use a debugger, roughly you will do the following steps: +To use the debugger, you will do roughly the following steps: 1. Set breakpoints. 2. Run a program with the debugger. @@ -55,7 +55,7 @@ To use a debugger, roughly you will do the following steps: 4. Use debug commands. * [Evaluate Ruby expressions](#evaluate) (e.g. `p lvar` to see the local variable `lvar`). * [Query the program status](#information) (e.g. `info` to see information about the current frame). - * [Control program flow](#control-flow) (e.g. move to the another line with `step`, to the next line with `next`). + * [Control program flow](#control-flow) (e.g. move to another line with `step`, to the next line with `next`). * [Set another breakpoint](#breakpoint) (e.g. `catch Exception` to set a breakpoint that'll be triggered when `Exception` is raised). * [Activate tracing in your program](#trace) (e.g. `trace call` to trace method calls). * [Change the configuration](#configuration-1) (e.g. `config set no_color true` to disable coloring). @@ -63,22 +63,23 @@ To use a debugger, roughly you will do the following steps: ## Invoke with the debugger -There are several options for (1) and (2). Please choose your favorite way. +There are several ways to invoke the debugger, depending on your needs, preferences, and the environment. ### Modify source code with [`binding.break`](#bindingbreak-method) (similar to `binding.pry` or `binding.irb`) -If you can modify the source code, you can use the debugger by adding `require 'debug'` at the top of your program and putting [`binding.break`](#bindingbreak-method) method into lines where you want to stop as breakpoints like `binding.pry` and `binding.irb`. +If you can modify the source code, you can use the debugger by adding `require 'debug'` at the top of your program and putting [`binding.break`](#bindingbreak-method) method into lines where you want to stop as breakpoints. +This is similar to how `binding.pry` and `binding.irb` work. -You can also use its 2 aliases in the same way: +`binding.break` has two aliases which do the same thing: - `binding.b` - `debugger` After that, run the program as usual and you will enter the debug console at breakpoints you inserted. -The following example shows the demonstration of [`binding.break`](#bindingbreak-method). +The following is an example of the [`binding.break`](#bindingbreak-method) method. -```shell +```console $ cat target.rb # Sample program require 'debug' @@ -140,10 +141,11 @@ d => 4 ### Invoke the program from the debugger as a traditional debuggers -If you don't want to modify the source code, you can set breakpoints with a debug command `break` (`b` for short). -Using `rdbg` command (or `bundle exec rdbg`) to launch the program without any modifications, you can run the program with the debugger. +If you don't want to modify the source code, you can use the `rdbg` command (or `bundle exec rdbg`) to run the program with the debugger. +This is similar to how you'd launch a program with `ruby program.rb`. +Then you can set breakpoints with the debug command `break` (`b` for short). -```shell +```console $ cat target.rb # Sample program a = 1 b = 2 @@ -166,9 +168,11 @@ DEBUGGER: Session start (pid: 7656) (rdbg) ``` -`rdbg` command suspends the program at the beginning of the given script (`target.rb` in this case) and you can use debug commands. `(rdbg)` is prompt. Let's set breakpoints on line 3 and line 5 with `break` command (`b` for short). +The `rdbg` command suspends the program at the beginning of the given script (`target.rb` in this case) and you can use debug commands to control execution from there. +`(rdbg)` is the console prompt. +Let's set breakpoints on line 3 and line 5 with `break` command (`b` for short). -```shell +```console (rdbg) break 3 # set breakpoint at line 3 #0 BP - Line /mnt/c/ko1/src/rb/ruby-debug/target.rb:3 (line) @@ -180,9 +184,10 @@ DEBUGGER: Session start (pid: 7656) #1 BP - Line /mnt/c/ko1/src/rb/ruby-debug/target.rb:5 (line) ``` -You can see that two breakpoints are registered. Let's continue the program by `continue` command. +You can see that two breakpoints are registered. +Let's continue the program by using the `continue` command. -```shell +```console (rdbg) continue [1, 7] in target.rb 1| a = 1 @@ -199,11 +204,11 @@ Stop by #0 BP - Line /mnt/c/ko1/src/rb/ruby-debug/target.rb:3 (line) (rdbg) ``` -You can see that we can stop at line 3. -Let's see the local variables with `info` command, and continue. -You can also confirm that the program will suspend at line 5 and you can use `info` command again. +You can see that we stopped at line 3. +Let's see the local variables with the `info` command, and continue execution with the `continue`. +The program will then suspend at line 5 and you can use the `info` command again. -```shell +```console (rdbg) info =>#0
at target.rb:3 %self => main @@ -237,25 +242,28 @@ d => 4 [1, 2, 3, 4] ``` -By the way, using `rdbg` command you can suspend your application with `C-c` (SIGINT) and enter the debug console. -It will help that if you want to know what the program is doing. +NOTE: When using `rdbg` you can suspend your application with `C-c` (SIGINT) and enter the debug console. +It will help if you want to know what the program is doing. ### Use `rdbg` with commands written in Ruby -If you want to run a command written in Ruby like like `rake`, `rails`, `bundle`, `rspec` and so on, you can use `rdbg -c` option. +If you want to run an executable written in Ruby like `rake`, `rails`, `bundle`, `rspec`, and so on, you can use `rdbg -c` option. -* Without `-c` option, `rdbg ` means that `` is Ruby script and invoke it like `ruby ` with the debugger. -* With `-c` option, `rdbg -c ` means that `` is command in `PATH` and simply invoke it with the debugger. +* Without the `-c` option, `rdbg ` means that `` is a Ruby script and it is invoked like `ruby ` with the debugger. +* With the `-c` option, `rdbg -c ` means that `` is an executable in `PATH` and simply invokes it with the debugger. Examples: + * `rdbg -c -- rails server` * `rdbg -c -- bundle exec ruby foo.rb` * `rdbg -c -- bundle exec rake test` -* `rdbg -c -- ruby target.rb` is same as `rdbg target.rb` +* `rdbg -c -- ruby target.rb` is the same as `rdbg target.rb` -NOTE: `--` is needed to separate the command line options for `rdbg` and invoking command. For example, `rdbg -c rake -T` is recognized like `rdbg -c -T -- rake`. It should be `rdbg -c -- rake -T`. +NOTE: `--` is needed to separate the command line options for `rdbg` from the executable being invoked, and its options. +For example, `rdbg -c rake -T` would be parsed as `rdbg -c -T -- rake`, which is incorrect. +It should be `rdbg -c -- rake -T`. -NOTE: If you want to use bundler (`bundle` command), you need to write `gem debug` line in your `Gemfile`. +NOTE: If you want to use Bundler (`bundle` executable), you need to add `gem 'debug'` to your `Gemfile`. ### Using VSCode @@ -263,53 +271,55 @@ Like other languages, you can use this debugger on the VSCode. 1. Install [VSCode rdbg Ruby Debugger - Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=KoichiSasada.vscode-rdbg) 2. Open `.rb` file (e.g. `target.rb`) -3. Register breakpoints with "Toggle breakpoint" in Run menu (or type F9 key) +3. Register breakpoints with "Toggle breakpoint" in the Run menu (or type F9 key) 4. Choose "Start debugging" in "Run" menu (or type F5 key) -5. You will see a dialog "Debug command line" and you can choose your favorite command line your want to run. -6. Chosen command line is invoked with `rdbg -c` and VSCode shows the details at breakpoints. +5. You will see a dialog "Debug command line" and you can choose your favorite command line you want to run. +6. Chosen command line is invoked with `rdbg -c`, and VSCode shows the details at breakpoints. -Please refer [Debugging in Visual Studio Code](https://code.visualstudio.com/docs/editor/debugging) for operations on VSCode. +Please refer to [Debugging in Visual Studio Code](https://code.visualstudio.com/docs/editor/debugging) for operations on VSCode. You can configure the extension in `.vscode/launch.json`. Please see the extension page for more details. ## Remote debugging -You can use this debugger as a remote debugger. For example, it will help the following situations: +You can use this debugger as a remote debugger. +For example, it will help in the following situations: -* Your application does not run on TTY and it is hard to use `binding.pry` or `binding.irb`. - * Your application is running on Docker container and there is no TTY. +* Your application does not run on TTY, and it is hard to use `binding.pry` or `binding.irb`. + * Your application is running on a Docker container, and there is no TTY. * Your application is running as a daemon. - * Your application uses pipe for STDIN or STDOUT. + * Your application uses pipe for `STDIN` or `STDOUT`. * Your application is running as a daemon and you want to query the running status (checking a backtrace and so on). -You can run your application as a remote debuggee and the remote debugger console can attach to the debuggee anytime. +You can run your application as a remote debuggee, and the remote debugger console can attach to the debuggee anytime. ### Invoke as a remote debuggee There are multiple ways to run your program as a debuggee: -Stop at program start | [`rdbg` option](https://github.com/ruby/debug#rdbg---open-or-rdbg--o-for-short) | [require](https://github.com/ruby/debug#require-debugopen-in-a-program) | [debugger API](https://github.com/ruby/debug#start-by-method) ----|---|---|---| -Yes | `rdbg --open` | `require "debug/open"` | `DEBUGGER__.open` -No | `rdbg --open --nonstop` | `require "debug/open_nonstop"` | `DEBUGGER__.open(nonstop: true)` +| Stop at program start | [`rdbg` option](https://github.com/ruby/debug#rdbg---open-or-rdbg--o-for-short) | [require](https://github.com/ruby/debug#require-debugopen-in-a-program) | [debugger API](https://github.com/ruby/debug#start-by-method) | +| --------------------- | ------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------- | +| Yes | `rdbg --open` | `require "debug/open"` | `DEBUGGER__.open` | +| No | `rdbg --open --nonstop` | `require "debug/open_nonstop"` | `DEBUGGER__.open(nonstop: true)` | #### `rdbg --open` (or `rdbg -O` for short) -You can run a script with `rdbg --open target.rb` command and run a `target.rb` as a debuggee program. It also opens the network port and suspends at the beginning of `target.rb`. +Launch a script with `rdbg --open target.rb` to run `target.rb` as a debuggee program. +It also opens the network port and suspends at the beginning of `target.rb`. -```shell -$ exe/rdbg --open target.rb +```console +$ rdbg --open target.rb DEBUGGER: Session start (pid: 7773) DEBUGGER: Debugger can attach via UNIX domain socket (/home/ko1/.ruby-debug-sock/ruby-debug-ko1-7773) DEBUGGER: wait for debugger connection... ``` -By default, `rdbg --open` uses UNIX domain socket and generates path name automatically (`/home/ko1/.ruby-debug-sock/ruby-debug-ko1-7773` in this case). +By default, `rdbg --open` uses UNIX domain socket and generates the path name automatically (`/home/ko1/.ruby-debug-sock/ruby-debug-ko1-7773` in this case). You can connect to the debuggee with `rdbg --attach` command (`rdbg -A` for short). -```shell +```console $ rdbg -A [1, 7] in target.rb => 1| a = 1 @@ -324,35 +334,41 @@ $ rdbg -A (rdbg:remote) ``` -If there is no other opening ports on the default directory, `rdbg --attach` command chooses the only one opening UNIX domain socket and connect to it. If there are more files, you need to specify the file. +If there are no other files in the default directory, `rdbg --attach` will automatically connect to the UNIX domain socket listed. +If there are multiple files, you need to specify which to use. -When `rdbg --attach` connects to the debuggee, you can use any debug commands (set breakpoints, continue the program and so on) like local debug console. When an debuggee program exits, the remote console will also terminate. +When `rdbg --attach` connects to the debuggee, you can use any debug commands (set breakpoints, continue the program, and so on) like the local debug console. +When a debuggee program exits, the remote console will also terminate. -NOTE: If you use `quit` command, only remote console exits and the debuggee program continues to run (and you can connect it again). If you want to exit the debuggee program, use `kill` command. +NOTE: If you use the `quit` command, only the remote console exits and the debuggee program continues to run (and you can connect it again). +If you want to exit the debuggee program, use `kill` command. -If you want to use TCP/IP for the remote debugging, you need to specify the port and host with `--port` like `rdbg --open --port 12345` and it binds to `localhost:12345`. +If you want to use TCP/IP for remote debugging, you need to specify the port and host with `--port` like `rdbg --open --port 12345` and it binds to `localhost:12345`. +You can add an optional `--port_range` to try multiple ports in a reliable way. +For example, `rdbg --open --port 12345 --port_range 10` will try to bind to 12345, 12346, 12347,… until it finds an available port. To connect to the debuggee, you need to specify the port. -```shell +```console $ rdbg --attach 12345 ``` If you want to choose the host to bind, you can use `--host` option. -Note that all messages communicated between the debugger and the debuggee are *NOT* encrypted so please use remote debugging carefully. +Messages communicated between the debugger and the debuggee are *NOT* encrypted so please use remote debugging carefully. #### `require 'debug/open'` in a program -If you can modify the program, you can open debugging port by adding `require 'debug/open'` line in the program. +If you can modify the program, you can open the debugging port by adding `require 'debug/open'` in the program. If you don't want to stop the program at the beginning, you can also use `require 'debug/open_nonstop'`. Using `debug/open_nonstop` is useful if you want to open a backdoor to the application. -However, it is also danger because it can become another vulnerability. +However, it is also dangerous because it can become another vulnerability. Please use it carefully. -By default, UNIX domain socket is used for the debugging port. To use TCP/IP, you can set the `RUBY_DEBUG_PORT` environment variable. +By default, UNIX domain socket is used for the debugging port. +To use TCP/IP, you can set the `RUBY_DEBUG_PORT` environment variable. -```shell +```console $ RUBY_DEBUG_PORT=12345 ruby target.rb ``` @@ -364,19 +380,17 @@ You can attach with external debugger frontend with VSCode and Chrome. $ rdbg --open=[frontend] target.rb ``` -will open a debug port and `[frontend]` can attach to the port. - -Also `open` command allows opening the debug port. +This will open a debug port and the `[frontend]` can attach to the port. #### VSCode integration ([vscode-rdbg v0.0.9](https://marketplace.visualstudio.com/items?itemName=KoichiSasada.vscode-rdbg) or later is required) -If you don't run a debuggee Ruby process on VSCode, you can attach with VSCode later with the following steps. +If you don't run a debuggee Ruby process on VSCode, you can attach it to VSCode later with the following steps. -`rdbg --open=vscode` opens the debug port and tries to invoke the VSCode (`code` command). +`rdbg --open=vscode` opens the debug port and tries to invoke the VSCode (`code` executable). -``` +```console $ rdbg --open=vscode target.rb DEBUGGER: Debugger can attach via UNIX domain socket (/tmp/ruby-debug-sock-1000/ruby-debug-ko1-27706) DEBUGGER: wait for debugger connection... @@ -384,11 +398,11 @@ Launching: code /tmp/ruby-debug-vscode-20211014-27706-gd7e85/ /tmp/ruby-debug-vs DEBUGGER: Connected. ``` -And it tries to invoke the new VSCode window and VSCode starts attaching to the debuggee Ruby program automatically. +It tries to invoke the new VSCode window and VSCode will attach to the debuggee Ruby program automatically. -You can also use `open vscode` command in REPL. +You can also use `open vscode` in a REPL. -``` +```console $ rdbg target.rb [1, 8] in target.rb 1| @@ -407,9 +421,9 @@ Launching: code /tmp/ruby-debug-vscode-20211014-28337-kg9dm/ /tmp/ruby-debug-vsc DEBUGGER: Connected. ``` -If the machine which runs the Ruby process doesn't have a `code` command, the following message will be shown: +If the machine which runs the Ruby process doesn't have a `code` executable on `$PATH`, the following message will be shown: -``` +```console (rdbg) open vscode DEBUGGER: wait for debugger connection... DEBUGGER: Debugger can attach via UNIX domain socket (/tmp/ruby-debug-sock-1000/ruby-debug-ko1-455) @@ -425,15 +439,13 @@ If your application is running on a SSH remote host, please try: ``` -and try to use proposed commands. - Note that you can attach with `rdbg --attach` and continue REPL debugging. #### Chrome DevTool integration -With `rdbg --open=chrome` command will show the following message. +Using `rdbg --open=chrome` will show the following message: -``` +```console $ rdbg target.rb --open=chrome DEBUGGER: Debugger can attach via TCP/IP (127.0.0.1:43633) DEBUGGER: With Chrome browser, type the following URL in the address-bar: @@ -443,20 +455,25 @@ DEBUGGER: With Chrome browser, type the following URL in the address-bar: DEBUGGER: wait for debugger connection... ``` -Type `devtools://devtools/bundled/inspector.html?v8only=true&panel=sources&ws=127.0.0.1:57231/b32a55cd-2eb5-4c5c-87d8-b3dfc59d80ef` in the address-bar on Chrome browser, and you can continue the debugging with chrome browser. +Type the following in the address bar on Chrome browser, and you can continue the debugging with chrome browser: + +```txt +devtools://devtools/bundled/inspector.html?v8only=true&panel=sources&ws=127.0.0.1:57231/b32a55cd-2eb5-4c5c-87d8-b3dfc59d80ef` +``` -Also `open chrome` command works like `open vscode`. +Similar to VSCode, you can use `open chrome` to open the debugger in Chrome. -For more information about how to use Chrome debugging, you might want to read [here](https://developer.chrome.com/docs/devtools/). +For more information about how to use Chrome debugging, [see the devtools docs](https://developer.chrome.com/docs/devtools/). ## Configuration You can configure the debugger's behavior with debug commands and environment variables. -When the debug session is started, initial scripts are loaded so you can put your favorite configurations in the initial scripts. +When the debug session is started, some [initialization scripts](#initial-scripts) (e.g., `~/.rdbgrc`) are loaded, allowing you to configure the debugger's behavior to your needs and preferences. ### Configuration list -You can configure debugger's behavior with environment variables and `config` command. Each configuration has environment variable and the name which can be specified by `config` command. +You can configure the debugger's behavior with environment variables and `config` command. +Each configuration has an environment variable and a name which can be specified by `config` command. ``` # configuration example @@ -469,12 +486,17 @@ config set no_color true * UI * `RUBY_DEBUG_LOG_LEVEL` (`log_level`): Log level same as Logger (default: WARN) * `RUBY_DEBUG_SHOW_SRC_LINES` (`show_src_lines`): Show n lines source code on breakpoint (default: 10) + * `RUBY_DEBUG_SHOW_SRC_LINES_FRAME` (`show_src_lines_frame`): Show n lines source code on frame operations (default: 1) + * `RUBY_DEBUG_SHOW_EVALEDSRC` (`show_evaledsrc`): Show actually evaluated source (default: false) * `RUBY_DEBUG_SHOW_FRAMES` (`show_frames`): Show n frames on breakpoint (default: 2) * `RUBY_DEBUG_USE_SHORT_PATH` (`use_short_path`): Show shorten PATH (like $(Gem)/foo.rb) (default: false) * `RUBY_DEBUG_NO_COLOR` (`no_color`): Do not use colorize (default: false) * `RUBY_DEBUG_NO_SIGINT_HOOK` (`no_sigint_hook`): Do not suspend on SIGINT (default: false) * `RUBY_DEBUG_NO_RELINE` (`no_reline`): Do not use Reline library (default: false) * `RUBY_DEBUG_NO_HINT` (`no_hint`): Do not show the hint on the REPL (default: false) + * `RUBY_DEBUG_NO_LINENO` (`no_lineno`): Do not show line numbers (default: false) + * `RUBY_DEBUG_NO_REPEAT` (`no_repeat`): Do not repeat last line when empty line (default: false) + * `RUBY_DEBUG_IRB_CONSOLE` (`irb_console`): Use IRB as the console (default: false) * CONTROL * `RUBY_DEBUG_SKIP_PATH` (`skip_path`): Skip showing/entering frames for given paths @@ -488,20 +510,22 @@ config set no_color true * `RUBY_DEBUG_NONSTOP` (`nonstop`): Nonstop mode (default: false) * `RUBY_DEBUG_STOP_AT_LOAD` (`stop_at_load`): Stop at just loading location (default: false) * `RUBY_DEBUG_INIT_SCRIPT` (`init_script`): debug command script path loaded at first stop - * `RUBY_DEBUG_COMMANDS` (`commands`): debug commands invoked at first stop. commands should be separated by ';;' + * `RUBY_DEBUG_COMMANDS` (`commands`): debug commands invoked at first stop. Commands should be separated by `;;` * `RUBY_DEBUG_NO_RC` (`no_rc`): ignore loading ~/.rdbgrc(.rb) (default: false) - * `RUBY_DEBUG_HISTORY_FILE` (`history_file`): history file (default: ~/.rdbg_history) + * `RUBY_DEBUG_HISTORY_FILE` (`history_file`): history file (default: ${XDG_STATE_HOME-~/.local/state}/rdbg/history) * `RUBY_DEBUG_SAVE_HISTORY` (`save_history`): maximum save history lines (default: 10000) * REMOTE * `RUBY_DEBUG_OPEN` (`open`): Open remote port (same as `rdbg --open` option) * `RUBY_DEBUG_PORT` (`port`): TCP/IP remote debugging: port + * `RUBY_DEBUG_PORT_RANGE` (`port_range`): TCP/IP remote debugging: length of port range * `RUBY_DEBUG_HOST` (`host`): TCP/IP remote debugging: host (default: 127.0.0.1) * `RUBY_DEBUG_SOCK_PATH` (`sock_path`): UNIX Domain Socket remote debugging: socket path * `RUBY_DEBUG_SOCK_DIR` (`sock_dir`): UNIX Domain Socket remote debugging: socket directory * `RUBY_DEBUG_LOCAL_FS_MAP` (`local_fs_map`): Specify local fs map * `RUBY_DEBUG_SKIP_BP` (`skip_bp`): Skip breakpoints if no clients are attached (default: false) * `RUBY_DEBUG_COOKIE` (`cookie`): Cookie for negotiation + * `RUBY_DEBUG_SESSION_NAME` (`session_name`): Session name for differentiating multiple sessions * `RUBY_DEBUG_CHROME_PATH` (`chrome_path`): Platform dependent path of Chrome (For more information, See [here](https://github.com/ruby/debug/pull/334/files#diff-5fc3d0a901379a95bc111b86cf0090b03f857edfd0b99a0c1537e26735698453R55-R64)) * OBSOLETE @@ -511,21 +535,21 @@ There are other environment variables: * `NO_COLOR`: If the value is set, set `RUBY_DEBUG_NO_COLOR` ([NO_COLOR: disabling ANSI color output in various Unix commands](https://no-color.org/)). * `RUBY_DEBUG_ENABLE`: If the value is `0`, do not enable debug.gem feature. -* `RUBY_DEBUG_ADDED_RUBYOPT`: Remove this value from `RUBYOPT` at first. This feature helps loading debug.gem with `RUBYOPT='-r debug/...'` and you don't want to derive it to child processes. In this case you can set `RUBY_DEBUG_ADDED_RUBYOPT='-r debug/...'` (same value) and this string will be deleted from `RUBYOPT` at first. +* `RUBY_DEBUG_ADDED_RUBYOPT`: Remove this value from `RUBYOPT` at first. This feature helps loading debug.gem with `RUBYOPT='-r debug/...'`, and you don't want to derive it to child processes. In this case, you can set `RUBY_DEBUG_ADDED_RUBYOPT='-r debug/...'` (same value), and this string will be deleted from `RUBYOPT` at first. * `RUBY_DEBUG_EDITOR` or `EDITOR`: An editor used by `edit` debug command. * `RUBY_DEBUG_BB`: Define `Kernel#bb` method which is alias of `Kernel#debugger`. ### Initial scripts -If there is `~/.rdbgrc`, the file is loaded as an initial script (which contains debug commands) when the debug session is started. +If there is a `~/.rdbgrc` file it is loaded as an initialization script (which contains debug commands) when the debug session is started. * `RUBY_DEBUG_INIT_SCRIPT` environment variable can specify the initial script file. * You can specify the initial script with `rdbg -x initial_script` (like gdb's `-x` option). Initial scripts are useful to write your favorite configurations. -For example, you can set break points with `break file:123` in `~/.rdbgrc`. +For example, you can set breakpoints with `break file:123` in `~/.rdbgrc`. -If there are `~/.rdbgrc.rb` is available, it is also loaded as a ruby script at same timing. +If there is a `~/.rdbgrc.rb` file it is also loaded as a Ruby script when the debug session is started. ## Debug command on the debug console @@ -533,17 +557,20 @@ On the debug console, you can use the following debug commands. There are additional features: -* `` without debug command is almost same as `pp `. - * If the input line `` does *NOT* start with any debug command, the line `` will be evaluated as a Ruby expression and the result will be printed with `pp` method. So that the input `foo.bar` is same as `pp foo.bar`. - * If `` is recognized as a debug command, of course it is not evaluated as a Ruby expression, but is executed as debug command. For example, you can not evaluate such single letter local variables `i`, `b`, `n`, `c` because they are single letter debug commands. Use `p i` instead. - * So the author (Koichi Sasada) recommends to use `p`, `pp` or `eval` command to evaluate the Ruby expression everytime. +* `` without debug command is almost the same as `pp `. + * If the input line `` does *NOT* start with any debug command, the line `` will be evaluated as a Ruby expression, and the result will be printed with `pp` method. + So that the input `foo.bar` is the same as `pp foo.bar`. + * If `` is recognized as a debug command, of course, it is not evaluated as a Ruby expression but is executed as debug command. + For example, you can not evaluate such single-letter local variables `i`, `b`, `n`, `c` because they are single-letter debug commands. Use `p i` instead. + * For consistency, the author (Koichi Sasada) recommends using the `p`, `pp`, or `eval` command to evaluate the Ruby expression every time. * `Enter` without any input repeats the last command (useful when repeating `step`s) for some commands. * `Ctrl-D` is equal to `quit` command. * [debug command compare sheet - Google Sheets](https://docs.google.com/spreadsheets/d/1TlmmUDsvwK4sSIyoMv-io52BUUz__R5wpu-ComXlsw0/edit?usp=sharing) -You can use the following debug commands. Each command should be written in 1 line. -The `[...]` notation means this part can be eliminate. For example, `s[tep]` means `s` or `step` are valid command. `ste` is not valid. -The `<...>` notation means the argument. +You can use the following debug commands. +Each command should be written in 1 line. +The `[…]` notation means this part can be eliminated. For example, `s[tep]` means `s` or `step` is a valid command. `ste` is not valid. +The `<…>` notation means the argument. ### Control flow @@ -562,11 +589,11 @@ The `<...>` notation means the argument. * `u[ntil]` * Similar to `next` command, but only stop later lines or the end of the current frame. * Similar to gdb's `advance` command. -* `u[ntil] <[file:]line> +* `u[ntil] <[file:]line>` * Run til the program reaches given location or the end of the current frame. -* `u[ntil] +* `u[ntil] ` * Run til the program invokes a method ``. `` can be a regexp with `/name/`. -* `c[ontinue]` +* `c` or `cont` or `continue` * Resume the program. * `q[uit]` or `Ctrl-D` * Finish debugger (with the debuggee process on non-remote debugging). @@ -654,20 +681,27 @@ The `<...>` notation means the argument. * `edit ` * Open on the editor. * `i[nfo]` - * Show information about current frame (local/instance variables and defined constants). -* `i[nfo] l[ocal[s]]` + * Show information about current frame (local/instance variables and defined constants). +* `i[nfo]` + * `info` has the following sub-commands. + * Sub-commands can be specified with few letters which is unambiguous, like `l` for 'locals'. +* `i[nfo] l or locals or local_variables` * Show information about the current frame (local variables) - * It includes `self` as `%self` and a return value as `%return`. -* `i[nfo] i[var[s]]` or `i[nfo] instance` + * It includes `self` as `%self` and a return value as `_return`. +* `i[nfo] i or ivars or instance_variables` * Show information about instance variables about `self`. -* `i[nfo] c[onst[s]]` or `i[nfo] constant[s]` + * `info ivars ` shows the instance variables of the result of ``. +* `i[nfo] c or consts or constants` * Show information about accessible constants except toplevel constants. -* `i[nfo] g[lobal[s]]` + * `info consts ` shows the constants of a class/module of the result of `` +* `i[nfo] g or globals or global_variables` * Show information about global variables +* `i[nfo] th or threads` + * Show all threads (same as `th[read]`). +* `i[nfo] b or breakpoints or w or watchpoints` + * Show all breakpoints and watchpoints. * `i[nfo] ... /regexp/` * Filter the output with `/regexp/`. -* `i[nfo] th[read[s]]` - * Show all threads (same as `th[read]`). * `o[utline]` or `ls` * Show you available methods, constants, local variables, and instance variables in the current scope. * `o[utline] ` or `ls ` @@ -702,7 +736,7 @@ The `<...>` notation means the argument. * `eval ` * Evaluate `` on the current frame. * `irb` - * Invoke `irb` on the current frame. + * Activate and switch to `irb:rdbg` console ### Trace @@ -773,6 +807,30 @@ The `<...>` notation means the argument. * Show help for the given command. +### Using IRB as the Debug Console + +Starting from version `v1.9`, you can now use IRB as the debug console. This integration brings additional features such as: + +* Autocompletion +* Support for multi-line input +* Access to commands not available in `debug`, like `show_source` or `show_doc` +* [Configurable command aliases](https://docs.ruby-lang.org/en/master/IRB.html#module-IRB-label-Command+Aliases) + +To switch to the IRB console, simply use the `irb` command in the debug console. + +Once activated, you'll notice the prompt changes to: + +```console +irb:rdbg(main):001> +``` + +If you want to make IRB the default console for all sessions, configure the `irb_console` setting by either: + +* Setting the `RUBY_DEBUG_IRB_CONSOLE=true` environment variable +* Or adding `config set irb_console 1` to your `~/.rdbgrc` + +To disable the IRB console in the current session, execute `config set irb_console 0` in the console. + ## Debugger API ### Start debugging @@ -789,9 +847,12 @@ You can start debugging without `rdbg` command by requiring the following librar You need to require one of them at the very beginning of the application. Using `ruby -r` (for example `ruby -r debug/start target.rb`) is another way to invoke with debugger. -NOTE: Until Ruby 3.0, there is old `lib/debug.rb` standard library. So that if this gem is not installed, or if `Gemfile` missed to list this gem and `bundle exec` is used, you will see the following output: +NOTE: Until Ruby 3.0, there is old `lib/debug.rb` in the standard library. +`lib/debug.rb` was not maintained well in recent years, and the purpose of this library is to rewrite old `lib/debug.rb` with recent techniques. + +So, if this gem is not installed, or if the `Gemfile` doesn't include this gem and `bundle exec` is used, you will see the following output: -```shell +```console $ ruby -r debug -e0 .../2.7.3/lib/ruby/2.7.0/x86_64-linux/continuation.so: warning: callcc is obsolete; use Fiber instead Debug.rb @@ -801,16 +862,15 @@ Emacs support available. (rdb:1) ``` -`lib/debug.rb` was not maintained well in recent years, and the purpose of this library is to rewrite old `lib/debug.rb` with recent techniques. - #### Start by method -After loading `debug/session`, you can start debug session with the following methods. They are convenient if you want to specify debug configurations in your program. +After loading `debug/session`, you can start a debug session with the following methods. +They are convenient if you want to specify debug configurations in your program. * `DEBUGGER__.start(**kw)`: start debug session with local console. -* `DEBUGGER__.open(**kw)`: open debug port with configuration (without configurations open with UNIX domain socket) -* `DEBUGGER__.open_unix(**kw)`: open debug port with UNIX domain socket -* `DEBUGGER__.open_tcp(**kw)`: open debug port with TCP/IP +* `DEBUGGER__.open(**kw)`: open debug port with configuration (without configurations open with UNIX domain socket). +* `DEBUGGER__.open_unix(**kw)`: open debug port with UNIX domain socket. +* `DEBUGGER__.open_tcp(**kw)`: open debug port with TCP/IP. For example: @@ -824,35 +884,39 @@ DEBUGGER__.start(no_color: true, # disable colorize ### `binding.break` method -`binding.break` (or `binding.b`) set breakpoints at written line. It also has several keywords. +`binding.break` (or `binding.b`) sets a breakpoint at that line. +It also has several keywords. -If `do: 'command'` is specified, the debugger suspends the program and run the `command` as a debug command and continue the program. +If `do: 'command'` is specified, the debugger suspends the program, runs the `command` as a debug command, and continues the program. It is useful if you only want to call a debug command and don't want to stop there. +For example: -``` +```ruby def initialize @a = 1 - binding.b do: 'watch @a' + binding.b do: 'info \n watch @a' end ``` -On this case, register a watch breakpoint for `@a` and continue to run. +In this case, execute the `info` command, then register a watch breakpoint for `@a` and continue to run. +You can also use `;;` instead of `\n` to separate your commands. -If `pre: 'command'` is specified, the debugger suspends the program and run the `command` as a debug command, and keep suspend. +If `pre: 'command'` is specified, the debugger suspends the program and runs the `command` as a debug command, and keeps suspended. It is useful if you have operations before suspend. +For example: -``` +```ruby def foo binding.b pre: 'p bar()' ... end ``` -On this case, you can see the result of `bar()` every time you stop there. +In this case, you can see the result of `bar()` every time you stop there. ## rdbg command help -``` +```console exe/rdbg [options] -- [debuggee options] Debug console mode: @@ -872,8 +936,10 @@ Debug console mode: Now rdbg, vscode and chrome is supported. --sock-path=SOCK_PATH UNIX Domain socket path --port=PORT Listening TCP/IP port + --port-range=PORT_RANGE Number of ports to try to connect to --host=HOST Listening TCP/IP host --cookie=COOKIE Set a cookie for connection + --session-name=NAME Session name Debug console mode runs Ruby program with the debug console. @@ -900,6 +966,8 @@ Attach mode: 'rdbg -A host port' tries to connect to host:port via TCP/IP. Other options: + -v Show version number + --version Show version number and exit -h, --help Print help --util=NAME Utility mode (used by tools) --stop-at-load Stop immediately when the debugging feature is loaded. @@ -917,7 +985,7 @@ NOTE # Contributing -Bug reports and pull requests are welcome on GitHub at https://github.com/ruby/debug. +Bug reports and pull requests are welcome on GitHub at [https://github.com/ruby/debug](). This debugger is not mature so your feedback will help us. Please also check the [contributing guideline](/CONTRIBUTING.md). diff --git a/Rakefile b/Rakefile index 99a5a2a10..bf5d31a2c 100644 --- a/Rakefile +++ b/Rakefile @@ -35,9 +35,14 @@ task :check_readme do end end +desc "Run debug.gem test-framework tests" +Rake::TestTask.new(:test_test) do |t| + t.test_files = FileList["test/support/*_test.rb"] +end + desc "Run all debugger console related tests" Rake::TestTask.new(:test_console) do |t| - t.test_files = FileList["test/console/*_test.rb", "test/support/*_test.rb"] + t.test_files = FileList["test/console/*_test.rb"] end desc "Run all debugger protocols (CAP & DAP) related tests" @@ -46,7 +51,7 @@ Rake::TestTask.new(:test_protocol) do |t| end task test: 'test_console' do - warn '`rake test` doesn\'t run protocol tests. Use `rake test-all` to test all.' + warn '`rake test` doesn\'t run protocol tests. Use `rake test_all` to test all.' end -task test_all: [:test_console, :test_protocol] +task test_all: [:test_test, :test_console, :test_protocol] diff --git a/TODO.md b/TODO.md index 91973e3fa..cc511416e 100644 --- a/TODO.md +++ b/TODO.md @@ -2,22 +2,22 @@ ## Basic functionality -* Support Ractors -* Signal (SIGINT) trap handling +* Support Fibers and Ractors ## UI +* Multi-line support * Completion for Ruby's code * Interactive breakpoint setting * Interactive record & play debugging * irb integration -* Web browser integrated UI -* History file ## Debug command -* Breakpoints - * Lightweight pending method break points with Ruby 3.1 feature (TP:method_added) * Watch points - * Lightweight watchpoints for instance variables with Ruby 3.1 features (TP:ivar_set) -* Faster `next`/`finish` command by specifying target code. + * Lightweight watchpoints for instance variables with Ruby 3.3 features (TP:ivar_set) +* Alias + +## Debug port + +* Debug port for monitoring diff --git a/debug.gemspec b/debug.gemspec index f05d0faa7..f77ae68ae 100644 --- a/debug.gemspec +++ b/debug.gemspec @@ -10,10 +10,11 @@ Gem::Specification.new do |spec| spec.description = %q{Debugging functionality for Ruby. This is completely rewritten debug.rb which was contained by the ancient Ruby versions.} spec.homepage = "https://github.com/ruby/debug" spec.licenses = ["Ruby", "BSD-2-Clause"] - spec.required_ruby_version = Gem::Requirement.new(">= 2.6.0") + spec.required_ruby_version = Gem::Requirement.new(">= 2.7.0") spec.metadata["homepage_uri"] = spec.homepage spec.metadata["source_code_uri"] = spec.homepage + spec.metadata["changelog_uri"] = "#{spec.homepage}/releases/tag/v#{spec.version}" # Specify which files should be added to the gem when it is released. # The `git ls-files -z` loads the files in the RubyGem that have been added into git. @@ -27,6 +28,6 @@ Gem::Specification.new do |spec| spec.require_paths = ["lib"] spec.extensions = ['ext/debug/extconf.rb'] - spec.add_dependency "irb", ">= 1.5.0" # for binding.irb(show_code: false) - spec.add_dependency "reline", ">= 0.3.1" + spec.add_dependency "irb", "~> 1.10" # for irb:debug integration + spec.add_dependency "reline", ">= 0.3.8" end diff --git a/exe/rdbg b/exe/rdbg index 52b93d8ce..14b5e978c 100755 --- a/exe/rdbg +++ b/exe/rdbg @@ -1,7 +1,7 @@ #!/usr/bin/env ruby require_relative '../lib/debug/config' -config = DEBUGGER__::Config::parse_argv(ARGV) +config, opt = *DEBUGGER__::Config::parse_argv(ARGV) # mode is not an actual configuration option # it's only used to carry the result of parse_argv here diff --git a/ext/debug/debug.c b/ext/debug/debug.c index fc4b4bb5a..b27263d46 100644 --- a/ext/debug/debug.c +++ b/ext/debug/debug.c @@ -8,13 +8,13 @@ static VALUE rb_mDebugger; // iseq typedef struct rb_iseq_struct rb_iseq_t; +const rb_iseq_t *rb_iseqw_to_iseq(VALUE iseqw); VALUE rb_iseq_realpath(const rb_iseq_t *iseq); static VALUE iseq_realpath(VALUE iseqw) { - rb_iseq_t *iseq = DATA_PTR(iseqw); - return rb_iseq_realpath(iseq); + return rb_iseq_realpath(rb_iseqw_to_iseq(iseqw)); } static VALUE rb_cFrameInfo; @@ -62,21 +62,34 @@ di_body(const rb_debug_inspector_t *dc, void *ptr) long i; for (i=1; i= BUFF_SIZE) { - VALUE bt = rb_make_backtrace(); - size = RARRAY_LEN(bt); - return INT2FIX(size); - } - - // rb_profile_frames will return one extra frame - // https://bugs.ruby-lang.org/issues/18907 - #ifdef RB_PROFILE_FRAMES_HAS_EXTRA_FRAME - return INT2FIX(size - 1); - #else - return INT2FIX(size); - #endif + return rb_debug_inspector_current_depth(); } #else static VALUE @@ -126,28 +118,29 @@ frame_depth(VALUE self) } #endif + // iseq -const struct rb_iseq *rb_iseqw_to_iseq(VALUE iseqw); +const rb_iseq_t *rb_iseqw_to_iseq(VALUE iseqw); #ifdef HAVE_RB_ISEQ_TYPE -VALUE rb_iseq_type(const struct rb_iseq *); +VALUE rb_iseq_type(const rb_iseq_t *); static VALUE iseq_type(VALUE iseqw) { - const struct rb_iseq *iseq = rb_iseqw_to_iseq(iseqw); + const rb_iseq_t *iseq = rb_iseqw_to_iseq(iseqw); return rb_iseq_type(iseq); } #endif #ifdef HAVE_RB_ISEQ_PARAMETERS -VALUE rb_iseq_parameters(const struct rb_iseq *, int is_proc); +VALUE rb_iseq_parameters(const rb_iseq_t *, int is_proc); static VALUE iseq_parameters_symbols(VALUE iseqw) { - const struct rb_iseq *iseq = rb_iseqw_to_iseq(iseqw); + const rb_iseq_t *iseq = rb_iseqw_to_iseq(iseqw); VALUE params = rb_iseq_parameters(iseq, 0); VALUE ary = rb_ary_new(); @@ -174,12 +167,12 @@ iseq_parameters_symbols(VALUE iseqw) #endif #ifdef HAVE_RB_ISEQ_CODE_LOCATION -void rb_iseq_code_location(const struct rb_iseq *, int *first_lineno, int *first_column, int *last_lineno, int *last_column); +void rb_iseq_code_location(const rb_iseq_t *, int *first_lineno, int *first_column, int *last_lineno, int *last_column); static VALUE iseq_first_line(VALUE iseqw) { - const struct rb_iseq *iseq = rb_iseqw_to_iseq(iseqw); + const rb_iseq_t *iseq = rb_iseqw_to_iseq(iseqw); int line; rb_iseq_code_location(iseq, &line, NULL, NULL, NULL); return INT2NUM(line); @@ -188,20 +181,24 @@ iseq_first_line(VALUE iseqw) static VALUE iseq_last_line(VALUE iseqw) { - const struct rb_iseq *iseq = rb_iseqw_to_iseq(iseqw); + const rb_iseq_t *iseq = rb_iseqw_to_iseq(iseqw); int line; rb_iseq_code_location(iseq, NULL, NULL, &line, NULL); return INT2NUM(line); } #endif +#ifdef HAVE_RB_ISEQ void Init_iseq_collector(void); +#endif void Init_debug(void) { +#ifdef HAVE_RB_ISEQ VALUE rb_mRubyVM = rb_const_get(rb_cObject, rb_intern("RubyVM")); VALUE rb_cISeq = rb_const_get(rb_mRubyVM, rb_intern("InstructionSequence")); +#endif rb_mDebugger = rb_const_get(rb_cObject, rb_intern("DEBUGGER__")); rb_cFrameInfo = rb_const_get(rb_mDebugger, rb_intern("FrameInfo")); @@ -225,5 +222,7 @@ Init_debug(void) rb_define_method(rb_cISeq, "last_line", iseq_last_line, 0); #endif +#ifdef HAVE_RB_ISEQ Init_iseq_collector(); +#endif } diff --git a/ext/debug/extconf.rb b/ext/debug/extconf.rb index c9d056b7e..9c4f5417a 100644 --- a/ext/debug/extconf.rb +++ b/ext/debug/extconf.rb @@ -4,17 +4,10 @@ $distcleanfiles << "debug_version.h" if defined? RubyVM + $defs << '-DHAVE_RB_ISEQ' $defs << '-DHAVE_RB_ISEQ_PARAMETERS' $defs << '-DHAVE_RB_ISEQ_CODE_LOCATION' - if RUBY_VERSION >= '3.0.0' - $defs << '-DRB_PROFILE_FRAMES_HAS_C_FRAMES' - - if RUBY_VERSION < '3.2.0' - $defs << '-DRB_PROFILE_FRAMES_HAS_EXTRA_FRAME' - end - end - if RUBY_VERSION >= '3.1.0' $defs << '-DHAVE_RB_ISEQ_TYPE' end diff --git a/ext/debug/iseq_collector.c b/ext/debug/iseq_collector.c index f87c4f978..6b8d355a9 100644 --- a/ext/debug/iseq_collector.c +++ b/ext/debug/iseq_collector.c @@ -1,5 +1,6 @@ #include +#ifdef HAVE_RB_ISEQ VALUE rb_iseqw_new(VALUE v); void rb_objspace_each_objects( int (*callback)(void *start, void *end, size_t stride, void *data), @@ -9,7 +10,7 @@ size_t rb_obj_memsize_of(VALUE); // implementation specific. enum imemo_type { imemo_iseq = 7, - imemo_mask = 0x07 + imemo_mask = 0xf }; static inline enum imemo_type @@ -89,3 +90,4 @@ Init_iseq_collector(void) rb_define_singleton_method(rb_mObjSpace, "each_iseq", each_iseq, 0); rb_define_singleton_method(rb_mObjSpace, "count_iseq", count_iseq, 0); } +#endif diff --git a/lib/debug.rb b/lib/debug.rb index 15ebccb62..a4890123a 100644 --- a/lib/debug.rb +++ b/lib/debug.rb @@ -1,5 +1,9 @@ # frozen_string_literal: true -require_relative 'debug/session' -return unless defined?(DEBUGGER__) -DEBUGGER__::start no_sigint_hook: true, nonstop: true +if ENV['RUBY_DEBUG_LAZY'] + require_relative 'debug/prelude' +else + require_relative 'debug/session' + return unless defined?(DEBUGGER__) + DEBUGGER__::start no_sigint_hook: true, nonstop: true +end diff --git a/lib/debug/abbrev_command.rb b/lib/debug/abbrev_command.rb new file mode 100644 index 000000000..96e8b2b1c --- /dev/null +++ b/lib/debug/abbrev_command.rb @@ -0,0 +1,77 @@ + +module DEBUGGER__ + class AbbrevCommand + class TrieNode + def initialize + @children = {} + @types = {} # set + end + + def append c, type + trie = (@children[c] ||= TrieNode.new) + trie.add_type type + end + + def [](c) + @children[c] + end + + def add_type type + @types[type] = true + self + end + + def types + @types.keys + end + + def type + if @types.size == 1 + @types.keys.first + else + nil + end + end + + def candidates + @children.map{|c, n| + ss = n.candidates + ss.empty? ? c : + ss.map{|s| + c+s + } + }.flatten + end + end + + # config: { type: [commands...], ... } + def initialize config + @trie = TrieNode.new + build config + end + + private def build config + config.each do |type, commands| + commands.each do |command| + trie = @trie + command.each_char do |c| + trie = trie.append(c, type) + end + end + end + end + + def search str, if_none = nil + trie = @trie + str.each_char do |c| + if trie = trie[c] + return trie.type if trie.type + else + return if_none + end + end + yield trie.candidates.map{|s| str + s} if block_given? + if_none + end + end +end diff --git a/lib/debug/breakpoint.rb b/lib/debug/breakpoint.rb index e288a4555..78c4d2174 100644 --- a/lib/debug/breakpoint.rb +++ b/lib/debug/breakpoint.rb @@ -23,7 +23,7 @@ def safe_eval b, expr b.eval(expr) rescue Exception => e puts "[EVAL ERROR]" - puts " expr: #{expr}" + puts " expr: #{expr.inspect}" puts " err: #{e} (#{e.class})" puts "Error caused by #{self}." nil @@ -101,10 +101,6 @@ def skip_path?(path) def generate_label(name) colorize(" BP - #{name} ", [:YELLOW, :BOLD, :REVERSE]) end - - def pending_until_load? - false - end end if RUBY_VERSION.to_f <= 2.7 @@ -163,10 +159,6 @@ def initialize path, line, cond: nil, oneshot: false, hook_call: true, command: @pending = !@iseq end - def pending_until_load? - @pending - end - def setup return unless @type @@ -207,6 +199,8 @@ def activate iseq, event, line if @pending && !@oneshot DEBUGGER__.info "#{self} is activated." end + + @pending = false end def activate_exact iseq, events, line @@ -273,13 +267,10 @@ def try_activate root_iseq = nil if !nearest || ((line - nline).abs < (line - nearest.line).abs) nearest = NearestISeq.new(iseq, nline, events) - else - if @hook_call && nearest.iseq.first_lineno <= iseq.first_lineno - if (nearest.line > line && !nearest.events.include?(:RUBY_EVENT_CALL)) || - (events.include?(:RUBY_EVENT_CALL)) - nearest = NearestISeq.new(iseq, nline, events) - end - end + elsif @hook_call && + nearest.line == iseq.first_line && + events.include?(:RUBY_EVENT_CALL) + nearest = NearestISeq.new(iseq, nline, events) end end end @@ -302,6 +293,10 @@ def to_s def inspect "<#{self.class.name} #{self.to_s}>" end + + def path_is? path + DEBUGGER__.compare_path(@path, path) + end end class CatchBreakpoint < Breakpoint @@ -357,7 +352,7 @@ def setup next if ThreadClient.current.management? next if skip_path?(tp.path) - if need_suspend? safe_eval(tp.binding, @cond) + if @cond.nil? || need_suspend?(safe_eval(tp.binding, @cond)) suspend end } diff --git a/lib/debug/client.rb b/lib/debug/client.rb index f3023f12f..a801d3502 100644 --- a/lib/debug/client.rb +++ b/lib/debug/client.rb @@ -25,6 +25,9 @@ def util name when 'list-socks' cleanup_unix_domain_sockets puts list_connections + when 'list-socks-verbose' + cleanup_unix_domain_sockets + puts list_connections verbose: true when 'setup-autoload' setup_autoload else @@ -91,10 +94,24 @@ def cleanup_unix_domain_sockets end end - def list_connections - Dir.glob(DEBUGGER__.create_unix_domain_socket_name_prefix + '*').find_all do |path| + def list_connections verbose: false + socks = Dir.glob(DEBUGGER__.create_unix_domain_socket_name_prefix + '*').find_all do |path| File.socket?(path) end + + if verbose + socks = socks.map{|sock_path| + Socket.unix(sock_path){|sock| + sock.puts "info cookie: #{CONFIG[:cookie] || '-'}" + pid = sock.gets.chomp + _dbg = sock.gets.chomp + _unm = sock.gets.chomp + [sock_path, pid] + } + } + end + + socks end end @@ -157,9 +174,10 @@ def connect_unix name = nil when 1 @s = Socket.unix(files.first) else + files = Client.list_connections verbose: true $stderr.puts "Please select a debug session:" - files.each{|f| - $stderr.puts " #{File.basename(f)}" + files.each{|(f, desc)| + $stderr.puts " #{File.basename(f)} (#{desc})" } exit end diff --git a/lib/debug/config.rb b/lib/debug/config.rb index 70ca12487..a5af775af 100644 --- a/lib/debug/config.rb +++ b/lib/debug/config.rb @@ -12,45 +12,52 @@ module DEBUGGER__ CONFIG_SET = { # UI setting - log_level: ['RUBY_DEBUG_LOG_LEVEL', "UI: Log level same as Logger", :loglevel, "WARN"], - show_src_lines: ['RUBY_DEBUG_SHOW_SRC_LINES', "UI: Show n lines source code on breakpoint", :int, "10"], - show_frames: ['RUBY_DEBUG_SHOW_FRAMES', "UI: Show n frames on breakpoint", :int, "2"], - use_short_path: ['RUBY_DEBUG_USE_SHORT_PATH', "UI: Show shorten PATH (like $(Gem)/foo.rb)", :bool, "false"], - no_color: ['RUBY_DEBUG_NO_COLOR', "UI: Do not use colorize", :bool, "false"], - no_sigint_hook: ['RUBY_DEBUG_NO_SIGINT_HOOK', "UI: Do not suspend on SIGINT", :bool, "false"], - no_reline: ['RUBY_DEBUG_NO_RELINE', "UI: Do not use Reline library", :bool, "false"], - no_hint: ['RUBY_DEBUG_NO_HINT', "UI: Do not show the hint on the REPL", :bool, "false"], + log_level: ['RUBY_DEBUG_LOG_LEVEL', "UI: Log level same as Logger", :loglevel, "WARN"], + show_src_lines: ['RUBY_DEBUG_SHOW_SRC_LINES', "UI: Show n lines source code on breakpoint", :int, "10"], + show_src_lines_frame:['RUBY_DEBUG_SHOW_SRC_LINES_FRAME', "UI: Show n lines source code on frame operations", :int, "1"], + show_evaledsrc: ['RUBY_DEBUG_SHOW_EVALEDSRC', "UI: Show actually evaluated source", :bool, "false"], + show_frames: ['RUBY_DEBUG_SHOW_FRAMES', "UI: Show n frames on breakpoint", :int, "2"], + use_short_path: ['RUBY_DEBUG_USE_SHORT_PATH', "UI: Show shorten PATH (like $(Gem)/foo.rb)", :bool, "false"], + no_color: ['RUBY_DEBUG_NO_COLOR', "UI: Do not use colorize", :bool, "false"], + no_sigint_hook: ['RUBY_DEBUG_NO_SIGINT_HOOK', "UI: Do not suspend on SIGINT", :bool, "false"], + no_reline: ['RUBY_DEBUG_NO_RELINE', "UI: Do not use Reline library", :bool, "false"], + no_hint: ['RUBY_DEBUG_NO_HINT', "UI: Do not show the hint on the REPL", :bool, "false"], + no_lineno: ['RUBY_DEBUG_NO_LINENO', "UI: Do not show line numbers", :bool, "false"], + no_repeat: ['RUBY_DEBUG_NO_REPEAT', "UI: Do not repeat last line when empty line",:bool, "false"], + irb_console: ["RUBY_DEBUG_IRB_CONSOLE", "UI: Use IRB as the console", :bool, "false"], # control setting - skip_path: ['RUBY_DEBUG_SKIP_PATH', "CONTROL: Skip showing/entering frames for given paths", :path], - skip_nosrc: ['RUBY_DEBUG_SKIP_NOSRC', "CONTROL: Skip on no source code lines", :bool, "false"], - keep_alloc_site:['RUBY_DEBUG_KEEP_ALLOC_SITE',"CONTROL: Keep allocation site and p, pp shows it", :bool, "false"], - postmortem: ['RUBY_DEBUG_POSTMORTEM', "CONTROL: Enable postmortem debug", :bool, "false"], - fork_mode: ['RUBY_DEBUG_FORK_MODE', "CONTROL: Control which process activates a debugger after fork (both/parent/child)", :forkmode, "both"], - sigdump_sig: ['RUBY_DEBUG_SIGDUMP_SIG', "CONTROL: Sigdump signal", :bool, "false"], + skip_path: ['RUBY_DEBUG_SKIP_PATH', "CONTROL: Skip showing/entering frames for given paths", :path], + skip_nosrc: ['RUBY_DEBUG_SKIP_NOSRC', "CONTROL: Skip on no source code lines", :bool, "false"], + keep_alloc_site: ['RUBY_DEBUG_KEEP_ALLOC_SITE',"CONTROL: Keep allocation site and p, pp shows it", :bool, "false"], + postmortem: ['RUBY_DEBUG_POSTMORTEM', "CONTROL: Enable postmortem debug", :bool, "false"], + fork_mode: ['RUBY_DEBUG_FORK_MODE', "CONTROL: Control which process activates a debugger after fork (both/parent/child)", :forkmode, "both"], + sigdump_sig: ['RUBY_DEBUG_SIGDUMP_SIG', "CONTROL: Sigdump signal", :bool, "false"], # boot setting - nonstop: ['RUBY_DEBUG_NONSTOP', "BOOT: Nonstop mode", :bool, "false"], - stop_at_load: ['RUBY_DEBUG_STOP_AT_LOAD',"BOOT: Stop at just loading location", :bool, "false"], - init_script: ['RUBY_DEBUG_INIT_SCRIPT', "BOOT: debug command script path loaded at first stop"], - commands: ['RUBY_DEBUG_COMMANDS', "BOOT: debug commands invoked at first stop. commands should be separated by ';;'"], - no_rc: ['RUBY_DEBUG_NO_RC', "BOOT: ignore loading ~/.rdbgrc(.rb)", :bool, "false"], - history_file: ['RUBY_DEBUG_HISTORY_FILE',"BOOT: history file", :string, "~/.rdbg_history"], - save_history: ['RUBY_DEBUG_SAVE_HISTORY',"BOOT: maximum save history lines", :int, "10000"], + nonstop: ['RUBY_DEBUG_NONSTOP', "BOOT: Nonstop mode", :bool, "false"], + stop_at_load: ['RUBY_DEBUG_STOP_AT_LOAD',"BOOT: Stop at just loading location", :bool, "false"], + init_script: ['RUBY_DEBUG_INIT_SCRIPT', "BOOT: debug command script path loaded at first stop"], + commands: ['RUBY_DEBUG_COMMANDS', "BOOT: debug commands invoked at first stop. Commands should be separated by `;;`"], + no_rc: ['RUBY_DEBUG_NO_RC', "BOOT: ignore loading ~/.rdbgrc(.rb)", :bool, "false"], + history_file: ['RUBY_DEBUG_HISTORY_FILE',"BOOT: history file (default: ${XDG_STATE_HOME-~/.local/state}/rdbg/history)", :string, nil], + save_history: ['RUBY_DEBUG_SAVE_HISTORY',"BOOT: maximum save history lines", :int, "10000"], # remote setting - open: ['RUBY_DEBUG_OPEN', "REMOTE: Open remote port (same as `rdbg --open` option)"], - port: ['RUBY_DEBUG_PORT', "REMOTE: TCP/IP remote debugging: port"], - host: ['RUBY_DEBUG_HOST', "REMOTE: TCP/IP remote debugging: host", :string, "127.0.0.1"], - sock_path: ['RUBY_DEBUG_SOCK_PATH', "REMOTE: UNIX Domain Socket remote debugging: socket path"], - sock_dir: ['RUBY_DEBUG_SOCK_DIR', "REMOTE: UNIX Domain Socket remote debugging: socket directory"], - local_fs_map: ['RUBY_DEBUG_LOCAL_FS_MAP', "REMOTE: Specify local fs map", :path_map], - skip_bp: ['RUBY_DEBUG_SKIP_BP', "REMOTE: Skip breakpoints if no clients are attached", :bool, 'false'], - cookie: ['RUBY_DEBUG_COOKIE', "REMOTE: Cookie for negotiation"], - chrome_path: ['RUBY_DEBUG_CHROME_PATH', "REMOTE: Platform dependent path of Chrome (For more information, See [here](https://github.com/ruby/debug/pull/334/files#diff-5fc3d0a901379a95bc111b86cf0090b03f857edfd0b99a0c1537e26735698453R55-R64))"], + open: ['RUBY_DEBUG_OPEN', "REMOTE: Open remote port (same as `rdbg --open` option)"], + port: ['RUBY_DEBUG_PORT', "REMOTE: TCP/IP remote debugging: port"], + port_range: ['RUBY_DEBUG_PORT_RANGE', "REMOTE: TCP/IP remote debugging: length of port range"], + host: ['RUBY_DEBUG_HOST', "REMOTE: TCP/IP remote debugging: host", :string, "127.0.0.1"], + sock_path: ['RUBY_DEBUG_SOCK_PATH', "REMOTE: UNIX Domain Socket remote debugging: socket path"], + sock_dir: ['RUBY_DEBUG_SOCK_DIR', "REMOTE: UNIX Domain Socket remote debugging: socket directory"], + local_fs_map: ['RUBY_DEBUG_LOCAL_FS_MAP', "REMOTE: Specify local fs map", :path_map], + skip_bp: ['RUBY_DEBUG_SKIP_BP', "REMOTE: Skip breakpoints if no clients are attached", :bool, 'false'], + cookie: ['RUBY_DEBUG_COOKIE', "REMOTE: Cookie for negotiation"], + session_name: ['RUBY_DEBUG_SESSION_NAME', "REMOTE: Session name for differentiating multiple sessions"], + chrome_path: ['RUBY_DEBUG_CHROME_PATH', "REMOTE: Platform dependent path of Chrome (For more information, See [here](https://github.com/ruby/debug/pull/334/files#diff-5fc3d0a901379a95bc111b86cf0090b03f857edfd0b99a0c1537e26735698453R55-R64))"], # obsolete - parent_on_fork: ['RUBY_DEBUG_PARENT_ON_FORK', "OBSOLETE: Keep debugging parent process on fork", :bool, "false"], + parent_on_fork: ['RUBY_DEBUG_PARENT_ON_FORK', "OBSOLETE: Keep debugging parent process on fork", :bool, "false"], }.freeze CONFIG_MAP = CONFIG_SET.map{|k, (ev, _)| [k, ev]}.to_h.freeze @@ -67,7 +74,7 @@ def initialize argv raise 'Can not make multiple configurations in one process' end - config = self.class.parse_argv(argv) + config, _ = *self.class.parse_argv(argv) # apply defaults CONFIG_SET.each do |k, config_detail| @@ -148,6 +155,28 @@ def update conf if_updated old_conf, conf, :sigdump_sig do |old_sig, new_sig| setup_sigdump old_sig, new_sig end + + if_updated old_conf, conf, :no_sigint_hook do |old, new| + if defined?(SESSION) + SESSION.set_no_sigint_hook old, new + end + end + + if_updated old_conf, conf, :irb_console do |old, new| + if defined?(SESSION) && SESSION.active? + # irb_console is switched from true to false + if old + SESSION.deactivate_irb_integration + # irb_console is switched from false to true + else + if CONFIG[:open] + SESSION.instance_variable_get(:@ui).puts "\nIRB is not supported on the remote console." + else + SESSION.activate_irb_integration + end + end + end + end end private def if_updated old_conf, new_conf, key @@ -248,16 +277,12 @@ def self.parse_argv argv config[key] = parse_config_value(key, val) end } - return config if !argv || argv.empty? - - if argv.kind_of? String - require 'shellwords' - argv = Shellwords.split(argv) - end require 'optparse' require_relative 'version' + have_shown_version = false + opt = OptionParser.new do |o| o.banner = "#{$0} [options] -- [debuggee options]" o.separator '' @@ -324,12 +349,18 @@ def self.parse_argv argv o.on('--port=PORT', 'Listening TCP/IP port') do |port| config[:port] = port end + o.on('--port-range=PORT_RANGE', 'Number of ports to try to connect to') do |port_range| + config[:port_range] = port_range + end o.on('--host=HOST', 'Listening TCP/IP host') do |host| config[:host] = host end o.on('--cookie=COOKIE', 'Set a cookie for connection') do |c| config[:cookie] = c end + o.on('--session-name=NAME', 'Session name') do |name| + config[:session_name] = name + end rdbg = 'rdbg' @@ -365,6 +396,16 @@ def self.parse_argv argv o.separator '' o.separator 'Other options:' + o.on('-v', 'Show version number') do + puts o.ver + have_shown_version = true + end + + o.on('--version', 'Show version number and exit') do + puts o.ver + exit + end + o.on("-h", "--help", "Print help") do puts o exit @@ -386,9 +427,23 @@ def self.parse_argv argv o.separator ' Please use the remote debugging feature carefully.' end + return [config, opt] if !argv || argv.empty? + + if argv.kind_of? String + require 'shellwords' + argv = Shellwords.split(argv) + end + opt.parse!(argv) - config + if argv.empty? + case + when have_shown_version && config[:mode] == :start + exit + end + end + + [config, opt] end def self.config_to_env_hash config @@ -418,8 +473,9 @@ def self.check_dir_authority path unless (dir_uid = fs.uid) == (uid = Process.uid) raise "#{path} uid is #{dir_uid}, but Process.uid is #{uid}" end - unless (dir_mode = fs.mode) == 040700 # 4: dir, 7:rwx - raise "#{path}'s mode is #{dir_mode.to_s(8)} (should be 040700)" + + if fs.world_writable? && !fs.sticky? + raise "#{path} is world writable but not sticky" end path @@ -429,7 +485,7 @@ def self.unix_domain_socket_tmpdir require 'tmpdir' if tmpdir = Dir.tmpdir - path = File.join(tmpdir, "ruby-debug-sock-#{Process.uid}") + path = File.join(tmpdir, "rdbg-#{Process.uid}") unless File.exist?(path) d = Dir.mktmpdir @@ -442,7 +498,7 @@ def self.unix_domain_socket_tmpdir def self.unix_domain_socket_homedir if home = ENV['HOME'] - path = File.join(home, '.ruby-debug-sock') + path = File.join(home, '.rdbg-sock') unless File.exist?(path) Dir.mkdir(path, 0700) @@ -466,12 +522,14 @@ def self.unix_domain_socket_dir end def self.create_unix_domain_socket_name_prefix(base_dir = unix_domain_socket_dir) - user = ENV['USER'] || 'UnknownUser' - File.join(base_dir, "ruby-debug-#{user}") + File.join(base_dir, "rdbg") end def self.create_unix_domain_socket_name(base_dir = unix_domain_socket_dir) - create_unix_domain_socket_name_prefix(base_dir) + "-#{Process.pid}" + suffix = "-#{Process.pid}" + name = CONFIG[:session_name] + suffix << "-#{name}" if name + create_unix_domain_socket_name_prefix(base_dir) + suffix end ## Help diff --git a/lib/debug/console.rb b/lib/debug/console.rb index 2da261662..211af9e49 100644 --- a/lib/debug/console.rb +++ b/lib/debug/console.rb @@ -5,30 +5,9 @@ class Console raise LoadError if CONFIG[:no_reline] require 'reline' - # reline 0.2.7 or later is required. - raise LoadError if Reline::VERSION < '0.2.7' - require_relative 'color' - include Color - - begin - prev = trap(:SIGWINCH, nil) - trap(:SIGWINCH, prev) - SIGWINCH_SUPPORTED = true - rescue ArgumentError - SIGWINCH_SUPPORTED = false - end - # 0.2.7 has SIGWINCH issue on non-main thread - class ::Reline::LineEditor - m = Module.new do - def reset(prompt = '', encoding:) - super - Signal.trap(:SIGWINCH, nil) - end - end - prepend m - end if SIGWINCH_SUPPORTED + include Color def parse_input buff, commands c, rest = get_command buff @@ -56,10 +35,10 @@ def readline_setup prompt Reline.prompt_proc = -> args, *kw do case state = parse_input(args.first, commands) when nil, :command - [prompt, prompt] + [prompt] when :ruby - [prompt.sub('rdbg'){colorize('ruby', [:RED])}] * 2 - end + [prompt.sub('rdbg'){colorize('ruby', [:RED])}] + end * args.size end Reline.completion_proc = -> given do @@ -96,7 +75,7 @@ def readline_setup prompt when nil buff when :ruby - colorize_code(buff.chomp) + colorize_code(buff) end end unless CONFIG[:no_hint] @@ -164,7 +143,7 @@ def history rescue LoadError def readline prompt print prompt - gets + $stdin.gets end def history @@ -174,21 +153,29 @@ def history end def history_file - history_file = CONFIG[:history_file] - - if !history_file.empty? - File.expand_path(history_file) + case + when (path = CONFIG[:history_file]) && !path.empty? + path = File.expand_path(path) + when (path = File.expand_path("~/.rdbg_history")) && File.exist?(path) # for compatibility + # path else - history_file + state_dir = ENV['XDG_STATE_HOME'] || File.join(Dir.home, '.local', 'state') + path = File.join(File.expand_path(state_dir), 'rdbg', 'history') end + + require 'fileutils' + FileUtils.mkdir_p(File.dirname(path)) unless File.exist?(path) + path end FH = "# Today's OMIKUJI: " def read_history_file - if history && File.exist?(path = history_file) + if history && File.exist?(path = history_file()) f = (['', 'DAI-', 'CHU-', 'SHO-'].map{|e| e+'KICHI'}+['KYO']).sample - ["#{FH}#{f}".dup] + File.readlines(path) + # Read history file and scrub invalid characters to prevent encoding errors + lines = File.readlines(path).map(&:scrub) + ["#{FH}#{f}".dup] + lines else [] end @@ -207,15 +194,17 @@ def load_history_if_not_loaded def deactivate if history && @init_history_lines added_records = history.to_a[@init_history_lines .. -1] - path = history_file + path = history_file() max = CONFIG[:save_history] if !added_records.empty? && !path.empty? orig_records = read_history_file - open(history_file, 'w'){|f| + open(history_file(), 'w'){|f| (orig_records + added_records).last(max).each{|line| - if !line.start_with?(FH) && !line.strip.empty? - f.puts line.strip + # Use scrub to handle encoding issues gracefully + scrubbed_line = line.scrub.strip + if !line.start_with?(FH) && !scrubbed_line.empty? + f.puts scrubbed_line end } } @@ -224,11 +213,13 @@ def deactivate end def load_history - read_history_file.count{|line| + read_history_file.each{|line| + # Use scrub to handle encoding issues gracefully, then strip + line.scrub! line.strip! history << line unless line.empty? - } + } if history.empty? + history.count end end # class Console end - diff --git a/lib/debug/dap_custom/traceInspector.rb b/lib/debug/dap_custom/traceInspector.rb new file mode 100644 index 000000000..902e3a24f --- /dev/null +++ b/lib/debug/dap_custom/traceInspector.rb @@ -0,0 +1,336 @@ +module DEBUGGER__ + module DAP_TraceInspector + class MultiTracer < Tracer + def initialize ui, evts, trace_params, max_log_size: nil, **kw + @evts = evts + @log = [] + @trace_params = trace_params + if max_log_size + @max_log_size = max_log_size + else + @max_log_size = 50000 + end + @dropped_trace_cnt = 0 + super(ui, **kw) + @type = 'multi' + @name = 'TraceInspector' + end + + attr_accessor :dropped_trace_cnt + attr_reader :log + + def setup + @tracer = TracePoint.new(*@evts){|tp| + next if skip?(tp) + + case tp.event + when :call, :c_call, :b_call + if @trace_params + params = parameters_info tp + end + append(call_trace_log(tp, params: params)) + when :return, :c_return, :b_return + return_str = DEBUGGER__.safe_inspect(tp.return_value, short: true, max_length: 4096) + append(call_trace_log(tp, return_str: return_str)) + when :line + append(line_trace_log(tp)) + end + } + end + + def parameters_info tp + b = tp.binding + tp.parameters.map{|_type, name| + begin + { name: name, value: DEBUGGER__.safe_inspect(b.local_variable_get(name), short: true, max_length: 4096) } + rescue NameError, TypeError + nil + end + }.compact + end + + def call_identifier_str tp + if tp.defined_class + minfo(tp) + else + "block" + end + end + + def append log + if @log.size >= @max_log_size + @dropped_trace_cnt += 1 + @log.shift + end + @log << log + end + + def call_trace_log tp, return_str: nil, params: nil + log = { + depth: DEBUGGER__.frame_depth, + name: call_identifier_str(tp), + threadId: Thread.current.instance_variable_get(:@__thread_client_id), + location: { + path: tp.path, + line: tp.lineno + } + } + log[:returnValue] = return_str if return_str + log[:parameters] = params if params && params.size > 0 + log + end + + def line_trace_log tp + { + depth: DEBUGGER__.frame_depth, + threadId: Thread.current.instance_variable_get(:@__thread_client_id), + location: { + path: tp.path, + line: tp.lineno + } + } + end + + def skip? tp + super || !@evts.include?(tp.event) + end + + def skip_with_pattern?(tp) + super && !tp.method_id&.match?(@pattern) + end + end + + class Custom_Recorder < ThreadClient::Recorder + def initialize max_log_size: nil + if max_log_size + @max_log_size = max_log_size + else + @max_log_size = 50000 + end + @dropped_trace_cnt = 0 + super() + end + + attr_accessor :dropped_trace_cnt + + def append frames + if @log.size >= @max_log_size + @dropped_trace_cnt += 1 + @log.shift + end + @log << frames + end + end + + module Custom_UI_DAP + def custom_dap_request_rdbgTraceInspector(req) + @q_msg << req + end + end + + module Custom_Session + def process_trace_cmd req + cmd = req.dig('arguments', 'subCommand') + case cmd + when 'enable' + events = req.dig('arguments', 'events') + evts = [] + trace_params = false + filter = req.dig('arguments', 'filterRegExp') + max_log_size = req.dig('arguments', 'maxLogSize') + events.each{|evt| + case evt + when 'traceLine' + evts << :line + when 'traceCall' + evts << :call + evts << :b_call + when 'traceReturn' + evts << :return + evts << :b_return + when 'traceParams' + trace_params = true + when 'traceClanguageCall' + evts << :c_call + when 'traceClanguageReturn' + evts << :c_return + else + raise "unknown trace type #{evt}" + end + } + add_tracer MultiTracer.new @ui, evts, trace_params, max_log_size: max_log_size, pattern: filter + @ui.respond req, {} + when 'disable' + if t = find_multi_trace + t.disable + end + @ui.respond req, {} + when 'collect' + logs = [] + if t = find_multi_trace + logs = t.log + if t.dropped_trace_cnt > 0 + @ui.puts "Return #{logs.size} traces and #{t.dropped_trace_cnt} traces are dropped" + else + @ui.puts "Return #{logs.size} traces" + end + t.dropped_trace_cnt = 0 + end + @ui.respond req, logs: logs + else + raise "Unknown trace sub command #{cmd}" + end + return :retry + end + + def find_multi_trace + @tracers.values.each{|t| + if t.type == 'multi' + return t + end + } + return nil + end + + def process_record_cmd req + cmd = req.dig('arguments', 'subCommand') + case cmd + when 'enable' + @tc << [:dap, :rdbgTraceInspector, req] + when 'disable' + @tc << [:dap, :rdbgTraceInspector, req] + when 'step' + tid = req.dig('arguments', 'threadId') + count = req.dig('arguments', 'count') + if tc = find_waiting_tc(tid) + @ui.respond req, {} + tc << [:step, :in, count] + else + fail_response req + end + when 'stepBack' + tid = req.dig('arguments', 'threadId') + count = req.dig('arguments', 'count') + if tc = find_waiting_tc(tid) + @ui.respond req, {} + tc << [:step, :back, count] + else + fail_response req + end + when 'collect' + tid = req.dig('arguments', 'threadId') + if tc = find_waiting_tc(tid) + tc << [:dap, :rdbgTraceInspector, req] + else + fail_response req + end + else + raise "Unknown record sub command #{cmd}" + end + end + + def custom_dap_request_rdbgTraceInspector(req) + cmd = req.dig('arguments', 'command') + case cmd + when 'trace' + process_trace_cmd req + when 'record' + process_record_cmd req + else + raise "Unknown command #{cmd}" + end + end + + def custom_dap_request_event_rdbgTraceInspector(req, result) + cmd = req.dig('arguments', 'command') + case cmd + when 'record' + process_event_record_cmd(req, result) + else + raise "Unknown command #{cmd}" + end + end + + def process_event_record_cmd(req, result) + cmd = req.dig('arguments', 'subCommand') + case cmd + when 'enable' + @ui.respond req, {} + when 'disable' + @ui.respond req, {} + when 'collect' + cnt = result.delete :dropped_trace_cnt + if cnt > 0 + @ui.puts "Return #{result[:logs].size} traces and #{cnt} traces are dropped" + else + @ui.puts "Return #{result[:logs].size} traces" + end + @ui.respond req, result + else + raise "Unknown command #{cmd}" + end + end + end + + module Custom_ThreadClient + def custom_dap_request_rdbgTraceInspector(req) + cmd = req.dig('arguments', 'command') + case cmd + when 'record' + process_record_cmd(req) + else + raise "Unknown command #{cmd}" + end + end + + def process_record_cmd(req) + cmd = req.dig('arguments', 'subCommand') + case cmd + when 'enable' + size = req.dig('arguments', 'maxLogSize') + @recorder = Custom_Recorder.new max_log_size: size + @recorder.enable + event! :protocol_result, :rdbgTraceInspector, req + when 'disable' + if @recorder&.enabled? + @recorder.disable + end + @recorder = nil + event! :protocol_result, :rdbgTraceInspector, req + when 'collect' + logs = [] + log_index = nil + trace_cnt = 0 + unless @recorder.nil? + log_index = @recorder.log_index + @recorder.log.each{|frames| + crt_frame = frames[0] + log = { + name: crt_frame.name, + location: { + path: crt_frame.location.path, + line: crt_frame.location.lineno, + }, + depth: crt_frame.frame_depth + } + if params = crt_frame.iseq_parameters_info + log[:parameters] = params + end + if return_str = crt_frame.return_str + log[:returnValue] = return_str + end + logs << log + } + trace_cnt = @recorder.dropped_trace_cnt + @recorder.dropped_trace_cnt = 0 + end + event! :protocol_result, :rdbgTraceInspector, req, logs: logs, stoppedIndex: log_index, dropped_trace_cnt: trace_cnt + else + raise "Unknown command #{cmd}" + end + end + end + + ::DEBUGGER__::SESSION.extend_feature session: Custom_Session, thread_client: Custom_ThreadClient, ui: Custom_UI_DAP + end +end diff --git a/lib/debug/frame_info.rb b/lib/debug/frame_info.rb index fa4135935..558f5466b 100644 --- a/lib/debug/frame_info.rb +++ b/lib/debug/frame_info.rb @@ -86,7 +86,9 @@ def frame_type def block_identifier return unless frame_type == :block - _, level, block_loc = location.label.match(BLOCK_LABL_REGEXP).to_a + re_match = location.label.match(BLOCK_LABL_REGEXP) + _, level, block_loc = re_match ? re_match.to_a : [nil, nil, location.label] + [level || "", block_loc] end @@ -147,6 +149,15 @@ def local_variables end end + def iseq_parameters_info + case frame_type + when :block, :method + parameters_info + else + nil + end + end + def parameters_info vars = iseq.parameters_symbols vars.map{|var| @@ -160,7 +171,7 @@ def parameters_info private def get_singleton_class obj obj.singleton_class # TODO: don't use it - rescue TypeError + rescue Exception nil end diff --git a/lib/debug/irb_integration.rb b/lib/debug/irb_integration.rb new file mode 100644 index 000000000..3fc92ea61 --- /dev/null +++ b/lib/debug/irb_integration.rb @@ -0,0 +1,37 @@ +# frozen_string_literal: true + +require 'irb' + +module DEBUGGER__ + module IrbPatch + def evaluate(line, line_no) + SESSION.send(:restart_all_threads) + super + # This is to communicate with the test framework so it can feed the next input + puts "INTERNAL_INFO: {}" if ENV['RUBY_DEBUG_TEST_UI'] == 'terminal' + ensure + SESSION.send(:stop_all_threads) + end + end + + class ThreadClient + def activate_irb_integration + IRB.setup(location, argv: []) + workspace = IRB::WorkSpace.new(current_frame&.binding || TOPLEVEL_BINDING) + irb = IRB::Irb.new(workspace) + IRB.conf[:MAIN_CONTEXT] = irb.context + IRB::Debug.setup(irb) + IRB::Context.prepend(IrbPatch) + end + end + + class Session + def deactivate_irb_integration + Reline.completion_proc = nil + Reline.output_modifier_proc = nil + Reline.autocompletion = false + Reline.dig_perfect_match_proc = nil + reset_ui UI_LocalConsole.new + end + end +end diff --git a/lib/debug/local.rb b/lib/debug/local.rb index 9cbecd1cd..77f6caa66 100644 --- a/lib/debug/local.rb +++ b/lib/debug/local.rb @@ -13,23 +13,28 @@ def remote? false end - def activate session, on_fork: false - unless CONFIG[:no_sigint_hook] - prev_handler = trap(:SIGINT){ - if session.active? - ThreadClient.current.on_trap :SIGINT - end - } - session.intercept_trap_sigint_start prev_handler - end + def activate_sigint + prev_handler = trap(:SIGINT){ + if SESSION.active? + ThreadClient.current.on_trap :SIGINT + end + } + SESSION.intercept_trap_sigint_start prev_handler end - def deactivate + def deactivate_sigint if SESSION.intercept_trap_sigint? prev = SESSION.intercept_trap_sigint_end trap(:SIGINT, prev) end + end + + def activate session, on_fork: false + activate_sigint unless CONFIG[:no_sigint_hook] + end + def deactivate + deactivate_sigint @console.deactivate end diff --git a/lib/debug/prelude.rb b/lib/debug/prelude.rb index 67ba18ca2..c83c63a5f 100644 --- a/lib/debug/prelude.rb +++ b/lib/debug/prelude.rb @@ -1,11 +1,11 @@ # frozen_string_literal: true return if ENV['RUBY_DEBUG_ENABLE'] == '0' -return if defined?(::DEBUGGER__) +return if defined?(::DEBUGGER__::Session) # Put the following line in your login script (e.g. ~/.bash_profile) with modified path: # -# export RUBYOPT="-r /path/to/debug/prelude $(RUBYOPT)" +# export RUBYOPT="-r /path/to/debug/prelude ${RUBYOPT}" # module Kernel def debugger(*a, up_level: 0, **kw) diff --git a/lib/debug/server.rb b/lib/debug/server.rb index 25445fb9e..0a3c7d266 100644 --- a/lib/debug/server.rb +++ b/lib/debug/server.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require 'socket' +require 'fileutils' require_relative 'config' require_relative 'version' @@ -133,7 +134,7 @@ def greeting require 'etc' check_cookie $1 - @sock.puts "PID: #{Process.pid}, $0: #{$0}" + @sock.puts "PID: #{Process.pid}, $0: #{$0}, session_name: #{CONFIG[:session_name]}" @sock.puts "debug #{VERSION} on #{RUBY_DESCRIPTION}" @sock.puts "uname: #{Etc.uname.inspect}" @sock.close @@ -144,11 +145,14 @@ def greeting # TODO: protocol version if v != VERSION - raise GreetingError, "Incompatible version (server:#{VERSION} and client:#{$1})" + @sock.puts msg = "out DEBUGGER: Incompatible version (server:#{VERSION} and client:#{$1})" + raise GreetingError, msg end parse_option(params) - puts "DEBUGGER (client): Connected. PID:#{Process.pid}, $0:#{$0}" + session_name = CONFIG[:session_name] + session_name_str = ", session_name:#{session_name}" if session_name + puts "DEBUGGER (client): Connected. PID:#{Process.pid}, $0:#{$0}#{session_name_str}" puts "DEBUGGER (client): Type `Ctrl-C` to enter the debug console." unless @need_pause_at_first puts @@ -396,6 +400,13 @@ def initialize host: nil, port: nil raise "Specify digits for port number" end end + @port_range = if @port.zero? + 0 + else + port_range_str = (CONFIG[:port_range] || "0").to_s + raise "Specify a positive integer <=16 for port range" unless port_range_str.match?(/\A\d+\z/) && port_range_str.to_i <= 16 + port_range_str.to_i + end @uuid = nil # for CDP super() @@ -405,14 +416,13 @@ def chrome_setup require_relative 'server_cdp' @uuid = SecureRandom.uuid - unless @chrome_pid = UI_CDP.setup_chrome(@local_addr.inspect_sockaddr, @uuid) - DEBUGGER__.warn <<~EOS - With Chrome browser, type the following URL in the address-bar: + @chrome_pid = UI_CDP.setup_chrome(@local_addr.inspect_sockaddr, @uuid) + DEBUGGER__.warn <<~EOS + With Chrome browser, type the following URL in the address-bar: - devtools://devtools/bundled/inspector.html?v8only=true&panel=sources&ws=#{@local_addr.inspect_sockaddr}/#{@uuid} + devtools://devtools/bundled/inspector.html?v8only=true&panel=sources&noJavaScriptCompletion=true&ws=#{@local_addr.inspect_sockaddr}/#{@uuid} - EOS - end + EOS end def accept @@ -430,7 +440,7 @@ def accept DEBUGGER__.warn "Port is saved into #{@port_save_file}" end - DEBUGGER__.warn <<~EOS + DEBUGGER__.info <<~EOS With rdbg, use the following command line: # # #{rdbg} --attach #{@local_addr.ip_address} #{@local_addr.ip_port} @@ -450,7 +460,9 @@ def accept end end rescue Errno::EADDRINUSE - if retry_cnt < 10 + number_of_retries = @port_range.zero? ? 10 : @port_range + if retry_cnt < number_of_retries + @port += 1 unless @port_range.zero? retry_cnt += 1 sleep 0.1 retry diff --git a/lib/debug/server_cdp.rb b/lib/debug/server_cdp.rb index a63dbb2b9..9adb09795 100644 --- a/lib/debug/server_cdp.rb +++ b/lib/debug/server_cdp.rb @@ -2,7 +2,6 @@ require 'json' require 'digest/sha1' -require 'base64' require 'securerandom' require 'stringio' require 'open3' @@ -34,33 +33,47 @@ def setup_chrome addr, uuid loop do res = ws_client.extract_data - case - when res['id'] == 1 && target_info = res.dig('result', 'targetInfos') + case res['id'] + when 1 + target_info = res.dig('result', 'targetInfos') page = target_info.find{|t| t['type'] == 'page'} ws_client.send id: 2, method: 'Target.attachToTarget', params: { targetId: page['targetId'], flatten: true } - when res['id'] == 2 + when 2 s_id = res.dig('result', 'sessionId') + # TODO: change id + ws_client.send sessionId: s_id, id: 100, method: 'Network.enable' ws_client.send sessionId: s_id, id: 3, method: 'Page.enable' - when res['id'] == 3 + when 3 s_id = res['sessionId'] ws_client.send sessionId: s_id, id: 4, method: 'Page.getFrameTree' - when res['id'] == 4 + when 4 s_id = res['sessionId'] f_id = res.dig('result', 'frameTree', 'frame', 'id') ws_client.send sessionId: s_id, id: 5, method: 'Page.navigate', params: { - url: "devtools://devtools/bundled/inspector.html?v8only=true&panel=sources&ws=#{addr}/#{uuid}", + url: "devtools://devtools/bundled/inspector.html?v8only=true&panel=sources&noJavaScriptCompletion=true&ws=#{addr}/#{uuid}", frameId: f_id } - when res['method'] == 'Page.loadEventFired' + when 101 break + else + if res['method'] == 'Network.webSocketWillSendHandshakeRequest' + s_id = res['sessionId'] + # Display the console by entering ESC key + ws_client.send sessionId: s_id, id: 101, # TODO: change id + method:"Input.dispatchKeyEvent", + params: { + type:"keyDown", + windowsVirtualKeyCode:27 # ESC key + } + end end end pid @@ -84,7 +97,6 @@ def run_new_chrome candidates = ['C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe', 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe'] path = get_chrome_path candidates end - uuid = SecureRandom.uuid # The path is based on https://github.com/sindresorhus/open/blob/v8.4.0/index.js#L128. stdin, stdout, stderr, wait_thr = *Open3.popen3("#{ENV['SystemRoot']}\\System32\\WindowsPowerShell\\v1.0\\powershell") tf = Tempfile.create(['debug-', '.txt']) @@ -118,7 +130,7 @@ def run_new_chrome stdout.close data = stderr.readpartial 4096 stderr.close - if data.match /DevTools listening on ws:\/\/127.0.0.1:(\d+)(.*)/ + if data.match(/DevTools listening on ws:\/\/127.0.0.1:(\d+)(.*)/) port = $1 path = $2 end @@ -145,7 +157,7 @@ def run_new_chrome raise NotFoundChromeEndpointError end stderr.close - if data.match /DevTools listening on ws:\/\/127.0.0.1:(\d+)(.*)/ + if data.match(/DevTools listening on ws:\/\/127.0.0.1:(\d+)(.*)/) port = $1 path = $2 end @@ -177,7 +189,7 @@ def get_devtools_endpoint tf while i < ITERATIONS i += 1 if File.exist?(tf) && data = File.read(tf) - if data.match /DevTools listening on ws:\/\/127.0.0.1:(\d+)(.*)/ + if data.match(/DevTools listening on ws:\/\/127.0.0.1:(\d+)(.*)/) port = $1 path = $2 return [port, path] @@ -284,8 +296,8 @@ def handshake port, path res = @sock.readpartial 4092 show_protocol :<, res - if res.match /^Sec-WebSocket-Accept: (.*)\r\n/ - correct_key = Base64.strict_encode64 Digest::SHA1.digest "#{key}==258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + if res.match(/^Sec-WebSocket-Accept: (.*)\r\n/) + correct_key = Digest::SHA1.base64digest "#{key}==258EAFA5-E914-47DA-95CA-C5AB0DC85B11" raise "The Sec-WebSocket-Accept value: #{$1} is not valid" unless $1 == correct_key else raise "Unknown response: #{res}" @@ -365,8 +377,8 @@ def handshake req = @sock.readpartial 4096 show_protocol '>', req - if req.match /^Sec-WebSocket-Key: (.*)\r\n/ - accept = Base64.strict_encode64 Digest::SHA1.digest "#{$1}258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + if req.match(/^Sec-WebSocket-Key: (.*)\r\n/) + accept = Digest::SHA1.base64digest "#{$1}258EAFA5-E914-47DA-95CA-C5AB0DC85B11" res = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: #{accept}\r\n\r\n" @sock.print res show_protocol :<, res @@ -436,11 +448,7 @@ def extract_data end def send_response req, **res - if res.empty? - @ws_server.send id: req['id'], result: {} - else - @ws_server.send id: req['id'], result: res - end + @ws_server.send id: req['id'], result: res end def send_fail_response req, **res @@ -448,11 +456,7 @@ def send_fail_response req, **res end def send_event method, **params - if params.empty? - @ws_server.send method: method, params: {} - else - @ws_server.send method: method, params: params - end + @ws_server.send method: method, params: params end INVALID_REQUEST = -32600 @@ -469,7 +473,7 @@ def process when 'Debugger.getScriptSource' @q_msg << req when 'Debugger.enable' - send_response req + send_response req, debuggerId: rand.to_s @q_msg << req when 'Runtime.enable' send_response req @@ -543,6 +547,9 @@ def process activate_bp bps end send_response req + when 'Debugger.pause' + send_response req + Process.kill(UI_ServerBase::TRAP_SIGNAL, Process.pid) # breakpoint when 'Debugger.getPossibleBreakpoints' @@ -550,35 +557,31 @@ def process when 'Debugger.setBreakpointByUrl' line = req.dig('params', 'lineNumber') if regexp = req.dig('params', 'urlRegex') - path = regexp.match(/(.*)\|/)[1].gsub("\\", "") - cond = req.dig('params', 'condition') - src = get_source_code path - end_line = src.lines.count - line = end_line if line > end_line b_id = "1:#{line}:#{regexp}" - if cond != '' - SESSION.add_line_breakpoint(path, line + 1, cond: cond) - else - SESSION.add_line_breakpoint(path, line + 1) - end bps[b_id] = bps.size - # Because we need to return scriptId, responses are returned in SESSION thread. - req['params']['scriptId'] = path - req['params']['lineNumber'] = line - req['params']['breakpointId'] = b_id - @q_msg << req + path = regexp.match(/(.*)\|/)[1].gsub("\\", "") + add_line_breakpoint(req, b_id, path) elsif url = req.dig('params', 'url') b_id = "#{line}:#{url}" - send_response req, - breakpointId: b_id, - locations: [] - elsif hash = req.dig('params', 'scriptHash') - b_id = "#{line}:#{hash}" - send_response req, - breakpointId: b_id, - locations: [] + # When breakpoints are set in Script snippet, non-existent path such as "snippet:///Script%20snippet%20%231" sent. + # That's why we need to check it here. + if File.exist? url + bps[b_id] = bps.size + add_line_breakpoint(req, b_id, url) + else + send_response req, + breakpointId: b_id, + locations: [] + end else - raise 'Unsupported' + if hash = req.dig('params', 'scriptHash') + b_id = "#{line}:#{hash}" + send_response req, + breakpointId: b_id, + locations: [] + else + raise 'Unsupported' + end end when 'Debugger.removeBreakpoint' b_id = req.dig('params', 'breakpointId') @@ -617,6 +620,24 @@ def process @q_msg << 'continue' end + def add_line_breakpoint req, b_id, path + cond = req.dig('params', 'condition') + line = req.dig('params', 'lineNumber') + src = get_source_code path + end_line = src.lines.count + line = end_line if line > end_line + if cond != '' + SESSION.add_line_breakpoint(path, line + 1, cond: cond) + else + SESSION.add_line_breakpoint(path, line + 1) + end + # Because we need to return scriptId, responses are returned in SESSION thread. + req['params']['scriptId'] = path + req['params']['lineNumber'] = line + req['params']['breakpointId'] = b_id + @q_msg << req + end + def del_bp bps, k return bps unless idx = bps[k] @@ -636,7 +657,7 @@ def get_source_code path def activate_bp bps bps.each_key{|k| - if k.match /^\d+:(\d+):(.*)/ + if k.match(/^\d+:(\d+):(.*)/) line = $1 path = $2 SESSION.add_line_breakpoint(path, line.to_i + 1) @@ -654,37 +675,50 @@ def deactivate_bp def cleanup_reader super Process.kill :KILL, @chrome_pid if @chrome_pid + rescue Errno::ESRCH # continue if @chrome_pid process is not found end ## Called by the SESSION thread - def respond req, **result - send_response req, **result - end - - def respond_fail req, **result - send_fail_response req, **result - end - - def fire_event event, **result - if result.empty? - send_event event - else - send_event event, **result - end - end + alias respond send_response + alias respond_fail send_fail_response + alias fire_event send_event def sock skip: false yield $stderr end - def puts result + def puts result = "" # STDERR.puts "puts: #{result}" # send_event 'output', category: 'stderr', output: "PUTS!!: " + result.to_s end end class Session + include GlobalVariablesHelper + + # FIXME: unify this method with ThreadClient#propertyDescriptor. + def get_type obj + case obj + when Array + ['object', 'array'] + when Hash + ['object', 'map'] + when String + ['string'] + when TrueClass, FalseClass + ['boolean'] + when Symbol + ['symbol'] + when Integer, Float + ['number'] + when Exception + ['object', 'error'] + else + ['object'] + end + end + def fail_response req, **result @ui.respond_fail req, **result return :retry @@ -708,17 +742,42 @@ def process_protocol_request req code: INVALID_PARAMS, message: "'callFrameId' is an invalid" end - when 'Runtime.getProperties' - oid = req.dig('params', 'objectId') + when 'Runtime.getProperties', 'Runtime.getExceptionDetails' + oid = req.dig('params', 'objectId') || req.dig('params', 'errorObjectId') if ref = @obj_map[oid] case ref[0] when 'local' frame_id = ref[1] fid = @frame_map[frame_id] request_tc [:cdp, :scope, req, fid] + when 'global' + vars = safe_global_variables.sort.map do |name| + begin + gv = eval(name.to_s) + rescue Errno::ENOENT + gv = nil + end + prop = { + name: name, + value: { + description: gv.inspect + }, + configurable: true, + enumerable: true + } + type, subtype = get_type(gv) + prop[:value][:type] = type + prop[:value][:subtype] = subtype if subtype + prop + end + + @ui.respond req, result: vars + return :retry when 'properties' request_tc [:cdp, :properties, req, oid] - when 'script', 'global' + when 'exception' + request_tc [:cdp, :exception, req, oid] + when 'script' # TODO: Support script and global types @ui.respond req, result: [] return :retry @@ -777,7 +836,7 @@ def process_protocol_request req end end - def cdp_event args + def process_protocol_result args type, req, result = args case type @@ -789,27 +848,25 @@ def cdp_event args unless s_id = @scr_id_map[path] s_id = (@scr_id_map.size + 1).to_s @scr_id_map[path] = s_id + lineno = 0 + src = '' if path && File.exist?(path) src = File.read(path) + @src_map[s_id] = src + lineno = src.lines.count end - @src_map[s_id] = src - end - if src = @src_map[s_id] - lineno = src.lines.count - else - lineno = 0 - end - frame[:location][:scriptId] = s_id - frame[:functionLocation][:scriptId] = s_id - @ui.fire_event 'Debugger.scriptParsed', + @ui.fire_event 'Debugger.scriptParsed', scriptId: s_id, - url: frame[:url], + url: path, startLine: 0, startColumn: 0, endLine: lineno, endColumn: 0, executionContextId: 1, hash: src.hash.inspect + end + frame[:location][:scriptId] = s_id + frame[:functionLocation][:scriptId] = s_id frame[:scopeChain].each {|s| oid = s.dig(:object, :objectId) @@ -854,6 +911,9 @@ def cdp_event args frame[:scriptId] = s_id end } + if oid = exc[:exception][:objectId] + @obj_map[oid] = ['exception'] + end end rs = result.dig(:response, :result) [rs].each{|obj| @@ -891,6 +951,8 @@ def cdp_event args } } @ui.respond req, **result + when :exception + @ui.respond req, **result end end end @@ -962,7 +1024,7 @@ def process_cdp args result[:data] = evaluate_result exception result[:reason] = 'exception' end - event! :cdp_result, :backtrace, req, result + event! :protocol_result, :backtrace, req, result when :evaluate res = {} fid, expr, group = args @@ -981,7 +1043,7 @@ def process_cdp args case expr # Chrome doesn't read instance variables when /\A\$\S/ - global_variables.each{|gvar| + safe_global_variables.each{|gvar| if gvar.to_s == expr result = eval(gvar.to_s) break false @@ -1007,38 +1069,10 @@ def process_cdp args begin orig_stdout = $stdout $stdout = StringIO.new - result = current_frame.binding.eval(expr.to_s, '(DEBUG CONSOLE)') + result = b.eval(expr.to_s, '(DEBUG CONSOLE)') rescue Exception => e result = e - b = result.backtrace.map{|e| " #{e}\n"} - frames = [ - { - columnNumber: 0, - functionName: 'eval', - lineNumber: 0, - url: '' - } - ] - e.backtrace_locations&.each do |loc| - break if loc.path == __FILE__ - path = loc.absolute_path || loc.path - frames << { - columnNumber: 0, - functionName: loc.base_label, - lineNumber: loc.lineno - 1, - url: path - } - end - res[:exceptionDetails] = { - exceptionId: 1, - text: 'Uncaught', - lineNumber: 0, - columnNumber: 0, - exception: evaluate_result(result), - stackTrace: { - callFrames: frames - } - } + res[:exceptionDetails] = exceptionDetails(e, 'Uncaught') ensure output = $stdout.string $stdout = orig_stdout @@ -1051,7 +1085,7 @@ def process_cdp args end res[:result] = evaluate_result(result) - event! :cdp_result, :evaluate, req, message: message, response: res, output: output + event! :protocol_result, :evaluate, req, message: message, response: res, output: output when :scope fid = args.shift frame = @target_frames[fid] @@ -1074,7 +1108,7 @@ def process_cdp args vars.unshift variable(name, val) end end - event! :cdp_result, :scope, req, vars + event! :protocol_result, :scope, req, vars when :properties oid = args.shift result = [] @@ -1116,16 +1150,58 @@ def process_cdp args } prop += [internalProperty('#class', M_CLASS.bind_call(obj))] end - event! :cdp_result, :properties, req, result: result, internalProperties: prop + event! :protocol_result, :properties, req, result: result, internalProperties: prop + when :exception + oid = args.shift + exc = nil + if obj = @obj_map[oid] + exc = exceptionDetails obj, obj.to_s + end + event! :protocol_result, :exception, req, exceptionDetails: exc end end + def exceptionDetails exc, text + frames = [ + { + columnNumber: 0, + functionName: 'eval', + lineNumber: 0, + url: '' + } + ] + exc.backtrace_locations&.each do |loc| + break if loc.path == __FILE__ + path = loc.absolute_path || loc.path + frames << { + columnNumber: 0, + functionName: loc.base_label, + lineNumber: loc.lineno - 1, + url: path + } + end + { + exceptionId: 1, + text: text, + lineNumber: 0, + columnNumber: 0, + exception: evaluate_result(exc), + stackTrace: { + callFrames: frames + } + } + end + def search_const b, expr cs = expr.delete_prefix('::').split('::') [Object, *b.eval('::Module.nesting')].reverse_each{|mod| if cs.all?{|c| if mod.const_defined?(c) - mod = mod.const_get(c) + begin + mod = mod.const_get(c) + rescue Exception + false + end else false end diff --git a/lib/debug/server_dap.rb b/lib/debug/server_dap.rb index 18eccdd55..907db2d1f 100644 --- a/lib/debug/server_dap.rb +++ b/lib/debug/server_dap.rb @@ -125,6 +125,7 @@ def self.local_fs_map_set map def dap_setup bytes CONFIG.set_config no_color: true @seq = 0 + @send_lock = Mutex.new case self when UI_UnixDomainServer @@ -199,15 +200,26 @@ def dap_setup bytes # supportsInstructionBreakpoints: ) send_event 'initialized' + puts <<~WELCOME + Ruby REPL: You can run any Ruby expression here. + Note that output to the STDOUT/ERR printed on the TERMINAL. + [experimental] + `,COMMAND` runs `COMMAND` debug command (ex: `,info`). + `,help` to list all debug commands. + WELCOME end def send **kw if sock = @sock kw[:seq] = @seq += 1 str = JSON.dump(kw) - sock.write "Content-Length: #{str.bytesize}\r\n\r\n#{str}" + @send_lock.synchronize do + sock.write "Content-Length: #{str.bytesize}\r\n\r\n#{str}" + end show_protocol '<', str end + rescue Errno::EPIPE => e + $stderr.puts "#{e.inspect} rescued during sending message" end def send_response req, success: true, message: nil, **kw @@ -239,17 +251,17 @@ class RetryBecauseCantRead < Exception end def recv_request - r = IO.select([@sock]) + IO.select([@sock]) @session.process_group.sync do raise RetryBecauseCantRead unless IO.select([@sock], nil, nil, 0) - case header = @sock.gets + case @sock.gets when /Content-Length: (\d+)/ b = @sock.read(2) raise b.inspect unless b == "\r\n" - l = @sock.read(s = $1.to_i) + l = @sock.read($1.to_i) show_protocol :>, l JSON.load(l) when nil @@ -262,183 +274,225 @@ def recv_request retry end + def load_extensions req + if exts = req.dig('arguments', 'rdbgExtensions') + exts.each{|ext| + require_relative "dap_custom/#{File.basename(ext)}" + } + end + + if scripts = req.dig('arguments', 'rdbgInitialScripts') + scripts.each do |script| + begin + eval(script) + rescue Exception => e + puts e.message + puts e.backtrace.inspect + end + end + end + end + def process while req = recv_request - raise "not a request: #{req.inspect}" unless req['type'] == 'request' - args = req.dig('arguments') + process_request(req) + end + ensure + send_event :terminated unless @sock.closed? + end - case req['command'] + def process_request req + raise "not a request: #{req.inspect}" unless req['type'] == 'request' + args = req.dig('arguments') - ## boot/configuration - when 'launch' - send_response req - UI_DAP.local_fs_map_set req.dig('arguments', 'localfs') || req.dig('arguments', 'localfsMap') - @nonstop = true + case req['command'] - when 'attach' - send_response req - UI_DAP.local_fs_map_set req.dig('arguments', 'localfs') || req.dig('arguments', 'localfsMap') + ## boot/configuration + when 'launch' + send_response req + # `launch` runs on debuggee on the same file system + UI_DAP.local_fs_map_set req.dig('arguments', 'localfs') || req.dig('arguments', 'localfsMap') || true + @nonstop = true - if req.dig('arguments', 'nonstop') == true - @nonstop = true - else - @nonstop = false - end + load_extensions req - when 'configurationDone' - send_response req + when 'attach' + send_response req + UI_DAP.local_fs_map_set req.dig('arguments', 'localfs') || req.dig('arguments', 'localfsMap') - if @nonstop - @q_msg << 'continue' - else - if SESSION.in_subsession? - send_event 'stopped', reason: 'pause', - threadId: 1, # maybe ... - allThreadsStopped: true - end - end + if req.dig('arguments', 'nonstop') == true + @nonstop = true + else + @nonstop = false + end - when 'setBreakpoints' - req_path = args.dig('source', 'path') - path = UI_DAP.local_to_remote_path(req_path) + load_extensions req - if path - SESSION.clear_line_breakpoints path + when 'configurationDone' + send_response req - bps = [] - args['breakpoints'].each{|bp| - line = bp['line'] - if cond = bp['condition'] - bps << SESSION.add_line_breakpoint(path, line, cond: cond) - else - bps << SESSION.add_line_breakpoint(path, line) - end - } - send_response req, breakpoints: (bps.map do |bp| {verified: true,} end) - else - send_response req, success: false, message: "#{req_path} is not available" + if @nonstop + @q_msg << 'continue' + else + if SESSION.in_subsession? + send_event 'stopped', reason: 'pause', + threadId: 1, # maybe ... + allThreadsStopped: true end + end - when 'setFunctionBreakpoints' - send_response req + when 'setBreakpoints' + req_path = args.dig('source', 'path') + path = UI_DAP.local_to_remote_path(req_path) + if path + SESSION.clear_line_breakpoints path + + bps = [] + args['breakpoints'].each{|bp| + line = bp['line'] + if cond = bp['condition'] + bps << SESSION.add_line_breakpoint(path, line, cond: cond) + else + bps << SESSION.add_line_breakpoint(path, line) + end + } + send_response req, breakpoints: (bps.map do |bp| {verified: true,} end) + else + send_response req, breakpoints: (args['breakpoints'].map do |bp| {verified: false, message: "#{req_path} could not be located; specify source location in launch.json with \"localfsMap\" or \"localfs\""} end) + end - when 'setExceptionBreakpoints' - process_filter = ->(filter_id, cond = nil) { - bp = - case filter_id - when 'any' - SESSION.add_catch_breakpoint 'Exception', cond: cond - when 'RuntimeError' - SESSION.add_catch_breakpoint 'RuntimeError', cond: cond - else - nil - end - { - verified: !bp.nil?, - message: bp.inspect, - } + when 'setFunctionBreakpoints' + send_response req + + when 'setExceptionBreakpoints' + process_filter = ->(filter_id, cond = nil) { + bp = + case filter_id + when 'any' + SESSION.add_catch_breakpoint 'Exception', cond: cond + when 'RuntimeError' + SESSION.add_catch_breakpoint 'RuntimeError', cond: cond + else + nil + end + { + verified: !bp.nil?, + message: bp.inspect, } + } - SESSION.clear_catch_breakpoints 'Exception', 'RuntimeError' + SESSION.clear_catch_breakpoints 'Exception', 'RuntimeError' - filters = args.fetch('filters').map {|filter_id| - process_filter.call(filter_id) - } - - filters += args.fetch('filterOptions', {}).map{|bp_info| - process_filter.call(bp_info['filterId'], bp_info['condition']) + filters = args.fetch('filters').map {|filter_id| + process_filter.call(filter_id) } - send_response req, breakpoints: filters + filters += args.fetch('filterOptions', {}).map{|bp_info| + process_filter.call(bp_info['filterId'], bp_info['condition']) + } - when 'disconnect' - terminate = args.fetch("terminateDebuggee", false) + send_response req, breakpoints: filters - SESSION.clear_all_breakpoints - send_response req + when 'disconnect' + terminate = args.fetch("terminateDebuggee", false) - if SESSION.in_subsession? - if terminate - @q_msg << 'kill!' - else - @q_msg << 'continue' - end - else - if terminate - @q_msg << 'kill!' - pause - end - end + SESSION.clear_all_breakpoints + send_response req - ## control - when 'continue' - @q_msg << 'c' - send_response req, allThreadsContinued: true - when 'next' - begin - @session.check_postmortem - @q_msg << 'n' - send_response req - rescue PostmortemError - send_response req, - success: false, message: 'postmortem mode', - result: "'Next' is not supported while postmortem mode" - end - when 'stepIn' - begin - @session.check_postmortem - @q_msg << 's' - send_response req - rescue PostmortemError - send_response req, - success: false, message: 'postmortem mode', - result: "'stepIn' is not supported while postmortem mode" + if SESSION.in_subsession? + if terminate + @q_msg << 'kill!' + else + @q_msg << 'continue' end - when 'stepOut' - begin - @session.check_postmortem - @q_msg << 'fin' - send_response req - rescue PostmortemError - send_response req, - success: false, message: 'postmortem mode', - result: "'stepOut' is not supported while postmortem mode" + else + if terminate + @q_msg << 'kill!' + pause end - when 'terminate' + end + + ## control + when 'continue' + @q_msg << 'c' + send_response req, allThreadsContinued: true + when 'next' + begin + @session.check_postmortem + @q_msg << 'n' send_response req - exit - when 'pause' + rescue PostmortemError + send_response req, + success: false, message: 'postmortem mode', + result: "'Next' is not supported while postmortem mode" + end + when 'stepIn' + begin + @session.check_postmortem + @q_msg << 's' send_response req - Process.kill(UI_ServerBase::TRAP_SIGNAL, Process.pid) - when 'reverseContinue' + rescue PostmortemError send_response req, - success: false, message: 'cancelled', - result: "Reverse Continue is not supported. Only \"Step back\" is supported." - when 'stepBack' - @q_msg << req + success: false, message: 'postmortem mode', + result: "'stepIn' is not supported while postmortem mode" + end + when 'stepOut' + begin + @session.check_postmortem + @q_msg << 'fin' + send_response req + rescue PostmortemError + send_response req, + success: false, message: 'postmortem mode', + result: "'stepOut' is not supported while postmortem mode" + end + when 'terminate' + send_response req + exit + when 'pause' + send_response req + Process.kill(UI_ServerBase::TRAP_SIGNAL, Process.pid) + when 'reverseContinue' + send_response req, + success: false, message: 'cancelled', + result: "Reverse Continue is not supported. Only \"Step back\" is supported." + when 'stepBack' + @q_msg << req - ## query - when 'threads' - send_response req, threads: SESSION.managed_thread_clients.map{|tc| - { id: tc.id, - name: tc.name, - } + ## query + when 'threads' + send_response req, threads: SESSION.managed_thread_clients.map{|tc| + { id: tc.id, + name: tc.name, } + } + + when 'evaluate' + expr = req.dig('arguments', 'expression') + if /\A\s*,(.+)\z/ =~ expr + dbg_expr = $1.strip + dbg_expr.split(';;') { |cmd| @q_msg << cmd } - when 'stackTrace', - 'scopes', - 'variables', - 'evaluate', - 'source', - 'completions' + send_response req, + result: "(rdbg:command) #{dbg_expr}", + variablesReference: 0 + else @q_msg << req + end + when 'stackTrace', + 'scopes', + 'variables', + 'source', + 'completions' + @q_msg << req + else + if respond_to? mid = "custom_dap_request_#{req['command']}" + __send__ mid, req else raise "Unknown request: #{req.inspect}" end end - ensure - send_event :terminated unless @sock.closed? end ## called by the SESSION thread @@ -447,9 +501,13 @@ def respond req, res send_response(req, **res) end - def puts result + def puts result = "" # STDERR.puts "puts: #{result}" - # send_event 'output', category: 'stderr', output: "PUTS!!: " + result.to_s + send_event 'output', category: 'console', output: "#{result&.chomp}\n" + end + + def ignore_output_on_suspend? + true end def event type, *args @@ -494,6 +552,8 @@ def event type, *args end class Session + include GlobalVariablesHelper + def find_waiting_tc id @th_clients.each{|th, tc| return tc if tc.id == id && tc.waiting? @@ -518,7 +578,7 @@ def process_protocol_request req when 'stackTrace' tid = req.dig('arguments', 'threadId') - if tc = find_waiting_tc(tid) + if find_waiting_tc(tid) request_tc [:dap, :backtrace, req] else fail_response req @@ -527,7 +587,7 @@ def process_protocol_request req frame_id = req.dig('arguments', 'frameId') if @frame_map[frame_id] tid, fid = @frame_map[frame_id] - if tc = find_waiting_tc(tid) + if find_waiting_tc(tid) request_tc [:dap, :scopes, req, fid] else fail_response req @@ -540,8 +600,12 @@ def process_protocol_request req if ref = @var_map[varid] case ref[0] when :globals - vars = global_variables.map do |name| - gv = 'Not implemented yet...' + vars = safe_global_variables.sort.map do |name| + begin + gv = eval(name.to_s) + rescue Exception => e + gv = e.inspect + end { name: name, value: gv.inspect, @@ -559,7 +623,7 @@ def process_protocol_request req frame_id = ref[1] tid, fid = @frame_map[frame_id] - if tc = find_waiting_tc(tid) + if find_waiting_tc(tid) request_tc [:dap, :scope, req, fid] else fail_response req @@ -568,7 +632,7 @@ def process_protocol_request req when :variable tid, vid = ref[1], ref[2] - if tc = find_waiting_tc(tid) + if find_waiting_tc(tid) request_tc [:dap, :variable, req, vid] else fail_response req @@ -586,7 +650,9 @@ def process_protocol_request req if @frame_map[frame_id] tid, fid = @frame_map[frame_id] expr = req.dig('arguments', 'expression') - if tc = find_waiting_tc(tid) + + if find_waiting_tc(tid) + restart_all_threads request_tc [:dap, :evaluate, req, fid, expr, context] else fail_response req @@ -607,7 +673,7 @@ def process_protocol_request req frame_id = req.dig('arguments', 'frameId') tid, fid = @frame_map[frame_id] - if tc = find_waiting_tc(tid) + if find_waiting_tc(tid) text = req.dig('arguments', 'text') line = req.dig('arguments', 'line') if col = req.dig('arguments', 'column') @@ -618,11 +684,15 @@ def process_protocol_request req fail_response req end else - raise "Unknown DAP request: #{req.inspect}" + if respond_to? mid = "custom_dap_request_#{req['command']}" + __send__ mid, req + else + raise "Unknown request: #{req.inspect}" + end end end - def dap_event args + def process_protocol_result args # puts({dap_event: args}.inspect) type, req, result = args @@ -659,6 +729,7 @@ def dap_event args register_vars result[:variables], tid @ui.respond req, result when :evaluate + stop_all_threads message = result.delete :message if message @ui.respond req, success: false, message: message @@ -670,7 +741,11 @@ def dap_event args when :completions @ui.respond req, result else - raise "unsupported: #{args.inspect}" + if respond_to? mid = "custom_dap_request_event_#{type}" + __send__ mid, req, result + else + raise "unsupported: #{args.inspect}" + end end end @@ -698,9 +773,8 @@ def initialize str end class ThreadClient - MAX_LENGTH = 180 - + def value_inspect obj, short: true # TODO: max length should be configuarable? str = DEBUGGER__.safe_inspect obj, short: short, max_length: MAX_LENGTH @@ -712,6 +786,16 @@ def value_inspect obj, short: true end end + def dap_eval b, expr, _context, prompt: '(repl_eval)' + begin + tp_allow_reentry do + b.eval(expr.to_s, prompt) + end + rescue Exception => e + e + end + end + def process_dap args # pp tc: self, args: args type = args.shift @@ -726,7 +810,7 @@ def process_dap args next if i < start_frame path = frame.realpath || frame.path - next if skip_path?(path) + next if skip_path?(path) && !SESSION.stop_stepping?(path, frame.location.lineno) break if (levels -= 1) < 0 source_name = path ? File.basename(path) : frame.location.to_s @@ -749,7 +833,7 @@ def process_dap args } end - event! :dap_result, :backtrace, req, { + event! :protocol_result, :backtrace, req, { stackFrames: frames, totalFrames: @target_frames.size, } @@ -766,7 +850,7 @@ def process_dap args 0 end - event! :dap_result, :scopes, req, scopes: [{ + event! :protocol_result, :scopes, req, scopes: [{ name: 'Local variables', presentationHint: 'locals', # variablesReference: N, # filled by SESSION @@ -777,7 +861,7 @@ def process_dap args name: 'Global variables', presentationHint: 'globals', variablesReference: 1, # GLOBAL - namedVariables: global_variables.size, + namedVariables: safe_global_variables.size, indexedVariables: 0, expensive: false, }] @@ -788,7 +872,7 @@ def process_dap args variable(var, val) end - event! :dap_result, :scope, req, variables: vars, tid: self.id + event! :protocol_result, :scope, req, variables: vars, tid: self.id when :variable vid = args.shift obj = @var_map[vid] @@ -817,7 +901,8 @@ def process_dap args variable('#length', obj.length), variable('#encoding', obj.encoding), ] - vars << variable('#dump', NaiveString.new(obj)) if obj.length > MAX_LENGTH + printed_str = value_inspect(obj) + vars << variable('#dump', NaiveString.new(obj)) if printed_str.end_with?('...') when Class, Module vars << variable('%ancestors', obj.ancestors[1..]) when Range @@ -835,7 +920,7 @@ def process_dap args end end end - event! :dap_result, :variable, req, variables: (vars || []), tid: self.id + event! :protocol_result, :variable, req, variables: (vars || []), tid: self.id when :evaluate fid, expr, context = args @@ -849,12 +934,7 @@ def process_dap args case context when 'repl', 'watch' - begin - result = b.eval(expr.to_s, '(DEBUG CONSOLE)') - rescue Exception => e - result = e - end - + result = dap_eval b, expr, context, prompt: '(DEBUG CONSOLE)' when 'hover' case expr when /\A\@\S/ @@ -864,7 +944,7 @@ def process_dap args message = "Error: Not defined instance variable: #{expr.inspect}" end when /\A\$\S/ - global_variables.each{|gvar| + safe_global_variables.each{|gvar| if gvar.to_s == expr result = eval(gvar.to_s) break false @@ -895,7 +975,7 @@ def process_dap args result = 'Error: Can not evaluate on this frame' end - event! :dap_result, :evaluate, req, message: message, tid: self.id, **evaluate_result(result) + event! :protocol_result, :evaluate, req, message: message, tid: self.id, **evaluate_result(result) when :completions fid, text = args @@ -905,7 +985,7 @@ def process_dap args words = IRB::InputCompletor::retrieve_completion_data(word, bind: b).compact end - event! :dap_result, :completions, req, targets: (words || []).map{|phrase| + event! :protocol_result, :completions, req, targets: (words || []).map{|phrase| detail = nil if /\b([_a-zA-Z]\w*[!\?]?)\z/ =~ phrase @@ -928,7 +1008,11 @@ def process_dap args } else - raise "Unknown req: #{args.inspect}" + if respond_to? mid = "custom_dap_request_#{type}" + __send__ mid, req + else + raise "Unknown request: #{args.inspect}" + end end end @@ -937,7 +1021,11 @@ def search_const b, expr [Object, *b.eval('::Module.nesting')].reverse_each{|mod| if cs.all?{|c| if mod.const_defined?(c) - mod = mod.const_get(c) + begin + mod = mod.const_get(c) + rescue Exception + false + end else false end @@ -957,7 +1045,7 @@ def type_name obj klass = M_CLASS.bind_call(obj) begin - klass.name || klass.to_s + M_NAME.bind_call(klass) || klass.to_s rescue Exception => e "" end diff --git a/lib/debug/session.rb b/lib/debug/session.rb index b83479390..99c78af1d 100644 --- a/lib/debug/session.rb +++ b/lib/debug/session.rb @@ -82,7 +82,7 @@ def last_line def first_line self.to_a[4][:code_location][0] end unless method_defined?(:first_line) -end +end if defined?(RubyVM::InstructionSequence) module DEBUGGER__ PresetCommands = Struct.new(:commands, :source, :auto_continue) @@ -128,15 +128,16 @@ def initialize @obj_map = {} # { object_id => ... } for CDP @tp_thread_begin = nil + @tp_thread_end = nil + @commands = {} @unsafe_context = false - has_keep_script_lines = RubyVM.respond_to? :keep_script_lines + @has_keep_script_lines = defined?(RubyVM.keep_script_lines) @tp_load_script = TracePoint.new(:script_compiled){|tp| - if !has_keep_script_lines || bps_pending_until_load? - ThreadClient.current.on_load tp.instruction_sequence, tp.eval_script - end + eval_script = tp.eval_script unless @has_keep_script_lines + ThreadClient.current.on_load tp.instruction_sequence, eval_script } @tp_load_script.enable @@ -150,10 +151,14 @@ def active? !@q_evt.closed? end - def stop_stepping? file, line, subsession_id + def remote? + @ui.remote? + end + + def stop_stepping? file, line, subsession_id = nil if @bps.has_key? [file, line] true - elsif @subsession_id != subsession_id + elsif subsession_id && @subsession_id != subsession_id true else false @@ -164,12 +169,17 @@ def activate ui = nil, on_fork: false @ui = ui if ui @tp_thread_begin&.disable + @tp_thread_end&.disable @tp_thread_begin = nil - + @tp_thread_end = nil @ui.activate self, on_fork: on_fork q = Queue.new + first_q = Queue.new @session_server = Thread.new do + # make sure `@session_server` is assigned + first_q.pop; first_q = nil + Thread.current.name = 'DEBUGGER__::SESSION@server' Thread.current.abort_on_exception = true @@ -187,12 +197,24 @@ def activate ui = nil, on_fork: false end @tp_thread_begin.enable + @tp_thread_end = TracePoint.new(:thread_end) do |tp| + @th_clients.delete(Thread.current) + end + @tp_thread_end.enable + # session start q << true session_server_main end + first_q << :ok q.pop + + # For activating irb:rdbg with startup config like `RUBY_DEBUG_IRB_CONSOLE=1` + # Because in that case the `Config#if_updated` callback would not be triggered + if CONFIG[:irb_console] && !CONFIG[:open] + activate_irb_integration + end end def deactivate @@ -200,6 +222,7 @@ def deactivate @thread_stopper.disable @tp_load_script.disable @tp_thread_begin.disable + @tp_thread_end.disable @bps.each_value{|bp| bp.disable} @th_clients.each_value{|thc| thc.close} @tracers.values.each{|t| t.disable} @@ -214,11 +237,13 @@ def reset_ui ui # activate new ui @tp_thread_begin.disable + @tp_thread_end.disable @ui.activate self if @ui.respond_to?(:reader_thread) && thc = get_thread_client(@ui.reader_thread) thc.mark_as_management end @tp_thread_begin.enable + @tp_thread_end.enable end def pop_event @@ -237,6 +262,15 @@ def request_tc(req) @tc << req end + def request_tc_with_restarted_threads(req) + restart_all_threads + request_tc(req) + end + + def request_eval type, src + request_tc_with_restarted_threads [:eval, type, src] + end + def process_event evt # variable `@internal_info` is only used for test tc, output, ev, @internal_info, *ev_args = evt @@ -274,7 +308,7 @@ def process_event evt when :suspend enter_subsession if ev_args.first != :replay - output.each{|str| @ui.puts str} + output.each{|str| @ui.puts str} unless @ui.ignore_output_on_suspend? case ev_args.first when :breakpoint @@ -295,7 +329,7 @@ def process_event evt if @displays.empty? wait_command_loop else - request_tc [:eval, :display, @displays] + request_eval :display, @displays end when :result raise "[BUG] not in subsession" if @subsession_stack.empty? @@ -310,6 +344,7 @@ def process_event evt end end + stop_all_threads when :method_breakpoint, :watch_breakpoint bp = ev_args[1] if bp @@ -323,17 +358,15 @@ def process_event evt obj_inspect = ev_args[2] opt = ev_args[3] add_tracer ObjectTracer.new(@ui, obj_id, obj_inspect, **opt) + stop_all_threads else - # ignore + stop_all_threads end wait_command_loop - when :dap_result - dap_event ev_args # server.rb - wait_command_loop - when :cdp_result - cdp_event ev_args + when :protocol_result + process_protocol_result ev_args wait_command_loop end end @@ -475,9 +508,9 @@ def register_default_command # * `u[ntil]` # * Similar to `next` command, but only stop later lines or the end of the current frame. # * Similar to gdb's `advance` command. - # * `u[ntil] <[file:]line> + # * `u[ntil] <[file:]line>` # * Run til the program reaches given location or the end of the current frame. - # * `u[ntil] + # * `u[ntil] ` # * Run til the program invokes a method ``. `` can be a regexp with `/name/`. register_command 'u', 'until', repeat: true, @@ -487,9 +520,9 @@ def register_default_command step_command :until, arg end - # * `c[ontinue]` + # * `c` or `cont` or `continue` # * Resume the program. - register_command 'c', 'continue', + register_command 'c', 'cont', 'continue', repeat: true, cancel_auto_continue: true do |arg| leave_subsession :continue @@ -669,15 +702,15 @@ def register_default_command register_command 'bt', 'backtrace', unsafe: false do |arg| case arg when /\A(\d+)\z/ - request_tc [:show, :backtrace, arg.to_i, nil] + request_tc_with_restarted_threads [:show, :backtrace, arg.to_i, nil] when /\A\/(.*)\/\z/ pattern = $1 - request_tc [:show, :backtrace, nil, Regexp.compile(pattern)] + request_tc_with_restarted_threads [:show, :backtrace, nil, Regexp.compile(pattern)] when /\A(\d+)\s+\/(.*)\/\z/ max, pattern = $1, $2 - request_tc [:show, :backtrace, max.to_i, Regexp.compile(pattern)] + request_tc_with_restarted_threads [:show, :backtrace, max.to_i, Regexp.compile(pattern)] else - request_tc [:show, :backtrace, nil, nil] + request_tc_with_restarted_threads [:show, :backtrace, nil, nil] end end @@ -731,21 +764,31 @@ def register_default_command request_tc [:show, :edit, arg] end + info_subcommands = nil + info_subcommands_abbrev = nil + # * `i[nfo]` - # * Show information about current frame (local/instance variables and defined constants). - # * `i[nfo] l[ocal[s]]` + # * Show information about current frame (local/instance variables and defined constants). + # * `i[nfo]` + # * `info` has the following sub-commands. + # * Sub-commands can be specified with few letters which is unambiguous, like `l` for 'locals'. + # * `i[nfo] l or locals or local_variables` # * Show information about the current frame (local variables) - # * It includes `self` as `%self` and a return value as `%return`. - # * `i[nfo] i[var[s]]` or `i[nfo] instance` + # * It includes `self` as `%self` and a return value as `_return`. + # * `i[nfo] i or ivars or instance_variables` # * Show information about instance variables about `self`. - # * `i[nfo] c[onst[s]]` or `i[nfo] constant[s]` + # * `info ivars ` shows the instance variables of the result of ``. + # * `i[nfo] c or consts or constants` # * Show information about accessible constants except toplevel constants. - # * `i[nfo] g[lobal[s]]` + # * `info consts ` shows the constants of a class/module of the result of `` + # * `i[nfo] g or globals or global_variables` # * Show information about global variables + # * `i[nfo] th or threads` + # * Show all threads (same as `th[read]`). + # * `i[nfo] b or breakpoints or w or watchpoints` + # * Show all breakpoints and watchpoints. # * `i[nfo] ... /regexp/` # * Filter the output with `/regexp/`. - # * `i[nfo] th[read[s]]` - # * Show all threads (same as `th[read]`). register_command 'i', 'info', unsafe: false do |arg| if /\/(.+)\/\z/ =~ arg pat = Regexp.compile($1) @@ -754,20 +797,51 @@ def register_default_command sub = arg end + if /\A(.+?)\b(.+)/ =~ sub + sub = $1 + opt = $2.strip + opt = nil if opt.empty? + end + + if sub && !info_subcommands + info_subcommands = { + locals: %w[ locals local_variables ], + ivars: %w[ ivars instance_variables ], + consts: %w[ consts constants ], + globals:%w[ globals global_variables ], + threads:%w[ threads ], + breaks: %w[ breakpoints ], + watchs: %w[ watchpoints ], + } + + require_relative 'abbrev_command' + info_subcommands_abbrev = AbbrevCommand.new(info_subcommands) + end + + if sub + sub = info_subcommands_abbrev.search sub, :unknown do |candidates| + # note: unreached now + @ui.puts "Ambiguous command '#{sub}': #{candidates.join(' ')}" + end + end + case sub when nil - request_tc [:show, :default, pat] # something useful - when 'l', /^locals?/ - request_tc [:show, :locals, pat] - when 'i', /^ivars?/i, /^instance[_ ]variables?/i - request_tc [:show, :ivars, pat] - when 'c', /^consts?/i, /^constants?/i - request_tc [:show, :consts, pat] - when 'g', /^globals?/i, /^global[_ ]variables?/i - request_tc [:show, :globals, pat] - when 'th', /threads?/ + request_tc_with_restarted_threads [:show, :default, pat] # something useful + when :locals + request_tc_with_restarted_threads [:show, :locals, pat] + when :ivars + request_tc_with_restarted_threads [:show, :ivars, pat, opt] + when :consts + request_tc_with_restarted_threads [:show, :consts, pat, opt] + when :globals + request_tc_with_restarted_threads [:show, :globals, pat] + when :threads thread_list :retry + when :breaks, :watchs + show_bps + :retry else @ui.puts "unrecognized argument for info command: #{arg}" show_help 'info' @@ -781,7 +855,7 @@ def register_default_command # * Show you available methods and instance variables of the given object. # * If the object is a class/module, it also lists its constants. register_command 'outline', 'o', 'ls', unsafe: false do |arg| - request_tc [:show, :outline, arg] + request_tc_with_restarted_threads [:show, :outline, arg] end # * `display` @@ -791,9 +865,9 @@ def register_default_command register_command 'display', postmortem: false do |arg| if arg && !arg.empty? @displays << arg - request_tc [:eval, :try_display, @displays] + request_eval :try_display, @displays else - request_tc [:eval, :display, @displays] + request_eval :display, @displays end end @@ -807,7 +881,7 @@ def register_default_command if @displays[n = $1.to_i] @displays.delete_at n end - request_tc [:eval, :display, @displays] + request_eval :display, @displays when nil if ask "clear all?", 'N' @displays.clear @@ -843,13 +917,13 @@ def register_default_command # * `p ` # * Evaluate like `p ` on the current frame. register_command 'p' do |arg| - request_tc [:eval, :p, arg.to_s] + request_eval :p, arg.to_s end # * `pp ` # * Evaluate like `pp ` on the current frame. register_command 'pp' do |arg| - request_tc [:eval, :pp, arg.to_s] + request_eval :pp, arg.to_s end # * `eval ` @@ -857,21 +931,22 @@ def register_default_command register_command 'eval', 'call' do |arg| if arg == nil || arg.empty? show_help 'eval' - @ui.puts "\nTo evaluate the variable `#{cmd}`, use `pp #{cmd}` instead." :retry else - request_tc [:eval, :call, arg] + request_eval :call, arg end end # * `irb` - # * Invoke `irb` on the current frame. + # * Activate and switch to `irb:rdbg` console register_command 'irb' do |arg| if @ui.remote? - @ui.puts "not supported on the remote console." - :retry + @ui.puts "\nIRB is not supported on the remote console." + else + config_set :irb_console, true end - request_tc [:eval, :irb] + + :retry end ### Trace @@ -926,7 +1001,7 @@ def register_default_command :retry when /\Aobject\s+(.+)/ - request_tc [:trace, :object, $1.strip, {pattern: pattern, into: into}] + request_tc_with_restarted_threads [:trace, :object, $1.strip, {pattern: pattern, into: into}] when /\Aoff\s+(\d+)\z/ if t = @tracers.values[$1.to_i] @@ -1068,7 +1143,7 @@ def register_default_command def process_command line if line.empty? - if @repl_prev_line + if @repl_prev_line && !CONFIG[:no_repeat] line = @repl_prev_line else return :retry @@ -1091,7 +1166,7 @@ def process_command line @repl_prev_line = nil check_unsafe - request_tc [:eval, :pp, line] + request_eval :pp, line end rescue Interrupt @@ -1275,10 +1350,6 @@ def ask msg, default = 'Y' # breakpoint management - def bps_pending_until_load? - @bps.any?{|key, bp| bp.pending_until_load?} - end - def iterate_bps deleted_bps = [] i = 0 @@ -1454,7 +1525,7 @@ def clear_breakpoints(&condition) def clear_line_breakpoints path path = resolve_path(path) clear_breakpoints do |k, bp| - bp.is_a?(LineBreakpoint) && DEBUGGER__.compare_path(k.first, path) + bp.is_a?(LineBreakpoint) && bp.path_is?(path) end rescue Errno::ENOENT # just ignore @@ -1478,7 +1549,7 @@ def add_iseq_breakpoint iseq, **kw # tracers def add_tracer tracer - if @tracers.has_key? tracer.key + if @tracers[tracer.key]&.enabled? tracer.disable @ui.puts "Duplicated tracer: #{tracer}" else @@ -1607,6 +1678,14 @@ def get_thread_client th = Thread.current private def thread_stopper TracePoint.new(:line) do + # When leave_subsession pops the subsession stack and sets @tc = nil, + # there is a window before the TracePoint is disabled where this block + # can still fire on other threads. Without this guard, the main thread + # (back in IRB's eval loop) would be paused by on_pause, but the + # session server is already waiting on @q_evt.pop -- causing a mutual + # deadlock ("No live threads left. Deadlock?"). + next unless in_subsession? + # run on each thread tc = ThreadClient.current next if tc.management? @@ -1678,25 +1757,30 @@ def on_load iseq, src file_path, reloaded = @sr.add(iseq, src) @ui.event :load, file_path, reloaded - pending_line_breakpoints = @bps.find_all do |key, bp| - LineBreakpoint === bp && !bp.iseq - end + # check breakpoints + if file_path + @bps.find_all do |_key, bp| + LineBreakpoint === bp && bp.path_is?(file_path) && (iseq.first_lineno..iseq.last_line).cover?(bp.line) + end.each do |_key, bp| + if !bp.iseq + bp.try_activate iseq + elsif reloaded + @bps.delete bp.key # to allow duplicate - pending_line_breakpoints.each do |_key, bp| - if DEBUGGER__.compare_path(bp.path, (iseq.absolute_path || iseq.path)) - bp.try_activate iseq - end - end + # When we delete a breakpoint from the @bps hash, we also need to deactivate it or else its tracepoint event + # will continue to be enabled and we'll suspend on ghost breakpoints + bp.delete - if reloaded - @bps.find_all do |key, bp| - LineBreakpoint === bp && DEBUGGER__.compare_path(bp.path, file_path) - end.each do |_key, bp| - @bps.delete bp.key # to allow duplicate - if nbp = LineBreakpoint.copy(bp, iseq) + nbp = LineBreakpoint.copy(bp, iseq) add_bp nbp end end + else # !file_path => file_path is not existing + @bps.find_all do |_key, bp| + LineBreakpoint === bp && !bp.iseq && DEBUGGER__.compare_path(bp.path, (iseq.absolute_path || iseq.path)) + end.each do |_key, bp| + bp.try_activate iseq + end end end @@ -1801,6 +1885,12 @@ def check_unsafe end end + def activate_irb_integration + require_relative "irb_integration" + thc = get_thread_client(@session_server) + thc.activate_irb_integration + end + def enter_postmortem_session exc return unless exc.instance_variable_defined? :@__debugger_postmortem_frames @@ -1880,6 +1970,17 @@ def postmortem=(is_enable) end end + def set_no_sigint_hook old, new + return unless old != new + return unless @ui.respond_to? :activate_sigint + + if old # no -> yes + @ui.activate_sigint + else + @ui.deactivate_sigint + end + end + def save_int_trap cmd prev, @intercepted_sigint_cmd = @intercepted_sigint_cmd, cmd prev @@ -1923,6 +2024,13 @@ def before_fork need_lock = true def after_fork_parent @ui.after_fork_parent end + + # experimental API + def extend_feature session: nil, thread_client: nil, ui: nil + Session.include session if session + ThreadClient.include thread_client if thread_client + @ui.extend ui if ui + end end class ProcessGroup @@ -2069,6 +2177,10 @@ def event type, *args end end + def ignore_output_on_suspend? + false + end + def flush end end @@ -2093,6 +2205,7 @@ def self.require_location case loc.absolute_path when dir_prefix when %r{rubygems/core_ext/kernel_require\.rb} + when %r{bundled_gems\.rb} else return loc if loc.absolute_path end @@ -2195,11 +2308,20 @@ def skip? end def self.load_rc - [[File.expand_path('~/.rdbgrc'), true], - [File.expand_path('~/.rdbgrc.rb'), true], - # ['./.rdbgrc', true], # disable because of security concern - [CONFIG[:init_script], false], - ].each{|(path, rc)| + rc_file_paths = [ + [File.expand_path('~/.rdbgrc'), true], + [File.expand_path('~/.rdbgrc.rb'), true], + # ['./.rdbgrc', true], # disable because of security concern + ] + + if (xdg_home = ENV["XDG_CONFIG_HOME"]) + rc_file_paths << [File.expand_path(File.join(xdg_home, "rdbg", "config")), true] + rc_file_paths << [File.expand_path(File.join(xdg_home, "rdbg", "config.rb")), true] + end + + rc_file_paths << [CONFIG[:init_script], false] + + rc_file_paths.each{|(path, rc)| next unless path next if rc && CONFIG[:no_rc] # ignore rc @@ -2293,6 +2415,7 @@ def self.debug(&b) def self.log level, msg if check_loglevel level @logfile = STDERR unless defined? @logfile + return if @logfile.closed? if defined? SESSION pi = SESSION.process_info @@ -2375,8 +2498,24 @@ def fork(&given_block) end end - private def __fork_setup_for_debugger - fork_mode = CONFIG[:fork_mode] + module DaemonInterceptor + def daemon(*args) + return super unless defined?(SESSION) && SESSION.active? + + _, child_hook = __fork_setup_for_debugger(:child) + + unless SESSION.remote? + DEBUGGER__.warn "Can't debug the code after Process.daemon locally. Use the remote debugging feature." + end + + super.tap do + child_hook.call + end + end + end + + private def __fork_setup_for_debugger fork_mode = nil + fork_mode ||= CONFIG[:fork_mode] if fork_mode == :both && CONFIG[:parent_on_fork] fork_mode = :parent @@ -2426,7 +2565,17 @@ def fork(&given_block) module TrapInterceptor def trap sig, *command, &command_proc - case sig&.to_sym + sym = + case sig + when String + sig.to_sym + when Integer + Signal.signame(sig)&.to_sym + else + sig + end + + case sym when :INT, :SIGINT if defined?(SESSION) && SESSION.active? && SESSION.intercept_trap_sigint? return SESSION.save_int_trap(command.empty? ? command_proc : command.first) @@ -2441,6 +2590,7 @@ def trap sig, *command, &command_proc module ::Process class << self prepend ForkInterceptor + prepend DaemonInterceptor end end @@ -2476,6 +2626,7 @@ class << self module ::Process class << self prepend ForkInterceptor + prepend DaemonInterceptor end end end @@ -2492,10 +2643,17 @@ def debugger pre: nil, do: nil, up_level: 0 return if !defined?(::DEBUGGER__::SESSION) || !::DEBUGGER__::SESSION.active? if pre || (do_expr = binding.local_variable_get(:do)) - cmds = ['binding.break', pre, do_expr] + cmds = ['#debugger', pre, do_expr] end - loc = caller_locations(up_level, 1).first; ::DEBUGGER__.add_line_breakpoint loc.path, loc.lineno + 1, oneshot: true, command: cmds + if ::DEBUGGER__::SESSION.in_subsession? + if cmds + commands = [*cmds[1], *cmds[2]].map{|c| c.split(';;').join("\n")} + ::DEBUGGER__::SESSION.add_preset_commands cmds[0], commands, kick: false, continue: false + end + else + loc = caller_locations(up_level, 1).first; ::DEBUGGER__.add_line_breakpoint loc.path, loc.lineno + 1, oneshot: true, command: cmds + end self end diff --git a/lib/debug/source_repository.rb b/lib/debug/source_repository.rb index 76142dd1e..52e43cf7d 100644 --- a/lib/debug/source_repository.rb +++ b/lib/debug/source_repository.rb @@ -6,7 +6,23 @@ module DEBUGGER__ class SourceRepository include Color - if RubyVM.respond_to? :keep_script_lines + def file_src iseq + if (path = (iseq.absolute_path || iseq.path)) && File.exist?(path) + File.readlines(path, chomp: true) + end + end + + def get iseq + return unless iseq + + if CONFIG[:show_evaledsrc] + orig_src(iseq) || file_src(iseq) + else + file_src(iseq) || orig_src(iseq) + end + end + + if defined?(RubyVM.keep_script_lines) # Ruby 3.1 and later RubyVM.keep_script_lines = true require 'objspace' @@ -18,7 +34,7 @@ def initialize end def add iseq, src - # do nothing + # only manage loaded file names if (path = (iseq.absolute_path || iseq.path)) && File.exist?(path) if @loaded_file_map.has_key? path return path, true # reloaded @@ -29,17 +45,13 @@ def add iseq, src end end - def get iseq - return unless iseq - - if lines = iseq.script_lines&.map(&:chomp) - lines + def orig_src iseq + lines = iseq.script_lines&.map(&:chomp) + line = iseq.first_line + if line > 1 + [*([''] * (line - 1)), *lines] else - if (path = (iseq.absolute_path || iseq.path)) && File.exist?(path) - File.readlines(path, chomp: true) - else - nil - end + lines end end @@ -63,15 +75,22 @@ def initialize end def add iseq, src - if (path = (iseq.absolute_path || iseq.path)) && File.exist?(path) + path = (iseq.absolute_path || iseq.path) + + if path && File.exist?(path) reloaded = @files.has_key? path - add_path path - return path, reloaded - elsif src + + if src + add_iseq iseq, src + return path, reloaded + else + add_path path + return path, reloaded + end + else add_iseq iseq, src + nil end - - nil end private def all_iseq iseq, rs = [] @@ -87,7 +106,8 @@ def add iseq, src if line > 1 src = ("\n" * (line - 1)) + src end - si = SrcInfo.new(src.lines) + + si = SrcInfo.new(src.each_line.map{|l| l.chomp}) all_iseq(iseq).each{|e| e.instance_variable_set(:@debugger_si, si) e.freeze @@ -102,7 +122,7 @@ def add iseq, src private def get_si iseq return unless iseq - + if iseq.instance_variable_defined?(:@debugger_si) iseq.instance_variable_get(:@debugger_si) elsif @files.has_key?(path = (iseq.absolute_path || iseq.path)) @@ -112,7 +132,7 @@ def add iseq, src end end - def get iseq + def orig_src iseq if si = get_si(iseq) si.src end diff --git a/lib/debug/start.rb b/lib/debug/start.rb index ce5ebf548..6cdfb608c 100644 --- a/lib/debug/start.rb +++ b/lib/debug/start.rb @@ -2,4 +2,4 @@ require_relative 'session' return unless defined?(DEBUGGER__) -DEBUGGER__.start +DEBUGGER__.start no_sigint_hook: false diff --git a/lib/debug/thread_client.rb b/lib/debug/thread_client.rb index 1379352f2..0a92fe356 100644 --- a/lib/debug/thread_client.rb +++ b/lib/debug/thread_client.rb @@ -5,6 +5,10 @@ require_relative 'color' +class ::Thread + attr_accessor :debug_thread_client +end + module DEBUGGER__ M_INSTANCE_VARIABLES = method(:instance_variables).unbind M_INSTANCE_VARIABLE_GET = method(:instance_variable_get).unbind @@ -14,6 +18,7 @@ module DEBUGGER__ M_RESPOND_TO_P = method(:respond_to?).unbind M_METHOD = method(:method).unbind M_OBJECT_ID = method(:object_id).unbind + M_NAME = method(:name).unbind module SkipPathHelper def skip_path?(path) @@ -29,7 +34,7 @@ def skip_config_skip_path?(path) end def skip_internal_path?(path) - path.start_with?(__dir__) || path.start_with?('') next unless File.exist?(tp.path) if CONFIG[:skip_nosrc] + next if skip_internal_path?(tp.path) loc = caller_locations(1, 1).first next if skip_location?(loc) next if iter && (iter -= 1) > 0 @@ -361,6 +370,7 @@ def step_tp iter, events = [:line, :b_return, :return] next if tp.path.start_with?(__dir__) next if tp.path.start_with?('') next unless File.exist?(tp.path) if CONFIG[:skip_nosrc] + next if skip_internal_path?(tp.path) loc = caller_locations(1, 1).first next if skip_location?(loc) next if iter && (iter -= 1) > 0 @@ -427,7 +437,7 @@ def frame_eval_core src, b, binding_location: false def frame_eval src, re_raise: false, binding_location: false @success_last_eval = false - b = current_frame.eval_binding + b = current_frame&.eval_binding || TOPLEVEL_BINDING special_local_variables current_frame do |name, var| b.local_variable_set(name, var) if /\%/ !~ name @@ -460,10 +470,14 @@ def get_src(frame, if file_lines = frame.file_lines frame_line = frame.location.lineno - 1 - lines = file_lines.map.with_index do |e, i| - cur = i == frame_line ? '=>' : ' ' - line = colorize_dim('%4d|' % (i+1)) - "#{cur}#{line} #{e}" + if CONFIG[:no_lineno] + lines = file_lines + else + lines = file_lines.map.with_index do |e, i| + cur = i == frame_line ? '=>' : ' ' + line = colorize_dim('%4d|' % (i+1)) + "#{cur}#{line} #{e}" + end end unless start_line @@ -568,27 +582,60 @@ def show_locals pat end end - def show_ivars pat - if s = current_frame&.self - M_INSTANCE_VARIABLES.bind_call(s).sort.each{|iv| - value = M_INSTANCE_VARIABLE_GET.bind_call(s, iv) + def show_ivars pat, expr = nil + if expr && !expr.empty? + _self = frame_eval(expr); + elsif _self = current_frame&.self + else + _self = nil + end + + if _self + M_INSTANCE_VARIABLES.bind_call(_self).sort.each{|iv| + value = M_INSTANCE_VARIABLE_GET.bind_call(_self, iv) puts_variable_info iv, value, pat } end end - def show_consts pat, only_self: false - if s = current_frame&.self + def iter_consts c, names = {} + c.constants(false).sort.each{|name| + next if names.has_key? name + names[name] = nil + begin + value = c.const_get(name) + rescue Exception => e + value = e + end + yield name, value + } + end + + def get_consts expr = nil, only_self: false, &block + if expr && !expr.empty? + begin + _self = frame_eval(expr, re_raise: true) + rescue Exception + # ignore + else + if M_KIND_OF_P.bind_call(_self, Module) + iter_consts _self, &block + return + else + puts "#{_self.inspect} (by #{expr}) is not a Module." + end + end + elsif _self = current_frame&.self cs = {} - if M_KIND_OF_P.bind_call(s, Module) - cs[s] = :self + if M_KIND_OF_P.bind_call(_self, Module) + cs[_self] = :self else - s = M_CLASS.bind_call(s) - cs[s] = :self unless only_self + _self = M_CLASS.bind_call(_self) + cs[_self] = :self unless only_self end unless only_self - s.ancestors.each{|c| break if c == Object; cs[c] = :ancestors} + _self.ancestors.each{|c| break if c == Object; cs[c] = :ancestors} if b = current_frame&.binding b.eval('::Module.nesting').each{|c| cs[c] = :nesting unless cs.has_key? c} end @@ -597,19 +644,19 @@ def show_consts pat, only_self: false names = {} cs.each{|c, _| - c.constants(false).sort.each{|name| - next if names.has_key? name - names[name] = nil - value = c.const_get(name) - puts_variable_info name, value, pat - } + iter_consts c, names, &block } end end - SKIP_GLOBAL_LIST = %i[$= $KCODE $-K $SAFE].freeze + def show_consts pat, expr = nil, only_self: false + get_consts expr, only_self: only_self do |name, value| + puts_variable_info name, value, pat + end + end + def show_globals pat - global_variables.sort.each{|name| + safe_global_variables.sort.each{|name| next if SKIP_GLOBAL_LIST.include? name value = eval(name.to_s) @@ -781,7 +828,7 @@ def make_breakpoint args case args.first when :method klass_name, op, method_name, cond, cmd, path = args[1..] - bp = MethodBreakpoint.new(current_frame.eval_binding, klass_name, op, method_name, cond: cond, command: cmd, path: path) + bp = MethodBreakpoint.new(current_frame&.eval_binding || TOPLEVEL_BINDING, klass_name, op, method_name, cond: cond, command: cmd, path: path) begin bp.enable rescue NameError => e @@ -816,8 +863,18 @@ def make_breakpoint args class SuspendReplay < Exception end + if ::Fiber.respond_to?(:blocking) + private def fiber_blocking + ::Fiber.blocking{yield} + end + else + private def fiber_blocking + yield + end + end + def wait_next_action - wait_next_action_ + fiber_blocking{wait_next_action_} rescue SuspendReplay replay_suspend end @@ -870,6 +927,7 @@ def wait_next_action_ frame = @target_frames.first path = frame.location.absolute_path || "!eval:#{frame.path}" line = frame.location.lineno + label = frame.location.base_label if frame.iseq frame.iseq.traceable_lines_norec(lines = {}) @@ -881,23 +939,32 @@ def wait_next_action_ depth = @target_frames.first.frame_depth - step_tp iter do + step_tp iter do |tp| loc = caller_locations(2, 1).first loc_path = loc.absolute_path || "!eval:#{loc.path}" + loc_label = loc.base_label + loc_depth = DEBUGGER__.frame_depth - 3 - # same stack depth - (DEBUGGER__.frame_depth - 3 <= depth) || - - # different frame - (next_line && loc_path == path && - (loc_lineno = loc.lineno) > line && - loc_lineno <= next_line) + case + when loc_depth == depth && loc_label == label + true + when loc_depth < depth + # lower stack depth + true + when (next_line && + loc_path == path && + (loc_lineno = loc.lineno) > line && + loc_lineno <= next_line) + # different frame (maybe block) but the line is before next_line + true + end end break when :finish finish_frames = (iter || 1) - 1 - goal_depth = @target_frames.first.frame_depth - finish_frames + frame = @target_frames.first + goal_depth = frame.frame_depth - finish_frames - (frame.has_return_value ? 1 : 0) step_tp nil, [:return, :b_return] do DEBUGGER__.frame_depth - 3 <= goal_depth ? true : false @@ -907,22 +974,25 @@ def wait_next_action_ when :until location = iter&.strip frame = @target_frames.first - depth = frame.frame_depth + depth = frame.frame_depth - (frame.has_return_value ? 1 : 0) target_location_label = frame.location.base_label case location when nil, /\A(?:(.+):)?(\d+)\z/ - file = $1 + no_loc = !location + file = $1 || frame.location.path line = ($2 || frame.location.lineno + 1).to_i step_tp nil, [:line, :return] do |tp| if tp.event == :line - next true if file && tp.path.end_with?(file) - next true if tp.lineno >= line + next false if no_loc && depth < DEBUGGER__.frame_depth - 3 + next false unless tp.path.end_with?(file) + next false unless tp.lineno >= line + true else - next true if depth >= DEBUGGER__.frame_depth - 3 && - caller_locations(2, 1).first.label == target_location_label - # TODO: imcomplete condition + true if depth >= DEBUGGER__.frame_depth - 3 && + caller_locations(2, 1).first.base_label == target_location_label + # TODO: imcomplete condition end end else @@ -934,11 +1004,11 @@ def wait_next_action_ step_tp nil, [:call, :c_call, :return] do |tp| case tp.event when :call, :c_call - next true if pat === tp.callee_id.to_s + true if pat === tp.callee_id.to_s else # :return, :b_return - next true if depth >= DEBUGGER__.frame_depth - 3 && - caller_locations(2, 1).first.label == target_location_label - # TODO: imcomplete condition + true if depth >= DEBUGGER__.frame_depth - 3 && + caller_locations(2, 1).first.base_label == target_location_label + # TODO: imcomplete condition end end end @@ -988,14 +1058,6 @@ def wait_next_action_ end when :call result = frame_eval(eval_src) - when :irb - require 'irb' # prelude's binding.irb doesn't have show_code option - begin - result = frame_eval('binding.irb(show_code: false)', binding_location: true) - ensure - # workaround: https://github.com/ruby/debug/issues/308 - Reline.prompt_proc = nil if defined? Reline - end when :display, :try_display failed_results = [] eval_src.each_with_index{|src, i| @@ -1019,13 +1081,13 @@ def wait_next_action_ when :up if @current_frame_index + 1 < @target_frames.size @current_frame_index += 1 - show_src max_lines: 1 + show_src max_lines: CONFIG[:show_src_lines_frame] show_frame(@current_frame_index) end when :down if @current_frame_index > 0 @current_frame_index -= 1 - show_src max_lines: 1 + show_src max_lines: CONFIG[:show_src_lines_frame] show_frame(@current_frame_index) end when :set @@ -1037,7 +1099,7 @@ def wait_next_action_ puts "out of frame index: #{index}" end end - show_src max_lines: 1 + show_src max_lines: CONFIG[:show_src_lines_frame] show_frame(@current_frame_index) else raise "unsupported frame operation: #{arg.inspect}" @@ -1075,11 +1137,13 @@ def wait_next_action_ when :ivars pat = args.shift - show_ivars pat + expr = args.shift + show_ivars pat, expr when :consts pat = args.shift - show_consts pat + expr = args.shift + show_consts pat, expr when :globals pat = args.shift @@ -1179,8 +1243,18 @@ def wait_next_action_ rescue SuspendReplay, SystemExit, Interrupt raise rescue Exception => e - pp ["DEBUGGER Exception: #{__FILE__}:#{__LINE__}", e, e.backtrace] + STDERR.puts e.cause.inspect + STDERR.puts e.inspect + Thread.list.each{|th| + STDERR.puts "@@@ #{th}" + th.backtrace.each{|b| + STDERR.puts " > #{b}" + } + } + p ["DEBUGGER Exception: #{__FILE__}:#{__LINE__}", e, e.backtrace] raise + ensure + @returning = false end def debug_event(ev, args) @@ -1236,13 +1310,17 @@ def initialize frame._local_variables = b.local_variables.map{|name| [name, b.local_variable_get(name)] }.to_h - frame._callee = b.eval('__callee__') + frame._callee = b.eval('::Kernel.__callee__') end } - @log << frames + append(frames) } end + def append frames + @log << frames + end + def enable unless @tp_recorder.enabled? @log.clear diff --git a/lib/debug/tracer.rb b/lib/debug/tracer.rb index 09da6dd97..49c6923c1 100644 --- a/lib/debug/tracer.rb +++ b/lib/debug/tracer.rb @@ -54,6 +54,10 @@ def disable @tracer.disable end + def enabled? + @tracer.enabled? + end + def description nil end @@ -85,11 +89,6 @@ def out tp, msg = nil, depth = caller.size - 1 end end - def puts msg - @output.puts msg - @output.flush - end - def minfo tp return "block{}" if tp.event == :b_call diff --git a/lib/debug/version.rb b/lib/debug/version.rb index a27451118..d5b3811a8 100644 --- a/lib/debug/version.rb +++ b/lib/debug/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module DEBUGGER__ - VERSION = "1.7.0dev" + VERSION = "1.11.1" end diff --git a/misc/README.md.erb b/misc/README.md.erb index 99195e138..9565a74da 100644 --- a/misc/README.md.erb +++ b/misc/README.md.erb @@ -2,9 +2,9 @@ # debug.rb -This library provides debugging functionality to Ruby (MRI) 2.6 and later. +This library provides debugging functionality to Ruby (MRI) 2.7 and later. -This debug.rb is replacement of traditional lib/debug.rb standard library which is implemented by `set_trace_func`. +This debug.rb is the replacement of traditional lib/debug.rb standard library, which is implemented by `set_trace_func`. New debug.rb has several advantages: * Fast: No performance penalty on non-stepping mode and non-breakpoints. @@ -13,41 +13,41 @@ New debug.rb has several advantages: * TCP/IP * Integration with rich debugger frontends - Frontend | [Console](https://github.com/ruby/debug#invoke-as-a-remote-debuggee) | [VSCode](https://github.com/ruby/debug#vscode-integration) | [Chrome DevTool](#chrome-devtool-integration) | - ---|---|---|---| - Connection | UDS, TCP/IP | UDS, TCP/IP | TCP/IP | - Requirement | No | [vscode-rdbg](https://marketplace.visualstudio.com/items?itemName=KoichiSasada.vscode-rdbg) | Chrome | + | Frontend | [Console](https://github.com/ruby/debug#invoke-as-a-remote-debuggee) | [VSCode](https://github.com/ruby/debug#vscode-integration) | [Chrome DevTool](#chrome-devtool-integration) | + | ----------- | -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | --------------------------------------------- | + | Connection | UDS, TCP/IP | UDS, TCP/IP | TCP/IP | + | Requirement | None | [vscode-rdbg](https://marketplace.visualstudio.com/items?itemName=KoichiSasada.vscode-rdbg) | Chrome | -* Extensible: application can introduce debugging support with several ways: +* Extensible: application can introduce debugging support in several ways: * By `rdbg` command * By loading libraries with `-r` command line option * By calling Ruby's method explicitly * Misc - * Support threads (almost done) and ractors (TODO). - * Support suspending and entering to the console debugging with `Ctrl-C` at most of timing. + * Support threads (almost done) and Ractors (TODO). + * Support suspending and entering the debug console with `Ctrl-C` at most of timing. * Show parameters on backtrace command. - * Support recording & reply debugging. + * Support recording and replay debugging. # Installation -``` +```console $ gem install debug ``` -or specify `-Ipath/to/debug/lib` in `RUBYOPT` or each ruby command-line option, especially for debug this gem development. +Alternatively, specify `-Ipath/to/debug/lib` in `RUBYOPT`, or as a Ruby command-line option +This is especially useful for debugging this gem during development. -If you use Bundler, write the following line to your Gemfile. +If using Bundler, add the following to your Gemfile: -``` +```ruby gem "debug", ">= 1.0.0" ``` -(The version constraint is important; `debug < 1.0.0` is an older, -abandoned gem that is completely different from this product.) +(The version constraint is important; `debug < 1.0.0` is an older, abandoned gem that is completely different from this product.) # HOW TO USE -To use a debugger, roughly you will do the following steps: +To use the debugger, you will do roughly the following steps: 1. Set breakpoints. 2. Run a program with the debugger. @@ -55,7 +55,7 @@ To use a debugger, roughly you will do the following steps: 4. Use debug commands. * [Evaluate Ruby expressions](#evaluate) (e.g. `p lvar` to see the local variable `lvar`). * [Query the program status](#information) (e.g. `info` to see information about the current frame). - * [Control program flow](#control-flow) (e.g. move to the another line with `step`, to the next line with `next`). + * [Control program flow](#control-flow) (e.g. move to another line with `step`, to the next line with `next`). * [Set another breakpoint](#breakpoint) (e.g. `catch Exception` to set a breakpoint that'll be triggered when `Exception` is raised). * [Activate tracing in your program](#trace) (e.g. `trace call` to trace method calls). * [Change the configuration](#configuration-1) (e.g. `config set no_color true` to disable coloring). @@ -63,22 +63,23 @@ To use a debugger, roughly you will do the following steps: ## Invoke with the debugger -There are several options for (1) and (2). Please choose your favorite way. +There are several ways to invoke the debugger, depending on your needs, preferences, and the environment. ### Modify source code with [`binding.break`](#bindingbreak-method) (similar to `binding.pry` or `binding.irb`) -If you can modify the source code, you can use the debugger by adding `require 'debug'` at the top of your program and putting [`binding.break`](#bindingbreak-method) method into lines where you want to stop as breakpoints like `binding.pry` and `binding.irb`. +If you can modify the source code, you can use the debugger by adding `require 'debug'` at the top of your program and putting [`binding.break`](#bindingbreak-method) method into lines where you want to stop as breakpoints. +This is similar to how `binding.pry` and `binding.irb` work. -You can also use its 2 aliases in the same way: +`binding.break` has two aliases which do the same thing: - `binding.b` - `debugger` After that, run the program as usual and you will enter the debug console at breakpoints you inserted. -The following example shows the demonstration of [`binding.break`](#bindingbreak-method). +The following is an example of the [`binding.break`](#bindingbreak-method) method. -```shell +```console $ cat target.rb # Sample program require 'debug' @@ -140,10 +141,11 @@ d => 4 ### Invoke the program from the debugger as a traditional debuggers -If you don't want to modify the source code, you can set breakpoints with a debug command `break` (`b` for short). -Using `rdbg` command (or `bundle exec rdbg`) to launch the program without any modifications, you can run the program with the debugger. +If you don't want to modify the source code, you can use the `rdbg` command (or `bundle exec rdbg`) to run the program with the debugger. +This is similar to how you'd launch a program with `ruby program.rb`. +Then you can set breakpoints with the debug command `break` (`b` for short). -```shell +```console $ cat target.rb # Sample program a = 1 b = 2 @@ -166,9 +168,11 @@ DEBUGGER: Session start (pid: 7656) (rdbg) ``` -`rdbg` command suspends the program at the beginning of the given script (`target.rb` in this case) and you can use debug commands. `(rdbg)` is prompt. Let's set breakpoints on line 3 and line 5 with `break` command (`b` for short). +The `rdbg` command suspends the program at the beginning of the given script (`target.rb` in this case) and you can use debug commands to control execution from there. +`(rdbg)` is the console prompt. +Let's set breakpoints on line 3 and line 5 with `break` command (`b` for short). -```shell +```console (rdbg) break 3 # set breakpoint at line 3 #0 BP - Line /mnt/c/ko1/src/rb/ruby-debug/target.rb:3 (line) @@ -180,9 +184,10 @@ DEBUGGER: Session start (pid: 7656) #1 BP - Line /mnt/c/ko1/src/rb/ruby-debug/target.rb:5 (line) ``` -You can see that two breakpoints are registered. Let's continue the program by `continue` command. +You can see that two breakpoints are registered. +Let's continue the program by using the `continue` command. -```shell +```console (rdbg) continue [1, 7] in target.rb 1| a = 1 @@ -199,11 +204,11 @@ Stop by #0 BP - Line /mnt/c/ko1/src/rb/ruby-debug/target.rb:3 (line) (rdbg) ``` -You can see that we can stop at line 3. -Let's see the local variables with `info` command, and continue. -You can also confirm that the program will suspend at line 5 and you can use `info` command again. +You can see that we stopped at line 3. +Let's see the local variables with the `info` command, and continue execution with the `continue`. +The program will then suspend at line 5 and you can use the `info` command again. -```shell +```console (rdbg) info =>#0
at target.rb:3 %self => main @@ -237,25 +242,28 @@ d => 4 [1, 2, 3, 4] ``` -By the way, using `rdbg` command you can suspend your application with `C-c` (SIGINT) and enter the debug console. -It will help that if you want to know what the program is doing. +NOTE: When using `rdbg` you can suspend your application with `C-c` (SIGINT) and enter the debug console. +It will help if you want to know what the program is doing. ### Use `rdbg` with commands written in Ruby -If you want to run a command written in Ruby like like `rake`, `rails`, `bundle`, `rspec` and so on, you can use `rdbg -c` option. +If you want to run an executable written in Ruby like `rake`, `rails`, `bundle`, `rspec`, and so on, you can use `rdbg -c` option. -* Without `-c` option, `rdbg ` means that `` is Ruby script and invoke it like `ruby ` with the debugger. -* With `-c` option, `rdbg -c ` means that `` is command in `PATH` and simply invoke it with the debugger. +* Without the `-c` option, `rdbg ` means that `` is a Ruby script and it is invoked like `ruby ` with the debugger. +* With the `-c` option, `rdbg -c ` means that `` is an executable in `PATH` and simply invokes it with the debugger. Examples: + * `rdbg -c -- rails server` * `rdbg -c -- bundle exec ruby foo.rb` * `rdbg -c -- bundle exec rake test` -* `rdbg -c -- ruby target.rb` is same as `rdbg target.rb` +* `rdbg -c -- ruby target.rb` is the same as `rdbg target.rb` -NOTE: `--` is needed to separate the command line options for `rdbg` and invoking command. For example, `rdbg -c rake -T` is recognized like `rdbg -c -T -- rake`. It should be `rdbg -c -- rake -T`. +NOTE: `--` is needed to separate the command line options for `rdbg` from the executable being invoked, and its options. +For example, `rdbg -c rake -T` would be parsed as `rdbg -c -T -- rake`, which is incorrect. +It should be `rdbg -c -- rake -T`. -NOTE: If you want to use bundler (`bundle` command), you need to write `gem debug` line in your `Gemfile`. +NOTE: If you want to use Bundler (`bundle` executable), you need to add `gem 'debug'` to your `Gemfile`. ### Using VSCode @@ -263,53 +271,55 @@ Like other languages, you can use this debugger on the VSCode. 1. Install [VSCode rdbg Ruby Debugger - Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=KoichiSasada.vscode-rdbg) 2. Open `.rb` file (e.g. `target.rb`) -3. Register breakpoints with "Toggle breakpoint" in Run menu (or type F9 key) +3. Register breakpoints with "Toggle breakpoint" in the Run menu (or type F9 key) 4. Choose "Start debugging" in "Run" menu (or type F5 key) -5. You will see a dialog "Debug command line" and you can choose your favorite command line your want to run. -6. Chosen command line is invoked with `rdbg -c` and VSCode shows the details at breakpoints. +5. You will see a dialog "Debug command line" and you can choose your favorite command line you want to run. +6. Chosen command line is invoked with `rdbg -c`, and VSCode shows the details at breakpoints. -Please refer [Debugging in Visual Studio Code](https://code.visualstudio.com/docs/editor/debugging) for operations on VSCode. +Please refer to [Debugging in Visual Studio Code](https://code.visualstudio.com/docs/editor/debugging) for operations on VSCode. You can configure the extension in `.vscode/launch.json`. Please see the extension page for more details. ## Remote debugging -You can use this debugger as a remote debugger. For example, it will help the following situations: +You can use this debugger as a remote debugger. +For example, it will help in the following situations: -* Your application does not run on TTY and it is hard to use `binding.pry` or `binding.irb`. - * Your application is running on Docker container and there is no TTY. +* Your application does not run on TTY, and it is hard to use `binding.pry` or `binding.irb`. + * Your application is running on a Docker container, and there is no TTY. * Your application is running as a daemon. - * Your application uses pipe for STDIN or STDOUT. + * Your application uses pipe for `STDIN` or `STDOUT`. * Your application is running as a daemon and you want to query the running status (checking a backtrace and so on). -You can run your application as a remote debuggee and the remote debugger console can attach to the debuggee anytime. +You can run your application as a remote debuggee, and the remote debugger console can attach to the debuggee anytime. ### Invoke as a remote debuggee There are multiple ways to run your program as a debuggee: -Stop at program start | [`rdbg` option](https://github.com/ruby/debug#rdbg---open-or-rdbg--o-for-short) | [require](https://github.com/ruby/debug#require-debugopen-in-a-program) | [debugger API](https://github.com/ruby/debug#start-by-method) ----|---|---|---| -Yes | `rdbg --open` | `require "debug/open"` | `DEBUGGER__.open` -No | `rdbg --open --nonstop` | `require "debug/open_nonstop"` | `DEBUGGER__.open(nonstop: true)` +| Stop at program start | [`rdbg` option](https://github.com/ruby/debug#rdbg---open-or-rdbg--o-for-short) | [require](https://github.com/ruby/debug#require-debugopen-in-a-program) | [debugger API](https://github.com/ruby/debug#start-by-method) | +| --------------------- | ------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------- | +| Yes | `rdbg --open` | `require "debug/open"` | `DEBUGGER__.open` | +| No | `rdbg --open --nonstop` | `require "debug/open_nonstop"` | `DEBUGGER__.open(nonstop: true)` | #### `rdbg --open` (or `rdbg -O` for short) -You can run a script with `rdbg --open target.rb` command and run a `target.rb` as a debuggee program. It also opens the network port and suspends at the beginning of `target.rb`. +Launch a script with `rdbg --open target.rb` to run `target.rb` as a debuggee program. +It also opens the network port and suspends at the beginning of `target.rb`. -```shell -$ exe/rdbg --open target.rb +```console +$ rdbg --open target.rb DEBUGGER: Session start (pid: 7773) DEBUGGER: Debugger can attach via UNIX domain socket (/home/ko1/.ruby-debug-sock/ruby-debug-ko1-7773) DEBUGGER: wait for debugger connection... ``` -By default, `rdbg --open` uses UNIX domain socket and generates path name automatically (`/home/ko1/.ruby-debug-sock/ruby-debug-ko1-7773` in this case). +By default, `rdbg --open` uses UNIX domain socket and generates the path name automatically (`/home/ko1/.ruby-debug-sock/ruby-debug-ko1-7773` in this case). You can connect to the debuggee with `rdbg --attach` command (`rdbg -A` for short). -```shell +```console $ rdbg -A [1, 7] in target.rb => 1| a = 1 @@ -324,35 +334,41 @@ $ rdbg -A (rdbg:remote) ``` -If there is no other opening ports on the default directory, `rdbg --attach` command chooses the only one opening UNIX domain socket and connect to it. If there are more files, you need to specify the file. +If there are no other files in the default directory, `rdbg --attach` will automatically connect to the UNIX domain socket listed. +If there are multiple files, you need to specify which to use. -When `rdbg --attach` connects to the debuggee, you can use any debug commands (set breakpoints, continue the program and so on) like local debug console. When an debuggee program exits, the remote console will also terminate. +When `rdbg --attach` connects to the debuggee, you can use any debug commands (set breakpoints, continue the program, and so on) like the local debug console. +When a debuggee program exits, the remote console will also terminate. -NOTE: If you use `quit` command, only remote console exits and the debuggee program continues to run (and you can connect it again). If you want to exit the debuggee program, use `kill` command. +NOTE: If you use the `quit` command, only the remote console exits and the debuggee program continues to run (and you can connect it again). +If you want to exit the debuggee program, use `kill` command. -If you want to use TCP/IP for the remote debugging, you need to specify the port and host with `--port` like `rdbg --open --port 12345` and it binds to `localhost:12345`. +If you want to use TCP/IP for remote debugging, you need to specify the port and host with `--port` like `rdbg --open --port 12345` and it binds to `localhost:12345`. +You can add an optional `--port_range` to try multiple ports in a reliable way. +For example, `rdbg --open --port 12345 --port_range 10` will try to bind to 12345, 12346, 12347,… until it finds an available port. To connect to the debuggee, you need to specify the port. -```shell +```console $ rdbg --attach 12345 ``` If you want to choose the host to bind, you can use `--host` option. -Note that all messages communicated between the debugger and the debuggee are *NOT* encrypted so please use remote debugging carefully. +Messages communicated between the debugger and the debuggee are *NOT* encrypted so please use remote debugging carefully. #### `require 'debug/open'` in a program -If you can modify the program, you can open debugging port by adding `require 'debug/open'` line in the program. +If you can modify the program, you can open the debugging port by adding `require 'debug/open'` in the program. If you don't want to stop the program at the beginning, you can also use `require 'debug/open_nonstop'`. Using `debug/open_nonstop` is useful if you want to open a backdoor to the application. -However, it is also danger because it can become another vulnerability. +However, it is also dangerous because it can become another vulnerability. Please use it carefully. -By default, UNIX domain socket is used for the debugging port. To use TCP/IP, you can set the `RUBY_DEBUG_PORT` environment variable. +By default, UNIX domain socket is used for the debugging port. +To use TCP/IP, you can set the `RUBY_DEBUG_PORT` environment variable. -```shell +```console $ RUBY_DEBUG_PORT=12345 ruby target.rb ``` @@ -364,19 +380,17 @@ You can attach with external debugger frontend with VSCode and Chrome. $ rdbg --open=[frontend] target.rb ``` -will open a debug port and `[frontend]` can attach to the port. - -Also `open` command allows opening the debug port. +This will open a debug port and the `[frontend]` can attach to the port. #### VSCode integration ([vscode-rdbg v0.0.9](https://marketplace.visualstudio.com/items?itemName=KoichiSasada.vscode-rdbg) or later is required) -If you don't run a debuggee Ruby process on VSCode, you can attach with VSCode later with the following steps. +If you don't run a debuggee Ruby process on VSCode, you can attach it to VSCode later with the following steps. -`rdbg --open=vscode` opens the debug port and tries to invoke the VSCode (`code` command). +`rdbg --open=vscode` opens the debug port and tries to invoke the VSCode (`code` executable). -``` +```console $ rdbg --open=vscode target.rb DEBUGGER: Debugger can attach via UNIX domain socket (/tmp/ruby-debug-sock-1000/ruby-debug-ko1-27706) DEBUGGER: wait for debugger connection... @@ -384,11 +398,11 @@ Launching: code /tmp/ruby-debug-vscode-20211014-27706-gd7e85/ /tmp/ruby-debug-vs DEBUGGER: Connected. ``` -And it tries to invoke the new VSCode window and VSCode starts attaching to the debuggee Ruby program automatically. +It tries to invoke the new VSCode window and VSCode will attach to the debuggee Ruby program automatically. -You can also use `open vscode` command in REPL. +You can also use `open vscode` in a REPL. -``` +```console $ rdbg target.rb [1, 8] in target.rb 1| @@ -407,9 +421,9 @@ Launching: code /tmp/ruby-debug-vscode-20211014-28337-kg9dm/ /tmp/ruby-debug-vsc DEBUGGER: Connected. ``` -If the machine which runs the Ruby process doesn't have a `code` command, the following message will be shown: +If the machine which runs the Ruby process doesn't have a `code` executable on `$PATH`, the following message will be shown: -``` +```console (rdbg) open vscode DEBUGGER: wait for debugger connection... DEBUGGER: Debugger can attach via UNIX domain socket (/tmp/ruby-debug-sock-1000/ruby-debug-ko1-455) @@ -425,15 +439,13 @@ If your application is running on a SSH remote host, please try: ``` -and try to use proposed commands. - Note that you can attach with `rdbg --attach` and continue REPL debugging. #### Chrome DevTool integration -With `rdbg --open=chrome` command will show the following message. +Using `rdbg --open=chrome` will show the following message: -``` +```console $ rdbg target.rb --open=chrome DEBUGGER: Debugger can attach via TCP/IP (127.0.0.1:43633) DEBUGGER: With Chrome browser, type the following URL in the address-bar: @@ -443,20 +455,25 @@ DEBUGGER: With Chrome browser, type the following URL in the address-bar: DEBUGGER: wait for debugger connection... ``` -Type `devtools://devtools/bundled/inspector.html?v8only=true&panel=sources&ws=127.0.0.1:57231/b32a55cd-2eb5-4c5c-87d8-b3dfc59d80ef` in the address-bar on Chrome browser, and you can continue the debugging with chrome browser. +Type the following in the address bar on Chrome browser, and you can continue the debugging with chrome browser: + +```txt +devtools://devtools/bundled/inspector.html?v8only=true&panel=sources&ws=127.0.0.1:57231/b32a55cd-2eb5-4c5c-87d8-b3dfc59d80ef` +``` -Also `open chrome` command works like `open vscode`. +Similar to VSCode, you can use `open chrome` to open the debugger in Chrome. -For more information about how to use Chrome debugging, you might want to read [here](https://developer.chrome.com/docs/devtools/). +For more information about how to use Chrome debugging, [see the devtools docs](https://developer.chrome.com/docs/devtools/). ## Configuration You can configure the debugger's behavior with debug commands and environment variables. -When the debug session is started, initial scripts are loaded so you can put your favorite configurations in the initial scripts. +When the debug session is started, some [initialization scripts](#initial-scripts) (e.g., `~/.rdbgrc`) are loaded, allowing you to configure the debugger's behavior to your needs and preferences. ### Configuration list -You can configure debugger's behavior with environment variables and `config` command. Each configuration has environment variable and the name which can be specified by `config` command. +You can configure the debugger's behavior with environment variables and `config` command. +Each configuration has an environment variable and a name which can be specified by `config` command. ``` # configuration example @@ -473,21 +490,21 @@ There are other environment variables: * `NO_COLOR`: If the value is set, set `RUBY_DEBUG_NO_COLOR` ([NO_COLOR: disabling ANSI color output in various Unix commands](https://no-color.org/)). * `RUBY_DEBUG_ENABLE`: If the value is `0`, do not enable debug.gem feature. -* `RUBY_DEBUG_ADDED_RUBYOPT`: Remove this value from `RUBYOPT` at first. This feature helps loading debug.gem with `RUBYOPT='-r debug/...'` and you don't want to derive it to child processes. In this case you can set `RUBY_DEBUG_ADDED_RUBYOPT='-r debug/...'` (same value) and this string will be deleted from `RUBYOPT` at first. +* `RUBY_DEBUG_ADDED_RUBYOPT`: Remove this value from `RUBYOPT` at first. This feature helps loading debug.gem with `RUBYOPT='-r debug/...'`, and you don't want to derive it to child processes. In this case, you can set `RUBY_DEBUG_ADDED_RUBYOPT='-r debug/...'` (same value), and this string will be deleted from `RUBYOPT` at first. * `RUBY_DEBUG_EDITOR` or `EDITOR`: An editor used by `edit` debug command. * `RUBY_DEBUG_BB`: Define `Kernel#bb` method which is alias of `Kernel#debugger`. ### Initial scripts -If there is `~/.rdbgrc`, the file is loaded as an initial script (which contains debug commands) when the debug session is started. +If there is a `~/.rdbgrc` file it is loaded as an initialization script (which contains debug commands) when the debug session is started. * `RUBY_DEBUG_INIT_SCRIPT` environment variable can specify the initial script file. * You can specify the initial script with `rdbg -x initial_script` (like gdb's `-x` option). Initial scripts are useful to write your favorite configurations. -For example, you can set break points with `break file:123` in `~/.rdbgrc`. +For example, you can set breakpoints with `break file:123` in `~/.rdbgrc`. -If there are `~/.rdbgrc.rb` is available, it is also loaded as a ruby script at same timing. +If there is a `~/.rdbgrc.rb` file it is also loaded as a Ruby script when the debug session is started. ## Debug command on the debug console @@ -495,20 +512,47 @@ On the debug console, you can use the following debug commands. There are additional features: -* `` without debug command is almost same as `pp `. - * If the input line `` does *NOT* start with any debug command, the line `` will be evaluated as a Ruby expression and the result will be printed with `pp` method. So that the input `foo.bar` is same as `pp foo.bar`. - * If `` is recognized as a debug command, of course it is not evaluated as a Ruby expression, but is executed as debug command. For example, you can not evaluate such single letter local variables `i`, `b`, `n`, `c` because they are single letter debug commands. Use `p i` instead. - * So the author (Koichi Sasada) recommends to use `p`, `pp` or `eval` command to evaluate the Ruby expression everytime. +* `` without debug command is almost the same as `pp `. + * If the input line `` does *NOT* start with any debug command, the line `` will be evaluated as a Ruby expression, and the result will be printed with `pp` method. + So that the input `foo.bar` is the same as `pp foo.bar`. + * If `` is recognized as a debug command, of course, it is not evaluated as a Ruby expression but is executed as debug command. + For example, you can not evaluate such single-letter local variables `i`, `b`, `n`, `c` because they are single-letter debug commands. Use `p i` instead. + * For consistency, the author (Koichi Sasada) recommends using the `p`, `pp`, or `eval` command to evaluate the Ruby expression every time. * `Enter` without any input repeats the last command (useful when repeating `step`s) for some commands. * `Ctrl-D` is equal to `quit` command. * [debug command compare sheet - Google Sheets](https://docs.google.com/spreadsheets/d/1TlmmUDsvwK4sSIyoMv-io52BUUz__R5wpu-ComXlsw0/edit?usp=sharing) -You can use the following debug commands. Each command should be written in 1 line. -The `[...]` notation means this part can be eliminate. For example, `s[tep]` means `s` or `step` are valid command. `ste` is not valid. -The `<...>` notation means the argument. +You can use the following debug commands. +Each command should be written in 1 line. +The `[…]` notation means this part can be eliminated. For example, `s[tep]` means `s` or `step` is a valid command. `ste` is not valid. +The `<…>` notation means the argument. <%= DEBUGGER__.help %> +### Using IRB as the Debug Console + +Starting from version `v1.9`, you can now use IRB as the debug console. This integration brings additional features such as: + +* Autocompletion +* Support for multi-line input +* Access to commands not available in `debug`, like `show_source` or `show_doc` +* [Configurable command aliases](https://docs.ruby-lang.org/en/master/IRB.html#module-IRB-label-Command+Aliases) + +To switch to the IRB console, simply use the `irb` command in the debug console. + +Once activated, you'll notice the prompt changes to: + +```console +irb:rdbg(main):001> +``` + +If you want to make IRB the default console for all sessions, configure the `irb_console` setting by either: + +* Setting the `RUBY_DEBUG_IRB_CONSOLE=true` environment variable +* Or adding `config set irb_console 1` to your `~/.rdbgrc` + +To disable the IRB console in the current session, execute `config set irb_console 0` in the console. + ## Debugger API ### Start debugging @@ -525,9 +569,12 @@ You can start debugging without `rdbg` command by requiring the following librar You need to require one of them at the very beginning of the application. Using `ruby -r` (for example `ruby -r debug/start target.rb`) is another way to invoke with debugger. -NOTE: Until Ruby 3.0, there is old `lib/debug.rb` standard library. So that if this gem is not installed, or if `Gemfile` missed to list this gem and `bundle exec` is used, you will see the following output: +NOTE: Until Ruby 3.0, there is old `lib/debug.rb` in the standard library. +`lib/debug.rb` was not maintained well in recent years, and the purpose of this library is to rewrite old `lib/debug.rb` with recent techniques. + +So, if this gem is not installed, or if the `Gemfile` doesn't include this gem and `bundle exec` is used, you will see the following output: -```shell +```console $ ruby -r debug -e0 .../2.7.3/lib/ruby/2.7.0/x86_64-linux/continuation.so: warning: callcc is obsolete; use Fiber instead Debug.rb @@ -537,16 +584,15 @@ Emacs support available. (rdb:1) ``` -`lib/debug.rb` was not maintained well in recent years, and the purpose of this library is to rewrite old `lib/debug.rb` with recent techniques. - #### Start by method -After loading `debug/session`, you can start debug session with the following methods. They are convenient if you want to specify debug configurations in your program. +After loading `debug/session`, you can start a debug session with the following methods. +They are convenient if you want to specify debug configurations in your program. * `DEBUGGER__.start(**kw)`: start debug session with local console. -* `DEBUGGER__.open(**kw)`: open debug port with configuration (without configurations open with UNIX domain socket) -* `DEBUGGER__.open_unix(**kw)`: open debug port with UNIX domain socket -* `DEBUGGER__.open_tcp(**kw)`: open debug port with TCP/IP +* `DEBUGGER__.open(**kw)`: open debug port with configuration (without configurations open with UNIX domain socket). +* `DEBUGGER__.open_unix(**kw)`: open debug port with UNIX domain socket. +* `DEBUGGER__.open_tcp(**kw)`: open debug port with TCP/IP. For example: @@ -560,35 +606,39 @@ DEBUGGER__.start(no_color: true, # disable colorize ### `binding.break` method -`binding.break` (or `binding.b`) set breakpoints at written line. It also has several keywords. +`binding.break` (or `binding.b`) sets a breakpoint at that line. +It also has several keywords. -If `do: 'command'` is specified, the debugger suspends the program and run the `command` as a debug command and continue the program. +If `do: 'command'` is specified, the debugger suspends the program, runs the `command` as a debug command, and continues the program. It is useful if you only want to call a debug command and don't want to stop there. +For example: -``` +```ruby def initialize @a = 1 - binding.b do: 'watch @a' + binding.b do: 'info \n watch @a' end ``` -On this case, register a watch breakpoint for `@a` and continue to run. +In this case, execute the `info` command, then register a watch breakpoint for `@a` and continue to run. +You can also use `;;` instead of `\n` to separate your commands. -If `pre: 'command'` is specified, the debugger suspends the program and run the `command` as a debug command, and keep suspend. +If `pre: 'command'` is specified, the debugger suspends the program and runs the `command` as a debug command, and keeps suspended. It is useful if you have operations before suspend. +For example: -``` +```ruby def foo binding.b pre: 'p bar()' ... end ``` -On this case, you can see the result of `bar()` every time you stop there. +In this case, you can see the result of `bar()` every time you stop there. ## rdbg command help -``` +```console <%= `exe/rdbg --help` %> ``` @@ -599,7 +649,7 @@ On this case, you can see the result of `bar()` every time you stop there. # Contributing -Bug reports and pull requests are welcome on GitHub at https://github.com/ruby/debug. +Bug reports and pull requests are welcome on GitHub at [https://github.com/ruby/debug](). This debugger is not mature so your feedback will help us. Please also check the [contributing guideline](/CONTRIBUTING.md). diff --git a/test/console/backtrace_test.rb b/test/console/backtrace_test.rb index 818fe609e..8c6056a6a 100644 --- a/test/console/backtrace_test.rb +++ b/test/console/backtrace_test.rb @@ -22,7 +22,7 @@ def program 14| end 15| end 16| - 17| 3.times do + 17| [1, 2, 3].reverse_each do 18| Foo.new.first_call 19| end RUBY @@ -33,7 +33,7 @@ def test_backtrace_prints_c_method_frame type 'b 18' type 'c' type 'bt' - assert_line_text(/\[C\] Integer#times/) + assert_line_text(/\[C\] Array#reverse_each/) type 'kill!' end end @@ -116,33 +116,41 @@ def test_backtrace_takes_both_number_and_pattern end def test_frame_filtering_works_with_unexpanded_path_and_expanded_skip_path - foo_file = 'class Foo; def bar; debugger; end; end' + foo_path = "#{pty_home_dir}/foo_#{Time.now.to_i}.rb" + foo_file = <<~RUBY + class Foo + def bar + debugger + end + end + RUBY + program = <<~RUBY - 1| load "~/foo.rb" + 1| load "~/#{File.basename(foo_path)}" 2| Foo.new.bar RUBY begin - File.open("#{pty_home_dir}/foo.rb", 'w+').close + File.open(foo_path, 'w+').close rescue Errno::EACCES, Errno::EPERM omit "Skip test with load files. Cannot create files in HOME directory." end + File.open(foo_path, 'w+') { |f| f.write(foo_file) } debug_code(program) do - type "file = File.open('#{pty_home_dir}/foo.rb', 'w+') { |f| f.write('#{foo_file}') }" type 'c' type 'bt' assert_line_text(/Foo#bar/) - assert_line_text(/~\/foo\.rb/) - type "DEBUGGER__::CONFIG[:skip_path] = '#{pty_home_dir}/foo.rb'" + assert_line_text(/~\/foo_\d+.rb/) + type "eval DEBUGGER__::CONFIG[:skip_path] = '#{foo_path}'" type 'bt' - assert_no_line_text(/Foo#bar/) # ~/foo.rb should match foo.rb's absolute path and be skipped + assert_no_line_text(/Foo#bar/) # ~/foo....rb should match foo.rb's absolute path and be skipped assert_no_line_text(/~\/foo\.rb/) type 'c' end ensure - if File.exist? "#{pty_home_dir}/foo.rb" - File.unlink "#{pty_home_dir}/foo.rb" + if File.exist? foo_path + File.unlink foo_path end end end @@ -180,4 +188,72 @@ def test_backtrace_prints_nested_block_label_correctly end end end + + class ThreadLockingTraceTest < ConsoleTestCase + def program + <<~RUBY + 1| th0 = Thread.new{sleep} + 2| $m = Mutex.new + 3| th1 = Thread.new do + 4| $m.lock + 5| sleep 1 + 6| $m.unlock + 7| end + 8| + 9| o = Object.new + 10| def o.inspect + 11| $m.lock + 12| "foo".tap { $m.unlock } + 13| end + 14| + 15| def foo(o) + 16| debugger + 17| end + 18| sleep 0.5 + 19| foo(o) + RUBY + end + + def test_backtrace_prints_without_hanging + debug_code(program) do + type "c" + + type "bt" + assert_line_text(/Object#foo\(o=foo\)/) + type "bt" + assert_line_text(/Object#foo\(o=foo\)/) + type "bt" + assert_line_text(/Object#foo\(o=foo\)/) + + type "kill!" + end + end + end + + class BrokenSingletonMethodBacktraceTest < ConsoleTestCase + def program + <<~RUBY + 1| class C + 2| def self.foo + 3| debugger + 4| end + 5| def singleton_class + 6| raise + 7| end + 8| def self.singleton_class + 9| eval(")") # SyntaxError + 10| end + 11| end + 12| C.foo + RUBY + end + + def test_raise_exception + debug_code program do + type 'c' + assert_line_text(/foo/) + type 'c' + end + end + end end diff --git a/test/console/break_test.rb b/test/console/break_test.rb index bd8ed86cf..4733360ff 100644 --- a/test/console/break_test.rb +++ b/test/console/break_test.rb @@ -255,6 +255,17 @@ def test_break_only_stops_when_path_matches end end + def test_break_only_path + with_extra_tempfile "foohtml" do |extra_file| + debug_code(program(extra_file.path)) do + type "break path: #{extra_file.path}" + type 'c' + assert_line_text(/#{extra_file.path}/) + type 'c' + end + end + end + def test_the_path_option_supersede_skip_path_config # skips the extra_file's breakpoint with_extra_tempfile do |extra_file| @@ -384,11 +395,11 @@ def test_break_only_stops_when_path_matches class BreakAtCMethod2Test < ConsoleTestCase def program <<~RUBY - 1| binding.b(do: "b Array#each") + 1| binding.b(do: "b Array#reverse_each") 2| 3| result = "" 4| - 5| [1, 2, 3].each do |i| + 5| [1, 2, 3].reverse_each do |i| 6| result += i.to_s 7| end 8| @@ -819,7 +830,7 @@ def program path RUBY end - def test_break_on_realoded_file + def test_break_on_realoded_file_pending with_extra_tempfile do |extra_file| debug_code(program(extra_file.path)) do type "break #{extra_file.path}:2 do: p :xyzzy" @@ -837,5 +848,154 @@ def test_break_on_realoded_file end end end + + def test_break_on_reloaded_file + code = <<~'DEBUG_CODE' + 1| require 'tempfile' + 2| tf = Tempfile.new('debug_gem_test') + 3| tf.puts(<#{CLEAR}\n": dummy_class.new('b'), + { "#{GREEN}##{CLEAR}\n": dummy_class.new('b'), "#{RED}#{BOLD}\"#{CLEAR}#{RED}hoge#{CLEAR}#{RED}#{BOLD}\"#{CLEAR}\n": 'hoge'}.each do |k, v| expected = k.to_s obj = v @@ -94,7 +94,7 @@ def test_colorize_does_not_color_string_if_do_not_use_colorize CONFIG[:no_color] = nil end - SESSION_class = Struct.new('SESSION') + SESSION_class = Struct.new('SESSION', :a) private diff --git a/test/console/config_test.rb b/test/console/config_test.rb index 102329165..6d87b6da4 100644 --- a/test/console/config_test.rb +++ b/test/console/config_test.rb @@ -105,6 +105,119 @@ def test_show_src_lines_control_the_lines_displayed_on_breakpoint end end + class ShowSrcLinesFrameTest < ConsoleTestCase + def program + <<~RUBY + 1| class Foo + 2| def self.a + 3| p 1 + 4| p 2 + 5| p 3 + 6| p 3 + 7| p 5 + 8| p 6 + 9| p 7 + 10| p 8 + 11| p 9 + 12| p 10 + 13| b + 14| end + 15| + 16| def self.b + 17| binding.b + 18| p 11 + 19| end + 20| end + 21| + 22| Foo.a + RUBY + end + + def test_show_src_lines_control_the_lines_displayed_on_up + debug_code(program) do + type 'config set show_src_lines_frame 2' + type 'continue' + type 'up' + assert_line_text([ + /12\| p 10/, + /=> 13\| b/, + ]) + assert_no_line_text(/11\|/) + assert_no_line_text(/14\|/) + type 'continue' + end + end + + def test_show_src_lines_control_the_lines_displayed_on_down + debug_code(program) do + type 'config set show_src_lines_frame 2' + type 'continue' + type 'up' + type 'down' + assert_line_text([ + /16\| def self\.b/, + /=> 17\| binding\.b/ + ]) + assert_no_line_text(/15\|/) + assert_no_line_text(/18\|/) + type 'continue' + end + end + + def test_show_src_lines_control_the_lines_displayed_on_set + debug_code(program) do + type 'config set show_src_lines_frame 2' + type 'continue' + type 'frame' + assert_line_text([ + /16\| def self\.b/, + /=> 17\| binding\.b/ + ]) + assert_no_line_text(/15\|/) + assert_no_line_text(/18\|/) + type 'continue' + end + end + end + + class ShowOrigSrcTest < ConsoleTestCase + def program + <<~RUBY + 1| binding.eval < e + 12| puts "the end" + 13| end + 14| end + 15| end + 16| end + 17| + 18| Whatever.new.some_method + RUBY + end + + def test_frame_block_identifier + debug_code(program) do + type 'b 12' + type 'c' + assert_line_num 12 + assert_line_text([ + /\[7, 16\] in .*/, + / 7\| will_exit = true/, + / 8\| /, + / 9\| begin/, + / 10\| raise "foo"/, + / 11\| rescue => e/, + /=> 12\| puts "the end"/, + / 13\| end/, + / 14\| end/, + / 15\| end/, + / 16\| end/, + /=>\#0\tWhatever\#some_method at .*/, + / \#1\t.*/, + / \# and (?:2|3) frames \(use `bt' command for all frames\)/, + //, + /Stop by \#0 BP \- Line .*/ + ]) + type 'c' + end + end + end +end diff --git a/test/console/info_test.rb b/test/console/info_test.rb index 47697d8fc..972d18103 100644 --- a/test/console/info_test.rb +++ b/test/console/info_test.rb @@ -107,7 +107,7 @@ def test_prints_current_thread type 'b 7' type 'c' type 'info threads' - assert_line_text(/#0 \(sleep\)@.*:7:in `
'/) + assert_line_text(/#0 \(sleep\)@.*:7:in [`']
'/) type 'kill!' end end @@ -127,29 +127,36 @@ class InfoConstantTest < ConsoleTestCase def program <<~RUBY 1| - 1| class C0 - 2| C0_CONST1 = -1 - 3| C0_CONST2 = -2 - 4| end - 5| - 6| class D - 7| D_CONST1 = 1 - 8| D_CONST2 = 1 - 9| class C1 < C0 - 10| CONST1 = 1 - 11| CONST2 = 2 - 12| l1 = 10 - 13| l2 = 20 - 14| @i1 = 100 - 15| @i2 = 200 - 16| - 17| def foo - 18| :foo - 19| end - 20| end - 21| end - 22| - 23| D::C1.new.foo + 2| class C0 + 3| C0_CONST1 = -1 + 4| C0_CONST2 = -2 + 5| end + 6| + 7| class D + 8| D_CONST1 = 1 + 9| D_CONST2 = 1 + 10| class C1 < C0 + 11| CONST1 = 1 + 12| CONST2 = 2 + 13| l1 = 10 + 14| l2 = 20 + 15| @i1 = 100 + 16| @i2 = 200 + 17| + 18| def foo + 19| :foo + 20| end + 21| end + 22| end + 23| + 24| class E + 25| E_CONST1 = C0 + 26| def self.foo + 27| D + 28| end + 29| end + 30| + 31| D::C1.new.foo RUBY end @@ -203,5 +210,193 @@ def test_info_constant type 'c' end end + + def test_info_constant_twice + debug_code program do + type 'i c' # on Ruby 3.2, `Set` loads `set.rb` + type 'i c' # on Ruby 3.2, accessing `SortedSet` raises an error + # # 123' + type 'irb_info' + assert_line_text('IRB version:') + type 'next' + type 'info' + assert_line_text([/a = 1/, /b = nil/]) + + # disable irb console + type 'config set irb_console false' + type '456' + assert_raw_line_text '(rdbg) 456' + type 'q!' + end + end + + def test_irb_console_config_activates_irb + ENV["RUBY_DEBUG_IRB_CONSOLE"] = "true" + + debug_code(program, remote: false) do + type '123' + assert_raw_line_text 'irb:rdbg(main):002> 123' + type 'irb_info' + assert_line_text('IRB version:') + type 'next' + type 'info' + assert_line_text([/a = 1/, /b = nil/]) + + # disable irb console + type 'config set irb_console false' + type '456' + assert_raw_line_text '(rdbg) 456' + type 'q!' + end + ensure + ENV["RUBY_DEBUG_IRB_CONSOLE"] = nil + end + + private + + # assert_line_text ignores the prompt line, so we can't use it to assert the prompt transition + # assert_raw_line_text is a workaround for that + def assert_raw_line_text(expectation) + @scenario.push(Proc.new do |test_info| + assert_include(test_info.last_backlog.join, expectation) + end) + end + end +end diff --git a/test/console/nested_break_test.rb b/test/console/nested_break_test.rb index c90f8c9c5..c152b3f01 100644 --- a/test/console/nested_break_test.rb +++ b/test/console/nested_break_test.rb @@ -10,7 +10,7 @@ def program 2| b = a + 1 # break 3| end 4| def bar - 5| x = 1 # break + 5| x = 1 # break 6| end 7| bar 8| x = 2 @@ -35,7 +35,7 @@ def test_nested_break type 'p a' assert_line_text(/42/) type 'c' - assert_line_num 7 + assert_line_num 7 # because restored `up` line end # pop nested break @@ -48,6 +48,27 @@ def test_nested_break end end + def test_nested_break_bt + debug_code program do + type 'break 2' + type 'break 5' + type 'c' + + assert_line_num 5 + type 'p foo(42)' + + if TracePoint.respond_to? :allow_reentry + # nested break + assert_line_num 2 + type 'bt' + assert_no_line_text 'thread_client.rb' + type 'c' + end + + type 'c' + end + end + def test_multiple_nested_break debug_code program do type 'break 2' @@ -62,7 +83,7 @@ def test_multiple_nested_break assert_line_num 2 type 'p foo(142)' type 'bt' - assert_line_text(/\#9/) # TODO: can be changed + assert_line_text(/\#\d+\s+
/) type 'c' assert_line_text(/143/) diff --git a/test/console/outline_test.rb b/test/console/outline_test.rb index f86350399..73b9a5481 100644 --- a/test/console/outline_test.rb +++ b/test/console/outline_test.rb @@ -67,4 +67,35 @@ def test_outline_aliases end end end + + class OutlineThreadLockingTest < ConsoleTestCase + def program + <<~RUBY + 1| th0 = Thread.new{sleep} + 2| $m = Mutex.new + 3| th1 = Thread.new do + 4| $m.lock + 5| sleep 1 + 6| $m.unlock + 7| end + 8| + 9| def self.constants # overriding constants is only one of the ways to cause deadlock with outline + 10| $m.lock + 11| [] + 12| end + 13| + 14| sleep 0.5 + 15| debugger + RUBY + end + + def test_outline_doesnt_cause_deadlock + debug_code(program) do + type 'c' + type 'ls' + assert_line_text(/locals: th0/) + type 'c' + end + end + end end diff --git a/test/console/print_test.rb b/test/console/print_test.rb index 3f9702b76..16f5c4436 100644 --- a/test/console/print_test.rb +++ b/test/console/print_test.rb @@ -15,7 +15,7 @@ def test_p_prints_the_expression debug_code(program) do type "c" type "p h" - assert_line_text('{:foo=>"bar"}') + assert_line_text({ foo: "bar" }.inspect) type "c" end end @@ -24,7 +24,7 @@ def test_pp_pretty_prints_the_expression debug_code(program) do type "c" type "pp h" - assert_line_text([/\{:foo=>/, /"bar"\}/]) + assert_line_text({ foo: "bar" }.pretty_print_inspect) type "c" end end diff --git a/test/console/rdbg_option_test.rb b/test/console/rdbg_option_test.rb index 615b07ef3..c173c33bd 100644 --- a/test/console/rdbg_option_test.rb +++ b/test/console/rdbg_option_test.rb @@ -72,7 +72,7 @@ def program def test_debugger_stops_immediately run_rdbg(program, options: "--stop-at-load") do # stops at the earliest possible location - assert_line_text(/\[C\] Kernel#require/) + assert_line_text(/\[C\] Kernel[#\.]require/) type "c" type "a + 'bar'" assert_line_text(/foobar/) diff --git a/test/console/record_test.rb b/test/console/record_test.rb index 6b6f99798..9cf32756e 100644 --- a/test/console/record_test.rb +++ b/test/console/record_test.rb @@ -315,4 +315,24 @@ def test_1663647719 end end end + + class RecordOnBasicClassTest < ConsoleTestCase + def program + <<~RUBY + 1| class Test < BasicObject + 2| def test + 3| 42 + 4| end + 5| end + 6| Test.new.test + RUBY + end + + def test_issue1152 + debug_code program do + type 'record on' + type 'c' + end + end + end end diff --git a/test/console/rescue_test.rb b/test/console/rescue_test.rb new file mode 100644 index 000000000..f0225147b --- /dev/null +++ b/test/console/rescue_test.rb @@ -0,0 +1,28 @@ +# frozen_string_literal: true + +require_relative '../support/console_test_case' + +module DEBUGGER__ + class RescueTest < ConsoleTestCase + def program + <<~RUBY + 1| 1.times do + 2| begin + 3| raise + 4| rescue + 5| p :ok + 6| end + 7| end + RUBY + end + + def test_rescue + debug_code program, remote: false do + type 's' + type 's' + type 'c' + end + end + end if RUBY_VERSION.to_f >= 3.5 +end + diff --git a/test/console/trace_test.rb b/test/console/trace_test.rb index e75186d2f..68e1df260 100644 --- a/test/console/trace_test.rb +++ b/test/console/trace_test.rb @@ -473,6 +473,36 @@ def test_block_doesnt_break_tracer end end + class ThreadLockingTest < ConsoleTestCase + def program + <<~RUBY + 1| th0 = Thread.new{sleep} + 2| $m = Mutex.new + 3| th1 = Thread.new do + 4| $m.lock + 5| sleep 1 + 6| $m.unlock + 7| end + 8| + 9| def inspect + 10| m.lock + 11| "" + 12| end + 13| + 14| sleep 0.5 + 15| debugger + RUBY + end + + def test_object_tracer_doesnt_cause_deadlock + debug_code(program) do + type 'c' + type 'trace object self' + type 'c' + end + end + end + class TraceCallReceiverTest < ConsoleTestCase def program <<~RUBY @@ -532,5 +562,31 @@ def test_tracer_prints_correct_method_receiving_messages end end end + + class TraceOnAfterStoppingOnceTest < ConsoleTestCase + def program + <<~RUBY + 1| a=1 + 2| + 3| b=1 + 4| + 5| c=1 + 6| p a + RUBY + end + + def test_1656237686 + debug_code(program) do + type 'trace line' + type 'trace off' + type 'trace line' + type 'b 5' + type 'c' + assert_line_num 5 + assert_line_text(/DEBUGGER \(trace\/line\)/) + type 'kill!' + end + end + end end end diff --git a/test/console/trap_test.rb b/test/console/trap_test.rb index 4664d3757..0f18e14ac 100644 --- a/test/console/trap_test.rb +++ b/test/console/trap_test.rb @@ -16,7 +16,6 @@ def test_sigint debug_code program, remote: false do type 'b 3' type 'c' - assert_line_num 2 assert_line_text(/is registered as SIGINT handler/) type 'sigint' assert_line_num 3 @@ -24,6 +23,32 @@ def test_sigint type 'c' end end + + def test_trap_with + debug_code %q{ + 1| trap(:INT){} # Symbol + 2| _ = 1 + }, remote: false do + type 'n' + type 'n' + end + + debug_code %q{ + 1| trap('INT'){} # String + 2| _ = 1 + }, remote: false do + type 'n' + type 'n' + end + + debug_code %q{ + 1| trap(Signal.list['INT']){} if Signal.list['INT'] # Integer + 2| _ = 1 + }, remote: false do + type 'n' + type 'n' + end + end end end diff --git a/test/protocol/boot_config_raw_dap_test.rb b/test/protocol/boot_config_raw_dap_test.rb index dd32e790a..677becd63 100644 --- a/test/protocol/boot_config_raw_dap_test.rb +++ b/test/protocol/boot_config_raw_dap_test.rb @@ -120,7 +120,7 @@ def test_boot_configuration_works_correctly threads: [ { id: 1, - name: "#1 #{temp_file_path}:1:in `
'" + name: /\#1 #{temp_file_path}:1:in [`']
'/ } ] } @@ -141,7 +141,7 @@ def test_boot_configuration_works_correctly threads: [ { id: 1, - name: "#1 #{temp_file_path}:1:in `
'" + name: /\#1 #{temp_file_path}:1:in [`']
'/ } ] } diff --git a/test/protocol/break_raw_cdp_test.rb b/test/protocol/break_raw_cdp_test.rb index edf611210..418e0b2e4 100644 --- a/test/protocol/break_raw_cdp_test.rb +++ b/test/protocol/break_raw_cdp_test.rb @@ -18,7 +18,7 @@ class BreakTest1647164808 < ProtocolTestCase RUBY - def test_1647164808 + def test_1680359282 run_cdp_scenario PROGRAM do [ *INITIALIZE_CDP_MSGS, @@ -126,70 +126,18 @@ def test_1647164808 }, { id: 10, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 10, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Object" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 11, - method: "Debugger.getPossibleBreakpoints", - params: { - start: { - scriptId: "1", - lineNumber: 0, - columnNumber: 0 - }, - restrictToFunction: true - } - }, - { - id: 11, - result: { - locations: [ - { - scriptId: /.+/, - lineNumber: 0 - } - ] - } - }, - { - id: 12, method: "Debugger.setBreakpointsActive", params: { active: true } }, { - id: 12, + id: 10, result: { } }, { - id: 13, + id: 11, method: "Debugger.setBreakpointByUrl", params: { lineNumber: 3, @@ -199,7 +147,7 @@ def test_1647164808 } }, { - id: 13, + id: 11, result: { breakpointId: /.+/, locations: [ @@ -211,7 +159,7 @@ def test_1647164808 } }, { - id: 14, + id: 12, method: "Debugger.getPossibleBreakpoints", params: { start: { @@ -228,7 +176,7 @@ def test_1647164808 } }, { - id: 14, + id: 12, result: { locations: [ { @@ -239,19 +187,19 @@ def test_1647164808 } }, { - id: 15, + id: 13, method: "Debugger.setBreakpointsActive", params: { active: true } }, { - id: 15, + id: 13, result: { } }, { - id: 16, + id: 14, method: "Debugger.setBreakpointByUrl", params: { lineNumber: 6, @@ -261,7 +209,7 @@ def test_1647164808 } }, { - id: 16, + id: 14, result: { breakpointId: /.+/, locations: [ @@ -273,7 +221,7 @@ def test_1647164808 } }, { - id: 17, + id: 15, method: "Debugger.getPossibleBreakpoints", params: { start: { @@ -290,7 +238,7 @@ def test_1647164808 } }, { - id: 18, + id: 16, method: "Debugger.getPossibleBreakpoints", params: { start: { @@ -307,7 +255,7 @@ def test_1647164808 } }, { - id: 17, + id: 15, result: { locations: [ { @@ -318,7 +266,7 @@ def test_1647164808 } }, { - id: 18, + id: 16, result: { locations: [ { @@ -329,19 +277,19 @@ def test_1647164808 } }, { - id: 19, + id: 17, method: "Debugger.setBreakpointsActive", params: { active: true } }, { - id: 19, + id: 17, result: { } }, { - id: 20, + id: 18, method: "Debugger.setBreakpointByUrl", params: { lineNumber: 7, @@ -351,7 +299,7 @@ def test_1647164808 } }, { - id: 20, + id: 18, result: { breakpointId: /.+/, locations: [ @@ -363,7 +311,7 @@ def test_1647164808 } }, { - id: 21, + id: 19, method: "Debugger.getPossibleBreakpoints", params: { start: { @@ -380,7 +328,7 @@ def test_1647164808 } }, { - id: 22, + id: 20, method: "Debugger.getPossibleBreakpoints", params: { start: { @@ -397,7 +345,7 @@ def test_1647164808 } }, { - id: 21, + id: 19, result: { locations: [ { @@ -408,7 +356,7 @@ def test_1647164808 } }, { - id: 23, + id: 21, method: "Debugger.getPossibleBreakpoints", params: { start: { @@ -425,7 +373,7 @@ def test_1647164808 } }, { - id: 22, + id: 20, result: { locations: [ { @@ -436,7 +384,7 @@ def test_1647164808 } }, { - id: 23, + id: 21, result: { locations: [ { @@ -447,14 +395,14 @@ def test_1647164808 } }, { - id: 24, + id: 22, method: "Debugger.resume", params: { terminateOnResume: false } }, { - id: 24, + id: 22, result: { } }, @@ -463,32 +411,6 @@ def test_1647164808 params: { } }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, { method: "Debugger.paused", params: { @@ -576,18 +498,7 @@ def test_1647164808 } }, { - id: 25, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 26, + id: 23, method: "Runtime.getProperties", params: { objectId: "0:local", @@ -598,36 +509,7 @@ def test_1647164808 } }, { - id: 25, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Module" - }, - configurable: true, - enumerable: true - }, - { - name: "bar", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 26, + id: 23, result: { result: [ { @@ -656,14 +538,14 @@ def test_1647164808 } }, { - id: 27, + id: 24, method: "Debugger.resume", params: { terminateOnResume: false } }, { - id: 27, + id: 24, result: { } }, @@ -672,45 +554,6 @@ def test_1647164808 params: { } }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, { method: "Debugger.paused", params: { @@ -837,36 +680,7 @@ def test_1647164808 } }, { - id: 28, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 28, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Class" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 29, + id: 25, method: "Runtime.getProperties", params: { objectId: "0:local", @@ -877,7 +691,7 @@ def test_1647164808 } }, { - id: 29, + id: 25, result: { result: [ { @@ -895,14 +709,14 @@ def test_1647164808 } }, { - id: 30, + id: 26, method: "Debugger.resume", params: { terminateOnResume: false } }, { - id: 30, + id: 26, result: { } }, @@ -911,32 +725,6 @@ def test_1647164808 params: { } }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, { method: "Debugger.paused", params: { @@ -1024,18 +812,7 @@ def test_1647164808 } }, { - id: 31, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 32, + id: 27, method: "Runtime.getProperties", params: { objectId: "0:local", @@ -1046,36 +823,7 @@ def test_1647164808 } }, { - id: 31, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Module" - }, - configurable: true, - enumerable: true - }, - { - name: "bar", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 32, + id: 27, result: { result: [ { @@ -1104,14 +852,14 @@ def test_1647164808 } }, { - id: 33, + id: 28, method: "Debugger.resume", params: { terminateOnResume: false } }, { - id: 33, + id: 28, result: { } } diff --git a/test/protocol/break_test.rb b/test/protocol/break_test.rb index 30ad2025d..a78f70ebd 100644 --- a/test/protocol/break_test.rb +++ b/test/protocol/break_test.rb @@ -83,4 +83,56 @@ def test_break_stops_at_the_extra_file end end end + + class NestedBreakTest < ProtocolTestCase + PROGRAM = <<~RUBY + 1| def foo(x) + 2| x + 3| end + 4| + 5| foo("foo") + RUBY + + def test_breakpoint_can_be_triggered_inside_suspenssion + run_protocol_scenario PROGRAM, cdp: false do + req_add_breakpoint 2 + req_continue + assert_line_num 2 + + assert_locals_result( + [ + { name: "%self", value: "main", type: "Object" }, + { name: "x", value: "foo", type: "String" }, + ] + ) + + # Only if TracePoint.allow_reentry is available, we can trigger TracePoint events + # inside another TracePoint event, which is essential for nested breakpoints. + if TracePoint.respond_to? :allow_reentry + evaluate("foo('bar')") + + assert_line_num 2 + assert_locals_result( + [ + { name: "%self", value: "main", type: "Object" }, + { name: "x", value: "bar", type: "String" }, + ] + ) + end + + req_terminate_debuggee + end + end + + private + + def evaluate(expression) + res = send_dap_request 'stackTrace', + threadId: 1, + startFrame: 0, + levels: 20 + f_id = res.dig(:body, :stackFrames, 0, :id) + send_request 'evaluate', expression: expression, frameId: f_id, context: "repl" + end + end end diff --git a/test/protocol/call_stack_raw_cdp_test.rb b/test/protocol/call_stack_raw_cdp_test.rb index 73376a508..602381d64 100644 --- a/test/protocol/call_stack_raw_cdp_test.rb +++ b/test/protocol/call_stack_raw_cdp_test.rb @@ -3,8 +3,7 @@ require_relative '../support/protocol_test_case' module DEBUGGER__ - - class CallStackTest1647167458 < ProtocolTestCase + class CallStackTest1680367946 < ProtocolTestCase PROGRAM = <<~RUBY 1| module Foo 2| class Bar @@ -18,7 +17,7 @@ class CallStackTest1647167458 < ProtocolTestCase RUBY - def test_1647167458 + def test_1680367946 run_cdp_scenario PROGRAM do [ *INITIALIZE_CDP_MSGS, @@ -126,47 +125,18 @@ def test_1647167458 }, { id: 10, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 10, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Object" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 11, method: "Debugger.setBreakpointsActive", params: { active: true } }, { - id: 11, + id: 10, result: { } }, { - id: 12, + id: 11, method: "Debugger.setBreakpointByUrl", params: { lineNumber: 3, @@ -176,7 +146,7 @@ def test_1647167458 } }, { - id: 12, + id: 11, result: { breakpointId: /.+/, locations: [ @@ -188,7 +158,7 @@ def test_1647167458 } }, { - id: 13, + id: 12, method: "Debugger.getPossibleBreakpoints", params: { start: { @@ -205,7 +175,7 @@ def test_1647167458 } }, { - id: 13, + id: 12, result: { locations: [ { @@ -216,14 +186,14 @@ def test_1647167458 } }, { - id: 14, + id: 13, method: "Debugger.resume", params: { terminateOnResume: false } }, { - id: 14, + id: 13, result: { } }, @@ -232,45 +202,6 @@ def test_1647167458 params: { } }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, { method: "Debugger.paused", params: { @@ -397,18 +328,7 @@ def test_1647167458 } }, { - id: 15, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 16, + id: 14, method: "Runtime.getProperties", params: { objectId: "0:local", @@ -419,25 +339,7 @@ def test_1647167458 } }, { - id: 15, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Class" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 16, + id: 14, result: { result: [ { @@ -455,18 +357,7 @@ def test_1647167458 } }, { - id: 17, - method: "Runtime.getProperties", - params: { - objectId: "1:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 18, + id: 15, method: "Runtime.getProperties", params: { objectId: "1:local", @@ -477,36 +368,7 @@ def test_1647167458 } }, { - id: 17, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Module" - }, - configurable: true, - enumerable: true - }, - { - name: "bar", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 18, + id: 15, result: { result: [ { @@ -535,18 +397,7 @@ def test_1647167458 } }, { - id: 19, - method: "Runtime.getProperties", - params: { - objectId: "2:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 20, + id: 16, method: "Runtime.getProperties", params: { objectId: "2:local", @@ -557,25 +408,7 @@ def test_1647167458 } }, { - id: 19, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Object" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 20, + id: 16, result: { result: [ { @@ -593,14 +426,14 @@ def test_1647167458 } }, { - id: 21, + id: 17, method: "Debugger.resume", params: { terminateOnResume: false } }, { - id: 21, + id: 17, result: { } } diff --git a/test/protocol/call_stack_with_skip_dap_test.rb b/test/protocol/call_stack_with_skip_dap_test.rb index 52cec55a2..32b94be09 100644 --- a/test/protocol/call_stack_with_skip_dap_test.rb +++ b/test/protocol/call_stack_with_skip_dap_test.rb @@ -58,5 +58,21 @@ def test_it_skips_a_path ensure ENV['RUBY_DEBUG_SKIP_PATH'] = nil end + + def test_it_does_not_skip_a_path_if_there_is_a_breakpoint + with_extra_tempfile do |extra_file| + ENV['RUBY_DEBUG_SKIP_PATH'] = extra_file.path + run_protocol_scenario(program(extra_file.path), cdp: false) do + req_add_breakpoint 2, path: extra_file.path + req_continue + + assert_equal([File.basename(extra_file.path), File.basename(temp_file_path)], req_stacktrace_file_names) + + req_terminate_debuggee + end + end + ensure + ENV['RUBY_DEBUG_SKIP_PATH'] = nil + end end end diff --git a/test/protocol/catch_raw_cdp_test.rb b/test/protocol/catch_raw_cdp_test.rb index db9835b94..c867f2f95 100644 --- a/test/protocol/catch_raw_cdp_test.rb +++ b/test/protocol/catch_raw_cdp_test.rb @@ -4,7 +4,7 @@ module DEBUGGER__ - class CatchTest1647168678 < ProtocolTestCase + class CatchTest1680366940 < ProtocolTestCase PROGRAM = <<~RUBY 1| module Foo 2| class Bar @@ -17,7 +17,7 @@ class CatchTest1647168678 < ProtocolTestCase 9| end RUBY - def test_1647168678 + def test_1680366940 run_cdp_scenario PROGRAM do [ *INITIALIZE_CDP_MSGS, @@ -125,66 +125,25 @@ def test_1647168678 }, { id: 10, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 10, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Object" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 11, method: "Debugger.setPauseOnExceptions", params: { state: "uncaught" } }, { - id: 11, - result: { - } - }, - { - id: 12, - method: "Debugger.setPauseOnExceptions", - params: { - state: "all" - } - }, - { - id: 12, + id: 10, result: { } }, { - id: 13, + id: 11, method: "Debugger.resume", params: { terminateOnResume: false } }, { - id: 13, + id: 11, result: { } }, @@ -193,45 +152,6 @@ def test_1647168678 params: { } }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, { method: "Debugger.paused", params: { @@ -365,18 +285,7 @@ def test_1647168678 } }, { - id: 14, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 15, + id: 12, method: "Runtime.getProperties", params: { objectId: "0:local", @@ -387,37 +296,7 @@ def test_1647168678 } }, { - id: 14, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Class" - }, - configurable: true, - enumerable: true - }, - { - name: "_raised", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - subtype: "error", - className: "RuntimeError" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 15, + id: 12, result: { result: [ { @@ -447,14 +326,14 @@ def test_1647168678 } }, { - id: 16, + id: 13, method: "Debugger.resume", params: { terminateOnResume: false } }, { - id: 16, + id: 13, result: { } }, diff --git a/test/protocol/catch_raw_dap_test.rb b/test/protocol/catch_raw_dap_test.rb index 273c3dd10..3e6a3c437 100644 --- a/test/protocol/catch_raw_dap_test.rb +++ b/test/protocol/catch_raw_dap_test.rb @@ -646,7 +646,9 @@ def test_catching_any_exception_works_correctly success: true, message: "Success", body: { - stackFrames: [ + stackFrames: + RUBY_VERSION < "4.0.0" ? [ + ## { name: "[C] Integer#/", line: 4, @@ -690,6 +692,40 @@ def test_catching_any_exception_works_correctly sourceReference: 0 }, id: 5 + }] : [ + ## RUBY_VERSION >= '4.0.0' + { + name: "Foo::Bar.a", + line: 4, + column: 1, + source: { + name: /#{File.basename temp_file_path}/, + path: /#{temp_file_path}/, + sourceReference: 0 + }, + id: 2 + }, + { + name: "", + line: 7, + column: 1, + source: { + name: /#{File.basename temp_file_path}/, + path: /#{temp_file_path}/, + sourceReference: 0 + }, + id: 3 + }, + { + name: "
", + line: 1, + column: 1, + source: { + name: /#{File.basename temp_file_path}/, + path: /#{temp_file_path}/, + sourceReference: 0 + }, + id: 4 } ] } @@ -738,7 +774,7 @@ def test_catching_any_exception_works_correctly }, type: "request" }, - { + RUBY_VERSION < "4.0.0" ? { seq: 19, type: "response", command: "variables", @@ -765,6 +801,24 @@ def test_catching_any_exception_works_correctly } ] } + } : # RUBY_VERSION >= "4.0.0" + { + "type": "response", + "command": "variables", + "request_seq": 16, + "success": true, + "message": "Success", + "body": { + "variables": [ + { + "name": "%self", + "value": "Foo::Bar", + "type": "Class", + "variablesReference": 5, + "indexedVariables": 0, + "namedVariables": 1 + }] + } }, { seq: 17, diff --git a/test/protocol/catch_test.rb b/test/protocol/catch_test.rb index 48ecf524b..b1749b59e 100644 --- a/test/protocol/catch_test.rb +++ b/test/protocol/catch_test.rb @@ -26,14 +26,14 @@ def test_set_exception_breakpoints_unsets_exception_breakpoints run_protocol_scenario PROGRAM, cdp: false do req_set_exception_breakpoints([{ name: "RuntimeError" }]) req_set_exception_breakpoints([]) - req_continue + req_terminate_debuggee end end def test_set_exception_breakpoints_accepts_condition run_protocol_scenario PROGRAM, cdp: false do req_set_exception_breakpoints([{ name: "RuntimeError", condition: "a == 2" }]) - req_continue + req_terminate_debuggee end run_protocol_scenario PROGRAM, cdp: false do diff --git a/test/protocol/detach_raw_dap_test.rb b/test/protocol/detach_raw_dap_test.rb deleted file mode 100644 index 03406af9e..000000000 --- a/test/protocol/detach_raw_dap_test.rb +++ /dev/null @@ -1,555 +0,0 @@ -# frozen_string_literal: true - -require_relative '../support/protocol_test_case' - -module DEBUGGER__ - - class DetachTest1639218122 < ProtocolTestCase - PROGRAM = <<~RUBY - 1| module Foo - 2| class Bar - 3| def self.a - 4| "hello" - 5| end - 6| end - 7| loop do - 8| b = 1 - 9| end - 10| Bar.a - 11| bar = Bar.new - 12| end - RUBY - - def test_1657544386 - run_dap_scenario PROGRAM do - [ - *INITIALIZE_DAP_MSGS, - { - seq: 7, - type: "event", - event: "stopped", - body: { - reason: "pause", - threadId: 1, - allThreadsStopped: true - } - }, - { - seq: 6, - command: "threads", - type: "request" - }, - { - seq: 8, - type: "response", - command: "threads", - request_seq: 6, - success: true, - message: "Success", - body: { - threads: [ - { - id: 1, - name: /#1 .*/ - } - ] - } - }, - { - seq: 7, - command: "threads", - type: "request" - }, - { - seq: 9, - type: "response", - command: "threads", - request_seq: 7, - success: true, - message: "Success", - body: { - threads: [ - { - id: 1, - name: /#1 .*/ - } - ] - } - }, - { - seq: 8, - command: "stackTrace", - arguments: { - threadId: 1, - startFrame: 0, - levels: 20 - }, - type: "request" - }, - { - seq: 10, - type: "response", - command: "stackTrace", - request_seq: 8, - success: true, - message: "Success", - body: { - stackFrames: [ - { - id: 1, - name: "
", - line: 1, - column: 1, - source: { - name: /#{File.basename temp_file_path}/, - path: /#{temp_file_path}/, - sourceReference: 0 - } - } - ], - totalFrames: 1 - } - }, - { - seq: 9, - command: "scopes", - arguments: { - frameId: 1 - }, - type: "request" - }, - { - seq: 11, - type: "response", - command: "scopes", - request_seq: 9, - success: true, - message: "Success", - body: { - scopes: [ - { - name: "Local variables", - presentationHint: "locals", - namedVariables: /\d+/, - indexedVariables: 0, - expensive: false, - variablesReference: 2 - }, - { - name: "Global variables", - presentationHint: "globals", - variablesReference: 1, - namedVariables: /\d+/, - indexedVariables: 0, - expensive: false - } - ] - } - }, - { - seq: 10, - command: "variables", - arguments: { - variablesReference: 2 - }, - type: "request" - }, - { - seq: 12, - type: "response", - command: "variables", - request_seq: 10, - success: true, - message: "Success", - body: { - variables: [ - { - name: "%self", - value: "main", - type: "Object", - variablesReference: 3, - indexedVariables: 0, - namedVariables: /\d+/ - } - ] - } - }, - { - seq: 11, - command: "disconnect", - arguments: { - restart: false, - terminateDebuggee: false - }, - type: "request" - }, - { - seq: 13, - type: "response", - command: "disconnect", - request_seq: 11, - success: true, - message: "Success" - }, - { - seq: 1, - command: "initialize", - arguments: { - clientID: "vscode", - clientName: "Visual Studio Code", - adapterID: "rdbg", - pathFormat: "path", - linesStartAt1: true, - columnsStartAt1: true, - supportsVariableType: true, - supportsVariablePaging: true, - supportsRunInTerminalRequest: true, - locale: "en-us", - supportsProgressReporting: true, - supportsInvalidatedEvent: true, - supportsMemoryReferences: true - }, - type: "request" - }, - { - seq: 1, - type: "response", - command: "initialize", - request_seq: 1, - success: true, - message: "Success", - body: { - supportsConfigurationDoneRequest: true, - supportsFunctionBreakpoints: true, - supportsConditionalBreakpoints: true, - supportTerminateDebuggee: true, - supportsTerminateRequest: true, - exceptionBreakpointFilters: [ - { - filter: "any", - label: "rescue any exception", - supportsCondition: true - }, - { - filter: "RuntimeError", - label: "rescue RuntimeError", - supportsCondition: true - } - ], - supportsExceptionFilterOptions: true, - supportsStepBack: true, - supportsEvaluateForHovers: true, - supportsCompletionsRequest: true - } - }, - { - seq: 2, - type: "event", - event: "initialized" - }, - { - seq: 2, - command: "attach", - arguments: { - type: "rdbg", - name: "Attach with rdbg", - request: "attach", - __configurationTarget: 5, - __sessionId: "46523ba0-38c2-4503-aa21-ee7c19a263dd" - }, - type: "request" - }, - { - seq: 3, - type: "response", - command: "attach", - request_seq: 2, - success: true, - message: "Success" - }, - { - seq: 3, - command: "setFunctionBreakpoints", - arguments: { - breakpoints: [ - - ] - }, - type: "request" - }, - { - seq: 4, - type: "response", - command: "setFunctionBreakpoints", - request_seq: 3, - success: true, - message: "Success" - }, - { - seq: 4, - command: "setExceptionBreakpoints", - arguments: { - filters: [ - - ], - filterOptions: [ - - ] - }, - type: "request" - }, - { - seq: 5, - type: "response", - command: "setExceptionBreakpoints", - request_seq: 4, - success: true, - message: "Success", - body: { - breakpoints: [ - - ] - } - }, - { - seq: 5, - command: "configurationDone", - type: "request" - }, - { - seq: 6, - type: "response", - command: "configurationDone", - request_seq: 5, - success: true, - message: "Success" - }, - { - seq: 6, - command: "threads", - type: "request" - }, - { - seq: 7, - type: "response", - command: "threads", - request_seq: 6, - success: true, - message: "Success", - body: { - threads: [ - { - id: 1, - name: /#1 .*/ - } - ] - } - }, - { - seq: 7, - command: "pause", - arguments: { - threadId: 1 - }, - type: "request" - }, - { - seq: 8, - type: "response", - command: "pause", - request_seq: 7, - success: true, - message: "Success" - }, - { - seq: 9, - type: "event", - event: "stopped", - body: { - reason: "pause", - threadId: 1, - allThreadsStopped: true - } - }, - { - seq: 8, - command: "threads", - type: "request" - }, - { - seq: 10, - type: "response", - command: "threads", - request_seq: 8, - success: true, - message: "Success", - body: { - threads: [ - { - id: 1, - name: /#1 .*/ - } - ] - } - }, - { - seq: 9, - command: "stackTrace", - arguments: { - threadId: 1, - startFrame: 0, - levels: 20 - }, - type: "request" - }, - { - seq: 11, - type: "response", - command: "stackTrace", - request_seq: 9, - success: true, - message: "Success", - body: { - stackFrames: [ - { - id: 2, - name: "block in ", - line: 9, - column: 1, - source: { - name: /#{File.basename temp_file_path}/, - path: /#{temp_file_path}/, - sourceReference: 0 - } - }, - { - id: 3, - name: "[C] Kernel#loop", - line: 7, - column: 1, - source: { - name: /#{File.basename temp_file_path}/, - path: /#{temp_file_path}/, - sourceReference: 0 - } - }, - { - id: 4, - name: "", - line: 7, - column: 1, - source: { - name: /#{File.basename temp_file_path}/, - path: /#{temp_file_path}/, - sourceReference: 0 - } - }, - { - id: 5, - name: "
", - line: 1, - column: 1, - source: { - name: /#{File.basename temp_file_path}/, - path: /#{temp_file_path}/, - sourceReference: 0 - } - } - ], - totalFrames: 4 - } - }, - { - seq: 10, - command: "scopes", - arguments: { - frameId: 2 - }, - type: "request" - }, - { - seq: 12, - type: "response", - command: "scopes", - request_seq: 10, - success: true, - message: "Success", - body: { - scopes: [ - { - name: "Local variables", - presentationHint: "locals", - namedVariables: /\d+/, - indexedVariables: 0, - expensive: false, - variablesReference: 4 - }, - { - name: "Global variables", - presentationHint: "globals", - variablesReference: 1, - namedVariables: /\d+/, - indexedVariables: 0, - expensive: false - } - ] - } - }, - { - seq: 11, - command: "variables", - arguments: { - variablesReference: 4 - }, - type: "request" - }, - { - seq: 13, - type: "response", - command: "variables", - request_seq: 11, - success: true, - message: "Success", - body: { - variables: [ - { - name: "%self", - value: "Foo", - type: "Module", - variablesReference: 5, - indexedVariables: 0, - namedVariables: /\d+/ - }, - { - name: "b", - value: "1", - type: "Integer", - variablesReference: 6, - indexedVariables: 0, - namedVariables: /\d+/ - }, - { - name: "bar", - value: "nil", - type: "NilClass", - variablesReference: 7, - indexedVariables: 0, - namedVariables: /\d+/ - } - ] - } - }, - { - seq: 12, - command: "disconnect", - arguments: { - restart: false, - terminateDebuggee: true - }, - type: "request" - } - ] - end - end - end -end diff --git a/test/protocol/eval_test.rb b/test/protocol/eval_test.rb index 635ea814e..8f78128f7 100644 --- a/test/protocol/eval_test.rb +++ b/test/protocol/eval_test.rb @@ -13,13 +13,71 @@ class EvalTest < ProtocolTestCase 6| f = 6 RUBY - def test_eval_evaluates_arithmetic_expressions + def test_eval_evaluates_expressions run_protocol_scenario PROGRAM do req_add_breakpoint 5 req_continue assert_repl_result({value: '2', type: 'Integer'}, 'a') assert_repl_result({value: '4', type: 'Integer'}, 'd') assert_repl_result({value: '3', type: 'Integer'}, '1+2') + assert_repl_result({value: 'false', type: 'FalseClass'}, 'a == 1') + req_terminate_debuggee + end + end + + def test_eval_executes_commands + run_protocol_scenario PROGRAM, cdp: false do + req_add_breakpoint 3 + req_continue + assert_repl_result({value: '(rdbg:command) b 5 ;; b 6', type: nil}, ",b 5 ;; b 6") + req_continue + assert_line_num 5 + req_continue + assert_line_num 6 + req_terminate_debuggee + end + end + end + + class EvaluateOnSomeFramesTest < ProtocolTestCase + PROGRAM = <<~RUBY + 1| a = 2 + 2| def foo + 3| a = 4 + 4| end + 5| foo + RUBY + + def test_eval_evaluates_arithmetic_expressions + omit 'this test is fragile on older versions' if RUBY_VERSION < '3.4.0' + run_protocol_scenario PROGRAM do + req_add_breakpoint 4 + req_continue + assert_repl_result({value: '4', type: 'Integer'}, 'a', frame_idx: 0) + assert_repl_result({value: '2', type: 'Integer'}, 'a', frame_idx: 1) + req_terminate_debuggee + end + end + end + + class EvaluateThreadTest < ProtocolTestCase + PROGRAM = <<~RUBY + 1| th0 = Thread.new{sleep} + 2| m = Mutex.new; q = Queue.new + 3| th1 = Thread.new do + 4| m.lock; q << true + 5| sleep 1 + 6| m.unlock + 7| end + 8| q.pop # wait for locking + 9| p :ok + RUBY + + def test_eval_with_threads + run_protocol_scenario PROGRAM, cdp: false do + req_add_breakpoint 9 + req_continue + assert_repl_result({value: 'false', type: 'FalseClass'}, 'm.lock.nil?', frame_idx: 0) req_terminate_debuggee end end diff --git a/test/protocol/hover_raw_cdp_test.rb b/test/protocol/hover_raw_cdp_test.rb index ef4004535..cb2499960 100644 --- a/test/protocol/hover_raw_cdp_test.rb +++ b/test/protocol/hover_raw_cdp_test.rb @@ -4,7 +4,7 @@ module DEBUGGER__ - class HoverTest1647163915 < ProtocolTestCase + class HoverTest1680367110 < ProtocolTestCase PROGRAM = <<~RUBY 1| a = 1 2| b = 2 @@ -14,7 +14,7 @@ class HoverTest1647163915 < ProtocolTestCase RUBY - def test_1647163915 + def test_1680367110 run_cdp_scenario PROGRAM do [ *INITIALIZE_CDP_MSGS, @@ -177,125 +177,18 @@ def test_1647163915 }, { id: 10, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 10, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Object" - }, - configurable: true, - enumerable: true - }, - { - name: "a", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - }, - { - name: "b", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - }, - { - name: "c", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - }, - { - name: "d", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - }, - { - name: "e", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 11, - method: "Debugger.getPossibleBreakpoints", - params: { - start: { - scriptId: "1", - lineNumber: 0, - columnNumber: 0 - }, - restrictToFunction: true - } - }, - { - id: 11, - result: { - locations: [ - { - scriptId: /.+/, - lineNumber: 0 - } - ] - } - }, - { - id: 12, method: "Debugger.setBreakpointsActive", params: { active: true } }, { - id: 12, + id: 10, result: { } }, { - id: 13, + id: 11, method: "Debugger.setBreakpointByUrl", params: { lineNumber: 3, @@ -305,7 +198,7 @@ def test_1647163915 } }, { - id: 13, + id: 11, result: { breakpointId: /.+/, locations: [ @@ -317,7 +210,7 @@ def test_1647163915 } }, { - id: 14, + id: 12, method: "Debugger.getPossibleBreakpoints", params: { start: { @@ -334,7 +227,7 @@ def test_1647163915 } }, { - id: 14, + id: 12, result: { locations: [ { @@ -345,14 +238,14 @@ def test_1647163915 } }, { - id: 15, + id: 13, method: "Debugger.resume", params: { terminateOnResume: false } }, { - id: 15, + id: 13, result: { } }, @@ -361,19 +254,6 @@ def test_1647163915 params: { } }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 5, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, { method: "Debugger.paused", params: { @@ -422,18 +302,7 @@ def test_1647163915 } }, { - id: 16, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 17, + id: 14, method: "Runtime.getProperties", params: { objectId: "0:local", @@ -444,80 +313,7 @@ def test_1647163915 } }, { - id: 16, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Object" - }, - configurable: true, - enumerable: true - }, - { - name: "a", - value: { - type: "number", - description: /.+/, - value: 1, - objectId: /.+/ - }, - configurable: true, - enumerable: true - }, - { - name: "b", - value: { - type: "number", - description: /.+/, - value: 2, - objectId: /.+/ - }, - configurable: true, - enumerable: true - }, - { - name: "c", - value: { - type: "number", - description: /.+/, - value: 3, - objectId: /.+/ - }, - configurable: true, - enumerable: true - }, - { - name: "d", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - }, - { - name: "e", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 17, + id: 14, result: { result: [ { @@ -590,10 +386,10 @@ def test_1647163915 } }, { - id: 18, + id: 15, method: "Debugger.evaluateOnCallFrame", params: { - callFrameId: "b0517caf9ad3aa17aec13bda2d6a7e41", + callFrameId: "749f0545d098a59afc45091a1b8edc35", expression: "c", objectGroup: "popover", includeCommandLineAPI: false, @@ -616,7 +412,7 @@ def test_1647163915 } }, { - id: 18, + id: 15, result: { result: { type: "number", @@ -627,22 +423,22 @@ def test_1647163915 } }, { - id: 19, + id: 16, method: "Runtime.releaseObjectGroup", params: { objectGroup: "popover" } }, { - id: 19, + id: 16, result: { } }, { - id: 20, + id: 17, method: "Debugger.evaluateOnCallFrame", params: { - callFrameId: "b0517caf9ad3aa17aec13bda2d6a7e41", + callFrameId: "749f0545d098a59afc45091a1b8edc35", expression: "b", objectGroup: "popover", includeCommandLineAPI: false, @@ -665,7 +461,7 @@ def test_1647163915 } }, { - id: 20, + id: 17, result: { result: { type: "number", @@ -676,22 +472,22 @@ def test_1647163915 } }, { - id: 21, + id: 18, method: "Runtime.releaseObjectGroup", params: { objectGroup: "popover" } }, { - id: 21, + id: 18, result: { } }, { - id: 22, + id: 19, method: "Debugger.evaluateOnCallFrame", params: { - callFrameId: "b0517caf9ad3aa17aec13bda2d6a7e41", + callFrameId: "749f0545d098a59afc45091a1b8edc35", expression: "a", objectGroup: "popover", includeCommandLineAPI: false, @@ -714,7 +510,7 @@ def test_1647163915 } }, { - id: 22, + id: 19, result: { result: { type: "number", @@ -725,26 +521,26 @@ def test_1647163915 } }, { - id: 23, + id: 20, method: "Runtime.releaseObjectGroup", params: { objectGroup: "popover" } }, { - id: 23, + id: 20, result: { } }, { - id: 24, + id: 21, method: "Debugger.resume", params: { terminateOnResume: false } }, { - id: 24, + id: 21, result: { } } diff --git a/test/protocol/next_raw_cdp_test.rb b/test/protocol/next_raw_cdp_test.rb index 25278cda0..b26999c65 100644 --- a/test/protocol/next_raw_cdp_test.rb +++ b/test/protocol/next_raw_cdp_test.rb @@ -4,7 +4,7 @@ module DEBUGGER__ - class NextTest1647162227 < ProtocolTestCase + class NextTest1680366131 < ProtocolTestCase PROGRAM = <<~RUBY 1| module Foo 2| class Bar @@ -18,7 +18,7 @@ class NextTest1647162227 < ProtocolTestCase RUBY - def test_1647162227 + def test_1680366131 run_cdp_scenario PROGRAM do [ *INITIALIZE_CDP_MSGS, @@ -126,44 +126,15 @@ def test_1647162227 }, { id: 10, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 10, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Object" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 11, method: "Debugger.stepOver", params: { skipList: [ - + ] } }, { - id: 11, + id: 10, result: { } }, @@ -172,32 +143,6 @@ def test_1647162227 params: { } }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, { method: "Debugger.paused", params: { @@ -285,18 +230,7 @@ def test_1647162227 } }, { - id: 12, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 13, + id: 11, method: "Runtime.getProperties", params: { objectId: "0:local", @@ -307,36 +241,7 @@ def test_1647162227 } }, { - id: 12, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Module" - }, - configurable: true, - enumerable: true - }, - { - name: "bar", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 13, + id: 11, result: { result: [ { @@ -365,16 +270,16 @@ def test_1647162227 } }, { - id: 14, + id: 12, method: "Debugger.stepOver", params: { skipList: [ - + ] } }, { - id: 14, + id: 12, result: { } }, @@ -383,45 +288,6 @@ def test_1647162227 params: { } }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, { method: "Debugger.paused", params: { @@ -548,18 +414,7 @@ def test_1647162227 } }, { - id: 15, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 16, + id: 13, method: "Runtime.getProperties", params: { objectId: "0:local", @@ -570,25 +425,7 @@ def test_1647162227 } }, { - id: 15, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Class" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 16, + id: 13, result: { result: [ { @@ -606,16 +443,16 @@ def test_1647162227 } }, { - id: 17, + id: 14, method: "Debugger.stepOver", params: { skipList: [ - + ] } }, { - id: 17, + id: 14, result: { } }, @@ -624,32 +461,6 @@ def test_1647162227 params: { } }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, { method: "Debugger.paused", params: { @@ -737,18 +548,7 @@ def test_1647162227 } }, { - id: 18, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 19, + id: 15, method: "Runtime.getProperties", params: { objectId: "0:local", @@ -759,36 +559,7 @@ def test_1647162227 } }, { - id: 18, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Module" - }, - configurable: true, - enumerable: true - }, - { - name: "bar", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 19, + id: 15, result: { result: [ { @@ -817,16 +588,16 @@ def test_1647162227 } }, { - id: 20, + id: 16, method: "Debugger.stepOver", params: { skipList: [ - + ] } }, { - id: 20, + id: 16, result: { } }, @@ -835,32 +606,6 @@ def test_1647162227 params: { } }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, { method: "Debugger.paused", params: { @@ -948,18 +693,7 @@ def test_1647162227 } }, { - id: 21, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 22, + id: 17, method: "Runtime.getProperties", params: { objectId: "0:local", @@ -970,36 +704,7 @@ def test_1647162227 } }, { - id: 21, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Module" - }, - configurable: true, - enumerable: true - }, - { - name: "bar", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 22, + id: 17, result: { result: [ { @@ -1028,16 +733,16 @@ def test_1647162227 } }, { - id: 23, + id: 18, method: "Debugger.stepOver", params: { skipList: [ - + ] } }, { - id: 23, + id: 18, result: { } }, diff --git a/test/protocol/rdbgTraceInspctor_test.rb b/test/protocol/rdbgTraceInspctor_test.rb new file mode 100644 index 000000000..f42049b63 --- /dev/null +++ b/test/protocol/rdbgTraceInspctor_test.rb @@ -0,0 +1,218 @@ +# frozen_string_literal: true + +require_relative '../support/protocol_test_case' + +module DEBUGGER__ + class RdbgTraceInspectorTraceTest < ProtocolTestCase + PROGRAM = <<~RUBY + 1| def foo + 2| 'bar' + 3| end + 4| foo + 5| foo + RUBY + + def test_defaut_setting + DEBUGGER__::INITIALIZE_DAP_MSGS[1][:arguments][:rdbgExtensions] = ["traceInspector"] + run_protocol_scenario(PROGRAM, cdp: false) do + req_rdbgTraceInspector_trace_enable + req_add_breakpoint 5 + req_continue + assert_rdbgTraceInspector_trace_collect_result( + [ + { + returnValue: "\"bar\"", + name: 'Object#foo', + location: { + line: 3, + } + }, + { + name: 'Object#foo', + location: { + line: 1, + } + }, + { + location: { + line: 4, + } + }, + ] + ) + req_terminate_debuggee + end + ensure + DEBUGGER__::INITIALIZE_DAP_MSGS[1][:arguments].delete :rdbgExtensions + end + + def test_call_event + DEBUGGER__::INITIALIZE_DAP_MSGS[1][:arguments][:rdbgExtensions] = ["traceInspector"] + run_protocol_scenario(PROGRAM, cdp: false) do + req_rdbgTraceInspector_trace_enable(events: ['traceCall']) + req_add_breakpoint 5 + req_continue + assert_rdbgTraceInspector_trace_collect_result( + [ + { + name: 'Object#foo', + location: { + line: 1, + } + }, + ] + ) + req_terminate_debuggee + end + ensure + DEBUGGER__::INITIALIZE_DAP_MSGS[1][:arguments].delete :rdbgExtensions + end + + def test_return_event + DEBUGGER__::INITIALIZE_DAP_MSGS[1][:arguments][:rdbgExtensions] = ["traceInspector"] + run_protocol_scenario(PROGRAM, cdp: false) do + req_rdbgTraceInspector_trace_enable(events: ['traceReturn']) + req_add_breakpoint 5 + req_continue + assert_rdbgTraceInspector_trace_collect_result( + [ + { + returnValue: "\"bar\"", + name: 'Object#foo', + location: { + line: 3, + } + }, + ] + ) + req_terminate_debuggee + end + ensure + DEBUGGER__::INITIALIZE_DAP_MSGS[1][:arguments].delete :rdbgExtensions + end + + def test_line_event + DEBUGGER__::INITIALIZE_DAP_MSGS[1][:arguments][:rdbgExtensions] = ["traceInspector"] + run_protocol_scenario(PROGRAM, cdp: false) do + req_rdbgTraceInspector_trace_enable(events: ['traceLine']) + req_add_breakpoint 5 + req_continue + assert_rdbgTraceInspector_trace_collect_result( + [ + { + location: { + line: 4, + } + }, + ] + ) + req_terminate_debuggee + end + ensure + DEBUGGER__::INITIALIZE_DAP_MSGS[1][:arguments].delete :rdbgExtensions + end + + def test_restart_trace + DEBUGGER__::INITIALIZE_DAP_MSGS[1][:arguments][:rdbgExtensions] = ["traceInspector"] + run_protocol_scenario(PROGRAM, cdp: false) do + req_rdbgTraceInspector_trace_enable + req_rdbgTraceInspector_trace_disable + req_rdbgTraceInspector_trace_enable(events: ['traceLine']) + req_add_breakpoint 5 + req_continue + assert_rdbgTraceInspector_trace_collect_result( + [ + { + location: { + line: 4, + } + }, + ] + ) + req_terminate_debuggee + end + ensure + DEBUGGER__::INITIALIZE_DAP_MSGS[1][:arguments].delete :rdbgExtensions + end + end + + class RdbgTraceInspectorRecordTest < ProtocolTestCase + PROGRAM = <<~RUBY + 1| module Foo + 2| class Bar + 3| def self.a + 4| "hello" + 5| end + 6| end + 7| Bar.a + 8| bar = Bar.new + 9| end + RUBY + + def test_defaut_setting + DEBUGGER__::INITIALIZE_DAP_MSGS[1][:arguments][:rdbgExtensions] = ["traceInspector"] + run_protocol_scenario(PROGRAM, cdp: false) do + req_rdbgTraceInspector_record_enable + req_add_breakpoint 5 + req_continue + assert_rdbgTraceInspector_record_collect_result( + [ + { + name: "", + location: { + line: 2, + } + }, + { + name: "", + location: { + line: 3, + } + } + ] + ) + req_rdbgTraceInspector_record_step_back 4 + assert_line_num 2 + req_rdbgTraceInspector_record_step 1 + assert_line_num 3 + req_terminate_debuggee + end + ensure + DEBUGGER__::INITIALIZE_DAP_MSGS[1][:arguments].delete :rdbgExtensions + end + + def test_restart_trace + DEBUGGER__::INITIALIZE_DAP_MSGS[1][:arguments][:rdbgExtensions] = ["traceInspector"] + run_protocol_scenario(PROGRAM, cdp: false) do + req_rdbgTraceInspector_record_enable + req_rdbgTraceInspector_record_disable + req_rdbgTraceInspector_record_enable + req_add_breakpoint 5 + req_continue + assert_rdbgTraceInspector_record_collect_result( + [ + { + name: "", + location: { + line: 2, + } + }, + { + name: "", + location: { + line: 3, + } + } + ] + ) + req_rdbgTraceInspector_record_step_back 4 + assert_line_num 2 + req_rdbgTraceInspector_record_step 1 + assert_line_num 3 + req_terminate_debuggee + end + ensure + DEBUGGER__::INITIALIZE_DAP_MSGS[1][:arguments].delete :rdbgExtensions + end + end +end diff --git a/test/protocol/step_raw_cdp_test.rb b/test/protocol/step_raw_cdp_test.rb index 435f6ff91..b9083d1a2 100644 --- a/test/protocol/step_raw_cdp_test.rb +++ b/test/protocol/step_raw_cdp_test.rb @@ -4,7 +4,7 @@ module DEBUGGER__ - class StepTest1647142777 < ProtocolTestCase + class StepTest1680366703 < ProtocolTestCase PROGRAM = <<~RUBY 1| module Foo 2| class Bar @@ -18,23 +18,10 @@ class StepTest1647142777 < ProtocolTestCase RUBY - def test_1647142777 + def test_1680366703 run_cdp_scenario PROGRAM do [ *INITIALIZE_CDP_MSGS, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, { method: "Debugger.paused", params: { @@ -126,35 +113,6 @@ def test_1647142777 }, { id: 10, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 10, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Object" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 11, method: "Debugger.stepInto", params: { breakOnAsyncCall: true, @@ -164,7 +122,7 @@ def test_1647142777 } }, { - id: 11, + id: 10, result: { } }, @@ -173,32 +131,6 @@ def test_1647142777 params: { } }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, { method: "Debugger.paused", params: { @@ -286,18 +218,7 @@ def test_1647142777 } }, { - id: 12, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 13, + id: 11, method: "Runtime.getProperties", params: { objectId: "0:local", @@ -308,36 +229,7 @@ def test_1647142777 } }, { - id: 12, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Module" - }, - configurable: true, - enumerable: true - }, - { - name: "bar", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 13, + id: 11, result: { result: [ { @@ -366,7 +258,7 @@ def test_1647142777 } }, { - id: 14, + id: 12, method: "Debugger.stepInto", params: { breakOnAsyncCall: true, @@ -376,7 +268,7 @@ def test_1647142777 } }, { - id: 14, + id: 12, result: { } }, @@ -385,45 +277,6 @@ def test_1647142777 params: { } }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, { method: "Debugger.paused", params: { @@ -550,36 +403,7 @@ def test_1647142777 } }, { - id: 15, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 15, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Class" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 16, + id: 13, method: "Runtime.getProperties", params: { objectId: "0:local", @@ -590,7 +414,7 @@ def test_1647142777 } }, { - id: 16, + id: 13, result: { result: [ { @@ -608,7 +432,7 @@ def test_1647142777 } }, { - id: 17, + id: 14, method: "Debugger.stepInto", params: { breakOnAsyncCall: true, @@ -618,7 +442,7 @@ def test_1647142777 } }, { - id: 17, + id: 14, result: { } }, @@ -627,32 +451,6 @@ def test_1647142777 params: { } }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, { method: "Debugger.paused", params: { @@ -740,18 +538,7 @@ def test_1647142777 } }, { - id: 18, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 19, + id: 15, method: "Runtime.getProperties", params: { objectId: "0:local", @@ -762,36 +549,7 @@ def test_1647142777 } }, { - id: 18, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Module" - }, - configurable: true, - enumerable: true - }, - { - name: "bar", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 19, + id: 15, result: { result: [ { @@ -820,7 +578,7 @@ def test_1647142777 } }, { - id: 20, + id: 16, method: "Debugger.stepInto", params: { breakOnAsyncCall: true, @@ -830,7 +588,7 @@ def test_1647142777 } }, { - id: 20, + id: 16, result: { } }, @@ -839,45 +597,6 @@ def test_1647142777 params: { } }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, { method: "Debugger.paused", params: { @@ -1004,18 +723,7 @@ def test_1647142777 } }, { - id: 21, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 22, + id: 17, method: "Runtime.getProperties", params: { objectId: "0:local", @@ -1026,25 +734,7 @@ def test_1647142777 } }, { - id: 21, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Class" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 22, + id: 17, result: { result: [ { @@ -1062,7 +752,7 @@ def test_1647142777 } }, { - id: 23, + id: 18, method: "Debugger.stepInto", params: { breakOnAsyncCall: true, @@ -1072,7 +762,7 @@ def test_1647142777 } }, { - id: 23, + id: 18, result: { } }, @@ -1081,45 +771,6 @@ def test_1647142777 params: { } }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, { method: "Debugger.paused", params: { @@ -1246,18 +897,7 @@ def test_1647142777 } }, { - id: 24, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 25, + id: 19, method: "Runtime.getProperties", params: { objectId: "0:local", @@ -1268,36 +908,7 @@ def test_1647142777 } }, { - id: 24, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Class" - }, - configurable: true, - enumerable: true - }, - { - name: "_return", - value: { - type: "string", - description: /.+/, - value: /.+/, - objectId: /.+/ - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 25, + id: 19, result: { result: [ { @@ -1326,7 +937,7 @@ def test_1647142777 } }, { - id: 26, + id: 20, method: "Debugger.stepInto", params: { breakOnAsyncCall: true, @@ -1336,7 +947,7 @@ def test_1647142777 } }, { - id: 26, + id: 20, result: { } }, @@ -1345,32 +956,6 @@ def test_1647142777 params: { } }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 9, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, { method: "Debugger.paused", params: { @@ -1458,18 +1043,7 @@ def test_1647142777 } }, { - id: 27, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 28, + id: 21, method: "Runtime.getProperties", params: { objectId: "0:local", @@ -1480,36 +1054,7 @@ def test_1647142777 } }, { - id: 27, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Module" - }, - configurable: true, - enumerable: true - }, - { - name: "bar", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 28, + id: 21, result: { result: [ { @@ -1538,7 +1083,7 @@ def test_1647142777 } }, { - id: 29, + id: 22, method: "Debugger.stepInto", params: { breakOnAsyncCall: true, @@ -1548,7 +1093,7 @@ def test_1647142777 } }, { - id: 29, + id: 22, result: { } }, diff --git a/test/protocol/threads_test.rb b/test/protocol/threads_test.rb index dc97bad1f..b27a4229f 100644 --- a/test/protocol/threads_test.rb +++ b/test/protocol/threads_test.rb @@ -20,8 +20,8 @@ def test_reponse_returns_correct_threads_info assert_threads_result( [ - /\.rb:\d:in `
'/, - /\.rb:\d:in `block in foo'/ + /\.rb:\d:in [`']
'/, + /\.rb:\d:in [`']block in (Object#)?foo'/ ] ) diff --git a/test/protocol/variables_test.rb b/test/protocol/variables_test.rb new file mode 100644 index 000000000..9b82419e8 --- /dev/null +++ b/test/protocol/variables_test.rb @@ -0,0 +1,158 @@ +# frozen_string_literal: true + +require_relative "../support/protocol_test_case" + +module DEBUGGER__ + class DAPGlobalVariablesTest < ProtocolTestCase + PROGRAM = <<~RUBY + 1| $a = 1 + 2| $b = 2 + 3| $c = 3 + RUBY + + def test_eval_evaluates_global_variables + run_protocol_scenario PROGRAM, cdp: false do + req_add_breakpoint 3 + req_continue + + globals = gather_variables(type: "globals") + + # User defined globals + assert_includes(globals, { name: "$a", value: "1", type: "Integer", variablesReference: 0 }) + assert_includes(globals, { name: "$b", value: "2", type: "Integer", variablesReference: 0 }) + + # Ruby defined globals + assert_includes(globals, { name: "$VERBOSE", value: "false", type: "FalseClass", variablesReference: 0 }) + assert_includes(globals, { name: "$stdout", value: "#>", type: "IO", variablesReference: 0 }) + + req_terminate_debuggee + end + end + end + + class CDPGlobalVariablesTest < ProtocolTestCase + PROGRAM = <<~RUBY + 1| $a = 1 + 2| $b = 2 + 3| $c = 3 + RUBY + + def test_eval_evaluates_global_variables + run_protocol_scenario PROGRAM, dap: false do + req_add_breakpoint 3 + req_continue + + globals = gather_variables(type: "global") + + # User defined globals + assert_includes(globals, { name: "$a", value: "1", type: "Number" }) + assert_includes(globals, { name: "$b", value: "2", type: "Number" }) + + # Ruby defined globals + assert_includes(globals, { name: "$VERBOSE", value: "false", type: "Boolean" }) + assert_includes(globals, { name: "$stdout", value: "#>", type: "Object" }) + + req_terminate_debuggee + end + end + end + + class DAPInstanceVariableTest < ProtocolTestCase + PROGRAM = <<~RUBY + 1| @a = 1 + 2| @c = 3 + 3| @b = 2 + 4| __LINE__ + RUBY + + def test_ordering_instance_variables + run_protocol_scenario PROGRAM, cdp: false do + req_add_breakpoint 4 + req_continue + + locals = gather_variables + + variables_reference = locals.find { |local| local[:name] == "%self" }[:variablesReference] + res = send_dap_request 'variables', variablesReference: variables_reference + + instance_vars = res.dig(:body, :variables) + assert_equal instance_vars.map { |var| var[:name] }, ["#class", "@a", "@b", "@c"] + + req_terminate_debuggee + end + end + end + + class DAPOverwrittenNameMethod < ProtocolTestCase + PROGRAM = <<~RUBY + 1| class Foo + 2| def self.name(value) end + 3| end + 4| f = Foo.new + 5| __LINE__ + RUBY + + def test_overwritten_name_method + run_protocol_scenario PROGRAM, cdp: false do + req_add_breakpoint 5 + req_continue + + locals = gather_variables + + variable_info = locals.find { |local| local[:name] == "f" } + + assert_match(/\#/, variable_info[:value]) + assert_equal "Foo", variable_info[:type] + + req_terminate_debuggee + end + end + end + + class DAPOverwrittenClassMethod < ProtocolTestCase + PROGRAM = <<~RUBY + 1| class Foo + 2| def self.class(value) end + 3| end + 4| f = Foo.new + 5| __LINE__ + RUBY + + def test_overwritten_class_method + run_protocol_scenario PROGRAM, cdp: false do + req_add_breakpoint 5 + req_continue + + locals = gather_variables + + variable_info = locals.find { |local| local[:name] == "f" } + assert_match(/\#/, variable_info[:value]) + assert_equal "Foo", variable_info[:type] + + req_terminate_debuggee + end + end + end + + class DAPAnonymousClassInstance < ProtocolTestCase + PROGRAM = <<~RUBY + 1| f = Class.new.new + 2| __LINE__ + RUBY + + def test_anonymous_class_instance + run_protocol_scenario PROGRAM, cdp: false do + req_add_breakpoint 2 + req_continue + + locals = gather_variables + + variable_info = locals.find { |local| local[:name] == "f" } + assert_match(/\#/, variable_info[:value]) + assert_match(/\#/, variable_info[:type]) + + req_terminate_debuggee + end + end + end +end diff --git a/test/protocol/watch_raw_cdp_test.rb b/test/protocol/watch_raw_cdp_test.rb index 656d7c8ee..f836e4d6f 100644 --- a/test/protocol/watch_raw_cdp_test.rb +++ b/test/protocol/watch_raw_cdp_test.rb @@ -3,7 +3,7 @@ require_relative '../support/protocol_test_case' module DEBUGGER__ - class WatchTest1647161607 < ProtocolTestCase + class WatchTest1680367761 < ProtocolTestCase PROGRAM = <<~RUBY 1| a = 2 2| a += 1 @@ -14,7 +14,7 @@ class WatchTest1647161607 < ProtocolTestCase 7| f = 6 RUBY - def test_1647161607 + def test_1680367761 run_cdp_scenario PROGRAM do [ *INITIALIZE_CDP_MSGS, @@ -166,129 +166,9 @@ def test_1647161607 }, { id: 10, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 10, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Object" - }, - configurable: true, - enumerable: true - }, - { - name: "a", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - }, - { - name: "d", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - }, - { - name: "e", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - }, - { - name: "f", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 11, - method: "Runtime.getProperties", - params: { - objectId: "0:script", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 12, - method: "Runtime.getProperties", - params: { - objectId: "0:global", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: false - } - }, - { - id: 11, - result: { - result: [ - - ] - } - }, - { - id: 12, - result: { - result: [ - - ] - } - }, - { - id: 13, - method: "Runtime.evaluate", - params: { - expression: "(async function(){ await 1; })()", - contextId: "50d169823cddf0a4b6ce990dd7e51844", - throwOnSideEffect: true - } - }, - { - id: 14, method: "Debugger.evaluateOnCallFrame", params: { - callFrameId: "0f91c69d774fa115d355aa58101be1e3", + callFrameId: "a126f00649ca00f0b32aba84149b1ea9", expression: "a", objectGroup: "watch-group", includeCommandLineAPI: false, @@ -311,7 +191,7 @@ def test_1647161607 } }, { - id: 14, + id: 10, result: { result: { type: "object", @@ -322,7 +202,7 @@ def test_1647161607 } }, { - id: 15, + id: 11, method: "Debugger.stepOver", params: { skipList: [ @@ -331,7 +211,7 @@ def test_1647161607 } }, { - id: 15, + id: 11, result: { } }, @@ -340,19 +220,6 @@ def test_1647161607 params: { } }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 7, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, { method: "Debugger.paused", params: { @@ -401,33 +268,44 @@ def test_1647161607 } }, { - id: 16, - method: "Runtime.evaluate", + id: 12, + method: "Debugger.evaluateOnCallFrame", params: { + callFrameId: "a126f00649ca00f0b32aba84149b1ea9", expression: "a", objectGroup: "watch-group", includeCommandLineAPI: false, silent: true, returnByValue: false, - generatePreview: false, - userGesture: false, - awaitPromise: false, - contextId: "50d169823cddf0a4b6ce990dd7e51844" + generatePreview: false } }, { - id: 17, - method: "Runtime.getProperties", + method: "Debugger.scriptParsed", params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true + scriptId: /.+/, + url: "", + startLine: 0, + startColumn: 0, + endLine: 1, + endColumn: 0, + executionContextId: 1, + hash: /.+/ } }, { - id: 18, + id: 12, + result: { + result: { + type: "number", + description: /.+/, + value: 2, + objectId: /.+/ + } + } + }, + { + id: 13, method: "Runtime.getProperties", params: { objectId: "0:local", @@ -438,69 +316,7 @@ def test_1647161607 } }, { - id: 17, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Object" - }, - configurable: true, - enumerable: true - }, - { - name: "a", - value: { - type: "number", - description: /.+/, - value: 2, - objectId: /.+/ - }, - configurable: true, - enumerable: true - }, - { - name: "d", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - }, - { - name: "e", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - }, - { - name: "f", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 18, + id: 13, result: { result: [ { @@ -562,10 +378,10 @@ def test_1647161607 } }, { - id: 19, + id: 14, method: "Debugger.evaluateOnCallFrame", params: { - callFrameId: "4214a828add392fa49b2b22782a4d3fd", + callFrameId: "6942cc45103f29405a912664c8e4f1fc", expression: "a", objectGroup: "watch-group", includeCommandLineAPI: false, @@ -588,7 +404,7 @@ def test_1647161607 } }, { - id: 19, + id: 14, result: { result: { type: "number", @@ -599,7 +415,7 @@ def test_1647161607 } }, { - id: 20, + id: 15, method: "Debugger.stepOver", params: { skipList: [ @@ -608,7 +424,7 @@ def test_1647161607 } }, { - id: 20, + id: 15, result: { } }, @@ -617,19 +433,6 @@ def test_1647161607 params: { } }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 7, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, { method: "Debugger.paused", params: { @@ -678,10 +481,10 @@ def test_1647161607 } }, { - id: 21, + id: 16, method: "Debugger.evaluateOnCallFrame", params: { - callFrameId: "249684c74b6e52ac6ef45990ece6e164", + callFrameId: "6942cc45103f29405a912664c8e4f1fc", expression: "a", objectGroup: "watch-group", includeCommandLineAPI: false, @@ -704,7 +507,7 @@ def test_1647161607 } }, { - id: 21, + id: 16, result: { result: { type: "number", @@ -715,18 +518,7 @@ def test_1647161607 } }, { - id: 22, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 23, + id: 17, method: "Runtime.getProperties", params: { objectId: "0:local", @@ -737,69 +529,7 @@ def test_1647161607 } }, { - id: 22, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Object" - }, - configurable: true, - enumerable: true - }, - { - name: "a", - value: { - type: "number", - description: /.+/, - value: 3, - objectId: /.+/ - }, - configurable: true, - enumerable: true - }, - { - name: "d", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - }, - { - name: "e", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - }, - { - name: "f", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 23, + id: 17, result: { result: [ { @@ -861,10 +591,10 @@ def test_1647161607 } }, { - id: 24, + id: 18, method: "Debugger.evaluateOnCallFrame", params: { - callFrameId: "249684c74b6e52ac6ef45990ece6e164", + callFrameId: "59cd2941422d2a90b887393f6ab12291", expression: "a", objectGroup: "watch-group", includeCommandLineAPI: false, @@ -887,7 +617,7 @@ def test_1647161607 } }, { - id: 24, + id: 18, result: { result: { type: "number", @@ -898,7 +628,7 @@ def test_1647161607 } }, { - id: 25, + id: 19, method: "Debugger.stepOver", params: { skipList: [ @@ -907,7 +637,7 @@ def test_1647161607 } }, { - id: 25, + id: 19, result: { } }, @@ -916,19 +646,6 @@ def test_1647161607 params: { } }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 7, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, { method: "Debugger.paused", params: { @@ -959,146 +676,73 @@ def test_1647161607 object: { type: "object", objectId: /.+/ - } - }, - { - type: "global", - object: { - type: "object", - objectId: /.+/ - } - } - ], - this: { - type: "object" - } - } - ] - } - }, - { - id: 26, - method: "Debugger.evaluateOnCallFrame", - params: { - callFrameId: "c9845cfbf14bfb534a516247d28e699d", - expression: "a", - objectGroup: "watch-group", - includeCommandLineAPI: false, - silent: true, - returnByValue: false, - generatePreview: false - } - }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: "", - startLine: 0, - startColumn: 0, - endLine: 1, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, - { - id: 26, - result: { - result: { - type: "number", - description: /.+/, - value: 4, - objectId: /.+/ - } - } - }, - { - id: 27, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 28, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 27, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Object" - }, - configurable: true, - enumerable: true - }, - { - name: "a", - value: { - type: "number", - description: /.+/, - value: 4, - objectId: /.+/ - }, - configurable: true, - enumerable: true - }, - { - name: "d", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - }, - { - name: "e", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - }, - { - name: "f", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true + } + }, + { + type: "global", + object: { + type: "object", + objectId: /.+/ + } + } + ], + this: { + type: "object" + } } ] } }, { - id: 28, + id: 20, + method: "Debugger.evaluateOnCallFrame", + params: { + callFrameId: "59cd2941422d2a90b887393f6ab12291", + expression: "a", + objectGroup: "watch-group", + includeCommandLineAPI: false, + silent: true, + returnByValue: false, + generatePreview: false + } + }, + { + method: "Debugger.scriptParsed", + params: { + scriptId: /.+/, + url: "", + startLine: 0, + startColumn: 0, + endLine: 1, + endColumn: 0, + executionContextId: 1, + hash: /.+/ + } + }, + { + id: 20, + result: { + result: { + type: "number", + description: /.+/, + value: 4, + objectId: /.+/ + } + } + }, + { + id: 21, + method: "Runtime.getProperties", + params: { + objectId: "0:local", + ownProperties: false, + accessorPropertiesOnly: false, + nonIndexedPropertiesOnly: false, + generatePreview: true + } + }, + { + id: 21, result: { result: [ { @@ -1160,10 +804,10 @@ def test_1647161607 } }, { - id: 29, + id: 22, method: "Debugger.evaluateOnCallFrame", params: { - callFrameId: "c9845cfbf14bfb534a516247d28e699d", + callFrameId: "75b24efedc7d4376c056f9de46e682e2", expression: "a", objectGroup: "watch-group", includeCommandLineAPI: false, @@ -1186,7 +830,7 @@ def test_1647161607 } }, { - id: 29, + id: 22, result: { result: { type: "number", @@ -1197,7 +841,7 @@ def test_1647161607 } }, { - id: 30, + id: 23, method: "Debugger.stepOver", params: { skipList: [ @@ -1206,7 +850,7 @@ def test_1647161607 } }, { - id: 30, + id: 23, result: { } }, @@ -1215,19 +859,6 @@ def test_1647161607 params: { } }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 7, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, { method: "Debugger.paused", params: { @@ -1276,10 +907,10 @@ def test_1647161607 } }, { - id: 31, + id: 24, method: "Debugger.evaluateOnCallFrame", params: { - callFrameId: "b5aa856edfac6fd69923bad78711fb57", + callFrameId: "75b24efedc7d4376c056f9de46e682e2", expression: "a", objectGroup: "watch-group", includeCommandLineAPI: false, @@ -1302,7 +933,7 @@ def test_1647161607 } }, { - id: 31, + id: 24, result: { result: { type: "number", @@ -1313,18 +944,7 @@ def test_1647161607 } }, { - id: 32, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 33, + id: 25, method: "Runtime.getProperties", params: { objectId: "0:local", @@ -1335,69 +955,7 @@ def test_1647161607 } }, { - id: 32, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Object" - }, - configurable: true, - enumerable: true - }, - { - name: "a", - value: { - type: "number", - description: /.+/, - value: 4, - objectId: /.+/ - }, - configurable: true, - enumerable: true - }, - { - name: "d", - value: { - type: "number", - description: /.+/, - value: 4, - objectId: /.+/ - }, - configurable: true, - enumerable: true - }, - { - name: "e", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - }, - { - name: "f", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 33, + id: 25, result: { result: [ { @@ -1459,10 +1017,10 @@ def test_1647161607 } }, { - id: 34, + id: 26, method: "Debugger.evaluateOnCallFrame", params: { - callFrameId: "b5aa856edfac6fd69923bad78711fb57", + callFrameId: "f09c1dd6f3726f4615e1eecee097699d", expression: "a", objectGroup: "watch-group", includeCommandLineAPI: false, @@ -1485,7 +1043,7 @@ def test_1647161607 } }, { - id: 34, + id: 26, result: { result: { type: "number", @@ -1496,7 +1054,7 @@ def test_1647161607 } }, { - id: 35, + id: 27, method: "Debugger.stepOver", params: { skipList: [ @@ -1505,7 +1063,7 @@ def test_1647161607 } }, { - id: 35, + id: 27, result: { } }, @@ -1514,19 +1072,6 @@ def test_1647161607 params: { } }, - { - method: "Debugger.scriptParsed", - params: { - scriptId: /.+/, - url: /.+/, - startLine: 0, - startColumn: 0, - endLine: 7, - endColumn: 0, - executionContextId: 1, - hash: /.+/ - } - }, { method: "Debugger.paused", params: { @@ -1575,10 +1120,10 @@ def test_1647161607 } }, { - id: 36, + id: 28, method: "Debugger.evaluateOnCallFrame", params: { - callFrameId: "c0cea16455b6ec62f97edc6eadec2006", + callFrameId: "f09c1dd6f3726f4615e1eecee097699d", expression: "a", objectGroup: "watch-group", includeCommandLineAPI: false, @@ -1601,7 +1146,7 @@ def test_1647161607 } }, { - id: 36, + id: 28, result: { result: { type: "number", @@ -1612,18 +1157,7 @@ def test_1647161607 } }, { - id: 37, - method: "Runtime.getProperties", - params: { - objectId: "0:local", - ownProperties: false, - accessorPropertiesOnly: false, - nonIndexedPropertiesOnly: false, - generatePreview: true - } - }, - { - id: 38, + id: 29, method: "Runtime.getProperties", params: { objectId: "0:local", @@ -1634,69 +1168,7 @@ def test_1647161607 } }, { - id: 37, - result: { - result: [ - { - name: "%self", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "Object" - }, - configurable: true, - enumerable: true - }, - { - name: "a", - value: { - type: "number", - description: /.+/, - value: 5, - objectId: /.+/ - }, - configurable: true, - enumerable: true - }, - { - name: "d", - value: { - type: "number", - description: /.+/, - value: 4, - objectId: /.+/ - }, - configurable: true, - enumerable: true - }, - { - name: "e", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - }, - { - name: "f", - value: { - type: "object", - description: /.+/, - objectId: /.+/, - className: "NilClass" - }, - configurable: true, - enumerable: true - } - ] - } - }, - { - id: 38, + id: 29, result: { result: [ { @@ -1758,10 +1230,10 @@ def test_1647161607 } }, { - id: 39, + id: 30, method: "Debugger.evaluateOnCallFrame", params: { - callFrameId: "c0cea16455b6ec62f97edc6eadec2006", + callFrameId: "17f8a6576d5c28763f42a0c7aadd3e4b", expression: "a", objectGroup: "watch-group", includeCommandLineAPI: false, @@ -1784,7 +1256,7 @@ def test_1647161607 } }, { - id: 39, + id: 30, result: { result: { type: "number", @@ -1795,14 +1267,14 @@ def test_1647161607 } }, { - id: 40, + id: 31, method: "Debugger.resume", params: { terminateOnResume: false } }, { - id: 40, + id: 31, result: { } } diff --git a/test/support/assertions_test.rb b/test/support/assertions_test.rb index d03ad5dfb..e964c7b6a 100644 --- a/test/support/assertions_test.rb +++ b/test/support/assertions_test.rb @@ -49,6 +49,30 @@ def test_the_helper_raises_an_error_with_invalid_expectation end end end + + def test_the_test_fails_when_debuggee_on_unix_domain_socket_mode_doesnt_exist_after_scenarios + assert_raise_message(/Expected to include `"foobar\\\\?/) do + prepare_test_environment(program, steps) do + debug_code_on_unix_domain_socket() + end + end + end + + def test_the_test_fails_when_debuggee_on_tcpip_mode_doesnt_exist_after_scenarios + assert_raise_message(/Expected to include `"foobar\\\\?/) do + prepare_test_environment(program, steps) do + debug_code_on_tcpip() + end + end + end + + private + + def steps + Proc.new{ + assert_line_text("foobar?") + } + end end end diff --git a/test/support/console_test_case.rb b/test/support/console_test_case.rb index 1f42fa438..b174f9f96 100644 --- a/test/support/console_test_case.rb +++ b/test/support/console_test_case.rb @@ -18,10 +18,10 @@ class ConsoleTestCase < TestCase pwd = Dir.pwd ruby = ENV['RUBY'] || RbConfig.ruby home_cannot_change = false - PTY.spawn({ "HOME" => pwd }, ruby, '-e', 'puts ENV["HOME"]') do |r,| + PTY.spawn({ "HOME" => pwd }, ruby, '-e', 'puts ENV["HOME"]; sleep 0.1') do |r,| home_cannot_change = r.gets.chomp != pwd end - home_cannot_change + !home_cannot_change end class << self @@ -85,20 +85,20 @@ def create_message fail_msg, test_info MSG end - def debug_code(program, remote: true, &test_steps) - Timeout.timeout(30) do + def debug_code(program, remote: true, verbose: false, &test_steps) + Timeout.timeout(60) do prepare_test_environment(program, test_steps) do if remote && !NO_REMOTE && MULTITHREADED_TEST begin th = [ - new_thread { debug_code_on_local }, + (new_thread { debug_code_on_local } unless remote == :remote_only), new_thread { debug_code_on_unix_domain_socket }, new_thread { debug_code_on_tcpip }, - ] + ].compact th.each do |t| if fail_msg = t.join.value - th.each(&:kill) + th.each{|t| t.raise Test::Unit::AssertionFailedError} flunk fail_msg end end @@ -109,17 +109,17 @@ def debug_code(program, remote: true, &test_steps) th.each {|t| t.join} end elsif remote && !NO_REMOTE - debug_code_on_local + debug_code_on_local verbose: verbose unless remote == :remote_only debug_code_on_unix_domain_socket debug_code_on_tcpip else - debug_code_on_local + debug_code_on_local verbose: verbose unless remote == :remote_only end end end end - def run_test_scenario cmd, test_info + def run_test_scenario cmd, test_info, verbose: false PTY.spawn({ "HOME" => pty_home_dir }, cmd) do |read, write, pid| test_info.backlog = [] test_info.last_backlog = [] @@ -176,24 +176,42 @@ def run_test_scenario cmd, test_info check_error(/DEBUGGEE Exception/, test_info) assert_empty_queue test_info end + + if r = test_info.remote_info + assert_program_finish test_info, r.pid, :debuggee + end + + assert_program_finish test_info, pid, :debugger # result of `gets` return this exception in some platform # https://github.com/ruby/ruby/blob/master/ext/pty/pty.c#L729-L736 rescue Errno::EIO => e check_error(/DEBUGGEE Exception/, test_info) assert_empty_queue test_info, exception: e + if r = test_info.remote_info + assert_program_finish test_info, r.pid, :debuggee + end + + assert_program_finish test_info, pid, :debugger + # result of `gets` return this exception in some platform rescue Timeout::Error assert_block(create_message("TIMEOUT ERROR (#{TIMEOUT_SEC} sec)", test_info)) { false } + rescue Test::Unit::AssertionFailedError + is_assertion_failure = true + raise ensure - kill_remote_debuggee test_info + kill_remote_debuggee test_info, force: is_assertion_failure # kill debug console process read.close write.close - kill_safely pid, :debugger, test_info - if name = test_info.failed_process - assert_block(create_message("Expected the #{name} program to finish", test_info)) { false } - end + kill_safely pid, force: is_assertion_failure end end + ensure + pp backlog: test_info.backlog if verbose + end + + def assert_program_finish test_info, pid, name + assert_block(create_message("Expected the #{name} program to finish", test_info)) { wait_pid pid, TIMEOUT_SEC } end def prepare_test_environment(program, test_steps, &block) @@ -201,12 +219,18 @@ def prepare_test_environment(program, test_steps, &block) ENV['RUBY_DEBUG_TEST_UI'] = 'terminal' ENV['RUBY_DEBUG_NO_RELINE'] = 'true' ENV['RUBY_DEBUG_HISTORY_FILE'] = '' + ENV['TERM'] = 'dumb' write_temp_file(strip_line_num(program)) @scenario = [] test_steps.call @scenario.freeze - inject_lib_to_load_path + + ENV['RUBYOPT'] = "-I #{__dir__}/../../lib" + + if ENV.key?('BUNDLE_GEMFILE') + ENV["RUBYOPT"] += " -rbundler/setup" + end block.call @@ -232,10 +256,10 @@ def manual_debug_code(program) kill_remote_debuggee remote_info end - private def debug_code_on_local + private def debug_code_on_local verbose: false test_info = TestInfo.new(dup_scenario, 'LOCAL', /\(rdbg\)/) cmd = "#{RDBG_EXECUTABLE} #{temp_file_path}" - run_test_scenario cmd, test_info + run_test_scenario cmd, test_info, verbose: verbose end private def debug_code_on_unix_domain_socket @@ -264,7 +288,7 @@ def run_rdbg program, options: nil, rubyopt: nil, &test_steps prepare_test_environment(program, test_steps) do test_info = TestInfo.new(dup_scenario, 'LOCAL', /\(rdbg\)/) cmd = "#{RDBG_EXECUTABLE} #{options} -- #{temp_file_path}" - cmd = "RUBYOPT=#{rubyopt} #{cmd}" if rubyopt + ENV["RUBYOPT"] += " #{rubyopt}" if rubyopt run_test_scenario cmd, test_info end end @@ -282,10 +306,6 @@ def new_thread &block end end - def inject_lib_to_load_path - ENV['RUBYOPT'] = "-I #{__dir__}/../../lib" - end - def assert_empty_queue test_info, exception: nil message = "Expected all commands/assertions to be executed. Still have #{test_info.queue.length} left." if exception diff --git a/test/support/protocol_test_case.rb b/test/support/protocol_test_case.rb index a2c3414e3..78e0b5bb0 100644 --- a/test/support/protocol_test_case.rb +++ b/test/support/protocol_test_case.rb @@ -1,7 +1,6 @@ require 'net/http' require 'uri' require 'digest/sha1' -require 'base64' require_relative 'test_case' require_relative 'dap_utils' @@ -65,30 +64,9 @@ def attach_to_dap_server end def attach_to_cdp_server - body = get_request HOST, @remote_info.port, '/json' - Timeout.timeout(TIMEOUT_SEC) do - sleep 0.001 until @remote_info.debuggee_backlog.join.include? 'Disconnected.' - end - - sock = Socket.tcp HOST, @remote_info.port - uuid = body[0][:id] - - Timeout.timeout(TIMEOUT_SEC) do - sleep 0.001 until @remote_info.debuggee_backlog.join.match?(/Disconnected\.\R.*Connected/) - end - - @web_sock = WebSocketClient.new sock - @web_sock.handshake @remote_info.port, uuid - @id = 1 - @reader_thread = Thread.new do - while res = @web_sock.extract_data - @queue.push res - end - rescue Detach + retry_connect do + attach_to_cdp_server_ end - sleep 0.001 while @reader_thread.status != 'sleep' - @reader_thread.run - INITIALIZE_CDP_MSGS.each{|msg| send(**msg)} end def req_dap_disconnect(terminate_debuggee:) @@ -133,6 +111,7 @@ def req_continue case get_target_ui when 'vscode' send_dap_request 'continue', threadId: 1 + find_response :event, 'stopped', 'V e + is_assertion_failure = true + raise e ensure + if is_assertion_failure + kill_remote_debuggee(test_info, force: true) + else + if kill_remote_debuggee(test_info) + flunk create_protocol_message "Expected the debuggee program to finish" + end + end + # Because the debuggee may be terminated by executing the following operations, we need to run them after `kill_remote_debuggee` method. @reader_thread&.kill @sock&.close - kill_remote_debuggee test_info - if name = test_info.failed_process - flunk create_protocol_message "Expected the debuggee program to finish" - end end def execute_cdp_scenario_ scenario @@ -364,19 +447,32 @@ def execute_cdp_scenario_ scenario res = find_response :method, 'Debugger.paused', 'C e + is_assertion_failure = true + raise e ensure + if is_assertion_failure + kill_remote_debuggee(test_info, force: true) + else + if kill_remote_debuggee(test_info) + flunk create_protocol_message "Expected the debuggee program to finish" + end + end + # Because the debuggee may be terminated by executing the following operations, we need to run them after `kill_remote_debuggee` method. @reader_thread&.kill @web_sock&.close - kill_remote_debuggee test_info - if name = test_info.failed_process - flunk create_protocol_message "Expected the debuggee program to finish" - end end def execute_cdp_scenario scenario + retry_connect do + execute_cdp_scenario_ scenario + end + end + + def retry_connect retry_cnt = 0 begin - execute_cdp_scenario_ scenario + yield rescue Errno::ECONNREFUSED if (retry_cnt += 1) > 10 STDERR.puts "retry #{retry_cnt} but can not connect!" @@ -441,10 +537,10 @@ def close_reader HOST = '127.0.0.1' JAVASCRIPT_TYPE_TO_CLASS_MAPS = { - 'string' => String, - 'number' => Integer, - 'boolean' => [TrueClass, FalseClass], - 'symbol' => Symbol + 'string' => "String", + 'number' => "Integer", + 'boolean' => ["TrueClass", "FalseClass"], + 'symbol' => "Symbol" } def assert_eval_result context, expression, expected, frame_idx @@ -483,7 +579,7 @@ def assert_eval_result context, expression, expected, frame_idx failure_msg = FailureMessage.new{create_protocol_message "result:\n#{JSON.pretty_generate res}"} - cl = res.dig(:result, :result, :className) || JAVASCRIPT_TYPE_TO_CLASS_MAPS[res.dig(:result, :result, :type)].inspect + cl = res.dig(:result, :result, :className) || JAVASCRIPT_TYPE_TO_CLASS_MAPS[res.dig(:result, :result, :type)] result_type = Array cl assert_include result_type, expected[:type], failure_msg @@ -524,6 +620,11 @@ def send_dap_request command, **kw res end + def send_custom_dap_request command, **kw + send_request command, **kw + return find_crt_dap_response + end + def send_cdp_request command, **kw send_request command, **kw res = find_crt_cdp_response @@ -826,7 +927,7 @@ def handshake port, uuid @sock.print "GET /#{uuid} HTTP/1.1\r\nHost: 127.0.0.1:#{port}\r\nConnection: Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Key: #{key}==\r\n\r\n" server_key = get_server_key - correct_key = Base64.strict_encode64 Digest::SHA1.digest "#{key}==258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + correct_key = Digest::SHA1.base64digest "#{key}==258EAFA5-E914-47DA-95CA-C5AB0DC85B11" raise "The Sec-WebSocket-Accept value: #{$1} is not valid" unless server_key == correct_key end @@ -1065,4 +1166,3 @@ def parse_ k, v end end end - diff --git a/test/support/protocol_test_case_test.rb b/test/support/protocol_test_case_test.rb index d9e687f9b..1b1c723cf 100644 --- a/test/support/protocol_test_case_test.rb +++ b/test/support/protocol_test_case_test.rb @@ -3,14 +3,31 @@ require_relative 'protocol_test_case' module DEBUGGER__ - class TestFrameworkTestHOge < ProtocolTestCase - PROGRAM = <<~RUBY - 1| a=1 - RUBY - + class TestProtocolTestCase < ProtocolTestCase def test_the_test_fails_when_debuggee_doesnt_exit + omit "too slow now" + + program = <<~RUBY + 1| a=1 + RUBY + assert_fail_assertion do - run_protocol_scenario PROGRAM do + run_protocol_scenario program do + end + end + end + + def test_the_assertion_failure_takes_presedence_over_debuggee_not_exiting + program = <<~RUBY + 1| a = 2 + 2| b = 3 + RUBY + + assert_raise_message(/<\"100\"> expected but was/) do + run_protocol_scenario program do + req_add_breakpoint 2 + req_continue + assert_repl_result({value: '100', type: 'Integer'}, 'a') end end end diff --git a/test/support/test_case.rb b/test/support/test_case.rb index e5e0dd9e4..9797975f2 100644 --- a/test/support/test_case.rb +++ b/test/support/test_case.rb @@ -7,14 +7,22 @@ require 'timeout' require 'json' require 'rbconfig' +require 'fileutils' require_relative '../../lib/debug/client' require_relative 'assertions' +# Load this library only in the debug CI to prevent LoadError +# when these tests are executed in ruby/ruby. +if ENV['LAUNCHABLE_ORGANIZATION'] && ENV['LAUNCHABLE_WORKSPACE'] + # "test/unit/runner/launchable" is used for uploading test result to Launchable. + require "test/unit/runner/launchable" +end + module DEBUGGER__ class TestCase < Test::Unit::TestCase TestInfo = Struct.new(:queue, :mode, :prompt_pattern, :remote_info, - :backlog, :last_backlog, :internal_info, :failed_process) + :backlog, :last_backlog, :internal_info) RemoteInfo = Struct.new(:r, :w, :pid, :sock_path, :port, :reader_thread, :debuggee_backlog) @@ -118,19 +126,23 @@ def wait_pid pid, sec end false + rescue Errno::ECHILD + true end - def kill_safely pid, name, test_info - return if wait_pid pid, TIMEOUT_SEC - - test_info.failed_process = name + def kill_safely pid, force: false + unless force + return false if wait_pid pid, TIMEOUT_SEC + end Process.kill :TERM, pid - return if wait_pid pid, 0.2 + return true if wait_pid pid, 0.2 Process.kill :KILL, pid Process.waitpid(pid) + true rescue Errno::EPERM, Errno::ESRCH + true end def check_error(error, test_info) @@ -139,23 +151,46 @@ def check_error(error, test_info) end end - def kill_remote_debuggee test_info - return unless r = test_info.remote_info + def kill_remote_debuggee test_info, force: false + return false unless r = test_info.remote_info - kill_safely r.pid, :remote, test_info + force_killed = kill_safely r.pid, force: force r.reader_thread.kill # Because the debuggee may be terminated by executing the following operations, we need to run them after `kill_safely` method. r.r.close r.w.close + force_killed end def setup_remote_debuggee(cmd) homedir = defined?(self.class.pty_home_dir) ? self.class.pty_home_dir : ENV['HOME'] remote_info = DEBUGGER__::TestCase::RemoteInfo.new(*PTY.spawn({'HOME' => homedir}, cmd)) - remote_info.r.read(1) # wait for the remote server to boot up remote_info.debuggee_backlog = [] + line = nil + msg1 = msg2 = nil + + Timeout.timeout(TIMEOUT_SEC) do + line = remote_info.r.gets + line = line.scrub if line + remote_info.debuggee_backlog << line + + # wait for two lines (order is unstable) + case line + when /\ADEBUGGER: Debugger can attach via/ + msg1 = true + when /\ADEBUGGER: wait for debugger connection/ + msg2 = true + else + # unknown lines + STDERR.puts "> #{line}" + end + + break if msg1 && msg2 + redo # loop + end + remote_info.reader_thread = Thread.new(remote_info) do |info| while data = info.r.gets info.debuggee_backlog << data @@ -179,14 +214,19 @@ def setup_unix_domain_socket_remote_debuggee remote_info end - # search free port by opening server socket with port 0 - Socket.tcp_server_sockets(0).tap do |ss| - TCPIP_PORT = ss.first.local_address.ip_port - end.each{|s| s.close} - def setup_tcpip_remote_debuggee - remote_info = setup_remote_debuggee("#{RDBG_EXECUTABLE} -O --port=#{TCPIP_PORT} -- #{temp_file_path}") - remote_info.port = TCPIP_PORT + remote_info = setup_remote_debuggee("#{RDBG_EXECUTABLE} -O --port=0 -- #{temp_file_path}") + port = nil + remote_info.debuggee_backlog.each{|line| + if /Debugger can attach via TCP\/IP \(.+:(\d+)\)/ =~ line + port = $1.to_i + end + } + raise "can not find TCP/IP port with backlog: #{remote_info.debuggee_backlog.inspect}" unless port + remote_info.port = port + Timeout.timeout(TIMEOUT_SEC) do + sleep 0.001 until remote_info.debuggee_backlog.join.include? remote_info.port.to_s + end remote_info end @@ -198,11 +238,11 @@ def get_request host, port, path sock.print "GET #{path} HTTP/1.1\r\n" sock.close_write loop do - case header = sock.gets + case sock.gets when /Content-Length: (\d+)/ b = sock.read(2) raise b.inspect unless b == "\r\n" - + l = sock.read $1.to_i return JSON.parse l, symbolize_names: true end diff --git a/test/support/test_case_test.rb b/test/support/test_case_test.rb index 929c67d56..ec2f28403 100644 --- a/test/support/test_case_test.rb +++ b/test/support/test_case_test.rb @@ -12,7 +12,7 @@ def program def test_the_test_fails_when_debugger_exits_early assert_raise_message(/Expected all commands\/assertions to be executed/) do - debug_code(program) do + debug_code(program, remote: false) do type 'continue' type 'foo' end @@ -35,7 +35,7 @@ def test_the_test_work_when_debuggee_outputs_many_lines def test_the_test_fails_when_the_repl_prompt_does_not_finish_even_though_scenario_is_empty assert_raise_message(/Expected the REPL prompt to finish/) do - debug_code(program) do + debug_code(program, remote: false) do end end end @@ -61,7 +61,9 @@ def steps end def test_the_test_fails_when_debuggee_on_unix_domain_socket_mode_doesnt_exist_after_scenarios - assert_raise_message(/Expected the remote program to finish/) do + omit "too slow now" + + assert_raise_message(/Expected the debuggee program to finish/) do prepare_test_environment(program, steps) do debug_code_on_unix_domain_socket() end @@ -69,7 +71,9 @@ def test_the_test_fails_when_debuggee_on_unix_domain_socket_mode_doesnt_exist_af end def test_the_test_fails_when_debuggee_on_tcpip_mode_doesnt_exist_after_scenarios - assert_raise_message(/Expected the remote program to finish/) do + omit "too slow now" + + assert_raise_message(/Expected the debuggee program to finish/) do prepare_test_environment(program, steps) do debug_code_on_tcpip() end diff --git a/test/tool/test_builder.rb b/test/tool/test_builder.rb index 5553ea599..45fe10843 100644 --- a/test/tool/test_builder.rb +++ b/test/tool/test_builder.rb @@ -157,7 +157,7 @@ def #{@method} def create_scenario_and_program <<-TEST.chomp - class #{@class}#{@current_time} < TestCase + class #{@class}#{@current_time} < ConsoleTestCase def program <<~RUBY #{format_program} @@ -477,7 +477,7 @@ def activate_debugger when /\[\>\]\s(.*)/ begin req = JSON.parse $1 - rescue JSON::ParserError => e + rescue JSON::ParserError $stderr.print data next end @@ -504,7 +504,7 @@ def activate_debugger when /\[\<\]\s(.*)/ begin res = JSON.parse $1 - rescue JSON::ParserError => e + rescue JSON::ParserError $stderr.print data next end