Category Archives: Uncategorized

Mozilla Research is on a roll

I was struck by the following slide from Brendan’s Mozilla-at-15 post.

Current Mozilla Research projects

Hot damn, those are some impressive projects.

Don’t make me guess who you are

I read Planet Mozilla through Google Reader.  When I see a post with a title that sounds interesting, I open it in a new tab.  If I’m lucky, I’ll get a blog that looks like this:

blog header

It’s totally clear whose blog this is.  This is good.  Bonus points for a subtitle that gives a good idea of what the blog is about.

But all too often the author’s name isn’t prominent.  Maybe it’s down the bottom of the post:  “Posted by J. Programmer.”  Sometimes it’s tucked away on a separate “about” page.  Sometimes people use a nickname that is meaningless to me.  And sometimes there is no name at all.

It’s even worse when this lack of identification is combined with one of the common WordPress templates — then I can’t even tell if I’m reading the same blog as the last one I saw that had that same theme.

So:  put your name somewhere prominent on your blog.  Preferably in the title or subtitle.  Please don’t make me guess who you are.

This blog’s URL has changed

This blog recently moved from blog.mozilla.com/nnethercote to blog.mozilla.org/nnethercote.  This move broke the captcha I use for comments for a couple of days.  The breakage has now been fixed, sorry for any inconvenience!

Testing the top 100 add-ons for memory leaks

Yesterday I mentioned that the plan for testing the top 100 add-ons for memory leaks had hit a snag — our list is that of the top 100 installed add-ons, rather than the top 100 enabled add-ons, and the latter is what we really want.

However, after some thought, I’ve concluded that there is likely to be a lot of overlap between the two lists.  For example, I’d be surprised if any of the top 50 enabled add-ons are not in the top 100 installed add-ons list.  Furthermore, this kind of testing will never give perfect coverage anyway.

Therefore, there’s little point in delaying the testing while we wait for a better top 100 list.  If you are interested in helping, please jump in.  And if you contact me privately I’ll be able to suggest some add-ons that are towards the more popular end of the top 100 list.  Thanks, and apologies for any confusion I have caused!

MemShrink progress, week 20

Surprise of the week

[Update: This analysis about livemarks may be wrong.  Talos results from early September show that the MaxHeaps number increased, and the reduction when the "Latest Headlines" livemark was removed has undone that increase.  So livemarks may not be responsible at all, it could just be a coincidence.  More investigation is needed!]

Jeff Muizelaar removed the “Latest Headlines” live bookmark from new profiles.  This was in the Bookmarks Toolbar, and so hasn’t been visible since Firefox 4.0, and most people don’t use it.  And it uses a non-zero amount of memory and CPU.  Just how non-zero was unclear until Marco Bonardo noticed some big performance improvements.  First, in the Talos “MaxHeap” results on WinNT5.2:

Talos MaxHeap graph

And secondly in the Talos “Allocs” results on WinNT5.2 and Mac10.5.2:

Talos Allocs graph

In the WinNT5.2 cases, it looks like we had a bi-modal distribution previously, and this patch changed things so that the higher of the two cases never occurred.  In the Mac10.5.2 case we just had a simple reduction in the number of allocations.  On Linux the results were less conclusive, but there may have been a similar if smaller effect.

This surprised me greatly.  I’ve done a lot of memory profiling of Firefox and never seen anything that pointed to the feed reader as using a lot of memory.  This may be because the feed reader’s usage is falling into a larger, innocuous bucket, such as JS or generic strings.  Or maybe I just missed the signs altogether.

Some conclusions and questions:

  • If you have live bookmarks in your bookmarks toolbar, remove them! [Update: I meant to say "unused live bookmarks".]
  • We need to work out what is going on with the feed reader, and optimize its memory usage.
  • Can we disable unused live bookmarks for existing users?

Apparently nobody really owns the feed reader, because previous contributors to it have all moved on.  So I’m planning to investigate, but I don’t know the first thing about it.  Any help would be welcome!

 Other stuff

There was a huge memory leak in the Video DownloadHelper add-on v4.9.5, and possibly earlier versions.  This has been fixed in v4.9.6a3 and the fix will make it into the final version v4.9.6 when it is released.  That’s one more add-on leak down, I wonder how many more there are to go.

