How Facebook fixed its Gingerbread Dalvik problem

Facebook developers had faced many challenges when developing their app for older platforms like Android 2.2 Froyo and Android 2.3 Gingerbread. When Facebook completely revamped its app last year to provide a better user experience, they discovered that the app did not play well with older Android devices. They discovered that the problem had to do with a program called "dexopt" which determines a fixed-size buffer called "LinearAlloc" of apps installed on a specific device. While the buffer size is 8 or 16 MB in size for newer Android versions like Ice Cream Sandwich and Jelly Bean, its only 5 MB in the older versions.

The group was able to come up with a solution by injecting secondary dex files directly into the Android class loader, but then another problem appeared. It turns out that the Facebook app would crash immediately after startup because it had surpassed the method limit set by Android's virtual machine, Dalvik. The team was at a stand-still, unsure what they could do to fix the problem. They thought that they would have to cut out various features in their Facebook 2.0 app, or just restrict the revamped app to devices with newer versions of Android.

The developers thought "if we could only increase that buffer from 5 MB to 8 MB, we would be safe!". They realized that they needed to find the LinearAllocHdr object, "lock it, and replace the buffer." They then had an idea of using a JNI extension to replace the existing buffer with a bigger one. They found the proper value in the vmList using the JavaVM pointer in JNI, they scanned the DvmGlobals object to find the match, found the LinearAlloc header and replaced the buffer. They were able to build the JNI extension and implement it into the Facebook app.

They ran into a small issue with the Samsung Galaxy S II, which they dubbed as "the most popular Gingerbread phone of all time". The buffer size was 4 bytes off, so they had to safely scan the process heap to search for the correct buffer. After they found the fix, they created a test app, and with the help of manual testing, DeviceAnywhere, and a Google test lab, they were able to test their new Facebook app on 70 different Android devices. To their relief, the app successfully worked on each device.

The team thanks Google and Android for being an open source platform. If the platform wasn't open, they wouldn't have been able to "ship our best version of the app". Facebook also has its extensive training program to thank for that. The program, which was started last year, helped many Facebook staff members discover the reasoning behind the Gingerbread/Facebook debacle.

[via Facebook]