am ca234a07: am 8656ba12: Merge "Fix bug 4501658 - adjust toast frame padding" into honeycomb-mr2

* commit 'ca234a0765e3b43ab202f29caceba68b7c5363df':
  Fix bug 4501658 - adjust toast frame padding
diff --git a/api/current.xml b/api/current.xml
index 7670bc9..e927eca 100644
--- a/api/current.xml
+++ b/api/current.xml
@@ -93722,6 +93722,17 @@
  visibility="public"
 >
 </field>
+<field name="TYPE_RELATIVE_HUMIDITY"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="12"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="TYPE_ROTATION_VECTOR"
  type="int"
  transient="false"
@@ -227307,6 +227318,17 @@
  visibility="public"
 >
 </method>
+<method name="getScaledLargeTouchSlop"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
 <method name="getScaledMaximumDrawingCacheSize"
  return="int"
  abstract="false"
diff --git a/core/java/android/accounts/AccountManagerService.java b/core/java/android/accounts/AccountManagerService.java
index 894e196..93983a6 100644
--- a/core/java/android/accounts/AccountManagerService.java
+++ b/core/java/android/accounts/AccountManagerService.java
@@ -1786,22 +1786,6 @@
         }
     }
 
-    private String getMetaValue(String key) {
-        synchronized (mCacheLock) {
-            final SQLiteDatabase db = mOpenHelper.getReadableDatabase();
-            Cursor c = db.query(TABLE_META,
-                    new String[]{META_VALUE}, META_KEY + "=?", new String[]{key}, null, null, null);
-            try {
-                if (c.moveToNext()) {
-                    return c.getString(0);
-                }
-                return null;
-            } finally {
-                c.close();
-            }
-        }
-    }
-
     public IBinder onBind(Intent intent) {
         return asBinder();
     }
diff --git a/core/java/android/app/Dialog.java b/core/java/android/app/Dialog.java
index 087753b..82186dd 100644
--- a/core/java/android/app/Dialog.java
+++ b/core/java/android/app/Dialog.java
@@ -931,7 +931,7 @@
 
         // associate search with owner activity
         final ComponentName appName = getAssociatedActivity();
-        if (appName != null) {
+        if (appName != null && searchManager.getSearchableInfo(appName) != null) {
             searchManager.startSearch(null, false, appName, null, false);
             dismiss();
             return true;
diff --git a/core/java/android/bluetooth/BluetoothDeviceProfileState.java b/core/java/android/bluetooth/BluetoothDeviceProfileState.java
index 6f3a2e7..56f236d 100644
--- a/core/java/android/bluetooth/BluetoothDeviceProfileState.java
+++ b/core/java/android/bluetooth/BluetoothDeviceProfileState.java
@@ -679,7 +679,6 @@
         @Override
         public boolean processMessage(Message message) {
             log("IncomingA2dp State->Processing Message: " + message.what);
-            Message deferMsg = new Message();
             switch(message.what) {
                 case CONNECT_HFP_OUTGOING:
                     deferMessage(message);
diff --git a/core/java/android/content/res/AssetManager.java b/core/java/android/content/res/AssetManager.java
index 72fca0a..dbb4271 100644
--- a/core/java/android/content/res/AssetManager.java
+++ b/core/java/android/content/res/AssetManager.java
@@ -235,6 +235,7 @@
             StringBlock[] blocks = mStringBlocks;
             if (blocks == null) {
                 ensureStringBlocks();
+                blocks = mStringBlocks;
             }
             outValue.string = blocks[block].get(outValue.data);
             return true;
diff --git a/core/java/android/hardware/Sensor.java b/core/java/android/hardware/Sensor.java
index f2b907b..595c7d1 100644
--- a/core/java/android/hardware/Sensor.java
+++ b/core/java/android/hardware/Sensor.java
@@ -97,6 +97,13 @@
      */
     public static final int TYPE_ROTATION_VECTOR = 11;
 
+    /**
+     * A constant describing a relative humidity sensor type.
+     * See {@link android.hardware.SensorEvent SensorEvent}
+     * for more details.
+     */
+    public static final int TYPE_RELATIVE_HUMIDITY = 12;
+
     /** 
      * A constant describing all sensor types.
      */
diff --git a/core/java/android/hardware/SensorEvent.java b/core/java/android/hardware/SensorEvent.java
index 78d7991..9b62a68 100644
--- a/core/java/android/hardware/SensorEvent.java
+++ b/core/java/android/hardware/SensorEvent.java
@@ -304,7 +304,65 @@
      * in the clockwise direction (mathematically speaking, it should be
      * positive in the counter-clockwise direction).
      * </p>
-     * 
+     *
+     * <h4>{@link android.hardware.Sensor#TYPE_RELATIVE_HUMIDITY
+     * Sensor.TYPE_RELATIVE_HUMIDITY}:</h4>
+     * <ul>
+     * <p>
+     * values[0]: Relative ambient air humidity in percent
+     * </p>
+     * </ul>
+     * <p>
+     * When relative ambient air humidity and ambient temperature are
+     * measured, the dew point and absolute humidity can be calculated.
+     * </p>
+     * <u>Dew Point</u>
+     * <p>
+     * The dew point is the temperature to which a given parcel of air must be
+     * cooled, at constant barometric pressure, for water vapor to condense
+     * into water.
+     * </p>
+     * <center><pre>
+     *                    ln(RH/100%) + m&#183;t/(T<sub>n</sub>+t)
+     * t<sub>d</sub>(t,RH) = T<sub>n</sub> &#183; ------------------------------
+     *                 m - [ln(RH/100%) + m&#183;t/(T<sub>n</sub>+t)]
+     * </pre></center>
+     * <dl>
+     * <dt>t<sub>d</sub></dt> <dd>dew point temperature in &deg;C</dd>
+     * <dt>t</dt>             <dd>actual temperature in &deg;C</dd>
+     * <dt>RH</dt>            <dd>actual relative humidity in %</dd>
+     * <dt>m</dt>             <dd>17.62</dd>
+     * <dt>T<sub>n</sub></dt> <dd>243.12 &deg;C</dd>
+     * </dl>
+     * <p>for example:</p>
+     * <pre class="prettyprint">
+     * h = Math.log(rh / 100.0) + (17.62 * t) / (243.12 + t);
+     * td = 243.12 * h / (17.62 - h);
+     * </pre>
+     * <u>Absolute Humidity</u>
+     * <p>
+     * The absolute humidity is the mass of water vapor in a particular volume
+     * of dry air. The unit is g/m<sup>3</sup>.
+     * </p>
+     * <center><pre>
+     *                    RH/100%&#183;A&#183;exp(m&#183;t/(T<sub>n</sub>+t))
+     * d<sub>v</sub>(t,RH) = 216.7 &#183; -------------------------
+     *                           273.15 + t
+     * </pre></center>
+     * <dl>
+     * <dt>d<sub>v</sub></dt> <dd>absolute humidity in g/m<sup>3</sup></dd>
+     * <dt>t</dt>             <dd>actual temperature in &deg;C</dd>
+     * <dt>RH</dt>            <dd>actual relative humidity in %</dd>
+     * <dt>m</dt>             <dd>17.62</dd>
+     * <dt>T<sub>n</sub></dt> <dd>243.12 &deg;C</dd>
+     * <dt>A</dt>             <dd>6.112 hPa</dd>
+     * </dl>
+     * <p>for example:</p>
+     * <pre class="prettyprint">
+     * dv = 216.7 *
+     * (rh / 100.0 * 6.112 * Math.exp(17.62 * t / (243.12 + t)) / (273.15 + t));
+     * </pre>
+     *
      * @see SensorEvent
      * @see GeomagneticField
      */
diff --git a/core/java/android/nfc/ApduList.aidl b/core/java/android/nfc/ApduList.aidl
new file mode 100644
index 0000000..f6236b2
--- /dev/null
+++ b/core/java/android/nfc/ApduList.aidl
@@ -0,0 +1,19 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.nfc;
+
+parcelable ApduList;
\ No newline at end of file
diff --git a/core/java/android/nfc/ApduList.java b/core/java/android/nfc/ApduList.java
new file mode 100644
index 0000000..85b0547
--- /dev/null
+++ b/core/java/android/nfc/ApduList.java
@@ -0,0 +1,68 @@
+package android.nfc;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @hide
+ */
+public class ApduList implements Parcelable {
+
+    private ArrayList<byte[]> commands = new ArrayList<byte[]>();
+
+    public ApduList() {
+    }
+
+    public void add(byte[] command) {
+        commands.add(command);
+    }
+
+    public List<byte[]> get() {
+        return commands;
+    }
+
+    public static final Parcelable.Creator<ApduList> CREATOR =
+        new Parcelable.Creator<ApduList>() {
+        @Override
+        public ApduList createFromParcel(Parcel in) {
+            return new ApduList(in);
+        }
+
+        @Override
+        public ApduList[] newArray(int size) {
+            return new ApduList[size];
+        }
+    };
+
+    private ApduList(Parcel in) {
+        int count = in.readInt();
+
+        for (int i = 0 ; i < count ; i++) {
+
+            int length = in.readInt();
+            byte[] cmd = new byte[length];
+            in.readByteArray(cmd);
+            commands.add(cmd);
+        }
+    }
+
+    @Override
+    public int describeContents() {
+        return 0;
+    }
+
+    @Override
+    public void writeToParcel(Parcel dest, int flags) {
+        dest.writeInt(commands.size());
+
+        for (byte[] cmd : commands) {
+            dest.writeInt(cmd.length);
+            dest.writeByteArray(cmd);
+        }
+    }
+}
+
+
diff --git a/core/java/android/nfc/INfcAdapterExtras.aidl b/core/java/android/nfc/INfcAdapterExtras.aidl
index ab5c1a6..8677a50 100755
--- a/core/java/android/nfc/INfcAdapterExtras.aidl
+++ b/core/java/android/nfc/INfcAdapterExtras.aidl
@@ -16,8 +16,10 @@
 
 package android.nfc;
 
+import android.nfc.ApduList;
 import android.os.Bundle;
 
+
 /**
  * {@hide}
  */
@@ -26,5 +28,7 @@
     Bundle close();
     Bundle transceive(in byte[] data_in);
     int getCardEmulationRoute();
-    void setCardEmulationRoute(int route);    
+    void setCardEmulationRoute(int route);
+    void registerTearDownApdus(String packageName, in ApduList apdu);
+    void unregisterTearDownApdus(String packageName);
 }
diff --git a/core/java/android/os/BatteryStats.java b/core/java/android/os/BatteryStats.java
index 90e2e79..1d6bc4e2 100644
--- a/core/java/android/os/BatteryStats.java
+++ b/core/java/android/os/BatteryStats.java
@@ -1883,7 +1883,6 @@
         final int NU = uidStats.size();
         boolean didPid = false;
         long nowRealtime = SystemClock.elapsedRealtime();
-        StringBuilder sb = new StringBuilder(64);
         for (int i=0; i<NU; i++) {
             Uid uid = uidStats.valueAt(i);
             SparseArray<? extends Uid.Pid> pids = uid.getPidStats();
diff --git a/core/java/android/os/Looper.java b/core/java/android/os/Looper.java
index 8204e3c..ccf642c 100644
--- a/core/java/android/os/Looper.java
+++ b/core/java/android/os/Looper.java
@@ -141,7 +141,8 @@
                     Log.wtf("Looper", "Thread identity changed from 0x"
                             + Long.toHexString(ident) + " to 0x"
                             + Long.toHexString(newIdent) + " while dispatching to "
-                            + msg.target + " " + msg.callback + " what=" + msg.what);
+                            + msg.target.getClass().getName() + " "
+                            + msg.callback + " what=" + msg.what);
                 }
                 
                 msg.recycle();
diff --git a/core/java/android/os/Process.java b/core/java/android/os/Process.java
index 0c6ab9e..2bfada0 100644
--- a/core/java/android/os/Process.java
+++ b/core/java/android/os/Process.java
@@ -95,7 +95,7 @@
      * Defines the UID/GID for the NFC service process.
      * @hide
      */
-    public static final int NFC_UID = 1022;
+    public static final int NFC_UID = 1025;
 
     /**
      * Defines the GID for the group that allows write access to the internal media storage.
diff --git a/core/java/android/os/RecoverySystem.java b/core/java/android/os/RecoverySystem.java
index 4991914..c1dd911 100644
--- a/core/java/android/os/RecoverySystem.java
+++ b/core/java/android/os/RecoverySystem.java
@@ -16,6 +16,11 @@
 
 package android.os;
 
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
 import java.io.ByteArrayInputStream;
 import java.io.File;
 import java.io.FileNotFoundException;
@@ -37,9 +42,6 @@
 import java.util.zip.ZipEntry;
 import java.util.zip.ZipFile;
 
-import android.content.Context;
-import android.util.Log;
-
 import org.apache.harmony.security.asn1.BerInputStream;
 import org.apache.harmony.security.pkcs7.ContentInfo;
 import org.apache.harmony.security.pkcs7.SignedData;
@@ -336,8 +338,21 @@
      * @throws IOException  if writing the recovery command file
      * fails, or if the reboot itself fails.
      */
-    public static void rebootWipeUserData(Context context)
-        throws IOException {
+    public static void rebootWipeUserData(Context context) throws IOException {
+        final ConditionVariable condition = new ConditionVariable();
+
+        Intent intent = new Intent("android.intent.action.MASTER_CLEAR_NOTIFICATION");
+        context.sendOrderedBroadcast(intent, android.Manifest.permission.MASTER_CLEAR,
+                new BroadcastReceiver() {
+                    @Override
+                    public void onReceive(Context context, Intent intent) {
+                        condition.open();
+                    }
+                }, null, 0, null, null);
+
+        // Block until the ordered broadcast has completed.
+        condition.block();
+
         bootCommand(context, "--wipe_data");
     }
 
diff --git a/core/java/android/server/BluetoothService.java b/core/java/android/server/BluetoothService.java
old mode 100644
new mode 100755
index f98d275..b3cbf50
--- a/core/java/android/server/BluetoothService.java
+++ b/core/java/android/server/BluetoothService.java
@@ -1104,7 +1104,7 @@
     }
 
     /*package*/ synchronized boolean setBondState(String address, int state, int reason) {
-        mBondState.setBondState(address.toUpperCase(), state);
+        mBondState.setBondState(address.toUpperCase(), state, reason);
         return true;
     }
 
diff --git a/core/java/android/speech/RecognitionService.java b/core/java/android/speech/RecognitionService.java
index 75a5ed5..32b2d8f 100644
--- a/core/java/android/speech/RecognitionService.java
+++ b/core/java/android/speech/RecognitionService.java
@@ -68,6 +68,8 @@
 
     private static final int MSG_CANCEL = 3;
 
+    private static final int MSG_RESET = 4;
+
     private final Handler mHandler = new Handler() {
         @Override
         public void handleMessage(Message msg) {
@@ -81,6 +83,10 @@
                     break;
                 case MSG_CANCEL:
                     dispatchCancel((IRecognitionListener) msg.obj);
+                    break;
+                case MSG_RESET:
+                    dispatchClearCallback();
+                    break;
             }
         }
     };
@@ -128,6 +134,10 @@
         }
     }
 
+    private void dispatchClearCallback() {
+        mCurrentCallback = null;
+    }
+
     private class StartListeningArgs {
         public final Intent mIntent;
 
@@ -241,7 +251,7 @@
          * @param error code is defined in {@link SpeechRecognizer}
          */
         public void error(int error) throws RemoteException {
-            mCurrentCallback = null;
+            Message.obtain(mHandler, MSG_RESET).sendToTarget();
             mListener.onError(error);
         }
 
@@ -278,7 +288,7 @@
          *        {@link SpeechRecognizer#RESULTS_RECOGNITION} as a parameter
          */
         public void results(Bundle results) throws RemoteException {
-            mCurrentCallback = null;
+            Message.obtain(mHandler, MSG_RESET).sendToTarget();
             mListener.onResults(results);
         }
 
diff --git a/core/java/android/text/Layout.java b/core/java/android/text/Layout.java
index 1e4cca9..4107c5a 100644
--- a/core/java/android/text/Layout.java
+++ b/core/java/android/text/Layout.java
@@ -1170,7 +1170,7 @@
         if (h2 < 0.5f)
             h2 = 0.5f;
 
-        if (h1 == h2) {
+        if (Float.compare(h1, h2) == 0) {
             dest.moveTo(h1, top);
             dest.lineTo(h1, bottom);
         } else {
diff --git a/core/java/android/text/TextUtils.java b/core/java/android/text/TextUtils.java
index d5010c6..cdb7228 100644
--- a/core/java/android/text/TextUtils.java
+++ b/core/java/android/text/TextUtils.java
@@ -624,10 +624,16 @@
         public  CharSequence createFromParcel(Parcel p) {
             int kind = p.readInt();
 
-            if (kind == 1)
-                return p.readString();
+            String string = p.readString();
+            if (string == null) {
+                return null;
+            }
 
-            SpannableString sp = new SpannableString(p.readString());
+            if (kind == 1) {
+                return string;
+            }
+
+            SpannableString sp = new SpannableString(string);
 
             while (true) {
                 kind = p.readInt();
diff --git a/core/java/android/text/method/MultiTapKeyListener.java b/core/java/android/text/method/MultiTapKeyListener.java
index 6d94788..2a739fa 100644
--- a/core/java/android/text/method/MultiTapKeyListener.java
+++ b/core/java/android/text/method/MultiTapKeyListener.java
@@ -116,7 +116,7 @@
                     content.replace(selStart, selEnd,
                                     String.valueOf(current).toUpperCase());
                     removeTimeouts(content);
-                    Timeout t = new Timeout(content);
+                    new Timeout(content); // for its side effects
 
                     return true;
                 }
@@ -124,7 +124,7 @@
                     content.replace(selStart, selEnd,
                                     String.valueOf(current).toLowerCase());
                     removeTimeouts(content);
-                    Timeout t = new Timeout(content);
+                    new Timeout(content); // for its side effects
 
                     return true;
                 }
@@ -140,7 +140,7 @@
 
                     content.replace(selStart, selEnd, val, ix, ix + 1);
                     removeTimeouts(content);
-                    Timeout t = new Timeout(content);
+                    new Timeout(content); // for its side effects
 
                     return true;
                 }
@@ -206,7 +206,7 @@
             }
 
             removeTimeouts(content);
-            Timeout t = new Timeout(content);
+            new Timeout(content); // for its side effects
 
             // Set up the callback so we can remove the timeout if the
             // cursor moves.
diff --git a/core/java/android/text/style/DrawableMarginSpan.java b/core/java/android/text/style/DrawableMarginSpan.java
index 3c471a5..c2564d5 100644
--- a/core/java/android/text/style/DrawableMarginSpan.java
+++ b/core/java/android/text/style/DrawableMarginSpan.java
@@ -50,9 +50,6 @@
         int dw = mDrawable.getIntrinsicWidth();
         int dh = mDrawable.getIntrinsicHeight();
 
-        if (dir < 0)
-            x -= dw;
-
         // XXX What to do about Paint?
         mDrawable.setBounds(ix, itop, ix+dw, itop+dh);
         mDrawable.draw(c);
diff --git a/core/java/android/text/util/Rfc822Tokenizer.java b/core/java/android/text/util/Rfc822Tokenizer.java
index 69cf93c..68334e4 100644
--- a/core/java/android/text/util/Rfc822Tokenizer.java
+++ b/core/java/android/text/util/Rfc822Tokenizer.java
@@ -256,7 +256,7 @@
                     if (c == '"') {
                         i++;
                         break;
-                    } else if (c == '\\') {
+                    } else if (c == '\\' && i + 1 < len) {
                         i += 2;
                     } else {
                         i++;
@@ -275,7 +275,7 @@
                     } else if (c == '(') {
                         level++;
                         i++;
-                    } else if (c == '\\') {
+                    } else if (c == '\\' && i + 1 < len) {
                         i += 2;
                     } else {
                         i++;
diff --git a/core/java/android/view/GestureDetector.java b/core/java/android/view/GestureDetector.java
old mode 100644
new mode 100755
index c1e1049..79b3d42
--- a/core/java/android/view/GestureDetector.java
+++ b/core/java/android/view/GestureDetector.java
@@ -193,10 +193,8 @@
         }
     }
 
-    // TODO: ViewConfiguration
-    private int mBiggerTouchSlopSquare = 20 * 20;
-
     private int mTouchSlopSquare;
+    private int mLargeTouchSlopSquare;
     private int mDoubleTapSlopSquare;
     private int mMinimumFlingVelocity;
     private int mMaximumFlingVelocity;
@@ -384,10 +382,11 @@
         mIgnoreMultitouch = ignoreMultitouch;
 
         // Fallback to support pre-donuts releases
-        int touchSlop, doubleTapSlop;
+        int touchSlop, largeTouchSlop, doubleTapSlop;
         if (context == null) {
             //noinspection deprecation
             touchSlop = ViewConfiguration.getTouchSlop();
+            largeTouchSlop = touchSlop + 2;
             doubleTapSlop = ViewConfiguration.getDoubleTapSlop();
             //noinspection deprecation
             mMinimumFlingVelocity = ViewConfiguration.getMinimumFlingVelocity();
@@ -395,11 +394,13 @@
         } else {
             final ViewConfiguration configuration = ViewConfiguration.get(context);
             touchSlop = configuration.getScaledTouchSlop();
+            largeTouchSlop = configuration.getScaledLargeTouchSlop();
             doubleTapSlop = configuration.getScaledDoubleTapSlop();
             mMinimumFlingVelocity = configuration.getScaledMinimumFlingVelocity();
             mMaximumFlingVelocity = configuration.getScaledMaximumFlingVelocity();
         }
         mTouchSlopSquare = touchSlop * touchSlop;
+        mLargeTouchSlopSquare = largeTouchSlop * largeTouchSlop;
         mDoubleTapSlopSquare = doubleTapSlop * doubleTapSlop;
     }
 
@@ -534,7 +535,7 @@
                     mHandler.removeMessages(SHOW_PRESS);
                     mHandler.removeMessages(LONG_PRESS);
                 }
-                if (distance > mBiggerTouchSlopSquare) {
+                if (distance > mLargeTouchSlopSquare) {
                     mAlwaysInBiggerTapRegion = false;
                 }
             } else if ((Math.abs(scrollX) >= 1) || (Math.abs(scrollY) >= 1)) {
diff --git a/core/java/android/view/ViewConfiguration.java b/core/java/android/view/ViewConfiguration.java
old mode 100644
new mode 100755
index 739758c..2a74eb7
--- a/core/java/android/view/ViewConfiguration.java
+++ b/core/java/android/view/ViewConfiguration.java
@@ -129,6 +129,12 @@
     private static final int TOUCH_SLOP = 16;
     
     /**
+     * Distance a touch can wander before we think the user is the first touch
+     * in a sequence of double tap
+     */
+    private static final int LARGE_TOUCH_SLOP = 18;
+
+    /**
      * Distance a touch can wander before we think the user is attempting a paged scroll
      * (in dips)
      */
@@ -183,6 +189,7 @@
     private final int mMaximumFlingVelocity;
     private final int mScrollbarSize;
     private final int mTouchSlop;
+    private final int mLargeTouchSlop;
     private final int mPagingTouchSlop;
     private final int mDoubleTapSlop;
     private final int mWindowTouchSlop;
@@ -204,6 +211,7 @@
         mMaximumFlingVelocity = MAXIMUM_FLING_VELOCITY;
         mScrollbarSize = SCROLL_BAR_SIZE;
         mTouchSlop = TOUCH_SLOP;
+        mLargeTouchSlop = LARGE_TOUCH_SLOP;
         mPagingTouchSlop = PAGING_TOUCH_SLOP;
         mDoubleTapSlop = DOUBLE_TAP_SLOP;
         mWindowTouchSlop = WINDOW_TOUCH_SLOP;
@@ -240,6 +248,7 @@
         mMaximumFlingVelocity = (int) (density * MAXIMUM_FLING_VELOCITY + 0.5f);
         mScrollbarSize = (int) (density * SCROLL_BAR_SIZE + 0.5f);
         mTouchSlop = (int) (sizeAndDensity * TOUCH_SLOP + 0.5f);
+        mLargeTouchSlop =  (int) (sizeAndDensity * LARGE_TOUCH_SLOP + 0.5f);
         mPagingTouchSlop = (int) (sizeAndDensity * PAGING_TOUCH_SLOP + 0.5f);
         mDoubleTapSlop = (int) (sizeAndDensity * DOUBLE_TAP_SLOP + 0.5f);
         mWindowTouchSlop = (int) (sizeAndDensity * WINDOW_TOUCH_SLOP + 0.5f);
@@ -416,6 +425,14 @@
     }
     
     /**
+     * @return Distance a touch can wander before we think the user is the first touch
+     *         in a sequence of double tap
+     */
+    public int getScaledLargeTouchSlop() {
+        return mLargeTouchSlop;
+    }
+
+    /**
      * @return Distance a touch can wander before we think the user is scrolling a full page
      *         in dips
      */
