I’m no expert in this field nor having a PhD in Compiler. This is just my pure curiosity and I hope to share of what I’ve discovered so people can continue their curiosity.
Why I’m interested in this.
How does computer works?
One of the best movies for me is “The Core” where “Rat” had to hack the Internet to control the flow of information. The hacker claims that he only knew one language, “zeros and ones”. At the time, I understood that it’s something to do with binary number, and I thought that it’s just hollywood talk and these people didn’t know what they were talking. I have to write
print('Hello'); to print
Hello on my console, it has nothing to do with zeros or ones.
So, I started digging and I found this.
Basically, when we execute a piece of code, the compiler compiles the code to a set of instructions which is Assembly. Then, we have an assembler to translate the instructions to their numerical equivalents. For example,
is translated in x86 architecture like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
Notice the HEX code
83C408 which you can translate to binary number later for the computer to understand.
You can use this online assembler to play with it.
There are four main stages of how the code passes through V8.
Hydrogen - Intermediate code
Lithium - Machine specific code
Machine Code - This is what your computer understand.
In this post we’re going to see the assembly code which is the machine specific code.
Show me the code
Enough talking. Now show me the code you say. Let’s say you have a simple function to add two numbers together like this.
1 2 3
Note: The documentation of how to install V8 is subject to change. So, please refer to link.
In order to get
V8 you need to run. You will also need
The script will take sometime to finish. It will fetch V8 source code. Then you need to build all the dependencies by running.
Now you need to install D8. The next step is going to take a long time. So, get yourself a nice cup of coffee.
Once everything is in place, you’re ready to see how your code is communicating with your CPU.
You can do this to get the assembly code
This is what you’re likely going to see.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
~~Now, in theory you can grab the hex code and run that in C and you should be able to get the same result. I haven’t tried it please let me know if it works or not.~~ It wouldn’t work because the generated code has fixed memory address from when the program was executed.