FULL DISCLOSURE: ADVICE FOR COMPOSING JAVASCRIPT Benjamin Lerner Affiliates Day 2009.

Slides:



Advertisements
Similar presentations
HTML Basics Customizing your site using the basics of HTML.
Advertisements

Introducing JavaScript
JSP1 Java Server Pages (JSP) Introducing JavaServer Pages TM (JSP TM ) JSP scripting elements.
WEAVING CODE EXTENSIONS INTO JAVASCRIPT Benjamin Lerner, Herman Venter, and Dan Grossman University of Washington, Microsoft Research.
GATEKEEPER MOSTLY STATIC ENFORCEMENT OF SECURITY AND RELIABILITY PROPERTIES FOR JAVASCRIPT CODE Salvatore Guarnieri & Benjamin Livshits Presented by Michael.
Language Support for Extensible Web Browsers Benjamin Lerner and Dan Grossman.
Web Server Programming
Detecting Conflicts Among Declarative UI Extensions Benjamin Lerner Brown University Dan Grossman UW Computer Science & Engineering.
AJAX Presented by: Dickson Fu Dimas Ariawan Niels Andreassen Ryan Dial Jordan Nielson CMPUT 410 University of Alberta 2006.
1 Introducing Collaboration to Single User Applications A Survey and Analysis of Recent Work by Brian Cornell For Collaborative Systems Fall 2006.
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
Kevin Reuter & Brian Guthrie.  Multi-paradigm  Prototype based objects  Dynamic, weak typing.
Tutorial 10 Programming with JavaScript
HTML Recall that HTML is static in that it describes how a page is to be displayed, but it doesn’t provide for interaction or animation. A page created.
1 CA201 Word Application Creating Document for the Web Week # 9 By Tariq Ibn Aziz Dammam Community college.
XP Tutorial 1 New Perspectives on JavaScript, Comprehensive1 Introducing JavaScript Hiding Addresses from Spammers.
4.01B Authoring Languages and Web Authoring Software 4.01 Examine webpage development and design.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
© Janice Regan, CMPT 128, Jan CMPT 128 Introduction to Computing Science for Engineering Students Creating a program.
Java: Chapter 1 Computer Systems Computer Programming II.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
CSS Class 7 Add JavaScript to your page Add event handlers Validate a form Open a new window Hide and show elements Swap images Debug JavaScript.
Patroklos Patroklou George Antoniou Constantinos Kyprianou.
Javascript. Outline Introduction Fundamental of JavaScript Javascript events management DOM and Dynamic HTML (DHTML)
11 Web Services. 22 Objectives You will be able to Say what a web service is. Write and deploy a simple web service. Test a simple web service. Write.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 13: An Introduction to C++
JAVA SERVER PAGES. 2 SERVLETS The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
1 Computer Systems -- Introduction  Chapter 1 focuses on:  the structure of a Java application  basic program elements  preparing and executing a program.
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
1 JavaScript in Context. Server-Side Programming.
XP Tutorial 10New Perspectives on Creating Web Pages with HTML, XHTML, and XML 1 Working with JavaScript Creating a Programmable Web Page for North Pole.
Tutorial 10 Programming with JavaScript. XP Objectives Learn the history of JavaScript Create a script element Understand basic JavaScript syntax Write.
Tutorial 10 Programming with JavaScript
Done by: Hanadi Muhsen1 Tutorial 1.  Learn the history of JavaScript  Create a script element  Write text to a Web page with JavaScript  Understand.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
Java server pages. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them. A JSP file basically contains.
XP Tutorial 10New Perspectives on HTML and XHTML, Comprehensive 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial.
What is Programming? A program is a list of instructions that is executed by a computer to accomplish a particular task. Creating those instructions is.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Introduction to JavaScript CS101 Introduction to Computing.
Computing System Fundamentals 3.1 Language Translators.
SUPPORTING DYNAMIC, THIRD-PARTY CODE CUSTOMIZATIONS IN JAVASCRIPT USING ASPECTS Benjamin Lerner, Herman Venter, and Dan Grossman University of Washington,
David Lawrence 7/8/091Intro. to PHP -- David Lawrence.
Introduction Selenium IDE is a Firefox extension that allows you to record, edit, and debug tests for HTML Easy record and playback Intelligent field selection.
Unit 10 – JavaScript Validation Instructor: Brent Presley.
1 JavaScript in Context. Server-Side Programming.
Plug-in Architectures Presented by Truc Nguyen. What’s a plug-in? “a type of program that tightly integrates with a larger application to add a special.
Creating a Java Application and Applet
Tutorial 10 Programming with JavaScript. 2New Perspectives on HTML, XHTML, and XML, Comprehensive, 3rd Edition Objectives Learn the history of JavaScript.
Chapter – 8 Software Tools.
Tutorial 10 Programming with JavaScript. 2New Perspectives on HTML, XHTML, and XML, Comprehensive, 3rd Edition Objectives Learn the history of JavaScript.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
1 CSC160 Chapter 1: Introduction to JavaScript Chapter 2: Placing JavaScript in an HTML File.
JavaScript and AJAX 2nd Edition Tutorial 1 Programming with JavaScript.
XP Tutorial 10New Perspectives on HTML, XHTML, and DHTML, Comprehensive 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties.
Javascript Javascript The JavaScript Programming Language – Scripting Languages Executed by an interpreter contained within.
Tutorial 10 Programming with JavaScript
* Lecture # 7 Instructor: Rida Noor Department of Computer Science
Michael Robertson Yuta Takayama Google Closure Tools.
Presented by Brian Nicholson
Server-Side Application and Data Management IT IS 3105 (Spring 2010)
JavaScript an introduction.
Functions BIS1523 – Lecture 17.
PHP.
Tutorial 10 Programming with JavaScript
JavaScript CS 4640 Programming Languages for Web Applications
Web Application Development Using PHP
JavaScript CS 4640 Programming Languages for Web Applications
Presentation transcript:

