SlideShare a Scribd company logo
1 of 85
Download to read offline
Monday, November 29, 2010
JavaScript Engines
                              Under the Hood

                                     ARIYA HIDAYAT
                              ENGINEERING DIRECTOR, SENCHA


Monday, November 29, 2010
JavaScript Engines

                            Get It
                            See It
                            Tweak It


Monday, November 29, 2010
JavaScript Engines




Monday, November 29, 2010
JavaScript Engines
                            SpiderMonkey     Opera Carakan
                            JavaScriptCore   Microsoft JScript
                                 V8          ...


                              Open                 Closed


Monday, November 29, 2010
JavaScript Engines
                            SpiderMonkey
                            JavaScriptCore
                                 V8


                              Open



Monday, November 29, 2010
SpiderMonkey
       First JavaScript engine
       created by Brendan Eich

       Written in C
       Mostly used in Mozilla, Firefox, ...

       License: MPL/LGPL/GPL




Monday, November 29, 2010
JavaScriptCore (JSC)
       Built into WebKit
       Forked from KDE’s KJS a long time ago

       License: LGPL




Monday, November 29, 2010
Other Names of JSC
       SquirrelFish
       byte-code interpreter

       SquirrelFish Extreme (SFX)
       native/machine code

       Nitro, Nitro Extreme
       Apple’s marketing terms


Monday, November 29, 2010
Google V8
       Written in C++
       License: BSD

       Used in Chromium (Google Chrome)




Monday, November 29, 2010
Qt Script
       Uses JSC as the back-end
       Does not power any web browser

       Powerful bindings, debugger
       Useful to make applications scriptable




Monday, November 29, 2010
Let’s Go
        UNDER THE HOOD
Monday, November 29, 2010
Let’s Go        Platform +
                             Compiler
        UNDER THE HOOD
Monday, November 29, 2010
Monday, November 29, 2010
Get the real V8
        svn checkout http://v8.googlecode.com/svn/trunk v8
        cd v8

        git clone git://github.com/v8/v8.git v8
        cd v8




Monday, November 29, 2010
Build V8

        scons sample=shell mode=release snapshot=on




Monday, November 29, 2010
Build V8

        scons sample=shell mode=release snapshot=on



                                        --jobs 4




Monday, November 29, 2010
Build V8

        scons sample=shell mode=release snapshot=on



                                        --jobs 4


                                        arch=x64

Monday, November 29, 2010
Run your-favorite-
                               benchmark


      perl sunspider --shell=/path/to/v8/directory/
      shell --args=-expose-gc




Monday, November 29, 2010
Run your-favorite-
                               benchmark


      perl sunspider --shell=/path/to/v8/directory/
      shell --args=-expose-gc


                                        garbage collector


Monday, November 29, 2010
Let’s Get DIRTY




Monday, November 29, 2010
Building Blocks

                            Parser
                                                   Runtime



                                     Interpreter


Monday, November 29, 2010
Parser




Monday, November 29, 2010
Tokenize



     var answer = 42;

Monday, November 29, 2010
Tokenize
                            identifier                number



     var answer = 42;
             keyword                    equal sign
                                                        semicolon


Monday, November 29, 2010
Look Ahead

                            greater than
       >
      >>                      right shift

      >>>                      zero-filled right shift


Monday, November 29, 2010
Look Ahead

                            greater than                >=
       >
      >>                      right shift               >>=
      >>>                                               >>>=
                               zero-filled right shift


Monday, November 29, 2010
Tokenizer on V8

                               src/scanner.*




Monday, November 29, 2010
Tokenizer on V8

                               src/scanner.*


                                   hand-written
                                   state machine



Monday, November 29, 2010
Keyword vs Identifier

                  instanceof           instanceComponent

                                           requires checking
                                                9 chars




Monday, November 29, 2010
Keyword vs Identifier

                  instanceof           instanceComponent

                                           requires checking
                                                9 chars




                            a g h j klmopqxyz
Monday, November 29, 2010
Grammar
        SourceElement :: (Statement)*

        FunctionDeclaration ::
          'function' Identifier '(' FormalParameters ')'
          '{' FunctionBody '}'




