Is it possible to view the machine code (x86 instructions) that a browser ultimately generates from my JavaScript? E.g.
--- Raw source ---
function add(a, b){
return a + b;
}
...
--- Code ---
source_position = 0
kind = FUNCTION
Instructions (size = 456)
0x36953100 0 8b4c2404 mov ecx,[esp+0x4]
0x36953104 4 81f991806049 cmp ecx,0x49608091 ;; object: 0x49608091 <undefined>
0x3695310a 10 750a jnz 22 (0x36953116)
0x3695310c 12 8b4e13 mov ecx,[esi+0x13]
0x3695310f 15 8b4917 mov ecx,[ecx+0x17]
0x36953112 18 894c2404 mov [esp+0x4],ecx
0x36953116 22 55 push ebp
Is it possible to view the machine code (x86 instructions) that a browser ultimately generates from my JavaScript? E.g.
--- Raw source ---
function add(a, b){
return a + b;
}
...
--- Code ---
source_position = 0
kind = FUNCTION
Instructions (size = 456)
0x36953100 0 8b4c2404 mov ecx,[esp+0x4]
0x36953104 4 81f991806049 cmp ecx,0x49608091 ;; object: 0x49608091 <undefined>
0x3695310a 10 750a jnz 22 (0x36953116)
0x3695310c 12 8b4e13 mov ecx,[esi+0x13]
0x3695310f 15 8b4917 mov ecx,[ecx+0x17]
0x36953112 18 894c2404 mov [esp+0x4],ecx
0x36953116 22 55 push ebp
Share
Improve this question
edited May 20, 2023 at 3:08
user3064538
asked Dec 19, 2019 at 14:38
DefarineDefarine
82010 silver badges22 bronze badges
1
- Does this answer your question? How to convert Javascript code to human-readable opcodes or asm? – jmrk Commented Dec 19, 2019 at 18:09
2 Answers
Reset to default 17Your script isn't transformed to machine code directly. Chrome and Node.js run JavaScript on a virtual machine called V8 and you can get the VM bytecode using:
node --print-bytecode script.js
Then V8 executes and optimizes the bytecode and calls external C libraries and OS API (system calls) or Web API. Final machine code may vary even with the same JavaScript code (for example before and after optimization).
You can also start Chrome from the command line with
--js-flags="--print-bytecode"
UPD:
As @PeterCordes noticed Node.js allows seeing the Turbofan generated machine code using
node --print-opt-code script.js
Chrome:
--js-flags="--print-opt-code"
Also you can use an HTML visualizer like https://github.com/v8/v8/tree/main/tools/turbolizer
Run your code with Node.js (which uses the same JavaScript engine as Chrome) with the --trace-turbo
flag, like this:
node --trace-turbo <( echo "for (let i = 100000; i>0; i--) {}")
it will generate some turbo-<whatever>.cfg files and a turbo-<foo>.json file. Next, go to Turbolizer:
https://v8.github.io/tools/head/turbolizer/index.html
press ctrl-l and upload the .json file. It will show you the generated bytecode, the resulting assembly and a graph. The top-middle dropdown selects various stages of optimization, you probably want the last one.
You can see the decrement instruction at address 5c (I ran this on an ARM CPU):
subs w3, w3, #0x1 (1)