TraceMonkey, the trace JIT, is no longer built by default.  This means it’s no longer used, and this saves both code and data space.  The old combination of TraceMonkey and JaegerMonkey is slower than the new combination of JaegerMonkey with type inference, and TraceMonkey is also preventing various clean-ups and simplifications, so it’ll be removed entirely soon.

I refined the JS memory reporters in about:memory to give more information about objects, shapes and property tables.

I avoided creating small property tables, removed KidHashes when possible, and reduced the size of KidHashes with few entries.

I wrote about various upcoming memory optimizations in the JS engine.

Justin Lebar enabled jemalloc on MacOS 10.5 builds.  This was expected to be a space improvement, but it also reduced the “Tp5 MozAfterPaint” page loading benchmark by 8%.

Robert O’Callahan avoided excessive memory usage in certain DOM animations on Windows.

Drew Willcoxon avoided excessive memory usage in context menu items created by the add-on SDK.

Bug Counts

  • P1: 35 (-1, +1)
  • P2: 116 (-2, +5)
  • P3: 55 (-2, +3)
  • Unprioritized: 5 (-4, +5)

At this week’s MemShrink meeting we only had 9 bugs to triage, which is the lowest we’ve had in a long time.  It feels like the MemShrink bug list is growing slower than in the past.

Faster JavaScript parsing

Over the past year or so I’ve almost doubled the speed of SpiderMonkey’s JavaScript parser.  I did this by speeding up both the scanner (bug 564369, bug 584595, bug 588648, bug 639420, bug 645598) and the parser (bug 637549).  I used patch stacks in several of those bugs, and so in those six bugs I actually landed 28 changesets.

Notable things about scanning JavaScript code

Before I explain the changes I made, it will help to explain a few notable things about scanning JavaScript code.

  • JavaScript is encoded using UCS-2.  This means that each character is 16 bits.
  • There are several character sequences that indicate the end of a line (EOL): ‘\n’, ‘\r’, ‘\r\n’, \u2028 (a.k.a. LINE_SEPARATOR), and \u2029 (a.k.a. PARA_SEPARATOR).  Note that ‘\r\n’ is treated as a single character.
  • JavaScript code is often minified, and the characteristics of minified and non-minified code are quite different.  The most important difference is that minified code has much less whitespace.

Scanning improvements

Before I made any changes, there were two different modes in which the scanner could operate.  In the first mode, the entire character stream to be scanned was already in memory.  In the second, the scanner read the characters from a file in chunks a few thousand chars long.  Firefox always uses the first mode (except in the rare case where the platform doesn’t support mmap or an equivalent function), but the JavaScript shell used the second.  Supporting the second made made things complicated in two ways.

  • It was possible for an ‘\r\n’ EOL sequence to be split across two chunks, which required some extra checking code.
  • The scanner often needs to unget chars (up to six chars, due to the lookahead required for \uXXXX sequences), and it couldn’t unget chars across a chunk boundary.  This meant that it used a six-char unget buffer.  Every time a char was ungotten, it would be copied into this buffer.  As a consequence, every time it had to get a char, it first had to look in the unget buffer to see if there was one or more chars that had been previously ungotten.  This was an extra check (and a data-dependent and thus unpredictable check).

The first complication was easy to avoid by only reading N-1 chars into the chunk buffer, and only reading the Nth char in the ‘\r\n’ case.  But the second complication was harder to avoid with that design.  Instead, I just got rid of the second mode of operation;  if the JavaScript engine needs to read from file, it now reads the whole file into memory and then scans it via the first mode.  This can result in more memory being used but it only affects the shell, not the browser, so it was an acceptable change.  This allowed the unget buffer to be completely removed;  when a character is ungotten now the scanner just moves back one char in the char buffer being scanned.

Another improvement was that in the old code, there was an explicit EOL normalization step.  As each char was gotten from the memory buffer, the scanner would check if it was an EOL sequence;  if so it would change it to ‘\n’, if not, it would leave it unchanged.  Then it would copy this normalized char into another buffer, and scanning would proceed from this buffer.  (The way this copying worked was strange and confusing, to make things worse.)  I changed it so that getChar() would do the normalization without requiring the copy into the second buffer.