FULL DISCLOSURE: ADVICE FOR COMPOSING JAVASCRIPT Benjamin Lerner Affiliates Day 2009

Extension example: text formatting Most clients turn this: into this: Gmail doesn’t – how can we add this feature?

Motivation: Extending the Web  Extending Web Applications  “User scripts”  Bookmarklets  Extending the Browser  Firefox extensions  Chrome extensions, Opera widgets…  Very popular  Unknown numbers of problems… 40,000 scripts 6,000 extensions “When Gmail loads, run this script to preprocess and reformat the messages” “When I open a new tab, show me thumbnails of my ten most recently visited websites” “When I open a new tab, show me thumbnails of my ten most recently visited websites”

Userscript: Formatting Gmail messages Most clients turn this: This text should be _underlined_ into this: This text should be underlined 3. … that transforms punctuation to HTML 1. Save the original function 2. Replace the function with a new one… 4. … and then calls the original function var oldP = unsafeWindow.P; unsafeWindow.P = function(iframe, data) { if (data[0] == "mb") data[1] = format(data[1]); return oldP.apply(iframe, arguments); }

Extension: “SpeedDial” Firefox tabs

4. And replace the function with the modified version Extension: “SpeedDial” Firefox tabs 1. Find the function 2. Retrieve its source code… 3. …edit that string to include changes… SpeedDial.init = function () {... eval("getBrowser().removeTab = "+ getBrowser().removeTab.toString().replace( 'this.addTab("about:blank");', 'if (SpeedDial.loadInLastTab) { ' + ' this.addTab("chrome://speeddial ' + ' /content/speeddial.xul"' +')} else {$!}' ));... }

How are extensions written?  Mostly in JavaScript, HTML, and CSS  No overarching software engineering guidelines  “Just get it to work”  HTML & CSS: Overlays  JS: Wrapping  JS: Monkey-patching

Drawbacks of these approaches  Wrapping is inflexible  can’t be “inside” the function  Monkey patching is brittle  Patch may silently fail, may introduce syntax errors  Both are incorrect for closures  They are new closures that have the wrong environment  Both are incorrect for aliases  All other aliases are unmodified  What to do?

Aspects Advice Pointcut Arguments to function Type of advice  An aspect defines what new code to run, and when to run it  Advice defines what new code to run  Pointcuts define when to trigger it at pointcut(callee(Math.sin)) before(x) { print(“x is ”, x); }

Advice is visible to all aliases to window.P Advice is visible to all aliases to window.P Advising names versus closures window P Global object Window object Closure for P Userscript-defined closure for P preprocess Advice for P Suppose preprocess == window.P Userscript does not correctly advise preprocess !

Aspects for functions  Support before, after, and around advice at pointcut(callee(launchMissiles)) around(x) { if (!authorized(x)) print(“WARNING!!!”); else if (proceed() == false) { print(“Launch failed”); } return retval; }

Revisiting the Gmail userscript  Use before callee advice: var oldP = unsafeWindow.P; unsafeWindow.P = function(iframe, data) { if (data[0] == "mb") data[1] = format(data[1]); return oldP.apply(iframe, arguments); } at pointcut(callee(unsafeWindow.P)) before(iframe, data) { if (data[0] == "mb") data[1] = format(data[1]); }

Revisiting the SpeedDial extension  Use before statementContaining advice: eval("getBrowser().removeTab = "+ getBrowser().removeTab.toString().replace( 'this.addTab("about:blank");', 'if (SpeedDial.loadInLastTab)' + 'this.addTab("chrome://speeddial/content/speeddial.xul"); else $!' )); at pointcut(statementContaining(this.addTab("about:blank")) && within(getBrowser().removeTab) ) before { if (SpeedDial.loadInLastTab) this.addTab("chrome://speeddial/content/speeddial.xul") else this.addTab("about:blank") }

