Skip to content

Fix support for the DevTools protocol #32404

Closed

Description

@eerii

Hi! As part of the Outreachy project this year I will be working on supporting DevTools again, making them work with the current versions of Servo and Firefox. This is a meta issue that gathers all of the information in a place that can be easily referenced, and in which updates on the state of the project can be provided. Please do add anything you might consider useful or necessary to the discussion!

Roadmap

Current state

The DevTools connection prompt is functional and Firefox can find Servo. Tabs with their titles are listed in the overview. Now you can see the inspector window with the DOM tree and use the console to run Javascript on Servo. Support for css styling is being worked on.

There is some progress in the HTML department (Servo on the left, Firefox on the right). You can start to see the DOM structure and modify tags.

image

Open Issues

Recent (~2023-24)

These are the more relevant to restoring support for DevTools. It was broken around June 2023 and it is confirmed not to work properly from Firefox 110 onward.

#29831 : Main issue that details the broken support and previous attempts to fix it.

Mid (~2020-2022)

These are from a time where DevTools worked, but these issues were never presumably solved, so if we get it up and running again it may be good to look if they are still relevant.

#26667 : Reporting unhandled promise rejections didn't work
#26368 : Errors navigating DevTools
#26323 : Unreported network events
#25119 : Make it so DevTools can be started later

Older (~2013-2019)

Outdated but interesting issues.

#8973 : Old experiment to create a standalone HTML UI of the Firefox DevTools
#4957 : Add support for the debug timeline

Previous work

This section only includes relevant prs since DevTools were broken last year.

#32227 : Great pr from @oSoMoN that fixes how Servo is displayed in the about:debugging Firefox page and removes some warnings.
fabricedesre@0c41bf4 : Work done by @fabricedesre to update the DevTools implementation to conform to the new Firefox changes. It may be a good place to start.

Links to useful documentation