The scanner has to detect EOL sequences in order to know which line it is on.  At first glance, this requires checking every char to see if it’s an EOL, and the scanner uses a small look-up table to make this fast.  However, it turns out that you don’t have to check every char.  For example, once you know that you’re scanning an identifier, you know that if you hit an EOL sequence you’ll immediately unget it, because that marks the end of the identifier.  And when you unget that char you’ll undo the line update that you did when you hit the EOL.  This same logic applies in other situations (eg. parsing a number).  So I added a function getCharIgnoreEOL() that doesn’t do the EOL check.  It has to always be paired with ungetCharIgnoreEOL() and requires some care as to where it’s used, but it avoids the EOL check on more than half the scanned chars.

As well as detecting where each token starts and ends, for a lot of token kinds the scanner has to compute a value.  For example, after scanning the character sequence ” 123 ” it has to convert that to the number 123.  The old scanner would copy the chars into a temporary buffer before calling the function that did the conversion.  This was unnecessary — the conversion function didn’t even require NULL-terminated strings because it gets passed the length of the string being converted!  Also, the old scanner was using js_strtod() to do the number conversion.  js_strtod() can convert both integers and fractional numbers, but its quite slow and overkill for integers.  And when scanning, even before converting the string to a number, we know if the number we just scanned was an integer or not (by remembering if we saw a ‘.’ or exponent).  So now the scanner instead calls GetPrefixInteger() which is much faster.  Several of the tests in Kraken involve huge arrays of integers, and this made a big difference to them.

There’s a similar story with identifiers, but with an added complication.  Identifiers can contain \uXXXX chars, and these need to be normalized before we do more with the string inside SpiderMonkey.  So the scanner now remembers whether a \uXXXX char has occurred in an identifier.  If not, it can work directly (temporarily) with the copy of the string inside the char buffer.  Otherwise, the scanner will rescan the identifier, normalizing and copying it into a new buffer.  I.e. the scanner de-optimizes the (very) rare case in order to avoid the copying in the common case.

JavaScript supports decimal, hexadecimal and octal numbers.  The number-scanning code handled all three kinds in the same loop, which meant that it checked the radix every time it scanned another number char.  So I split this into three parts, which make it both faster and easier to read.

Although JavaScript chars are 16 bits, the vast majority of chars you see are in the first 128 chars.  This is true even for code written in non-Latin scripts, because of all the keywords (e.g. ‘var’) and operators (e.g. ‘+’) and punctuation (e.g. ‘;’).  So it’s worth optimizing for those.  The main scanning loop (in getTokenInternal()) now first checks every char to see if its value is greater than 128.  If so, it handles it in a side-path (the only legitimate such chars are whitespace, EOL or identifier chars, so that side-path is quite small).  The rest of getTokenInternal() can then assume that it’s a sub-128 char.  This meant I could be quite aggressive with look-up tables, because having lots of 128-entry look-up tables is fine, but having lots of 65,536-entry look-up tables would not be.  One particularly important look-up table is called firstCharKinds;  it tells you what kind of token you will have based on the first non-whitespace char in it.  For example, if the first char is a letter, it will be an identifier or keyword;  if the first char is a ’0′ it will be a number;  and so on.

Another important look-up table is called oneCharTokens.  There are a handful of tokens that are one-char long, cannot form a valid prefix of another token, and don’t require any additional special handling:  ;,?[]{}().  These account for 35–45% of all tokens seen in real code!  The scanner can detect them immediately and use another look-up table to convert the token char to the internal token kind without any further tests.  After that, the rough order of frequency for different token kinds is as follows:  identifiers/keywords, ‘.’, ‘=’, strings, decimal numbers, ‘:’, ‘+’, hex/octal numbers, and then everything else.  The scanner now looks for these token kinds in that order.

That’s just a few of the improvements, there were lots of other little clean-ups.  While writing this post I looked at the old scanning code, as it was before I started changing it.  It was awful, it’s really hard to see what was happening;  getChar() was 150 lines long because it included code for reading the next chunk from file (if necessary) and also normalizing EOLs.

In comparison, as well as being much faster, the new code is much easier to read, and much more DFA-like.  It’s worth taking a look at getTokenInternal() in jsscan.cpp.