“Full Disclosure”: Aspects with a twist  We want to support an aspect language for JS that:  Has standard before/after/around function advice  Can access local variables within functions  Can syntactically revise existing functions  Is as easy as monkey-patching  …and:  Introduces minimal runtime overhead  Permits static analysis of aspects  Technique: open up closures and modify them

Implementing Aspects for JS  Targeting MSR JScript Compiler  High-level relevant features:  Entirely managed code Runtime environment, generated code are standard.NET  JIT compilation Can implement weaving as we JIT the code Makes dynamic weaving “almost free”

Future work

 Given aspects that can replace most monkey- patches, efficiently and more correctly…  Re-implement this scheme for other JS engines  Manually translate more extensions to use aspects, and see how often they’re useful  Develop static analyses to detect conflicts among extensions before runtime.

Backup

Wrapping  “This function doesn’t quite do what I want; let me replace it”  How? function square(x) { return x*x; } function square(x) { print(“x is ”, x); return x*x; } (function() { var oldSquare = square; square = function(x) { print(“x is ”, x); return oldSquare(x); }; })(); Pros: simple Cons: clutters the namespace can only change behavior before or after function only fixes one alias to function

Monkey patching  “This function doesn’t quite do what I want; let me tweak it”  How? function square(x) { return x*x; } function square(x) { print(“x is ”, x); return x*x; } eval(“square = ” + square.toString().replace(“return”, “print(\"s is \", x);\n return”));

Monkey patching: “idioms” eval('window.aioTabFocus = '+window.aioTabFocus.toSource().replace( /\{/, '{'+ 'if (e.originalTarget.ownerDocument != document) return;'+ 'var b = e.originalTarget;'+ 'while (b.localName != "tabbrowser")'+ 'b = b.parentNode;' ).replace( /aioTabsNb/g, 'b.aioTabsNb' ).replace( /aioContent/g, 'b' ).replace( /aioRendering/g, '(b.mPanelContainer || b)' ) ); From SplitBrowser

Monkey patching: making a mess onPopupShowing: function BM_onPopupShowing(event) {... if (!(hasMultipleURIs || siteURIString)) {... return; } else if ((hasMultipleURIs || siteURIString)) { for (var i = target.childNodes.length - 1; i > -1; i--){ if (target.childNodes[i].getAttribute("builder") == "end"){ target._endMarker = i; break; } } } if (!target._endOptSeparator) {... } } From MultiRow Bookmarks Toolbar 2.9

Easy case: Syntactic advice  We have the AST of the code to be JITted  For statementContaining and field advice:  Search for the expression/statement of interest,  And insert the advice as appropriate,  And then JIT the revised AST  Meets our goals:  Has access to local variables, can revise function  Is no more expensive than JITting the function and advice…which we’d have to do anyway

Medium case: Advising script functions (1/2)  Again want to inline the advice  Again, rewrite code at JIT time  Still meets our goals  Challenge: proper control flow function square(x) { return x*x; } at pointcut(call(square)) after(x) { print(“x = ”, x, “ x*x = ”, retval); } function square(x) { return x*x; print(“x = ”, x, “ x*x = ”, retval); } Naïve inlining Dead code!

Medium case: Advising script functions (2/2)  Solution: play games with either JS or with the codegen, to change the target of that return  Note: Do not try this at home! function square(x) { while (true) { return x*x; } print(“x = ”, x, “ x*x = ”, retval); } retval = x*x; break; retval = x*x; break;

Hard case: Predefined functions (1/2) print ReferenceToProperty Type[] expectedTypes Delegate doPrint Delegate GetDelegate( params Type[] offeredTypes ) print(“Three and five makes ”, 3+5) PredefinedFunction new Delegate((s, d) => { String d’ = d.ToString(); return doPrint(s, d’) } Delegate 1.Resolve reference 2.Call GetDelegate(String, Double) on the PredefinedFunction 1.Offered types (String, Double) don’t match expected types (String, String) 2.Create a thunk that converts argument types and calls doPrint 3.Call the delegate

Hard case: Predefined functions (2/2) print ReferenceToProperty Type[] expectedTypes List advice Delegate doPrint Delegate GetDelegate( params Type[] offeredTypes ) print(“Three and five makes ”, 3+5) PredefinedFunction 1.Resolve reference 2.Call GetDelegate(String, Double) on the PredefinedFunction 1.There’s advice, so construct a ScriptFunction that calls the original doPrint delegate 2.Install the advice on the ScriptFunction 3.Call GetDelegate(String, Double) on the ScriptFunction 1.Construct a thunk, as before, and return it 3.Call the delegate Type[] expectedTypes List advice function (args) { doPrint(args) } ScriptFunction List advice at pointcut(call(print))...

Outline  Motivation: Browser extensions  Aspects for JavaScript  Implementation challenges  Future work