diff --git a/core/java/android/webkit/CacheManager.java b/core/java/android/webkit/CacheManager.java
index 3ce0730..e21a02e 100644
--- a/core/java/android/webkit/CacheManager.java
+++ b/core/java/android/webkit/CacheManager.java
@@ -857,6 +857,7 @@
         String cacheControl = headers.getCacheControl();
         if (cacheControl != null) {
             String[] controls = cacheControl.toLowerCase().split("[ ,;]");
+            boolean noCache = false;
             for (int i = 0; i < controls.length; i++) {
                 if (NO_STORE.equals(controls[i])) {
                     return null;
@@ -867,7 +868,12 @@
                 // can only be used in CACHE_MODE_CACHE_ONLY case
                 if (NO_CACHE.equals(controls[i])) {
                     ret.expires = 0;
-                } else if (controls[i].startsWith(MAX_AGE)) {
+                    noCache = true;
+                // if cache control = no-cache has been received, ignore max-age
+                // header, according to http spec:
+                // If a request includes the no-cache directive, it SHOULD NOT
+                // include min-fresh, max-stale, or max-age.
+                } else if (controls[i].startsWith(MAX_AGE) && !noCache) {
                     int separator = controls[i].indexOf('=');
                     if (separator < 0) {
                         separator = controls[i].indexOf(':');
diff --git a/core/java/android/widget/PopupWindow.java b/core/java/android/widget/PopupWindow.java
index 4fcd7a9..a5b7281 100644
--- a/core/java/android/widget/PopupWindow.java
+++ b/core/java/android/widget/PopupWindow.java
@@ -1488,6 +1488,10 @@
         @Override
         public boolean dispatchKeyEvent(KeyEvent event) {
             if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
+                if (getKeyDispatcherState() == null) {
+                    return super.dispatchKeyEvent(event);
+                }
+
                 if (event.getAction() == KeyEvent.ACTION_DOWN
                         && event.getRepeatCount() == 0) {
                     KeyEvent.DispatcherState state = getKeyDispatcherState();
diff --git a/core/java/android/widget/ScrollView.java b/core/java/android/widget/ScrollView.java
index 4b4f5f2..ade3a0a 100644
--- a/core/java/android/widget/ScrollView.java
+++ b/core/java/android/widget/ScrollView.java
@@ -873,7 +873,7 @@
             int count = getChildCount();
             if (count > 0) {
                 View view = getChildAt(count - 1);
-                mTempRect.bottom = view.getBottom();
+                mTempRect.bottom = view.getBottom() + mPaddingBottom;
                 mTempRect.top = mTempRect.bottom - height;
             }
         }
@@ -949,9 +949,7 @@
             } else if (direction == View.FOCUS_DOWN) {
                 if (getChildCount() > 0) {
                     int daBottom = getChildAt(0).getBottom();
-
-                    int screenBottom = getScrollY() + getHeight();
-
+                    int screenBottom = getScrollY() + getHeight() - mPaddingBottom;
                     if (daBottom - screenBottom < maxJump) {
                         scrollDelta = daBottom - screenBottom;
                     }
diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java
index d86504d..2847cf3 100644
--- a/core/java/com/android/internal/os/BatteryStatsImpl.java
+++ b/core/java/com/android/internal/os/BatteryStatsImpl.java
@@ -4708,7 +4708,7 @@
         mHistory = mHistoryEnd = mHistoryCache = null;
         mHistoryBaseTime = 0;
         long time;
-        while ((time=in.readLong()) >= 0) {
+        while (in.dataAvail() > 0 && (time=in.readLong()) >= 0) {
             HistoryItem rec = new HistoryItem(time, in);
             addHistoryRecordLocked(rec);
             if (rec.time > mHistoryBaseTime) {
diff --git a/core/jni/Android.mk b/core/jni/Android.mk
index b549098..91a1935 100644
--- a/core/jni/Android.mk
+++ b/core/jni/Android.mk
@@ -101,6 +101,7 @@
 	android/graphics/Movie.cpp \
 	android/graphics/NinePatch.cpp \
 	android/graphics/NinePatchImpl.cpp \
+	android/graphics/NinePatchPeeker.cpp \
 	android/graphics/Paint.cpp \
 	android/graphics/Path.cpp \
 	android/graphics/PathMeasure.cpp \
diff --git a/core/jni/android/graphics/Movie.cpp b/core/jni/android/graphics/Movie.cpp
index de18f9f..d1a5546 100644
--- a/core/jni/android/graphics/Movie.cpp
+++ b/core/jni/android/graphics/Movie.cpp
@@ -115,6 +115,10 @@
     return create_jmovie(env, moov);
 }
 
+static void movie_destructor(JNIEnv* env, jobject, SkMovie* movie) {
+    delete movie;
+}
+
 //////////////////////////////////////////////////////////////////////////////////////////////
 
 #include <android_runtime/AndroidRuntime.h>
@@ -129,6 +133,7 @@
                             (void*)movie_draw  },
     { "decodeStream", "(Ljava/io/InputStream;)Landroid/graphics/Movie;",
                             (void*)movie_decodeStream },
+    { "nativeDestructor","(I)V", (void*)movie_destructor },
     { "decodeByteArray", "([BII)Landroid/graphics/Movie;",
                             (void*)movie_decodeByteArray },
 };
diff --git a/core/jni/android/graphics/NinePatchPeeker.cpp b/core/jni/android/graphics/NinePatchPeeker.cpp
new file mode 100644
index 0000000..365d985
--- /dev/null
+++ b/core/jni/android/graphics/NinePatchPeeker.cpp
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "NinePatchPeeker.h"
+
+#include "SkBitmap.h"
+
+using namespace android;
+
+bool NinePatchPeeker::peek(const char tag[], const void* data, size_t length) {
+    if (strcmp("npTc", tag) == 0 && length >= sizeof(Res_png_9patch)) {
+        Res_png_9patch* patch = (Res_png_9patch*) data;
+        size_t patchSize = patch->serializedSize();
+        assert(length == patchSize);
+        // You have to copy the data because it is owned by the png reader
+        Res_png_9patch* patchNew = (Res_png_9patch*) malloc(patchSize);
+        memcpy(patchNew, patch, patchSize);
+        // this relies on deserialization being done in place
+        Res_png_9patch::deserialize(patchNew);
+        patchNew->fileToDevice();
+        if (fPatchIsValid) {
+            free(fPatch);
+        }
+        fPatch = patchNew;
+        //printf("9patch: (%d,%d)-(%d,%d)\n",
+        //       fPatch.sizeLeft, fPatch.sizeTop,
+        //       fPatch.sizeRight, fPatch.sizeBottom);
+        fPatchIsValid = true;
+
+        // now update our host to force index or 32bit config
+        // 'cause we don't want 565 predithered, since as a 9patch, we know
+        // we will be stretched, and therefore we want to dither afterwards.
+        static const SkBitmap::Config gNo565Pref[] = {
+            SkBitmap::kIndex8_Config,
+            SkBitmap::kIndex8_Config,
+            SkBitmap::kARGB_8888_Config,
+            SkBitmap::kARGB_8888_Config,
+            SkBitmap::kARGB_8888_Config,
+            SkBitmap::kARGB_8888_Config,
+        };
+        fHost->setPrefConfigTable(gNo565Pref);
+    } else {
+        fPatch = NULL;
+    }
+    return true;    // keep on decoding
+}
diff --git a/core/jni/android/graphics/NinePatchPeeker.h b/core/jni/android/graphics/NinePatchPeeker.h
new file mode 100644
index 0000000..8567e23
--- /dev/null
+++ b/core/jni/android/graphics/NinePatchPeeker.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef NinePatchPeeker_h
+#define NinePatchPeeker_h
+
+#include "SkImageDecoder.h"
+#include <utils/ResourceTypes.h>
+
+using namespace android;
+
+class NinePatchPeeker : public SkImageDecoder::Peeker {
+    SkImageDecoder* fHost;
+public:
+    NinePatchPeeker(SkImageDecoder* host) {
+        // the host lives longer than we do, so a raw ptr is safe
+        fHost = host;
+        fPatchIsValid = false;
+    }
+
+    ~NinePatchPeeker() {
+        if (fPatchIsValid) {
+            free(fPatch);
+        }
+    }
+
+    bool    fPatchIsValid;
+    Res_png_9patch*  fPatch;
+
+    virtual bool peek(const char tag[], const void* data, size_t length);
+};
+
+#endif // NinePatchPeeker_h
diff --git a/core/jni/android_bluetooth_BluetoothSocket.cpp b/core/jni/android_bluetooth_BluetoothSocket.cpp
index b87f7c4..d09c4e9 100644
--- a/core/jni/android_bluetooth_BluetoothSocket.cpp
+++ b/core/jni/android_bluetooth_BluetoothSocket.cpp
@@ -448,7 +448,7 @@
 #ifdef HAVE_BLUETOOTH
     LOGV("%s", __FUNCTION__);
 
-    int ret;
+    int ret, total;
     jbyte *b;
     int sz;
     struct asocket *s = get_socketData(env, obj);
@@ -471,15 +471,21 @@
         return -1;
     }
 
-    ret = asocket_write(s, &b[offset], length, -1);
-    if (ret < 0) {
-        jniThrowIOException(env, errno);
-        env->ReleaseByteArrayElements(jb, b, JNI_ABORT);
-        return -1;
+    total = 0;
+    while (length > 0) {
+        ret = asocket_write(s, &b[offset], length, -1);
+        if (ret < 0) {
+            jniThrowIOException(env, errno);
+            env->ReleaseByteArrayElements(jb, b, JNI_ABORT);
+            return -1;
+        }
+        offset += ret;
+        total += ret;
+        length -= ret;
     }
 
     env->ReleaseByteArrayElements(jb, b, JNI_ABORT);  // no need to commit
-    return (jint)ret;
+    return (jint)total;
 
 #endif
     jniThrowIOException(env, ENOSYS);
diff --git a/core/jni/android_server_BluetoothEventLoop.cpp b/core/jni/android_server_BluetoothEventLoop.cpp
index afaade8..a6bde88 100644
--- a/core/jni/android_server_BluetoothEventLoop.cpp
+++ b/core/jni/android_server_BluetoothEventLoop.cpp
@@ -351,7 +351,7 @@
 {
     DBusMessage *msg, *reply;
     DBusError err;
-    bool oob = TRUE;
+    dbus_bool_t oob = TRUE;
 
     if (!dbus_connection_register_object_path(nat->conn, agent_path,
             &agent_vtable, nat)) {
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index bb31347..60cf939 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -57,6 +57,7 @@
     <protected-broadcast android:name="android.intent.action.NEW_OUTGOING_CALL" />
     <protected-broadcast android:name="android.intent.action.REBOOT" />
     <protected-broadcast android:name="android.intent.action.DOCK_EVENT" />
+    <protected-broadcast android:name="android.intent.action.MASTER_CLEAR_NOTIFICATION" />
 
     <protected-broadcast android:name="android.app.action.ENTER_CAR_MODE" />
     <protected-broadcast android:name="android.app.action.EXIT_CAR_MODE" />
@@ -1045,7 +1046,7 @@
     <permission android:name="android.permission.STOP_APP_SWITCHES"
         android:label="@string/permlab_stopAppSwitches"
         android:description="@string/permdesc_stopAppSwitches"
-        android:protectionLevel="signature" />
+        android:protectionLevel="signatureOrSystem" />
 
     <!-- Allows an application to retrieve the current state of keys and
          switches.  This is only for use by the system.-->
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index 4bcdac1..6980fa7 100755
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -566,4 +566,44 @@
          If false, mms read reports are not supported and the preference
          option to enable/disable read reports is removed in the Messaging app. -->
     <bool name="config_mms_read_reports_support">true</bool>
+
+    <!-- National Language Identifier codes for the following two config items.
+         (from 3GPP TS 23.038 V9.1.1 Table 6.2.1.2.4.1):
+          0  - reserved
+          1  - Turkish
+          2  - Spanish (single shift table only)
+          3  - Portuguese
+          4  - Bengali
+          5  - Gujarati
+          6  - Hindi
+          7  - Kannada
+          8  - Malayalam
+          9  - Oriya
+         10  - Punjabi
+         11  - Tamil
+         12  - Telugu
+         13  - Urdu
+         14+ - reserved -->
+
+    <!-- National language single shift tables to enable for SMS encoding.
+         Decoding is always enabled. 3GPP TS 23.038 states that this feature
+         should not be enabled until a formal request is issued by the relevant
+         national regulatory body. Array elements are codes from the table above.
+         Example 1: devices sold in Turkey must include table 1 to conform with
+           By-Law Number 27230. (http://www.btk.gov.tr/eng/pdf/2009/BY-LAW_SMS.pdf)
+         Example 2: devices sold in India should include tables 4 through 13
+           to enable use of the new Release 9 tables for Indic languages. -->
+    <integer-array name="config_sms_enabled_single_shift_tables"></integer-array>
+
+    <!-- National language locking shift tables to enable for SMS encoding.
+         Decoding is always enabled. 3GPP TS 23.038 states that this feature
+         should not be enabled until a formal request is issued by the relevant
+         national regulatory body. Array elements are codes from the table above.
+         Example 1: devices sold in Turkey must include table 1 after the
+           Turkish Telecommunication Authority requires locking shift encoding
+           to be enabled (est. July 2012). (http://www.btk.gov.tr/eng/pdf/2009/BY-LAW_SMS.pdf)
+           See also: http://www.mobitech.com.tr/tr/ersanozturkblog_en/index.php?entry=entry090223-160014
+         Example 2: devices sold in India should include tables 4 through 13
+         to enable use of the new Release 9 tables for Indic languages. -->
+    <integer-array name="config_sms_enabled_locking_shift_tables"></integer-array>
 </resources>
diff --git a/core/tests/coretests/AndroidManifest.xml b/core/tests/coretests/AndroidManifest.xml
index 4be6995..fadf1ec 100644
--- a/core/tests/coretests/AndroidManifest.xml
+++ b/core/tests/coretests/AndroidManifest.xml
@@ -100,6 +100,12 @@
 
     <application android:theme="@style/Theme">
         <uses-library android:name="android.test.runner" />
+        <activity android:name="android.view.ViewAttachTestActivity" android:label="View Attach Test">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
+            </intent-filter>
+        </activity>
         <activity android:name="StubTestBrowserActivity" android:label="Stubbed Test Browser">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN"/>
@@ -415,6 +421,13 @@
             </intent-filter>
         </activity>
 
+        <activity android:name="android.widget.scroll.arrowscroll.MultiPageTextWithPadding" android:label="arrowscrollMultiPageTextWithPadding">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
+            </intent-filter>
+        </activity>
+
         <activity android:name="android.view.Include" android:label="IncludeTag">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
diff --git a/core/tests/coretests/res/layout/attach_view_test.xml b/core/tests/coretests/res/layout/attach_view_test.xml
new file mode 100644
index 0000000..42841cb
--- /dev/null
+++ b/core/tests/coretests/res/layout/attach_view_test.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<LinearLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:orientation="vertical"
+    android:layout_width="fill_parent"
+    android:layout_height="fill_parent">
+    <android.view.ViewAttachView
+    android:id="@+id/view_attach_view"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:keepScreenOn="true"/>
+</LinearLayout>
diff --git a/core/tests/coretests/src/android/content/pm/PackageHelperTests.java b/core/tests/coretests/src/android/content/pm/PackageHelperTests.java
new file mode 100644
index 0000000..27112a6
--- /dev/null
+++ b/core/tests/coretests/src/android/content/pm/PackageHelperTests.java
@@ -0,0 +1,131 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.content.pm;
+
+import com.android.internal.content.PackageHelper;
+
+import android.os.IBinder;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.os.storage.IMountService;
+import android.test.AndroidTestCase;
+import android.util.Log;
+
+public class PackageHelperTests extends AndroidTestCase {
+    private static final boolean localLOGV = true;
+    public static final String TAG = "PackageHelperTests";
+    protected final String PREFIX = "android.content.pm";
+    private IMountService mMs;
+    private String fullId;
+    private String fullId2;
+
+    private IMountService getMs() {
+        IBinder service = ServiceManager.getService("mount");
+        if (service != null) {
+            return IMountService.Stub.asInterface(service);
+        } else {
+            Log.e(TAG, "Can't get mount service");
+        }
+        return null;
+    }
+
+    private void cleanupContainers() throws RemoteException {
+        Log.d(TAG,"cleanUp");
+        IMountService ms = getMs();
+        String[] containers = ms.getSecureContainerList();
+        for (int i = 0; i < containers.length; i++) {
+            if (containers[i].startsWith(PREFIX)) {
+                Log.d(TAG,"cleaing up "+containers[i]);
+                ms.destroySecureContainer(containers[i], true);
+            }
+        }
+    }
+
+    void failStr(String errMsg) {
+        Log.w(TAG, "errMsg=" + errMsg);
+        fail(errMsg);
+    }
+
+    void failStr(Exception e) {
+        failStr(e.getMessage());
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        if (localLOGV) Log.i(TAG, "Cleaning out old test containers");
+        cleanupContainers();
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        super.tearDown();
+        if (localLOGV) Log.i(TAG, "Cleaning out old test containers");
+        cleanupContainers();
+    }
+
+    public void testMountAndPullSdCard() {
+        try {
+            fullId = PREFIX;
+            fullId2 = PackageHelper.createSdDir(1024, fullId, "none", android.os.Process.myUid());
+
+            Log.d(TAG,PackageHelper.getSdDir(fullId));
+            PackageHelper.unMountSdDir(fullId);
+
+            Runnable r1 = getMountRunnable();
+            Runnable r2 = getDestroyRunnable();
+            Thread thread = new Thread(r1);
+            Thread thread2 = new Thread(r2);
+            thread2.start();
+            thread.start();
+        } catch (Exception e) {
+            failStr(e);
+        }
+    }
+
+    public Runnable getMountRunnable() {
+        Runnable r = new Runnable () {
+            public void run () {
+                try {
+                    Thread.sleep(5);
+                    String path = PackageHelper.mountSdDir(fullId, "none",
+                            android.os.Process.myUid());
+                    Log.e(TAG, "mount done " + path);
+                } catch (IllegalArgumentException iae) {
+                    throw iae;
+                } catch (Throwable t) {
+                    Log.e(TAG, "mount failed", t);
+                }
+            }
+        };
+        return r;
+    }
+
+    public Runnable getDestroyRunnable() {
+        Runnable r = new Runnable () {
+            public void run () {
+                try {
+                    PackageHelper.destroySdDir(fullId);
+                    Log.e(TAG, "destroy done: " + fullId);
+                } catch (Throwable t) {
+                    Log.e(TAG, "destroy failed", t);
+                }
+            }
+        };
+        return r;
+    }
+}
diff --git a/core/tests/coretests/src/android/text/TextUtilsTest.java b/core/tests/coretests/src/android/text/TextUtilsTest.java
index e111662..63dd0cc 100644
--- a/core/tests/coretests/src/android/text/TextUtilsTest.java
+++ b/core/tests/coretests/src/android/text/TextUtilsTest.java
@@ -17,6 +17,7 @@
 package android.text;
 
 import android.graphics.Paint;
+import android.os.Parcel;
 import android.test.suitebuilder.annotation.LargeTest;
 import android.test.suitebuilder.annotation.SmallTest;
 import android.text.Spannable;
@@ -255,6 +256,23 @@
         assertEquals("Foo Bar", tokens[0].getAddress());
     }
 
+    @SmallTest
+    public void testRfc822FindToken() {
+        Rfc822Tokenizer tokenizer = new Rfc822Tokenizer();
+        //                0           1         2           3         4
+        //                0 1234 56789012345678901234 5678 90123456789012345
+        String address = "\"Foo\" <foo@google.com>, \"Bar\" <bar@google.com>";
+        assertEquals(0, tokenizer.findTokenStart(address, 21));
+        assertEquals(22, tokenizer.findTokenEnd(address, 21));
+        assertEquals(24, tokenizer.findTokenStart(address, 25));
+        assertEquals(46, tokenizer.findTokenEnd(address, 25));
+    }
+
+    @SmallTest
+    public void testRfc822FindTokenWithError() {
+        assertEquals(9, new Rfc822Tokenizer().findTokenEnd("\"Foo Bar\\", 0));
+    }
+
     @LargeTest
     public void testEllipsize() {
         CharSequence s1 = "The quick brown fox jumps over \u00FEhe lazy dog.";
@@ -335,6 +353,51 @@
         assertFalse(TextUtils.delimitedStringContains("network,mock,gpsx", ',', "gps"));
     }
 
+    @SmallTest
+    public void testCharSequenceCreator() {
+        Parcel p = Parcel.obtain();
+        TextUtils.writeToParcel(null, p, 0);
+        CharSequence text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(p);
+        assertNull("null CharSequence should generate null from parcel", text);
+        p = Parcel.obtain();
+        TextUtils.writeToParcel("test", p, 0);
+        text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(p);
+        assertEquals("conversion to/from parcel failed", "test", text);
+    }
+
+    @SmallTest
+    public void testCharSequenceCreatorNull() {
+        Parcel p;
+        CharSequence text;
+        p = Parcel.obtain();
+        TextUtils.writeToParcel(null, p, 0);
+        p.setDataPosition(0);
+        text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(p);
+        assertNull("null CharSequence should generate null from parcel", text);
+    }
+
+    @SmallTest
+    public void testCharSequenceCreatorSpannable() {
+        Parcel p;
+        CharSequence text;
+        p = Parcel.obtain();
+        TextUtils.writeToParcel(new SpannableString("test"), p, 0);
+        p.setDataPosition(0);
+        text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(p);
+        assertEquals("conversion to/from parcel failed", "test", text.toString());
+    }
+
+    @SmallTest
+    public void testCharSequenceCreatorString() {
+        Parcel p;
+        CharSequence text;
+        p = Parcel.obtain();
+        TextUtils.writeToParcel("test", p, 0);
+        p.setDataPosition(0);
+        text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(p);
+        assertEquals("conversion to/from parcel failed", "test", text.toString());
+    }
+
     /**
      * CharSequence wrapper for testing the cases where text is copied into
      * a char array instead of working from a String or a Spanned.
diff --git a/core/tests/coretests/src/android/util/ScrollViewScenario.java b/core/tests/coretests/src/android/util/ScrollViewScenario.java
index 83afe06..db3d9d0 100644
--- a/core/tests/coretests/src/android/util/ScrollViewScenario.java
+++ b/core/tests/coretests/src/android/util/ScrollViewScenario.java
@@ -61,6 +61,7 @@
 
     /**
      * Partially implement ViewFactory given a height ratio.
+     * A negative height ratio means that WRAP_CONTENT will be used as height
      */
     private static abstract class ViewFactoryBase implements ViewFactory {
 
@@ -87,6 +88,9 @@
 
         List<ViewFactory> mViewFactories = Lists.newArrayList();
 
+        int mTopPadding = 0;
+        int mBottomPadding = 0;
+
         /**
          * Add a text view.
          * @param text The text of the text view.
@@ -186,6 +190,13 @@
             });
             return this;
         }
+
+        public Params addPaddingToScrollView(int topPadding, int bottomPadding) {
+            mTopPadding = topPadding;
+            mBottomPadding = bottomPadding;
+
+            return this;
+        }
     }
 
     /**
@@ -239,13 +250,17 @@
 
         // create views specified by params
         for (ViewFactory viewFactory : params.mViewFactories) {
+            int height = ViewGroup.LayoutParams.WRAP_CONTENT;
+            if (viewFactory.getHeightRatio() >= 0) {
+                height = (int) (viewFactory.getHeightRatio() * screenHeight);
+            }
             final LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
-                    ViewGroup.LayoutParams.MATCH_PARENT,
-                    (int) (viewFactory.getHeightRatio() * screenHeight));
+                    ViewGroup.LayoutParams.MATCH_PARENT, height);
             mLinearLayout.addView(viewFactory.create(this), lp);
         }
 
         mScrollView = createScrollView();
+        mScrollView.setPadding(0, params.mTopPadding, 0, params.mBottomPadding);
         mScrollView.addView(mLinearLayout, new ViewGroup.LayoutParams(
                 ViewGroup.LayoutParams.MATCH_PARENT,
                 ViewGroup.LayoutParams.MATCH_PARENT));
diff --git a/core/tests/coretests/src/android/view/ViewAttachTest.java b/core/tests/coretests/src/android/view/ViewAttachTest.java
new file mode 100644
index 0000000..cff66e4
--- /dev/null
+++ b/core/tests/coretests/src/android/view/ViewAttachTest.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.view;
+
+import android.content.pm.ActivityInfo;
+import android.os.SystemClock;
+import android.test.ActivityInstrumentationTestCase2;
+
+public class ViewAttachTest extends
+        ActivityInstrumentationTestCase2<ViewAttachTestActivity> {
+
+    public ViewAttachTest() {
+        super(ViewAttachTestActivity.class);
+    }
+
+    /**
+     * Make sure that onAttachedToWindow and onDetachedToWindow is called in the
+     * correct order The ViewAttachTestActivity contains a view that will throw
+     * an RuntimeException if onDetachedToWindow and onAttachedToWindow is
+     * called in the wrong order.
+     *
+     * 1. Initiate the activity 2. Perform a series of orientation changes to
+     * the activity (this will force the View hierarchy to be rebuild,
+     * generating onAttachedToWindow and onDetachedToWindow)
+     *
+     * Expected result: No RuntimeException is thrown from the TestView in
+     * ViewFlipperTestActivity.
+     *
+     * @throws Throwable
+     */
+    public void testAttached() throws Throwable {
+        final ViewAttachTestActivity activity = getActivity();
+        for (int i = 0; i < 20; i++) {
+            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
+            SystemClock.sleep(250);
+            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
+            SystemClock.sleep(250);
+        }
+    }
+}
diff --git a/core/tests/coretests/src/android/view/ViewAttachTestActivity.java b/core/tests/coretests/src/android/view/ViewAttachTestActivity.java
new file mode 100644
index 0000000..59e25ae
--- /dev/null
+++ b/core/tests/coretests/src/android/view/ViewAttachTestActivity.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.view;
+
+import com.android.frameworks.coretests.R;
+
+import android.app.Activity;
+import android.os.Bundle;
+
+public class ViewAttachTestActivity extends Activity {
+    public static final String TAG = "OnAttachedTest";
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.attach_view_test);
+    }
+}
diff --git a/core/tests/coretests/src/android/view/ViewAttachView.java b/core/tests/coretests/src/android/view/ViewAttachView.java
new file mode 100644
index 0000000..5af2d8f
--- /dev/null
+++ b/core/tests/coretests/src/android/view/ViewAttachView.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.view;
+
+import android.content.Context;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.os.SystemClock;
+import android.util.AttributeSet;
+import android.util.Log;
+import android.view.View;
+
+/**
+ * A View that will throw a RuntimeException if onAttachedToWindow and
+ * onDetachedFromWindow is called in the wrong order for ViewAttachTest
+ */
+public class ViewAttachView extends View {
+    public static final String TAG = "OnAttachedTest";
+    private boolean attached;
+
+    public ViewAttachView(Context context, AttributeSet attrs, int defStyle) {
+        super(context, attrs, defStyle);
+        init(attrs, defStyle);
+    }
+
+    public ViewAttachView(Context context, AttributeSet attrs) {
+        super(context, attrs);
+        init(attrs, 0);
+    }
+
+    public ViewAttachView(Context context) {
+        super(context);
+        init(null, 0);
+    }
+
+    private void init(AttributeSet attrs, int defStyle) {
+        SystemClock.sleep(2000);
+    }
+
+    @Override
+    protected void onAttachedToWindow() {
+        Log.d(TAG, "onAttachedToWindow");
+        super.onAttachedToWindow();
+        if (attached) {
+            throw new RuntimeException("OnAttachedToWindow called more than once in a row");
+        }
+        attached = true;
+    }
+
+    @Override
+    protected void onDetachedFromWindow() {
+        Log.d(TAG, "onDetachedFromWindow");
+        super.onDetachedFromWindow();
+        if (!attached) {
+            throw new RuntimeException(
+                    "onDetachedFromWindowcalled without prior call to OnAttachedToWindow");
+        }
+        attached = false;
+    }
+
+    @Override
+    protected void onDraw(Canvas canvas) {
+        super.onDraw(canvas);
+        canvas.drawColor(Color.BLUE);
+    }
+}
diff --git a/core/tests/coretests/src/android/widget/scroll/arrowscroll/MultiPageTextWithPadding.java b/core/tests/coretests/src/android/widget/scroll/arrowscroll/MultiPageTextWithPadding.java
new file mode 100644
index 0000000..7d5a8d8
--- /dev/null
+++ b/core/tests/coretests/src/android/widget/scroll/arrowscroll/MultiPageTextWithPadding.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.widget.scroll.arrowscroll;
+
+import android.util.ScrollViewScenario;
+
+/**
+ * One TextView with a text covering several pages. Padding is added
+ * above and below the ScrollView.
+ */
+public class MultiPageTextWithPadding extends ScrollViewScenario {
+
+    @Override
+    protected void init(Params params) {
+
+        String text = "This is a long text.";
+        String longText = "First text.";
+        for (int i = 0; i < 300; i++) {
+            longText = longText + " " + text;
+        }
+        longText = longText + " Last text.";
+        params.addTextView(longText, -1.0f).addPaddingToScrollView(50, 50);
+    }
+}
diff --git a/core/tests/coretests/src/android/widget/scroll/arrowscroll/MultiPageTextWithPaddingTest.java b/core/tests/coretests/src/android/widget/scroll/arrowscroll/MultiPageTextWithPaddingTest.java
new file mode 100644
index 0000000..ddde48f
--- /dev/null
+++ b/core/tests/coretests/src/android/widget/scroll/arrowscroll/MultiPageTextWithPaddingTest.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2011 Sony Ericsson Mobile Communications AB.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.widget.scroll.arrowscroll;
+
+import android.widget.scroll.arrowscroll.MultiPageTextWithPadding;
+import android.test.ActivityInstrumentationTestCase;
+import android.test.suitebuilder.annotation.LargeTest;
+import android.test.suitebuilder.annotation.MediumTest;
+import android.view.KeyEvent;
+import android.widget.TextView;
+import android.widget.ScrollView;
+
+public class MultiPageTextWithPaddingTest extends
+        ActivityInstrumentationTestCase<MultiPageTextWithPadding> {
+
+    private ScrollView mScrollView;
+
+    private TextView mTextView;
+
+    public MultiPageTextWithPaddingTest() {
+        super("com.android.frameworks.coretests", MultiPageTextWithPadding.class);
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+
+        mScrollView = getActivity().getScrollView();
+        mTextView = getActivity().getContentChildAt(0);
+    }
+
+    @MediumTest
+    public void testPreconditions() {
+        assertTrue("text should not fit on screen",
+                   mTextView.getHeight() > mScrollView.getHeight());
+    }
+
+    @LargeTest
+    public void testScrollDownToBottom() throws Exception {
+        // Calculate the number of arrow scrolls needed to reach the bottom
+        int scrollsNeeded = (int)Math.ceil(Math.max(0.0f,
+                (mTextView.getHeight() - mScrollView.getHeight()))
+                / mScrollView.getMaxScrollAmount());
+        for (int i = 0; i < scrollsNeeded; i++) {
+            sendKeys(KeyEvent.KEYCODE_DPAD_DOWN);
+        }
+
+        assertEquals(
+                "should be fully scrolled to bottom",
+                getActivity().getLinearLayout().getHeight()
+                        - (mScrollView.getHeight() - mScrollView.getPaddingTop() - mScrollView
+                                .getPaddingBottom()), mScrollView.getScrollY());
+    }
+}
diff --git a/core/tests/overlaytests/Android.mk b/core/tests/overlaytests/Android.mk
new file mode 100644
index 0000000..bf69442
--- /dev/null
+++ b/core/tests/overlaytests/Android.mk
@@ -0,0 +1,4 @@
+# Dummy makefile to halt recursive directory traversal.
+
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
diff --git a/core/tests/overlaytests/OverlayTest/Android.mk b/core/tests/overlaytests/OverlayTest/Android.mk
new file mode 100644
index 0000000..f7f67f6
--- /dev/null
+++ b/core/tests/overlaytests/OverlayTest/Android.mk
@@ -0,0 +1,10 @@
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+
+LOCAL_PACKAGE_NAME := OverlayTest
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+include $(BUILD_PACKAGE)
diff --git a/core/tests/overlaytests/OverlayTest/AndroidManifest.xml b/core/tests/overlaytests/OverlayTest/AndroidManifest.xml
new file mode 100644
index 0000000..9edba12
--- /dev/null
+++ b/core/tests/overlaytests/OverlayTest/AndroidManifest.xml
@@ -0,0 +1,10 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.android.overlaytest">
+    <uses-permission android:name="android.permission.RUN_INSTRUMENTATION"/>
+    <application>
+        <uses-library android:name="android.test.runner"/>
+    </application>
+    <instrumentation android:name="android.test.InstrumentationTestRunner"
+        android:targetPackage="com.android.overlaytest"
+        android:label="Runtime resource overlay tests"/>
+</manifest>
diff --git a/core/tests/overlaytests/OverlayTest/src/com/android/overlaytest/OverlayBaseTest.java b/core/tests/overlaytests/OverlayTest/src/com/android/overlaytest/OverlayBaseTest.java
new file mode 100644
index 0000000..85b49ce
--- /dev/null
+++ b/core/tests/overlaytests/OverlayTest/src/com/android/overlaytest/OverlayBaseTest.java
@@ -0,0 +1,118 @@
+package com.android.overlaytest;
+
+import android.content.res.Configuration;
+import android.content.res.Resources;
+import android.test.AndroidTestCase;
+import java.io.InputStream;
+import java.util.Locale;
+
+public abstract class OverlayBaseTest extends AndroidTestCase {
+    private Resources mResources;
+    protected boolean mWithOverlay; // will be set by subclasses
+
+    protected void setUp() {
+        mResources = getContext().getResources();
+    }
+
+    private int calculateRawResourceChecksum(int resId) throws Throwable {
+        InputStream input = null;
+        try {
+            input = mResources.openRawResource(resId);
+            int ch, checksum = 0;
+            while ((ch = input.read()) != -1) {
+                checksum = (checksum + ch) % 0xffddbb00;
+            }
+            return checksum;
+        } finally {
+            input.close();
+        }
+    }
+
+    private void setLocale(String code) {
+        Locale locale = new Locale(code);
+        Locale.setDefault(locale);
+        Configuration config = new Configuration();
+        config.locale = locale;
+        mResources.updateConfiguration(config, mResources.getDisplayMetrics());
+    }
+
+    private void assertResource(int resId, boolean ewo, boolean ew) throws Throwable {
+        boolean expected = mWithOverlay ? ew : ewo;
+        boolean actual = mResources.getBoolean(resId);
+        assertEquals(expected, actual);
+    }
+
+    private void assertResource(int resId, String ewo, String ew) throws Throwable {
+        String expected = mWithOverlay ? ew : ewo;
+        String actual = mResources.getString(resId);
+        assertEquals(expected, actual);
+    }
+
+    private void assertResource(int resId, int[] ewo, int[] ew) throws Throwable {
+        int[] expected = mWithOverlay ? ew : ewo;
+        int[] actual = mResources.getIntArray(resId);
+        assertEquals("length:", expected.length, actual.length);
+        for (int i = 0; i < actual.length; ++i) {
+            assertEquals("index " + i + ":", actual[i], expected[i]);
+        }
+    }
+
+    public void testBooleanOverlay() throws Throwable {
+        // config_automatic_brightness_available has overlay (default config)
+        final int resId = com.android.internal.R.bool.config_automatic_brightness_available;
+        assertResource(resId, false, true);
+    }
+
+    public void testBoolean() throws Throwable {
+        // config_bypass_keyguard_if_slider_open has no overlay
+        final int resId = com.android.internal.R.bool.config_bypass_keyguard_if_slider_open;
+        assertResource(resId, true, true);
+    }
+
+    public void testStringOverlay() throws Throwable {
+        // phoneTypeCar has an overlay (default config), which shouldn't shadow
+        // the Swedish translation
+        final int resId = com.android.internal.R.string.phoneTypeCar;
+        setLocale("sv_SE");
+        assertResource(resId, "Bil", "Bil");
+    }
+
+    public void testStringSwedishOverlay() throws Throwable {
+        // phoneTypeWork has overlay (no default config, only for lang=sv)
+        final int resId = com.android.internal.R.string.phoneTypeWork;
+        setLocale("en_US");
+        assertResource(resId, "Work", "Work");
+        setLocale("sv_SE");
+        assertResource(resId, "Arbete", "Jobb");
+    }
+
+    public void testString() throws Throwable {
+        // phoneTypeHome has no overlay
+        final int resId = com.android.internal.R.string.phoneTypeHome;
+        setLocale("en_US");
+        assertResource(resId, "Home", "Home");
+        setLocale("sv_SE");
+        assertResource(resId, "Hem", "Hem");
+    }
+
+    public void testIntegerArrayOverlay() throws Throwable {
+        // config_scrollBarrierVibePattern has overlay (default config)
+        final int resId = com.android.internal.R.array.config_scrollBarrierVibePattern;
+        assertResource(resId, new int[]{0, 15, 10, 10}, new int[]{100, 200, 300});
+    }
+
+    public void testIntegerArray() throws Throwable {
+        // config_virtualKeyVibePattern has no overlay
+        final int resId = com.android.internal.R.array.config_virtualKeyVibePattern;
+        final int[] expected = {0, 10, 20, 30};
+        assertResource(resId, expected, expected);
+    }
+
+    public void testAsset() throws Throwable {
+        // drawable/default_background.jpg has overlay (default config)
+        final int resId = com.android.internal.R.drawable.default_wallpaper;
+        int actual = calculateRawResourceChecksum(resId);
+        int expected = mWithOverlay ? 0x000051da : 0x0014ebce;
+        assertEquals(expected, actual);
+    }
+}
diff --git a/core/tests/overlaytests/OverlayTest/src/com/android/overlaytest/WithOverlayTest.java b/core/tests/overlaytests/OverlayTest/src/com/android/overlaytest/WithOverlayTest.java
new file mode 100644
index 0000000..1292d03
--- /dev/null
+++ b/core/tests/overlaytests/OverlayTest/src/com/android/overlaytest/WithOverlayTest.java
@@ -0,0 +1,7 @@
+package com.android.overlaytest;
+
+public class WithOverlayTest extends OverlayBaseTest {
+    public WithOverlayTest() {
+        mWithOverlay = true;
+    }
+}
diff --git a/core/tests/overlaytests/OverlayTest/src/com/android/overlaytest/WithoutOverlayTest.java b/core/tests/overlaytests/OverlayTest/src/com/android/overlaytest/WithoutOverlayTest.java
new file mode 100644
index 0000000..630ff8f
--- /dev/null
+++ b/core/tests/overlaytests/OverlayTest/src/com/android/overlaytest/WithoutOverlayTest.java
@@ -0,0 +1,7 @@
+package com.android.overlaytest;
+
+public class WithoutOverlayTest extends OverlayBaseTest {
+    public WithoutOverlayTest() {
+        mWithOverlay = false;
+    }
+}
diff --git a/core/tests/overlaytests/OverlayTestOverlay/Android.mk b/core/tests/overlaytests/OverlayTestOverlay/Android.mk
new file mode 100644
index 0000000..cf32c9f
--- /dev/null
+++ b/core/tests/overlaytests/OverlayTestOverlay/Android.mk
@@ -0,0 +1,14 @@
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+LOCAL_SDK_VERSION := current
+
+LOCAL_PACKAGE_NAME := com.android.overlaytest.overlay
+
+LOCAL_AAPT_FLAGS := -o
+
+include $(BUILD_PACKAGE)
diff --git a/core/tests/overlaytests/OverlayTestOverlay/AndroidManifest.xml b/core/tests/overlaytests/OverlayTestOverlay/AndroidManifest.xml
new file mode 100644
index 0000000..bcbb0d1
--- /dev/null
+++ b/core/tests/overlaytests/OverlayTestOverlay/AndroidManifest.xml
@@ -0,0 +1,6 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.android.overlaytest.overlay"
+        android:versionCode="1"
+        android:versionName="1.0">
+    <overlay-package android:name="android"/>
+</manifest>
diff --git a/core/tests/overlaytests/OverlayTestOverlay/res/drawable/default_wallpaper.jpg b/core/tests/overlaytests/OverlayTestOverlay/res/drawable/default_wallpaper.jpg
new file mode 100644
index 0000000..0d944d0
--- /dev/null
+++ b/core/tests/overlaytests/OverlayTestOverlay/res/drawable/default_wallpaper.jpg
Binary files differ
diff --git a/core/tests/overlaytests/OverlayTestOverlay/res/values-sv/config.xml b/core/tests/overlaytests/OverlayTestOverlay/res/values-sv/config.xml
new file mode 100644
index 0000000..bc52367
--- /dev/null
+++ b/core/tests/overlaytests/OverlayTestOverlay/res/values-sv/config.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <string name="phoneTypeWork">Jobb</string>
+</resources>
diff --git a/core/tests/overlaytests/OverlayTestOverlay/res/values/config.xml b/core/tests/overlaytests/OverlayTestOverlay/res/values/config.xml
new file mode 100644
index 0000000..794f475
--- /dev/null
+++ b/core/tests/overlaytests/OverlayTestOverlay/res/values/config.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <bool name="config_automatic_brightness_available">true</bool>
+    <string name="phoneTypeCar">Automobile</string>
+    <integer-array name="config_scrollBarrierVibePattern">
+        <item>100</item>
+        <item>200</item>
+        <item>300</item>
+    </integer-array>
+    <!-- The following integer does not exist in the original package. Idmap
+         generation should therefore ignore it. -->
+    <integer name="integer_not_in_original_package">0</integer>
+</resources>
diff --git a/core/tests/overlaytests/README b/core/tests/overlaytests/README
new file mode 100644
index 0000000..4b3e6f2
--- /dev/null
+++ b/core/tests/overlaytests/README
@@ -0,0 +1,15 @@
+Unit tests for runtime resource overlay
+=======================================
+
+As of this writing, runtime resource overlay is only triggered for
+/system/framework/framework-res.apk. Because of this, installation of
+overlay packages require the Android platform be rebooted. However, the
+regular unit tests (triggered via development/testrunner/runtest.py)
+cannot handle reboots. As a workaround, this directory contains a shell
+script which will trigger the tests in a non-standard way.
+
+Once runtime resource overlay may be applied to applications, the tests
+in this directory should be moved to core/tests/coretests. Also, by
+applying runtime resource overlay to a dedicated test application, the
+test cases would not need to assume default values for non-overlaid
+resources.
diff --git a/core/tests/overlaytests/runtests.sh b/core/tests/overlaytests/runtests.sh
new file mode 100755
index 0000000..0ad9efb
--- /dev/null
+++ b/core/tests/overlaytests/runtests.sh
@@ -0,0 +1,89 @@
+#!/bin/bash
+
+adb="adb"
+if [[ $# -gt 0 ]]; then
+	adb="adb $*" # for setting -e, -d or -s <serial>
+fi
+
+function atexit()
+{
+	local retval=$?
+
+	if [[ $retval -eq 0 ]]; then
+		rm $log
+	else
+		echo "There were errors, please check log at $log"
+	fi
+}
+
+log=$(mktemp)
+trap "atexit" EXIT
+failures=0
+
+function compile_module()
+{
+	local android_mk="$1"
+
+	echo "Compiling .${android_mk:${#PWD}}"
+	ONE_SHOT_MAKEFILE="$android_mk" make -C "../../../../../" files | tee -a $log
+	if [[ ${PIPESTATUS[0]} -ne 0 ]]; then
+		exit 1
+	fi
+}
+
+function wait_for_boot_completed()
+{
+	echo "Rebooting device"
+	$adb wait-for-device logcat -c
+	$adb wait-for-device logcat | grep -m 1 -e 'PowerManagerService.*bootCompleted' >/dev/null
+}
+
+function disable_overlay()
+{
+	echo "Disabling overlay"
+	$adb shell rm /vendor/overlay/framework/framework-res.apk
+	$adb shell rm /data/resource-cache/vendor@overlay@framework@framework-res.apk@idmap
+}
+
+function enable_overlay()
+{
+	echo "Enabling overlay"
+	$adb shell ln -s /data/app/com.android.overlaytest.overlay.apk /vendor/overlay/framework/framework-res.apk
+}
+
+function instrument()
+{
+	local class="$1"
+
+	echo "Instrumenting $class"
+	$adb shell am instrument -w -e class $class com.android.overlaytest/android.test.InstrumentationTestRunner | tee -a $log
+}
+
+function sync()
+{
+	echo "Syncing to device"
+	$adb remount | tee -a $log
+	$adb sync data | tee -a $log
+}
+
+# build and sync
+compile_module "$PWD/OverlayTest/Android.mk"
+compile_module "$PWD/OverlayTestOverlay/Android.mk"
+sync
+
+# instrument test (without overlay)
+$adb shell stop
+disable_overlay
+$adb shell start
+wait_for_boot_completed
+instrument "com.android.overlaytest.WithoutOverlayTest"
+
+# instrument test (with overlay)
+$adb shell stop
+enable_overlay
+$adb shell start
+wait_for_boot_completed
+instrument "com.android.overlaytest.WithOverlayTest"
+
+# cleanup
+exit $(grep -c -e '^FAILURES' $log)
diff --git a/data/fonts/MTLc3m.ttf b/data/fonts/MTLc3m.ttf
index 3cc5c96..86bdcc7 100644
--- a/data/fonts/MTLc3m.ttf
+++ b/data/fonts/MTLc3m.ttf
Binary files differ
diff --git a/data/fonts/MTLmr3m.ttf b/data/fonts/MTLmr3m.ttf
index 05b9093..76fe737 100644
--- a/data/fonts/MTLmr3m.ttf
+++ b/data/fonts/MTLmr3m.ttf
Binary files differ
diff --git a/graphics/java/android/graphics/Movie.java b/graphics/java/android/graphics/Movie.java
index 95e9946..4a33453 100644
--- a/graphics/java/android/graphics/Movie.java
+++ b/graphics/java/android/graphics/Movie.java
@@ -46,6 +46,8 @@
     public static native Movie decodeByteArray(byte[] data, int offset,
                                                int length);
 
+    private static native void nativeDestructor(int nativeMovie);
+
     public static Movie decodeFile(String pathName) {
         InputStream is;
         try {
@@ -57,6 +59,15 @@
         return decodeTempStream(is);
     }
 
+    @Override
+    protected void finalize() throws Throwable {
+        try {
+            nativeDestructor(mNativeMovie);
+        } finally {
+            super.finalize();
+        }
+    }
+
     private static Movie decodeTempStream(InputStream is) {
         Movie moov = null;
         try {
diff --git a/graphics/java/android/graphics/YuvImage.java b/graphics/java/android/graphics/YuvImage.java
index 9368da6..af3f276 100644
--- a/graphics/java/android/graphics/YuvImage.java
+++ b/graphics/java/android/graphics/YuvImage.java
@@ -36,7 +36,7 @@
     private final static int WORKING_COMPRESS_STORAGE = 4096;
 
    /**
-     * The YUV format as defined in {@link PixelFormat}.
+     * The YUV format as defined in {@link ImageFormat}.
      */
     private int mFormat;
 
@@ -67,7 +67,7 @@
      *
      * @param yuv     The YUV data. In the case of more than one image plane, all the planes must be
      *                concatenated into a single byte array.
-     * @param format  The YUV data format as defined in {@link PixelFormat}.
+     * @param format  The YUV data format as defined in {@link ImageFormat}.
      * @param width   The width of the YuvImage.
      * @param height  The height of the YuvImage.
      * @param strides (Optional) Row bytes of each image plane. If yuv contains padding, the stride
@@ -152,7 +152,7 @@
     }
 
     /**
-     * @return the YUV format as defined in {@link PixelFormat}.
+     * @return the YUV format as defined in {@link ImageFormat}.
      */
     public int getYuvFormat() {
         return mFormat;
diff --git a/graphics/java/android/graphics/drawable/BitmapDrawable.java b/graphics/java/android/graphics/drawable/BitmapDrawable.java
index 2c09ddc..6e62ab3 100644
--- a/graphics/java/android/graphics/drawable/BitmapDrawable.java
+++ b/graphics/java/android/graphics/drawable/BitmapDrawable.java
@@ -486,10 +486,8 @@
         mBitmapState = state;
         if (res != null) {
             mTargetDensity = res.getDisplayMetrics().densityDpi;
-        } else if (state != null) {
-            mTargetDensity = state.mTargetDensity;
         } else {
-            mTargetDensity = DisplayMetrics.DENSITY_DEFAULT;
+            mTargetDensity = state.mTargetDensity;
         }
         setBitmap(state.mBitmap);
     }
diff --git a/include/media/EffectApi.h b/include/media/EffectApi.h
index b97c22e..6e6660c 100644
--- a/include/media/EffectApi.h
+++ b/include/media/EffectApi.h
@@ -602,9 +602,9 @@
 
 // Audio mode
 enum audio_mode_e {
-    AUDIO_MODE_NORMAL,      // device idle
-    AUDIO_MODE_RINGTONE,    // device ringing
-    AUDIO_MODE_IN_CALL      // audio call connected (VoIP or telephony)
+    AUDIO_EFFECT_MODE_NORMAL,   // device idle
+    AUDIO_EFFECT_MODE_RINGTONE, // device ringing
+    AUDIO_EFFECT_MODE_IN_CALL   // audio call connected (VoIP or telephony)
 };
 
 // Values for "accessMode" field of buffer_config_t:
diff --git a/include/utils/AssetManager.h b/include/utils/AssetManager.h
index 9e2bf37..a8c7ddb 100644
--- a/include/utils/AssetManager.h
+++ b/include/utils/AssetManager.h
@@ -222,6 +222,7 @@
     {
         String8 path;
         FileType type;
+        String8 idmap;
     };
 
     Asset* openInPathLocked(const char* fileName, AccessMode mode,
@@ -262,6 +263,16 @@
     void setLocaleLocked(const char* locale);
     void updateResourceParamsLocked() const;
 
+    bool createIdmapFileLocked(const String8& originalPath, const String8& overlayPath,
+                               const String8& idmapPath);
+
+    bool isIdmapStaleLocked(const String8& originalPath, const String8& overlayPath,
+                            const String8& idmapPath);
+
+    Asset* openIdmapLocked(const struct asset_path& ap) const;
+
+    bool getZipEntryCrcLocked(const String8& zipPath, const char* entryFilename, uint32_t* pCrc);
+
     class SharedZip : public RefBase {
     public:
         static sp<SharedZip> get(const String8& path);
diff --git a/include/utils/ResourceTypes.h b/include/utils/ResourceTypes.h
index d1d9844..8a92cd6 100644
--- a/include/utils/ResourceTypes.h
+++ b/include/utils/ResourceTypes.h
@@ -1813,9 +1813,9 @@
     ~ResTable();
 
     status_t add(const void* data, size_t size, void* cookie,
-                 bool copyData=false);
+                 bool copyData=false, const void* idmap = NULL);
     status_t add(Asset* asset, void* cookie,
-                 bool copyData=false);
+                 bool copyData=false, const void* idmap = NULL);
     status_t add(ResTable* src);
 
     status_t getError() const;
@@ -2061,6 +2061,24 @@
 
     void getLocales(Vector<String8>* locales) const;
 
+    // Generate an idmap.
+    //
+    // Return value: on success: NO_ERROR; caller is responsible for free-ing
+    // outData (using free(3)). On failure, any status_t value other than
+    // NO_ERROR; the caller should not free outData.
+    status_t createIdmap(const ResTable& overlay, uint32_t originalCrc, uint32_t overlayCrc,
+                         void** outData, size_t* outSize) const;
+
+    enum {
+        IDMAP_HEADER_SIZE_BYTES = 3 * sizeof(uint32_t),
+    };
+    // Retrieve idmap meta-data.
+    //
+    // This function only requires the idmap header (the first
+    // IDMAP_HEADER_SIZE_BYTES) bytes of an idmap file.
+    static bool getIdmapInfo(const void* idmap, size_t size,
+                             uint32_t* pOriginalCrc, uint32_t* pOverlayCrc);
+
 #ifndef HAVE_ANDROID_OS
     void print(bool inclValues) const;
     static String8 normalizeForOutput(const char* input);
@@ -2074,7 +2092,7 @@
     struct bag_set;
 
     status_t add(const void* data, size_t size, void* cookie,
-                 Asset* asset, bool copyData);
+                 Asset* asset, bool copyData, const Asset* idmap);
 
     ssize_t getResourcePackageIndex(uint32_t resID) const;
     ssize_t getEntry(
@@ -2083,7 +2101,7 @@
         const ResTable_type** outType, const ResTable_entry** outEntry,
         const Type** outTypeClass) const;
     status_t parsePackage(
-        const ResTable_package* const pkg, const Header* const header);
+        const ResTable_package* const pkg, const Header* const header, uint32_t idmap_id);
 
     void print_value(const Package* pkg, const Res_value& value) const;
     
diff --git a/libs/usb/src/com/android/future/usb/UsbManager.java b/libs/usb/src/com/android/future/usb/UsbManager.java
index d424b63..91d8e8a 100644
--- a/libs/usb/src/com/android/future/usb/UsbManager.java
+++ b/libs/usb/src/com/android/future/usb/UsbManager.java
@@ -28,7 +28,7 @@
 import android.util.Log;
 
 /**
- * This class allows you to access the state of USB, both in host and device mode.
+ * This is a wrapper class for the USB Manager to support USB accessories.
  *
  * <p>You can obtain an instance of this class by calling {@link #getInstance}
  *
@@ -141,7 +141,7 @@
     /**
      * Returns true if the caller has permission to access the accessory.
      * Permission might have been granted temporarily via
-     * {@link #requestPermission(android.hardware.usb.UsbAccessory} or
+     * {@link #requestPermission} or
      * by the user choosing the caller as the default application for the accessory.
      *
      * @param accessory to check permissions for
diff --git a/libs/utils/AssetManager.cpp b/libs/utils/AssetManager.cpp
index e09e755..0b4d1ac 100644
--- a/libs/utils/AssetManager.cpp
+++ b/libs/utils/AssetManager.cpp
@@ -36,6 +36,19 @@
 #include <dirent.h>
 #include <errno.h>
 #include <assert.h>
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#ifndef TEMP_FAILURE_RETRY
+/* Used to retry syscalls that can return EINTR. */
+#define TEMP_FAILURE_RETRY(exp) ({         \
+    typeof (exp) _rc;                      \
+    do {                                   \
+        _rc = (exp);                       \
+    } while (_rc == -1 && errno == EINTR); \
+    _rc; })
+#endif
 
 using namespace android;
 
@@ -48,6 +61,7 @@
 static const char* kAssetsRoot = "assets";
 static const char* kAppZipName = NULL; //"classes.jar";
 static const char* kSystemAssets = "framework/framework-res.apk";
+static const char* kIdmapCacheDir = "resource-cache";
 
 static const char* kExcludeExtension = ".EXCLUDE";
 
@@ -55,6 +69,35 @@
 
 static volatile int32_t gCount = 0;
 
+namespace {
+    // Transform string /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
+    String8 idmapPathForPackagePath(const String8& pkgPath)
+    {
+        const char* root = getenv("ANDROID_DATA");
+        LOG_ALWAYS_FATAL_IF(root == NULL, "ANDROID_DATA not set");
+        String8 path(root);
+        path.appendPath(kIdmapCacheDir);
+
+        char buf[256]; // 256 chars should be enough for anyone...
+        strncpy(buf, pkgPath.string(), 255);
+        buf[255] = '\0';
+        char* filename = buf;
+        while (*filename && *filename == '/') {
+            ++filename;
+        }
+        char* p = filename;
+        while (*p) {
+            if (*p == '/') {
+                *p = '@';
+            }
+            ++p;
+        }
+        path.appendPath(filename);
+        path.append("@idmap");
+
+        return path;
+    }
+}
 
 /*
  * ===========================================================================
@@ -122,7 +165,7 @@
             return true;
         }
     }
-    
+
     LOGV("In %p Asset %s path: %s", this,
          ap.type == kFileTypeDirectory ? "dir" : "zip", ap.path.string());
 
@@ -133,9 +176,181 @@
         *cookie = (void*)mAssetPaths.size();
     }
 
+    // add overlay packages for /system/framework; apps are handled by the
+    // (Java) package manager
+    if (strncmp(path.string(), "/system/framework/", 18) == 0) {
+        // When there is an environment variable for /vendor, this
+        // should be changed to something similar to how ANDROID_ROOT
+        // and ANDROID_DATA are used in this file.
+        String8 overlayPath("/vendor/overlay/framework/");
+        overlayPath.append(path.getPathLeaf());
+        if (TEMP_FAILURE_RETRY(access(overlayPath.string(), R_OK)) == 0) {
+            asset_path oap;
+            oap.path = overlayPath;
+            oap.type = ::getFileType(overlayPath.string());
+            bool addOverlay = (oap.type == kFileTypeRegular); // only .apks supported as overlay
+            if (addOverlay) {
+                oap.idmap = idmapPathForPackagePath(overlayPath);
+
+                if (isIdmapStaleLocked(ap.path, oap.path, oap.idmap)) {
+                    addOverlay = createIdmapFileLocked(ap.path, oap.path, oap.idmap);
+                }
+            }
+            if (addOverlay) {
+                mAssetPaths.add(oap);
+            } else {
+                LOGW("failed to add overlay package %s\n", overlayPath.string());
+            }
+        }
+    }
+
     return true;
 }
 
+bool AssetManager::isIdmapStaleLocked(const String8& originalPath, const String8& overlayPath,
+                                      const String8& idmapPath)
+{
+    struct stat st;
+    if (TEMP_FAILURE_RETRY(stat(idmapPath.string(), &st)) == -1) {
+        if (errno == ENOENT) {
+            return true; // non-existing idmap is always stale
+        } else {
+            LOGW("failed to stat file %s: %s\n", idmapPath.string(), strerror(errno));
+            return false;
+        }
+    }
+    if (st.st_size < ResTable::IDMAP_HEADER_SIZE_BYTES) {
+        LOGW("file %s has unexpectedly small size=%zd\n", idmapPath.string(), (size_t)st.st_size);
+        return false;
+    }
+    int fd = TEMP_FAILURE_RETRY(::open(idmapPath.string(), O_RDONLY));
+    if (fd == -1) {
+        LOGW("failed to open file %s: %s\n", idmapPath.string(), strerror(errno));
+        return false;
+    }
+    char buf[ResTable::IDMAP_HEADER_SIZE_BYTES];
+    ssize_t bytesLeft = ResTable::IDMAP_HEADER_SIZE_BYTES;
+    for (;;) {
+        ssize_t r = TEMP_FAILURE_RETRY(read(fd, buf + ResTable::IDMAP_HEADER_SIZE_BYTES - bytesLeft,
+                                            bytesLeft));
+        if (r < 0) {
+            TEMP_FAILURE_RETRY(close(fd));
+            return false;
+        }
+        bytesLeft -= r;
+        if (bytesLeft == 0) {
+            break;
+        }
+    }
+    TEMP_FAILURE_RETRY(close(fd));
+
+    uint32_t cachedOriginalCrc, cachedOverlayCrc;
+    if (!ResTable::getIdmapInfo(buf, ResTable::IDMAP_HEADER_SIZE_BYTES,
+                                &cachedOriginalCrc, &cachedOverlayCrc)) {
+        return false;
+    }
+
+    uint32_t actualOriginalCrc, actualOverlayCrc;
+    if (!getZipEntryCrcLocked(originalPath, "resources.arsc", &actualOriginalCrc)) {
+        return false;
+    }
+    if (!getZipEntryCrcLocked(overlayPath, "resources.arsc", &actualOverlayCrc)) {
+        return false;
+    }
+    return cachedOriginalCrc != actualOriginalCrc || cachedOverlayCrc != actualOverlayCrc;
+}
+
+bool AssetManager::getZipEntryCrcLocked(const String8& zipPath, const char* entryFilename,
+                                        uint32_t* pCrc)
+{
+    asset_path ap;
+    ap.path = zipPath;
+    const ZipFileRO* zip = getZipFileLocked(ap);
+    if (zip == NULL) {
+        return false;
+    }
+    const ZipEntryRO entry = zip->findEntryByName(entryFilename);
+    if (entry == NULL) {
+        return false;
+    }
+    if (!zip->getEntryInfo(entry, NULL, NULL, NULL, NULL, NULL, (long*)pCrc)) {
+        return false;
+    }
+    return true;
+}
+
+bool AssetManager::createIdmapFileLocked(const String8& originalPath, const String8& overlayPath,
+                                         const String8& idmapPath)
+{
+    LOGD("%s: originalPath=%s overlayPath=%s idmapPath=%s\n",
+         __FUNCTION__, originalPath.string(), overlayPath.string(), idmapPath.string());
+    ResTable tables[2];
+    const String8* paths[2] = { &originalPath, &overlayPath };
+    uint32_t originalCrc, overlayCrc;
+    bool retval = false;
+    ssize_t offset = 0;
+    int fd = 0;
+    uint32_t* data = NULL;
+    size_t size;
+
+    for (int i = 0; i < 2; ++i) {
+        asset_path ap;
+        ap.type = kFileTypeRegular;
+        ap.path = *paths[i];
+        Asset* ass = openNonAssetInPathLocked("resources.arsc", Asset::ACCESS_BUFFER, ap);
+        if (ass == NULL) {
+            LOGW("failed to find resources.arsc in %s\n", ap.path.string());
+            goto error;
+        }
+        tables[i].add(ass, (void*)1, false);
+    }
+
+    if (!getZipEntryCrcLocked(originalPath, "resources.arsc", &originalCrc)) {
+        LOGW("failed to retrieve crc for resources.arsc in %s\n", originalPath.string());
+        goto error;
+    }
+    if (!getZipEntryCrcLocked(overlayPath, "resources.arsc", &overlayCrc)) {
+        LOGW("failed to retrieve crc for resources.arsc in %s\n", overlayPath.string());
+        goto error;
+    }
+
+    if (tables[0].createIdmap(tables[1], originalCrc, overlayCrc,
+                              (void**)&data, &size) != NO_ERROR) {
+        LOGW("failed to generate idmap data for file %s\n", idmapPath.string());
+        goto error;
+    }
+
+    // This should be abstracted (eg replaced by a stand-alone
+    // application like dexopt, triggered by something equivalent to
+    // installd).
+    fd = TEMP_FAILURE_RETRY(::open(idmapPath.string(), O_WRONLY | O_CREAT | O_TRUNC, 0644));
+    if (fd == -1) {
+        LOGW("failed to write idmap file %s (open: %s)\n", idmapPath.string(), strerror(errno));
+        goto error_free;
+    }
+    for (;;) {
+        ssize_t written = TEMP_FAILURE_RETRY(write(fd, data + offset, size));
+        if (written < 0) {
+            LOGW("failed to write idmap file %s (write: %s)\n", idmapPath.string(),
+                 strerror(errno));
+            goto error_close;
+        }
+        size -= (size_t)written;
+        offset += written;
+        if (size == 0) {
+            break;
+        }
+    }
+
+    retval = true;
+error_close:
+    TEMP_FAILURE_RETRY(close(fd));
+error_free:
+    free(data);
+error:
+    return retval;
+}
+
 bool AssetManager::addDefaultAssets()
 {
     const char* root = getenv("ANDROID_ROOT");
@@ -404,6 +619,7 @@
         ResTable* sharedRes = NULL;
         bool shared = true;
         const asset_path& ap = mAssetPaths.itemAt(i);
+        Asset* idmap = openIdmapLocked(ap);
         LOGV("Looking for resource asset in '%s'\n", ap.path.string());
         if (ap.type != kFileTypeDirectory) {
             if (i == 0) {
@@ -433,7 +649,7 @@
                     // can quickly copy it out for others.
                     LOGV("Creating shared resources for %s", ap.path.string());
                     sharedRes = new ResTable();
-                    sharedRes->add(ass, (void*)(i+1), false);
+                    sharedRes->add(ass, (void*)(i+1), false, idmap);
                     sharedRes = const_cast<AssetManager*>(this)->
                         mZipSet.setZipResourceTable(ap.path, sharedRes);
                 }
@@ -457,13 +673,16 @@
                 rt->add(sharedRes);
             } else {
                 LOGV("Parsing resources for %s", ap.path.string());
-                rt->add(ass, (void*)(i+1), !shared);
+                rt->add(ass, (void*)(i+1), !shared, idmap);
             }
 
             if (!shared) {
                 delete ass;
             }
         }
+        if (idmap != NULL) {
+            delete idmap;
+        }
     }
 
     if (required && !rt) LOGW("Unable to find resources file resources.arsc");
@@ -498,6 +717,21 @@
     res->setParameters(mConfig);
 }
 
+Asset* AssetManager::openIdmapLocked(const struct asset_path& ap) const
+{
+    Asset* ass = NULL;
+    if (ap.idmap.size() != 0) {
+        ass = const_cast<AssetManager*>(this)->
+            openAssetFromFileLocked(ap.idmap, Asset::ACCESS_BUFFER);
+        if (ass) {
+            LOGV("loading idmap %s\n", ap.idmap.string());
+        } else {
+            LOGW("failed to load idmap %s\n", ap.idmap.string());
+        }
+    }
+    return ass;
+}
+
 const ResTable& AssetManager::getResources(bool required) const
 {
     const ResTable* rt = getResTable(required);
diff --git a/libs/utils/README b/libs/utils/README
index 36a706d..01741e0 100644
--- a/libs/utils/README
+++ b/libs/utils/README
@@ -1,4 +1,6 @@
 Android Utility Function Library
+================================
+
 
 If you need a feature that is native to Linux but not present on other
 platforms, construct a platform-dependent implementation that shares
@@ -12,3 +14,276 @@
 layer.  The goal is to provide an optimized solution for Linux with
 reasonable implementations for other platforms.
 
+
+
+Resource overlay
+================
+
+
+Introduction
+------------
+
+Overlay packages are special .apk files which provide no code but
+additional resource values (and possibly new configurations) for
+resources in other packages. When an application requests resources,
+the system will return values from either the application's original
+package or any associated overlay package. Any redirection is completely
+transparent to the calling application.
+
+Resource values have the following precedence table, listed in
+descending precedence.
+
+ * overlay package, matching config (eg res/values-en-land)
+
+ * original package, matching config
+
+ * overlay package, no config (eg res/values)
+
+ * original package, no config
+
+During compilation, overlay packages are differentiated from regular
+packages by passing the -o flag to aapt.
+
+
+Background
+----------
+
+This section provides generic background material on resources in
+Android.
+
+
+How resources are bundled in .apk files
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Android .apk files are .zip files, usually housing .dex code,
+certificates and resources, though packages containing resources but
+no code are possible. Resources can be divided into the following
+categories; a `configuration' indicates a set of phone language, display
+density, network operator, etc.
+
+ * assets: uncompressed, raw files packaged as part of an .apk and
+           explicitly referenced by filename. These files are
+           independent of configuration.
+
+ * res/drawable: bitmap or xml graphics. Each file may have different
+                 values depending on configuration.
+
+ * res/values: integers, strings, etc. Each resource may have different
+               values depending on configuration.
+
+Resource meta information and information proper is stored in a binary
+format in a named file resources.arsc, bundled as part of the .apk.
+
+Resource IDs and lookup
+~~~~~~~~~~~~~~~~~~~~~~~
+During compilation, the aapt tool gathers application resources and
+generates a resources.arsc file. Each resource name is assigned an
+integer ID 0xppttiii (translated to a symbolic name via R.java), where
+
+ * pp: corresponds to the package namespace (details below).
+
+ * tt: corresponds to the resource type (string, int, etc). Every
+       resource of the same type within the same package has the same
+       tt value, but depending on available types, the actual numerical
+       value may be different between packages.
+
+ * iiii: sequential number, assigned in the order resources are found.
+
+Resource values are specified paired with a set of configuration
+constraints (the default being the empty set), eg res/values-sv-port
+which imposes restrictions on language (Swedish) and display orientation
+(portrait). During lookup, every constraint set is matched against the
+current configuration, and the value corresponding to the best matching
+constraint set is returned (ResourceTypes.{h,cpp}).
+
+Parsing of resources.arsc is handled by ResourceTypes.cpp; this utility
+is governed by AssetManager.cpp, which tracks loaded resources per
+process.
+
+Assets are looked up by path and filename in AssetManager.cpp. The path
+to resources in res/drawable are located by ResourceTypes.cpp and then
+handled like assets by AssetManager.cpp. Other resources are handled
+solely by ResourceTypes.cpp.
+
+Package ID as namespace
+~~~~~~~~~~~~~~~~~~~~~~~
+The pp part of a resource ID defines a namespace. Android currently
+defines two namespaces:
+
+ * 0x01: system resources (pre-installed in framework-res.apk)
+
+ * 0x7f: application resources (bundled in the application .apk)
+
+ResourceTypes.cpp supports package IDs between 0x01 and 0x7f
+(inclusive); values outside this range are invalid.
+
+Each running (Dalvik) process is assigned a unique instance of
+AssetManager, which in turn keeps a forest structure of loaded
+resource.arsc files. Normally, this forest is structured as follows,
+where mPackageMap is the internal vector employed in ResourceTypes.cpp.
+
+mPackageMap[0x00] -> system package
+mPackageMap[0x01] -> NULL
+mPackageMap[0x02] -> NULL
+...
+mPackageMap[0x7f - 2] -> NULL
+mPackageMap[0x7f - 1] -> application package
+
+
+
+The resource overlay extension
+------------------------------
+
+The resource overlay mechanism aims to (partly) shadow and extend
+existing resources with new values for defined and new configurations.
+Technically, this is achieved by adding resource-only packages (called
+overlay packages) to existing resource namespaces, like so:
+
+mPackageMap[0x00] -> system package -> system overlay package
+mPackageMap[0x01] -> NULL
+mPackageMap[0x02] -> NULL
+...
+mPackageMap[0x7f - 2] -> NULL
+mPackageMap[0x7f - 1] -> application package -> overlay 1 -> overlay 2
+
+The use of overlay resources is completely transparent to
+applications; no additional resource identifiers are introduced, only
+configuration/value pairs. Any number of overlay packages may be loaded
+at a time; overlay packages are agnostic to what they target -- both
+system and application resources are fair game.
+
+The package targeted by an overlay package is called the target or
+original package.
+
+Resource overlay operates on symbolic resources names. Hence, to
+override the string/str1 resources in a package, the overlay package
+would include a resource also named string/str1. The end user does not
+have to worry about the numeric resources IDs assigned by aapt, as this
+is resolved automatically by the system.
+
+As of this writing, the use of resource overlay has not been fully
+explored. Until it has, only OEMs are trusted to use resource overlay.
+For this reason, overlay packages must reside in /system/overlay.
+
+
+Resource ID mapping
+~~~~~~~~~~~~~~~~~~~
+Resource identifiers must be coherent within the same namespace (ie
+PackageGroup in ResourceTypes.cpp). Calling applications will refer to
+resources using the IDs defined in the original package, but there is no
+guarantee aapt has assigned the same ID to the corresponding resource in
+an overlay package. To translate between the two, a resource ID mapping
+{original ID -> overlay ID} is created during package installation
+(PackageManagerService.java) and used during resource lookup. The
+mapping is stored in /data/resource-cache, with a @idmap file name
+suffix.
+
+The idmap file format is documented in a separate section, below.
+
+
+Package management
+~~~~~~~~~~~~~~~~~~
+Packages are managed by the PackageManagerService. Addition and removal
+of packages are monitored via the inotify framework, exposed via
+android.os.FileObserver.
+
+During initialization of a Dalvik process, ActivityThread.java requests
+the process' AssetManager (by proxy, via AssetManager.java and JNI)
+to load a list of packages. This list includes overlay packages, if
+present.
+
+When a target package or a corresponding overlay package is installed,
+the target package's process is stopped and a new idmap is generated.
+This is similar to how applications are stopped when their packages are
+upgraded.
+
+
+Creating overlay packages
+-------------------------
+
+Overlay packages should contain no code, define (some) resources with
+the same type and name as in the original package, and be compiled with
+the -o flag passed to aapt.
+
+The aapt -o flag instructs aapt to create an overlay package.
+Technically, this means the package will be assigned package id 0x00.
+
+There are no restrictions on overlay packages names, though the naming
+convention <original.package.name>.overlay.<name> is recommended.
+
+
+Example overlay package
+~~~~~~~~~~~~~~~~~~~~~~~
+
+To overlay the resource bool/b in package com.foo.bar, to be applied
+when the display is in landscape mode, create a new package with
+no source code and a single .xml file under res/values-land, with
+an entry for bool/b. Compile with aapt -o and place the results in
+/system/overlay by adding the following to Android.mk:
+
+LOCAL_AAPT_FLAGS := -o com.foo.bar
+LOCAL_MODULE_PATH := $(TARGET_OUT)/overlay
+
+
+The ID map (idmap) file format
+------------------------------
+
+The idmap format is designed for lookup performance. However, leading
+and trailing undefined overlay values are discarded to reduce the memory
+footprint.
+
+
+idmap grammar
+~~~~~~~~~~~~~
+All atoms (names in square brackets) are uint32_t integers. The
+idmap-magic constant spells "idmp" in ASCII. Offsets are given relative
+to the data_header, not to the beginning of the file.
+
+map          := header data
+header       := idmap-magic <crc32-original-pkg> <crc32-overlay-pkg>
+idmap-magic  := <0x706d6469>
+data         := data_header type_block+
+data_header  := <m> header_block{m}
+header_block := <0> | <type_block_offset>
+type_block   := <n> <id_offset> entry{n}
+entry        := <resource_id_in_target_package>
+
+
+idmap example
+~~~~~~~~~~~~~
+Given a pair of target and overlay packages with CRC sums 0x216a8fe2
+and 0x6b9beaec, each defining the following resources
+
+Name          Target package  Overlay package
+string/str0   0x7f010000      -
+string/str1   0x7f010001      0x7f010000
+string/str2   0x7f010002      -
+string/str3   0x7f010003      0x7f010001
+string/str4   0x7f010004      -
+bool/bool0    0x7f020000      -
+integer/int0  0x7f030000      0x7f020000
+integer/int1  0x7f030001      -
+
+the corresponding resource map is
+
+0x706d6469 0x216a8fe2 0x6b9beaec 0x00000003 \
+0x00000004 0x00000000 0x00000009 0x00000003 \
+0x00000001 0x7f010000 0x00000000 0x7f010001 \
+0x00000001 0x00000000 0x7f020000
+
+or, formatted differently
+
+0x706d6469  # magic: all idmap files begin with this constant
+0x216a8fe2  # CRC32 of the resources.arsc file in the original package
+0x6b9beaec  # CRC32 of the resources.arsc file in the overlay package
+0x00000003  # header; three types (string, bool, integer) in the target package
+0x00000004  #   header_block for type 0 (string) is located at offset 4
+0x00000000  #   no bool type exists in overlay package -> no header_block
+0x00000009  #   header_block for type 2 (integer) is located at offset 9
+0x00000003  # header_block for string; overlay IDs span 3 elements
+0x00000001  #   the first string in target package is entry 1 == offset
+0x7f010000  #   target 0x7f01001 -> overlay 0x7f010000
+0x00000000  #   str2 not defined in overlay package
+0x7f010001  #   target 0x7f010003 -> overlay 0x7f010001
+0x00000001  # header_block for integer; overlay IDs span 1 element
+0x00000000  #   offset == 0
+0x7f020000  #   target 0x7f030000 -> overlay 0x7f020000
diff --git a/libs/utils/RefBase.cpp b/libs/utils/RefBase.cpp
index bb6c125..2034486 100644
--- a/libs/utils/RefBase.cpp
+++ b/libs/utils/RefBase.cpp
@@ -524,7 +524,7 @@
 
 void RefBase::weakref_type::trackMe(bool enable, bool retain)
 {
-    static_cast<const weakref_impl*>(this)->trackMe(enable, retain);
+    static_cast<weakref_impl*>(this)->trackMe(enable, retain);
 }
 
 RefBase::weakref_type* RefBase::createWeak(const void* id) const
diff --git a/libs/utils/ResourceTypes.cpp b/libs/utils/ResourceTypes.cpp
index a64918d..4a6a3db 100644
--- a/libs/utils/ResourceTypes.cpp
+++ b/libs/utils/ResourceTypes.cpp
@@ -63,6 +63,10 @@
 #endif
 #endif
 
+#define IDMAP_MAGIC         0x706d6469
+// size measured in sizeof(uint32_t)
+#define IDMAP_HEADER_SIZE (ResTable::IDMAP_HEADER_SIZE_BYTES / sizeof(uint32_t))
+
 static void printToLogFunc(void* cookie, const char* txt)
 {
     LOGV("%s", txt);
@@ -214,6 +218,81 @@
     outData->colors = (uint32_t*) data;
 }
 
+static bool assertIdmapHeader(const uint32_t* map, size_t sizeBytes)
+{
+    if (sizeBytes < ResTable::IDMAP_HEADER_SIZE_BYTES) {
+        LOGW("idmap assertion failed: size=%d bytes\n", sizeBytes);
+        return false;
+    }
+    if (*map != htodl(IDMAP_MAGIC)) { // htodl: map data expected to be in correct endianess
+        LOGW("idmap assertion failed: invalid magic found (is 0x%08x, expected 0x%08x)\n",
+             *map, htodl(IDMAP_MAGIC));
+        return false;
+    }
+    return true;
+}
+
+static status_t idmapLookup(const uint32_t* map, size_t sizeBytes, uint32_t key, uint32_t* outValue)
+{
+    // see README for details on the format of map
+    if (!assertIdmapHeader(map, sizeBytes)) {
+        return UNKNOWN_ERROR;
+    }
+    map = map + IDMAP_HEADER_SIZE; // skip ahead to data segment
+    // size of data block, in uint32_t
+    const size_t size = (sizeBytes - ResTable::IDMAP_HEADER_SIZE_BYTES) / sizeof(uint32_t);
+    const uint32_t type = Res_GETTYPE(key) + 1; // add one, idmap stores "public" type id
+    const uint32_t entry = Res_GETENTRY(key);
+    const uint32_t typeCount = *map;
+
+    if (type > typeCount) {
+        LOGW("Resource ID map: type=%d exceeds number of types=%d\n", type, typeCount);
+        return UNKNOWN_ERROR;
+    }
+    if (typeCount > size) {
+        LOGW("Resource ID map: number of types=%d exceeds size of map=%d\n", typeCount, size);
+        return UNKNOWN_ERROR;
+    }
+    const uint32_t typeOffset = map[type];
+    if (typeOffset == 0) {
+        *outValue = 0;
+        return NO_ERROR;
+    }
+    if (typeOffset + 1 > size) {
+        LOGW("Resource ID map: type offset=%d exceeds reasonable value, size of map=%d\n",
+             typeOffset, size);
+        return UNKNOWN_ERROR;
+    }
+    const uint32_t entryCount = map[typeOffset];
+    const uint32_t entryOffset = map[typeOffset + 1];
+    if (entryCount == 0 || entry < entryOffset || entry - entryOffset > entryCount - 1) {
+        *outValue = 0;
+        return NO_ERROR;
+    }
+    const uint32_t index = typeOffset + 2 + entry - entryOffset;
+    if (index > size) {
+        LOGW("Resource ID map: entry index=%d exceeds size of map=%d\n", index, size);
+        *outValue = 0;
+        return NO_ERROR;
+    }
+    *outValue = map[index];
+
+    return NO_ERROR;
+}
+
+static status_t getIdmapPackageId(const uint32_t* map, size_t mapSize, uint32_t *outId)
+{
+    if (!assertIdmapHeader(map, mapSize)) {
+        return UNKNOWN_ERROR;
+    }
+    const uint32_t* p = map + IDMAP_HEADER_SIZE + 1;
+    while (*p == 0) {
+        ++p;
+    }
+    *outId = (map[*p + IDMAP_HEADER_SIZE + 2] >> 24) & 0x000000ff;
+    return NO_ERROR;
+}
+
 Res_png_9patch* Res_png_9patch::deserialize(const void* inData)
 {
     if (sizeof(void*) != sizeof(int32_t)) {
@@ -1290,7 +1369,13 @@
 
 struct ResTable::Header
 {
-    Header(ResTable* _owner) : owner(_owner), ownedData(NULL), header(NULL) { }
+    Header(ResTable* _owner) : owner(_owner), ownedData(NULL), header(NULL),
+        resourceIDMap(NULL), resourceIDMapSize(0) { }
+
+    ~Header()
+    {
+        free(resourceIDMap);
+    }
 
     ResTable* const                 owner;
     void*                           ownedData;
@@ -1301,6 +1386,8 @@
     void*                           cookie;
 
     ResStringPool                   values;
+    uint32_t*                       resourceIDMap;
+    size_t                          resourceIDMapSize;
 };
 
 struct ResTable::Type
@@ -1716,12 +1803,13 @@
     return ((ssize_t)mPackageMap[Res_GETPACKAGE(resID)+1])-1;
 }
 
-status_t ResTable::add(const void* data, size_t size, void* cookie, bool copyData)
+status_t ResTable::add(const void* data, size_t size, void* cookie, bool copyData,
+                       const void* idmap)
 {
-    return add(data, size, cookie, NULL, copyData);
+    return add(data, size, cookie, NULL, copyData, reinterpret_cast<const Asset*>(idmap));
 }
 
-status_t ResTable::add(Asset* asset, void* cookie, bool copyData)
+status_t ResTable::add(Asset* asset, void* cookie, bool copyData, const void* idmap)
 {
     const void* data = asset->getBuffer(true);
     if (data == NULL) {
@@ -1729,7 +1817,7 @@
         return UNKNOWN_ERROR;
     }
     size_t size = (size_t)asset->getLength();
-    return add(data, size, cookie, asset, copyData);
+    return add(data, size, cookie, asset, copyData, reinterpret_cast<const Asset*>(idmap));
 }
 
 status_t ResTable::add(ResTable* src)
@@ -1757,19 +1845,30 @@
 }
 
 status_t ResTable::add(const void* data, size_t size, void* cookie,
-                       Asset* asset, bool copyData)
+                       Asset* asset, bool copyData, const Asset* idmap)
 {
     if (!data) return NO_ERROR;
     Header* header = new Header(this);
     header->index = mHeaders.size();
     header->cookie = cookie;
+    if (idmap != NULL) {
+        const size_t idmap_size = idmap->getLength();
+        const void* idmap_data = const_cast<Asset*>(idmap)->getBuffer(true);
+        header->resourceIDMap = (uint32_t*)malloc(idmap_size);
+        if (header->resourceIDMap == NULL) {
+            delete header;
+            return (mError = NO_MEMORY);
+        }
+        memcpy((void*)header->resourceIDMap, idmap_data, idmap_size);
+        header->resourceIDMapSize = idmap_size;
+    }
     mHeaders.add(header);
 
     const bool notDeviceEndian = htods(0xf0) != 0xf0;
 
     LOAD_TABLE_NOISY(
-        LOGV("Adding resources to ResTable: data=%p, size=0x%x, cookie=%p, asset=%p, copy=%d\n",
-             data, size, cookie, asset, copyData));
+        LOGV("Adding resources to ResTable: data=%p, size=0x%x, cookie=%p, asset=%p, copy=%d "
+             "idmap=%p\n", data, size, cookie, asset, copyData, idmap));
     
     if (copyData || notDeviceEndian) {
         header->ownedData = malloc(size);
@@ -1836,7 +1935,16 @@
                      dtohl(header->header->packageCount));
                 return (mError=BAD_TYPE);
             }
-            if (parsePackage((ResTable_package*)chunk, header) != NO_ERROR) {
+            uint32_t idmap_id = 0;
+            if (idmap != NULL) {
+                uint32_t tmp;
+                if (getIdmapPackageId(header->resourceIDMap,
+                                      header->resourceIDMapSize,
+                                      &tmp) == NO_ERROR) {
+                    idmap_id = tmp;
+                }
+            }
+            if (parsePackage((ResTable_package*)chunk, header, idmap_id) != NO_ERROR) {
                 return mError;
             }
             curPackage++;
@@ -1858,6 +1966,7 @@
     if (mError != NO_ERROR) {
         LOGW("No string values found in resource table!");
     }
+
     TABLE_NOISY(LOGV("Returning from add with mError=%d\n", mError));
     return mError;
 }
@@ -2002,17 +2111,38 @@
     size_t ip = grp->packages.size();
     while (ip > 0) {
         ip--;
+        int T = t;
+        int E = e;
 
         const Package* const package = grp->packages[ip];
+        if (package->header->resourceIDMap) {
+            uint32_t overlayResID = 0x0;
+            status_t retval = idmapLookup(package->header->resourceIDMap,
+                                          package->header->resourceIDMapSize,
+                                          resID, &overlayResID);
+            if (retval == NO_ERROR && overlayResID != 0x0) {
+                // for this loop iteration, this is the type and entry we really want
+                LOGV("resource map 0x%08x -> 0x%08x\n", resID, overlayResID);
+                T = Res_GETTYPE(overlayResID);
+                E = Res_GETENTRY(overlayResID);
+            } else {
+                // resource not present in overlay package, continue with the next package
+                continue;
+            }
+        }
 
         const ResTable_type* type;
         const ResTable_entry* entry;
         const Type* typeClass;
-        ssize_t offset = getEntry(package, t, e, desiredConfig, &type, &entry, &typeClass);
+        ssize_t offset = getEntry(package, T, E, desiredConfig, &type, &entry, &typeClass);
         if (offset <= 0) {
-            if (offset < 0) {
+            // No {entry, appropriate config} pair found in package. If this
+            // package is an overlay package (ip != 0), this simply means the
+            // overlay package did not specify a default.
+            // Non-overlay packages are still required to provide a default.
+            if (offset < 0 && ip == 0) {
                 LOGW("Failure getting entry for 0x%08x (t=%d e=%d) in package %zd (error %d)\n",
-                        resID, t, e, ip, (int)offset);
+                        resID, T, E, ip, (int)offset);
                 rc = offset;
                 goto out;
             }
@@ -2044,13 +2174,16 @@
 
         if (outSpecFlags != NULL) {
             if (typeClass->typeSpecFlags != NULL) {
-                *outSpecFlags |= dtohl(typeClass->typeSpecFlags[e]);
+                *outSpecFlags |= dtohl(typeClass->typeSpecFlags[E]);
             } else {
                 *outSpecFlags = -1;
             }
         }
-        
-        if (bestPackage != NULL && bestItem.isMoreSpecificThan(thisConfig)) {
+
+        if (bestPackage != NULL &&
+            (bestItem.isMoreSpecificThan(thisConfig) || bestItem.diff(thisConfig) == 0)) {
+            // Discard thisConfig not only if bestItem is more specific, but also if the two configs
+            // are identical (diff == 0), or overlay packages will not take effect.
             continue;
         }
         
@@ -2250,21 +2383,45 @@
 
     TABLE_NOISY(LOGI("Building bag: %p\n", (void*)resID));
     
+    ResTable_config bestConfig;
+    memset(&bestConfig, 0, sizeof(bestConfig));
+
     // Now collect all bag attributes from all packages.
     size_t ip = grp->packages.size();
     while (ip > 0) {
         ip--;
+        int T = t;
+        int E = e;
 
         const Package* const package = grp->packages[ip];
+        if (package->header->resourceIDMap) {
+            uint32_t overlayResID = 0x0;
+            status_t retval = idmapLookup(package->header->resourceIDMap,
+                                          package->header->resourceIDMapSize,
+                                          resID, &overlayResID);
+            if (retval == NO_ERROR && overlayResID != 0x0) {
+                // for this loop iteration, this is the type and entry we really want
+                LOGV("resource map 0x%08x -> 0x%08x\n", resID, overlayResID);
+                T = Res_GETTYPE(overlayResID);
+                E = Res_GETENTRY(overlayResID);
+            } else {
+                // resource not present in overlay package, continue with the next package
+                continue;
+            }
+        }
 
         const ResTable_type* type;
         const ResTable_entry* entry;
         const Type* typeClass;
-        LOGV("Getting entry pkg=%p, t=%d, e=%d\n", package, t, e);
-        ssize_t offset = getEntry(package, t, e, &mParams, &type, &entry, &typeClass);
+        LOGV("Getting entry pkg=%p, t=%d, e=%d\n", package, T, E);
+        ssize_t offset = getEntry(package, T, E, &mParams, &type, &entry, &typeClass);
         LOGV("Resulting offset=%d\n", offset);
         if (offset <= 0) {
-            if (offset < 0) {
+            // No {entry, appropriate config} pair found in package. If this
+            // package is an overlay package (ip != 0), this simply means the
+            // overlay package did not specify a default.
+            // Non-overlay packages are still required to provide a default.
+            if (offset < 0 && ip == 0) {
                 if (set) free(set);
                 return offset;
             }
@@ -2277,6 +2434,15 @@
             continue;
         }
 
+        if (set != NULL && !type->config.isBetterThan(bestConfig, NULL)) {
+            continue;
+        }
+        bestConfig = type->config;
+        if (set) {
+            free(set);
+            set = NULL;
+        }
+
         const uint16_t entrySize = dtohs(entry->size);
         const uint32_t parent = entrySize >= sizeof(ResTable_map_entry)
             ? dtohl(((const ResTable_map_entry*)entry)->parent.ident) : 0;
@@ -2288,43 +2454,41 @@
         TABLE_NOISY(LOGI("Found map: size=%p parent=%p count=%d\n",
                          entrySize, parent, count));
 
-        if (set == NULL) {
-            // If this map inherits from another, we need to start
-            // with its parent's values.  Otherwise start out empty.
-            TABLE_NOISY(printf("Creating new bag, entrySize=0x%08x, parent=0x%08x\n",
-                         entrySize, parent));
-            if (parent) {
-                const bag_entry* parentBag;
-                uint32_t parentTypeSpecFlags = 0;
-                const ssize_t NP = getBagLocked(parent, &parentBag, &parentTypeSpecFlags);
-                const size_t NT = ((NP >= 0) ? NP : 0) + N;
-                set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*NT);
-                if (set == NULL) {
-                    return NO_MEMORY;
-                }
-                if (NP > 0) {
-                    memcpy(set+1, parentBag, NP*sizeof(bag_entry));
-                    set->numAttrs = NP;
-                    TABLE_NOISY(LOGI("Initialized new bag with %d inherited attributes.\n", NP));
-                } else {
-                    TABLE_NOISY(LOGI("Initialized new bag with no inherited attributes.\n"));
-                    set->numAttrs = 0;
-                }
-                set->availAttrs = NT;
-                set->typeSpecFlags = parentTypeSpecFlags;
-            } else {
-                set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*N);
-                if (set == NULL) {
-                    return NO_MEMORY;
-                }
-                set->numAttrs = 0;
-                set->availAttrs = N;
-                set->typeSpecFlags = 0;
+        // If this map inherits from another, we need to start
+        // with its parent's values.  Otherwise start out empty.
+        TABLE_NOISY(printf("Creating new bag, entrySize=0x%08x, parent=0x%08x\n",
+                           entrySize, parent));
+        if (parent) {
+            const bag_entry* parentBag;
+            uint32_t parentTypeSpecFlags = 0;
+            const ssize_t NP = getBagLocked(parent, &parentBag, &parentTypeSpecFlags);
+            const size_t NT = ((NP >= 0) ? NP : 0) + N;
+            set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*NT);
+            if (set == NULL) {
+                return NO_MEMORY;
             }
+            if (NP > 0) {
+                memcpy(set+1, parentBag, NP*sizeof(bag_entry));
+                set->numAttrs = NP;
+                TABLE_NOISY(LOGI("Initialized new bag with %d inherited attributes.\n", NP));
+            } else {
+                TABLE_NOISY(LOGI("Initialized new bag with no inherited attributes.\n"));
+                set->numAttrs = 0;
+            }
+            set->availAttrs = NT;
+            set->typeSpecFlags = parentTypeSpecFlags;
+        } else {
+            set = (bag_set*)malloc(sizeof(bag_set)+sizeof(bag_entry)*N);
+            if (set == NULL) {
+                return NO_MEMORY;
+            }
+            set->numAttrs = 0;
+            set->availAttrs = N;
+            set->typeSpecFlags = 0;
         }
 
         if (typeClass->typeSpecFlags != NULL) {
-            set->typeSpecFlags |= dtohl(typeClass->typeSpecFlags[e]);
+            set->typeSpecFlags |= dtohl(typeClass->typeSpecFlags[E]);
         } else {
             set->typeSpecFlags = -1;
         }
@@ -3873,7 +4037,7 @@
 }
 
 status_t ResTable::parsePackage(const ResTable_package* const pkg,
-                                const Header* const header)
+                                const Header* const header, uint32_t idmap_id)
 {
     const uint8_t* base = (const uint8_t*)pkg;
     status_t err = validate_chunk(&pkg->header, sizeof(*pkg),
@@ -3907,8 +4071,12 @@
     
     Package* package = NULL;
     PackageGroup* group = NULL;
-    uint32_t id = dtohl(pkg->id);
-    if (id != 0 && id < 256) {
+    uint32_t id = idmap_id != 0 ? idmap_id : dtohl(pkg->id);
+    // If at this point id == 0, pkg is an overlay package without a
+    // corresponding idmap. During regular usage, overlay packages are
+    // always loaded alongside their idmaps, but during idmap creation
+    // the package is temporarily loaded by itself.
+    if (id < 256) {
     
         package = new Package(this, header, pkg);
         if (package == NULL) {
@@ -3961,7 +4129,7 @@
             return (mError=err);
         }
     } else {
-        LOG_ALWAYS_FATAL("Skins not supported!");
+        LOG_ALWAYS_FATAL("Package id out of range");
         return NO_ERROR;
     }
 
@@ -4116,6 +4284,136 @@
     return NO_ERROR;
 }
 
+status_t ResTable::createIdmap(const ResTable& overlay, uint32_t originalCrc, uint32_t overlayCrc,
+                               void** outData, size_t* outSize) const
+{
+    // see README for details on the format of map
+    if (mPackageGroups.size() == 0) {
+        return UNKNOWN_ERROR;
+    }
+    if (mPackageGroups[0]->packages.size() == 0) {
+        return UNKNOWN_ERROR;
+    }
+
+    Vector<Vector<uint32_t> > map;
+    const PackageGroup* pg = mPackageGroups[0];
+    const Package* pkg = pg->packages[0];
+    size_t typeCount = pkg->types.size();
+    // starting size is header + first item (number of types in map)
+    *outSize = (IDMAP_HEADER_SIZE + 1) * sizeof(uint32_t);
+    const String16 overlayPackage(overlay.mPackageGroups[0]->packages[0]->package->name);
+    const uint32_t pkg_id = pkg->package->id << 24;
+
+    for (size_t typeIndex = 0; typeIndex < typeCount; ++typeIndex) {
+        ssize_t offset = -1;
+        const Type* typeConfigs = pkg->getType(typeIndex);
+        ssize_t mapIndex = map.add();
+        if (mapIndex < 0) {
+            return NO_MEMORY;
+        }
+        Vector<uint32_t>& vector = map.editItemAt(mapIndex);
+        for (size_t entryIndex = 0; entryIndex < typeConfigs->entryCount; ++entryIndex) {
+            uint32_t resID = (0xff000000 & ((pkg->package->id)<<24))
+                | (0x00ff0000 & ((typeIndex+1)<<16))
+                | (0x0000ffff & (entryIndex));
+            resource_name resName;
+            if (!this->getResourceName(resID, &resName)) {
+                return UNKNOWN_ERROR;
+            }
+
+            const String16 overlayType(resName.type, resName.typeLen);
+            const String16 overlayName(resName.name, resName.nameLen);
+            uint32_t overlayResID = overlay.identifierForName(overlayName.string(),
+                                                              overlayName.size(),
+                                                              overlayType.string(),
+                                                              overlayType.size(),
+                                                              overlayPackage.string(),
+                                                              overlayPackage.size());
+            if (overlayResID != 0) {
+                // overlay package has package ID == 0, use original package's ID instead
+                overlayResID |= pkg_id;
+            }
+            vector.push(overlayResID);
+            if (overlayResID != 0 && offset == -1) {
+                offset = Res_GETENTRY(resID);
+            }
+#if 0
+            if (overlayResID != 0) {
+                LOGD("%s/%s 0x%08x -> 0x%08x\n",
+                     String8(String16(resName.type)).string(),
+                     String8(String16(resName.name)).string(),
+                     resID, overlayResID);
+            }
+#endif
+        }
+
+        if (offset != -1) {
+            // shave off leading and trailing entries which lack overlay values
+            vector.removeItemsAt(0, offset);
+            vector.insertAt((uint32_t)offset, 0, 1);
+            while (vector.top() == 0) {
+                vector.pop();
+            }
+            // reserve space for number and offset of entries, and the actual entries
+            *outSize += (2 + vector.size()) * sizeof(uint32_t);
+        } else {
+            // no entries of current type defined in overlay package
+            vector.clear();
+            // reserve space for type offset
+            *outSize += 1 * sizeof(uint32_t);
+        }
+    }
+
+    if ((*outData = malloc(*outSize)) == NULL) {
+        return NO_MEMORY;
+    }
+    uint32_t* data = (uint32_t*)*outData;
+    *data++ = htodl(IDMAP_MAGIC);
+    *data++ = htodl(originalCrc);
+    *data++ = htodl(overlayCrc);
+    const size_t mapSize = map.size();
+    *data++ = htodl(mapSize);
+    size_t offset = mapSize;
+    for (size_t i = 0; i < mapSize; ++i) {
+        const Vector<uint32_t>& vector = map.itemAt(i);
+        const size_t N = vector.size();
+        if (N == 0) {
+            *data++ = htodl(0);
+        } else {
+            offset++;
+            *data++ = htodl(offset);
+            offset += N;
+        }
+    }
+    for (size_t i = 0; i < mapSize; ++i) {
+        const Vector<uint32_t>& vector = map.itemAt(i);
+        const size_t N = vector.size();
+        if (N == 0) {
+            continue;
+        }
+        *data++ = htodl(N - 1); // do not count the offset (which is vector's first element)
+        for (size_t j = 0; j < N; ++j) {
+            const uint32_t& overlayResID = vector.itemAt(j);
+            *data++ = htodl(overlayResID);
+        }
+    }
+
+    return NO_ERROR;
+}
+
+bool ResTable::getIdmapInfo(const void* idmap, size_t sizeBytes,
+                            uint32_t* pOriginalCrc, uint32_t* pOverlayCrc)
+{
+    const uint32_t* map = (const uint32_t*)idmap;
+    if (!assertIdmapHeader(map, sizeBytes)) {
+        return false;
+    }
+    *pOriginalCrc = map[1];
+    *pOverlayCrc = map[2];
+    return true;
+}
+
+
 #ifndef HAVE_ANDROID_OS
 #define CHAR16_TO_CSTR(c16, len) (String8(String16(c16,len)).string())
 
diff --git a/media/java/android/media/ThumbnailUtils.java b/media/java/android/media/ThumbnailUtils.java
index 7fdf448..7c181ee 100644
--- a/media/java/android/media/ThumbnailUtils.java
+++ b/media/java/android/media/ThumbnailUtils.java
@@ -83,7 +83,7 @@
      *
      * @param filePath the path of image file
      * @param kind could be MINI_KIND or MICRO_KIND
-     * @return Bitmap
+     * @return Bitmap, or null on failures
      *
      * @hide This method is only used by media framework and media provider internally.
      */
@@ -123,6 +123,8 @@
                 bitmap = BitmapFactory.decodeFileDescriptor(fd, null, options);
             } catch (IOException ex) {
                 Log.e(TAG, "", ex);
+            } catch (OutOfMemoryError oom) {
+                Log.e(TAG, "Unable to decode file " + filePath + ". OutOfMemoryError.", oom);
             }
         }
 
diff --git a/nfc-extras/java/com/android/nfc_extras/NfcAdapterExtras.java b/nfc-extras/java/com/android/nfc_extras/NfcAdapterExtras.java
index cf38bd1..6001be9 100644
--- a/nfc-extras/java/com/android/nfc_extras/NfcAdapterExtras.java
+++ b/nfc-extras/java/com/android/nfc_extras/NfcAdapterExtras.java
@@ -18,6 +18,7 @@
 
 import android.annotation.SdkConstant;
 import android.annotation.SdkConstant.SdkConstantType;
+import android.nfc.ApduList;
 import android.nfc.INfcAdapterExtras;
 import android.nfc.NfcAdapter;
 import android.os.RemoteException;
@@ -55,14 +56,21 @@
     public static final String ACTION_RF_FIELD_OFF_DETECTED =
             "com.android.nfc_extras.action.RF_FIELD_OFF_DETECTED";
 
-    // protected by NfcAdapterExtras.class, and final after first construction
+    // protected by NfcAdapterExtras.class, and final after first construction,
+    // except for attemptDeadServiceRecovery() when NFC crashes - we accept a
+    // best effort recovery
+    private static NfcAdapter sAdapter;
     private static INfcAdapterExtras sService;
-    private static boolean sIsInitialized = false;
     private static NfcAdapterExtras sSingleton;
     private static NfcExecutionEnvironment sEmbeddedEe;
     private static CardEmulationRoute sRouteOff;
     private static CardEmulationRoute sRouteOnWhenScreenOn;
 
+    /** get service handles */
+    private static void initService() {
+        sService = sAdapter.getNfcAdapterExtrasInterface();
+    }
+
     /**
      * Get the {@link NfcAdapterExtras} for the given {@link NfcAdapter}.
      *
@@ -74,14 +82,23 @@
      */
     public static NfcAdapterExtras get(NfcAdapter adapter) {
         synchronized(NfcAdapterExtras.class) {
-            if (!sIsInitialized) {
-               sIsInitialized = true;
-               sService = adapter.getNfcAdapterExtrasInterface();
-               sEmbeddedEe = new NfcExecutionEnvironment(sService);
-               sRouteOff = new CardEmulationRoute(CardEmulationRoute.ROUTE_OFF, null);
-               sRouteOnWhenScreenOn = new CardEmulationRoute(
-                       CardEmulationRoute.ROUTE_ON_WHEN_SCREEN_ON, sEmbeddedEe);
-               sSingleton = new NfcAdapterExtras();
+            if (sSingleton == null) {
+                try {
+                    sAdapter = adapter;
+                    sRouteOff = new CardEmulationRoute(CardEmulationRoute.ROUTE_OFF, null);
+                    sSingleton = new NfcAdapterExtras();
+                    sEmbeddedEe = new NfcExecutionEnvironment(sSingleton);
+                    sRouteOnWhenScreenOn = new CardEmulationRoute(
+                            CardEmulationRoute.ROUTE_ON_WHEN_SCREEN_ON, sEmbeddedEe);
+                    initService();
+                } finally {
+                    if (sSingleton == null) {
+                        sService = null;
+                        sEmbeddedEe = null;
+                        sRouteOff = null;
+                        sRouteOnWhenScreenOn = null;
+                    }
+                }
             }
             return sSingleton;
         }
@@ -128,6 +145,19 @@
     }
 
     /**
+     * NFC service dead - attempt best effort recovery
+     */
+    void attemptDeadServiceRecovery(Exception e) {
+        Log.e(TAG, "NFC Adapter Extras dead - attempting to recover");
+        sAdapter.attemptDeadServiceRecovery(e);
+        initService();
+    }
+
+    INfcAdapterExtras getService() {
+        return sService;
+    }
+
+    /**
      * Get the routing state of this NFC EE.
      *
      * <p class="note">
@@ -142,7 +172,7 @@
                     sRouteOff :
                     sRouteOnWhenScreenOn;
         } catch (RemoteException e) {
-            Log.e(TAG, "", e);
+            attemptDeadServiceRecovery(e);
             return sRouteOff;
         }
     }
@@ -161,7 +191,7 @@
         try {
             sService.setCardEmulationRoute(route.route);
         } catch (RemoteException e) {
-            Log.e(TAG, "", e);
+            attemptDeadServiceRecovery(e);
         }
     }
 
@@ -177,4 +207,20 @@
     public NfcExecutionEnvironment getEmbeddedExecutionEnvironment() {
         return sEmbeddedEe;
     }
+
+    public void registerTearDownApdus(String packageName, ApduList apdus) {
+        try {
+            sService.registerTearDownApdus(packageName, apdus);
+        } catch (RemoteException e) {
+            attemptDeadServiceRecovery(e);
+        }
+    }
+
+    public void unregisterTearDownApdus(String packageName) {
+        try {
+            sService.unregisterTearDownApdus(packageName);
+        } catch (RemoteException e) {
+            attemptDeadServiceRecovery(e);
+        }
+    }
 }
diff --git a/nfc-extras/java/com/android/nfc_extras/NfcExecutionEnvironment.java b/nfc-extras/java/com/android/nfc_extras/NfcExecutionEnvironment.java
index 3efe492..eb2f6f8 100644
--- a/nfc-extras/java/com/android/nfc_extras/NfcExecutionEnvironment.java
+++ b/nfc-extras/java/com/android/nfc_extras/NfcExecutionEnvironment.java
@@ -29,7 +29,7 @@
 import android.os.RemoteException;
 
 public class NfcExecutionEnvironment {
-    private final INfcAdapterExtras mService;
+    private final NfcAdapterExtras mExtras;
 
     /**
      * Broadcast Action: An ISO-DEP AID was selected.
@@ -55,8 +55,8 @@
      */
     public static final String EXTRA_AID = "com.android.nfc_extras.extra.AID";
 
-    NfcExecutionEnvironment(INfcAdapterExtras service) {
-        mService = service;
+    NfcExecutionEnvironment(NfcAdapterExtras extras) {
+        mExtras = extras;
     }
 
     /**
@@ -75,10 +75,11 @@
      */
     public void open() throws IOException {
         try {
-            Bundle b = mService.open(new Binder());
+            Bundle b = mExtras.getService().open(new Binder());
             throwBundle(b);
         } catch (RemoteException e) {
-            return;
+            mExtras.attemptDeadServiceRecovery(e);
+            throw new IOException("NFC Service was dead, try again");
         }
     }
 
@@ -92,9 +93,10 @@
      */
     public void close() throws IOException {
         try {
-            throwBundle(mService.close());
+            throwBundle(mExtras.getService().close());
         } catch (RemoteException e) {
-            return;
+            mExtras.attemptDeadServiceRecovery(e);
+            throw new IOException("NFC Service was dead");
         }
     }
 
@@ -109,9 +111,10 @@
     public byte[] transceive(byte[] in) throws IOException {
         Bundle b;
         try {
-            b = mService.transceive(in);
+            b = mExtras.getService().transceive(in);
         } catch (RemoteException e) {
-            throw new IOException(e.getMessage());
+            mExtras.attemptDeadServiceRecovery(e);
+            throw new IOException("NFC Service was dead, need to re-open");
         }
         throwBundle(b);
         return b.getByteArray("out");
diff --git a/obex/javax/obex/ClientSession.java b/obex/javax/obex/ClientSession.java
index 0935383..27d8976 100644
--- a/obex/javax/obex/ClientSession.java
+++ b/obex/javax/obex/ClientSession.java
@@ -449,8 +449,8 @@
                 maxPacketSize = (mInput.read() << 8) + mInput.read();
 
                 //check with local max size
-                if (maxPacketSize > ObexHelper.MAX_PACKET_SIZE_INT) {
-                    maxPacketSize = ObexHelper.MAX_PACKET_SIZE_INT;
+                if (maxPacketSize > ObexHelper.MAX_CLIENT_PACKET_SIZE) {
+                    maxPacketSize = ObexHelper.MAX_CLIENT_PACKET_SIZE;
                 }
 
                 if (length > 7) {
diff --git a/obex/javax/obex/ObexHelper.java b/obex/javax/obex/ObexHelper.java
index df0e0fb..8c12a20 100644
--- a/obex/javax/obex/ObexHelper.java
+++ b/obex/javax/obex/ObexHelper.java
@@ -70,6 +70,12 @@
      */
     public static final int MAX_PACKET_SIZE_INT = 0xFFFE;
 
+    /**
+     * Temporary workaround to be able to push files to Windows 7.
+     * TODO: Should be removed as soon as Microsoft updates their driver.
+     */
+    public static final int MAX_CLIENT_PACKET_SIZE = 0xFC00;
+
     public static final int OBEX_OPCODE_CONNECT = 0x80;
 
     public static final int OBEX_OPCODE_DISCONNECT = 0x81;
diff --git a/obex/javax/obex/PrivateOutputStream.java b/obex/javax/obex/PrivateOutputStream.java
index ca420af..713f4ae 100644
--- a/obex/javax/obex/PrivateOutputStream.java
+++ b/obex/javax/obex/PrivateOutputStream.java
@@ -107,18 +107,15 @@
 
         ensureOpen();
         mParent.ensureNotDone();
-        if (count < mMaxPacketSize) {
-            mArray.write(buffer, offset, count);
-        } else {
-            while (remainLength >= mMaxPacketSize) {
-                mArray.write(buffer, offset1, mMaxPacketSize);
-                offset1 += mMaxPacketSize;
-                remainLength = count - offset1;
-                mParent.continueOperation(true, false);
-            }
-            if (remainLength > 0) {
-                mArray.write(buffer, offset1, remainLength);
-            }
+        while ((mArray.size() + remainLength) >= mMaxPacketSize) {
+            int bufferLeft = mMaxPacketSize - mArray.size();
+            mArray.write(buffer, offset1, bufferLeft);
+            offset1 += bufferLeft;
+            remainLength -= bufferLeft;
+            mParent.continueOperation(true, false);
+        }
+        if (remainLength > 0) {
+            mArray.write(buffer, offset1, remainLength);
         }
     }
 
diff --git a/packages/SystemUI/res/drawable-hdpi/stat_sys_roaming_cdma_0.png b/packages/SystemUI/res/drawable-hdpi/stat_sys_roaming_cdma_0.png
index adde938..c8ddfce 100644
--- a/packages/SystemUI/res/drawable-hdpi/stat_sys_roaming_cdma_0.png
+++ b/packages/SystemUI/res/drawable-hdpi/stat_sys_roaming_cdma_0.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/stat_sys_roaming_cdma_flash_anim1.png b/packages/SystemUI/res/drawable-hdpi/stat_sys_roaming_cdma_flash_anim1.png
index adde938..6b6a6df 100644
--- a/packages/SystemUI/res/drawable-hdpi/stat_sys_roaming_cdma_flash_anim1.png
+++ b/packages/SystemUI/res/drawable-hdpi/stat_sys_roaming_cdma_flash_anim1.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_roaming_cdma_0.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_roaming_cdma_0.png
index c61cce7..827d84a 100755
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_roaming_cdma_0.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_roaming_cdma_0.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_roaming_cdma_flash_anim1.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_roaming_cdma_flash_anim1.png
index c61cce7..edc6023 100755
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_roaming_cdma_flash_anim1.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_roaming_cdma_flash_anim1.png
Binary files differ
diff --git a/policy/src/com/android/internal/policy/impl/GlobalActions.java b/policy/src/com/android/internal/policy/impl/GlobalActions.java
index 1f06dcc..c47383a 100644
--- a/policy/src/com/android/internal/policy/impl/GlobalActions.java
+++ b/policy/src/com/android/internal/policy/impl/GlobalActions.java
@@ -316,9 +316,10 @@
                 filteredPos++;
             }
 
-            throw new IllegalArgumentException("position " + position + " out of "
-                    + "range of showable actions, filtered count = "
-                    + "= " + getCount() + ", keyguardshowing=" + mKeyguardShowing
+            throw new IllegalArgumentException("position " + position
+                    + " out of range of showable actions"
+                    + ", filtered count=" + getCount()
+                    + ", keyguardshowing=" + mKeyguardShowing
                     + ", provisioned=" + mDeviceProvisioned);
         }
 
diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp
index 2b08ab5..dff9f33 100644
--- a/services/audioflinger/AudioFlinger.cpp
+++ b/services/audioflinger/AudioFlinger.cpp
@@ -5717,10 +5717,10 @@
 
 // update this table when AudioSystem::audio_mode or audio_mode_e (in EffectApi.h) are modified
 const uint32_t AudioFlinger::EffectModule::sModeConvTable[] = {
-    AUDIO_MODE_NORMAL,   // AudioSystem::MODE_NORMAL
-    AUDIO_MODE_RINGTONE, // AudioSystem::MODE_RINGTONE
-    AUDIO_MODE_IN_CALL,  // AudioSystem::MODE_IN_CALL
-    AUDIO_MODE_IN_CALL   // AudioSystem::MODE_IN_COMMUNICATION, same conversion as for MODE_IN_CALL
+    AUDIO_EFFECT_MODE_NORMAL,   // AudioSystem::MODE_NORMAL
+    AUDIO_EFFECT_MODE_RINGTONE, // AudioSystem::MODE_RINGTONE
+    AUDIO_EFFECT_MODE_IN_CALL,  // AudioSystem::MODE_IN_CALL
+    AUDIO_EFFECT_MODE_IN_CALL   // AudioSystem::MODE_IN_COMMUNICATION, same conversion as for MODE_IN_CALL
 };
 
 int AudioFlinger::EffectModule::modeAudioSystemToEffectApi(uint32_t mode)
diff --git a/services/audioflinger/AudioResampler.cpp b/services/audioflinger/AudioResampler.cpp
index 5c3b43fc..dca795c 100644
--- a/services/audioflinger/AudioResampler.cpp
+++ b/services/audioflinger/AudioResampler.cpp
@@ -26,11 +26,15 @@
 #include "AudioResamplerSinc.h"
 #include "AudioResamplerCubic.h"
 
+#ifdef __arm__
+#include <machine/cpu-features.h>
+#endif
+
 namespace android {
 
-#ifdef __ARM_ARCH_5E__  // optimized asm option
+#ifdef __ARM_HAVE_HALFWORD_MULTIPLY // optimized asm option
     #define ASM_ARM_RESAMP1 // enable asm optimisation for ResamplerOrder1
-#endif // __ARM_ARCH_5E__
+#endif // __ARM_HAVE_HALFWORD_MULTIPLY
 // ----------------------------------------------------------------------------
 
 class AudioResamplerOrder1 : public AudioResampler {
diff --git a/services/java/com/android/server/ConnectivityService.java b/services/java/com/android/server/ConnectivityService.java
index 9330491..55ce80b 100644
--- a/services/java/com/android/server/ConnectivityService.java
+++ b/services/java/com/android/server/ConnectivityService.java
@@ -1327,6 +1327,7 @@
                     }
                     if (!teardown(otherNet)) {
                         loge("Network declined teardown request");
+                        teardown(thisNet);
                         return;
                     }
                 }
@@ -1376,6 +1377,19 @@
                 handleApplyDefaultProxy(netType);
                 addDefaultRoute(mNetTrackers[netType]);
             } else {
+                // many radios add a default route even when we don't want one.
+                // remove the default interface unless we need it for our active network
+                if (mActiveDefaultNetwork != -1) {
+                    LinkProperties linkProperties =
+                            mNetTrackers[mActiveDefaultNetwork].getLinkProperties();
+                    LinkProperties newLinkProperties =
+                            mNetTrackers[netType].getLinkProperties();
+                    String defaultIface = linkProperties.getInterfaceName();
+                    if (defaultIface != null &&
+                            !defaultIface.equals(newLinkProperties.getInterfaceName())) {
+                        removeDefaultRoute(mNetTrackers[netType]);
+                    }
+                }
                 addPrivateDnsRoutes(mNetTrackers[netType]);
             }
 
diff --git a/services/java/com/android/server/MountService.java b/services/java/com/android/server/MountService.java
index 1f2ac2b..8570e6e 100644
--- a/services/java/com/android/server/MountService.java
+++ b/services/java/com/android/server/MountService.java
@@ -1653,7 +1653,8 @@
         } catch (NativeDaemonConnectorException e) {
             int code = e.getCode();
             if (code == VoldResponseCode.OpFailedStorageNotFound) {
-                throw new IllegalArgumentException(String.format("Container '%s' not found", id));
+                Slog.i(TAG, String.format("Container '%s' not found", id));
+                return null;
             } else {
                 throw new IllegalStateException(String.format("Unexpected response code %d", code));
             }
diff --git a/services/java/com/android/server/VibratorService.java b/services/java/com/android/server/VibratorService.java
index 2fcdb5d..c39dc80 100755
--- a/services/java/com/android/server/VibratorService.java
+++ b/services/java/com/android/server/VibratorService.java
@@ -247,6 +247,7 @@
     // Lock held on mVibrations
     private void startNextVibrationLocked() {
         if (mVibrations.size() <= 0) {
+            mCurrentVibration = null;
             return;
         }
         mCurrentVibration = mVibrations.getFirst();
@@ -273,17 +274,27 @@
             Vibration vib = iter.next();
             if (vib.mToken == token) {
                 iter.remove();
+                unlinkVibration(vib);
                 return vib;
             }
         }
         // We might be looking for a simple vibration which is only stored in
         // mCurrentVibration.
         if (mCurrentVibration != null && mCurrentVibration.mToken == token) {
+            unlinkVibration(mCurrentVibration);
             return mCurrentVibration;
         }
         return null;
     }
 
+    private void unlinkVibration(Vibration vib) {
+        if (vib.mPattern != null) {
+            // If Vibration object has a pattern,
+            // the Vibration object has also been linkedToDeath.
+            vib.mToken.unlinkToDeath(vib, 0);
+        }
+    }
+
     private class VibrateThread extends Thread {
         final Vibration mVibration;
         boolean mDone;
@@ -360,6 +371,7 @@
                     // If this vibration finished naturally, start the next
                     // vibration.
                     mVibrations.remove(mVibration);
+                    unlinkVibration(mVibration);
                     startNextVibrationLocked();
                 }
             }
diff --git a/services/java/com/android/server/am/ActivityManagerService.java b/services/java/com/android/server/am/ActivityManagerService.java
index 4cc032f..9989d3b 100644
--- a/services/java/com/android/server/am/ActivityManagerService.java
+++ b/services/java/com/android/server/am/ActivityManagerService.java
@@ -7050,8 +7050,9 @@
 
         addErrorToDropBox("wtf", r, null, null, tag, null, null, crashInfo);
 
-        if (Settings.Secure.getInt(mContext.getContentResolver(),
-                Settings.Secure.WTF_IS_FATAL, 0) != 0) {
+        if (r != null && r.pid != Process.myPid() &&
+                Settings.Secure.getInt(mContext.getContentResolver(),
+                        Settings.Secure.WTF_IS_FATAL, 0) != 0) {
             crashApplication(r, crashInfo);
             return true;
         } else {
@@ -7091,18 +7092,25 @@
      * to append various headers to the dropbox log text.
      */
     private void appendDropBoxProcessHeaders(ProcessRecord process, StringBuilder sb) {
+        // Watchdog thread ends up invoking this function (with
+        // a null ProcessRecord) to add the stack file to dropbox.
+        // Do not acquire a lock on this (am) in such cases, as it
+        // could cause a potential deadlock, if and when watchdog
+        // is invoked due to unavailability of lock on am and it
+        // would prevent watchdog from killing system_server.
+        if (process == null) {
+            sb.append("Process: system_server\n");
+            return;
+        }
         // Note: ProcessRecord 'process' is guarded by the service
         // instance.  (notably process.pkgList, which could otherwise change
         // concurrently during execution of this method)
         synchronized (this) {
-            if (process == null || process.pid == MY_PID) {
+            if (process.pid == MY_PID) {
                 sb.append("Process: system_server\n");
             } else {
                 sb.append("Process: ").append(process.processName).append("\n");
             }
-            if (process == null) {
-                return;
-            }
             int flags = process.info.flags;
             IPackageManager pm = AppGlobals.getPackageManager();
             sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
diff --git a/services/java/com/android/server/location/GpsLocationProvider.java b/services/java/com/android/server/location/GpsLocationProvider.java
index f3a2a62..67e73f5f 100755
--- a/services/java/com/android/server/location/GpsLocationProvider.java
+++ b/services/java/com/android/server/location/GpsLocationProvider.java
@@ -47,30 +47,25 @@
 import android.os.WorkSource;
 import android.provider.Settings;
 import android.provider.Telephony.Sms.Intents;
+import android.telephony.SmsMessage;
 import android.telephony.TelephonyManager;
 import android.telephony.gsm.GsmCellLocation;
-import android.telephony.SmsMessage;
 import android.util.Log;
 import android.util.SparseIntArray;
 
 import com.android.internal.app.IBatteryStats;
-import com.android.internal.telephony.Phone;
 import com.android.internal.location.GpsNetInitiatedHandler;
 import com.android.internal.location.GpsNetInitiatedHandler.GpsNiNotification;
-import com.android.internal.telephony.GsmAlphabet;
-import com.android.internal.telephony.SmsHeader;
-import com.android.internal.util.HexDump;
+import com.android.internal.telephony.Phone;
 
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.StringBufferInputStream;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
 import java.util.ArrayList;
 import java.util.Date;
-import java.util.Properties;
 import java.util.Map.Entry;
+import java.util.Properties;
 import java.util.concurrent.CountDownLatch;
 
 /**
@@ -203,7 +198,7 @@
     // flags to trigger NTP or XTRA data download when network becomes available
     // initialized to true so we do NTP and XTRA when the network comes up after booting
     private boolean mInjectNtpTimePending = true;
-    private boolean mDownloadXtraDataPending = false;
+    private boolean mDownloadXtraDataPending = true;
 
     // true if GPS is navigating
     private boolean mNavigating;
diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp
index 517c335..99d904d 100644
--- a/services/surfaceflinger/Layer.cpp
+++ b/services/surfaceflinger/Layer.cpp
@@ -984,8 +984,16 @@
     ssize_t index = mActiveBufferIndex;
     if (index >= 0) {
         if (!mFailover) {
-            Image& texture(mBufferData[index].texture);
-            err = mTextureManager.initEglImage(&texture, dpy, buffer);
+            {
+               // Without that lock, there is a chance of race condition
+               // where while composing a specific index, requestBuf
+               // with the same index can be executed and touch the same data
+               // that is being used in initEglImage.
+               // (e.g. dirty flag in texture)
+               Mutex::Autolock _l(mLock);
+               Image& texture(mBufferData[index].texture);
+               err = mTextureManager.initEglImage(&texture, dpy, buffer);
+            }
             // if EGLImage fails, we switch to regular texture mode, and we
             // free all resources associated with using EGLImages.
             if (err == NO_ERROR) {
diff --git a/services/surfaceflinger/TextureManager.cpp b/services/surfaceflinger/TextureManager.cpp
index c9a15f5..9e24f90 100644
--- a/services/surfaceflinger/TextureManager.cpp
+++ b/services/surfaceflinger/TextureManager.cpp
@@ -186,7 +186,7 @@
     if (texture->name == -1UL) {
         status_t err = initTexture(texture);
         LOGE_IF(err, "loadTexture failed in initTexture (%s)", strerror(err));
-        return err;
+        if (err != NO_ERROR) return err;
     }
 
     if (texture->target != Texture::TEXTURE_2D)
diff --git a/telephony/java/android/telephony/JapanesePhoneNumberFormatter.java b/telephony/java/android/telephony/JapanesePhoneNumberFormatter.java
index 6390d8e..f5e53ef 100644
--- a/telephony/java/android/telephony/JapanesePhoneNumberFormatter.java
+++ b/telephony/java/android/telephony/JapanesePhoneNumberFormatter.java
@@ -24,6 +24,7 @@
  *
  * 022-229-1234 0223-23-1234 022-301-9876 015-482-7849 0154-91-3478
  * 01547-5-4534 090-1234-1234 080-0123-6789
+ * 050-0000-0000 060-0000-0000
  * 0800-000-9999 0570-000-000 0276-00-0000
  *
  * As you can see, there is no straight-forward rule here.
@@ -31,7 +32,7 @@
  */
 /* package */ class JapanesePhoneNumberFormatter {
     private static short FORMAT_MAP[] = {
-    -100, 10, 220, -15, 410, 530, -15, 670, 780, 1060,
+    -100, 10, 220, -15, 410, 530, 1200, 670, 780, 1060,
     -100, -25, 20, 40, 70, 100, 150, 190, 200, 210,
     -36, -100, -100, -35, -35, -35, 30, -100, -100, -100,
     -35, -35, -35, -35, -35, -35, -35, -45, -35, -35,
@@ -84,7 +85,7 @@
     -35, -25, -25, -25, -25, -25, -25, -25, -25, -25,
     -25, -25, -25, -35, -35, -35, -25, -25, -25, 520,
     -100, -100, -45, -100, -45, -100, -45, -100, -45, -100,
-    -25, -100, -25, 540, 580, 590, 600, 610, 630, 640,
+    -26, -100, -25, 540, 580, 590, 600, 610, 630, 640,
     -25, -35, -35, -35, -25, -25, -35, -35, -35, 550,
     -35, -35, -25, -25, -25, -25, 560, 570, -25, -35,
     -35, -35, -35, -35, -25, -25, -25, -25, -25, -25,
@@ -150,7 +151,8 @@
     -35, 1170, -25, -35, 1180, -35, 1190, -35, -25, -25,
     -100, -100, -45, -45, -100, -100, -100, -100, -100, -100,
     -25, -35, -35, -35, -35, -35, -35, -25, -25, -35,
-    -35, -35, -35, -35, -35, -35, -35, -35, -35, -45};
+    -35, -35, -35, -35, -35, -35, -35, -35, -35, -45,
+    -26, -15, -15, -15, -15, -15, -15, -15, -15, -15};
 
     public static void format(Editable text) {
         // Here, "root" means the position of "'":
diff --git a/telephony/java/android/telephony/SmsMessage.java b/telephony/java/android/telephony/SmsMessage.java
index 93d89a7..e75d96d 100644
--- a/telephony/java/android/telephony/SmsMessage.java
+++ b/telephony/java/android/telephony/SmsMessage.java
@@ -317,7 +317,8 @@
                     nextPos = pos + Math.min(limit, textLen - pos);
                 } else {
                     // For multi-segment messages, CDMA 7bit equals GSM 7bit encoding (EMS mode).
-                    nextPos = GsmAlphabet.findGsmSeptetLimitIndex(text, pos, limit);
+                    nextPos = GsmAlphabet.findGsmSeptetLimitIndex(text, pos, limit,
+                            ted.languageTable, ted.languageShiftTable);
                 }
             } else {  // Assume unicode.
                 nextPos = pos + Math.min(limit / 2, textLen - pos);
@@ -373,7 +374,8 @@
      */
 
     /**
-     * Get an SMS-SUBMIT PDU for a destination address and a message
+     * Get an SMS-SUBMIT PDU for a destination address and a message.
+     * This method will not attempt to use any GSM national language 7 bit encodings.
      *
      * @param scAddress Service Centre address.  Null means use default.
      * @return a <code>SubmitPdu</code> containing the encoded SC
@@ -400,7 +402,8 @@
     }
 
     /**
-     * Get an SMS-SUBMIT PDU for a destination address and a message
+     * Get an SMS-SUBMIT PDU for a destination address and a message.
+     * This method will not attempt to use any GSM national language 7 bit encodings.
      *
      * @param scAddress Service Centre address.  Null means use default.
      * @return a <code>SubmitPdu</code> containing the encoded SC
@@ -424,7 +427,8 @@
     }
 
     /**
-     * Get an SMS-SUBMIT PDU for a data message to a destination address &amp; port
+     * Get an SMS-SUBMIT PDU for a data message to a destination address &amp; port.
+     * This method will not attempt to use any GSM national language 7 bit encodings.
      *
      * @param scAddress Service Centre address. null == use default
      * @param destinationAddress the address of the destination for the message
diff --git a/telephony/java/android/telephony/gsm/SmsMessage.java b/telephony/java/android/telephony/gsm/SmsMessage.java
index 6880175..4af99a6 100644
--- a/telephony/java/android/telephony/gsm/SmsMessage.java
+++ b/telephony/java/android/telephony/gsm/SmsMessage.java
@@ -297,37 +297,14 @@
      */
     @Deprecated
     public static int[] calculateLength(CharSequence messageBody, boolean use7bitOnly) {
+        SmsMessageBase.TextEncodingDetails ted =
+                com.android.internal.telephony.gsm.SmsMessage
+                        .calculateLength(messageBody, use7bitOnly);
         int ret[] = new int[4];
-
-        try {
-            // Try GSM alphabet
-            int septets = GsmAlphabet.countGsmSeptets(messageBody, !use7bitOnly);
-            ret[1] = septets;
-            if (septets > MAX_USER_DATA_SEPTETS) {
-                ret[0] = (septets + (MAX_USER_DATA_SEPTETS_WITH_HEADER - 1)) /
-                            MAX_USER_DATA_SEPTETS_WITH_HEADER;
-                ret[2] = (ret[0] * MAX_USER_DATA_SEPTETS_WITH_HEADER) - septets;
-            } else {
-                ret[0] = 1;
-                ret[2] = MAX_USER_DATA_SEPTETS - septets;
-            }
-            ret[3] = ENCODING_7BIT;
-        } catch (EncodeException ex) {
-            // fall back to UCS-2
-            int octets = messageBody.length() * 2;
-            ret[1] = messageBody.length();
-            if (octets > MAX_USER_DATA_BYTES) {
-                // 6 is the size of the user data header
-                ret[0] = (octets + (MAX_USER_DATA_BYTES_WITH_HEADER - 1)) /
-                            MAX_USER_DATA_BYTES_WITH_HEADER;
-                ret[2] = ((ret[0] * MAX_USER_DATA_BYTES_WITH_HEADER) - octets) / 2;
-            } else {
-                ret[0] = 1;
-                ret[2] = (MAX_USER_DATA_BYTES - octets)/2;
-            }
-            ret[3] = ENCODING_16BIT;
-        }
-
+        ret[0] = ted.msgCount;
+        ret[1] = ted.codeUnitCount;
+        ret[2] = ted.codeUnitsRemaining;
+        ret[3] = ted.codeUnitSize;
         return ret;
     }
 
diff --git a/telephony/java/com/android/internal/telephony/GsmAlphabet.java b/telephony/java/com/android/internal/telephony/GsmAlphabet.java
index e42827f..c7c91e4 100644
--- a/telephony/java/com/android/internal/telephony/GsmAlphabet.java
+++ b/telephony/java/com/android/internal/telephony/GsmAlphabet.java
@@ -16,6 +16,7 @@
 
 package com.android.internal.telephony;
 
+import android.content.res.Resources;
 import android.text.TextUtils;
 import android.util.SparseIntArray;
 
@@ -23,6 +24,14 @@
 
 import java.nio.ByteBuffer;
 import java.nio.charset.Charset;
+import com.android.internal.R;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static android.telephony.SmsMessage.ENCODING_7BIT;
+import static android.telephony.SmsMessage.MAX_USER_DATA_SEPTETS;
+import static android.telephony.SmsMessage.MAX_USER_DATA_SEPTETS_WITH_HEADER;
 
 /**
  * This class implements the character set mapping between
@@ -32,29 +41,51 @@
  * {@hide}
  */
 public class GsmAlphabet {
-    static final String LOG_TAG = "GSM";
+    private static final String TAG = "GSM";
 
-
+    private GsmAlphabet() { }
 
     //***** Constants
 
     /**
      * This escapes extended characters, and when present indicates that the
-     * following character should
-     * be looked up in the "extended" table
+     * following character should be looked up in the "extended" table.
      *
      * gsmToChar(GSM_EXTENDED_ESCAPE) returns 0xffff
      */
-
     public static final byte GSM_EXTENDED_ESCAPE = 0x1B;
 
+    /**
+     * User data header requires one octet for length. Count as one septet, because
+     * all combinations of header elements below will have at least one free bit
+     * when padding to the nearest septet boundary.
+     */
+    private static final int UDH_SEPTET_COST_LENGTH = 1;
 
     /**
-     * char to GSM alphabet char
-     * Returns ' ' in GSM alphabet if there's no possible match
-     * Returns GSM_EXTENDED_ESCAPE if this character is in the extended table
-     * In this case, you must call charToGsmExtended() for the value that
-     * should follow GSM_EXTENDED_ESCAPE in the GSM alphabet string
+     * Using a non-default language locking shift table OR single shift table
+     * requires a user data header of 3 octets, or 4 septets, plus UDH length.
+     */
+    private static final int UDH_SEPTET_COST_ONE_SHIFT_TABLE = 4;
+
+    /**
+     * Using a non-default language locking shift table AND single shift table
+     * requires a user data header of 6 octets, or 7 septets, plus UDH length.
+     */
+    private static final int UDH_SEPTET_COST_TWO_SHIFT_TABLES = 7;
+
+    /**
+     * Multi-part messages require a user data header of 5 octets, or 6 septets,
+     * plus UDH length.
+     */
+    private static final int UDH_SEPTET_COST_CONCATENATED_MESSAGE = 6;
+
+    /**
+     * Converts a char to a GSM 7 bit table index.
+     * Returns ' ' in GSM alphabet if there's no possible match. Returns
+     * GSM_EXTENDED_ESCAPE if this character is in the extended table.
+     * In this case, you must call charToGsmExtended() for the value
+     * that should follow GSM_EXTENDED_ESCAPE in the GSM alphabet string.
      */
     public static int
     charToGsm(char c) {
@@ -62,12 +93,12 @@
             return charToGsm(c, false);
         } catch (EncodeException ex) {
             // this should never happen
-            return sGsmSpaceChar;
+            return sCharsToGsmTables[0].get(' ', ' ');
         }
     }
 
     /**
-     * char to GSM alphabet char
+     * Converts a char to a GSM 7 bit table index.
      * @param throwException If true, throws EncodeException on invalid char.
      *   If false, returns GSM alphabet ' ' char.
      *
@@ -75,21 +106,20 @@
      * In this case, you must call charToGsmExtended() for the value that
      * should follow GSM_EXTENDED_ESCAPE in the GSM alphabet string
      */
-
     public static int
     charToGsm(char c, boolean throwException) throws EncodeException {
         int ret;
 
-        ret = charToGsm.get(c, -1);
+        ret = sCharsToGsmTables[0].get(c, -1);
 
         if (ret == -1) {
-            ret = charToGsmExtended.get(c, -1);
+            ret = sCharsToShiftTables[0].get(c, -1);
 
             if (ret == -1) {
                 if (throwException) {
                     throw new EncodeException(c);
                 } else {
-                    return sGsmSpaceChar;
+                    return sCharsToGsmTables[0].get(' ', ' ');
                 }
             } else {
                 return GSM_EXTENDED_ESCAPE;
@@ -97,44 +127,42 @@
         }
 
         return ret;
-
     }
 
-
     /**
-     * char to extended GSM alphabet char
-     *
-     * Extended chars should be escaped with GSM_EXTENDED_ESCAPE
-     *
-     * Returns ' ' in GSM alphabet if there's no possible match
-     *
+     * Converts a char to an extended GSM 7 bit table index.
+     * Extended chars should be escaped with GSM_EXTENDED_ESCAPE.
+     * Returns ' ' in GSM alphabet if there's no possible match.
      */
     public static int
     charToGsmExtended(char c) {
         int ret;
 
-        ret = charToGsmExtended.get(c, -1);
+        ret = sCharsToShiftTables[0].get(c, -1);
 
         if (ret == -1) {
-            return sGsmSpaceChar;
+            return sCharsToGsmTables[0].get(' ', ' ');
         }
 
         return ret;
     }
 
     /**
-     * Converts a character in the GSM alphabet into a char
+     * Converts a character in the GSM alphabet into a char.
      *
-     * if GSM_EXTENDED_ESCAPE is passed, 0xffff is returned. In this case,
+     * If GSM_EXTENDED_ESCAPE is passed, 0xffff is returned. In this case,
      * the following character in the stream should be decoded with
-     * gsmExtendedToChar()
+     * gsmExtendedToChar().
      *
-     * If an unmappable value is passed (one greater than 127), ' ' is returned
+     * If an unmappable value is passed (one greater than 127), ' ' is returned.
      */
-
     public static char
     gsmToChar(int gsmChar) {
-        return (char)gsmToChar.get(gsmChar, ' ');
+        if (gsmChar >= 0 && gsmChar < 128) {
+            return sLanguageTables[0].charAt(gsmChar);
+        } else {
+            return ' ';
+        }
     }
 
     /**
@@ -144,20 +172,23 @@
      * extension page has yet been defined (see Note 1 in table 6.2.1.1 of
      * TS 23.038 v7.00)
      *
-     * If an unmappable value is passed , ' ' is returned
+     * If an unmappable value is passed, the character from the GSM 7 bit
+     * default table will be used (table 6.2.1.1 of TS 23.038).
      */
-
     public static char
     gsmExtendedToChar(int gsmChar) {
-        int ret;
-
-        ret = gsmExtendedToChar.get(gsmChar, -1);
-
-        if (ret == -1) {
+        if (gsmChar == GSM_EXTENDED_ESCAPE) {
             return ' ';
+        } else if (gsmChar >= 0 && gsmChar < 128) {
+            char c = sLanguageShiftTables[0].charAt(gsmChar);
+            if (c == ' ') {
+                return sLanguageTables[0].charAt(gsmChar);
+            } else {
+                return c;
+            }
+        } else {
+            return ' ';     // out of range
         }
-
-        return (char)ret;
     }
 
     /**
@@ -176,19 +207,24 @@
      * @param data The text string to encode.
      * @param header Optional header (including length byte) that precedes
      * the encoded data, padded to septet boundary.
+     * @param languageTable the 7 bit language table, or 0 for the default GSM alphabet
+     * @param languageShiftTable the 7 bit single shift language table, or 0 for the default
+     *     GSM extension table
      * @return Byte array containing header and encoded data.
+     * @throws EncodeException if String is too large to encode
      */
-    public static byte[] stringToGsm7BitPackedWithHeader(String data, byte[] header)
+    public static byte[] stringToGsm7BitPackedWithHeader(String data, byte[] header,
+            int languageTable, int languageShiftTable)
             throws EncodeException {
-
         if (header == null || header.length == 0) {
-            return stringToGsm7BitPacked(data);
+            return stringToGsm7BitPacked(data, languageTable, languageShiftTable);
         }
 
         int headerBits = (header.length + 1) * 8;
         int headerSeptets = (headerBits + 6) / 7;
 
-        byte[] ret = stringToGsm7BitPacked(data, headerSeptets, true);
+        byte[] ret = stringToGsm7BitPacked(data, headerSeptets, true, languageTable,
+                languageShiftTable);
 
         // Paste in the header
         ret[1] = (byte)header.length;
@@ -208,11 +244,16 @@
      * septets.
      *
      * @param data the data string to encode
+     * @param languageTable the 7 bit language table, or 0 for the default GSM alphabet
+     * @param languageShiftTable the 7 bit single shift language table, or 0 for the default
+     *     GSM extension table
+     * @return the encoded string
      * @throws EncodeException if String is too large to encode
      */
-    public static byte[] stringToGsm7BitPacked(String data)
+    public static byte[] stringToGsm7BitPacked(String data, int languageTable,
+            int languageShiftTable)
             throws EncodeException {
-        return stringToGsm7BitPacked(data, 0, true);
+        return stringToGsm7BitPacked(data, 0, true, languageTable, languageShiftTable);
     }
 
     /**
@@ -229,28 +270,48 @@
      *  the character data at the beginning of the array
      * @param throwException If true, throws EncodeException on invalid char.
      *   If false, replaces unencodable char with GSM alphabet space char.
+     * @param languageTable the 7 bit language table, or 0 for the default GSM alphabet
+     * @param languageShiftTable the 7 bit single shift language table, or 0 for the default
+     *     GSM extension table
+     * @return the encoded message
      *
      * @throws EncodeException if String is too large to encode
      */
     public static byte[] stringToGsm7BitPacked(String data, int startingSeptetOffset,
-            boolean throwException) throws EncodeException {
+            boolean throwException, int languageTable, int languageShiftTable)
+            throws EncodeException {
         int dataLen = data.length();
-        int septetCount = countGsmSeptets(data, throwException) + startingSeptetOffset;
+        int septetCount = countGsmSeptetsUsingTables(data, !throwException,
+                languageTable, languageShiftTable);
+        if (septetCount == -1) {
+            throw new EncodeException("countGsmSeptetsUsingTables(): unencodable char");
+        }
+        septetCount += startingSeptetOffset;
         if (septetCount > 255) {
             throw new EncodeException("Payload cannot exceed 255 septets");
         }
         int byteCount = ((septetCount * 7) + 7) / 8;
         byte[] ret = new byte[byteCount + 1];  // Include space for one byte length prefix.
+        SparseIntArray charToLanguageTable = sCharsToGsmTables[languageTable];
+        SparseIntArray charToShiftTable = sCharsToShiftTables[languageShiftTable];
         for (int i = 0, septets = startingSeptetOffset, bitOffset = startingSeptetOffset * 7;
                  i < dataLen && septets < septetCount;
                  i++, bitOffset += 7) {
             char c = data.charAt(i);
-            int v = GsmAlphabet.charToGsm(c, throwException);
-            if (v == GSM_EXTENDED_ESCAPE) {
-                v = GsmAlphabet.charToGsmExtended(c);  // Lookup the extended char.
-                packSmsChar(ret, bitOffset, GSM_EXTENDED_ESCAPE);
-                bitOffset += 7;
-                septets++;
+            int v = charToLanguageTable.get(c, -1);
+            if (v == -1) {
+                v = charToShiftTable.get(c, -1);  // Lookup the extended char.
+                if (v == -1) {
+                    if (throwException) {
+                        throw new EncodeException("stringToGsm7BitPacked(): unencodable char");
+                    } else {
+                        v = charToLanguageTable.get(' ', ' ');   // should return ASCII space
+                    }
+                } else {
+                    packSmsChar(ret, bitOffset, GSM_EXTENDED_ESCAPE);
+                    bitOffset += 7;
+                    septets++;
+                }
             }
             packSmsChar(ret, bitOffset, v);
             septets++;
@@ -262,8 +323,10 @@
     /**
      * Pack a 7-bit char into its appropriate place in a byte array
      *
+     * @param packedChars the destination byte array
      * @param bitOffset the bit offset that the septet should be packed at
      *                  (septet index * 7)
+     * @param value the 7-bit character to store
      */
     private static void
     packSmsChar(byte[] packedChars, int bitOffset, int value) {
@@ -290,7 +353,7 @@
      */
     public static String gsm7BitPackedToString(byte[] pdu, int offset,
             int lengthSeptets) {
-        return gsm7BitPackedToString(pdu, offset, lengthSeptets, 0);
+        return gsm7BitPackedToString(pdu, offset, lengthSeptets, 0, 0, 0);
     }
 
     /**
@@ -304,15 +367,37 @@
      * @param lengthSeptets string length in septets, not bytes
      * @param numPaddingBits the number of padding bits before the start of the
      *  string in the first byte
+     * @param languageTable the 7 bit language table, or 0 for the default GSM alphabet
+     * @param shiftTable the 7 bit single shift language table, or 0 for the default
+     *     GSM extension table
      * @return String representation or null on decoding exception
      */
     public static String gsm7BitPackedToString(byte[] pdu, int offset,
-            int lengthSeptets, int numPaddingBits) {
+            int lengthSeptets, int numPaddingBits, int languageTable, int shiftTable) {
         StringBuilder ret = new StringBuilder(lengthSeptets);
-        boolean prevCharWasEscape;
+
+        if (languageTable < 0 || languageTable > sLanguageTables.length) {
+            Log.w(TAG, "unknown language table " + languageTable + ", using default");
+            languageTable = 0;
+        }
+        if (shiftTable < 0 || shiftTable > sLanguageShiftTables.length) {
+            Log.w(TAG, "unknown single shift table " + shiftTable + ", using default");
+            shiftTable = 0;
+        }
 
         try {
-            prevCharWasEscape = false;
+            boolean prevCharWasEscape = false;
+            String languageTableToChar = sLanguageTables[languageTable];
+            String shiftTableToChar = sLanguageShiftTables[shiftTable];
+
+            if (languageTableToChar.isEmpty()) {
+                Log.w(TAG, "no language table for code " + languageTable + ", using default");
+                languageTableToChar = sLanguageTables[0];
+            }
+            if (shiftTableToChar.isEmpty()) {
+                Log.w(TAG, "no single shift table for code " + shiftTable + ", using default");
+                shiftTableToChar = sLanguageShiftTables[0];
+            }
 
             for (int i = 0 ; i < lengthSeptets ; i++) {
                 int bitOffset = (7 * i) + numPaddingBits;
@@ -332,16 +417,25 @@
                 }
 
                 if (prevCharWasEscape) {
-                    ret.append(GsmAlphabet.gsmExtendedToChar(gsmVal));
+                    if (gsmVal == GSM_EXTENDED_ESCAPE) {
+                        ret.append(' ');    // display ' ' for reserved double escape sequence
+                    } else {
+                        char c = shiftTableToChar.charAt(gsmVal);
+                        if (c == ' ') {
+                            ret.append(languageTableToChar.charAt(gsmVal));
+                        } else {
+                            ret.append(c);
+                        }
+                    }
                     prevCharWasEscape = false;
                 } else if (gsmVal == GSM_EXTENDED_ESCAPE) {
                     prevCharWasEscape = true;
                 } else {
-                    ret.append(GsmAlphabet.gsmToChar(gsmVal));
+                    ret.append(languageTableToChar.charAt(gsmVal));
                 }
             }
         } catch (RuntimeException ex) {
-            Log.e(LOG_TAG, "Error GSM 7 bit packed: ", ex);
+            Log.e(TAG, "Error GSM 7 bit packed: ", ex);
             return null;
         }
 
@@ -384,10 +478,13 @@
             charset = Charset.forName(characterset);
             mbcsBuffer = ByteBuffer.allocate(2);
         }
-        boolean prevWasEscape;
-        StringBuilder ret = new StringBuilder(length);
 
-        prevWasEscape = false;
+        // Always use GSM 7 bit default alphabet table for this method
+        String languageTableToChar = sLanguageTables[0];
+        String shiftTableToChar = sLanguageShiftTables[0];
+
+        StringBuilder ret = new StringBuilder(length);
+        boolean prevWasEscape = false;
         for (int i = offset ; i < offset + length ; i++) {
             // Never underestimate the pain that can be caused
             // by signed bytes
@@ -407,10 +504,16 @@
                 }
             } else {
                 if (prevWasEscape) {
-                    ret.append((char)gsmExtendedToChar.get(c, ' '));
+                    char shiftChar = shiftTableToChar.charAt(c);
+                    if (shiftChar == ' ') {
+                        // display character from main table if not present in shift table
+                        ret.append(languageTableToChar.charAt(c));
+                    } else {
+                        ret.append(shiftChar);
+                    }
                 } else {
                     if (!isMbcs || c < 0x80 || i + 1 >= offset + length) {
-                        ret.append((char)gsmToChar.get(c, ' '));
+                        ret.append(languageTableToChar.charAt(c));
                     } else {
                         // isMbcs must be true. So both mbcsBuffer and charset are initialized.
                         mbcsBuffer.clear();
@@ -427,16 +530,14 @@
     }
 
     /**
-     * Convert a string into an 8-bit unpacked GSM alphabet byte
-     * array
+     * Convert a string into an 8-bit unpacked GSM alphabet byte array.
+     * Always uses GSM default 7-bit alphabet and extension table.
      */
     public static byte[]
     stringToGsm8BitPacked(String s) {
         byte[] ret;
 
-        int septets = 0;
-
-        septets = countGsmSeptets(s);
+        int septets = countGsmSeptetsUsingTables(s, true, 0, 0);
 
         // Enough for all the septets and the length byte prefix
         ret = new byte[septets];
@@ -457,6 +558,8 @@
     public static void
     stringToGsm8BitUnpackedField(String s, byte dest[], int offset, int length) {
         int outByteIndex = offset;
+        SparseIntArray charToLanguageTable = sCharsToGsmTables[0];
+        SparseIntArray charToShiftTable = sCharsToShiftTables[0];
 
         // Septets are stored in byte-aligned octets
         for (int i = 0, sz = s.length()
@@ -465,17 +568,20 @@
         ) {
             char c = s.charAt(i);
 
-            int v = GsmAlphabet.charToGsm(c);
+            int v = charToLanguageTable.get(c, -1);
 
-            if (v == GSM_EXTENDED_ESCAPE) {
-                // make sure we can fit an escaped char
-                if (! (outByteIndex + 1 - offset < length)) {
-                    break;
+            if (v == -1) {
+                v = charToShiftTable.get(c, -1);
+                if (v == -1) {
+                    v = charToLanguageTable.get(' ', ' ');  // fall back to ASCII space
+                } else {
+                    // make sure we can fit an escaped char
+                    if (! (outByteIndex + 1 - offset < length)) {
+                        break;
+                    }
+
+                    dest[outByteIndex++] = GSM_EXTENDED_ESCAPE;
                 }
-
-                dest[outByteIndex++] = GSM_EXTENDED_ESCAPE;
-
-                v = GsmAlphabet.charToGsmExtended(c);
             }
 
             dest[outByteIndex++] = (byte)v;
@@ -503,17 +609,17 @@
 
     /**
      * Returns the count of 7-bit GSM alphabet characters
-     * needed to represent this character
+     * needed to represent this character using the default 7 bit GSM alphabet.
      * @param throwsException If true, throws EncodeException if unencodable
      * char. Otherwise, counts invalid char as 1 septet
      */
     public static int
     countGsmSeptets(char c, boolean throwsException) throws EncodeException {
-        if (charToGsm.get(c, -1) != -1) {
+        if (sCharsToGsmTables[0].get(c, -1) != -1) {
             return 1;
         }
 
-        if (charToGsmExtended.get(c, -1) != -1) {
+        if (sCharsToShiftTables[0].get(c, -1) != -1) {
             return 2;
         }
 
@@ -526,37 +632,196 @@
     }
 
     /**
-     * Returns the count of 7-bit GSM alphabet characters
-     * needed to represent this string. Counts unencodable char as 1 septet.
+     * Returns the count of 7-bit GSM alphabet characters needed
+     * to represent this string, using the specified 7-bit language table
+     * and extension table (0 for GSM default tables).
+     * @param s the Unicode string that will be encoded
+     * @param use7bitOnly allow using space in place of unencodable character if true,
+     *     otherwise, return -1 if any characters are unencodable
+     * @param languageTable the 7 bit language table, or 0 for the default GSM alphabet
+     * @param languageShiftTable the 7 bit single shift language table, or 0 for the default
+     *     GSM extension table
+     * @return the septet count for s using the specified language tables, or -1 if any
+     *     characters are unencodable and use7bitOnly is false
      */
-    public static int
-    countGsmSeptets(CharSequence s) {
-        try {
-            return countGsmSeptets(s, false);
-        } catch (EncodeException ex) {
-            // this should never happen
-            return 0;
+    public static int countGsmSeptetsUsingTables(CharSequence s, boolean use7bitOnly,
+            int languageTable, int languageShiftTable) {
+        int count = 0;
+        int sz = s.length();
+        SparseIntArray charToLanguageTable = sCharsToGsmTables[languageTable];
+        SparseIntArray charToShiftTable = sCharsToShiftTables[languageShiftTable];
+        for (int i = 0; i < sz; i++) {
+            char c = s.charAt(i);
+            if (c == GSM_EXTENDED_ESCAPE) {
+                Log.w(TAG, "countGsmSeptets() string contains Escape character, skipping.");
+                continue;
+            }
+            if (charToLanguageTable.get(c, -1) != -1) {
+                count++;
+            } else if (charToShiftTable.get(c, -1) != -1) {
+                count += 2; // escape + shift table index
+            } else if (use7bitOnly) {
+                count++;    // encode as space
+            } else {
+                return -1;  // caller must check for this case
+            }
         }
+        return count;
     }
 
     /**
      * Returns the count of 7-bit GSM alphabet characters
-     * needed to represent this string.
-     * @param throwsException If true, throws EncodeException if unencodable
-     * char. Otherwise, counts invalid char as 1 septet
+     * needed to represent this string, and the language table and
+     * language shift table used to achieve this result.
+     * For multi-part text messages, each message part may use its
+     * own language table encoding as specified in the message header
+     * for that message. However, this method will only return the
+     * optimal encoding for the message as a whole. When the individual
+     * pieces are encoded, a more optimal encoding may be chosen for each
+     * piece of the message, but the message will be split into pieces
+     * based on the encoding chosen for the message as a whole.
+     * @param s the Unicode string that will be encoded
+     * @param use7bitOnly allow using space in place of unencodable character if true,
+     *     using the language table pair with the fewest unencodable characters
+     * @return a TextEncodingDetails object containing the message and
+     *     character counts for the most efficient 7-bit encoding,
+     *     or null if there are no suitable language tables to encode the string.
      */
-    public static int
-    countGsmSeptets(CharSequence s, boolean throwsException) throws EncodeException {
-        int charIndex = 0;
-        int sz = s.length();
-        int count = 0;
-
-        while (charIndex < sz) {
-            count += countGsmSeptets(s.charAt(charIndex), throwsException);
-            charIndex++;
+    public static SmsMessageBase.TextEncodingDetails
+    countGsmSeptets(CharSequence s, boolean use7bitOnly) {
+        // fast path for common case where no national language shift tables are enabled
+        if (sEnabledSingleShiftTables.length + sEnabledLockingShiftTables.length == 0) {
+            SmsMessageBase.TextEncodingDetails ted = new SmsMessageBase.TextEncodingDetails();
+            int septets = GsmAlphabet.countGsmSeptetsUsingTables(s, use7bitOnly, 0, 0);
+            if (septets == -1) {
+                return null;
+            }
+            ted.codeUnitSize = ENCODING_7BIT;
+            ted.codeUnitCount = septets;
+            if (septets > MAX_USER_DATA_SEPTETS) {
+                ted.msgCount = (septets + (MAX_USER_DATA_SEPTETS_WITH_HEADER - 1)) /
+                        MAX_USER_DATA_SEPTETS_WITH_HEADER;
+                ted.codeUnitsRemaining = (ted.msgCount *
+                        MAX_USER_DATA_SEPTETS_WITH_HEADER) - septets;
+            } else {
+                ted.msgCount = 1;
+                ted.codeUnitsRemaining = MAX_USER_DATA_SEPTETS - septets;
+            }
+            ted.codeUnitSize = ENCODING_7BIT;
+            return ted;
         }
 
-        return count;
+        int maxSingleShiftCode = sHighestEnabledSingleShiftCode;
+        List<LanguagePairCount> lpcList = new ArrayList<LanguagePairCount>(
+                sEnabledLockingShiftTables.length + 1);
+
+        // Always add default GSM 7-bit alphabet table
+        lpcList.add(new LanguagePairCount(0));
+        for (int i : sEnabledLockingShiftTables) {
+            // Avoid adding default table twice in case 0 is in the list of allowed tables
+            if (i != 0 && !sLanguageTables[i].isEmpty()) {
+                lpcList.add(new LanguagePairCount(i));
+            }
+        }
+
+        int sz = s.length();
+        // calculate septet count for each valid table / shift table pair
+        for (int i = 0; i < sz && !lpcList.isEmpty(); i++) {
+            char c = s.charAt(i);
+            if (c == GSM_EXTENDED_ESCAPE) {
+                Log.w(TAG, "countGsmSeptets() string contains Escape character, ignoring!");
+                continue;
+            }
+            // iterate through enabled locking shift tables
+            for (LanguagePairCount lpc : lpcList) {
+                int tableIndex = sCharsToGsmTables[lpc.languageCode].get(c, -1);
+                if (tableIndex == -1) {
+                    // iterate through single shift tables for this locking table
+                    for (int table = 0; table <= maxSingleShiftCode; table++) {
+                        if (lpc.septetCounts[table] != -1) {
+                            int shiftTableIndex = sCharsToShiftTables[table].get(c, -1);
+                            if (shiftTableIndex == -1) {
+                                if (use7bitOnly) {
+                                    // can't encode char, use space instead
+                                    lpc.septetCounts[table]++;
+                                    lpc.unencodableCounts[table]++;
+                                } else {
+                                    // can't encode char, remove language pair from list
+                                    lpc.septetCounts[table] = -1;
+                                }
+                            } else {
+                                // encode as Escape + index into shift table
+                                lpc.septetCounts[table] += 2;
+                            }
+                        }
+                    }
+                } else {
+                    // encode as index into locking shift table for all pairs
+                    for (int table = 0; table <= maxSingleShiftCode; table++) {
+                        if (lpc.septetCounts[table] != -1) {
+                            lpc.septetCounts[table]++;
+                        }
+                    }
+                }
+            }
+        }
+
+        // find the least cost encoding (lowest message count and most code units remaining)
+        SmsMessageBase.TextEncodingDetails ted = new SmsMessageBase.TextEncodingDetails();
+        ted.msgCount = Integer.MAX_VALUE;
+        ted.codeUnitSize = ENCODING_7BIT;
+        int minUnencodableCount = Integer.MAX_VALUE;
+        for (LanguagePairCount lpc : lpcList) {
+            for (int shiftTable = 0; shiftTable <= maxSingleShiftCode; shiftTable++) {
+                int septets = lpc.septetCounts[shiftTable];
+                if (septets == -1) {
+                    continue;
+                }
+                int udhLength;
+                if (lpc.languageCode != 0 && shiftTable != 0) {
+                    udhLength = UDH_SEPTET_COST_LENGTH + UDH_SEPTET_COST_TWO_SHIFT_TABLES;
+                } else if (lpc.languageCode != 0 || shiftTable != 0) {
+                    udhLength = UDH_SEPTET_COST_LENGTH + UDH_SEPTET_COST_ONE_SHIFT_TABLE;
+                } else {
+                    udhLength = 0;
+                }
+                int msgCount;
+                int septetsRemaining;
+                if (septets + udhLength > MAX_USER_DATA_SEPTETS) {
+                    if (udhLength == 0) {
+                        udhLength = UDH_SEPTET_COST_LENGTH;
+                    }
+                    udhLength += UDH_SEPTET_COST_CONCATENATED_MESSAGE;
+                    int septetsPerMessage = MAX_USER_DATA_SEPTETS - udhLength;
+                    msgCount = (septets + septetsPerMessage - 1) / septetsPerMessage;
+                    septetsRemaining = (msgCount * septetsPerMessage) - septets;
+                } else {
+                    msgCount = 1;
+                    septetsRemaining = MAX_USER_DATA_SEPTETS - udhLength - septets;
+                }
+                // for 7-bit only mode, use language pair with the least unencodable chars
+                int unencodableCount = lpc.unencodableCounts[shiftTable];
+                if (use7bitOnly && unencodableCount > minUnencodableCount) {
+                    continue;
+                }
+                if ((use7bitOnly && unencodableCount < minUnencodableCount)
+                        || msgCount < ted.msgCount || (msgCount == ted.msgCount
+                        && septetsRemaining > ted.codeUnitsRemaining)) {
+                    minUnencodableCount = unencodableCount;
+                    ted.msgCount = msgCount;
+                    ted.codeUnitCount = septets;
+                    ted.codeUnitsRemaining = septetsRemaining;
+                    ted.languageTable = lpc.languageCode;
+                    ted.languageShiftTable = shiftTable;
+                }
+            }
+        }
+
+        if (ted.msgCount == Integer.MAX_VALUE) {
+            return null;
+        }
+
+        return ted;
     }
 
     /**
@@ -569,16 +834,31 @@
      * @param start index of where to start counting septets
      * @param limit maximum septets to include,
      *   e.g. <code>MAX_USER_DATA_SEPTETS</code>
+     * @param langTable the 7 bit character table to use (0 for default GSM 7-bit alphabet)
+     * @param langShiftTable the 7 bit shift table to use (0 for default GSM extension table)
      * @return index of first character that won't fit, or the length
      *   of the entire string if everything fits
      */
     public static int
-    findGsmSeptetLimitIndex(String s, int start, int limit) {
+    findGsmSeptetLimitIndex(String s, int start, int limit, int langTable, int langShiftTable) {
         int accumulator = 0;
         int size = s.length();
 
+        SparseIntArray charToLangTable = sCharsToGsmTables[langTable];
+        SparseIntArray charToLangShiftTable = sCharsToShiftTables[langShiftTable];
         for (int i = start; i < size; i++) {
-            accumulator += countGsmSeptets(s.charAt(i));
+            int encodedSeptet = charToLangTable.get(s.charAt(i), -1);
+            if (encodedSeptet == -1) {
+                encodedSeptet = charToLangShiftTable.get(s.charAt(i), -1);
+                if (encodedSeptet == -1) {
+                    // char not found, assume we're replacing with space
+                    accumulator++;
+                } else {
+                    accumulator += 2;  // escape character + shift table index
+                }
+            } else {
+                accumulator++;
+            }
             if (accumulator > limit) {
                 return i;
             }
@@ -586,178 +866,488 @@
         return size;
     }
 
-    // Set in the static initializer
-    private static int sGsmSpaceChar;
+    /**
+     * Modify the array of enabled national language single shift tables for SMS
+     * encoding. This is used for unit testing, but could also be used to
+     * modify the enabled encodings based on the active MCC/MNC, for example.
+     *
+     * @param tables the new list of enabled single shift tables
+     */
+    static synchronized void setEnabledSingleShiftTables(int[] tables) {
+        sEnabledSingleShiftTables = tables;
 
-    private static final SparseIntArray charToGsm = new SparseIntArray();
-    private static final SparseIntArray gsmToChar = new SparseIntArray();
-    private static final SparseIntArray charToGsmExtended = new SparseIntArray();
-    private static final SparseIntArray gsmExtendedToChar = new SparseIntArray();
-
-    static {
-        int i = 0;
-
-        charToGsm.put('@', i++);
-        charToGsm.put('\u00a3', i++);
-        charToGsm.put('$', i++);
-        charToGsm.put('\u00a5', i++);
-        charToGsm.put('\u00e8', i++);
-        charToGsm.put('\u00e9', i++);
-        charToGsm.put('\u00f9', i++);
-        charToGsm.put('\u00ec', i++);
-        charToGsm.put('\u00f2', i++);
-        charToGsm.put('\u00c7', i++);
-        charToGsm.put('\n', i++);
-        charToGsm.put('\u00d8', i++);
-        charToGsm.put('\u00f8', i++);
-        charToGsm.put('\r', i++);
-        charToGsm.put('\u00c5', i++);
-        charToGsm.put('\u00e5', i++);
-
-        charToGsm.put('\u0394', i++);
-        charToGsm.put('_', i++);
-        charToGsm.put('\u03a6', i++);
-        charToGsm.put('\u0393', i++);
-        charToGsm.put('\u039b', i++);
-        charToGsm.put('\u03a9', i++);
-        charToGsm.put('\u03a0', i++);
-        charToGsm.put('\u03a8', i++);
-        charToGsm.put('\u03a3', i++);
-        charToGsm.put('\u0398', i++);
-        charToGsm.put('\u039e', i++);
-        charToGsm.put('\uffff', i++);
-        charToGsm.put('\u00c6', i++);
-        charToGsm.put('\u00e6', i++);
-        charToGsm.put('\u00df', i++);
-        charToGsm.put('\u00c9', i++);
-
-        charToGsm.put(' ', i++);
-        charToGsm.put('!', i++);
-        charToGsm.put('"', i++);
-        charToGsm.put('#', i++);
-        charToGsm.put('\u00a4', i++);
-        charToGsm.put('%', i++);
-        charToGsm.put('&', i++);
-        charToGsm.put('\'', i++);
-        charToGsm.put('(', i++);
-        charToGsm.put(')', i++);
-        charToGsm.put('*', i++);
-        charToGsm.put('+', i++);
-        charToGsm.put(',', i++);
-        charToGsm.put('-', i++);
-        charToGsm.put('.', i++);
-        charToGsm.put('/', i++);
-
-        charToGsm.put('0', i++);
-        charToGsm.put('1', i++);
-        charToGsm.put('2', i++);
-        charToGsm.put('3', i++);
-        charToGsm.put('4', i++);
-        charToGsm.put('5', i++);
-        charToGsm.put('6', i++);
-        charToGsm.put('7', i++);
-        charToGsm.put('8', i++);
-        charToGsm.put('9', i++);
-        charToGsm.put(':', i++);
-        charToGsm.put(';', i++);
-        charToGsm.put('<', i++);
-        charToGsm.put('=', i++);
-        charToGsm.put('>', i++);
-        charToGsm.put('?', i++);
-
-        charToGsm.put('\u00a1', i++);
-        charToGsm.put('A', i++);
-        charToGsm.put('B', i++);
-        charToGsm.put('C', i++);
-        charToGsm.put('D', i++);
-        charToGsm.put('E', i++);
-        charToGsm.put('F', i++);
-        charToGsm.put('G', i++);
-        charToGsm.put('H', i++);
-        charToGsm.put('I', i++);
-        charToGsm.put('J', i++);
-        charToGsm.put('K', i++);
-        charToGsm.put('L', i++);
-        charToGsm.put('M', i++);
-        charToGsm.put('N', i++);
-        charToGsm.put('O', i++);
-
-        charToGsm.put('P', i++);
-        charToGsm.put('Q', i++);
-        charToGsm.put('R', i++);
-        charToGsm.put('S', i++);
-        charToGsm.put('T', i++);
-        charToGsm.put('U', i++);
-        charToGsm.put('V', i++);
-        charToGsm.put('W', i++);
-        charToGsm.put('X', i++);
-        charToGsm.put('Y', i++);
-        charToGsm.put('Z', i++);
-        charToGsm.put('\u00c4', i++);
-        charToGsm.put('\u00d6', i++);
-        charToGsm.put('\u00d1', i++);
-        charToGsm.put('\u00dc', i++);
-        charToGsm.put('\u00a7', i++);
-
-        charToGsm.put('\u00bf', i++);
-        charToGsm.put('a', i++);
-        charToGsm.put('b', i++);
-        charToGsm.put('c', i++);
-        charToGsm.put('d', i++);
-        charToGsm.put('e', i++);
-        charToGsm.put('f', i++);
-        charToGsm.put('g', i++);
-        charToGsm.put('h', i++);
-        charToGsm.put('i', i++);
-        charToGsm.put('j', i++);
-        charToGsm.put('k', i++);
-        charToGsm.put('l', i++);
-        charToGsm.put('m', i++);
-        charToGsm.put('n', i++);
-        charToGsm.put('o', i++);
-
-        charToGsm.put('p', i++);
-        charToGsm.put('q', i++);
-        charToGsm.put('r', i++);
-        charToGsm.put('s', i++);
-        charToGsm.put('t', i++);
-        charToGsm.put('u', i++);
-        charToGsm.put('v', i++);
-        charToGsm.put('w', i++);
-        charToGsm.put('x', i++);
-        charToGsm.put('y', i++);
-        charToGsm.put('z', i++);
-        charToGsm.put('\u00e4', i++);
-        charToGsm.put('\u00f6', i++);
-        charToGsm.put('\u00f1', i++);
-        charToGsm.put('\u00fc', i++);
-        charToGsm.put('\u00e0', i++);
-
-
-        charToGsmExtended.put('\f', 10);
-        charToGsmExtended.put('^', 20);
-        charToGsmExtended.put('{', 40);
-        charToGsmExtended.put('}', 41);
-        charToGsmExtended.put('\\', 47);
-        charToGsmExtended.put('[', 60);
-        charToGsmExtended.put('~', 61);
-        charToGsmExtended.put(']', 62);
-        charToGsmExtended.put('|', 64);
-        charToGsmExtended.put('\u20ac', 101);
-
-        int size = charToGsm.size();
-        for (int j=0; j<size; j++) {
-            gsmToChar.put(charToGsm.valueAt(j), charToGsm.keyAt(j));
+        if (tables.length > 0) {
+            sHighestEnabledSingleShiftCode = tables[tables.length - 1];
+        } else {
+            sHighestEnabledSingleShiftCode = 0;
         }
-
-        size = charToGsmExtended.size();
-        for (int j=0; j<size; j++) {
-            gsmExtendedToChar.put(charToGsmExtended.valueAt(j), charToGsmExtended.keyAt(j));
-        }
-
-
-        sGsmSpaceChar = charToGsm.get(' ');
     }
 
+    /**
+     * Modify the array of enabled national language locking shift tables for SMS
+     * encoding. This is used for unit testing, but could also be used to
+     * modify the enabled encodings based on the active MCC/MNC, for example.
+     *
+     * @param tables the new list of enabled locking shift tables
+     */
+    static synchronized void setEnabledLockingShiftTables(int[] tables) {
+        sEnabledLockingShiftTables = tables;
+    }
 
+    /**
+     * Return the array of enabled national language single shift tables for SMS
+     * encoding. This is used for unit testing. The returned array is not a copy, so
+     * the caller should be careful not to modify it.
+     *
+     * @return the list of enabled single shift tables
+     */
+    static synchronized int[] getEnabledSingleShiftTables() {
+        return sEnabledSingleShiftTables;
+    }
+
+    /**
+     * Return the array of enabled national language locking shift tables for SMS
+     * encoding. This is used for unit testing. The returned array is not a copy, so
+     * the caller should be careful not to modify it.
+     *
+     * @return the list of enabled locking shift tables
+     */
+    static synchronized int[] getEnabledLockingShiftTables() {
+        return sEnabledLockingShiftTables;
+    }
+
+    /** Reverse mapping from Unicode characters to indexes into language tables. */
+    private static final SparseIntArray[] sCharsToGsmTables;
+
+    /** Reverse mapping from Unicode characters to indexes into language shift tables. */
+    private static final SparseIntArray[] sCharsToShiftTables;
+
+    /** OEM configured list of enabled national language single shift tables for encoding. */
+    private static int[] sEnabledSingleShiftTables;
+
+    /** OEM configured list of enabled national language locking shift tables for encoding. */
+    private static int[] sEnabledLockingShiftTables;
+
+    /** Highest language code to include in array of single shift counters. */
+    private static int sHighestEnabledSingleShiftCode;
+
+    /**
+     * Septet counter for a specific locking shift table and all of
+     * the single shift tables that it can be paired with.
+     */
+    private static class LanguagePairCount {
+        final int languageCode;
+        final int[] septetCounts;
+        final int[] unencodableCounts;
+        LanguagePairCount(int code) {
+            this.languageCode = code;
+            int maxSingleShiftCode = sHighestEnabledSingleShiftCode;
+            septetCounts = new int[maxSingleShiftCode + 1];
+            unencodableCounts = new int[maxSingleShiftCode + 1];
+            // set counters for disabled single shift tables to -1
+            // (GSM default extension table index 0 is always enabled)
+            for (int i = 1, tableOffset = 0; i <= maxSingleShiftCode; i++) {
+                if (sEnabledSingleShiftTables[tableOffset] == i) {
+                    tableOffset++;
+                } else {
+                    septetCounts[i] = -1;   // disabled
+                }
+            }
+            // exclude Turkish locking + Turkish single shift table and
+            // Portuguese locking + Spanish single shift table (these
+            // combinations will never be optimal for any input).
+            if (code == 1 && maxSingleShiftCode >= 1) {
+                septetCounts[1] = -1;   // Turkish + Turkish
+            } else if (code == 3 && maxSingleShiftCode >= 2) {
+                septetCounts[2] = -1;   // Portuguese + Spanish
+            }
+        }
+    }
+
+    /**
+     * GSM default 7 bit alphabet plus national language locking shift character tables.
+     * Comment lines above strings indicate the lower four bits of the table position.
+     */
+    private static final String[] sLanguageTables = {
+        /* 3GPP TS 23.038 V9.1.1 section 6.2.1 - GSM 7 bit Default Alphabet
+         01.....23.....4.....5.....6.....7.....8.....9.....A.B.....C.....D.E.....F.....0.....1 */
+        "@\u00a3$\u00a5\u00e8\u00e9\u00f9\u00ec\u00f2\u00c7\n\u00d8\u00f8\r\u00c5\u00e5\u0394_"
+            // 2.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....
+            + "\u03a6\u0393\u039b\u03a9\u03a0\u03a8\u03a3\u0398\u039e\uffff\u00c6\u00e6\u00df"
+            // F.....012.34.....56789ABCDEF0123456789ABCDEF0.....123456789ABCDEF0123456789A
+            + "\u00c9 !\"#\u00a4%&'()*+,-./0123456789:;<=>?\u00a1ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+            // B.....C.....D.....E.....F.....0.....123456789ABCDEF0123456789AB.....C.....D.....
+            + "\u00c4\u00d6\u00d1\u00dc\u00a7\u00bfabcdefghijklmnopqrstuvwxyz\u00e4\u00f6\u00f1"
+            // E.....F.....
+            + "\u00fc\u00e0",
+
+        /* A.3.1 Turkish National Language Locking Shift Table
+         01.....23.....4.....5.....6.....7.....8.....9.....A.B.....C.....D.E.....F.....0.....1 */
+        "@\u00a3$\u00a5\u20ac\u00e9\u00f9\u0131\u00f2\u00c7\n\u011e\u011f\r\u00c5\u00e5\u0394_"
+            // 2.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....
+            + "\u03a6\u0393\u039b\u03a9\u03a0\u03a8\u03a3\u0398\u039e\uffff\u015e\u015f\u00df"
+            // F.....012.34.....56789ABCDEF0123456789ABCDEF0.....123456789ABCDEF0123456789A
+            + "\u00c9 !\"#\u00a4%&'()*+,-./0123456789:;<=>?\u0130ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+            // B.....C.....D.....E.....F.....0.....123456789ABCDEF0123456789AB.....C.....D.....
+            + "\u00c4\u00d6\u00d1\u00dc\u00a7\u00e7abcdefghijklmnopqrstuvwxyz\u00e4\u00f6\u00f1"
+            // E.....F.....
+            + "\u00fc\u00e0",
+
+        /* A.3.2 Void (no locking shift table for Spanish) */
+        "",
+
+        /* A.3.3 Portuguese National Language Locking Shift Table
+         01.....23.....4.....5.....6.....7.....8.....9.....A.B.....C.....D.E.....F.....0.....1 */
+        "@\u00a3$\u00a5\u00ea\u00e9\u00fa\u00ed\u00f3\u00e7\n\u00d4\u00f4\r\u00c1\u00e1\u0394_"
+            // 2.....3.....4.....5.....67.8.....9.....AB.....C.....D.....E.....F.....012.34.....
+            + "\u00aa\u00c7\u00c0\u221e^\\\u20ac\u00d3|\uffff\u00c2\u00e2\u00ca\u00c9 !\"#\u00ba"
+            // 56789ABCDEF0123456789ABCDEF0.....123456789ABCDEF0123456789AB.....C.....D.....E.....
+            + "%&'()*+,-./0123456789:;<=>?\u00cdABCDEFGHIJKLMNOPQRSTUVWXYZ\u00c3\u00d5\u00da\u00dc"
+            // F.....0123456789ABCDEF0123456789AB.....C.....DE.....F.....
+            + "\u00a7~abcdefghijklmnopqrstuvwxyz\u00e3\u00f5`\u00fc\u00e0",
+
+        /* A.3.4 Bengali National Language Locking Shift Table
+         0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.B.....CD.EF.....0..... */
+        "\u0981\u0982\u0983\u0985\u0986\u0987\u0988\u0989\u098a\u098b\n\u098c \r \u098f\u0990"
+            // 123.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....F.....
+            + "  \u0993\u0994\u0995\u0996\u0997\u0998\u0999\u099a\uffff\u099b\u099c\u099d\u099e"
+            // 012.....3.....4.....5.....6.....7.....89A.....B.....CD.....EF.....0123456789ABC
+            + " !\u099f\u09a0\u09a1\u09a2\u09a3\u09a4)(\u09a5\u09a6,\u09a7.\u09a80123456789:; "
+            // D.....E.....F0.....1.....2.....3.....4.....56.....789A.....B.....C.....D.....
+            + "\u09aa\u09ab?\u09ac\u09ad\u09ae\u09af\u09b0 \u09b2   \u09b6\u09b7\u09b8\u09b9"
+            // E.....F.....0.....1.....2.....3.....4.....5.....6.....789.....A.....BCD.....E.....
+            + "\u09bc\u09bd\u09be\u09bf\u09c0\u09c1\u09c2\u09c3\u09c4  \u09c7\u09c8  \u09cb\u09cc"
+            // F.....0.....123456789ABCDEF0123456789AB.....C.....D.....E.....F.....
+            + "\u09cd\u09ceabcdefghijklmnopqrstuvwxyz\u09d7\u09dc\u09dd\u09f0\u09f1",
+
+        /* A.3.5 Gujarati National Language Locking Shift Table
+         0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.B.....C.....D.EF.....0.....*/
+        "\u0a81\u0a82\u0a83\u0a85\u0a86\u0a87\u0a88\u0a89\u0a8a\u0a8b\n\u0a8c\u0a8d\r \u0a8f\u0a90"
+            // 1.....23.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....
+            + "\u0a91 \u0a93\u0a94\u0a95\u0a96\u0a97\u0a98\u0a99\u0a9a\uffff\u0a9b\u0a9c\u0a9d"
+            // F.....012.....3.....4.....5.....6.....7.....89A.....B.....CD.....EF.....0123456789AB
+            + "\u0a9e !\u0a9f\u0aa0\u0aa1\u0aa2\u0aa3\u0aa4)(\u0aa5\u0aa6,\u0aa7.\u0aa80123456789:;"
+            // CD.....E.....F0.....1.....2.....3.....4.....56.....7.....89.....A.....B.....C.....
+            + " \u0aaa\u0aab?\u0aac\u0aad\u0aae\u0aaf\u0ab0 \u0ab2\u0ab3 \u0ab5\u0ab6\u0ab7\u0ab8"
+            // D.....E.....F.....0.....1.....2.....3.....4.....5.....6.....7.....89.....A.....
+            + "\u0ab9\u0abc\u0abd\u0abe\u0abf\u0ac0\u0ac1\u0ac2\u0ac3\u0ac4\u0ac5 \u0ac7\u0ac8"
+            // B.....CD.....E.....F.....0.....123456789ABCDEF0123456789AB.....C.....D.....E.....
+            + "\u0ac9 \u0acb\u0acc\u0acd\u0ad0abcdefghijklmnopqrstuvwxyz\u0ae0\u0ae1\u0ae2\u0ae3"
+            // F.....
+            + "\u0af1",
+
+        /* A.3.6 Hindi National Language Locking Shift Table
+         0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.B.....C.....D.E.....F.....*/
+        "\u0901\u0902\u0903\u0905\u0906\u0907\u0908\u0909\u090a\u090b\n\u090c\u090d\r\u090e\u090f"
+            // 0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....
+            + "\u0910\u0911\u0912\u0913\u0914\u0915\u0916\u0917\u0918\u0919\u091a\uffff\u091b\u091c"
+            // E.....F.....012.....3.....4.....5.....6.....7.....89A.....B.....CD.....EF.....012345
+            + "\u091d\u091e !\u091f\u0920\u0921\u0922\u0923\u0924)(\u0925\u0926,\u0927.\u0928012345"
+            // 6789ABC.....D.....E.....F0.....1.....2.....3.....4.....5.....6.....7.....8.....
+            + "6789:;\u0929\u092a\u092b?\u092c\u092d\u092e\u092f\u0930\u0931\u0932\u0933\u0934"
+            // 9.....A.....B.....C.....D.....E.....F.....0.....1.....2.....3.....4.....5.....6.....
+            + "\u0935\u0936\u0937\u0938\u0939\u093c\u093d\u093e\u093f\u0940\u0941\u0942\u0943\u0944"
+            // 7.....8.....9.....A.....B.....C.....D.....E.....F.....0.....123456789ABCDEF012345678
+            + "\u0945\u0946\u0947\u0948\u0949\u094a\u094b\u094c\u094d\u0950abcdefghijklmnopqrstuvwx"
+            // 9AB.....C.....D.....E.....F.....
+            + "yz\u0972\u097b\u097c\u097e\u097f",
+
+        /* A.3.7 Kannada National Language Locking Shift Table
+           NOTE: TS 23.038 V9.1.1 shows code 0x24 as \u0caa, corrected to \u0ca1 (typo)
+         01.....2.....3.....4.....5.....6.....7.....8.....9.....A.B.....CD.E.....F.....0.....1 */
+        " \u0c82\u0c83\u0c85\u0c86\u0c87\u0c88\u0c89\u0c8a\u0c8b\n\u0c8c \r\u0c8e\u0c8f\u0c90 "
+            // 2.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....F.....
+            + "\u0c92\u0c93\u0c94\u0c95\u0c96\u0c97\u0c98\u0c99\u0c9a\uffff\u0c9b\u0c9c\u0c9d\u0c9e"
+            // 012.....3.....4.....5.....6.....7.....89A.....B.....CD.....EF.....0123456789ABC
+            + " !\u0c9f\u0ca0\u0ca1\u0ca2\u0ca3\u0ca4)(\u0ca5\u0ca6,\u0ca7.\u0ca80123456789:; "
+            // D.....E.....F0.....1.....2.....3.....4.....5.....6.....7.....89.....A.....B.....
+            + "\u0caa\u0cab?\u0cac\u0cad\u0cae\u0caf\u0cb0\u0cb1\u0cb2\u0cb3 \u0cb5\u0cb6\u0cb7"
+            // C.....D.....E.....F.....0.....1.....2.....3.....4.....5.....6.....78.....9.....
+            + "\u0cb8\u0cb9\u0cbc\u0cbd\u0cbe\u0cbf\u0cc0\u0cc1\u0cc2\u0cc3\u0cc4 \u0cc6\u0cc7"
+            // A.....BC.....D.....E.....F.....0.....123456789ABCDEF0123456789AB.....C.....D.....
+            + "\u0cc8 \u0cca\u0ccb\u0ccc\u0ccd\u0cd5abcdefghijklmnopqrstuvwxyz\u0cd6\u0ce0\u0ce1"
+            // E.....F.....
+            + "\u0ce2\u0ce3",
+
+        /* A.3.8 Malayalam National Language Locking Shift Table
+         01.....2.....3.....4.....5.....6.....7.....8.....9.....A.B.....CD.E.....F.....0.....1 */
+        " \u0d02\u0d03\u0d05\u0d06\u0d07\u0d08\u0d09\u0d0a\u0d0b\n\u0d0c \r\u0d0e\u0d0f\u0d10 "
+            // 2.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....F.....
+            + "\u0d12\u0d13\u0d14\u0d15\u0d16\u0d17\u0d18\u0d19\u0d1a\uffff\u0d1b\u0d1c\u0d1d\u0d1e"
+            // 012.....3.....4.....5.....6.....7.....89A.....B.....CD.....EF.....0123456789ABC
+            + " !\u0d1f\u0d20\u0d21\u0d22\u0d23\u0d24)(\u0d25\u0d26,\u0d27.\u0d280123456789:; "
+            // D.....E.....F0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.....
+            + "\u0d2a\u0d2b?\u0d2c\u0d2d\u0d2e\u0d2f\u0d30\u0d31\u0d32\u0d33\u0d34\u0d35\u0d36"
+            // B.....C.....D.....EF.....0.....1.....2.....3.....4.....5.....6.....78.....9.....
+            + "\u0d37\u0d38\u0d39 \u0d3d\u0d3e\u0d3f\u0d40\u0d41\u0d42\u0d43\u0d44 \u0d46\u0d47"
+            // A.....BC.....D.....E.....F.....0.....123456789ABCDEF0123456789AB.....C.....D.....
+            + "\u0d48 \u0d4a\u0d4b\u0d4c\u0d4d\u0d57abcdefghijklmnopqrstuvwxyz\u0d60\u0d61\u0d62"
+            // E.....F.....
+            + "\u0d63\u0d79",
+
+        /* A.3.9 Oriya National Language Locking Shift Table
+         0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.B.....CD.EF.....0.....12 */
+        "\u0b01\u0b02\u0b03\u0b05\u0b06\u0b07\u0b08\u0b09\u0b0a\u0b0b\n\u0b0c \r \u0b0f\u0b10  "
+            // 3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....F.....01
+            + "\u0b13\u0b14\u0b15\u0b16\u0b17\u0b18\u0b19\u0b1a\uffff\u0b1b\u0b1c\u0b1d\u0b1e !"
+            // 2.....3.....4.....5.....6.....7.....89A.....B.....CD.....EF.....0123456789ABCD.....
+            + "\u0b1f\u0b20\u0b21\u0b22\u0b23\u0b24)(\u0b25\u0b26,\u0b27.\u0b280123456789:; \u0b2a"
+            // E.....F0.....1.....2.....3.....4.....56.....7.....89.....A.....B.....C.....D.....
+            + "\u0b2b?\u0b2c\u0b2d\u0b2e\u0b2f\u0b30 \u0b32\u0b33 \u0b35\u0b36\u0b37\u0b38\u0b39"
+            // E.....F.....0.....1.....2.....3.....4.....5.....6.....789.....A.....BCD.....E.....
+            + "\u0b3c\u0b3d\u0b3e\u0b3f\u0b40\u0b41\u0b42\u0b43\u0b44  \u0b47\u0b48  \u0b4b\u0b4c"
+            // F.....0.....123456789ABCDEF0123456789AB.....C.....D.....E.....F.....
+            + "\u0b4d\u0b56abcdefghijklmnopqrstuvwxyz\u0b57\u0b60\u0b61\u0b62\u0b63",
+
+        /* A.3.10 Punjabi National Language Locking Shift Table
+         0.....1.....2.....3.....4.....5.....6.....7.....8.....9A.BCD.EF.....0.....123.....4.....*/
+        "\u0a01\u0a02\u0a03\u0a05\u0a06\u0a07\u0a08\u0a09\u0a0a \n  \r \u0a0f\u0a10  \u0a13\u0a14"
+            // 5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....F.....012.....3.....
+            + "\u0a15\u0a16\u0a17\u0a18\u0a19\u0a1a\uffff\u0a1b\u0a1c\u0a1d\u0a1e !\u0a1f\u0a20"
+            // 4.....5.....6.....7.....89A.....B.....CD.....EF.....0123456789ABCD.....E.....F0.....
+            + "\u0a21\u0a22\u0a23\u0a24)(\u0a25\u0a26,\u0a27.\u0a280123456789:; \u0a2a\u0a2b?\u0a2c"
+            // 1.....2.....3.....4.....56.....7.....89.....A.....BC.....D.....E.....F0.....1.....
+            + "\u0a2d\u0a2e\u0a2f\u0a30 \u0a32\u0a33 \u0a35\u0a36 \u0a38\u0a39\u0a3c \u0a3e\u0a3f"
+            // 2.....3.....4.....56789.....A.....BCD.....E.....F.....0.....123456789ABCDEF012345678
+            + "\u0a40\u0a41\u0a42    \u0a47\u0a48  \u0a4b\u0a4c\u0a4d\u0a51abcdefghijklmnopqrstuvwx"
+            // 9AB.....C.....D.....E.....F.....
+            + "yz\u0a70\u0a71\u0a72\u0a73\u0a74",
+
+        /* A.3.11 Tamil National Language Locking Shift Table
+         01.....2.....3.....4.....5.....6.....7.....8.....9A.BCD.E.....F.....0.....12.....3..... */
+        " \u0b82\u0b83\u0b85\u0b86\u0b87\u0b88\u0b89\u0b8a \n  \r\u0b8e\u0b8f\u0b90 \u0b92\u0b93"
+            // 4.....5.....6789.....A.....B.....CD.....EF.....012.....3456.....7.....89ABCDEF.....
+            + "\u0b94\u0b95   \u0b99\u0b9a\uffff \u0b9c \u0b9e !\u0b9f   \u0ba3\u0ba4)(  , .\u0ba8"
+            // 0123456789ABC.....D.....EF012.....3.....4.....5.....6.....7.....8.....9.....A.....
+            + "0123456789:;\u0ba9\u0baa ?  \u0bae\u0baf\u0bb0\u0bb1\u0bb2\u0bb3\u0bb4\u0bb5\u0bb6"
+            // B.....C.....D.....EF0.....1.....2.....3.....4.....5678.....9.....A.....BC.....D.....
+            + "\u0bb7\u0bb8\u0bb9  \u0bbe\u0bbf\u0bc0\u0bc1\u0bc2   \u0bc6\u0bc7\u0bc8 \u0bca\u0bcb"
+            // E.....F.....0.....123456789ABCDEF0123456789AB.....C.....D.....E.....F.....
+            + "\u0bcc\u0bcd\u0bd0abcdefghijklmnopqrstuvwxyz\u0bd7\u0bf0\u0bf1\u0bf2\u0bf9",
+
+        /* A.3.12 Telugu National Language Locking Shift Table
+         0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.B.....CD.E.....F.....0.....*/
+        "\u0c01\u0c02\u0c03\u0c05\u0c06\u0c07\u0c08\u0c09\u0c0a\u0c0b\n\u0c0c \r\u0c0e\u0c0f\u0c10"
+            // 12.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....
+            + " \u0c12\u0c13\u0c14\u0c15\u0c16\u0c17\u0c18\u0c19\u0c1a\uffff\u0c1b\u0c1c\u0c1d"
+            // F.....012.....3.....4.....5.....6.....7.....89A.....B.....CD.....EF.....0123456789AB
+            + "\u0c1e !\u0c1f\u0c20\u0c21\u0c22\u0c23\u0c24)(\u0c25\u0c26,\u0c27.\u0c280123456789:;"
+            // CD.....E.....F0.....1.....2.....3.....4.....5.....6.....7.....89.....A.....B.....
+            + " \u0c2a\u0c2b?\u0c2c\u0c2d\u0c2e\u0c2f\u0c30\u0c31\u0c32\u0c33 \u0c35\u0c36\u0c37"
+            // C.....D.....EF.....0.....1.....2.....3.....4.....5.....6.....78.....9.....A.....B
+            + "\u0c38\u0c39 \u0c3d\u0c3e\u0c3f\u0c40\u0c41\u0c42\u0c43\u0c44 \u0c46\u0c47\u0c48 "
+            // C.....D.....E.....F.....0.....123456789ABCDEF0123456789AB.....C.....D.....E.....
+            + "\u0c4a\u0c4b\u0c4c\u0c4d\u0c55abcdefghijklmnopqrstuvwxyz\u0c56\u0c60\u0c61\u0c62"
+            // F.....
+            + "\u0c63",
+
+        /* A.3.13 Urdu National Language Locking Shift Table
+         0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.B.....C.....D.E.....F.....*/
+        "\u0627\u0622\u0628\u067b\u0680\u067e\u06a6\u062a\u06c2\u067f\n\u0679\u067d\r\u067a\u067c"
+            // 0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....
+            + "\u062b\u062c\u0681\u0684\u0683\u0685\u0686\u0687\u062d\u062e\u062f\uffff\u068c\u0688"
+            // E.....F.....012.....3.....4.....5.....6.....7.....89A.....B.....CD.....EF.....012345
+            + "\u0689\u068a !\u068f\u068d\u0630\u0631\u0691\u0693)(\u0699\u0632,\u0696.\u0698012345"
+            // 6789ABC.....D.....E.....F0.....1.....2.....3.....4.....5.....6.....7.....8.....
+            + "6789:;\u069a\u0633\u0634?\u0635\u0636\u0637\u0638\u0639\u0641\u0642\u06a9\u06aa"
+            // 9.....A.....B.....C.....D.....E.....F.....0.....1.....2.....3.....4.....5.....6.....
+            + "\u06ab\u06af\u06b3\u06b1\u0644\u0645\u0646\u06ba\u06bb\u06bc\u0648\u06c4\u06d5\u06c1"
+            // 7.....8.....9.....A.....B.....C.....D.....E.....F.....0.....123456789ABCDEF012345678
+            + "\u06be\u0621\u06cc\u06d0\u06d2\u064d\u0650\u064f\u0657\u0654abcdefghijklmnopqrstuvwx"
+            // 9AB.....C.....D.....E.....F.....
+            + "yz\u0655\u0651\u0653\u0656\u0670"
+    };
+
+    /**
+     * GSM default extension table plus national language single shift character tables.
+     */
+    private static final String[] sLanguageShiftTables = new String[]{
+        /* 6.2.1.1 GSM 7 bit Default Alphabet Extension Table
+         0123456789A.....BCDEF0123456789ABCDEF0123456789ABCDEF.0123456789ABCDEF0123456789ABCDEF */
+        "          \u000c         ^                   {}     \\            [~] |               "
+            // 0123456789ABCDEF012345.....6789ABCDEF0123456789ABCDEF
+            + "                     \u20ac                          ",
+
+        /* A.2.1 Turkish National Language Single Shift Table
+         0123456789A.....BCDEF0123456789ABCDEF0123456789ABCDEF.0123456789ABCDEF01234567.....8 */
+        "          \u000c         ^                   {}     \\            [~] |      \u011e "
+            // 9.....ABCDEF0123.....456789ABCDEF0123.....45.....67.....89.....ABCDEF0123.....
+            + "\u0130         \u015e               \u00e7 \u20ac \u011f \u0131         \u015f"
+            // 456789ABCDEF
+            + "            ",
+
+        /* A.2.2 Spanish National Language Single Shift Table
+         0123456789.....A.....BCDEF0123456789ABCDEF0123456789ABCDEF.0123456789ABCDEF01.....23 */
+        "         \u00e7\u000c         ^                   {}     \\            [~] |\u00c1  "
+            // 456789.....ABCDEF.....012345.....6789ABCDEF01.....2345.....6789.....ABCDEF.....012
+            + "     \u00cd     \u00d3     \u00da           \u00e1   \u20ac   \u00ed     \u00f3   "
+            // 345.....6789ABCDEF
+            + "  \u00fa          ",
+
+        /* A.2.3 Portuguese National Language Single Shift Table
+         012345.....6789.....A.....B.....C.....DE.....F.....012.....3.....45.....6.....7.....8....*/
+        "     \u00ea   \u00e7\u000c\u00d4\u00f4 \u00c1\u00e1  \u03a6\u0393^\u03a9\u03a0\u03a8\u03a3"
+            // 9.....ABCDEF.....0123456789ABCDEF.0123456789ABCDEF01.....23456789.....ABCDE
+            + "\u0398     \u00ca        {}     \\            [~] |\u00c0       \u00cd     "
+            // F.....012345.....6789AB.....C.....DEF01.....2345.....6789.....ABCDEF.....01234
+            + "\u00d3     \u00da     \u00c3\u00d5    \u00c2   \u20ac   \u00ed     \u00f3     "
+            // 5.....6789AB.....C.....DEF.....
+            + "\u00fa     \u00e3\u00f5  \u00e2",
+
+        /* A.2.4 Bengali National Language Single Shift Table
+         01.....23.....4.....5.6.....789A.....BCDEF0123.....45.....6789.....A.....BC.....D..... */
+        "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+ -/<=>\u00a1^\u00a1_#*\u09e6\u09e7 \u09e8\u09e9"
+            // E.....F.....0.....1.....2.....3.....4.....5.....6.....7.....89A.....B.....C.....
+            + "\u09ea\u09eb\u09ec\u09ed\u09ee\u09ef\u09df\u09e0\u09e1\u09e2{}\u09e3\u09f2\u09f3"
+            // D.....E.....F.0.....1.....2.....3.....4.....56789ABCDEF0123456789ABCDEF
+            + "\u09f4\u09f5\\\u09f6\u09f7\u09f8\u09f9\u09fa       [~] |ABCDEFGHIJKLMNO"
+            // 0123456789ABCDEF012345.....6789ABCDEF0123456789ABCDEF
+            + "PQRSTUVWXYZ          \u20ac                          ",
+
+        /* A.2.5 Gujarati National Language Single Shift Table
+         01.....23.....4.....5.6.....789A.....BCDEF0123.....45.....6789.....A.....BC.....D..... */
+        "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+ -/<=>\u00a1^\u00a1_#*\u0964\u0965 \u0ae6\u0ae7"
+            // E.....F.....0.....1.....2.....3.....4.....5.....6789ABCDEF.0123456789ABCDEF
+            + "\u0ae8\u0ae9\u0aea\u0aeb\u0aec\u0aed\u0aee\u0aef  {}     \\            [~] "
+            // 0123456789ABCDEF0123456789ABCDEF012345.....6789ABCDEF0123456789ABCDEF
+            + "|ABCDEFGHIJKLMNOPQRSTUVWXYZ          \u20ac                          ",
+
+        /* A.2.6 Hindi National Language Single Shift Table
+         01.....23.....4.....5.6.....789A.....BCDEF0123.....45.....6789.....A.....BC.....D..... */
+        "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+ -/<=>\u00a1^\u00a1_#*\u0964\u0965 \u0966\u0967"
+            // E.....F.....0.....1.....2.....3.....4.....5.....6.....7.....89A.....B.....C.....
+            + "\u0968\u0969\u096a\u096b\u096c\u096d\u096e\u096f\u0951\u0952{}\u0953\u0954\u0958"
+            // D.....E.....F.0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.....
+            + "\u0959\u095a\\\u095b\u095c\u095d\u095e\u095f\u0960\u0961\u0962\u0963\u0970\u0971"
+            // BCDEF0123456789ABCDEF0123456789ABCDEF012345.....6789ABCDEF0123456789ABCDEF
+            + " [~] |ABCDEFGHIJKLMNOPQRSTUVWXYZ          \u20ac                          ",
+
+        /* A.2.7 Kannada National Language Single Shift Table
+         01.....23.....4.....5.6.....789A.....BCDEF0123.....45.....6789.....A.....BC.....D..... */
+        "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+ -/<=>\u00a1^\u00a1_#*\u0964\u0965 \u0ce6\u0ce7"
+            // E.....F.....0.....1.....2.....3.....4.....5.....6.....7.....89A.....BCDEF.01234567
+            + "\u0ce8\u0ce9\u0cea\u0ceb\u0cec\u0ced\u0cee\u0cef\u0cde\u0cf1{}\u0cf2    \\        "
+            // 89ABCDEF0123456789ABCDEF0123456789ABCDEF012345.....6789ABCDEF0123456789ABCDEF
+            + "    [~] |ABCDEFGHIJKLMNOPQRSTUVWXYZ          \u20ac                          ",
+
+        /* A.2.8 Malayalam National Language Single Shift Table
+         01.....23.....4.....5.6.....789A.....BCDEF0123.....45.....6789.....A.....BC.....D..... */
+        "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+ -/<=>\u00a1^\u00a1_#*\u0964\u0965 \u0d66\u0d67"
+            // E.....F.....0.....1.....2.....3.....4.....5.....6.....7.....89A.....B.....C.....
+            + "\u0d68\u0d69\u0d6a\u0d6b\u0d6c\u0d6d\u0d6e\u0d6f\u0d70\u0d71{}\u0d72\u0d73\u0d74"
+            // D.....E.....F.0.....1.....2.....3.....4.....56789ABCDEF0123456789ABCDEF0123456789A
+            + "\u0d75\u0d7a\\\u0d7b\u0d7c\u0d7d\u0d7e\u0d7f       [~] |ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+            // BCDEF012345.....6789ABCDEF0123456789ABCDEF
+            + "          \u20ac                          ",
+
+        /* A.2.9 Oriya National Language Single Shift Table
+         01.....23.....4.....5.6.....789A.....BCDEF0123.....45.....6789.....A.....BC.....D..... */
+        "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+ -/<=>\u00a1^\u00a1_#*\u0964\u0965 \u0b66\u0b67"
+            // E.....F.....0.....1.....2.....3.....4.....5.....6.....7.....89A.....B.....C.....DE
+            + "\u0b68\u0b69\u0b6a\u0b6b\u0b6c\u0b6d\u0b6e\u0b6f\u0b5c\u0b5d{}\u0b5f\u0b70\u0b71  "
+            // F.0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF012345.....6789ABCDEF0123456789A
+            + "\\            [~] |ABCDEFGHIJKLMNOPQRSTUVWXYZ          \u20ac                     "
+            // BCDEF
+            + "     ",
+
+        /* A.2.10 Punjabi National Language Single Shift Table
+         01.....23.....4.....5.6.....789A.....BCDEF0123.....45.....6789.....A.....BC.....D..... */
+        "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+ -/<=>\u00a1^\u00a1_#*\u0964\u0965 \u0a66\u0a67"
+            // E.....F.....0.....1.....2.....3.....4.....5.....6.....7.....89A.....B.....C.....
+            + "\u0a68\u0a69\u0a6a\u0a6b\u0a6c\u0a6d\u0a6e\u0a6f\u0a59\u0a5a{}\u0a5b\u0a5c\u0a5e"
+            // D.....EF.0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF012345.....6789ABCDEF01
+            + "\u0a75 \\            [~] |ABCDEFGHIJKLMNOPQRSTUVWXYZ          \u20ac            "
+            // 23456789ABCDEF
+            + "              ",
+
+        /* A.2.11 Tamil National Language Single Shift Table
+           NOTE: TS 23.038 V9.1.1 shows code 0x24 as \u0bef, corrected to \u0bee (typo)
+         01.....23.....4.....5.6.....789A.....BCDEF0123.....45.....6789.....A.....BC.....D..... */
+        "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+ -/<=>\u00a1^\u00a1_#*\u0964\u0965 \u0be6\u0be7"
+            // E.....F.....0.....1.....2.....3.....4.....5.....6.....7.....89A.....B.....C.....
+            + "\u0be8\u0be9\u0bea\u0beb\u0bec\u0bed\u0bee\u0bef\u0bf3\u0bf4{}\u0bf5\u0bf6\u0bf7"
+            // D.....E.....F.0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF012345.....6789ABC
+            + "\u0bf8\u0bfa\\            [~] |ABCDEFGHIJKLMNOPQRSTUVWXYZ          \u20ac       "
+            // DEF0123456789ABCDEF
+            + "                   ",
+
+        /* A.2.12 Telugu National Language Single Shift Table
+           NOTE: TS 23.038 V9.1.1 shows code 0x22-0x23 as \u06cc\u06cd, corrected to \u0c6c\u0c6d
+         01.....23.....4.....5.6.....789A.....BCDEF0123.....45.....6789ABC.....D.....E.....F..... */
+        "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+ -/<=>\u00a1^\u00a1_#*   \u0c66\u0c67\u0c68\u0c69"
+            // 0.....1.....2.....3.....4.....5.....6.....7.....89A.....B.....C.....D.....E.....F.
+            + "\u0c6a\u0c6b\u0c6c\u0c6d\u0c6e\u0c6f\u0c58\u0c59{}\u0c78\u0c79\u0c7a\u0c7b\u0c7c\\"
+            // 0.....1.....2.....3456789ABCDEF0123456789ABCDEF0123456789ABCDEF012345.....6789ABCD
+            + "\u0c7d\u0c7e\u0c7f         [~] |ABCDEFGHIJKLMNOPQRSTUVWXYZ          \u20ac        "
+            // EF0123456789ABCDEF
+            + "                  ",
+
+        /* A.2.13 Urdu National Language Single Shift Table
+         01.....23.....4.....5.6.....789A.....BCDEF0123.....45.....6789.....A.....BC.....D..... */
+        "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+ -/<=>\u00a1^\u00a1_#*\u0600\u0601 \u06f0\u06f1"
+            // E.....F.....0.....1.....2.....3.....4.....5.....6.....7.....89A.....B.....C.....
+            + "\u06f2\u06f3\u06f4\u06f5\u06f6\u06f7\u06f8\u06f9\u060c\u060d{}\u060e\u060f\u0610"
+            // D.....E.....F.0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.....
+            + "\u0611\u0612\\\u0613\u0614\u061b\u061f\u0640\u0652\u0658\u066b\u066c\u0672\u0673"
+            // B.....CDEF.....0123456789ABCDEF0123456789ABCDEF012345.....6789ABCDEF0123456789ABCDEF
+            + "\u06cd[~]\u06d4|ABCDEFGHIJKLMNOPQRSTUVWXYZ          \u20ac                          "
+    };
+
+    static {
+        Resources r = Resources.getSystem();
+        // See comments in frameworks/base/core/res/res/values/config.xml for allowed values
+        sEnabledSingleShiftTables = r.getIntArray(R.array.config_sms_enabled_single_shift_tables);
+        sEnabledLockingShiftTables = r.getIntArray(R.array.config_sms_enabled_locking_shift_tables);
+        int numTables = sLanguageTables.length;
+        int numShiftTables = sLanguageShiftTables.length;
+        if (numTables != numShiftTables) {
+            Log.e(TAG, "Error: language tables array length " + numTables +
+                    " != shift tables array length " + numShiftTables);
+        }
+
+        if (sEnabledSingleShiftTables.length > 0) {
+            sHighestEnabledSingleShiftCode =
+                    sEnabledSingleShiftTables[sEnabledSingleShiftTables.length-1];
+        } else {
+            sHighestEnabledSingleShiftCode = 0;
+        }
+
+        sCharsToGsmTables = new SparseIntArray[numTables];
+        for (int i = 0; i < numTables; i++) {
+            String table = sLanguageTables[i];
+
+            int tableLen = table.length();
+            if (tableLen != 0 && tableLen != 128) {
+                Log.e(TAG, "Error: language tables index " + i +
+                        " length " + tableLen + " (expected 128 or 0)");
+            }
+
+            SparseIntArray charToGsmTable = new SparseIntArray(tableLen);
+            sCharsToGsmTables[i] = charToGsmTable;
+            for (int j = 0; j < tableLen; j++) {
+                char c = table.charAt(j);
+                charToGsmTable.put(c, j);
+            }
+        }
+
+        sCharsToShiftTables = new SparseIntArray[numTables];
+        for (int i = 0; i < numShiftTables; i++) {
+            String shiftTable = sLanguageShiftTables[i];
+
+            int shiftTableLen = shiftTable.length();
+            if (shiftTableLen != 0 && shiftTableLen != 128) {
+                Log.e(TAG, "Error: language shift tables index " + i +
+                        " length " + shiftTableLen + " (expected 128 or 0)");
+            }
+
+            SparseIntArray charToShiftTable = new SparseIntArray(shiftTableLen);
+            sCharsToShiftTables[i] = charToShiftTable;
+            for (int j = 0; j < shiftTableLen; j++) {
+                char c = shiftTable.charAt(j);
+                if (c != ' ') {
+                    charToShiftTable.put(c, j);
+                }
+            }
+        }
+    }
 }
diff --git a/telephony/java/com/android/internal/telephony/IccPhoneBookInterfaceManager.java b/telephony/java/com/android/internal/telephony/IccPhoneBookInterfaceManager.java
index 2f22d74..45562ca 100644
--- a/telephony/java/com/android/internal/telephony/IccPhoneBookInterfaceManager.java
+++ b/telephony/java/com/android/internal/telephony/IccPhoneBookInterfaceManager.java
@@ -24,6 +24,7 @@
 import android.os.ServiceManager;
 
 import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
 
 /**
  * SimPhoneBookInterfaceManager to provide an inter-process communication to
@@ -63,14 +64,14 @@
                                     " total " + recordSize[1] +
                                     " #record " + recordSize[2]);
                         }
-                        mLock.notifyAll();
+                        notifyPending(ar);
                     }
                     break;
                 case EVENT_UPDATE_DONE:
                     ar = (AsyncResult) msg.obj;
                     synchronized (mLock) {
                         success = (ar.exception == null);
-                        mLock.notifyAll();
+                        notifyPending(ar);
                     }
                     break;
                 case EVENT_LOAD_DONE:
@@ -84,11 +85,20 @@
                                 records.clear();
                             }
                         }
-                        mLock.notifyAll();
+                        notifyPending(ar);
                     }
                     break;
             }
         }
+
+        private void notifyPending(AsyncResult ar) {
+            if (ar.userObj == null) {
+                return;
+            }
+            AtomicBoolean status = (AtomicBoolean) ar.userObj;
+            status.set(true);
+            mLock.notifyAll();
+        }
     };
 
     public IccPhoneBookInterfaceManager(PhoneBase phone) {
@@ -150,15 +160,12 @@
         synchronized(mLock) {
             checkThread();
             success = false;
-            Message response = mBaseHandler.obtainMessage(EVENT_UPDATE_DONE);
+            AtomicBoolean status = new AtomicBoolean(false);
+            Message response = mBaseHandler.obtainMessage(EVENT_UPDATE_DONE, status);
             AdnRecord oldAdn = new AdnRecord(oldTag, oldPhoneNumber);
             AdnRecord newAdn = new AdnRecord(newTag, newPhoneNumber);
             adnCache.updateAdnBySearch(efid, oldAdn, newAdn, pin2, response);
-            try {
-                mLock.wait();
-            } catch (InterruptedException e) {
-                logd("interrupted while trying to update by search");
-            }
+            waitForResult(status);
         }
         return success;
     }
@@ -197,14 +204,11 @@
         synchronized(mLock) {
             checkThread();
             success = false;
-            Message response = mBaseHandler.obtainMessage(EVENT_UPDATE_DONE);
+            AtomicBoolean status = new AtomicBoolean(false);
+            Message response = mBaseHandler.obtainMessage(EVENT_UPDATE_DONE, status);
             AdnRecord newAdn = new AdnRecord(newTag, newPhoneNumber);
             adnCache.updateAdnByIndex(efid, newAdn, index, pin2, response);
-            try {
-                mLock.wait();
-            } catch (InterruptedException e) {
-                logd("interrupted while trying to update by index");
-            }
+            waitForResult(status);
         }
         return success;
     }
@@ -243,15 +247,12 @@
 
         synchronized(mLock) {
             checkThread();
-            Message response = mBaseHandler.obtainMessage(EVENT_LOAD_DONE);
+            AtomicBoolean status = new AtomicBoolean(false);
+            Message response = mBaseHandler.obtainMessage(EVENT_LOAD_DONE, status);
             adnCache.requestLoadAllAdnLike(efid, adnCache.extensionEfForEf(efid), response);
-            try {
-                mLock.wait();
-            } catch (InterruptedException e) {
-                logd("interrupted while trying to load from the SIM");
-            }
+            waitForResult(status);
         }
-            return records;
+        return records;
     }
 
     protected void checkThread() {
@@ -265,6 +266,16 @@
         }
     }
 
+    protected void waitForResult(AtomicBoolean status) {
+        while (!status.get()) {
+            try {
+                mLock.wait();
+            } catch (InterruptedException e) {
+                logd("interrupted while trying to update by search");
+            }
+        }
+    }
+
     private int updateEfForIccType(int efid) {
         // Check if we are trying to read ADN records
         if (efid == IccConstants.EF_ADN) {
diff --git a/telephony/java/com/android/internal/telephony/IccUtils.java b/telephony/java/com/android/internal/telephony/IccUtils.java
index df579b0..c3b0ffc 100644
--- a/telephony/java/com/android/internal/telephony/IccUtils.java
+++ b/telephony/java/com/android/internal/telephony/IccUtils.java
@@ -416,7 +416,6 @@
         int colorNumber = data[valueIndex++] & 0xFF;
         int clutOffset = ((data[valueIndex++] & 0xFF) << 8)
                 | (data[valueIndex++] & 0xFF);
-        length = length - 6;
 
         int[] colorIndexArray = getCLUT(data, clutOffset, colorNumber);
         if (true == transparency) {
diff --git a/telephony/java/com/android/internal/telephony/SmsHeader.java b/telephony/java/com/android/internal/telephony/SmsHeader.java
index 7a65162..9492e0e 100644
--- a/telephony/java/com/android/internal/telephony/SmsHeader.java
+++ b/telephony/java/com/android/internal/telephony/SmsHeader.java
@@ -66,6 +66,8 @@
     public static final int ELT_ID_HYPERLINK_FORMAT_ELEMENT           = 0x21;
     public static final int ELT_ID_REPLY_ADDRESS_ELEMENT              = 0x22;
     public static final int ELT_ID_ENHANCED_VOICE_MAIL_INFORMATION    = 0x23;
+    public static final int ELT_ID_NATIONAL_LANGUAGE_SINGLE_SHIFT     = 0x24;
+    public static final int ELT_ID_NATIONAL_LANGUAGE_LOCKING_SHIFT    = 0x25;
 
     public static final int PORT_WAP_PUSH = 2948;
     public static final int PORT_WAP_WSP  = 9200;
@@ -96,6 +98,12 @@
     public ConcatRef concatRef;
     public ArrayList<MiscElt> miscEltList = new ArrayList<MiscElt>();
 
+    /** 7 bit national language locking shift table, or 0 for GSM default 7 bit alphabet. */
+    public int languageTable;
+
+    /** 7 bit national language single shift table, or 0 for GSM default 7 bit extension table. */
+    public int languageShiftTable;
+
     public SmsHeader() {}
 
     /**
@@ -157,6 +165,12 @@
                 portAddrs.areEightBits = false;
                 smsHeader.portAddrs = portAddrs;
                 break;
+            case ELT_ID_NATIONAL_LANGUAGE_SINGLE_SHIFT:
+                smsHeader.languageShiftTable = inStream.read();
+                break;
+            case ELT_ID_NATIONAL_LANGUAGE_LOCKING_SHIFT:
+                smsHeader.languageTable = inStream.read();
+                break;
             default:
                 MiscElt miscElt = new MiscElt();
                 miscElt.id = id;
@@ -212,6 +226,16 @@
                 outStream.write(portAddrs.origPort & 0x00FF);
             }
         }
+        if (smsHeader.languageShiftTable != 0) {
+            outStream.write(ELT_ID_NATIONAL_LANGUAGE_SINGLE_SHIFT);
+            outStream.write(1);
+            outStream.write(smsHeader.languageShiftTable);
+        }
+        if (smsHeader.languageTable != 0) {
+            outStream.write(ELT_ID_NATIONAL_LANGUAGE_LOCKING_SHIFT);
+            outStream.write(1);
+            outStream.write(smsHeader.languageTable);
+        }
         for (MiscElt miscElt : smsHeader.miscEltList) {
             outStream.write(miscElt.id);
             outStream.write(miscElt.data.length);
@@ -243,6 +267,12 @@
             builder.append(", areEightBits=" + portAddrs.areEightBits);
             builder.append(" }");
         }
+        if (languageShiftTable != 0) {
+            builder.append(", languageShiftTable=" + languageShiftTable);
+        }
+        if (languageTable != 0) {
+            builder.append(", languageTable=" + languageTable);
+        }
         for (MiscElt miscElt : miscEltList) {
             builder.append(", MiscElt ");
             builder.append("{ id=" + miscElt.id);
diff --git a/telephony/java/com/android/internal/telephony/SmsMessageBase.java b/telephony/java/com/android/internal/telephony/SmsMessageBase.java
index cbd8606..fcd038c 100644
--- a/telephony/java/com/android/internal/telephony/SmsMessageBase.java
+++ b/telephony/java/com/android/internal/telephony/SmsMessageBase.java
@@ -117,6 +117,16 @@
          */
         public int codeUnitSize;
 
+        /**
+         * The GSM national language table to use, or 0 for the default 7-bit alphabet.
+         */
+        public int languageTable;
+
+        /**
+         * The GSM national language shift table to use, or 0 for the default 7-bit extension table.
+         */
+        public int languageShiftTable;
+
         @Override
         public String toString() {
             return "TextEncodingDetails " +
@@ -124,6 +134,8 @@
                     ", codeUnitCount=" + codeUnitCount +
                     ", codeUnitsRemaining=" + codeUnitsRemaining +
                     ", codeUnitSize=" + codeUnitSize +
+                    ", languageTable=" + languageTable +
+                    ", languageShiftTable=" + languageShiftTable +
                     " }";
         }
     }
diff --git a/telephony/java/com/android/internal/telephony/cat/ResponseData.java b/telephony/java/com/android/internal/telephony/cat/ResponseData.java
index 4846a3e..55a2b63 100644
--- a/telephony/java/com/android/internal/telephony/cat/ResponseData.java
+++ b/telephony/java/com/android/internal/telephony/cat/ResponseData.java
@@ -113,7 +113,7 @@
                     int size = mInData.length();
 
                     byte[] tempData = GsmAlphabet
-                            .stringToGsm7BitPacked(mInData);
+                            .stringToGsm7BitPacked(mInData, 0, 0);
                     data = new byte[size];
                     // Since stringToGsm7BitPacked() set byte 0 in the
                     // returned byte array to the count of septets used...
diff --git a/telephony/java/com/android/internal/telephony/cdma/RuimPhoneBookInterfaceManager.java b/telephony/java/com/android/internal/telephony/cdma/RuimPhoneBookInterfaceManager.java
index ce33066..04ee2dd8 100644
--- a/telephony/java/com/android/internal/telephony/cdma/RuimPhoneBookInterfaceManager.java
+++ b/telephony/java/com/android/internal/telephony/cdma/RuimPhoneBookInterfaceManager.java
@@ -16,6 +16,8 @@
 
 package com.android.internal.telephony.cdma;
 
+import java.util.concurrent.atomic.AtomicBoolean;
+
 import android.os.Message;
 import android.util.Log;
 
@@ -56,14 +58,11 @@
             recordSize = new int[3];
 
             //Using mBaseHandler, no difference in EVENT_GET_SIZE_DONE handling
-            Message response = mBaseHandler.obtainMessage(EVENT_GET_SIZE_DONE);
+            AtomicBoolean status = new AtomicBoolean(false);
+            Message response = mBaseHandler.obtainMessage(EVENT_GET_SIZE_DONE, status);
 
             phone.getIccFileHandler().getEFLinearRecordSize(efid, response);
-            try {
-                mLock.wait();
-            } catch (InterruptedException e) {
-                logd("interrupted while trying to load from the RUIM");
-            }
+            waitForResult(status);
         }
 
         return recordSize;
diff --git a/telephony/java/com/android/internal/telephony/cdma/RuimRecords.java b/telephony/java/com/android/internal/telephony/cdma/RuimRecords.java
old mode 100644
new mode 100755
index 719eff3..ee63ede
--- a/telephony/java/com/android/internal/telephony/cdma/RuimRecords.java
+++ b/telephony/java/com/android/internal/telephony/cdma/RuimRecords.java
@@ -16,10 +16,13 @@
 
 package com.android.internal.telephony.cdma;
 
+import static com.android.internal.telephony.TelephonyProperties.PROPERTY_ICC_OPERATOR_ISO_COUNTRY;
+import static com.android.internal.telephony.TelephonyProperties.PROPERTY_ICC_OPERATOR_NUMERIC;
 import android.os.AsyncResult;
 import android.os.Handler;
 import android.os.Message;
 import android.os.Registrant;
+import android.os.SystemProperties;
 import android.util.Log;
 
 import com.android.internal.telephony.AdnRecord;
@@ -59,6 +62,7 @@
 
     private static final int EVENT_RUIM_READY = 1;
     private static final int EVENT_RADIO_OFF_OR_NOT_AVAILABLE = 2;
+    private static final int EVENT_GET_IMSI_DONE = 3;
     private static final int EVENT_GET_DEVICE_IDENTITY_DONE = 4;
     private static final int EVENT_GET_ICCID_DONE = 5;
     private static final int EVENT_GET_CDMA_SUBSCRIPTION_DONE = 10;
@@ -115,6 +119,9 @@
 
         adnCache.reset();
 
+        phone.setSystemProperty(PROPERTY_ICC_OPERATOR_NUMERIC, null);
+        phone.setSystemProperty(PROPERTY_ICC_OPERATOR_ISO_COUNTRY, null);
+
         // recordsRequested is set to false indicating that the SIM
         // read requests made so far are not valid. This is set to
         // true only when fresh set of read requests are made.
@@ -202,6 +209,33 @@
             break;
 
             /* IO events */
+            case EVENT_GET_IMSI_DONE:
+                isRecordLoadResponse = true;
+
+                ar = (AsyncResult)msg.obj;
+                if (ar.exception != null) {
+                    Log.e(LOG_TAG, "Exception querying IMSI, Exception:" + ar.exception);
+                    break;
+                }
+
+                mImsi = (String) ar.result;
+
+                // IMSI (MCC+MNC+MSIN) is at least 6 digits, but not more
+                // than 15 (and usually 15).
+                if (mImsi != null && (mImsi.length() < 6 || mImsi.length() > 15)) {
+                    Log.e(LOG_TAG, "invalid IMSI " + mImsi);
+                    mImsi = null;
+                }
+
+                Log.d(LOG_TAG, "IMSI: " + mImsi.substring(0, 6) + "xxxxxxxxx");
+
+                String operatorNumeric = getRUIMOperatorNumeric();
+                if (operatorNumeric != null) {
+                    if(operatorNumeric.length() <= 6){
+                        MccTable.updateMccMncConfiguration(phone, operatorNumeric);
+                    }
+                }
+            break;
 
             case EVENT_GET_CDMA_SUBSCRIPTION_DONE:
                 ar = (AsyncResult)msg.obj;
@@ -292,6 +326,13 @@
 
         // Further records that can be inserted are Operator/OEM dependent
 
+        String operator = getRUIMOperatorNumeric();
+        SystemProperties.set(PROPERTY_ICC_OPERATOR_NUMERIC, operator);
+
+        if (mImsi != null) {
+            SystemProperties.set(PROPERTY_ICC_OPERATOR_ISO_COUNTRY,
+                    MccTable.countryCodeForMcc(Integer.parseInt(mImsi.substring(0,3))));
+        }
         recordsLoadedRegistrants.notifyRegistrants(
             new AsyncResult(null, null, null));
         phone.mIccCard.broadcastIccStateChangedIntent(
@@ -318,6 +359,9 @@
 
         Log.v(LOG_TAG, "RuimRecords:fetchRuimRecords " + recordsToLoad);
 
+        phone.mCM.getIMSI(obtainMessage(EVENT_GET_IMSI_DONE));
+        recordsToLoad++;
+
         phone.getIccFileHandler().loadEFTransparent(EF_ICCID,
                 obtainMessage(EVENT_GET_ICCID_DONE));
         recordsToLoad++;
diff --git a/telephony/java/com/android/internal/telephony/cdma/SmsMessage.java b/telephony/java/com/android/internal/telephony/cdma/SmsMessage.java
index 4911644..fdd0c9f 100644
--- a/telephony/java/com/android/internal/telephony/cdma/SmsMessage.java
+++ b/telephony/java/com/android/internal/telephony/cdma/SmsMessage.java
@@ -18,6 +18,7 @@
 
 import android.os.Parcel;
 import android.os.SystemProperties;
+import android.telephony.PhoneNumberUtils;
 import android.util.Config;
 import android.util.Log;
 import com.android.internal.telephony.IccUtils;
@@ -807,7 +808,12 @@
          * mechanism, and avoid null pointer exceptions.
          */
 
-        CdmaSmsAddress destAddr = CdmaSmsAddress.parse(destAddrStr);
+        /**
+         * North America Plus Code :
+         * Convert + code to 011 and dial out for international SMS
+         */
+        CdmaSmsAddress destAddr = CdmaSmsAddress.parse(
+                PhoneNumberUtils.cdmaCheckAndProcessPlusCode(destAddrStr));
         if (destAddr == null) return null;
 
         BearerData bearerData = new BearerData();
diff --git a/telephony/java/com/android/internal/telephony/cdma/sms/BearerData.java b/telephony/java/com/android/internal/telephony/cdma/sms/BearerData.java
index 7a45e15..e17d98d 100755
--- a/telephony/java/com/android/internal/telephony/cdma/sms/BearerData.java
+++ b/telephony/java/com/android/internal/telephony/cdma/sms/BearerData.java
@@ -501,7 +501,7 @@
              * stringToGsm7BitPacked, and potentially directly support
              * access to the main bitwise stream from encode/decode.
              */
-            byte[] fullData = GsmAlphabet.stringToGsm7BitPacked(msg, septetOffset, !force);
+            byte[] fullData = GsmAlphabet.stringToGsm7BitPacked(msg, septetOffset, !force, 0, 0);
             Gsm7bitCodingResult result = new Gsm7bitCodingResult();
             result.data = new byte[fullData.length - 1];
             System.arraycopy(fullData, 1, result.data, 0, fullData.length - 1);
@@ -976,7 +976,8 @@
         int offsetSeptets = (offsetBits + 6) / 7;
         numFields -= offsetSeptets;
         int paddingBits = (offsetSeptets * 7) - offsetBits;
-        String result = GsmAlphabet.gsm7BitPackedToString(data, offset, numFields, paddingBits);
+        String result = GsmAlphabet.gsm7BitPackedToString(data, offset, numFields, paddingBits,
+                0, 0);
         if (result == null) {
             throw new CodingException("7bit GSM decoding failed");
         }
diff --git a/telephony/java/com/android/internal/telephony/gsm/GsmSMSDispatcher.java b/telephony/java/com/android/internal/telephony/gsm/GsmSMSDispatcher.java
index 21a12f1..4a33582 100755
--- a/telephony/java/com/android/internal/telephony/gsm/GsmSMSDispatcher.java
+++ b/telephony/java/com/android/internal/telephony/gsm/GsmSMSDispatcher.java
@@ -70,9 +70,8 @@
         String pduString = (String) ar.result;
         SmsMessage sms = SmsMessage.newFromCDS(pduString);
 
-        int tpStatus = sms.getStatus();
-
         if (sms != null) {
+            int tpStatus = sms.getStatus();
             int messageRef = sms.messageRef;
             for (int i = 0, count = deliveryPendingList.size(); i < count; i++) {
                 SmsTracker tracker = deliveryPendingList.get(i);
@@ -202,6 +201,7 @@
 
         mRemainingMessages = msgCount;
 
+        TextEncodingDetails[] encodingForParts = new TextEncodingDetails[msgCount];
         for (int i = 0; i < msgCount; i++) {
             TextEncodingDetails details = SmsMessage.calculateLength(parts.get(i), false);
             if (encoding != details.codeUnitSize
@@ -209,6 +209,7 @@
                             || encoding == android.telephony.SmsMessage.ENCODING_7BIT)) {
                 encoding = details.codeUnitSize;
             }
+            encodingForParts[i] = details;
         }
 
         for (int i = 0; i < msgCount; i++) {
@@ -225,6 +226,10 @@
             concatRef.isEightBits = true;
             SmsHeader smsHeader = new SmsHeader();
             smsHeader.concatRef = concatRef;
+            if (encoding == android.telephony.SmsMessage.ENCODING_7BIT) {
+                smsHeader.languageTable = encodingForParts[i].languageTable;
+                smsHeader.languageShiftTable = encodingForParts[i].languageShiftTable;
+            }
 
             PendingIntent sentIntent = null;
             if (sentIntents != null && sentIntents.size() > i) {
@@ -238,7 +243,7 @@
 
             SmsMessage.SubmitPdu pdus = SmsMessage.getSubmitPdu(scAddress, destinationAddress,
                     parts.get(i), deliveryIntent != null, SmsHeader.toByteArray(smsHeader),
-                    encoding);
+                    encoding, smsHeader.languageTable, smsHeader.languageShiftTable);
 
             sendRawPdu(pdus.encodedScAddress, pdus.encodedMessage, sentIntent, deliveryIntent);
         }
@@ -293,6 +298,7 @@
 
         mRemainingMessages = msgCount;
 
+        TextEncodingDetails[] encodingForParts = new TextEncodingDetails[msgCount];
         for (int i = 0; i < msgCount; i++) {
             TextEncodingDetails details = SmsMessage.calculateLength(parts.get(i), false);
             if (encoding != details.codeUnitSize
@@ -300,6 +306,7 @@
                             || encoding == android.telephony.SmsMessage.ENCODING_7BIT)) {
                 encoding = details.codeUnitSize;
             }
+            encodingForParts[i] = details;
         }
 
         for (int i = 0; i < msgCount; i++) {
@@ -310,6 +317,10 @@
             concatRef.isEightBits = false;
             SmsHeader smsHeader = new SmsHeader();
             smsHeader.concatRef = concatRef;
+            if (encoding == android.telephony.SmsMessage.ENCODING_7BIT) {
+                smsHeader.languageTable = encodingForParts[i].languageTable;
+                smsHeader.languageShiftTable = encodingForParts[i].languageShiftTable;
+            }
 
             PendingIntent sentIntent = null;
             if (sentIntents != null && sentIntents.size() > i) {
@@ -323,7 +334,7 @@
 
             SmsMessage.SubmitPdu pdus = SmsMessage.getSubmitPdu(scAddress, destinationAddress,
                     parts.get(i), deliveryIntent != null, SmsHeader.toByteArray(smsHeader),
-                    encoding);
+                    encoding, smsHeader.languageTable, smsHeader.languageShiftTable);
 
             HashMap<String, Object> map = new HashMap<String, Object>();
             map.put("smsc", pdus.encodedScAddress);
diff --git a/telephony/java/com/android/internal/telephony/gsm/SimPhoneBookInterfaceManager.java b/telephony/java/com/android/internal/telephony/gsm/SimPhoneBookInterfaceManager.java
index 377f8f0..35ba0d1 100644
--- a/telephony/java/com/android/internal/telephony/gsm/SimPhoneBookInterfaceManager.java
+++ b/telephony/java/com/android/internal/telephony/gsm/SimPhoneBookInterfaceManager.java
@@ -16,6 +16,8 @@
 
 package com.android.internal.telephony.gsm;
 
+import java.util.concurrent.atomic.AtomicBoolean;
+
 import android.os.Message;
 import android.util.Log;
 
@@ -56,14 +58,11 @@
             recordSize = new int[3];
 
             //Using mBaseHandler, no difference in EVENT_GET_SIZE_DONE handling
-            Message response = mBaseHandler.obtainMessage(EVENT_GET_SIZE_DONE);
+            AtomicBoolean status = new AtomicBoolean(false);
+            Message response = mBaseHandler.obtainMessage(EVENT_GET_SIZE_DONE, status);
 
             phone.getIccFileHandler().getEFLinearRecordSize(efid, response);
-            try {
-                mLock.wait();
-            } catch (InterruptedException e) {
-                logd("interrupted while trying to load from the SIM");
-            }
+            waitForResult(status);
         }
 
         return recordSize;
diff --git a/telephony/java/com/android/internal/telephony/gsm/SmsMessage.java b/telephony/java/com/android/internal/telephony/gsm/SmsMessage.java
index e24613f..ac184f4 100644
--- a/telephony/java/com/android/internal/telephony/gsm/SmsMessage.java
+++ b/telephony/java/com/android/internal/telephony/gsm/SmsMessage.java
@@ -38,7 +38,6 @@
 import static android.telephony.SmsMessage.MAX_USER_DATA_BYTES;
 import static android.telephony.SmsMessage.MAX_USER_DATA_BYTES_WITH_HEADER;
 import static android.telephony.SmsMessage.MAX_USER_DATA_SEPTETS;
-import static android.telephony.SmsMessage.MAX_USER_DATA_SEPTETS_WITH_HEADER;
 import static android.telephony.SmsMessage.MessageClass;
 
 /**
@@ -214,9 +213,7 @@
      */
     public static int getTPLayerLengthForPDU(String pdu) {
         int len = pdu.length() / 2;
-        int smscLen = 0;
-
-        smscLen = Integer.parseInt(pdu.substring(0, 2), 16);
+        int smscLen = Integer.parseInt(pdu.substring(0, 2), 16);
 
         return len - smscLen - 1;
     }
@@ -234,7 +231,7 @@
             String destinationAddress, String message,
             boolean statusReportRequested, byte[] header) {
         return getSubmitPdu(scAddress, destinationAddress, message, statusReportRequested, header,
-                ENCODING_UNKNOWN);
+                ENCODING_UNKNOWN, 0, 0);
     }
 
 
@@ -244,6 +241,8 @@
      *
      * @param scAddress Service Centre address.  Null means use default.
      * @param encoding Encoding defined by constants in android.telephony.SmsMessage.ENCODING_*
+     * @param languageTable
+     * @param languageShiftTable
      * @return a <code>SubmitPdu</code> containing the encoded SC
      *         address, if applicable, and the encoded message.
      *         Returns null on encode error.
@@ -251,7 +250,8 @@
      */
     public static SubmitPdu getSubmitPdu(String scAddress,
             String destinationAddress, String message,
-            boolean statusReportRequested, byte[] header, int encoding) {
+            boolean statusReportRequested, byte[] header, int encoding,
+            int languageTable, int languageShiftTable) {
 
         // Perform null parameter checks.
         if (message == null || destinationAddress == null) {
@@ -272,7 +272,8 @@
         }
         try {
             if (encoding == ENCODING_7BIT) {
-                userData = GsmAlphabet.stringToGsm7BitPackedWithHeader(message, header);
+                userData = GsmAlphabet.stringToGsm7BitPackedWithHeader(message, header,
+                        languageTable, languageShiftTable);
             } else { //assume UCS-2
                 try {
                     userData = encodeUCS2(message, header);
@@ -686,70 +687,19 @@
             return userDataHeader;
         }
 
-/*
-        XXX Not sure what this one is supposed to be doing, and no one is using
-        it.
-        String getUserDataGSM8bit() {
-            // System.out.println("remainder of pdu:" +
-            // HexDump.dumpHexString(pdu, cur, pdu.length - cur));
-            int count = pdu[cur++] & 0xff;
-            int size = pdu[cur++];
-
-            // skip over header for now
-            cur += size;
-
-            if (pdu[cur - 1] == 0x01) {
-                int tid = pdu[cur++] & 0xff;
-                int type = pdu[cur++] & 0xff;
-
-                size = pdu[cur++] & 0xff;
-
-                int i = cur;
-
-                while (pdu[i++] != '\0') {
-                }
-
-                int length = i - cur;
-                String mimeType = new String(pdu, cur, length);
-
-                cur += length;
-
-                if (false) {
-                    System.out.println("tid = 0x" + HexDump.toHexString(tid));
-                    System.out.println("type = 0x" + HexDump.toHexString(type));
-                    System.out.println("header size = " + size);
-                    System.out.println("mimeType = " + mimeType);
-                    System.out.println("remainder of header:" +
-                     HexDump.dumpHexString(pdu, cur, (size - mimeType.length())));
-                }
-
-                cur += size - mimeType.length();
-
-                // System.out.println("data count = " + count + " cur = " + cur
-                // + " :" + HexDump.dumpHexString(pdu, cur, pdu.length - cur));
-
-                MMSMessage msg = MMSMessage.parseEncoding(mContext, pdu, cur,
-                        pdu.length - cur);
-            } else {
-                System.out.println(new String(pdu, cur, pdu.length - cur - 1));
-            }
-
-            return IccUtils.bytesToHexString(pdu);
-        }
-*/
-
         /**
-         * Interprets the user data payload as pack GSM 7bit characters, and
+         * Interprets the user data payload as packed GSM 7bit characters, and
          * decodes them into a String.
          *
          * @param septetCount the number of septets in the user data payload
          * @return a String with the decoded characters
          */
-        String getUserDataGSM7Bit(int septetCount) {
+        String getUserDataGSM7Bit(int septetCount, int languageTable,
+                int languageShiftTable) {
             String ret;
 
             ret = GsmAlphabet.gsm7BitPackedToString(pdu, cur, septetCount,
-                    mUserDataSeptetPadding);
+                    mUserDataSeptetPadding, languageTable, languageShiftTable);
 
             cur += (septetCount * 7) / 8;
 
@@ -812,21 +762,9 @@
      */
     public static TextEncodingDetails calculateLength(CharSequence msgBody,
             boolean use7bitOnly) {
-        TextEncodingDetails ted = new TextEncodingDetails();
-        try {
-            int septets = GsmAlphabet.countGsmSeptets(msgBody, !use7bitOnly);
-            ted.codeUnitCount = septets;
-            if (septets > MAX_USER_DATA_SEPTETS) {
-                ted.msgCount = (septets + (MAX_USER_DATA_SEPTETS_WITH_HEADER - 1)) /
-                        MAX_USER_DATA_SEPTETS_WITH_HEADER;
-                ted.codeUnitsRemaining = (ted.msgCount *
-                        MAX_USER_DATA_SEPTETS_WITH_HEADER) - septets;
-            } else {
-                ted.msgCount = 1;
-                ted.codeUnitsRemaining = MAX_USER_DATA_SEPTETS - septets;
-            }
-            ted.codeUnitSize = ENCODING_7BIT;
-        } catch (EncodeException ex) {
+        TextEncodingDetails ted = GsmAlphabet.countGsmSeptets(msgBody, use7bitOnly);
+        if (ted == null) {
+            ted = new TextEncodingDetails();
             int octets = msgBody.length() * 2;
             ted.codeUnitCount = msgBody.length();
             if (octets > MAX_USER_DATA_BYTES) {
@@ -867,7 +805,7 @@
     /** {@inheritDoc} */
     @Override
     public boolean isMWIClearMessage() {
-        if (isMwi && (mwiSense == false)) {
+        if (isMwi && !mwiSense) {
             return true;
         }
 
@@ -878,7 +816,7 @@
     /** {@inheritDoc} */
     @Override
     public boolean isMWISetMessage() {
-        if (isMwi && (mwiSense == true)) {
+        if (isMwi && mwiSense) {
             return true;
         }
 
@@ -1161,7 +1099,9 @@
             break;
 
         case ENCODING_7BIT:
-            messageBody = p.getUserDataGSM7Bit(count);
+            messageBody = p.getUserDataGSM7Bit(count,
+                    hasUserDataHeader ? userDataHeader.languageTable : 0,
+                    hasUserDataHeader ? userDataHeader.languageShiftTable : 0);
             break;
 
         case ENCODING_16BIT:
diff --git a/telephony/java/com/android/internal/telephony/sip/SipPhone.java b/telephony/java/com/android/internal/telephony/sip/SipPhone.java
old mode 100755
new mode 100644
index 7373cbb..5471289
--- a/telephony/java/com/android/internal/telephony/sip/SipPhone.java
+++ b/telephony/java/com/android/internal/telephony/sip/SipPhone.java
@@ -40,6 +40,7 @@
 
 import java.text.ParseException;
 import java.util.List;
+import java.util.regex.Pattern;
 
 /**
  * {@hide}
@@ -386,8 +387,8 @@
         Connection dial(String originalNumber) throws SipException {
             String calleeSipUri = originalNumber;
             if (!calleeSipUri.contains("@")) {
-                calleeSipUri = mProfile.getUriString().replaceFirst(
-                        mProfile.getUserName() + "@",
+                String replaceStr = Pattern.quote(mProfile.getUserName() + "@");
+                calleeSipUri = mProfile.getUriString().replaceFirst(replaceStr,
                         calleeSipUri + "@");
             }
             try {
diff --git a/telephony/tests/telephonytests/src/com/android/internal/telephony/GsmAlphabetTest.java b/telephony/tests/telephonytests/src/com/android/internal/telephony/GsmAlphabetTest.java
index 7011aeb..f9dc3a9 100644
--- a/telephony/tests/telephonytests/src/com/android/internal/telephony/GsmAlphabetTest.java
+++ b/telephony/tests/telephonytests/src/com/android/internal/telephony/GsmAlphabetTest.java
@@ -22,7 +22,6 @@
 
 import android.test.suitebuilder.annotation.LargeTest;
 import android.test.suitebuilder.annotation.SmallTest;
-import android.test.suitebuilder.annotation.Suppress;
 
 public class GsmAlphabetTest extends TestCase {
 
@@ -40,15 +39,16 @@
 
         String message = "aaaaaaaaaabbbbbbbbbbcccccccccc";
         byte[] userData = GsmAlphabet.stringToGsm7BitPackedWithHeader(message,
-                SmsHeader.toByteArray(header));
-        int septetCount = GsmAlphabet.countGsmSeptets(message, false);
+                SmsHeader.toByteArray(header), 0, 0);
+        int septetCount = GsmAlphabet.countGsmSeptetsUsingTables(message, true, 0, 0);
         String parsedMessage = GsmAlphabet.gsm7BitPackedToString(
-                userData, SmsHeader.toByteArray(header).length+2, septetCount, 1);
+                userData, SmsHeader.toByteArray(header).length+2, septetCount, 1, 0, 0);
         assertEquals(message, parsedMessage);
     }
 
     // TODO: This method should *really* be a series of individual test methods.
-    @LargeTest
+    // However, it's a SmallTest because it executes quickly.
+    @SmallTest
     public void testBasic() throws Exception {
         // '@' maps to char 0
         assertEquals(0, GsmAlphabet.charToGsm('@'));
@@ -99,7 +99,7 @@
 
         assertEquals('@', GsmAlphabet.gsmToChar(0));
 
-        // `a (a with grave accent) maps to last GSM charater
+        // `a (a with grave accent) maps to last GSM character
         assertEquals('\u00e0', GsmAlphabet.gsmToChar(0x7f));
 
         assertEquals('\uffff',
@@ -118,8 +118,12 @@
         assertEquals(' ', GsmAlphabet.gsmExtendedToChar(
                 GsmAlphabet.GSM_EXTENDED_ESCAPE));
 
-        // Unmappable
-        assertEquals(' ', GsmAlphabet.gsmExtendedToChar(0));
+        // Reserved for extension to extension table (mapped to space)
+        assertEquals(' ', GsmAlphabet.gsmExtendedToChar(GsmAlphabet.GSM_EXTENDED_ESCAPE));
+
+        // Unmappable (mapped to character in default or national locking shift table)
+        assertEquals('@', GsmAlphabet.gsmExtendedToChar(0));
+        assertEquals('\u00e0', GsmAlphabet.gsmExtendedToChar(0x7f));
 
         //
         // stringTo7BitPacked, gsm7BitPackedToString
@@ -130,7 +134,7 @@
 
         // Check all alignment cases
         for (int i = 0; i < 9; i++, testString.append('@')) {
-            packed = GsmAlphabet.stringToGsm7BitPacked(testString.toString());
+            packed = GsmAlphabet.stringToGsm7BitPacked(testString.toString(), 0, 0);
             assertEquals(testString.toString(),
                     GsmAlphabet.gsm7BitPackedToString(packed, 1, 0xff & packed[0]));
         }
@@ -151,7 +155,7 @@
             assertEquals(1, GsmAlphabet.countGsmSeptets(c));
         }
 
-        packed = GsmAlphabet.stringToGsm7BitPacked(testString.toString());
+        packed = GsmAlphabet.stringToGsm7BitPacked(testString.toString(), 0, 0);
         assertEquals(testString.toString(),
                 GsmAlphabet.gsm7BitPackedToString(packed, 1, 0xff & packed[0]));
 
@@ -166,7 +170,7 @@
 
         }
 
-        packed = GsmAlphabet.stringToGsm7BitPacked(testString.toString());
+        packed = GsmAlphabet.stringToGsm7BitPacked(testString.toString(), 0, 0);
         assertEquals(testString.toString(),
                 GsmAlphabet.gsm7BitPackedToString(packed, 1, 0xff & packed[0]));
 
@@ -177,7 +181,7 @@
             testString.append('@');
         }
 
-        packed = GsmAlphabet.stringToGsm7BitPacked(testString.toString());
+        packed = GsmAlphabet.stringToGsm7BitPacked(testString.toString(), 0, 0);
         assertEquals(testString.toString(),
                 GsmAlphabet.gsm7BitPackedToString(packed, 1, 0xff & packed[0]));
 
@@ -185,7 +189,7 @@
         testString.append('@');
 
         try {
-            GsmAlphabet.stringToGsm7BitPacked(testString.toString());
+            GsmAlphabet.stringToGsm7BitPacked(testString.toString(), 0, 0);
             fail("expected exception");
         } catch (EncodeException ex) {
             // exception expected
@@ -198,7 +202,7 @@
             testString.append('{');
         }
 
-        packed = GsmAlphabet.stringToGsm7BitPacked(testString.toString());
+        packed = GsmAlphabet.stringToGsm7BitPacked(testString.toString(), 0, 0);
         assertEquals(testString.toString(),
                 GsmAlphabet.gsm7BitPackedToString(packed, 1, 0xff & packed[0]));
 
@@ -206,17 +210,29 @@
         testString.append('{');
 
         try {
-            GsmAlphabet.stringToGsm7BitPacked(testString.toString());
+            GsmAlphabet.stringToGsm7BitPacked(testString.toString(), 0, 0);
             fail("expected exception");
         } catch (EncodeException ex) {
             // exception expected
         }
 
+        // Reserved for extension to extension table (mapped to space)
+        packed = new byte[]{(byte)(0x1b | 0x80), 0x1b >> 1};
+        assertEquals(" ", GsmAlphabet.gsm7BitPackedToString(packed, 0, 2));
+
+        // Unmappable (mapped to character in default alphabet table)
+        packed[0] = 0x1b;
+        packed[1] = 0x00;
+        assertEquals("@", GsmAlphabet.gsm7BitPackedToString(packed, 0, 2));
+        packed[0] = (byte)(0x1b | 0x80);
+        packed[1] = (byte)(0x7f >> 1);
+        assertEquals("\u00e0", GsmAlphabet.gsm7BitPackedToString(packed, 0, 2));
+
         //
         // 8 bit unpacked format
         //
         // Note: we compare hex strings here
-        // because Assert doesnt have array-comparisons
+        // because Assert doesn't have array comparisons
 
         byte unpacked[];
 
@@ -308,6 +324,17 @@
 
         assertEquals("a",
                 GsmAlphabet.gsm8BitUnpackedToString(unpacked, 1, unpacked.length - 1));
+
+        // Reserved for extension to extension table (mapped to space)
+        unpacked[0] = 0x1b;
+        unpacked[1] = 0x1b;
+        assertEquals(" ", GsmAlphabet.gsm8BitUnpackedToString(unpacked, 0, 2));
+
+        // Unmappable (mapped to character in default or national locking shift table)
+        unpacked[1] = 0x00;
+        assertEquals("@", GsmAlphabet.gsm8BitUnpackedToString(unpacked, 0, 2));
+        unpacked[1] = 0x7f;
+        assertEquals("\u00e0", GsmAlphabet.gsm8BitUnpackedToString(unpacked, 0, 2));
     }
 
     @SmallTest
diff --git a/telephony/tests/telephonytests/src/com/android/internal/telephony/GsmSmsTest.java b/telephony/tests/telephonytests/src/com/android/internal/telephony/GsmSmsTest.java
index 215c6ce..41a719e 100644
--- a/telephony/tests/telephonytests/src/com/android/internal/telephony/GsmSmsTest.java
+++ b/telephony/tests/telephonytests/src/com/android/internal/telephony/GsmSmsTest.java
@@ -16,8 +16,6 @@
 
 package com.android.internal.telephony;
 
-import com.android.internal.telephony.GsmAlphabet;
-import com.android.internal.telephony.SmsHeader;
 import com.android.internal.telephony.gsm.SmsMessage;
 import com.android.internal.util.HexDump;
 
@@ -209,8 +207,38 @@
                 sms.getMessageBody());
     }
 
+    // GSM 7 bit tables in String form, Escape (0x1B) replaced with '@'
+    private static final String[] sBasicTables = {
+        // GSM 7 bit default alphabet
+        "@\u00a3$\u00a5\u00e8\u00e9\u00f9\u00ec\u00f2\u00c7\n\u00d8\u00f8\r\u00c5\u00e5\u0394_"
+            + "\u03a6\u0393\u039b\u03a9\u03a0\u03a8\u03a3\u0398\u039e@\u00c6\u00e6\u00df\u00c9"
+            + " !\"#\u00a4%&'()*+,-./0123456789:;<=>?\u00a1ABCDEFGHIJKLMNOPQRSTUVWXYZ\u00c4\u00d6"
+            + "\u00d1\u00dc\u00a7\u00bfabcdefghijklmnopqrstuvwxyz\u00e4\u00f6\u00f1\u00fc\u00e0",
+
+        // Turkish locking shift table
+        "@\u00a3$\u00a5\u20ac\u00e9\u00f9\u0131\u00f2\u00c7\n\u011e\u011f\r\u00c5\u00e5\u0394_"
+            + "\u03a6\u0393\u039b\u03a9\u03a0\u03a8\u03a3\u0398\u039e@\u015e\u015f\u00df\u00c9"
+            + " !\"#\u00a4%&'()*+,-./0123456789:;<=>?\u0130ABCDEFGHIJKLMNOPQRSTUVWXYZ\u00c4\u00d6"
+            + "\u00d1\u00dc\u00a7\u00e7abcdefghijklmnopqrstuvwxyz\u00e4\u00f6\u00f1\u00fc\u00e0",
+
+        // no locking shift table defined for Spanish
+        "",
+
+        // Portuguese locking shift table
+        "@\u00a3$\u00a5\u00ea\u00e9\u00fa\u00ed\u00f3\u00e7\n\u00d4\u00f4\r\u00c1\u00e1\u0394_"
+            + "\u00aa\u00c7\u00c0\u221e^\\\u20ac\u00d3|@\u00c2\u00e2\u00ca\u00c9 !\"#\u00ba%&'()"
+            + "*+,-./0123456789:;<=>?\u00cdABCDEFGHIJKLMNOPQRSTUVWXYZ\u00c3\u00d5\u00da\u00dc"
+            + "\u00a7~abcdefghijklmnopqrstuvwxyz\u00e3\u00f5`\u00fc\u00e0"
+    };
+
     @SmallTest
     public void testDecode() throws Exception {
+        decodeSingle(0);    // default table
+        decodeSingle(1);    // Turkish locking shift table
+        decodeSingle(3);    // Portuguese locking shift table
+    }
+
+    private void decodeSingle(int language) throws Exception {
         byte[] septets = new byte[(7 * 128 + 7) / 8];
 
         int bitOffset = 0;
@@ -236,15 +264,168 @@
             bitOffset += 7;
         }
 
-        String decoded = GsmAlphabet.gsm7BitPackedToString(septets, 0, 128);
-        byte[] reEncoded = GsmAlphabet.stringToGsm7BitPacked(decoded);
+        String decoded = GsmAlphabet.gsm7BitPackedToString(septets, 0, 128, 0, language, 0);
+        byte[] reEncoded = GsmAlphabet.stringToGsm7BitPacked(decoded, language, 0);
+
+        assertEquals(sBasicTables[language], decoded);
 
         // reEncoded has the count septets byte at the front
-        assertEquals(reEncoded.length, septets.length + 1);
+        assertEquals(septets.length + 1, reEncoded.length);
 
         for (int i = 0; i < septets.length; i++) {
-            assertEquals(reEncoded[i + 1], septets[i]);
+            assertEquals(septets[i], reEncoded[i + 1]);
         }
     }
 
+    private static final int GSM_ESCAPE_CHARACTER = 0x1b;
+
+    private static final String[] sExtendedTables = {
+        // GSM 7 bit default alphabet extension table
+        "\f^{}\\[~]|\u20ac",
+
+        // Turkish single shift extension table
+        "\f^{}\\[~]|\u011e\u0130\u015e\u00e7\u20ac\u011f\u0131\u015f",
+
+        // Spanish single shift extension table
+        "\u00e7\f^{}\\[~]|\u00c1\u00cd\u00d3\u00da\u00e1\u20ac\u00ed\u00f3\u00fa",
+
+        // Portuguese single shift extension table
+        "\u00ea\u00e7\f\u00d4\u00f4\u00c1\u00e1\u03a6\u0393^\u03a9\u03a0\u03a8\u03a3\u0398\u00ca"
+            + "{}\\[~]|\u00c0\u00cd\u00d3\u00da\u00c3\u00d5\u00c2\u20ac\u00ed\u00f3\u00fa\u00e3"
+            + "\u00f5\u00e2"
+    };
+
+    private static final int[][] sExtendedTableIndexes = {
+        {0x0a, 0x14, 0x28, 0x29, 0x2f, 0x3c, 0x3d, 0x3e, 0x40, 0x65},
+        {0x0a, 0x14, 0x28, 0x29, 0x2f, 0x3c, 0x3d, 0x3e, 0x40, 0x47, 0x49, 0x53, 0x63,
+                0x65, 0x67, 0x69, 0x73},
+        {0x09, 0x0a, 0x14, 0x28, 0x29, 0x2f, 0x3c, 0x3d, 0x3e, 0x40, 0x41, 0x49, 0x4f,
+                0x55, 0x61, 0x65, 0x69, 0x6f, 0x75},
+        {0x05, 0x09, 0x0a, 0x0b, 0x0c, 0x0e, 0x0f, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
+                0x18, 0x19, 0x1f, 0x28, 0x29, 0x2f, 0x3c, 0x3d, 0x3e, 0x40, 0x41, 0x49,
+                0x4f, 0x55, 0x5b, 0x5c, 0x61, 0x65, 0x69, 0x6f, 0x75, 0x7b, 0x7c, 0x7f}
+    };
+
+    @SmallTest
+    public void testDecodeExtended() throws Exception {
+        for (int language = 0; language < 3; language++) {
+            int[] tableIndex = sExtendedTableIndexes[language];
+            int numSeptets = tableIndex.length * 2;  // two septets per extended char
+            byte[] septets = new byte[(7 * numSeptets + 7) / 8];
+
+            int bitOffset = 0;
+
+            for (int v : tableIndex) {
+                // escape character
+                int byteOffset = bitOffset / 8;
+                int shift = bitOffset % 8;
+
+                septets[byteOffset] |= GSM_ESCAPE_CHARACTER << shift;
+
+                if (shift > 1) {
+                    septets[byteOffset + 1] = (byte) (GSM_ESCAPE_CHARACTER >> (8 - shift));
+                }
+
+                bitOffset += 7;
+
+                // extended table index
+                byteOffset = bitOffset / 8;
+                shift = bitOffset % 8;
+
+                septets[byteOffset] |= v << shift;
+
+                if (shift > 1) {
+                    septets[byteOffset + 1] = (byte) (v >> (8 - shift));
+                }
+
+                bitOffset += 7;
+            }
+
+            String decoded = GsmAlphabet.gsm7BitPackedToString(septets, 0, numSeptets, 0,
+                    0, language);
+            byte[] reEncoded = GsmAlphabet.stringToGsm7BitPacked(decoded, 0, language);
+
+            assertEquals(sExtendedTables[language], decoded);
+
+            // reEncoded has the count septets byte at the front
+            assertEquals(septets.length + 1, reEncoded.length);
+
+            for (int i = 0; i < septets.length; i++) {
+                assertEquals(septets[i], reEncoded[i + 1]);
+            }
+        }
+    }
+
+    @SmallTest
+    public void testDecodeExtendedFallback() throws Exception {
+        // verify that unmapped characters in extension table fall back to locking shift table
+        for (int language = 0; language < 3; language++) {
+            int[] tableIndex = sExtendedTableIndexes[language];
+            int numChars = 128 - tableIndex.length;
+            int numSeptets = numChars * 2;  // two septets per extended char
+            byte[] septets = new byte[(7 * numSeptets + 7) / 8];
+
+            int tableOffset = 0;
+            int bitOffset = 0;
+
+            StringBuilder defaultTable = new StringBuilder(128);
+            StringBuilder turkishTable = new StringBuilder(128);
+            StringBuilder portugueseTable = new StringBuilder(128);
+
+            for (char c = 0; c < 128; c++) {
+                // skip characters that are present in the current extension table
+                if (tableOffset < tableIndex.length && tableIndex[tableOffset] == c) {
+                    tableOffset++;
+                    continue;
+                }
+
+                // escape character
+                int byteOffset = bitOffset / 8;
+                int shift = bitOffset % 8;
+
+                septets[byteOffset] |= GSM_ESCAPE_CHARACTER << shift;
+
+                if (shift > 1) {
+                    septets[byteOffset + 1] = (byte) (GSM_ESCAPE_CHARACTER >> (8 - shift));
+                }
+
+                bitOffset += 7;
+
+                // extended table index
+                byteOffset = bitOffset / 8;
+                shift = bitOffset % 8;
+
+                septets[byteOffset] |= c << shift;
+
+                if (shift > 1) {
+                    septets[byteOffset + 1] = (byte) (c >> (8 - shift));
+                }
+
+                bitOffset += 7;
+
+                if (c == GsmAlphabet.GSM_EXTENDED_ESCAPE) {
+                    // double Escape maps to space character
+                    defaultTable.append(' ');
+                    turkishTable.append(' ');
+                    portugueseTable.append(' ');
+                } else {
+                    // other unmapped chars map to the default or locking shift table
+                    defaultTable.append(sBasicTables[0].charAt(c));
+                    turkishTable.append(sBasicTables[1].charAt(c));
+                    portugueseTable.append(sBasicTables[3].charAt(c));
+                }
+            }
+
+            String decoded = GsmAlphabet.gsm7BitPackedToString(septets, 0, numSeptets, 0,
+                    0, language);
+
+            assertEquals(defaultTable.toString(), decoded);
+
+            decoded = GsmAlphabet.gsm7BitPackedToString(septets, 0, numSeptets, 0, 1, language);
+            assertEquals(turkishTable.toString(), decoded);
+
+            decoded = GsmAlphabet.gsm7BitPackedToString(septets, 0, numSeptets, 0, 3, language);
+            assertEquals(portugueseTable.toString(), decoded);
+        }
+    }
 }
diff --git a/telephony/tests/telephonytests/src/com/android/internal/telephony/SmsMessageBodyTest.java b/telephony/tests/telephonytests/src/com/android/internal/telephony/SmsMessageBodyTest.java
index b214887..170bd9b 100644
--- a/telephony/tests/telephonytests/src/com/android/internal/telephony/SmsMessageBodyTest.java
+++ b/telephony/tests/telephonytests/src/com/android/internal/telephony/SmsMessageBodyTest.java
@@ -19,21 +19,57 @@
 import android.telephony.SmsMessage;
 import android.telephony.TelephonyManager;
 import android.test.AndroidTestCase;
+import android.test.suitebuilder.annotation.LargeTest;
+import android.test.suitebuilder.annotation.MediumTest;
 import android.test.suitebuilder.annotation.SmallTest;
+import android.util.Log;
 
+import java.util.Random;
+
+import static android.telephony.SmsMessage.MAX_USER_DATA_BYTES;
+import static android.telephony.SmsMessage.MAX_USER_DATA_BYTES_WITH_HEADER;
 import static android.telephony.SmsMessage.MAX_USER_DATA_SEPTETS;
+import static android.telephony.SmsMessage.MAX_USER_DATA_SEPTETS_WITH_HEADER;
 
+/**
+ * Test cases to verify selection of the optimal 7 bit encoding tables
+ * (for all combinations of enabled national language tables) for messages
+ * containing Turkish, Spanish, Portuguese, Greek, and other symbols
+ * present in the GSM default and national language tables defined in
+ * 3GPP TS 23.038. Also verifies correct SMS encoding for CDMA, which only
+ * supports the GSM 7 bit default alphabet, ASCII 8 bit, and UCS-2.
+ * Tests both encoding variations: unsupported characters mapped to space,
+ * and unsupported characters force entire message to UCS-2.
+ */
 public class SmsMessageBodyTest extends AndroidTestCase {
+    private static final String TAG = "SmsMessageBodyTest";
 
+    // ASCII chars in the GSM 7 bit default alphabet
     private static final String sAsciiChars = "@$_ !\"#%&'()*+,-./0123456789" +
             ":;<=>?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\n\r";
-    private static final String sGsmBasicChars = "\u00a3\u00a5\u00e8\u00e9" +
-            "\u00f9\u00ec\u00f2\u00c7\u00d8\u00f8\u00c5\u00e5\u0394\u03a6" +
-            "\u0393\u039b\u03a9\u03a0\u03a8\u03a3\u0398\u00c6\u00e6" +
-            "\u00df\u00c9\u00a4\u00a1\u00c4\u00d6\u00d1\u00dc\u00a7\u00bf" +
-            "\u00e4\u00f6\u00f1\u00fc\u00e0";
-    private static final String sGsmExtendedAsciiChars = "{|}\\[~]^\f";
+
+    // Unicode chars in the GSM 7 bit default alphabet and both locking shift tables
+    private static final String sGsmDefaultChars = "\u00a3\u00a5\u00e9\u00c7\u0394\u00c9" +
+            "\u00dc\u00a7\u00fc\u00e0";
+
+    // Unicode chars in the GSM 7 bit default table and Turkish locking shift tables
+    private static final String sGsmDefaultAndTurkishTables = "\u00f9\u00f2\u00c5\u00e5\u00df" +
+            "\u00a4\u00c4\u00d6\u00d1\u00e4\u00f6\u00f1";
+
+    // Unicode chars in the GSM 7 bit default table but not the locking shift tables
+    private static final String sGsmDefaultTableOnly = "\u00e8\u00ec\u00d8\u00f8\u00c6\u00e6" +
+            "\u00a1\u00bf";
+
+    // ASCII chars in the GSM default extension table
+    private static final String sGsmExtendedAsciiChars = "{}[]\f";
+
+    // chars in GSM default extension table and Portuguese locking shift table
+    private static final String sGsmExtendedPortugueseLocking = "^\\|~";
+
+    // Euro currency symbol
     private static final String sGsmExtendedEuroSymbol = "\u20ac";
+
+    // CJK ideographs, Hiragana, Katakana, full width letters, Cyrillic, etc.
     private static final String sUnicodeChars = "\u4e00\u4e01\u4e02\u4e03" +
             "\u4e04\u4e05\u4e06\u4e07\u4e08\u4e09\u4e0a\u4e0b\u4e0c\u4e0d" +
             "\u4e0e\u4e0f\u3041\u3042\u3043\u3044\u3045\u3046\u3047\u3048" +
@@ -43,6 +79,86 @@
             "\u0400\u0401\u0402\u0403\u0404\u0405\u0406\u0407\u0408" +
             "\u00a2\u00a9\u00ae\u2122";
 
+    // chars in Turkish single shift and locking shift tables
+    private static final String sTurkishChars = "\u0131\u011e\u011f\u015e\u015f\u0130";
+
+    // chars in Spanish single shift table and Portuguese single and locking shift tables
+    private static final String sPortugueseAndSpanishChars = "\u00c1\u00e1\u00cd\u00ed"
+            + "\u00d3\u00f3\u00da\u00fa";
+
+    // chars in all national language tables but not in the standard GSM alphabets
+    private static final String sNationalLanguageTablesOnly = "\u00e7";
+
+    // chars in Portuguese single shift and locking shift tables
+    private static final String sPortugueseChars = "\u00ea\u00d4\u00f4\u00c0\u00c2\u00e2"
+            + "\u00ca\u00c3\u00d5\u00e3\u00f5";
+
+    // chars in Portuguese locking shift table only
+    private static final String sPortugueseLockingShiftChars = "\u00aa\u221e\u00ba`";
+
+    // Greek letters in GSM alphabet missing from Portuguese locking and single shift tables
+    private static final String sGreekLettersNotInPortugueseTables = "\u039b\u039e";
+
+    // Greek letters in GSM alphabet and Portuguese single shift (but not locking shift) table
+    private static final String sGreekLettersInPortugueseShiftTable =
+            "\u03a6\u0393\u03a9\u03a0\u03a8\u03a3\u0398";
+
+    // List of classes of characters in SMS tables
+    private static final String[] sCharacterClasses = {
+            sGsmExtendedAsciiChars,
+            sGsmExtendedPortugueseLocking,
+            sGsmDefaultChars,
+            sGsmDefaultAndTurkishTables,
+            sGsmDefaultTableOnly,
+            sGsmExtendedEuroSymbol,
+            sUnicodeChars,
+            sTurkishChars,
+            sPortugueseChars,
+            sPortugueseLockingShiftChars,
+            sPortugueseAndSpanishChars,
+            sGreekLettersNotInPortugueseTables,
+            sGreekLettersInPortugueseShiftTable,
+            sNationalLanguageTablesOnly,
+            sAsciiChars
+    };
+
+    private static final int sNumCharacterClasses = sCharacterClasses.length;
+
+    // For each character class, whether it is present in a particular char table.
+    // First three entries are locking shift tables, followed by four single shift tables
+    private static final boolean[][] sCharClassPresenceInTables = {
+            // ASCII chars in all GSM extension tables
+            {false, false, false, true, true, true, true},
+            // ASCII chars in all GSM extension tables and Portuguese locking shift table
+            {false, false, true, true, true, true, true},
+            // non-ASCII chars in GSM default alphabet and all locking tables
+            {true, true, true, false, false, false, false},
+            // non-ASCII chars in GSM default alphabet and Turkish locking shift table
+            {true, true, false, false, false, false, false},
+            // non-ASCII chars in GSM default alphabet table only
+            {true, false, false, false, false, false, false},
+            // Euro symbol is present in several tables
+            {false, true, true, true, true, true, true},
+            // Unicode characters not present in any 7 bit tables
+            {false, false, false, false, false, false, false},
+            // Characters specific to Turkish language
+            {false, true, false, false, true, false, false},
+            // Characters in Portuguese single shift and locking shift tables
+            {false, false, true, false, false, false, true},
+            // Characters in Portuguese locking shift table only
+            {false, false, true, false, false, false, false},
+            // Chars in Spanish single shift and Portuguese single and locking shift tables
+            {false, false, true, false, false, true, true},
+            // Greek letters in GSM default alphabet missing from Portuguese tables
+            {true, true, false, false, false, false, false},
+            // Greek letters in GSM alphabet and Portuguese single shift table
+            {true, true, false, false, false, false, true},
+            // Chars in all national language tables but not the standard GSM tables
+            {false, true, true, false, true, true, true},
+            // ASCII chars in GSM default alphabet
+            {true, true, true, false, false, false, false}
+    };
+
     private static final int sTestLengthCount = 12;
 
     private static final int[] sSeptetTestLengths =
@@ -60,11 +176,92 @@
     private static final int[] sUnicodeUnitsRemaining =
             { 70,  69,  68, 35,   1,   0,  63,  34,   1,   0,  66,  41};
 
+    // Combinations of enabled GSM national language single shift tables
+    private static final int[][] sEnabledSingleShiftTables = {
+            {},         // GSM default alphabet only
+            {1},        // Turkish (single shift only)
+            {1},        // Turkish (single and locking shift)
+            {2},        // Spanish
+            {3},        // Portuguese (single shift only)
+            {3},        // Portuguese (single and locking shift)
+            {1, 2},     // Turkish + Spanish (single shift only)
+            {1, 2},     // Turkish + Spanish (single and locking shift)
+            {1, 3},     // Turkish + Portuguese (single shift only)
+            {1, 3},     // Turkish + Portuguese (single and locking shift)
+            {2, 3},     // Spanish + Portuguese (single shift only)
+            {2, 3},     // Spanish + Portuguese (single and locking shift)
+            {1, 2, 3},  // Turkish, Spanish, Portuguese (single shift only)
+            {1, 2, 3},  // Turkish, Spanish, Portuguese (single and locking shift)
+            {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13} // all language tables
+    };
+
+    // Combinations of enabled GSM national language locking shift tables
+    private static final int[][] sEnabledLockingShiftTables = {
+            {},         // GSM default alphabet only
+            {},         // Turkish (single shift only)
+            {1},        // Turkish (single and locking shift)
+            {},         // Spanish (no locking shift table)
+            {},         // Portuguese (single shift only)
+            {3},        // Portuguese (single and locking shift)
+            {},         // Turkish + Spanish (single shift only)
+            {1},        // Turkish + Spanish (single and locking shift)
+            {},         // Turkish + Portuguese (single shift only)
+            {1, 3},     // Turkish + Portuguese (single and locking shift)
+            {},         // Spanish + Portuguese (single shift only)
+            {3},        // Spanish + Portuguese (single and locking shift)
+            {},         // Turkish, Spanish, Portuguese (single shift only)
+            {1, 3},     // Turkish, Spanish, Portuguese (single and locking shift)
+            {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13} // all language tables
+    };
+
+    // LanguagePair counter indexes to check for each entry above
+    private static final int[][] sLanguagePairIndexesByEnabledIndex = {
+            {0},                            // default tables only
+            {0, 1},                         // Turkish (single shift only)
+            {0, 1, 4, 5},                   // Turkish (single and locking shift)
+            {0, 2},                         // Spanish
+            {0, 3},                         // Portuguese (single shift only)
+            {0, 3, 8, 11},                  // Portuguese (single and locking shift)
+            {0, 1, 2},                      // Turkish + Spanish (single shift only)
+            {0, 1, 2, 4, 5, 6},             // Turkish + Spanish (single and locking shift)
+            {0, 1, 3},                      // Turkish + Portuguese (single shift only)
+            {0, 1, 3, 4, 5, 7, 8, 9, 11},   // Turkish + Portuguese (single and locking shift)
+            {0, 2, 3},                      // Spanish + Portuguese (single shift only)
+            {0, 2, 3, 8, 10, 11},           // Spanish + Portuguese (single and locking shift)
+            {0, 1, 2, 3},                   // all languages (single shift only)
+            {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, // all languages (single and locking shift)
+            {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}  // all languages (no Indic chars in test)
+    };
+
+    /**
+     * User data header requires one octet for length. Count as one septet, because
+     * all combinations of header elements below will have at least one free bit
+     * when padding to the nearest septet boundary.
+     */
+    private static final int UDH_SEPTET_COST_LENGTH = 1;
+
+    /**
+     * Using a non-default language locking shift table OR single shift table
+     * requires a user data header of 3 octets, or 4 septets, plus UDH length.
+     */
+    private static final int UDH_SEPTET_COST_ONE_SHIFT_TABLE = 4;
+
+    /**
+     * Using a non-default language locking shift table AND single shift table
+     * requires a user data header of 6 octets, or 7 septets, plus UDH length.
+     */
+    private static final int UDH_SEPTET_COST_TWO_SHIFT_TABLES = 7;
+
+    /**
+     * Multi-part messages require a user data header of 5 octets, or 6 septets,
+     * plus UDH length.
+     */
+    private static final int UDH_SEPTET_COST_CONCATENATED_MESSAGE = 6;
 
     @SmallTest
     public void testCalcLengthAscii() throws Exception {
         StringBuilder sb = new StringBuilder(320);
-        int[] values = {0, 0, 0, SmsMessage.ENCODING_7BIT};
+        int[] values = {0, 0, 0, SmsMessage.ENCODING_7BIT, 0, 0};
         int startPos = 0;
         int asciiCharsLen = sAsciiChars.length();
 
@@ -94,20 +291,10 @@
     }
 
     @SmallTest
-    public void testCalcLength7bitGsm() throws Exception {
-        // TODO
-    }
-
-    @SmallTest
-    public void testCalcLength7bitGsmExtended() throws Exception {
-        // TODO
-    }
-
-    @SmallTest
     public void testCalcLengthUnicode() throws Exception {
         StringBuilder sb = new StringBuilder(160);
-        int[] values = {0, 0, 0, SmsMessage.ENCODING_16BIT};
-        int[] values7bit = {1, 0, 0, SmsMessage.ENCODING_7BIT};
+        int[] values = {0, 0, 0, SmsMessage.ENCODING_16BIT, 0, 0};
+        int[] values7bit = {1, 0, 0, SmsMessage.ENCODING_7BIT, 0, 0};
         int startPos = 0;
         int unicodeCharsLen = sUnicodeChars.length();
 
@@ -139,6 +326,229 @@
         }
     }
 
+    private static class LanguagePair {
+        // index is 2 for Portuguese locking shift because there is no Spanish locking shift table
+        private final int langTableIndex;
+        private final int langShiftTableIndex;
+        int length;
+        int missingChars7bit;
+
+        LanguagePair(int langTable, int langShiftTable) {
+            langTableIndex = langTable;
+            langShiftTableIndex = langShiftTable;
+        }
+
+        void clear() {
+            length = 0;
+            missingChars7bit = 0;
+        }
+
+        void addChar(boolean[] charClassTableRow) {
+            if (charClassTableRow[langTableIndex]) {
+                length++;
+            } else if (charClassTableRow[3 + langShiftTableIndex]) {
+                length += 2;
+            } else {
+                length++;    // use ' ' for unmapped char in 7 bit only mode
+                missingChars7bit++;
+            }
+        }
+    }
+
+    private static class CounterHelper {
+        LanguagePair[] mCounters;
+        int[] mStatsCounters;
+        int mUnicodeCounter;
+
+        CounterHelper() {
+            mCounters = new LanguagePair[12];
+            mStatsCounters = new int[12];
+            for (int i = 0; i < 12; i++) {
+                mCounters[i] = new LanguagePair(i/4, i%4);
+            }
+        }
+
+        void clear() {
+            // Note: don't clear stats counters
+            for (int i = 0; i < 12; i++) {
+                mCounters[i].clear();
+            }
+        }
+
+        void addChar(int charClass) {
+            boolean[] charClassTableRow = sCharClassPresenceInTables[charClass];
+            for (int i = 0; i < 12; i++) {
+                mCounters[i].addChar(charClassTableRow);
+            }
+        }
+
+        void fillData(int enabledLangsIndex, boolean use7bitOnly, int[] values, int length) {
+            int[] languagePairs = sLanguagePairIndexesByEnabledIndex[enabledLangsIndex];
+            int minNumSeptets = Integer.MAX_VALUE;
+            int minNumSeptetsWithHeader = Integer.MAX_VALUE;
+            int minNumMissingChars = Integer.MAX_VALUE;
+            int langIndex = -1;
+            int langShiftIndex = -1;
+            for (int i : languagePairs) {
+                LanguagePair pair = mCounters[i];
+                int udhLength = 0;
+                if (i != 0) {
+                    udhLength = UDH_SEPTET_COST_LENGTH;
+                    if (i < 4 || i % 4 == 0) {
+                        udhLength += UDH_SEPTET_COST_ONE_SHIFT_TABLE;
+                    } else {
+                        udhLength += UDH_SEPTET_COST_TWO_SHIFT_TABLES;
+                    }
+                }
+                int numSeptetsWithHeader;
+                if (pair.length > (MAX_USER_DATA_SEPTETS - udhLength)) {
+                    if (udhLength == 0) {
+                        udhLength = UDH_SEPTET_COST_LENGTH;
+                    }
+                    udhLength += UDH_SEPTET_COST_CONCATENATED_MESSAGE;
+                    int septetsPerPart = MAX_USER_DATA_SEPTETS - udhLength;
+                    int msgCount = (pair.length + septetsPerPart - 1) / septetsPerPart;
+                    numSeptetsWithHeader = udhLength * msgCount + pair.length;
+                } else {
+                    numSeptetsWithHeader = udhLength + pair.length;
+                }
+
+                if (use7bitOnly) {
+                    if (pair.missingChars7bit < minNumMissingChars || (pair.missingChars7bit ==
+                            minNumMissingChars && numSeptetsWithHeader < minNumSeptetsWithHeader)) {
+                        minNumSeptets = pair.length;
+                        minNumSeptetsWithHeader = numSeptetsWithHeader;
+                        minNumMissingChars = pair.missingChars7bit;
+                        langIndex = pair.langTableIndex;
+                        langShiftIndex = pair.langShiftTableIndex;
+                    }
+                } else {
+                    if (pair.missingChars7bit == 0 && numSeptetsWithHeader < minNumSeptetsWithHeader) {
+                        minNumSeptets = pair.length;
+                        minNumSeptetsWithHeader = numSeptetsWithHeader;
+                        langIndex = pair.langTableIndex;
+                        langShiftIndex = pair.langShiftTableIndex;
+                    }
+                }
+            }
+            if (langIndex == -1) {
+                // nothing matches, use values for Unicode
+                int byteCount = length * 2;
+                if (byteCount > MAX_USER_DATA_BYTES) {
+                    values[0] = (byteCount + MAX_USER_DATA_BYTES_WITH_HEADER - 1) /
+                            MAX_USER_DATA_BYTES_WITH_HEADER;
+                    values[2] = ((values[0] * MAX_USER_DATA_BYTES_WITH_HEADER) - byteCount) / 2;
+                } else {
+                    values[0] = 1;
+                    values[2] = (MAX_USER_DATA_BYTES - byteCount) / 2;
+                }
+                values[1] = length;
+                values[3] = SmsMessage.ENCODING_16BIT;
+                values[4] = 0;
+                values[5] = 0;
+                mUnicodeCounter++;
+            } else {
+                int udhLength = 0;
+                if (langIndex != 0 || langShiftIndex != 0) {
+                    udhLength = UDH_SEPTET_COST_LENGTH;
+                    if (langIndex == 0 || langShiftIndex == 0) {
+                        udhLength += UDH_SEPTET_COST_ONE_SHIFT_TABLE;
+                    } else {
+                        udhLength += UDH_SEPTET_COST_TWO_SHIFT_TABLES;
+                    }
+                }
+                int msgCount;
+                if (minNumSeptets > (MAX_USER_DATA_SEPTETS - udhLength)) {
+                    if (udhLength == 0) {
+                        udhLength = UDH_SEPTET_COST_LENGTH;
+                    }
+                    udhLength += UDH_SEPTET_COST_CONCATENATED_MESSAGE;
+                    int septetsPerPart = MAX_USER_DATA_SEPTETS - udhLength;
+                    msgCount = (minNumSeptets + septetsPerPart - 1) / septetsPerPart;
+                } else {
+                    msgCount = 1;
+                }
+                values[0] = msgCount;
+                values[1] = minNumSeptets;
+                values[2] = (values[0] * (MAX_USER_DATA_SEPTETS - udhLength)) - minNumSeptets;
+                values[3] = SmsMessage.ENCODING_7BIT;
+                values[4] = (langIndex == 2 ? 3 : langIndex); // Portuguese is code 3, index 2
+                values[5] = langShiftIndex;
+                assertEquals("minNumSeptetsWithHeader", minNumSeptetsWithHeader,
+                        udhLength * msgCount + minNumSeptets);
+                mStatsCounters[langIndex * 4 + langShiftIndex]++;
+            }
+        }
+
+        void printStats() {
+            Log.d(TAG, "Unicode selection count: " + mUnicodeCounter);
+            for (int i = 0; i < 12; i++) {
+                Log.d(TAG, "Language pair index " + i + " count: " + mStatsCounters[i]);
+            }
+        }
+    }
+
+    @LargeTest
+    public void testCalcLengthMixed7bit() throws Exception {
+        StringBuilder sb = new StringBuilder(320);
+        CounterHelper ch = new CounterHelper();
+        Random r = new Random(0x4321);  // use the same seed for reproducibility
+        int[] expectedValues = new int[6];
+        int[] origLockingShiftTables = GsmAlphabet.getEnabledLockingShiftTables();
+        int[] origSingleShiftTables = GsmAlphabet.getEnabledSingleShiftTables();
+        int enabledLanguagesTestCases = sEnabledSingleShiftTables.length;
+        long startTime = System.currentTimeMillis();
+
+        // Repeat for 10 test runs
+        for (int run = 0; run < 10; run++) {
+            sb.setLength(0);
+            ch.clear();
+            int unicodeOnlyCount = 0;
+
+            // Test incrementally from 1 to 320 character random messages
+            for (int i = 1; i < 320; i++) {
+                // 1% chance to add from each special character class, else add an ASCII char
+                int charClass = r.nextInt(100);
+                if (charClass >= sNumCharacterClasses) {
+                    charClass = sNumCharacterClasses - 1;   // last class is ASCII
+                }
+                int classLength = sCharacterClasses[charClass].length();
+                char nextChar = sCharacterClasses[charClass].charAt(r.nextInt(classLength));
+                sb.append(nextChar);
+                ch.addChar(charClass);
+
+//                if (i % 20 == 0) {
+//                    Log.d(TAG, "test string: " + sb);
+//                }
+
+                // Test string against all combinations of enabled languages
+                boolean unicodeOnly = true;
+                for (int j = 0; j < enabledLanguagesTestCases; j++) {
+                    GsmAlphabet.setEnabledSingleShiftTables(sEnabledSingleShiftTables[j]);
+                    GsmAlphabet.setEnabledLockingShiftTables(sEnabledLockingShiftTables[j]);
+                    ch.fillData(j, false, expectedValues, i);
+                    if (expectedValues[3] == SmsMessage.ENCODING_7BIT) {
+                        unicodeOnly = false;
+                    }
+                    callGsmLengthMethods(sb, false, expectedValues);
+                    // test 7 bit only mode
+                    ch.fillData(j, true, expectedValues, i);
+                    callGsmLengthMethods(sb, true, expectedValues);
+                }
+                // after 10 iterations with a Unicode-only string, skip to next test string
+                // so we can spend more time testing strings that do encode into 7 bits.
+                if (unicodeOnly && ++unicodeOnlyCount == 10) {
+//                    Log.d(TAG, "Unicode only: skipping to next test string");
+                    break;
+                }
+            }
+        }
+        ch.printStats();
+        Log.d(TAG, "Completed in " + (System.currentTimeMillis() - startTime) + " ms");
+        GsmAlphabet.setEnabledLockingShiftTables(origLockingShiftTables);
+        GsmAlphabet.setEnabledSingleShiftTables(origSingleShiftTables);
+    }
+
     private void callGsmLengthMethods(CharSequence msgBody, boolean use7bitOnly,
             int[] expectedValues)
     {
@@ -164,6 +574,8 @@
         assertEquals("codeUnitCount",      expectedValues[1], ted.codeUnitCount);
         assertEquals("codeUnitsRemaining", expectedValues[2], ted.codeUnitsRemaining);
         assertEquals("codeUnitSize",       expectedValues[3], ted.codeUnitSize);
+        assertEquals("languageTable",      expectedValues[4], ted.languageTable);
+        assertEquals("languageShiftTable", expectedValues[5], ted.languageShiftTable);
     }
 
     private void callCdmaLengthMethods(CharSequence msgBody, boolean use7bitOnly,
diff --git a/tests/CoreTests/android/core/HttpHeaderTest.java b/tests/CoreTests/android/core/HttpHeaderTest.java
index a5d48578..eedbc3f 100644
--- a/tests/CoreTests/android/core/HttpHeaderTest.java
+++ b/tests/CoreTests/android/core/HttpHeaderTest.java
@@ -19,12 +19,19 @@
 import org.apache.http.util.CharArrayBuffer;
 
 import android.net.http.Headers;
+import android.util.Log;
+import android.webkit.CacheManager;
+import android.webkit.CacheManager.CacheResult;
+
+import java.lang.reflect.Method;
 
 public class HttpHeaderTest extends AndroidTestCase {
 
     static final String LAST_MODIFIED = "Last-Modified: Fri, 18 Jun 2010 09:56:47 GMT";
     static final String CACHE_CONTROL_MAX_AGE = "Cache-Control:max-age=15";
     static final String CACHE_CONTROL_PRIVATE = "Cache-Control: private";
+    static final String CACHE_CONTROL_COMPOUND = "Cache-Control: no-cache, max-age=200000";
+    static final String CACHE_CONTROL_COMPOUND2 = "Cache-Control: max-age=200000, no-cache";
 
     /**
      * Tests that cache control header supports multiple instances of the header,
@@ -59,4 +66,39 @@
         h.parseHeader(buffer);
         assertEquals("max-age=15,private", h.getCacheControl());
     }
+
+    // Test that cache behaves correctly when receiving a compund
+    // cache-control statement containing no-cache and max-age argument.
+    //
+    // If a cache control header contains both a max-age arument and
+    // a no-cache argument the max-age argument should be ignored.
+    // The resource can be cached, but a validity check must be done on
+    // every request. Test case checks that the expiry time is 0 for
+    // this item, so item will be validated on subsequent requests.
+    public void testCacheControlMultipleArguments() throws Exception {
+        // get private method CacheManager.parseHeaders()
+        Method m = CacheManager.class.getDeclaredMethod("parseHeaders",
+                new Class[] {int.class, Headers.class, String.class});
+        m.setAccessible(true);
+
+        // create indata
+        Headers h = new Headers();
+        CharArrayBuffer buffer = new CharArrayBuffer(64);
+        buffer.append(CACHE_CONTROL_COMPOUND);
+        h.parseHeader(buffer);
+
+        CacheResult c = (CacheResult)m.invoke(null, 200, h, "text/html");
+
+        // Check that expires is set to 0, to ensure that no-cache has overridden
+        // the max-age argument
+        assertEquals(0, c.getExpires());
+
+        // check reverse order
+        buffer.clear();
+        buffer.append(CACHE_CONTROL_COMPOUND2);
+        h.parseHeader(buffer);
+
+        c = (CacheResult)m.invoke(null, 200, h, "text/html");
+        assertEquals(0, c.getExpires());
+    }
 }
diff --git a/tools/aapt/Bundle.h b/tools/aapt/Bundle.h
index 15570e4..fa84e93 100644
--- a/tools/aapt/Bundle.h
+++ b/tools/aapt/Bundle.h
@@ -40,6 +40,7 @@
           mWantUTF16(false), mValues(false),
           mCompressionMethod(0), mOutputAPKFile(NULL),
           mManifestPackageNameOverride(NULL), mInstrumentationPackageNameOverride(NULL),
+          mIsOverlayPackage(false),
           mAutoAddOverlay(false), mAssetSourceDir(NULL), mProguardFile(NULL),
           mAndroidManifestFile(NULL), mPublicOutputFile(NULL),
           mRClassDir(NULL), mResourceIntermediatesDir(NULL), mManifestMinSdkVersion(NULL),
@@ -92,6 +93,8 @@
     void setManifestPackageNameOverride(const char * val) { mManifestPackageNameOverride = val; }
     const char* getInstrumentationPackageNameOverride() const { return mInstrumentationPackageNameOverride; }
     void setInstrumentationPackageNameOverride(const char * val) { mInstrumentationPackageNameOverride = val; }
+    bool getIsOverlayPackage() const { return mIsOverlayPackage; }
+    void setIsOverlayPackage(bool val) { mIsOverlayPackage = val; }
     bool getAutoAddOverlay() { return mAutoAddOverlay; }
     void setAutoAddOverlay(bool val) { mAutoAddOverlay = val; }
 
@@ -219,6 +222,7 @@
     const char* mOutputAPKFile;
     const char* mManifestPackageNameOverride;
     const char* mInstrumentationPackageNameOverride;
+    bool        mIsOverlayPackage;
     bool        mAutoAddOverlay;
     const char* mAssetSourceDir;
     const char* mProguardFile;
diff --git a/tools/aapt/Main.cpp b/tools/aapt/Main.cpp
index 266a02f..1e63131 100644
--- a/tools/aapt/Main.cpp
+++ b/tools/aapt/Main.cpp
@@ -68,6 +68,7 @@
         "        [-S resource-sources [-S resource-sources ...]] "
         "        [-F apk-file] [-J R-file-dir] \\\n"
         "        [--product product1,product2,...] \\\n"
+        "        [-o] \\\n"
         "        [raw-files-dir [raw-files-dir] ...]\n"
         "\n"
         "   Package the android resources.  It will read assets and resources that are\n"
@@ -105,6 +106,7 @@
         "   -j  specify a jar or zip file containing classes to include\n"
         "   -k  junk path of file(s) added\n"
         "   -m  make package directories under location specified by -J\n"
+        "   -o  create overlay package (ie only resources; expects <overlay-package> in manifest)\n"
 #if 0
         "   -p  pseudolocalize the default configuration\n"
 #endif
@@ -275,6 +277,9 @@
             case 'm':
                 bundle.setMakePackageDirs(true);
                 break;
+            case 'o':
+                bundle.setIsOverlayPackage(true);
+                break;
 #if 0
             case 'p':
                 bundle.setPseudolocalize(true);
diff --git a/tools/aapt/ResourceTable.cpp b/tools/aapt/ResourceTable.cpp
index 68c3892..5c5b4fd 100644
--- a/tools/aapt/ResourceTable.cpp
+++ b/tools/aapt/ResourceTable.cpp
@@ -3705,7 +3705,9 @@
 {
     sp<Package> p = mPackages.valueFor(package);
     if (p == NULL) {
-        if (mIsAppPackage) {
+        if (mBundle->getIsOverlayPackage()) {
+            p = new Package(package, 0x00);
+        } else if (mIsAppPackage) {
             if (mHaveAppPackage) {
                 fprintf(stderr, "Adding multiple application package resources; only one is allowed.\n"
                                 "Use -x to create extended resources.\n");
diff --git a/voip/java/com/android/server/sip/SipHelper.java b/voip/java/com/android/server/sip/SipHelper.java
index ac580e7..4ee86b6 100644
--- a/voip/java/com/android/server/sip/SipHelper.java
+++ b/voip/java/com/android/server/sip/SipHelper.java
@@ -27,6 +27,8 @@
 import java.util.ArrayList;
 import java.util.EventObject;
 import java.util.List;
+import java.util.regex.Pattern;
+
 import javax.sip.ClientTransaction;
 import javax.sip.Dialog;
 import javax.sip.DialogTerminatedEvent;
@@ -215,9 +217,11 @@
             String tag) throws ParseException, SipException {
         FromHeader fromHeader = createFromHeader(userProfile, tag);
         ToHeader toHeader = createToHeader(userProfile);
+
+        String replaceStr = Pattern.quote(userProfile.getUserName() + "@");
         SipURI requestURI = mAddressFactory.createSipURI(
-                userProfile.getUriString().replaceFirst(
-                userProfile.getUserName() + "@", ""));
+                userProfile.getUriString().replaceFirst(replaceStr, ""));
+
         List<ViaHeader> viaHeaders = createViaHeaders();
         CallIdHeader callIdHeader = createCallIdHeader();
         CSeqHeader cSeqHeader = createCSeqHeader(requestType);
diff --git a/voip/jni/rtp/AudioGroup.cpp b/voip/jni/rtp/AudioGroup.cpp
index c031eee..41fedce 100644
--- a/voip/jni/rtp/AudioGroup.cpp
+++ b/voip/jni/rtp/AudioGroup.cpp
@@ -30,6 +30,7 @@
 
 #define LOG_TAG "AudioGroup"
 #include <cutils/atomic.h>
+#include <cutils/properties.h>
 #include <utils/Log.h>
 #include <utils/Errors.h>
 #include <utils/RefBase.h>
@@ -619,6 +620,14 @@
     if (mode < 0 || mode > LAST_MODE) {
         return false;
     }
+    //FIXME: temporary code to overcome echo and mic gain issues on herring board.
+    // Must be modified/removed when proper support for voice processing query and control
+    // is included in audio framework
+    char value[PROPERTY_VALUE_MAX];
+    property_get("ro.product.board", value, "");
+    if (mode == NORMAL && !strcmp(value, "herring")) {
+        mode = ECHO_SUPPRESSION;
+    }
     if (mode == ECHO_SUPPRESSION && AudioSystem::getParameters(
         0, String8("ec_supported")) == "ec_supported=yes") {
         mode = NORMAL;