Parsing improvements

The parsing improvements were all related to the parsing of expressions.  When the parser parses an expression like “3″ it needs to look for any following operators, such as “+”.  And there are roughly a dozen levels of operator precedence.  The way the parser did this was to get the next token, check if it matched any of the operators of a particular precedence, and then unget the token if it didn’t match.  It would then repeat these steps for the next precedence level, and so on.  So if there was no operator after the “3″, the parser would have gotten and ungotten the next token a dozen times!  Ungetting and regetting tokens is fast, because there’s a buffer used (i.e. you don’t rescan the token char by char) but it was still a bottleneck.  I changed it so that the sub-expression parsers were expected to parse one token past the end of the expression, instead of zero tokesn past the end.  This meant that the repeated getting/ungetting could be avoided.

These operator parsers are also very small.  I inlined them more aggressively, which also helped quite a bit.

Results

I had some timing results but now I can’t find them.  But I know that the overall speed-up from my changes was about 1.8x on Chris Leary’s parsemark suite, which takes code from lots of real sites, and the variation in parsing times for different codebases tends not to vary that much.

Many real websites, e.g. gmail, have MB of JS code, and this speed-up will probably save one or two tenths of a second when they load.  Not something you’d notice, but certainly something that’ll add up over time and help make the browser feel snappier.

Tools

I used Cachegrind to drive most of these changes.  It has two features that were crucial.

First, it does event-based profiling, i.e. it counts instructions, memory accesses, etc, rather than time.  When making a lot of very small improvements, noise variations often swamp the effects of the improvements, so being able to see that instruction counts are going down by 0.2% here, 0.3% there, is very helpful.

Second, it gives counts of these events for individual lines of source code.  This was particularly important for getTokenInternal(), which is the main scanning function and has around 700 lines;  function-level stats wouldn’t have been enough.

Warnings-as-errors in js/src/

Bug 609532 changed the way the JavaScript shell is built so that compile warnings are treated as errors.  We already had a zero-tolerance policy for compile warnings in js/src/, but they tend to creep in, especially on Windows, because most people develop on Mac or Linux.  Already at least one Windows build turned red because of a warning, and it was immediately fixed by the dev responsible. Previously that warning would have lasted for days or weeks until someone on Windows got sick enough of it to fix it.

I’d love to see the same thing done for the entire browser, but judging by the reams of compile warnings that go by when building the browser, this won’t happen any time soon.

Oh, and if you don’t know about make -s (a.k.a. make --silent or make --quiet), you should try it. It’s indispensible!

Community Service Announcement

Prepending ‘@’ to somebody’s name does something useful in Twitter.  Outside of Twitter, it’s extra typing and looks silly.

A note about umlauts

Umlauts appear on three German letters: ä, ö, ü.  If typing non-English characters is difficult, you can substitute ‘ae’, ‘oe’, ‘ue’ respectively.

If you can’t type “JägerMonkey”, you should type “JaegerMonkey”.  “JagerMonkey” is wrong.

Memory profiling Firefox on TechCrunch

Rob Sayre suggested TechCrunch to me as a good stress test for Firefox’s memory usage:

  {sayrer} take a look at techcrunch.com if you have a chance. that one is brutal.

So I measured space usage with Massif for a single TechCrunch tab, on 64-bit Linux. Here’s the high-level result:

  34.65% (371,376,128B) _dl_map_object_from_fd (dl-load.c:1199)
  21.14% (226,603,008B) pthread_create@@GLIBC_2.2.5 (allocatestack.c:483)
  08.93% (95,748,276B) in 4043 places, all below massif's threshold (00.20%)
  06.26% (67,112,960B) pa_shm_create_rw (in /usr/lib/libpulsecommon-0.9.21.so)
  03.10% (33,263,616B) JSC::ExecutablePool::systemAlloc(unsigned long) (ExecutableAllocatorPosix.cpp:43)
  02.67% (28,618,752B) NewOrRecycledNode(JSTreeContext*) (jsparse.cpp:670)
  01.90% (20,414,464B) js::PropertyTree::newShape(JSContext*, bool) (jspropertytree.cpp:97)
  01.57% (16,777,216B) GCGraphBuilder::AddNode(void*, nsCycleCollectionParticipant*) (nsCycleCollector.cpp:596)
  01.48% (15,841,208B) JSScript::NewScript(JSContext*, unsigned int, unsigned int, unsigned int, unsigned int, unsigned int, unsigned int, unsigned int, unsigned int, unsigned int, unsigned short, unsigned short, JSVersion) (jsutil.h:210)
  01.45% (15,504,752B) ChangeTable (pldhash.c:563)
  01.44% (15,478,784B) g_mapped_file_new (in /lib/libglib-2.0.so.0.2400.1)
  01.41% (15,167,488B) GCGraphBuilder::NoteScriptChild(unsigned int, void*) (mozalloc.h:229)
  01.37% (14,680,064B) js_NewFunction(JSContext*, JSObject*, int (*)(JSContext*, unsigned int, js::Value*), unsigned int, unsigned int, JSObject*, JSAtom*) (jsgcinlines.h:127)
  00.97% (10,383,040B) js::mjit::Compiler::finishThisUp(js::mjit::JITScript**) (jsutil.h:214)
  00.78% (8,388,608B) js::StackSpace::init() (jscntxt.cpp:164)
  00.69% (7,360,512B) pcache1Alloc (sqlite3.c:33491)
  00.62% (6,601,324B) PL_DHashTableInit (pldhash.c:268)
  00.59% (6,291,456B) js_NewStringCopyN(JSContext*, unsigned short const*, unsigned long) (jsgcinlines.h:127)
  00.59% (6,287,516B) nsTArray_base::EnsureCapacity(unsigned int, unsigned int) (nsTArray.h:88)
  00.52% (5,589,468B) gfxImageSurface::gfxImageSurface(gfxIntSize const&, gfxASurface::gfxImageFormat) (gfxImageSurface.cpp:111)
  00.49% (5,292,184B) js::Vector::growStorageBy(unsigned long) (jsutil.h:218)
  00.49% (5,283,840B) nsHTTPCompressConv::OnDataAvailable(nsIRequest*, nsISupports*, nsIInputStream*, unsigned int, unsigned int) (nsMemory.h:68)
  00.49% (5,255,168B) js::Parser::markFunArgs(JSFunctionBox*) (jsutil.h:210)
  00.49% (5,221,320B) nsStringBuffer::Alloc(unsigned long) (nsSubstring.cpp:209)
  00.43% (4,558,848B) _dl_map_object_from_fd (dl-load.c:1250)
  00.42% (4,554,740B) nsTArray_base::EnsureCapacity(unsigned int, unsigned int) (nsTArray.h:84)
  00.39% (4,194,304B) js_NewGCString(JSContext*) (jsgcinlines.h:127)
  00.39% (4,194,304B) js::NewCallObject(JSContext*, js::Bindings*, JSObject&, JSObject*) (jsgcinlines.h:127)
  00.39% (4,194,304B) js::NewNativeClassInstance(JSContext*, js::Class*, JSObject*, JSObject*) (jsgcinlines.h:127)
  00.39% (4,194,304B) JS_NewObject (jsgcinlines.h:127)
  00.35% (3,770,972B) js::PropertyTable::init(JSRuntime*, js::Shape*) (jsutil.h:214)
  00.35% (3,743,744B) NS_NewStyleContext(nsStyleContext*, nsIAtom*, nsCSSPseudoElements::Type, nsRuleNode*, nsPresContext*) (nsPresContext.h:306)
  00.34% (3,621,704B) XPT_ArenaMalloc (xpt_arena.c:221)
  00.31% (3,346,532B) nsCSSSelectorList::AddSelector(unsigned short) (mozalloc.h:229)
  00.30% (3,227,648B) js::InitJIT(js::TraceMonitor*) (jsutil.h:210)
  00.30% (3,207,168B) js::InitJIT(js::TraceMonitor*) (jsutil.h:210)
  00.30% (3,166,208B) js_alloc_temp_space(void*, unsigned long) (jsatom.cpp:689)
  00.28% (2,987,548B) nsCSSExpandedDataBlock::Compress(nsCSSCompressedDataBlock**, nsCSSCompressedDataBlock**) (mozalloc.h:229)
  00.27% (2,883,584B) js::detail::HashTable::SetOps, js::SystemAllocPolicy>::add(js::detail::HashTable::SetOps, js::SystemAllocPolicy>::AddPtr&, unsigned long const&) (jsutil.h:210)
  00.26% (2,752,512B) FT_Stream_Open (in /usr/lib/libfreetype.so.6.3.22)
  00.24% (2,564,096B) PresShell::AllocateFrame(nsQueryFrame::FrameIID, unsigned long) (nsPresShell.cpp:2098)
  00.21% (2,236,416B) nsRecyclingAllocator::Malloc(unsigned long, int) (nsRecyclingAllocator.cpp:170)

Total memory usage at peak was 1,071,940,088 bytes. Lets go through some of these entries one by one.

  34.65% (371,376,128B) _dl_map_object_from_fd (dl-load.c:1199)
  21.14% (226,603,008B) pthread_create@@GLIBC_2.2.5 (allocatestack.c:483)
  06.26% (67,112,960B) pa_shm_create_rw (in /usr/lib/libpulsecommon-0.9.21.so)

These three, although the biggest single entries, can be more or less ignored;  I explained why previously.

  03.10% (33,263,616B) JSC::ExecutablePool::systemAlloc() (ExecutableAllocatorPosix.cpp:43)

This is for code generated by JaegerMonkey.  I know very little about JaegerMonkey’s code generation so I don’t have any good suggestions for reducing it.  As I understand it very little effort has been made to minimize the size of the generated code so there may well be some easy wins there.

  02.67% (28,618,752B) NewOrRecycledNode() (jsparse.cpp:670)

This is for JSParseNode, the basic type from which JS parse trees are constructed.  Bug 626932 is open to shrink JSParseNode;  there are a couple of good ideas but not much progress has been made.  I hope to do more here but probably not in time for Firefox 4.0.

  01.90% (20,414,464B) js::PropertyTree::newShape() (jspropertytree.cpp:97)

Shapes are a structure used to speed up JS property accesses.  Increasing the MAX_HEIGHT constant from 64 to 128 (which reduces the number of JS objects that are converted to “dictionary mode”, and thus the number of Shapes that are allocated) may reduce this by 3 or 4 MB with negligible speed cost.  I opened bug 630456 for this.

  01.57% (16,777,216B) GCGraphBuilder::AddNode() (nsCycleCollector.cpp:596)
  01.41% (15,167,488B) GCGraphBuilder::NoteScriptChild() (mozalloc.h:229)

This is the cycle collector.  I know almost nothing about it, but I see it allocates 32,768 PtrInfo structs at a time.  I wonder if that strategy could be improved.

  01.48% (15,841,208B) JSScript::NewScript() (jsutil.h:210)
  01.37% (14,680,064B) js_NewFunction() (jsgcinlines.h:127)

Each JS function has a JSFunction associated with it, and each JSFunction has a JSScript associated with it.  Each of them stores various bits of information about the function.  I don’t have any good ideas for how to shrink these structures.  Both of them are reasonably large, with lots of fields.

  00.97% (10,383,040B) js::mjit::Compiler::finishThisUp() (jsutil.h:214)

Each function compiled by JaegerMonkey also has some additional information associated with it, including all the inline caches.  This is allocated here.  Some good progress has already been made here, and I have some more ideas for getting it down a bit further.

  00.59% (6,291,456B) js_NewStringCopyN() (jsgcinlines.h:127)
  00.49% (5,292,184B) js::Vector::growStorageBy() (jsutil.h:218)

These entries are for space used during JS scanning (a.k.a. lexing, tokenizing).  Identifiers and strings get atomized, i.e. put into a table so there’s a single copy of each one.  Take an identifier as an example.  It starts off stored in a buffer of characters.  It gets scanned and copied into a js::Vector, with any escaped chars being converted along the way.  Then the copy in the js::Vector is atomized, which involves copying it again into a malloc’d buffer of just the right size.  I thought about avoiding this copying in bug 588648, but it turned out to be difficult.  (I did manage to remove another extra copy of every character, though!)

In summary, there is definitely room for more improvement.  I hope to get a few more space optimizations in before Firefox 4.0 is released, but there’ll be plenty of other work to do afterwards.  If anyone can see other easy wins for the entries above, I’d love to hear about them.