Monday, November 29, 2010
Syntax Tree
                                 Variable Declaration




                            Identifier
                                                   Literal Constant

                            answer                      42
Monday, November 29, 2010
Another Syntax Tree
                                  Branch



         Condition                            Alternate
                                 Consequent
     age < 25                                 “old”
                                 “young”
Monday, November 29, 2010
Parser on V8

                             src/parser.*




Monday, November 29, 2010
Parser on V8

                             src/parser.*


                                  hand-written
                                recursive descent



Monday, November 29, 2010
Code Trace
                                 Script::Compile

                                   Script::New

                            internal::Compiler::Compile

                            internal::MakeFunctionInfo

                            internal::ParserApi::Parse


Monday, November 29, 2010
Interpreter




Monday, November 29, 2010
From Code to Execution

      var answer = 42;
                                   Declare a local object
                                      Call it “answer”
                            Create a (small integer) number 42
                                  Assign it to “answer”
Monday, November 29, 2010
Traverse and Run
                                 Variable Declaration




                            Identifier
                                                   Literal Constant

                            answer                      42
Monday, November 29, 2010
Bytecode

                            Serialize tree traversal into
                                 a list of “actions”




Monday, November 29, 2010
Machine Code

                            Compile the bytecodes into
                              machine instructions




Monday, November 29, 2010
Machine Code

                              Compile the bytecodes into
                                machine instructions



                            JIT (=just-in-time) compile

Monday, November 29, 2010
Machine Code on V8
                               Global

                    shell_g --print-code


                            When needed

       shell_g --expose-debug-as deb


Monday, November 29, 2010
Machine Code on V8
                               Global

                    shell_g --print-code


                            When needed
                                           deb.Debug.disassemble(f)

       shell_g --expose-debug-as deb


Monday, November 29, 2010
“Lazy” Approach
          foobar = function(x, y, z)
          {
          ....
          }

          foobar(x, y, z);




Monday, November 29, 2010
“Lazy” Approach
          foobar = function(x, y, z)   Analyze the syntax
          {
          ....
                                       Mark the position of
          }                             function ‘foobar’
          foobar(x, y, z);




Monday, November 29, 2010
“Lazy” Approach
          foobar = function(x, y, z)              Analyze the syntax
          {
          ....
                                                  Mark the position of
          }                                        function ‘foobar’
          foobar(x, y, z);



                            Compile and run the
                             function ‘foobar’
Monday, November 29, 2010
Runtime




Monday, November 29, 2010
Date.now()


                      “native”            JavaScript
                       world                world



Monday, November 29, 2010
Let’s Go
                            OFF ROAD




Monday, November 29, 2010
Bridge




Monday, November 29, 2010
V8 Embedder’s Guide




                 http://code.google.com/apis/v8/embed.html
Monday, November 29, 2010
Handle: Local vs Persistent


                        {
                            HandleScope scope;

                            Handle<Value> foobar = ....
                            ....
                            ....
                        }
Monday, November 29, 2010
short lived

                 Handle: Local vs Persistent
                                                  long lived


                        {
                             HandleScope scope;

                             Handle<Value> foobar = ....
                             ....
                             ....
                        }
Monday, November 29, 2010
C++-side of Objects
                Value         Primitive   Boolean
                              Date        String
                              Object      Number

                              Array
                              Function
                              External
Monday, November 29, 2010
Expose a Variable

        Handle<ObjectTemplate> global = ObjectTemplate::New();
        global->Set("foobar", String::New(“Hello”));




Monday, November 29, 2010
Expose a Function
      Handle<FunctionTemplate> systemObject = FunctionTemplate::New();
      systemObject->Set(String::New("exit"),
          FunctionTemplate::New(system_exit)->GetFunction());




                            static Handle<Value> system_exit(const Arguments& args)
                            {
                                int status = args[0]->Int32Value();
                                ::exit(status);
                                return Undefined();
                            }

Monday, November 29, 2010
Demo
                            Code Formatter



Monday, November 29, 2010
Demo
                            Syntax Checker



Monday, November 29, 2010
Demo
                            Canvas-based Game



Monday, November 29, 2010
http://10k.aneventapart.com/Entry/392
Monday, November 29, 2010
Demo
                            Syntax Parser