Activity

  1. added
    B-feature-tracking
    C-untriaged
    on May 29, 2024
  2. added and removed
    C-untriaged
    on May 30, 2024
  3. eerii commented on Jun 14, 2024

    @eerii
    MemberAuthor

    How to debug RDP messages

    One key part of restoring the DevTools support is correctly sending the proper messages through the RDP (remote debugging protocol). However, the message fields for each action between actors are not well documented, making it tricky to know exactly what to send.

    Servo can easily show the messages it sent and the ones it received from the DevTools server. It's as easy as enabling the correct logging level when running the program.

    RUST_LOG="error,devtools=debug" ./mach run --devtools=1234

    This is very useful to see if the message is properly formatted, but what about creating new messages? How could you find the correct fields and format? One idea is to run another instance of Firefox, which fully supports the entire protocol as both a server and a client, and see what happens between the two.

    Starting another Firefox instance

    To connect remotely via DevTools you need to go to about:debugging, just like you would for testing Servo. Here you can connect to multiple instances of Firefox (desktop or mobile) and other supported browsers. If you have an Android phone, you can connect it via USB and it should show up. For this example, I will be running another instance of Firefox on my laptop, but the process should be similar with a phone.

    One restriction that Firefox has is that you can't run multiple instances of the same profile. There are several options here, either downloading something like Firefox Developer Edition, which comes with another profile, or simply navigating to .mozilla/firefox (in Linux) and making a copy of your profile with another name. You can find more about profiles here.

    Now we can run another instance of Firefox with the debugging server enabled (this is important!) using this command:

    firefox --new-instance --start-debugger-server 1234 --profile ~/.mozilla/firefox/NAME

    Another window should pop up, and it likely has a robot on the search bar that indicates that we are running it in debugging mode.

    image

    Before being able to connect to it, there are a few settings that we have to change in the new profile. This only needs to be done and it can be done either modifying user.js or going to about:config (on the new browser window) and searching for each option.

    devtools.chrome.enabled = true
    devtools.debugger.remote-enabled = true
    devtools.debugger.prompt-connection = false # This is optional but helpful
    

    Inspecting the new instance

    Going back to the first browser, in about:debugging we can add a connection to the new instance that we created. Under Setup -> Network Location, add localhost:1234 (the same port as before). This is the same setup that needs to be done when debugging Servo.

    image

    Now, with the other instance still running, we can click Connect in the sidebar. It should show information about our other browser, like tab names and workers.

    image

    Intercepting the messages

    The messages between DevTools and the browser are sent as JSON payloads through a websocket. One would think that the browser console would be able to show them. In Multiprocess mode and targeting the browser itself and not the webpage it does indicate that there are messages being sent, but they don't seem to contain the relevant data. I also tried logging with MOZ_LOG but it wasn't very fruitful either.

    image

    Wireshark is a very useful network packet analyzer, and we can configure it to listen to this traffic. Open Wireshark and select the loopback intercept. This should start logging packets sent inside of your local network.

    This can be very messy, specially if you have some other services open, but we can refine it easily by filtering by the specified port and only showing JSON: tcp.port == 1234 && tcp.payload.

    image

    Here you can start seeing the messages and the responses. For example, this experiment started with me trying to implement the response to the getWatcher message. The way it is shown in Wireshark is not very easy to inspect, and it has a lot of extra information. Thankfully, Wireshark can export the packets' readable text, or you can use a tool like tcpdump -A -r capture.pcapng to batch show all of the decoded packet descriptions.

    image

    Finally, I want to mention geckordp, a complete implementation of the DevTools remote protocol in python which had very useful insights on how to inspect network packets and the general API design.

    Updated current progress: After being able to check the correct message format, I am working on implementing a Watcher Actor so that inspecting a webpage is functional again!

  4. eerii commented on Jul 2, 2024

    @eerii
    MemberAuthor

    Update on debugging messages

    Following up on the previous comment, I made the workflow of debugging messages a bit more straightforward. Launching wireshark, creating a capture, saving it, processing it and trying to read it every time was a bit cumbersome, so I created a small python script to automate the process. It can either take an existing .pcap file or launch tshark (wireshark's command line tool) with the appropriate parameters to start listening. Then, it processes the JSON, separates messages that are batched on the same call and pretty prints it so it is more legible. It can also filter by word or by a range of messages. Here is a small preview:

    There are still some edge cases with some messages that are so big that they are spread across multiple packets, but it is enough for now. It has proven very useful to know the format of the needed messages. Here is the source code:

    #!/usr/bin/env python3
    
    import json
    import re
    import signal
    import sys
    from argparse import ArgumentParser
    from datetime import datetime as dt
    from subprocess import Popen, PIPE
    try:
        from termcolor import colored
    except ImportError:
        def colored(text, *args, **kwargs):
            return text
    
    fields = ["frame.time", "tcp.srcport", "tcp.payload"]
    pattern = r"(\d+:){"
    
    # Use tshark to capture network traffic and save the result in a
    # format that this tool can process later
    def record_data(file, port):
        # Create tshark command
        cmd = [
            "tshark",
            "-T", "fields",
            "-i", "lo",
            "-d", f"tcp.port=={port},http",
            "-w", file,
        ] + [ e for f in fields for e in ("-e", f) ]
        process = Popen(cmd, stdout=PIPE)
    
        # Stop the analysis when using Ctrl+C
        def signal_handler(sig, frame):
            process.kill()
    
        signal.signal(signal.SIGINT, signal_handler)
        signal.pause()
    
        # Get the output
        out, err = process.communicate()
        out = out.decode("utf-8")
        
        return out
    
    # Read a pcap data file from tshark (or wireshark) and extract
    # the necessary output fields
    def read_data(file):
        # Create tshark command
        cmd = [
            "tshark",
            "-T", "fields",
            "-r", file,
        ] + [ e for f in fields for e in ("-e", f) ]
        process = Popen(cmd, stdout=PIPE)
    
        # Get the output
        out, err = process.communicate()
        out = out.decode("utf-8")
    
        return out
    
    # Transform the raw output of wireshark into a more manageable one
    def process_data(out, port):
        out = [l.split("\t") for l in out.split("\n")]
    
        # Process fields
        data = []
        for l in out:
            if len(l) != 3:
                continue
    
            curr_time, curr_port, curr_data = l
    
            try:
                # Time
                curr_time = curr_time.split(" ")[-2].split(".")[0]
                # Port
                curr_port = "Servo" if curr_port == port else "Firefox"
                # Data
                if not curr_data:
                    continue 
                dec = bytearray.fromhex(curr_data).decode()
            except:
                continue
    
            indices = [m.span() for m in re.finditer(pattern, dec)]
            indices.append((len(dec), -1))
            prev = 0
    
            for min, max in indices:
                if min > 0:
                    text = dec[prev-1:min]
                    data.append([curr_time, curr_port, len(data), text])
                prev = max
    
        return data
    
    # Pretty prints the json message
    def parse_message(msg):
        time, sender, i, data = msg
        from_servo = sender == "Servo"
    
        print(f"\n{colored(sender, 'black', 'on_yellow' if from_servo else 'on_magenta', attrs=['bold'])} - {colored(i, 'blue')} - {colored(time, 'dark_grey')}")
    
        try:
            content = json.loads(data)
            if from_servo and "from" in content:
                print(colored(f"Actor: {content['from']}", 'yellow'))
            print(json.dumps(content, sort_keys=True, indent=4))
            print()
        except:
            print("Warning: Couldn't decode json")
            print(data)
    
    if __name__ == "__main__":
        # Program arguments
        parser = ArgumentParser()
        parser.add_argument("-p", "--port", default="1234", help="the port where the devtools client is running")
        parser.add_argument("-f", "--filter", help="search for the string on the messages")
        parser.add_argument("-r", "--range", help="only parse messages from n to m, with the form of n:m")
        
        actions = parser.add_mutually_exclusive_group(required=True)
        actions.add_argument("-s", "--scan", help="scan and save the output to a file")
        actions.add_argument("-u", "--use", help="use the scan from a file")
        
        args = parser.parse_args()
    
        # Get the scan data
        if args.scan:
            data = record_data(args.scan, args.port)
        else:
             with open(args.use, "r") as f:
                data = read_data(args.use)
    
        data = process_data(data, args.port)
    
        min, max = 0, -2
        if args.range and len(args.range.split(":")) == 2:
            min, max = args.range.split(":")
    
        for msg in data[int(min):int(max)+1]:
            if not args.filter or args.filter.lower() in msg[3].lower():
                parse_message(msg)

    Finally, I was going to add a function where it converted the JSON objects into rust structs, but I found out this awesome website that automatically does it following Serde conventions and properly renaming fields, and I don't want to reinvent the wheel.

    image

    That's it for now! I am working on implementing the inspector again, currently I am adding all of the available CSS properties so that you can edit them. Sending the source code of the page is up next c:

  5. jdm commented on Jul 2, 2024

    @jdm
    Member

    Could you add that script under etc/ so it's easy to find in the future?

  6. eerii commented on Jul 3, 2024

    @eerii
    MemberAuthor

    Could you add that script under etc/ so it's easy to find in the future?

    Absolutely! I will clean it up a bit and open a pull request for it. Thanks for the suggestion.

    Edit: I opened #32684

  7. eerii commented on Apr 9, 2026

    @eerii
    MemberAuthor

    I'm going to close this now since support for DevTools has improved quite a bit. There are still issues and tabs that could use better support, but we are tracking those in separate meta issues (i.e. #36027 and #39858). I feel like this one was mostly related to the scope of the initial Outreachy internship. Also, the documentation from the comments is already in the book.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-devtoolsB-feature-tracking

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions