Search code examples
javascriptdebuggingchromiumv8

Can Chromium print JS source code before it's parsed?


I want to print or log JS source before it's compiled into bytecode. I've tried various js-flags without success so far. Is it possible? If so, what's the process?

Example HTML/JS:

 <html> <head>
 <script type="text/javascript"> alert('newtext'); </script>
 </head></html>

I'd like to expose "alert('newtext')".

I've made a number of attempt but can only get downstream code:

 chromium --no-sandbox file:///...html --js-flags="--log-source-code" -> byte code
 chromium --no-sandbox file:///...html --js-flags="--log-source-code" -> memory chunk addresses

I'm also trying to compile chromium with debugging enabled without success so far.


Solution

  • (V8 developer here.)

    Before it's parsed, no component of Chromium except for the network stack has a reason to even look at JavaScript code. I would hence have suggested the DevTools "Network" tab, but your example uses an inline <script> tag, which of course won't show up as a separate download.

    When a chunk of JS is passed to V8, V8 immediately parses it (what else should it do with it?). There doesn't seem to be an existing flag to dump incoming source code, presumably because that isn't interesting for V8 development. You could probably add such dumping to bool ParseProgram(...) in v8/src/parsing/parsing.cc, roughly as follows:

    diff --git a/src/parsing/parsing.cc b/src/parsing/parsing.cc
    index 8c55a6fb6e..91850c1d45 100644
    --- a/src/parsing/parsing.cc
    +++ b/src/parsing/parsing.cc
    @@ -47,6 +47,9 @@ bool ParseProgram(ParseInfo* info, Handle<Script> script,
    
       // Create a character stream for the parser.
       Handle<String> source(String::cast(script->source()), isolate);
    +
    +  source->StringPrint(std::cout);
    +
       std::unique_ptr<Utf16CharacterStream> stream(
           ScannerStream::For(isolate, source));
       info->set_character_stream(std::move(stream));
    

    (Note: I haven't tested this.)