Monday, November 29, 2010
Ext.extend

                            declare

         Ext.ComponentFoo = Ext.extend(Ext.ComponentBar, ....


                                              depend



Monday, November 29, 2010
Demo
                            Code Analyzer



Monday, November 29, 2010
"type": "IfStatement",
                            "test": {
                                        "type": "BinaryExpression",
                                        "operator": "==",
                                        "left": {
                                            "type": "Identifier",
                                            "name": "x"
                                        },
                                        "right": {
                                            "type": "Identifier",
                                            "name": "y"
                                        }
     if (x == y) foo();             },
                                    "consequent": {
                                        "type": "ExpressionStatement",
                                        "expression": {
                                            "type": "CallExpression",
                                            "callee": {
                                                "type": "Identifier",
                                                "name": "foo"
                                            },
                                            "arguments": []
                                        }
                                    },
                                    "alternate": null




Monday, November 29, 2010
"type": "IfStatement",
                            "test": {
                                        "type": "BinaryExpression",
                                        "operator": "==",
                                        "left": {
                                            "type": "Identifier",
                                            "name": "x"
                                        },
                                        "right": {
                                            "type": "Identifier",
                                            "name": "y"
                                        }
     if (x == y) foo();             },
                                    "consequent": {
                                        "type": "ExpressionStatement",
                                        "expression": {
                                            "type": "CallExpression",
                                            "callee": {
                                                "type": "Identifier",
                                                "name": "foo"
                                            },
                                            "arguments": []
                                        }
                                    },
                                    "alternate": null




Monday, November 29, 2010
"type": "IfStatement",
                                      "test": {
                                                  "type": "BinaryExpression",
                                                  "operator": "==",
                                                  "left": {
                                                      "type": "Identifier",
                                                      "name": "x"
                                                  },
                                                  "right": {
                                                      "type": "Identifier",
                                                      "name": "y"
                                                  }
     if (x == y) foo();                       },
                                              "consequent": {
                                                  "type": "ExpressionStatement",
                                                  "expression": {
                            Danger!                   "type": "CallExpression",
                                                      "callee": {
                                                          "type": "Identifier",
                                                          "name": "foo"
                                                      },
                                                      "arguments": []
                                                  }
                                              },
                                              "alternate": null




Monday, November 29, 2010
Debugging




Monday, November 29, 2010
http://code.google.com/p/chromedevtools
Monday, November 29, 2010
(Remote) Debugging


                            v8::Debug::EnableAgent("foobar", 5858);




Monday, November 29, 2010
(Remote) Debugging
                                        application name

                            v8::Debug::EnableAgent("foobar", 5858);


                                                listening port



Monday, November 29, 2010
Profiling




Monday, November 29, 2010
Activate Profiler

                                   scons prof=on ...

                                   shell --prof ....

                            tools/mac-tick-processor v8.log




Monday, November 29, 2010
Function-Level Profile
      [JavaScript]:
        ticks total          nonlib    name
        3125    5.9%           5.9%   LazyCompile: am3 crypto.js:108
        1036    2.0%           2.0%   KeyedLoadIC: A keyed load IC from the snapshot
         386    0.7%           0.7%   LazyCompile: StringReplaceRegExp native string.js:243
         362    0.7%           0.7%   LazyCompile: Scheduler.schedule richards.js:188
         326    0.6%           0.6%   LazyCompile: one_way_unify1_nboyer earley-boyer.js:3635
         301    0.6%           0.6%   LazyCompile: exec native regexp.js:156
         280    0.5%           0.5%   LazyCompile: TaskControlBlock.isHeldOrSuspended richards.js:309
         279    0.5%           0.5%   KeyedStoreIC: A keyed store IC from the snapshot
         278    0.5%           0.5%   LazyCompile: rewrite_nboyer earley-boyer.js:3604
         259    0.5%           0.5%   LazyCompile: BuildResultFromMatchInfo native regexp.js:121
         244    0.5%           0.5%   LazyCompile: TaskControlBlock.run richards.js:324
         186    0.4%           0.4%   Stub: Instanceof




Monday, November 29, 2010
THANK YOU!




Monday, November 29, 2010
QUESTIONS?

                            ariya @ sencha.com


                            ariya.blogspot.com


                            ariyahidayat

Monday, November 29, 2010
ADDENDUM




Monday, November 29, 2010
Get SpiderMonkey

        hg clone http://hg.mozilla.org/mozilla-central/
        cd mozilla-central/js/src




Monday, November 29, 2010
Get JavaScriptCore
          svn checkout http://svn.webkit.org/repository/
          webkit/trunk webkit
          cd webkit/JavaScriptCore

          git clone git://git.webkit.org/WebKit.git
          cd WebKit/JavaScriptCore




Monday, November 29, 2010
Build SpiderMonkey
        autoconf213
        ./configure --disable-debug --enable-optimize
        make




Monday, November 29, 2010
Build JavaScriptCore

        JavaScriptCore/JavaScriptCore.xcodeproj



                      JavaScriptCore

                               jsc

Monday, November 29, 2010
Run your-favorite-
                               benchmark
      perl sunspider --shell=/path/to/mozilla-
      central/js/src/build-release/js --args=-j

      perl sunspider --shell=/path/to/webkit/
      JavaScriptCore/jsc

      perl sunspider --shell=/path/to/v8/directory/
      shell --args=-expose-gc


Monday, November 29, 2010
Run your-favorite-
                               benchmark
      perl sunspider --shell=/path/to/mozilla-
      central/js/src/build-release/js --args=-j

      perl sunspider --shell=/path/to/webkit/
      JavaScriptCore/jsc

      perl sunspider --shell=/path/to/v8/directory/
      shell --args=-expose-gc
                                          garbage collector
Monday, November 29, 2010
Build JavaScriptCore
        qmake -r DerivedSources.pro
        cd JavaScriptCore
        make -f Makefile.DerivedSources
        qmake && make
        qmake jsc.pro && make




Monday, November 29, 2010

More Related Content

More from Sencha

More from Sencha (20)

Sencha Roadshow 2017: Sencha Upgrades - The Good. The Bad. The Ugly - Eva Luc...
Sencha Roadshow 2017: Sencha Upgrades - The Good. The Bad. The Ugly - Eva Luc...Sencha Roadshow 2017: Sencha Upgrades - The Good. The Bad. The Ugly - Eva Luc...
Sencha Roadshow 2017: Sencha Upgrades - The Good. The Bad. The Ugly - Eva Luc...
 
Sencha Roadshow 2017: Modernizing the Ext JS Class System and Tooling
Sencha Roadshow 2017: Modernizing the Ext JS Class System and ToolingSencha Roadshow 2017: Modernizing the Ext JS Class System and Tooling
Sencha Roadshow 2017: Modernizing the Ext JS Class System and Tooling
 
Sencha Roadshow 2017: Sencha Best Practices: Coworkee App
Sencha Roadshow 2017: Sencha Best Practices: Coworkee App Sencha Roadshow 2017: Sencha Best Practices: Coworkee App
Sencha Roadshow 2017: Sencha Best Practices: Coworkee App
 
Sencha Roadshow 2017: Mobile First or Desktop First
Sencha Roadshow 2017: Mobile First or Desktop FirstSencha Roadshow 2017: Mobile First or Desktop First
Sencha Roadshow 2017: Mobile First or Desktop First
 
Sencha Roadshow 2017: Innovations in Ext JS 6.5 and Beyond
Sencha Roadshow 2017: Innovations in Ext JS 6.5 and BeyondSencha Roadshow 2017: Innovations in Ext JS 6.5 and Beyond
Sencha Roadshow 2017: Innovations in Ext JS 6.5 and Beyond
 
Leveraging React and GraphQL to Create a Performant, Scalable Data Grid
Leveraging React and GraphQL to Create a Performant, Scalable Data GridLeveraging React and GraphQL to Create a Performant, Scalable Data Grid
Leveraging React and GraphQL to Create a Performant, Scalable Data Grid
 
Learn Key Insights from The State of Web Application Testing Research Report
Learn Key Insights from The State of Web Application Testing Research ReportLearn Key Insights from The State of Web Application Testing Research Report
Learn Key Insights from The State of Web Application Testing Research Report
 
Introducing ExtReact: Adding Powerful Sencha Components to React Apps
Introducing ExtReact: Adding Powerful Sencha Components to React AppsIntroducing ExtReact: Adding Powerful Sencha Components to React Apps
Introducing ExtReact: Adding Powerful Sencha Components to React Apps
 
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark BrocatoSenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
 
SenchaCon 2016: Add Magic to Your Ext JS Apps with D3 Visualizations - Vitaly...
SenchaCon 2016: Add Magic to Your Ext JS Apps with D3 Visualizations - Vitaly...SenchaCon 2016: Add Magic to Your Ext JS Apps with D3 Visualizations - Vitaly...
SenchaCon 2016: Add Magic to Your Ext JS Apps with D3 Visualizations - Vitaly...
 
SenchaCon 2016: LinkRest - Modern RESTful API Framework for Ext JS Apps - Rou...
SenchaCon 2016: LinkRest - Modern RESTful API Framework for Ext JS Apps - Rou...SenchaCon 2016: LinkRest - Modern RESTful API Framework for Ext JS Apps - Rou...
SenchaCon 2016: LinkRest - Modern RESTful API Framework for Ext JS Apps - Rou...
 
SenchaCon 2016: Expect the Unexpected - Dealing with Errors in Web Apps
SenchaCon 2016: Expect the Unexpected - Dealing with Errors in Web AppsSenchaCon 2016: Expect the Unexpected - Dealing with Errors in Web Apps
SenchaCon 2016: Expect the Unexpected - Dealing with Errors in Web Apps
 
Ext JS Architecture Best Practices - Mitchell Simeons
Ext JS Architecture Best Practices - Mitchell SimeonsExt JS Architecture Best Practices - Mitchell Simeons
Ext JS Architecture Best Practices - Mitchell Simeons
 
SenchaCon 2016: Mobile First? Desktop First? Or Should you Think Universal Ap...
SenchaCon 2016: Mobile First? Desktop First? Or Should you Think Universal Ap...SenchaCon 2016: Mobile First? Desktop First? Or Should you Think Universal Ap...
SenchaCon 2016: Mobile First? Desktop First? Or Should you Think Universal Ap...
 
Building Ext JS Using HATEOAS - Jeff Stano
Building Ext JS Using HATEOAS - Jeff StanoBuilding Ext JS Using HATEOAS - Jeff Stano
Building Ext JS Using HATEOAS - Jeff Stano
 
SenchaCon 2016: Improve Workflow Driven Applications with Ext JS Draw Package...
SenchaCon 2016: Improve Workflow Driven Applications with Ext JS Draw Package...SenchaCon 2016: Improve Workflow Driven Applications with Ext JS Draw Package...
SenchaCon 2016: Improve Workflow Driven Applications with Ext JS Draw Package...
 
SenchaCon 2016: Developing and Delivering Quality Code, Frequently - Neil Manvar
SenchaCon 2016: Developing and Delivering Quality Code, Frequently - Neil ManvarSenchaCon 2016: Developing and Delivering Quality Code, Frequently - Neil Manvar
SenchaCon 2016: Developing and Delivering Quality Code, Frequently - Neil Manvar
 
SenchaCon 2016: Creating a Flexible and Usable Industry Specific Solution - D...
SenchaCon 2016: Creating a Flexible and Usable Industry Specific Solution - D...SenchaCon 2016: Creating a Flexible and Usable Industry Specific Solution - D...
SenchaCon 2016: Creating a Flexible and Usable Industry Specific Solution - D...
 
SenchaCon 2016: JavaScript is Great but Stop Writing It - Rory Hardy
SenchaCon 2016: JavaScript is Great but Stop Writing It - Rory HardySenchaCon 2016: JavaScript is Great but Stop Writing It - Rory Hardy
SenchaCon 2016: JavaScript is Great but Stop Writing It - Rory Hardy
 
SenchaCon 2016: Accessibility, Teamwork & Ext JS: A Customer Success Story - ...
SenchaCon 2016: Accessibility, Teamwork & Ext JS: A Customer Success Story - ...SenchaCon 2016: Accessibility, Teamwork & Ext JS: A Customer Success Story - ...
SenchaCon 2016: Accessibility, Teamwork & Ext JS: A Customer Success Story - ...
 

Recently uploaded

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
FIDO Alliance
 

Recently uploaded (20)

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
 
API Governance and Monetization - The evolution of API governance
API Governance and Monetization -  The evolution of API governanceAPI Governance and Monetization -  The evolution of API governance
API Governance and Monetization - The evolution of API governance
 
Overview of Hyperledger Foundation
Overview of Hyperledger FoundationOverview of Hyperledger Foundation
Overview of Hyperledger Foundation
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream Processing
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overview
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Modernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaModernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using Ballerina
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptx
 
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
 
How to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cfHow to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cf
 
Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform Engineering
 

JavaScript Engines: Under the Hood

  • 2. JavaScript Engines Under the Hood ARIYA HIDAYAT ENGINEERING DIRECTOR, SENCHA Monday, November 29, 2010
  • 3. JavaScript Engines Get It See It Tweak It Monday, November 29, 2010
  • 5. JavaScript Engines SpiderMonkey Opera Carakan JavaScriptCore Microsoft JScript V8 ... Open Closed Monday, November 29, 2010
  • 6. JavaScript Engines SpiderMonkey JavaScriptCore V8 Open Monday, November 29, 2010
  • 7. SpiderMonkey First JavaScript engine created by Brendan Eich Written in C Mostly used in Mozilla, Firefox, ... License: MPL/LGPL/GPL Monday, November 29, 2010
  • 8. JavaScriptCore (JSC) Built into WebKit Forked from KDE’s KJS a long time ago License: LGPL Monday, November 29, 2010
  • 9. Other Names of JSC SquirrelFish byte-code interpreter SquirrelFish Extreme (SFX) native/machine code Nitro, Nitro Extreme Apple’s marketing terms Monday, November 29, 2010
  • 10. Google V8 Written in C++ License: BSD Used in Chromium (Google Chrome) Monday, November 29, 2010
  • 11. Qt Script Uses JSC as the back-end Does not power any web browser Powerful bindings, debugger Useful to make applications scriptable Monday, November 29, 2010
  • 12. Let’s Go UNDER THE HOOD Monday, November 29, 2010
  • 13. Let’s Go Platform + Compiler UNDER THE HOOD Monday, November 29, 2010
  • 15. Get the real V8 svn checkout http://v8.googlecode.com/svn/trunk v8 cd v8 git clone git://github.com/v8/v8.git v8 cd v8 Monday, November 29, 2010
  • 16. Build V8 scons sample=shell mode=release snapshot=on Monday, November 29, 2010
  • 17. Build V8 scons sample=shell mode=release snapshot=on --jobs 4 Monday, November 29, 2010
  • 18. Build V8 scons sample=shell mode=release snapshot=on --jobs 4 arch=x64 Monday, November 29, 2010
  • 19. Run your-favorite- benchmark perl sunspider --shell=/path/to/v8/directory/ shell --args=-expose-gc Monday, November 29, 2010
  • 20. Run your-favorite- benchmark perl sunspider --shell=/path/to/v8/directory/ shell --args=-expose-gc garbage collector Monday, November 29, 2010
  • 21. Let’s Get DIRTY Monday, November 29, 2010
  • 22. Building Blocks Parser Runtime Interpreter Monday, November 29, 2010
  • 24. Tokenize var answer = 42; Monday, November 29, 2010
  • 25. Tokenize identifier number var answer = 42; keyword equal sign semicolon Monday, November 29, 2010
  • 26. Look Ahead greater than > >> right shift >>> zero-filled right shift Monday, November 29, 2010
  • 27. Look Ahead greater than >= > >> right shift >>= >>> >>>= zero-filled right shift Monday, November 29, 2010
  • 28. Tokenizer on V8 src/scanner.* Monday, November 29, 2010
  • 29. Tokenizer on V8 src/scanner.* hand-written state machine Monday, November 29, 2010
  • 30. Keyword vs Identifier instanceof instanceComponent requires checking 9 chars Monday, November 29, 2010
  • 31. Keyword vs Identifier instanceof instanceComponent requires checking 9 chars a g h j klmopqxyz Monday, November 29, 2010
  • 32. Grammar SourceElement :: (Statement)* FunctionDeclaration :: 'function' Identifier '(' FormalParameters ')' '{' FunctionBody '}' Monday, November 29, 2010
  • 33. Syntax Tree Variable Declaration Identifier Literal Constant answer 42 Monday, November 29, 2010
  • 34. Another Syntax Tree Branch Condition Alternate Consequent age < 25 “old” “young” Monday, November 29, 2010
  • 35. Parser on V8 src/parser.* Monday, November 29, 2010
  • 36. Parser on V8 src/parser.* hand-written recursive descent Monday, November 29, 2010
  • 37. Code Trace Script::Compile Script::New internal::Compiler::Compile internal::MakeFunctionInfo internal::ParserApi::Parse Monday, November 29, 2010
  • 39. From Code to Execution var answer = 42; Declare a local object Call it “answer” Create a (small integer) number 42 Assign it to “answer” Monday, November 29, 2010
  • 40. Traverse and Run Variable Declaration Identifier Literal Constant answer 42 Monday, November 29, 2010
  • 41. Bytecode Serialize tree traversal into a list of “actions” Monday, November 29, 2010
  • 42. Machine Code Compile the bytecodes into machine instructions Monday, November 29, 2010
  • 43. Machine Code Compile the bytecodes into machine instructions JIT (=just-in-time) compile Monday, November 29, 2010
  • 44. Machine Code on V8 Global shell_g --print-code When needed shell_g --expose-debug-as deb Monday, November 29, 2010
  • 45. Machine Code on V8 Global shell_g --print-code When needed deb.Debug.disassemble(f) shell_g --expose-debug-as deb Monday, November 29, 2010
  • 46. “Lazy” Approach foobar = function(x, y, z) { .... } foobar(x, y, z); Monday, November 29, 2010
  • 47. “Lazy” Approach foobar = function(x, y, z) Analyze the syntax { .... Mark the position of } function ‘foobar’ foobar(x, y, z); Monday, November 29, 2010
  • 48. “Lazy” Approach foobar = function(x, y, z) Analyze the syntax { .... Mark the position of } function ‘foobar’ foobar(x, y, z); Compile and run the function ‘foobar’ Monday, November 29, 2010
  • 50. Date.now() “native” JavaScript world world Monday, November 29, 2010
  • 51. Let’s Go OFF ROAD Monday, November 29, 2010
  • 53. V8 Embedder’s Guide http://code.google.com/apis/v8/embed.html Monday, November 29, 2010
  • 54. Handle: Local vs Persistent { HandleScope scope; Handle<Value> foobar = .... .... .... } Monday, November 29, 2010
  • 55. short lived Handle: Local vs Persistent long lived { HandleScope scope; Handle<Value> foobar = .... .... .... } Monday, November 29, 2010
  • 56. C++-side of Objects Value Primitive Boolean Date String Object Number Array Function External Monday, November 29, 2010
  • 57. Expose a Variable Handle<ObjectTemplate> global = ObjectTemplate::New(); global->Set("foobar", String::New(“Hello”)); Monday, November 29, 2010
  • 58. Expose a Function Handle<FunctionTemplate> systemObject = FunctionTemplate::New(); systemObject->Set(String::New("exit"), FunctionTemplate::New(system_exit)->GetFunction()); static Handle<Value> system_exit(const Arguments& args) { int status = args[0]->Int32Value(); ::exit(status); return Undefined(); } Monday, November 29, 2010
  • 59. Demo Code Formatter Monday, November 29, 2010
  • 60. Demo Syntax Checker Monday, November 29, 2010
  • 61. Demo Canvas-based Game Monday, November 29, 2010
  • 63. Demo Syntax Parser Monday, November 29, 2010
  • 64. Ext.extend declare Ext.ComponentFoo = Ext.extend(Ext.ComponentBar, .... depend Monday, November 29, 2010
  • 65. Demo Code Analyzer Monday, November 29, 2010
  • 66. "type": "IfStatement", "test": { "type": "BinaryExpression", "operator": "==", "left": { "type": "Identifier", "name": "x" }, "right": { "type": "Identifier", "name": "y" } if (x == y) foo(); }, "consequent": { "type": "ExpressionStatement", "expression": { "type": "CallExpression", "callee": { "type": "Identifier", "name": "foo" }, "arguments": [] } }, "alternate": null Monday, November 29, 2010
  • 67. "type": "IfStatement", "test": { "type": "BinaryExpression", "operator": "==", "left": { "type": "Identifier", "name": "x" }, "right": { "type": "Identifier", "name": "y" } if (x == y) foo(); }, "consequent": { "type": "ExpressionStatement", "expression": { "type": "CallExpression", "callee": { "type": "Identifier", "name": "foo" }, "arguments": [] } }, "alternate": null Monday, November 29, 2010
  • 68. "type": "IfStatement", "test": { "type": "BinaryExpression", "operator": "==", "left": { "type": "Identifier", "name": "x" }, "right": { "type": "Identifier", "name": "y" } if (x == y) foo(); }, "consequent": { "type": "ExpressionStatement", "expression": { Danger! "type": "CallExpression", "callee": { "type": "Identifier", "name": "foo" }, "arguments": [] } }, "alternate": null Monday, November 29, 2010
  • 71. (Remote) Debugging v8::Debug::EnableAgent("foobar", 5858); Monday, November 29, 2010
  • 72. (Remote) Debugging application name v8::Debug::EnableAgent("foobar", 5858); listening port Monday, November 29, 2010
  • 74. Activate Profiler scons prof=on ... shell --prof .... tools/mac-tick-processor v8.log Monday, November 29, 2010
  • 75. Function-Level Profile [JavaScript]: ticks total nonlib name 3125 5.9% 5.9% LazyCompile: am3 crypto.js:108 1036 2.0% 2.0% KeyedLoadIC: A keyed load IC from the snapshot 386 0.7% 0.7% LazyCompile: StringReplaceRegExp native string.js:243 362 0.7% 0.7% LazyCompile: Scheduler.schedule richards.js:188 326 0.6% 0.6% LazyCompile: one_way_unify1_nboyer earley-boyer.js:3635 301 0.6% 0.6% LazyCompile: exec native regexp.js:156 280 0.5% 0.5% LazyCompile: TaskControlBlock.isHeldOrSuspended richards.js:309 279 0.5% 0.5% KeyedStoreIC: A keyed store IC from the snapshot 278 0.5% 0.5% LazyCompile: rewrite_nboyer earley-boyer.js:3604 259 0.5% 0.5% LazyCompile: BuildResultFromMatchInfo native regexp.js:121 244 0.5% 0.5% LazyCompile: TaskControlBlock.run richards.js:324 186 0.4% 0.4% Stub: Instanceof Monday, November 29, 2010
  • 77. QUESTIONS? ariya @ sencha.com ariya.blogspot.com ariyahidayat Monday, November 29, 2010
  • 79. Get SpiderMonkey hg clone http://hg.mozilla.org/mozilla-central/ cd mozilla-central/js/src Monday, November 29, 2010
  • 80. Get JavaScriptCore svn checkout http://svn.webkit.org/repository/ webkit/trunk webkit cd webkit/JavaScriptCore git clone git://git.webkit.org/WebKit.git cd WebKit/JavaScriptCore Monday, November 29, 2010
  • 81. Build SpiderMonkey autoconf213 ./configure --disable-debug --enable-optimize make Monday, November 29, 2010
  • 82. Build JavaScriptCore JavaScriptCore/JavaScriptCore.xcodeproj JavaScriptCore jsc Monday, November 29, 2010
  • 83. Run your-favorite- benchmark perl sunspider --shell=/path/to/mozilla- central/js/src/build-release/js --args=-j perl sunspider --shell=/path/to/webkit/ JavaScriptCore/jsc perl sunspider --shell=/path/to/v8/directory/ shell --args=-expose-gc Monday, November 29, 2010
  • 84. Run your-favorite- benchmark perl sunspider --shell=/path/to/mozilla- central/js/src/build-release/js --args=-j perl sunspider --shell=/path/to/webkit/ JavaScriptCore/jsc perl sunspider --shell=/path/to/v8/directory/ shell --args=-expose-gc garbage collector Monday, November 29, 2010
  • 85. Build JavaScriptCore qmake -r DerivedSources.pro cd JavaScriptCore make -f Makefile.DerivedSources qmake && make qmake jsc.pro && make Monday, November 29, 2010