Merge "AudioService: Fix monitorRotation for landscape applications"
diff --git a/api/current.txt b/api/current.txt
index a98fcfb..0a80cac 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -253,10 +253,13 @@
     field public static final int actionModeCloseDrawable = 16843484; // 0x10102dc
     field public static final int actionModeCopyDrawable = 16843538; // 0x1010312
     field public static final int actionModeCutDrawable = 16843537; // 0x1010311
+    field public static final int actionModeFindDrawable = 16843898; // 0x101047a
     field public static final int actionModePasteDrawable = 16843539; // 0x1010313
     field public static final int actionModeSelectAllDrawable = 16843646; // 0x101037e
+    field public static final int actionModeShareDrawable = 16843897; // 0x1010479
     field public static final int actionModeSplitBackground = 16843677; // 0x101039d
     field public static final int actionModeStyle = 16843668; // 0x1010394
+    field public static final int actionModeWebSearchDrawable = 16843899; // 0x101047b
     field public static final int actionOverflowButtonStyle = 16843510; // 0x10102f6
     field public static final int actionProviderClass = 16843657; // 0x1010389
     field public static final int actionViewClass = 16843516; // 0x10102fc
diff --git a/core/java/android/gesture/GestureOverlayView.java b/core/java/android/gesture/GestureOverlayView.java
index 2d47f28..e0bb6e0 100644
--- a/core/java/android/gesture/GestureOverlayView.java
+++ b/core/java/android/gesture/GestureOverlayView.java
@@ -635,7 +635,7 @@
             mStrokeBuffer.add(new GesturePoint(x, y, event.getEventTime()));
 
             if (mHandleGestureActions && !mIsGesturing) {
-                mTotalLength += (float) Math.sqrt(dx * dx + dy * dy);
+                mTotalLength += (float) Math.hypot(dx, dy);
 
                 if (mTotalLength > mGestureStrokeLengthThreshold) {
                     final OrientedBoundingBox box =
diff --git a/core/java/android/gesture/GestureStroke.java b/core/java/android/gesture/GestureStroke.java
index 1d0f0fe..bed904e 100644
--- a/core/java/android/gesture/GestureStroke.java
+++ b/core/java/android/gesture/GestureStroke.java
@@ -69,8 +69,7 @@
                 bx.bottom = p.y;
                 len = 0;
             } else {
-                len += Math.sqrt(Math.pow(p.x - tmpPoints[(i - 1) * 2], 2)
-                        + Math.pow(p.y - tmpPoints[(i -1 ) * 2 + 1], 2));
+                len += Math.hypot(p.x - tmpPoints[(i - 1) * 2], p.y - tmpPoints[(i -1 ) * 2 + 1]);
                 bx.union(p.x, p.y);
             }
             index++;
diff --git a/core/java/android/gesture/GestureUtils.java b/core/java/android/gesture/GestureUtils.java
index dd221fc..416279e 100644
--- a/core/java/android/gesture/GestureUtils.java
+++ b/core/java/android/gesture/GestureUtils.java
@@ -293,7 +293,7 @@
             }
             float deltaX = currentPointX - lstPointX;
             float deltaY = currentPointY - lstPointY;
-            float distance = (float) Math.sqrt(deltaX * deltaX + deltaY * deltaY);
+            float distance = (float) Math.hypot(deltaX, deltaY);
             if (distanceSoFar + distance >= increment) {
                 float ratio = (increment - distanceSoFar) / distance;
                 float nx = lstPointX + ratio * deltaX;
@@ -379,7 +379,7 @@
         for (int i = 0; i < count; i += 2) {
             float dx = points[i + 2] - points[i];
             float dy = points[i + 3] - points[i + 1];
-            sum += Math.sqrt(dx * dx + dy * dy);
+            sum += Math.hypot(dx, dy);
         }
         return sum;
     }
@@ -388,13 +388,13 @@
         float totalLen = computeTotalLength(points);
         float dx = points[2] - points[0];
         float dy = points[3] - points[1];
-        return (float) Math.sqrt(dx * dx + dy * dy) / totalLen;
+        return (float) Math.hypot(dx, dy) / totalLen;
     }
 
     static float computeStraightness(float[] points, float totalLen) {
         float dx = points[2] - points[0];
         float dy = points[3] - points[1];
-        return (float) Math.sqrt(dx * dx + dy * dy) / totalLen;
+        return (float) Math.hypot(dx, dy) / totalLen;
     }
 
     /**
diff --git a/core/java/android/hardware/GeomagneticField.java b/core/java/android/hardware/GeomagneticField.java
index 0369825..f1341a0 100644
--- a/core/java/android/hardware/GeomagneticField.java
+++ b/core/java/android/hardware/GeomagneticField.java
@@ -281,7 +281,7 @@
      * @return  Horizontal component of the field strength in nonoteslas.
      */
     public float getHorizontalStrength() {
-        return (float) Math.sqrt(mX * mX + mY * mY);
+        return (float) Math.hypot(mX, mY);
     }
 
     /**
diff --git a/core/java/android/os/Process.java b/core/java/android/os/Process.java
index 7bedfc1..0bcc20b 100644
--- a/core/java/android/os/Process.java
+++ b/core/java/android/os/Process.java
@@ -457,6 +457,7 @@
      * @param seInfo null-ok SELinux information for the new process.
      * @param abi non-null the ABI this app should be started with.
      * @param instructionSet null-ok the instruction set to use.
+     * @param appDataDir null-ok the data directory of the app.
      * @param zygoteArgs Additional arguments to supply to the zygote process.
      * 
      * @return An object that describes the result of the attempt to start the process.
@@ -472,11 +473,12 @@
                                   String seInfo,
                                   String abi,
                                   String instructionSet,
+                                  String appDataDir,
                                   String[] zygoteArgs) {
         try {
             return startViaZygote(processClass, niceName, uid, gid, gids,
                     debugFlags, mountExternal, targetSdkVersion, seInfo,
-                    abi, instructionSet, zygoteArgs);
+                    abi, instructionSet, appDataDir, zygoteArgs);
         } catch (ZygoteStartFailedEx ex) {
             Log.e(LOG_TAG,
                     "Starting VM process through Zygote failed");
@@ -580,6 +582,7 @@
      * @param seInfo null-ok SELinux information for the new process.
      * @param abi the ABI the process should use.
      * @param instructionSet null-ok the instruction set to use.
+     * @param appDataDir null-ok the data directory of the app.
      * @param extraArgs Additional arguments to supply to the zygote process.
      * @return An object that describes the result of the attempt to start the process.
      * @throws ZygoteStartFailedEx if process start failed for any reason
@@ -593,6 +596,7 @@
                                   String seInfo,
                                   String abi,
                                   String instructionSet,
+                                  String appDataDir,
                                   String[] extraArgs)
                                   throws ZygoteStartFailedEx {
         synchronized(Process.class) {
@@ -656,6 +660,10 @@
                 argsForZygote.add("--instruction-set=" + instructionSet);
             }
 
+            if (appDataDir != null) {
+                argsForZygote.add("--app-data-dir=" + appDataDir);
+            }
+
             argsForZygote.add(processClass);
 
             if (extraArgs != null) {
diff --git a/core/java/android/text/BoringLayout.java b/core/java/android/text/BoringLayout.java
index 77cd71e..52e6a2c 100644
--- a/core/java/android/text/BoringLayout.java
+++ b/core/java/android/text/BoringLayout.java
@@ -20,7 +20,6 @@
 import android.graphics.Paint;
 import android.graphics.Path;
 import android.text.style.ParagraphStyle;
-import android.util.FloatMath;
 
 /**
  * A BoringLayout is a very simple Layout implementation for text that
@@ -211,7 +210,7 @@
             TextLine line = TextLine.obtain();
             line.set(paint, source, 0, source.length(), Layout.DIR_LEFT_TO_RIGHT,
                     Layout.DIRS_ALL_LEFT_TO_RIGHT, false, null);
-            mMax = (int) FloatMath.ceil(line.metrics(null));
+            mMax = (int) Math.ceil(line.metrics(null));
             TextLine.recycle(line);
         }
 
@@ -305,7 +304,7 @@
             TextLine line = TextLine.obtain();
             line.set(paint, text, 0, length, Layout.DIR_LEFT_TO_RIGHT,
                     Layout.DIRS_ALL_LEFT_TO_RIGHT, false, null);
-            fm.width = (int) FloatMath.ceil(line.metrics(fm));
+            fm.width = (int) Math.ceil(line.metrics(fm));
             TextLine.recycle(line);
 
             return fm;
diff --git a/core/java/android/util/MathUtils.java b/core/java/android/util/MathUtils.java
index 13a692e..36d5b50 100644
--- a/core/java/android/util/MathUtils.java
+++ b/core/java/android/util/MathUtils.java
@@ -94,7 +94,7 @@
     public static float dist(float x1, float y1, float x2, float y2) {
         final float x = (x2 - x1);
         final float y = (y2 - y1);
-        return (float) Math.sqrt(x * x + y * y);
+        return (float) Math.hypot(x, y);
     }
 
     public static float dist(float x1, float y1, float z1, float x2, float y2, float z2) {
@@ -105,7 +105,7 @@
     }
 
     public static float mag(float a, float b) {
-        return (float) Math.sqrt(a * a + b * b);
+        return (float) Math.hypot(a, b);
     }
 
     public static float mag(float a, float b, float c) {
diff --git a/core/java/android/util/Spline.java b/core/java/android/util/Spline.java
index ed027eb..60d1e7c 100644
--- a/core/java/android/util/Spline.java
+++ b/core/java/android/util/Spline.java
@@ -88,7 +88,7 @@
                     throw new IllegalArgumentException("The control points must have "
                             + "monotonic Y values.");
                 }
-                float h = FloatMath.hypot(a, b);
+                float h = (float) Math.hypot(a, b);
                 if (h > 9f) {
                     float t = 3f / h;
                     m[i] = t * a * d[i];
diff --git a/core/java/android/view/ScaleGestureDetector.java b/core/java/android/view/ScaleGestureDetector.java
index 42a58a8..6508cca 100644
--- a/core/java/android/view/ScaleGestureDetector.java
+++ b/core/java/android/view/ScaleGestureDetector.java
@@ -21,7 +21,6 @@
 import android.os.Build;
 import android.os.Handler;
 import android.os.SystemClock;
-import android.util.FloatMath;
 
 /**
  * Detects scaling transformation gestures using the supplied {@link MotionEvent}s.
@@ -394,7 +393,7 @@
         if (inDoubleTapMode()) {
             span = spanY;
         } else {
-            span = FloatMath.sqrt(spanX * spanX + spanY * spanY);
+            span = (float) Math.hypot(spanX, spanY);
         }
 
         // Dispatch begin/end events as needed.
diff --git a/core/java/android/widget/OverScroller.java b/core/java/android/widget/OverScroller.java
index f218199..0d692eb 100644
--- a/core/java/android/widget/OverScroller.java
+++ b/core/java/android/widget/OverScroller.java
@@ -18,7 +18,6 @@
 
 import android.content.Context;
 import android.hardware.SensorManager;
-import android.util.FloatMath;
 import android.util.Log;
 import android.view.ViewConfiguration;
 import android.view.animation.AnimationUtils;
@@ -173,9 +172,7 @@
      * @return The original velocity less the deceleration, norm of the X and Y velocity vector.
      */
     public float getCurrVelocity() {
-        float squaredNorm = mScrollerX.mCurrVelocity * mScrollerX.mCurrVelocity;
-        squaredNorm += mScrollerY.mCurrVelocity * mScrollerY.mCurrVelocity;
-        return FloatMath.sqrt(squaredNorm);
+        return (float) Math.hypot(mScrollerX.mCurrVelocity, mScrollerY.mCurrVelocity);
     }
 
     /**
diff --git a/core/java/android/widget/Scroller.java b/core/java/android/widget/Scroller.java
index 3bfd39d..760e05c 100644
--- a/core/java/android/widget/Scroller.java
+++ b/core/java/android/widget/Scroller.java
@@ -19,7 +19,6 @@
 import android.content.Context;
 import android.hardware.SensorManager;
 import android.os.Build;
-import android.util.FloatMath;
 import android.view.ViewConfiguration;
 import android.view.animation.AnimationUtils;
 import android.view.animation.Interpolator;
@@ -436,7 +435,7 @@
 
             float dx = (float) (mFinalX - mStartX);
             float dy = (float) (mFinalY - mStartY);
-            float hyp = FloatMath.sqrt(dx * dx + dy * dy);
+            float hyp = (float) Math.hypot(dx, dy);
 
             float ndx = dx / hyp;
             float ndy = dy / hyp;
@@ -453,7 +452,7 @@
         mMode = FLING_MODE;
         mFinished = false;
 
-        float velocity = FloatMath.sqrt(velocityX * velocityX + velocityY * velocityY);
+        float velocity = (float) Math.hypot(velocityX, velocityY);
      
         mVelocity = velocity;
         mDuration = getSplineFlingDuration(velocity);
diff --git a/core/java/android/widget/StackView.java b/core/java/android/widget/StackView.java
index 6853660..7df0a31 100644
--- a/core/java/android/widget/StackView.java
+++ b/core/java/android/widget/StackView.java
@@ -1043,10 +1043,8 @@
             if (mView != null) {
                 final LayoutParams viewLp = (LayoutParams) mView.getLayoutParams();
 
-                float d = (float) Math.sqrt(Math.pow(viewLp.horizontalOffset, 2) +
-                        Math.pow(viewLp.verticalOffset, 2));
-                float maxd = (float) Math.sqrt(Math.pow(mSlideAmount, 2) +
-                        Math.pow(0.4f * mSlideAmount, 2));
+                float d = (float) Math.hypot(viewLp.horizontalOffset, viewLp.verticalOffset);
+                float maxd = (float) Math.hypot(mSlideAmount, 0.4f * mSlideAmount);
 
                 if (velocity == 0) {
                     return (invert ? (1 - d / maxd) : d / maxd) * DEFAULT_ANIMATION_DURATION;
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index 5ece016..3f26dd3 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -92,7 +92,6 @@
 import android.text.style.UpdateAppearance;
 import android.text.util.Linkify;
 import android.util.AttributeSet;
-import android.util.FloatMath;
 import android.util.Log;
 import android.util.TypedValue;
 import android.view.AccessibilityIterators.TextSegmentIterator;
@@ -4556,7 +4555,7 @@
                      * make sure the entire cursor gets invalidated instead of
                      * sometimes missing half a pixel.
                      */
-                    float thick = FloatMath.ceil(mTextPaint.getStrokeWidth());
+                    float thick = (float) Math.ceil(mTextPaint.getStrokeWidth());
                     if (thick < 1.0f) {
                         thick = 1.0f;
                     }
@@ -4566,10 +4565,10 @@
                     // mHighlightPath is guaranteed to be non null at that point.
                     mHighlightPath.computeBounds(TEMP_RECTF, false);
 
-                    invalidate((int) FloatMath.floor(horizontalPadding + TEMP_RECTF.left - thick),
-                            (int) FloatMath.floor(verticalPadding + TEMP_RECTF.top - thick),
-                            (int) FloatMath.ceil(horizontalPadding + TEMP_RECTF.right + thick),
-                            (int) FloatMath.ceil(verticalPadding + TEMP_RECTF.bottom + thick));
+                    invalidate((int) Math.floor(horizontalPadding + TEMP_RECTF.left - thick),
+                            (int) Math.floor(verticalPadding + TEMP_RECTF.top - thick),
+                            (int) Math.ceil(horizontalPadding + TEMP_RECTF.right + thick),
+                            (int) Math.ceil(verticalPadding + TEMP_RECTF.bottom + thick));
                 }
             } else {
                 for (int i = 0; i < mEditor.mCursorCount; i++) {
@@ -6236,7 +6235,7 @@
             max = Math.max(max, layout.getLineWidth(i));
         }
 
-        return (int) FloatMath.ceil(max);
+        return (int) Math.ceil(max);
     }
 
     /**
@@ -6313,7 +6312,7 @@
 
             if (boring == null || boring == UNKNOWN_BORING) {
                 if (des < 0) {
-                    des = (int) FloatMath.ceil(Layout.getDesiredWidth(mTransformed, mTextPaint));
+                    des = (int) Math.ceil(Layout.getDesiredWidth(mTransformed, mTextPaint));
                 }
                 width = des;
             } else {
@@ -6343,7 +6342,7 @@
 
                 if (hintBoring == null || hintBoring == UNKNOWN_BORING) {
                     if (hintDes < 0) {
-                        hintDes = (int) FloatMath.ceil(Layout.getDesiredWidth(mHint, mTextPaint));
+                        hintDes = (int) Math.ceil(Layout.getDesiredWidth(mHint, mTextPaint));
                     }
                     hintWidth = hintDes;
                 } else {
@@ -6649,8 +6648,8 @@
              * keep leading edge in view.
              */
 
-            int left = (int) FloatMath.floor(layout.getLineLeft(line));
-            int right = (int) FloatMath.ceil(layout.getLineRight(line));
+            int left = (int) Math.floor(layout.getLineLeft(line));
+            int right = (int) Math.ceil(layout.getLineRight(line));
 
             if (right - left < hspace) {
                 scrollx = (right + left) / 2 - hspace / 2;
@@ -6662,10 +6661,10 @@
                 }
             }
         } else if (a == Layout.Alignment.ALIGN_RIGHT) {
-            int right = (int) FloatMath.ceil(layout.getLineRight(line));
+            int right = (int) Math.ceil(layout.getLineRight(line));
             scrollx = right - hspace;
         } else { // a == Layout.Alignment.ALIGN_LEFT (will also be the default)
-            scrollx = (int) FloatMath.floor(layout.getLineLeft(line));
+            scrollx = (int) Math.floor(layout.getLineLeft(line));
         }
 
         if (ht < vspace) {
@@ -6740,8 +6739,8 @@
         final int top = layout.getLineTop(line);
         final int bottom = layout.getLineTop(line + 1);
 
-        int left = (int) FloatMath.floor(layout.getLineLeft(line));
-        int right = (int) FloatMath.ceil(layout.getLineRight(line));
+        int left = (int) Math.floor(layout.getLineLeft(line));
+        int right = (int) Math.ceil(layout.getLineRight(line));
         int ht = layout.getHeight();
 
         int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight();
diff --git a/core/java/com/android/internal/os/Zygote.java b/core/java/com/android/internal/os/Zygote.java
index f23326c..fced092 100644
--- a/core/java/com/android/internal/os/Zygote.java
+++ b/core/java/com/android/internal/os/Zygote.java
@@ -76,24 +76,25 @@
      * (and replaced by /dev/null) after forking.  An integer value
      * of -1 in any entry in the array means "ignore this one".
      * @param instructionSet null-ok the instruction set to use.
+     * @param appDataDir null-ok the data directory of the app.
      *
      * @return 0 if this is the child, pid of the child
      * if this is the parent, or -1 on error.
      */
     public static int forkAndSpecialize(int uid, int gid, int[] gids, int debugFlags,
           int[][] rlimits, int mountExternal, String seInfo, String niceName, int[] fdsToClose,
-          String instructionSet) {
+          String instructionSet, String appDataDir) {
         VM_HOOKS.preFork();
         int pid = nativeForkAndSpecialize(
                   uid, gid, gids, debugFlags, rlimits, mountExternal, seInfo, niceName, fdsToClose,
-                  instructionSet);
+                  instructionSet, appDataDir);
         VM_HOOKS.postForkCommon();
         return pid;
     }
 
     native private static int nativeForkAndSpecialize(int uid, int gid, int[] gids,int debugFlags,
           int[][] rlimits, int mountExternal, String seInfo, String niceName, int[] fdsToClose,
-          String instructionSet);
+          String instructionSet, String appDataDir);
 
     /**
      * Special method to start the system server process. In addition to the
diff --git a/core/java/com/android/internal/os/ZygoteConnection.java b/core/java/com/android/internal/os/ZygoteConnection.java
index 6c1901b..0b32b37 100644
--- a/core/java/com/android/internal/os/ZygoteConnection.java
+++ b/core/java/com/android/internal/os/ZygoteConnection.java
@@ -222,7 +222,8 @@
 
             pid = Zygote.forkAndSpecialize(parsedArgs.uid, parsedArgs.gid, parsedArgs.gids,
                     parsedArgs.debugFlags, rlimits, parsedArgs.mountExternal, parsedArgs.seInfo,
-                    parsedArgs.niceName, fdsToClose, parsedArgs.instructionSet);
+                    parsedArgs.niceName, fdsToClose, parsedArgs.instructionSet,
+                    parsedArgs.appDataDir);
         } catch (IOException ex) {
             logAndPrintError(newStderr, "Exception creating pipe", ex);
         } catch (ErrnoException ex) {
@@ -380,6 +381,12 @@
         String instructionSet;
 
         /**
+         * The app data directory. May be null, e.g., for the system server. Note that this might
+         * not be reliable in the case of process-sharing apps.
+         */
+        String appDataDir;
+
+        /**
          * Constructs instance and parses args
          * @param args zygote command-line args
          * @throws IllegalArgumentException
@@ -536,6 +543,8 @@
                     abiListQuery = true;
                 } else if (arg.startsWith("--instruction-set=")) {
                     instructionSet = arg.substring(arg.indexOf('=') + 1);
+                } else if (arg.startsWith("--app-data-dir=")) {
+                    appDataDir = arg.substring(arg.indexOf('=') + 1);
                 } else {
                     break;
                 }
diff --git a/core/java/com/android/internal/widget/multiwaveview/GlowPadView.java b/core/java/com/android/internal/widget/multiwaveview/GlowPadView.java
index cd1ccd3..bc058b6 100644
--- a/core/java/com/android/internal/widget/multiwaveview/GlowPadView.java
+++ b/core/java/com/android/internal/widget/multiwaveview/GlowPadView.java
@@ -857,7 +857,7 @@
             // tx and ty are relative to wave center
             float tx = eventX - mWaveCenterX;
             float ty = eventY - mWaveCenterY;
-            float touchRadius = (float) Math.sqrt(dist2(tx, ty));
+            float touchRadius = (float) Math.hypot(tx, ty);
             final float scale = touchRadius > mOuterRadius ? mOuterRadius / touchRadius : 1.0f;
             float limitX = tx * scale;
             float limitY = ty * scale;
diff --git a/core/java/com/android/internal/widget/multiwaveview/MultiWaveView.java b/core/java/com/android/internal/widget/multiwaveview/MultiWaveView.java
index e22d1e8..0a3d509c 100644
--- a/core/java/com/android/internal/widget/multiwaveview/MultiWaveView.java
+++ b/core/java/com/android/internal/widget/multiwaveview/MultiWaveView.java
@@ -832,7 +832,7 @@
             // tx and ty are relative to wave center
             float tx = eventX - mWaveCenterX;
             float ty = eventY - mWaveCenterY;
-            float touchRadius = (float) Math.sqrt(dist2(tx, ty));
+            float touchRadius = (float) Math.hypot(tx, ty);
             final float scale = touchRadius > mOuterRadius ? mOuterRadius / touchRadius : 1.0f;
             float limitX = tx * scale;
             float limitY = ty * scale;
diff --git a/core/java/com/android/internal/widget/multiwaveview/PointCloud.java b/core/java/com/android/internal/widget/multiwaveview/PointCloud.java
index f299935..6f26b99 100644
--- a/core/java/com/android/internal/widget/multiwaveview/PointCloud.java
+++ b/core/java/com/android/internal/widget/multiwaveview/PointCloud.java
@@ -22,7 +22,6 @@
 import android.graphics.Color;
 import android.graphics.Paint;
 import android.graphics.drawable.Drawable;
-import android.util.FloatMath;
 import android.util.Log;
 
 public class PointCloud {
@@ -151,8 +150,8 @@
             float eta = PI/2.0f;
             float dEta = 2.0f * PI / pointsInBand;
             for (int i = 0; i < pointsInBand; i++) {
-                float x = r * FloatMath.cos(eta);
-                float y = r * FloatMath.sin(eta);
+                float x = r * (float) Math.cos(eta);
+                float y = r * (float) Math.sin(eta);
                 eta += dEta;
                 mPointCloud.add(new Point(x, y, r));
             }
@@ -167,32 +166,24 @@
         return mScale;
     }
 
-    private static float hypot(float x, float y) {
-        return FloatMath.sqrt(x*x + y*y);
-    }
-
-    private static float max(float a, float b) {
-        return a > b ? a : b;
-    }
-
     public int getAlphaForPoint(Point point) {
         // Contribution from positional glow
-        float glowDistance = hypot(glowManager.x - point.x, glowManager.y - point.y);
+        float glowDistance = (float) Math.hypot(glowManager.x - point.x, glowManager.y - point.y);
         float glowAlpha = 0.0f;
         if (glowDistance < glowManager.radius) {
-            float cosf = FloatMath.cos(PI * 0.25f * glowDistance / glowManager.radius);
-            glowAlpha = glowManager.alpha * max(0.0f, (float) Math.pow(cosf, 10.0f));
+            float cosf = (float) Math.cos(PI * 0.25f * glowDistance / glowManager.radius);
+            glowAlpha = glowManager.alpha * Math.max(0.0f, (float) Math.pow(cosf, 10.0f));
         }
 
         // Compute contribution from Wave
-        float radius = hypot(point.x, point.y);
+        float radius = (float) Math.hypot(point.x, point.y);
         float waveAlpha = 0.0f;
         if (radius < waveManager.radius * 2) {
             float distanceToWaveRing = (radius - waveManager.radius);
-            float cosf = FloatMath.cos(PI * 0.5f * distanceToWaveRing / waveManager.radius);
-            waveAlpha = waveManager.alpha * max(0.0f, (float) Math.pow(cosf, 6.0f));
+            float cosf = (float) Math.cos(PI * 0.5f * distanceToWaveRing / waveManager.radius);
+            waveAlpha = waveManager.alpha * Math.max(0.0f, (float) Math.pow(cosf, 6.0f));
         }
-        return (int) (max(glowAlpha, waveAlpha) * 255);
+        return (int) (Math.max(glowAlpha, waveAlpha) * 255);
     }
 
     private float interp(float min, float max, float f) {
diff --git a/core/jni/android_util_Process.cpp b/core/jni/android_util_Process.cpp
index fbe7a17..7b8ac801 100644
--- a/core/jni/android_util_Process.cpp
+++ b/core/jni/android_util_Process.cpp
@@ -348,7 +348,6 @@
 jboolean android_os_Process_setOomAdj(JNIEnv* env, jobject clazz,
                                       jint pid, jint adj)
 {
-#ifdef HAVE_OOM_ADJ
     char text[64];
     sprintf(text, "/proc/%d/oom_adj", pid);
     int fd = open(text, O_WRONLY);
@@ -358,8 +357,6 @@
         close(fd);
     }
     return true;
-#endif
-    return false;
 }
 
 jboolean android_os_Process_setSwappiness(JNIEnv *env, jobject clazz,
diff --git a/core/jni/com_android_internal_os_Zygote.cpp b/core/jni/com_android_internal_os_Zygote.cpp
index bfbeca1..6dc29ed 100644
--- a/core/jni/com_android_internal_os_Zygote.cpp
+++ b/core/jni/com_android_internal_os_Zygote.cpp
@@ -48,6 +48,8 @@
 #include "ScopedPrimitiveArray.h"
 #include "ScopedUtfChars.h"
 
+#include "nativebridge/native_bridge.h"
+
 namespace {
 
 using android::String8;
@@ -126,7 +128,7 @@
 
   int err = sigaction(SIGCHLD, &sa, NULL);
   if (err < 0) {
-    ALOGW("Error setting SIGCHLD handler: %d", errno);
+    ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
   }
 }
 
@@ -138,7 +140,7 @@
 
   int err = sigaction(SIGCHLD, &sa, NULL);
   if (err < 0) {
-    ALOGW("Error unsetting SIGCHLD handler: %d", errno);
+    ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno));
   }
 }
 
@@ -246,7 +248,17 @@
 
 // Create a private mount namespace and bind mount appropriate emulated
 // storage for the given user.
-static bool MountEmulatedStorage(uid_t uid, jint mount_mode) {
+static bool MountEmulatedStorage(uid_t uid, jint mount_mode, bool force_mount_namespace) {
+  if (mount_mode == MOUNT_EXTERNAL_NONE && !force_mount_namespace) {
+    return true;
+  }
+
+  // Create a second private mount namespace for our process
+  if (unshare(CLONE_NEWNS) == -1) {
+      ALOGW("Failed to unshare(): %s", strerror(errno));
+      return false;
+  }
+
   if (mount_mode == MOUNT_EXTERNAL_NONE) {
     return true;
   }
@@ -254,12 +266,6 @@
   // See storage config details at http://source.android.com/tech/storage/
   userid_t user_id = multiuser_get_user_id(uid);
 
-  // Create a second private mount namespace for our process
-  if (unshare(CLONE_NEWNS) == -1) {
-      ALOGW("Failed to unshare(): %d", errno);
-      return false;
-  }
-
   // Create bind mounts to expose external storage
   if (mount_mode == MOUNT_EXTERNAL_MULTIUSER || mount_mode == MOUNT_EXTERNAL_MULTIUSER_ALL) {
     // These paths must already be created by init.rc
@@ -286,14 +292,15 @@
     if (mount_mode == MOUNT_EXTERNAL_MULTIUSER_ALL) {
       // Mount entire external storage tree for all users
       if (TEMP_FAILURE_RETRY(mount(source, target, NULL, MS_BIND, NULL)) == -1) {
-        ALOGW("Failed to mount %s to %s :%d", source, target, errno);
+        ALOGW("Failed to mount %s to %s: %s", source, target, strerror(errno));
         return false;
       }
     } else {
       // Only mount user-specific external storage
-      if (TEMP_FAILURE_RETRY(
-              mount(source_user.string(), target_user.string(), NULL, MS_BIND, NULL)) == -1) {
-        ALOGW("Failed to mount %s to %s: %d", source_user.string(), target_user.string(), errno);
+      if (TEMP_FAILURE_RETRY(mount(source_user.string(), target_user.string(), NULL,
+                                   MS_BIND, NULL)) == -1) {
+        ALOGW("Failed to mount %s to %s: %s", source_user.string(), target_user.string(),
+              strerror(errno));
         return false;
       }
     }
@@ -305,7 +312,7 @@
     // Finally, mount user-specific path into place for legacy users
     if (TEMP_FAILURE_RETRY(
             mount(target_user.string(), legacy, NULL, MS_BIND | MS_REC, NULL)) == -1) {
-      ALOGW("Failed to mount %s to %s: %d", target_user.string(), legacy, errno);
+      ALOGW("Failed to mount %s to %s: %s", target_user.string(), legacy, strerror(errno));
       return false;
     }
   } else {
@@ -356,13 +363,13 @@
   for (i = 0; i < count; i++) {
     devnull = open("/dev/null", O_RDWR);
     if (devnull < 0) {
-      ALOGE("Failed to open /dev/null");
+      ALOGE("Failed to open /dev/null: %s", strerror(errno));
       RuntimeAbort(env);
       continue;
     }
-    ALOGV("Switching descriptor %d to /dev/null: %d", ar[i], errno);
+    ALOGV("Switching descriptor %d to /dev/null: %s", ar[i], strerror(errno));
     if (dup2(devnull, ar[i]) < 0) {
-      ALOGE("Failed dup2() on descriptor %d", ar[i]);
+      ALOGE("Failed dup2() on descriptor %d: %s", ar[i], strerror(errno));
       RuntimeAbort(env);
     }
     close(devnull);
@@ -392,7 +399,7 @@
   strlcpy(buf, s, sizeof(buf)-1);
   errno = pthread_setname_np(pthread_self(), buf);
   if (errno != 0) {
-    ALOGW("Unable to set the name of current thread to '%s'", buf);
+    ALOGW("Unable to set the name of current thread to '%s': %s", buf, strerror(errno));
   }
 }
 
@@ -403,7 +410,7 @@
                                      jint mount_external,
                                      jstring java_se_info, jstring java_se_name,
                                      bool is_system_server, jintArray fdsToClose,
-                                     jstring instructionSet) {
+                                     jstring instructionSet, jstring dataDir) {
   SetSigChldHandler();
 
   pid_t pid = fork();
@@ -422,8 +429,14 @@
 
     DropCapabilitiesBoundingSet(env);
 
-    if (!MountEmulatedStorage(uid, mount_external)) {
-      ALOGW("Failed to mount emulated storage: %d", errno);
+    bool need_native_bridge = false;
+    if (instructionSet != NULL) {
+      ScopedUtfChars isa_string(env, instructionSet);
+      need_native_bridge = android::NeedsNativeBridge(isa_string.c_str());
+    }
+
+    if (!MountEmulatedStorage(uid, mount_external, need_native_bridge)) {
+      ALOGW("Failed to mount emulated storage: %s", strerror(errno));
       if (errno == ENOTCONN || errno == EROFS) {
         // When device is actively encrypting, we get ENOTCONN here
         // since FUSE was mounted before the framework restarted.
@@ -440,15 +453,26 @@
 
     SetRLimits(env, javaRlimits);
 
+    if (!is_system_server && need_native_bridge) {
+      // Set the environment for the apps running with native bridge.
+      ScopedUtfChars isa_string(env, instructionSet);  // Known non-null because of need_native_...
+      if (dataDir == NULL) {
+        android::PreInitializeNativeBridge(NULL, isa_string.c_str());
+      } else {
+        ScopedUtfChars data_dir(env, dataDir);
+        android::PreInitializeNativeBridge(data_dir.c_str(), isa_string.c_str());
+      }
+    }
+
     int rc = setresgid(gid, gid, gid);
     if (rc == -1) {
-      ALOGE("setresgid(%d) failed", gid);
+      ALOGE("setresgid(%d) failed: %s", gid, strerror(errno));
       RuntimeAbort(env);
     }
 
     rc = setresuid(uid, uid, uid);
     if (rc == -1) {
-      ALOGE("setresuid(%d) failed", uid);
+      ALOGE("setresuid(%d) failed: %s", uid, strerror(errno));
       RuntimeAbort(env);
     }
 
@@ -457,7 +481,7 @@
         int old_personality = personality(0xffffffff);
         int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
         if (new_personality == -1) {
-            ALOGW("personality(%d) failed", new_personality);
+            ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
         }
     }
 
@@ -525,9 +549,10 @@
         JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
         jint debug_flags, jobjectArray rlimits,
         jint mount_external, jstring se_info, jstring se_name,
-        jintArray fdsToClose, jstring instructionSet) {
+        jintArray fdsToClose, jstring instructionSet, jstring appDataDir) {
     return ForkAndSpecializeCommon(env, uid, gid, gids, debug_flags,
-            rlimits, 0, 0, mount_external, se_info, se_name, false, fdsToClose, instructionSet);
+            rlimits, 0, 0, mount_external, se_info, se_name, false, fdsToClose,
+            instructionSet, appDataDir);
 }
 
 static jint com_android_internal_os_Zygote_nativeForkSystemServer(
@@ -537,7 +562,8 @@
   pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
                                       debug_flags, rlimits,
                                       permittedCapabilities, effectiveCapabilities,
-                                      MOUNT_EXTERNAL_NONE, NULL, NULL, true, NULL, NULL);
+                                      MOUNT_EXTERNAL_NONE, NULL, NULL, true, NULL,
+                                      NULL, NULL);
   if (pid > 0) {
       // The zygote process checks whether the child process has died or not.
       ALOGI("System server process %d has been created", pid);
@@ -556,7 +582,7 @@
 
 static JNINativeMethod gMethods[] = {
     { "nativeForkAndSpecialize",
-      "(II[II[[IILjava/lang/String;Ljava/lang/String;[ILjava/lang/String;)I",
+      "(II[II[[IILjava/lang/String;Ljava/lang/String;[ILjava/lang/String;Ljava/lang/String;)I",
       (void *) com_android_internal_os_Zygote_nativeForkAndSpecialize },
     { "nativeForkSystemServer", "(II[II[[IJJ)I",
       (void *) com_android_internal_os_Zygote_nativeForkSystemServer }
diff --git a/core/res/res/values/public.xml b/core/res/res/values/public.xml
index 8187939..34f6afb 100644
--- a/core/res/res/values/public.xml
+++ b/core/res/res/values/public.xml
@@ -568,6 +568,9 @@
   <public type="attr" name="listChoiceIndicatorMultiple" id="0x0101021a" />
   <public type="attr" name="versionCode" id="0x0101021b" />
   <public type="attr" name="versionName" id="0x0101021c" />
+  <public type="attr" name="actionModeShareDrawable" id="0x01010479" />
+  <public type="attr" name="actionModeFindDrawable" id="0x0101047a" />
+  <public type="attr" name="actionModeWebSearchDrawable" id="0x0101047b" />
 
   <public type="id" name="background" id="0x01020000" />
   <public type="id" name="checkbox" id="0x01020001" />
diff --git a/graphics/java/android/graphics/ColorMatrix.java b/graphics/java/android/graphics/ColorMatrix.java
index e3596c8..0bfd07be 100644
--- a/graphics/java/android/graphics/ColorMatrix.java
+++ b/graphics/java/android/graphics/ColorMatrix.java
@@ -16,8 +16,6 @@
 
 package android.graphics;
 
-import android.util.FloatMath;
-
 /**
  *  4x5 matrix for transforming the color+alpha components of a Bitmap.
  *  The matrix is stored in a single array, and its treated as follows:
@@ -118,9 +116,9 @@
      */
     public void setRotate(int axis, float degrees) {
         reset();
-        float radians = degrees * (float)Math.PI / 180;
-        float cosine = FloatMath.cos(radians);
-        float sine = FloatMath.sin(radians);
+        double radians = degrees * Math.PI / 180d;
+        float cosine = (float) Math.cos(radians);
+        float sine = (float) Math.sin(radians);
         switch (axis) {
         // Rotation around the red color
         case 0:
diff --git a/graphics/java/android/graphics/PointF.java b/graphics/java/android/graphics/PointF.java
index ee38dbb..8e4288e 100644
--- a/graphics/java/android/graphics/PointF.java
+++ b/graphics/java/android/graphics/PointF.java
@@ -18,7 +18,6 @@
 
 import android.os.Parcel;
 import android.os.Parcelable;
-import android.util.FloatMath;
 
 
 /**
@@ -109,7 +108,7 @@
      * Returns the euclidian distance from (0,0) to (x,y)
      */
     public static float length(float x, float y) {
-        return FloatMath.sqrt(x * x + y * y);
+        return (float) Math.hypot(x, y);
     }
 
     /**
diff --git a/graphics/java/android/graphics/RectF.java b/graphics/java/android/graphics/RectF.java
index 53178b0..f5cedfa 100644
--- a/graphics/java/android/graphics/RectF.java
+++ b/graphics/java/android/graphics/RectF.java
@@ -20,7 +20,6 @@
 
 import android.os.Parcel;
 import android.os.Parcelable;
-import android.util.FloatMath;
 import com.android.internal.util.FastMath;
 
 /**
@@ -450,8 +449,8 @@
      * floor of top and left, and the ceiling of right and bottom.
      */
     public void roundOut(Rect dst) {
-        dst.set((int) FloatMath.floor(left), (int) FloatMath.floor(top),
-                (int) FloatMath.ceil(right), (int) FloatMath.ceil(bottom));
+        dst.set((int) Math.floor(left), (int) Math.floor(top),
+                (int) Math.ceil(right), (int) Math.ceil(bottom));
     }
 
     /**
diff --git a/media/mca/filterfw/java/android/filterfw/geometry/Point.java b/media/mca/filterfw/java/android/filterfw/geometry/Point.java
index 8207c72c..4682a0d 100644
--- a/media/mca/filterfw/java/android/filterfw/geometry/Point.java
+++ b/media/mca/filterfw/java/android/filterfw/geometry/Point.java
@@ -70,7 +70,7 @@
     }
 
     public float length() {
-        return (float)Math.sqrt(x*x + y*y);
+        return (float)Math.hypot(x, y);
     }
 
     public float distanceTo(Point p) {
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/camera/CameraFunctionalTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/camera/CameraFunctionalTest.java
index e6f0aaf..d12ef2e 100644
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/camera/CameraFunctionalTest.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/camera/CameraFunctionalTest.java
@@ -37,7 +37,6 @@
 import android.os.Looper;
 import android.test.ActivityInstrumentationTestCase2;
 import android.test.suitebuilder.annotation.LargeTest;
-import android.util.FloatMath;
 import android.util.Log;
 import android.view.SurfaceHolder;
 import com.android.mediaframeworktest.CameraStressTestRunner;
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/camera/CameraPairwiseTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/camera/CameraPairwiseTest.java
index 61b708a..8f67598 100644
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/camera/CameraPairwiseTest.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/camera/CameraPairwiseTest.java
@@ -24,7 +24,6 @@
 import android.os.Looper;
 import android.test.ActivityInstrumentationTestCase2;
 import android.test.suitebuilder.annotation.LargeTest;
-import android.util.FloatMath;
 import android.util.Log;
 import android.view.SurfaceHolder;
 
diff --git a/packages/SystemUI/src/com/android/systemui/recent/RecentsHorizontalScrollView.java b/packages/SystemUI/src/com/android/systemui/recent/RecentsHorizontalScrollView.java
index be42bc0..a56d5e7 100644
--- a/packages/SystemUI/src/com/android/systemui/recent/RecentsHorizontalScrollView.java
+++ b/packages/SystemUI/src/com/android/systemui/recent/RecentsHorizontalScrollView.java
@@ -23,7 +23,6 @@
 import android.graphics.Canvas;
 import android.util.AttributeSet;
 import android.util.DisplayMetrics;
-import android.util.FloatMath;
 import android.util.Log;
 import android.view.MotionEvent;
 import android.view.View;
@@ -351,7 +350,7 @@
         View child = mAdapter.createView(mLinearLayout);
         child.measure(childWidthMeasureSpec, childheightMeasureSpec);
         mNumItemsInOneScreenful =
-                (int) FloatMath.ceil(dm.widthPixels / (float) child.getMeasuredWidth());
+                (int) Math.ceil(dm.widthPixels / (double) child.getMeasuredWidth());
         addToRecycledViews(child);
 
         for (int i = 0; i < mNumItemsInOneScreenful - 1; i++) {
diff --git a/packages/SystemUI/src/com/android/systemui/recent/RecentsVerticalScrollView.java b/packages/SystemUI/src/com/android/systemui/recent/RecentsVerticalScrollView.java
index 6dddc39..569c418 100644
--- a/packages/SystemUI/src/com/android/systemui/recent/RecentsVerticalScrollView.java
+++ b/packages/SystemUI/src/com/android/systemui/recent/RecentsVerticalScrollView.java
@@ -23,7 +23,6 @@
 import android.graphics.Canvas;
 import android.util.AttributeSet;
 import android.util.DisplayMetrics;
-import android.util.FloatMath;
 import android.util.Log;
 import android.view.MotionEvent;
 import android.view.View;
@@ -361,7 +360,7 @@
         View child = mAdapter.createView(mLinearLayout);
         child.measure(childWidthMeasureSpec, childheightMeasureSpec);
         mNumItemsInOneScreenful =
-                (int) FloatMath.ceil(dm.heightPixels / (float) child.getMeasuredHeight());
+                (int) Math.ceil(dm.heightPixels / (double) child.getMeasuredHeight());
         addToRecycledViews(child);
 
         for (int i = 0; i < mNumItemsInOneScreenful - 1; i++) {
diff --git a/packages/WallpaperCropper/src/com/android/wallpapercropper/CropView.java b/packages/WallpaperCropper/src/com/android/wallpapercropper/CropView.java
index c3ef302..4405207 100644
--- a/packages/WallpaperCropper/src/com/android/wallpapercropper/CropView.java
+++ b/packages/WallpaperCropper/src/com/android/wallpapercropper/CropView.java
@@ -21,7 +21,6 @@
 import android.graphics.Point;
 import android.graphics.RectF;
 import android.util.AttributeSet;
-import android.util.FloatMath;
 import android.view.MotionEvent;
 import android.view.ScaleGestureDetector;
 import android.view.ScaleGestureDetector.OnScaleGestureListener;
@@ -300,12 +299,12 @@
                     adjustment[0] = (edges.right - getWidth()) / scale;
                 }
                 if (edges.top > 0) {
-                    adjustment[1] = FloatMath.ceil(edges.top / scale);
+                    adjustment[1] = (float) Math.ceil(edges.top / scale);
                 } else if (edges.bottom < getHeight()) {
                     adjustment[1] = (edges.bottom - getHeight()) / scale;
                 }
                 for (int dim = 0; dim <= 1; dim++) {
-                    if (coef[dim] > 0) adjustment[dim] = FloatMath.ceil(adjustment[dim]);
+                    if (coef[dim] > 0) adjustment[dim] = (float) Math.ceil(adjustment[dim]);
                 }
 
                 mInverseRotateMatrix.mapPoints(adjustment);
diff --git a/policy/src/com/android/internal/policy/impl/WindowOrientationListener.java b/policy/src/com/android/internal/policy/impl/WindowOrientationListener.java
index 0c77556..d927592 100644
--- a/policy/src/com/android/internal/policy/impl/WindowOrientationListener.java
+++ b/policy/src/com/android/internal/policy/impl/WindowOrientationListener.java
@@ -23,7 +23,6 @@
 import android.hardware.SensorManager;
 import android.os.Handler;
 import android.os.SystemProperties;
-import android.util.FloatMath;
 import android.util.Log;
 import android.util.Slog;
 
@@ -401,7 +400,7 @@
                 if (LOG) {
                     Slog.v(TAG, "Raw acceleration vector: "
                             + "x=" + x + ", y=" + y + ", z=" + z
-                            + ", magnitude=" + FloatMath.sqrt(x * x + y * y + z * z));
+                            + ", magnitude=" + Math.sqrt(x * x + y * y + z * z));
                 }
 
                 // Apply a low-pass filter to the acceleration up vector in cartesian space.
@@ -428,7 +427,7 @@
                     if (LOG) {
                         Slog.v(TAG, "Filtered acceleration vector: "
                                 + "x=" + x + ", y=" + y + ", z=" + z
-                                + ", magnitude=" + FloatMath.sqrt(x * x + y * y + z * z));
+                                + ", magnitude=" + Math.sqrt(x * x + y * y + z * z));
                     }
                     skipSample = false;
                 }
@@ -442,7 +441,7 @@
                 boolean isSwinging = false;
                 if (!skipSample) {
                     // Calculate the magnitude of the acceleration vector.
-                    final float magnitude = FloatMath.sqrt(x * x + y * y + z * z);
+                    final float magnitude = (float) Math.sqrt(x * x + y * y + z * z);
                     if (magnitude < NEAR_ZERO_MAGNITUDE) {
                         if (LOG) {
                             Slog.v(TAG, "Ignoring sensor data, magnitude too close to zero.");
diff --git a/services/java/com/android/server/TwilightCalculator.java b/services/java/com/android/server/TwilightCalculator.java
index a5c93b5..5839b16 100644
--- a/services/java/com/android/server/TwilightCalculator.java
+++ b/services/java/com/android/server/TwilightCalculator.java
@@ -17,7 +17,6 @@
 package com.android.server;
 
 import android.text.format.DateUtils;
-import android.util.FloatMath;
 
 /** @hide */
 public class TwilightCalculator {
@@ -75,24 +74,24 @@
         final float meanAnomaly = 6.240059968f + daysSince2000 * 0.01720197f;
 
         // true anomaly
-        final float trueAnomaly = meanAnomaly + C1 * FloatMath.sin(meanAnomaly) + C2
-                * FloatMath.sin(2 * meanAnomaly) + C3 * FloatMath.sin(3 * meanAnomaly);
+        final double trueAnomaly = meanAnomaly + C1 * Math.sin(meanAnomaly) + C2
+                * Math.sin(2 * meanAnomaly) + C3 * Math.sin(3 * meanAnomaly);
 
         // ecliptic longitude
-        final float solarLng = trueAnomaly + 1.796593063f + (float) Math.PI;
+        final double solarLng = trueAnomaly + 1.796593063d + Math.PI;
 
         // solar transit in days since 2000
         final double arcLongitude = -longitude / 360;
         float n = Math.round(daysSince2000 - J0 - arcLongitude);
-        double solarTransitJ2000 = n + J0 + arcLongitude + 0.0053f * FloatMath.sin(meanAnomaly)
-                + -0.0069f * FloatMath.sin(2 * solarLng);
+        double solarTransitJ2000 = n + J0 + arcLongitude + 0.0053d * Math.sin(meanAnomaly)
+                + -0.0069d * Math.sin(2 * solarLng);
 
         // declination of sun
-        double solarDec = Math.asin(FloatMath.sin(solarLng) * FloatMath.sin(OBLIQUITY));
+        double solarDec = Math.asin(Math.sin(solarLng) * Math.sin(OBLIQUITY));
 
         final double latRad = latiude * DEGREES_TO_RADIANS;
 
-        double cosHourAngle = (FloatMath.sin(ALTIDUTE_CORRECTION_CIVIL_TWILIGHT) - Math.sin(latRad)
+        double cosHourAngle = (Math.sin(ALTIDUTE_CORRECTION_CIVIL_TWILIGHT) - Math.sin(latRad)
                 * Math.sin(solarDec)) / (Math.cos(latRad) * Math.cos(solarDec));
         // The day or night never ends for the given date and location, if this value is out of
         // range.
diff --git a/services/java/com/android/server/accessibility/GestureUtils.java b/services/java/com/android/server/accessibility/GestureUtils.java
index b68b09f..bc76191 100644
--- a/services/java/com/android/server/accessibility/GestureUtils.java
+++ b/services/java/com/android/server/accessibility/GestureUtils.java
@@ -69,8 +69,7 @@
             return true;
         }
 
-        final float firstMagnitude =
-            (float) Math.sqrt(firstDeltaX * firstDeltaX + firstDeltaY * firstDeltaY);
+        final float firstMagnitude = (float) Math.hypot(firstDeltaX, firstDeltaY);
         final float firstXNormalized =
             (firstMagnitude > 0) ? firstDeltaX / firstMagnitude : firstDeltaX;
         final float firstYNormalized =
@@ -83,8 +82,7 @@
             return true;
         }
 
-        final float secondMagnitude =
-            (float) Math.sqrt(secondDeltaX * secondDeltaX + secondDeltaY * secondDeltaY);
+        final float secondMagnitude = (float) Math.hypot(secondDeltaX, secondDeltaY);
         final float secondXNormalized =
             (secondMagnitude > 0) ? secondDeltaX / secondMagnitude : secondDeltaX;
         final float secondYNormalized =
diff --git a/services/java/com/android/server/am/ActivityManagerService.java b/services/java/com/android/server/am/ActivityManagerService.java
index a77e241..9f8158a 100644
--- a/services/java/com/android/server/am/ActivityManagerService.java
+++ b/services/java/com/android/server/am/ActivityManagerService.java
@@ -2796,7 +2796,8 @@
             // the PID of the new process, or else throw a RuntimeException.
             Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
                     app.processName, uid, uid, gids, debugFlags, mountExternal,
-                    app.info.targetSdkVersion, app.info.seinfo, requiredAbi, instructionSet, null);
+                    app.info.targetSdkVersion, app.info.seinfo, requiredAbi, instructionSet,
+                    app.info.dataDir, null);
 
             BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
             synchronized (bs) {
diff --git a/services/java/com/android/server/power/DisplayPowerController.java b/services/java/com/android/server/power/DisplayPowerController.java
index 30bc922..389880a 100644
--- a/services/java/com/android/server/power/DisplayPowerController.java
+++ b/services/java/com/android/server/power/DisplayPowerController.java
@@ -35,7 +35,6 @@
 import android.os.PowerManager;
 import android.os.SystemClock;
 import android.text.format.DateUtils;
-import android.util.FloatMath;
 import android.util.Slog;
 import android.util.Spline;
 import android.util.TimeUtils;
@@ -1092,7 +1091,7 @@
 
         if (USE_SCREEN_AUTO_BRIGHTNESS_ADJUSTMENT
                 && mPowerRequest.screenAutoBrightnessAdjustment != 0.0f) {
-            final float adjGamma = FloatMath.pow(SCREEN_AUTO_BRIGHTNESS_ADJUSTMENT_MAX_GAMMA,
+            final float adjGamma = (float) Math.pow(SCREEN_AUTO_BRIGHTNESS_ADJUSTMENT_MAX_GAMMA,
                     Math.min(1.0f, Math.max(-1.0f,
                             -mPowerRequest.screenAutoBrightnessAdjustment)));
             gamma *= adjGamma;
@@ -1119,7 +1118,7 @@
 
         if (gamma != 1.0f) {
             final float in = value;
-            value = FloatMath.pow(value, gamma);
+            value = (float) Math.pow(value, gamma);
             if (DEBUG) {
                 Slog.d(TAG, "updateAutoBrightness: gamma=" + gamma
                         + ", in=" + in + ", out=" + value);
diff --git a/services/java/com/android/server/power/ElectronBeam.java b/services/java/com/android/server/power/ElectronBeam.java
index 729bd16..b9b892c 100644
--- a/services/java/com/android/server/power/ElectronBeam.java
+++ b/services/java/com/android/server/power/ElectronBeam.java
@@ -31,7 +31,6 @@
 import android.opengl.GLES10;
 import android.opengl.GLES11Ext;
 import android.os.Looper;
-import android.util.FloatMath;
 import android.util.Slog;
 import android.view.Display;
 import android.view.DisplayInfo;
@@ -636,7 +635,7 @@
     }
 
     private static float sigmoid(float x, float s) {
-        return 1.0f / (1.0f + FloatMath.exp(-x * s));
+        return 1.0f / (1.0f + (float) Math.exp(-x * s));
     }
 
     private static FloatBuffer createNativeFloatBuffer(int size) {
diff --git a/services/java/com/android/server/wm/WindowManagerService.java b/services/java/com/android/server/wm/WindowManagerService.java
index 096921d..eaa237a 100644
--- a/services/java/com/android/server/wm/WindowManagerService.java
+++ b/services/java/com/android/server/wm/WindowManagerService.java
@@ -91,7 +91,6 @@
 import android.provider.Settings;
 import android.util.DisplayMetrics;
 import android.util.EventLog;
-import android.util.FloatMath;
 import android.util.Log;
 import android.util.SparseArray;
 import android.util.Pair;
@@ -5724,7 +5723,7 @@
         Matrix matrix = new Matrix();
         ScreenRotationAnimation.createRotationMatrix(rot, dw, dh, matrix);
         // TODO: Test for RTL vs. LTR and use frame.right-width instead of -frame.left
-        matrix.postTranslate(-FloatMath.ceil(frame.left), -FloatMath.ceil(frame.top));
+        matrix.postTranslate((float) -Math.ceil(frame.left), (float) -Math.ceil(frame.top));
         Canvas canvas = new Canvas(bm);
         canvas.drawColor(0xFF000000);
         canvas.drawBitmap(rawss, matrix, null);
diff --git a/services/jni/Android.mk b/services/jni/Android.mk
index 83fe910..36107f8 100644
--- a/services/jni/Android.mk
+++ b/services/jni/Android.mk
@@ -52,7 +52,7 @@
     libEGL \
     libGLESv2
 
-LOCAL_CFLAGS += -DEGL_EGLEXT_PROTOTYPES -DGL_GLEXT_PROTOTYPES
+LOCAL_CFLAGS += -DEGL_EGLEXT_PROTOTYPES -DGL_GLEXT_PROTOTYPES -Wall -Werror
 
 LOCAL_MODULE:= libandroid_servers
 
diff --git a/services/jni/com_android_server_AssetAtlasService.cpp b/services/jni/com_android_server_AssetAtlasService.cpp
index 163692b..883df9b 100644
--- a/services/jni/com_android_server_AssetAtlasService.cpp
+++ b/services/jni/com_android_server_AssetAtlasService.cpp
@@ -28,8 +28,12 @@
 #include <EGL/egl.h>
 #include <EGL/eglext.h>
 
+// Disable warnings for Skia.
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wunused-parameter"
 #include <SkCanvas.h>
 #include <SkBitmap.h>
+#pragma GCC diagnostic pop
 
 namespace android {
 
diff --git a/services/jni/com_android_server_ConsumerIrService.cpp b/services/jni/com_android_server_ConsumerIrService.cpp
index 3a50ff7..f5121cd 100644
--- a/services/jni/com_android_server_ConsumerIrService.cpp
+++ b/services/jni/com_android_server_ConsumerIrService.cpp
@@ -29,7 +29,7 @@
 
 namespace android {
 
-static jlong halOpen(JNIEnv *env, jobject obj) {
+static jlong halOpen(JNIEnv* /* env */, jobject /* obj */) {
     hw_module_t const* module;
     consumerir_device_t *dev;
     int err;
@@ -50,7 +50,7 @@
     return reinterpret_cast<jlong>(dev);
 }
 
-static jint halTransmit(JNIEnv *env, jobject obj, jlong halObject,
+static jint halTransmit(JNIEnv *env, jobject /* obj */, jlong halObject,
    jint carrierFrequency, jintArray pattern) {
     int ret;
 
@@ -66,7 +66,7 @@
     return reinterpret_cast<jint>(ret);
 }
 
-static jintArray halGetCarrierFrequencies(JNIEnv *env, jobject obj,
+static jintArray halGetCarrierFrequencies(JNIEnv *env, jobject /* obj */,
     jlong halObject) {
     consumerir_device_t *dev = reinterpret_cast<consumerir_device_t*>(halObject);
     consumerir_freq_range_t *ranges;
diff --git a/services/jni/com_android_server_LightsService.cpp b/services/jni/com_android_server_LightsService.cpp
index 69793f7..572b324 100644
--- a/services/jni/com_android_server_LightsService.cpp
+++ b/services/jni/com_android_server_LightsService.cpp
@@ -60,7 +60,7 @@
     }
 }
 
-static jlong init_native(JNIEnv *env, jobject clazz)
+static jlong init_native(JNIEnv* /* env */, jobject /* clazz */)
 {
     int err;
     hw_module_t* module;
@@ -93,7 +93,7 @@
     return (jlong)devices;
 }
 
-static void finalize_native(JNIEnv *env, jobject clazz, jlong ptr)
+static void finalize_native(JNIEnv* /* env */, jobject /* clazz */, jlong ptr)
 {
     Devices* devices = (Devices*)ptr;
     if (devices == NULL) {
@@ -103,7 +103,7 @@
     free(devices);
 }
 
-static void setLight_native(JNIEnv *env, jobject clazz, jlong ptr,
+static void setLight_native(JNIEnv* /* env */, jobject /* clazz */, jlong ptr,
         jint light, jint colorARGB, jint flashMode, jint onMS, jint offMS, jint brightnessMode)
 {
     Devices* devices = (Devices*)ptr;
diff --git a/services/jni/com_android_server_SerialService.cpp b/services/jni/com_android_server_SerialService.cpp
index b889b78..d48d159 100644
--- a/services/jni/com_android_server_SerialService.cpp
+++ b/services/jni/com_android_server_SerialService.cpp
@@ -34,7 +34,7 @@
     jmethodID mConstructor;
 } gParcelFileDescriptorOffsets;
 
-static jobject android_server_SerialService_open(JNIEnv *env, jobject thiz, jstring path)
+static jobject android_server_SerialService_open(JNIEnv *env, jobject /* thiz */, jstring path)
 {
     const char *pathStr = env->GetStringUTFChars(path, NULL);
 
diff --git a/services/jni/com_android_server_SystemServer.cpp b/services/jni/com_android_server_SystemServer.cpp
index 0625544..c50d63c 100644
--- a/services/jni/com_android_server_SystemServer.cpp
+++ b/services/jni/com_android_server_SystemServer.cpp
@@ -25,7 +25,7 @@
 
 namespace android {
 
-static void android_server_SystemServer_nativeInit(JNIEnv* env, jobject clazz) {
+static void android_server_SystemServer_nativeInit(JNIEnv* /* env */, jobject /* clazz */) {
     char propBuf[PROPERTY_VALUE_MAX];
     property_get("system_init.startsensorservice", propBuf, "1");
     if (strcmp(propBuf, "1") == 0) {
diff --git a/services/jni/com_android_server_UsbDeviceManager.cpp b/services/jni/com_android_server_UsbDeviceManager.cpp
index 3551733..8d1a338 100644
--- a/services/jni/com_android_server_UsbDeviceManager.cpp
+++ b/services/jni/com_android_server_UsbDeviceManager.cpp
@@ -63,7 +63,8 @@
 }
 
 
-static jobjectArray android_server_UsbDeviceManager_getAccessoryStrings(JNIEnv *env, jobject thiz)
+static jobjectArray android_server_UsbDeviceManager_getAccessoryStrings(JNIEnv *env,
+                                                                        jobject /* thiz */)
 {
     int fd = open(DRIVER_NAME, O_RDWR);
     if (fd < 0) {
@@ -85,7 +86,7 @@
     return strArray;
 }
 
-static jobject android_server_UsbDeviceManager_openAccessory(JNIEnv *env, jobject thiz)
+static jobject android_server_UsbDeviceManager_openAccessory(JNIEnv *env, jobject /* thiz */)
 {
     int fd = open(DRIVER_NAME, O_RDWR);
     if (fd < 0) {
@@ -100,7 +101,8 @@
         gParcelFileDescriptorOffsets.mConstructor, fileDescriptor);
 }
 
-static jboolean android_server_UsbDeviceManager_isStartRequested(JNIEnv *env, jobject thiz)
+static jboolean android_server_UsbDeviceManager_isStartRequested(JNIEnv* /* env */,
+                                                                 jobject /* thiz */)
 {
     int fd = open(DRIVER_NAME, O_RDWR);
     if (fd < 0) {
@@ -112,7 +114,7 @@
     return (result == 1);
 }
 
-static jint android_server_UsbDeviceManager_getAudioMode(JNIEnv *env, jobject thiz)
+static jint android_server_UsbDeviceManager_getAudioMode(JNIEnv* /* env */, jobject /* thiz */)
 {
     int fd = open(DRIVER_NAME, O_RDWR);
     if (fd < 0) {
diff --git a/services/jni/com_android_server_UsbHostManager.cpp b/services/jni/com_android_server_UsbHostManager.cpp
index fc6de60..e5ee350 100644
--- a/services/jni/com_android_server_UsbHostManager.cpp
+++ b/services/jni/com_android_server_UsbHostManager.cpp
@@ -142,7 +142,7 @@
     return 0;
 }
 
-static void android_server_UsbHostManager_monitorUsbHostBus(JNIEnv *env, jobject thiz)
+static void android_server_UsbHostManager_monitorUsbHostBus(JNIEnv* /* env */, jobject thiz)
 {
     struct usb_host_context* context = usb_host_init();
     if (!context) {
@@ -153,7 +153,8 @@
     usb_host_run(context, usb_device_added, usb_device_removed, NULL, (void *)thiz);
 }
 
-static jobject android_server_UsbHostManager_openDevice(JNIEnv *env, jobject thiz, jstring deviceName)
+static jobject android_server_UsbHostManager_openDevice(JNIEnv *env, jobject /* thiz */,
+                                                        jstring deviceName)
 {
     const char *deviceNameStr = env->GetStringUTFChars(deviceName, NULL);
     struct usb_device* device = usb_device_open(deviceNameStr);
diff --git a/services/jni/com_android_server_VibratorService.cpp b/services/jni/com_android_server_VibratorService.cpp
index 2b3f74a..fb1166b 100644
--- a/services/jni/com_android_server_VibratorService.cpp
+++ b/services/jni/com_android_server_VibratorService.cpp
@@ -29,18 +29,18 @@
 namespace android
 {
 
-static jboolean vibratorExists(JNIEnv *env, jobject clazz)
+static jboolean vibratorExists(JNIEnv* /* env */, jobject /* clazz */)
 {
     return vibrator_exists() > 0 ? JNI_TRUE : JNI_FALSE;
 }
 
-static void vibratorOn(JNIEnv *env, jobject clazz, jlong timeout_ms)
+static void vibratorOn(JNIEnv* /* env */, jobject /* clazz */, jlong timeout_ms)
 {
     // ALOGI("vibratorOn\n");
     vibrator_on(timeout_ms);
 }
 
-static void vibratorOff(JNIEnv *env, jobject clazz)
+static void vibratorOff(JNIEnv* /* env */, jobject /* clazz */)
 {
     // ALOGI("vibratorOff\n");
     vibrator_off();
diff --git a/services/jni/com_android_server_connectivity_Vpn.cpp b/services/jni/com_android_server_connectivity_Vpn.cpp
index bf34a74..376d01b 100644
--- a/services/jni/com_android_server_connectivity_Vpn.cpp
+++ b/services/jni/com_android_server_connectivity_Vpn.cpp
@@ -313,7 +313,7 @@
     }
 }
 
-static jint create(JNIEnv *env, jobject thiz, jint mtu)
+static jint create(JNIEnv *env, jobject /* thiz */, jint mtu)
 {
     int tun = create_interface(mtu);
     if (tun < 0) {
@@ -323,7 +323,7 @@
     return tun;
 }
 
-static jstring getName(JNIEnv *env, jobject thiz, jint tun)
+static jstring getName(JNIEnv *env, jobject /* thiz */, jint tun)
 {
     char name[IFNAMSIZ];
     if (get_interface_name(name, tun) < 0) {
@@ -333,7 +333,7 @@
     return env->NewStringUTF(name);
 }
 
-static jint setAddresses(JNIEnv *env, jobject thiz, jstring jName,
+static jint setAddresses(JNIEnv *env, jobject /* thiz */, jstring jName,
         jstring jAddresses)
 {
     const char *name = NULL;
@@ -366,7 +366,7 @@
     return count;
 }
 
-static jint setRoutes(JNIEnv *env, jobject thiz, jstring jName,
+static jint setRoutes(JNIEnv *env, jobject /* thiz */, jstring jName,
         jstring jRoutes)
 {
     const char *name = NULL;
@@ -399,7 +399,7 @@
     return count;
 }
 
-static void reset(JNIEnv *env, jobject thiz, jstring jName)
+static void reset(JNIEnv *env, jobject /* thiz */, jstring jName)
 {
     const char *name = jName ? env->GetStringUTFChars(jName, NULL) : NULL;
     if (!name) {
@@ -412,7 +412,7 @@
     env->ReleaseStringUTFChars(jName, name);
 }
 
-static jint check(JNIEnv *env, jobject thiz, jstring jName)
+static jint check(JNIEnv *env, jobject /* thiz */, jstring jName)
 {
     const char *name = jName ? env->GetStringUTFChars(jName, NULL) : NULL;
     if (!name) {
diff --git a/services/jni/com_android_server_input_InputManagerService.cpp b/services/jni/com_android_server_input_InputManagerService.cpp
index 10ad278..facd8df 100644
--- a/services/jni/com_android_server_input_InputManagerService.cpp
+++ b/services/jni/com_android_server_input_InputManagerService.cpp
@@ -335,14 +335,14 @@
     }
 }
 
-status_t NativeInputManager::registerInputChannel(JNIEnv* env,
+status_t NativeInputManager::registerInputChannel(JNIEnv* /* env */,
         const sp<InputChannel>& inputChannel,
         const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
     return mInputManager->getDispatcher()->registerInputChannel(
             inputChannel, inputWindowHandle, monitor);
 }
 
-status_t NativeInputManager::unregisterInputChannel(JNIEnv* env,
+status_t NativeInputManager::unregisterInputChannel(JNIEnv* /* env */,
         const sp<InputChannel>& inputChannel) {
     return mInputManager->getDispatcher()->unregisterInputChannel(inputChannel);
 }
@@ -413,7 +413,7 @@
     } // release lock
 }
 
-sp<PointerControllerInterface> NativeInputManager::obtainPointerController(int32_t deviceId) {
+sp<PointerControllerInterface> NativeInputManager::obtainPointerController(int32_t /* deviceId */) {
     AutoMutex _l(mLock);
 
     sp<PointerController> controller = mLocked.pointerController.promote();
@@ -530,7 +530,7 @@
 }
 
 void NativeInputManager::notifySwitch(nsecs_t when,
-        uint32_t switchValues, uint32_t switchMask, uint32_t policyFlags) {
+        uint32_t switchValues, uint32_t switchMask, uint32_t /* policyFlags */) {
 #if DEBUG_INPUT_DISPATCHER_POLICY
     ALOGD("notifySwitch - when=%lld, switchValues=0x%08x, switchMask=0x%08x, policyFlags=0x%x",
             when, switchValues, switchMask, policyFlags);
@@ -977,7 +977,7 @@
 
 // ----------------------------------------------------------------------------
 
-static jlong nativeInit(JNIEnv* env, jclass clazz,
+static jlong nativeInit(JNIEnv* env, jclass /* clazz */,
         jobject serviceObj, jobject contextObj, jobject messageQueueObj) {
     sp<MessageQueue> messageQueue = android_os_MessageQueue_getMessageQueue(env, messageQueueObj);
     if (messageQueue == NULL) {
@@ -991,7 +991,7 @@
     return reinterpret_cast<jlong>(im);
 }
 
-static void nativeStart(JNIEnv* env, jclass clazz, jlong ptr) {
+static void nativeStart(JNIEnv* env, jclass /* clazz */, jlong ptr) {
     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
 
     status_t result = im->getInputManager()->start();
@@ -1000,8 +1000,8 @@
     }
 }
 
-static void nativeSetDisplayViewport(JNIEnv* env, jclass clazz, jlong ptr, jboolean external,
-        jint displayId, jint orientation,
+static void nativeSetDisplayViewport(JNIEnv* /* env */, jclass /* clazz */, jlong ptr,
+        jboolean external, jint displayId, jint orientation,
         jint logicalLeft, jint logicalTop, jint logicalRight, jint logicalBottom,
         jint physicalLeft, jint physicalTop, jint physicalRight, jint physicalBottom,
         jint deviceWidth, jint deviceHeight) {
@@ -1023,7 +1023,7 @@
     im->setDisplayViewport(external, v);
 }
 
-static jint nativeGetScanCodeState(JNIEnv* env, jclass clazz,
+static jint nativeGetScanCodeState(JNIEnv* /* env */, jclass /* clazz */,
         jlong ptr, jint deviceId, jint sourceMask, jint scanCode) {
     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
 
@@ -1031,7 +1031,7 @@
             deviceId, uint32_t(sourceMask), scanCode);
 }
 
-static jint nativeGetKeyCodeState(JNIEnv* env, jclass clazz,
+static jint nativeGetKeyCodeState(JNIEnv* /* env */, jclass /* clazz */,
         jlong ptr, jint deviceId, jint sourceMask, jint keyCode) {
     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
 
@@ -1039,7 +1039,7 @@
             deviceId, uint32_t(sourceMask), keyCode);
 }
 
-static jint nativeGetSwitchState(JNIEnv* env, jclass clazz,
+static jint nativeGetSwitchState(JNIEnv* /* env */, jclass /* clazz */,
         jlong ptr, jint deviceId, jint sourceMask, jint sw) {
     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
 
@@ -1047,7 +1047,7 @@
             deviceId, uint32_t(sourceMask), sw);
 }
 
-static jboolean nativeHasKeys(JNIEnv* env, jclass clazz,
+static jboolean nativeHasKeys(JNIEnv* env, jclass /* clazz */,
         jlong ptr, jint deviceId, jint sourceMask, jintArray keyCodes, jbooleanArray outFlags) {
     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
 
@@ -1077,7 +1077,7 @@
 }
 
 static void handleInputChannelDisposed(JNIEnv* env,
-        jobject inputChannelObj, const sp<InputChannel>& inputChannel, void* data) {
+        jobject /* inputChannelObj */, const sp<InputChannel>& inputChannel, void* data) {
     NativeInputManager* im = static_cast<NativeInputManager*>(data);
 
     ALOGW("Input channel object '%s' was disposed without first being unregistered with "
@@ -1085,7 +1085,7 @@
     im->unregisterInputChannel(env, inputChannel);
 }
 
-static void nativeRegisterInputChannel(JNIEnv* env, jclass clazz,
+static void nativeRegisterInputChannel(JNIEnv* env, jclass /* clazz */,
         jlong ptr, jobject inputChannelObj, jobject inputWindowHandleObj, jboolean monitor) {
     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
 
@@ -1114,7 +1114,7 @@
     }
 }
 
-static void nativeUnregisterInputChannel(JNIEnv* env, jclass clazz,
+static void nativeUnregisterInputChannel(JNIEnv* env, jclass /* clazz */,
         jlong ptr, jobject inputChannelObj) {
     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
 
@@ -1135,14 +1135,14 @@
     }
 }
 
-static void nativeSetInputFilterEnabled(JNIEnv* env, jclass clazz,
+static void nativeSetInputFilterEnabled(JNIEnv* /* env */, jclass /* clazz */,
         jlong ptr, jboolean enabled) {
     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
 
     im->getInputManager()->getDispatcher()->setInputFilterEnabled(enabled);
 }
 
-static jint nativeInjectInputEvent(JNIEnv* env, jclass clazz,
+static jint nativeInjectInputEvent(JNIEnv* env, jclass /* clazz */,
         jlong ptr, jobject inputEventObj, jint injectorPid, jint injectorUid,
         jint syncMode, jint timeoutMillis, jint policyFlags) {
     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
@@ -1174,36 +1174,36 @@
     }
 }
 
-static void nativeSetInputWindows(JNIEnv* env, jclass clazz,
+static void nativeSetInputWindows(JNIEnv* env, jclass /* clazz */,
         jlong ptr, jobjectArray windowHandleObjArray) {
     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
 
     im->setInputWindows(env, windowHandleObjArray);
 }
 
-static void nativeSetFocusedApplication(JNIEnv* env, jclass clazz,
+static void nativeSetFocusedApplication(JNIEnv* env, jclass /* clazz */,
         jlong ptr, jobject applicationHandleObj) {
     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
 
     im->setFocusedApplication(env, applicationHandleObj);
 }
 
-static void nativeSetInputDispatchMode(JNIEnv* env,
-        jclass clazz, jlong ptr, jboolean enabled, jboolean frozen) {
+static void nativeSetInputDispatchMode(JNIEnv* /* env */,
+        jclass /* clazz */, jlong ptr, jboolean enabled, jboolean frozen) {
     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
 
     im->setInputDispatchMode(enabled, frozen);
 }
 
-static void nativeSetSystemUiVisibility(JNIEnv* env,
-        jclass clazz, jlong ptr, jint visibility) {
+static void nativeSetSystemUiVisibility(JNIEnv* /* env */,
+        jclass /* clazz */, jlong ptr, jint visibility) {
     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
 
     im->setSystemUiVisibility(visibility);
 }
 
 static jboolean nativeTransferTouchFocus(JNIEnv* env,
-        jclass clazz, jlong ptr, jobject fromChannelObj, jobject toChannelObj) {
+        jclass /* clazz */, jlong ptr, jobject fromChannelObj, jobject toChannelObj) {
     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
 
     sp<InputChannel> fromChannel =
@@ -1223,22 +1223,22 @@
     }
 }
 
-static void nativeSetPointerSpeed(JNIEnv* env,
-        jclass clazz, jlong ptr, jint speed) {
+static void nativeSetPointerSpeed(JNIEnv* /* env */,
+        jclass /* clazz */, jlong ptr, jint speed) {
     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
 
     im->setPointerSpeed(speed);
 }
 
-static void nativeSetShowTouches(JNIEnv* env,
-        jclass clazz, jlong ptr, jboolean enabled) {
+static void nativeSetShowTouches(JNIEnv* /* env */,
+        jclass /* clazz */, jlong ptr, jboolean enabled) {
     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
 
     im->setShowTouches(enabled);
 }
 
 static void nativeVibrate(JNIEnv* env,
-        jclass clazz, jlong ptr, jint deviceId, jlongArray patternObj,
+        jclass /* clazz */, jlong ptr, jint deviceId, jlongArray patternObj,
         jint repeat, jint token) {
     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
 
@@ -1262,30 +1262,30 @@
     im->getInputManager()->getReader()->vibrate(deviceId, pattern, patternSize, repeat, token);
 }
 
-static void nativeCancelVibrate(JNIEnv* env,
-        jclass clazz, jlong ptr, jint deviceId, jint token) {
+static void nativeCancelVibrate(JNIEnv* /* env */,
+        jclass /* clazz */, jlong ptr, jint deviceId, jint token) {
     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
 
     im->getInputManager()->getReader()->cancelVibrate(deviceId, token);
 }
 
-static void nativeReloadKeyboardLayouts(JNIEnv* env,
-        jclass clazz, jlong ptr) {
+static void nativeReloadKeyboardLayouts(JNIEnv* /* env */,
+        jclass /* clazz */, jlong ptr) {
     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
 
     im->getInputManager()->getReader()->requestRefreshConfiguration(
             InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS);
 }
 
-static void nativeReloadDeviceAliases(JNIEnv* env,
-        jclass clazz, jlong ptr) {
+static void nativeReloadDeviceAliases(JNIEnv* /* env */,
+        jclass /* clazz */, jlong ptr) {
     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
 
     im->getInputManager()->getReader()->requestRefreshConfiguration(
             InputReaderConfiguration::CHANGE_DEVICE_ALIAS);
 }
 
-static jstring nativeDump(JNIEnv* env, jclass clazz, jlong ptr) {
+static jstring nativeDump(JNIEnv* env, jclass /* clazz */, jlong ptr) {
     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
 
     String8 dump;
@@ -1293,7 +1293,7 @@
     return env->NewStringUTF(dump.string());
 }
 
-static void nativeMonitor(JNIEnv* env, jclass clazz, jlong ptr) {
+static void nativeMonitor(JNIEnv* /* env */, jclass /* clazz */, jlong ptr) {
     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
 
     im->getInputManager()->getReader()->monitor();
diff --git a/services/jni/com_android_server_location_FlpHardwareProvider.cpp b/services/jni/com_android_server_location_FlpHardwareProvider.cpp
index 6c14887..91bcf5d 100644
--- a/services/jni/com_android_server_location_FlpHardwareProvider.cpp
+++ b/services/jni/com_android_server_location_FlpHardwareProvider.cpp
@@ -695,11 +695,11 @@
   // TODO: inject any device context if when needed
 }
 
-static jboolean IsSupported(JNIEnv* env, jclass clazz) {
+static jboolean IsSupported(JNIEnv* /* env */, jclass /* clazz */) {
   return sFlpInterface != NULL;
 }
 
-static jint GetBatchSize(JNIEnv* env, jobject object) {
+static jint GetBatchSize(JNIEnv* env, jobject /* object */) {
   if(sFlpInterface == NULL) {
     ThrowOnError(env, FLP_RESULT_ERROR, __FUNCTION__);
   }
@@ -709,7 +709,7 @@
 
 static void StartBatching(
     JNIEnv* env,
-    jobject object,
+    jobject /* object */,
     jint id,
     jobject optionsObject) {
   if(sFlpInterface == NULL || optionsObject == NULL) {
@@ -724,7 +724,7 @@
 
 static void UpdateBatchingOptions(
     JNIEnv* env,
-    jobject object,
+    jobject /* object */,
     jint id,
     jobject optionsObject) {
   if(sFlpInterface == NULL || optionsObject == NULL) {
@@ -737,7 +737,7 @@
   ThrowOnError(env, result, __FUNCTION__);
 }
 
-static void StopBatching(JNIEnv* env, jobject object, jint id) {
+static void StopBatching(JNIEnv* env, jobject /* object */, jint id) {
   if(sFlpInterface == NULL) {
     ThrowOnError(env, FLP_RESULT_ERROR, __FUNCTION__);
   }
@@ -745,7 +745,7 @@
   sFlpInterface->stop_batching(id);
 }
 
-static void Cleanup(JNIEnv* env, jobject object) {
+static void Cleanup(JNIEnv* env, jobject /* object */) {
   if(sFlpInterface == NULL) {
     ThrowOnError(env, FLP_RESULT_ERROR, __FUNCTION__);
   }
@@ -768,7 +768,7 @@
   }
 }
 
-static void GetBatchedLocation(JNIEnv* env, jobject object, jint lastNLocations) {
+static void GetBatchedLocation(JNIEnv* env, jobject /* object */, jint lastNLocations) {
   if(sFlpInterface == NULL) {
     ThrowOnError(env, FLP_RESULT_ERROR, __FUNCTION__);
   }
@@ -776,7 +776,7 @@
   sFlpInterface->get_batched_location(lastNLocations);
 }
 
-static void InjectLocation(JNIEnv* env, jobject object, jobject locationObject) {
+static void InjectLocation(JNIEnv* env, jobject /* object */, jobject locationObject) {
   if(locationObject == NULL) {
     ALOGE("Invalid location for injection: %p", locationObject);
     ThrowOnError(env, FLP_RESULT_ERROR, __FUNCTION__);
@@ -800,7 +800,7 @@
   return sFlpDiagnosticInterface != NULL;
 }
 
-static void InjectDiagnosticData(JNIEnv* env, jobject object, jstring stringData) {
+static void InjectDiagnosticData(JNIEnv* env, jobject /* object */, jstring stringData) {
   if(stringData == NULL) {
     ALOGE("Invalid diagnostic data for injection: %p", stringData);
     ThrowOnError(env, FLP_RESULT_ERROR, __FUNCTION__);
@@ -824,7 +824,7 @@
   return sFlpDeviceContextInterface != NULL;
 }
 
-static void InjectDeviceContext(JNIEnv* env, jobject object, jint enabledMask) {
+static void InjectDeviceContext(JNIEnv* env, jobject /* object */, jint enabledMask) {
   if(sFlpDeviceContextInterface == NULL) {
     ThrowOnError(env, FLP_RESULT_ERROR, __FUNCTION__);
   }
@@ -839,7 +839,7 @@
 
 static void AddGeofences(
     JNIEnv* env,
-    jobject object,
+    jobject /* object */,
     jobjectArray geofenceRequestsArray) {
   if(geofenceRequestsArray == NULL) {
     ALOGE("Invalid Geofences to add: %p", geofenceRequestsArray);
@@ -879,7 +879,7 @@
   }
 }
 
-static void PauseGeofence(JNIEnv* env, jobject object, jint geofenceId) {
+static void PauseGeofence(JNIEnv* env, jobject /* object */, jint geofenceId) {
   if(sFlpGeofencingInterface == NULL) {
     ThrowOnError(env, FLP_RESULT_ERROR, __FUNCTION__);
   }
@@ -889,7 +889,7 @@
 
 static void ResumeGeofence(
     JNIEnv* env,
-    jobject object,
+    jobject /* object */,
     jint geofenceId,
     jint monitorTransitions) {
   if(sFlpGeofencingInterface == NULL) {
@@ -901,7 +901,7 @@
 
 static void ModifyGeofenceOption(
     JNIEnv* env,
-    jobject object,
+    jobject /* object */,
     jint geofenceId,
     jint lastTransition,
     jint monitorTransitions,
@@ -925,7 +925,7 @@
 
 static void RemoveGeofences(
     JNIEnv* env,
-    jobject object,
+    jobject /* object */,
     jintArray geofenceIdsArray) {
   if(sFlpGeofencingInterface == NULL) {
     ThrowOnError(env, FLP_RESULT_ERROR, __FUNCTION__);
diff --git a/services/jni/com_android_server_location_GpsLocationProvider.cpp b/services/jni/com_android_server_location_GpsLocationProvider.cpp
index e9ba116..1d3ec55 100644
--- a/services/jni/com_android_server_location_GpsLocationProvider.cpp
+++ b/services/jni/com_android_server_location_GpsLocationProvider.cpp
@@ -386,7 +386,8 @@
     }
 }
 
-static jboolean android_location_GpsLocationProvider_is_supported(JNIEnv* env, jclass clazz) {
+static jboolean android_location_GpsLocationProvider_is_supported(JNIEnv* /* env */,
+                                                                  jclass /* clazz */) {
     if (sGpsInterface != NULL) {
         return JNI_TRUE;
     } else {
@@ -420,14 +421,15 @@
     return JNI_TRUE;
 }
 
-static void android_location_GpsLocationProvider_cleanup(JNIEnv* env, jobject obj)
+static void android_location_GpsLocationProvider_cleanup(JNIEnv* /* env */, jobject /* obj */)
 {
     if (sGpsInterface)
         sGpsInterface->cleanup();
 }
 
-static jboolean android_location_GpsLocationProvider_set_position_mode(JNIEnv* env, jobject obj,
-        jint mode, jint recurrence, jint min_interval, jint preferred_accuracy, jint preferred_time)
+static jboolean android_location_GpsLocationProvider_set_position_mode(JNIEnv* /* env */,
+        jobject /* obj */, jint mode, jint recurrence, jint min_interval, jint preferred_accuracy,
+        jint preferred_time)
 {
     if (sGpsInterface) {
         if (sGpsInterface->set_position_mode(mode, recurrence, min_interval, preferred_accuracy,
@@ -441,7 +443,7 @@
         return JNI_FALSE;
 }
 
-static jboolean android_location_GpsLocationProvider_start(JNIEnv* env, jobject obj)
+static jboolean android_location_GpsLocationProvider_start(JNIEnv* /* env */, jobject /* obj */)
 {
     if (sGpsInterface) {
         if (sGpsInterface->start() == 0) {
@@ -454,7 +456,7 @@
         return JNI_FALSE;
 }
 
-static jboolean android_location_GpsLocationProvider_stop(JNIEnv* env, jobject obj)
+static jboolean android_location_GpsLocationProvider_stop(JNIEnv* /* env */, jobject /* obj */)
 {
     if (sGpsInterface) {
         if (sGpsInterface->stop() == 0) {
@@ -467,13 +469,15 @@
         return JNI_FALSE;
 }
 
-static void android_location_GpsLocationProvider_delete_aiding_data(JNIEnv* env, jobject obj, jint flags)
+static void android_location_GpsLocationProvider_delete_aiding_data(JNIEnv* /* env */,
+                                                                    jobject /* obj */,
+                                                                    jint flags)
 {
     if (sGpsInterface)
         sGpsInterface->delete_aiding_data(flags);
 }
 
-static jint android_location_GpsLocationProvider_read_sv_status(JNIEnv* env, jobject obj,
+static jint android_location_GpsLocationProvider_read_sv_status(JNIEnv* env, jobject /* obj */,
         jintArray prnArray, jfloatArray snrArray, jfloatArray elevArray, jfloatArray azumArray,
         jintArray maskArray)
 {
@@ -504,8 +508,8 @@
     return (jint) num_svs;
 }
 
-static void android_location_GpsLocationProvider_agps_set_reference_location_cellid(JNIEnv* env,
-        jobject obj, jint type, jint mcc, jint mnc, jint lac, jint cid)
+static void android_location_GpsLocationProvider_agps_set_reference_location_cellid(
+        JNIEnv* /* env */, jobject /* obj */, jint type, jint mcc, jint mnc, jint lac, jint cid)
 {
     AGpsRefLocation location;
 
@@ -532,7 +536,7 @@
 }
 
 static void android_location_GpsLocationProvider_agps_send_ni_message(JNIEnv* env,
-        jobject obj, jbyteArray ni_msg, jint size)
+        jobject /* obj */, jbyteArray ni_msg, jint size)
 {
     size_t sz;
 
@@ -548,8 +552,8 @@
     env->ReleaseByteArrayElements(ni_msg,b,0);
 }
 
-static void android_location_GpsLocationProvider_agps_set_id(JNIEnv *env,
-        jobject obj, jint type, jstring  setid_string)
+static void android_location_GpsLocationProvider_agps_set_id(JNIEnv *env, jobject /* obj */,
+                                                             jint type, jstring  setid_string)
 {
     if (!sAGpsRilInterface) {
         ALOGE("no AGPS RIL interface in agps_set_id");
@@ -561,7 +565,7 @@
     env->ReleaseStringUTFChars(setid_string, setid);
 }
 
-static jint android_location_GpsLocationProvider_read_nmea(JNIEnv* env, jobject obj,
+static jint android_location_GpsLocationProvider_read_nmea(JNIEnv* env, jobject /* obj */,
                                             jbyteArray nmeaArray, jint buffer_size)
 {
     // this should only be called from within a call to reportNmea
@@ -574,21 +578,22 @@
     return (jint) length;
 }
 
-static void android_location_GpsLocationProvider_inject_time(JNIEnv* env, jobject obj,
+static void android_location_GpsLocationProvider_inject_time(JNIEnv* /* env */, jobject /* obj */,
         jlong time, jlong timeReference, jint uncertainty)
 {
     if (sGpsInterface)
         sGpsInterface->inject_time(time, timeReference, uncertainty);
 }
 
-static void android_location_GpsLocationProvider_inject_location(JNIEnv* env, jobject obj,
-        jdouble latitude, jdouble longitude, jfloat accuracy)
+static void android_location_GpsLocationProvider_inject_location(JNIEnv* /* env */,
+        jobject /* obj */, jdouble latitude, jdouble longitude, jfloat accuracy)
 {
     if (sGpsInterface)
         sGpsInterface->inject_location(latitude, longitude, accuracy);
 }
 
-static jboolean android_location_GpsLocationProvider_supports_xtra(JNIEnv* env, jobject obj)
+static jboolean android_location_GpsLocationProvider_supports_xtra(JNIEnv* /* env */,
+                                                                   jobject /* obj */)
 {
     if (sGpsXtraInterface != NULL) {
         return JNI_TRUE;
@@ -597,7 +602,7 @@
     }
 }
 
-static void android_location_GpsLocationProvider_inject_xtra_data(JNIEnv* env, jobject obj,
+static void android_location_GpsLocationProvider_inject_xtra_data(JNIEnv* env, jobject /* obj */,
         jbyteArray data, jint length)
 {
     if (!sGpsXtraInterface) {
@@ -610,7 +615,8 @@
     env->ReleasePrimitiveArrayCritical(data, bytes, JNI_ABORT);
 }
 
-static void android_location_GpsLocationProvider_agps_data_conn_open(JNIEnv* env, jobject obj, jstring apn)
+static void android_location_GpsLocationProvider_agps_data_conn_open(JNIEnv* env,
+                                                                     jobject /* obj */, jstring apn)
 {
     if (!sAGpsInterface) {
         ALOGE("no AGPS interface in agps_data_conn_open");
@@ -625,7 +631,8 @@
     env->ReleaseStringUTFChars(apn, apnStr);
 }
 
-static void android_location_GpsLocationProvider_agps_data_conn_closed(JNIEnv* env, jobject obj)
+static void android_location_GpsLocationProvider_agps_data_conn_closed(JNIEnv* /* env */,
+                                                                       jobject /* obj */)
 {
     if (!sAGpsInterface) {
         ALOGE("no AGPS interface in agps_data_conn_closed");
@@ -634,7 +641,8 @@
     sAGpsInterface->data_conn_closed();
 }
 
-static void android_location_GpsLocationProvider_agps_data_conn_failed(JNIEnv* env, jobject obj)
+static void android_location_GpsLocationProvider_agps_data_conn_failed(JNIEnv* /* env */,
+                                                                       jobject /* obj */)
 {
     if (!sAGpsInterface) {
         ALOGE("no AGPS interface in agps_data_conn_failed");
@@ -643,7 +651,7 @@
     sAGpsInterface->data_conn_failed();
 }
 
-static void android_location_GpsLocationProvider_set_agps_server(JNIEnv* env, jobject obj,
+static void android_location_GpsLocationProvider_set_agps_server(JNIEnv* env, jobject /* obj */,
         jint type, jstring hostname, jint port)
 {
     if (!sAGpsInterface) {
@@ -655,8 +663,8 @@
     env->ReleaseStringUTFChars(hostname, c_hostname);
 }
 
-static void android_location_GpsLocationProvider_send_ni_response(JNIEnv* env, jobject obj,
-      jint notifId, jint response)
+static void android_location_GpsLocationProvider_send_ni_response(JNIEnv* /* env */,
+      jobject /* obj */, jint notifId, jint response)
 {
     if (!sGpsNiInterface) {
         ALOGE("no NI interface in send_ni_response");
@@ -666,8 +674,8 @@
     sGpsNiInterface->respond(notifId, response);
 }
 
-static jstring android_location_GpsLocationProvider_get_internal_state(JNIEnv* env, jobject obj)
-{
+static jstring android_location_GpsLocationProvider_get_internal_state(JNIEnv* env,
+                                                                       jobject /* obj */) {
     jstring result = NULL;
     if (sGpsDebugInterface) {
         const size_t maxLength = 2047;
@@ -680,7 +688,7 @@
     return result;
 }
 
-static void android_location_GpsLocationProvider_update_network_state(JNIEnv* env, jobject obj,
+static void android_location_GpsLocationProvider_update_network_state(JNIEnv* env, jobject /* obj */,
         jboolean connected, jint type, jboolean roaming, jboolean available, jstring extraInfo, jstring apn)
 {
 
@@ -703,16 +711,17 @@
     }
 }
 
-static jboolean android_location_GpsLocationProvider_is_geofence_supported(JNIEnv* env,
-          jobject obj) {
+static jboolean android_location_GpsLocationProvider_is_geofence_supported(JNIEnv* /* env */,
+                                                                           jobject /* obj */)
+{
     if (sGpsGeofencingInterface != NULL) {
         return JNI_TRUE;
     }
     return JNI_FALSE;
 }
 
-static jboolean android_location_GpsLocationProvider_add_geofence(JNIEnv* env, jobject obj,
-        jint geofence_id, jdouble latitude, jdouble longitude, jdouble radius,
+static jboolean android_location_GpsLocationProvider_add_geofence(JNIEnv* /* env */,
+        jobject /* obj */, jint geofence_id, jdouble latitude, jdouble longitude, jdouble radius,
         jint last_transition, jint monitor_transition, jint notification_responsiveness,
         jint unknown_timer) {
     if (sGpsGeofencingInterface != NULL) {
@@ -726,8 +735,8 @@
     return JNI_FALSE;
 }
 
-static jboolean android_location_GpsLocationProvider_remove_geofence(JNIEnv* env, jobject obj,
-        jint geofence_id) {
+static jboolean android_location_GpsLocationProvider_remove_geofence(JNIEnv* /* env */,
+        jobject /* obj */, jint geofence_id) {
     if (sGpsGeofencingInterface != NULL) {
         sGpsGeofencingInterface->remove_geofence_area(geofence_id);
         return JNI_TRUE;
@@ -737,8 +746,8 @@
     return JNI_FALSE;
 }
 
-static jboolean android_location_GpsLocationProvider_pause_geofence(JNIEnv* env, jobject obj,
-        jint geofence_id) {
+static jboolean android_location_GpsLocationProvider_pause_geofence(JNIEnv* /* env */,
+        jobject /* obj */, jint geofence_id) {
     if (sGpsGeofencingInterface != NULL) {
         sGpsGeofencingInterface->pause_geofence(geofence_id);
         return JNI_TRUE;
@@ -748,8 +757,8 @@
     return JNI_FALSE;
 }
 
-static jboolean android_location_GpsLocationProvider_resume_geofence(JNIEnv* env, jobject obj,
-        jint geofence_id, jint monitor_transition) {
+static jboolean android_location_GpsLocationProvider_resume_geofence(JNIEnv* /* env */,
+        jobject /* obj */, jint geofence_id, jint monitor_transition) {
     if (sGpsGeofencingInterface != NULL) {
         sGpsGeofencingInterface->resume_geofence(geofence_id, monitor_transition);
         return JNI_TRUE;
diff --git a/services/jni/com_android_server_power_PowerManagerService.cpp b/services/jni/com_android_server_power_PowerManagerService.cpp
index 151e134..e5f29d9 100644
--- a/services/jni/com_android_server_power_PowerManagerService.cpp
+++ b/services/jni/com_android_server_power_PowerManagerService.cpp
@@ -150,24 +150,24 @@
     }
 }
 
-static void nativeSetPowerState(JNIEnv* env,
-        jclass clazz, jboolean screenOn, jboolean screenBright) {
+static void nativeSetPowerState(JNIEnv* /* env */,
+        jclass /* clazz */, jboolean screenOn, jboolean screenBright) {
     AutoMutex _l(gPowerManagerLock);
     gScreenOn = screenOn;
     gScreenBright = screenBright;
 }
 
-static void nativeAcquireSuspendBlocker(JNIEnv *env, jclass clazz, jstring nameStr) {
+static void nativeAcquireSuspendBlocker(JNIEnv *env, jclass /* clazz */, jstring nameStr) {
     ScopedUtfChars name(env, nameStr);
     acquire_wake_lock(PARTIAL_WAKE_LOCK, name.c_str());
 }
 
-static void nativeReleaseSuspendBlocker(JNIEnv *env, jclass clazz, jstring nameStr) {
+static void nativeReleaseSuspendBlocker(JNIEnv *env, jclass /* clazz */, jstring nameStr) {
     ScopedUtfChars name(env, nameStr);
     release_wake_lock(name.c_str());
 }
 
-static void nativeSetInteractive(JNIEnv *env, jclass clazz, jboolean enable) {
+static void nativeSetInteractive(JNIEnv* /* env */, jclass /* clazz */, jboolean enable) {
     if (gPowerModule) {
         if (enable) {
             ALOGD_IF_SLOW(20, "Excessive delay in setInteractive(true) while turning screen on");
@@ -179,7 +179,7 @@
     }
 }
 
-static void nativeSetAutoSuspend(JNIEnv *env, jclass clazz, jboolean enable) {
+static void nativeSetAutoSuspend(JNIEnv* /* env */, jclass /* clazz */, jboolean enable) {
     if (enable) {
         ALOGD_IF_SLOW(100, "Excessive delay in autosuspend_enable() while turning screen off");
         autosuspend_enable();
diff --git a/services/jni/onload.cpp b/services/jni/onload.cpp
index efc34a2..68982a7 100644
--- a/services/jni/onload.cpp
+++ b/services/jni/onload.cpp
@@ -40,7 +40,7 @@
 
 using namespace android;
 
-extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved)
+extern "C" jint JNI_OnLoad(JavaVM* vm, void* /* reserved */)
 {
     JNIEnv* env = NULL;
     jint result = -1;
diff --git a/test-runner/src/android/test/TouchUtils.java b/test-runner/src/android/test/TouchUtils.java
index acbde0b..0fbffcd 100644
--- a/test-runner/src/android/test/TouchUtils.java
+++ b/test-runner/src/android/test/TouchUtils.java
@@ -576,7 +576,7 @@
         final int fromX = xy[0];
         final int fromY = xy[1];
         
-        int distance = (int) Math.sqrt(deltaX * deltaX + deltaY * deltaY);
+        int distance = (int) Math.hypot(deltaX, deltaY);
 
         drag(test, fromX, fromX + deltaX, fromY, fromY + deltaY, distance);
 
@@ -629,7 +629,7 @@
         int deltaX = fromX - toX;
         int deltaY = fromY - toY;
         
-        int distance = (int)Math.sqrt(deltaX * deltaX + deltaY * deltaY);
+        int distance = (int)Math.hypot(deltaX, deltaY);
         drag(test, fromX, toX, fromY, toY, distance);
         
         return distance;
diff --git a/tests/Camera2Tests/SmartCamera/SimpleCamera/src/androidx/media/filterfw/CropFilter.java b/tests/Camera2Tests/SmartCamera/SimpleCamera/src/androidx/media/filterfw/CropFilter.java
index 91fe21c..6c0f353 100644
--- a/tests/Camera2Tests/SmartCamera/SimpleCamera/src/androidx/media/filterfw/CropFilter.java
+++ b/tests/Camera2Tests/SmartCamera/SimpleCamera/src/androidx/media/filterfw/CropFilter.java
@@ -20,7 +20,6 @@
 import android.graphics.Canvas;
 import android.graphics.Matrix;
 import android.graphics.Paint;
-import android.util.FloatMath;
 
 import androidx.media.filterfw.Filter;
 import androidx.media.filterfw.FrameImage2D;
@@ -90,8 +89,8 @@
         // Pull input frame
         FrameImage2D inputImage = getConnectedInputPort("image").pullFrame().asFrameImage2D();
         int[] inDims = inputImage.getDimensions();
-        int[] croppedDims = { (int)FloatMath.ceil(mCropRect.xEdge().length() * inDims[0]),
-                              (int)FloatMath.ceil(mCropRect.yEdge().length() * inDims[1]) };
+        int[] croppedDims = { (int)Math.ceil(mCropRect.xEdge().length() * inDims[0]),
+                              (int)Math.ceil(mCropRect.yEdge().length() * inDims[1]) };
         int[] outDims = { getOutputWidth(croppedDims[0], croppedDims[1]),
                 getOutputHeight(croppedDims[0], croppedDims[1]) };
         FrameImage2D outputImage = outPort.fetchAvailableFrame(outDims).asFrameImage2D();
diff --git a/tools/aapt/AaptAssets.cpp b/tools/aapt/AaptAssets.cpp
index 19532e8..c262b00 100644
--- a/tools/aapt/AaptAssets.cpp
+++ b/tools/aapt/AaptAssets.cpp
@@ -13,7 +13,6 @@
 #include <dirent.h>
 #include <errno.h>
 
-static const char* kDefaultLocale = "default";
 static const char* kWildcardName = "any";
 static const char* kAssetDir = "assets";
 static const char* kResourceDir = "res";
@@ -193,7 +192,7 @@
 
 void AaptLocaleValue::setLanguage(const char* languageChars) {
      size_t i = 0;
-     while ((*languageChars) != '\0') {
+     while ((*languageChars) != '\0' && i < sizeof(language)/sizeof(language[0])) {
           language[i++] = tolower(*languageChars);
           languageChars++;
      }
@@ -201,7 +200,7 @@
 
 void AaptLocaleValue::setRegion(const char* regionChars) {
     size_t i = 0;
-    while ((*regionChars) != '\0') {
+    while ((*regionChars) != '\0' && i < sizeof(region)/sizeof(region[0])) {
          region[i++] = toupper(*regionChars);
          regionChars++;
     }
@@ -209,7 +208,7 @@
 
 void AaptLocaleValue::setScript(const char* scriptChars) {
     size_t i = 0;
-    while ((*scriptChars) != '\0') {
+    while ((*scriptChars) != '\0' && i < sizeof(script)/sizeof(script[0])) {
          if (i == 0) {
              script[i++] = toupper(*scriptChars);
          } else {
@@ -221,7 +220,7 @@
 
 void AaptLocaleValue::setVariant(const char* variantChars) {
      size_t i = 0;
-     while ((*variantChars) != '\0') {
+     while ((*variantChars) != '\0' && i < sizeof(variant)/sizeof(variant[0])) {
           variant[i++] = *variantChars;
           variantChars++;
      }
@@ -679,7 +678,6 @@
     String8 uiModeType, uiModeNight, smallestwidthdp, widthdp, heightdp;
 
     AaptLocaleValue locale;
-    int numLocaleComponents = 0;
 
     const int N = parts.size();
     int index = 0;
@@ -2538,7 +2536,7 @@
 }
 
 ssize_t
-AaptAssets::slurpResourceZip(Bundle* bundle, const char* filename)
+AaptAssets::slurpResourceZip(Bundle* /* bundle */, const char* filename)
 {
     int count = 0;
     SortedVector<AaptGroupEntry> entries;
diff --git a/tools/aapt/Android.mk b/tools/aapt/Android.mk
index 162edc4..ede6d9d 100644
--- a/tools/aapt/Android.mk
+++ b/tools/aapt/Android.mk
@@ -27,7 +27,6 @@
 	WorkQueue.cpp \
     ZipEntry.cpp \
     ZipFile.cpp \
-	qsort_r_compat.c
 
 LOCAL_PATH:= $(call my-dir)
 include $(CLEAR_VARS)
@@ -41,6 +40,7 @@
 endif
 
 LOCAL_CFLAGS += -DSTATIC_ANDROIDFW_FOR_TOOLS
+LOCAL_CFLAGS += -Wall -Werror
 
 LOCAL_C_INCLUDES += external/libpng
 LOCAL_C_INCLUDES += external/zlib
@@ -84,6 +84,7 @@
 LOCAL_C_INCLUDES += external/zlib
 
 LOCAL_CFLAGS += -Wno-non-virtual-dtor
+LOCAL_CFLAGS += -Wall -Werror
 
 LOCAL_SHARED_LIBRARIES := \
         libandroidfw \
diff --git a/tools/aapt/CacheUpdater.h b/tools/aapt/CacheUpdater.h
index 0e65589..0af5872 100644
--- a/tools/aapt/CacheUpdater.h
+++ b/tools/aapt/CacheUpdater.h
@@ -35,6 +35,8 @@
 
     // Process an image from source out to dest
     virtual void processImage(String8 source, String8 dest) = 0;
+
+    virtual ~CacheUpdater() {}
 private:
 };
 
@@ -104,4 +106,4 @@
     Bundle* bundle;
 };
 
-#endif // CACHE_UPDATER_H
\ No newline at end of file
+#endif // CACHE_UPDATER_H
diff --git a/tools/aapt/Command.cpp b/tools/aapt/Command.cpp
index f863311..7e7d346 100644
--- a/tools/aapt/Command.cpp
+++ b/tools/aapt/Command.cpp
@@ -196,11 +196,16 @@
             goto bail;
         }
 
-        const ResTable& res = assets.getResources(false);
-#ifndef HAVE_ANDROID_OS
-        printf("\nResource table:\n");
-        res.print(false);
+#ifdef HAVE_ANDROID_OS
+        static const bool kHaveAndroidOs = true;
+#else
+        static const bool kHaveAndroidOs = false;
 #endif
+        const ResTable& res = assets.getResources(false);
+        if (!kHaveAndroidOs) {
+            printf("\nResource table:\n");
+            res.print(false);
+        }
 
         Asset* manifestAsset = assets.openNonAsset("AndroidManifest.xml",
                                                    Asset::ACCESS_BUFFER);
diff --git a/tools/aapt/CrunchCache.cpp b/tools/aapt/CrunchCache.cpp
index c4cf6bc..6c39d1d 100644
--- a/tools/aapt/CrunchCache.cpp
+++ b/tools/aapt/CrunchCache.cpp
@@ -101,4 +101,4 @@
     time_t sourceDate = mSourceFiles.valueFor(mSourcePath.appendPathCopy(relativePath));
     time_t destDate = mDestFiles.valueFor(mDestPath.appendPathCopy(relativePath));
     return sourceDate > destDate;
-}
\ No newline at end of file
+}
diff --git a/tools/aapt/Images.cpp b/tools/aapt/Images.cpp
index db74831..efa88e7 100644
--- a/tools/aapt/Images.cpp
+++ b/tools/aapt/Images.cpp
@@ -14,7 +14,8 @@
 #include <png.h>
 #include <zlib.h>
 
-#define NOISY(x) //x
+// Change this to true for noisy debug output.
+static const bool kIsDebug = false;
 
 static void
 png_write_aapt_file(png_structp png_ptr, png_bytep data, png_size_t length)
@@ -28,7 +29,7 @@
 
 
 static void
-png_flush_aapt_file(png_structp png_ptr)
+png_flush_aapt_file(png_structp /* png_ptr */)
 {
 }
 
@@ -138,11 +139,13 @@
 
     png_read_end(read_ptr, read_info);
 
-    NOISY(printf("Image %s: w=%d, h=%d, d=%d, colors=%d, inter=%d, comp=%d\n",
-                 imageName,
-                 (int)outImageInfo->width, (int)outImageInfo->height,
-                 bit_depth, color_type,
-                 interlace_type, compression_type));
+    if (kIsDebug) {
+        printf("Image %s: w=%d, h=%d, d=%d, colors=%d, inter=%d, comp=%d\n",
+                imageName,
+                (int)outImageInfo->width, (int)outImageInfo->height,
+                bit_depth, color_type,
+                interlace_type, compression_type);
+    }
 
     png_get_IHDR(read_ptr, read_info, &outImageInfo->width,
        &outImageInfo->height, &bit_depth, &color_type,
@@ -312,7 +315,7 @@
 }
 
 static status_t get_horizontal_layout_bounds_ticks(
-        png_bytep row, int width, bool transparent, bool required,
+        png_bytep row, int width, bool transparent, bool /* required */,
         int32_t* outLeft, int32_t* outRight, const char** outError)
 {
     int i;
@@ -350,7 +353,7 @@
 }
 
 static status_t get_vertical_layout_bounds_ticks(
-        png_bytepp rows, int offset, int height, bool transparent, bool required,
+        png_bytepp rows, int offset, int height, bool transparent, bool /* required */,
         int32_t* outTop, int32_t* outBottom, const char** outError)
 {
     int i;
@@ -418,41 +421,6 @@
     return (color[3]<<24) | (color[0]<<16) | (color[1]<<8) | color[2];
 }
 
-static void select_patch(
-    int which, int front, int back, int size, int* start, int* end)
-{
-    switch (which) {
-    case 0:
-        *start = 0;
-        *end = front-1;
-        break;
-    case 1:
-        *start = front;
-        *end = back-1;
-        break;
-    case 2:
-        *start = back;
-        *end = size-1;
-        break;
-    }
-}
-
-static uint32_t get_color(image_info* image, int hpatch, int vpatch)
-{
-    int left, right, top, bottom;
-    select_patch(
-        hpatch, image->xDivs[0], image->xDivs[1],
-        image->width, &left, &right);
-    select_patch(
-        vpatch, image->yDivs[0], image->yDivs[1],
-        image->height, &top, &bottom);
-    //printf("Selecting h=%d v=%d: (%d,%d)-(%d,%d)\n",
-    //       hpatch, vpatch, left, top, right, bottom);
-    const uint32_t c = get_color(image->rows, left, top, right, bottom);
-    NOISY(printf("Color in (%d,%d)-(%d,%d): #%08x\n", left, top, right, bottom, c));
-    return c;
-}
-
 static status_t do_9patch(const char* imageName, image_info* image)
 {
     image->is9Patch = true;
@@ -557,8 +525,10 @@
                                || image->layoutBoundsBottom != 0;
 
     if (image->haveLayoutBounds) {
-        NOISY(printf("layoutBounds=%d %d %d %d\n", image->layoutBoundsLeft, image->layoutBoundsTop,
-                image->layoutBoundsRight, image->layoutBoundsBottom));
+        if (kIsDebug) {
+            printf("layoutBounds=%d %d %d %d\n", image->layoutBoundsLeft, image->layoutBoundsTop,
+                    image->layoutBoundsRight, image->layoutBoundsBottom);
+        }
     }
 
     // If padding is not yet specified, take values from size.
@@ -577,12 +547,14 @@
         image->info9Patch.paddingBottom = H - 2 - image->info9Patch.paddingBottom;
     }
 
-    NOISY(printf("Size ticks for %s: x0=%d, x1=%d, y0=%d, y1=%d\n", imageName,
-                 image->info9Patch.xDivs[0], image->info9Patch.xDivs[1],
-                 image->info9Patch.yDivs[0], image->info9Patch.yDivs[1]));
-    NOISY(printf("padding ticks for %s: l=%d, r=%d, t=%d, b=%d\n", imageName,
-                 image->info9Patch.paddingLeft, image->info9Patch.paddingRight,
-                 image->info9Patch.paddingTop, image->info9Patch.paddingBottom));
+    if (kIsDebug) {
+        printf("Size ticks for %s: x0=%d, x1=%d, y0=%d, y1=%d\n", imageName,
+                image->info9Patch.getXDivs()[0], image->info9Patch.getXDivs()[1],
+                image->info9Patch.getYDivs()[0], image->info9Patch.getYDivs()[1]);
+        printf("padding ticks for %s: l=%d, r=%d, t=%d, b=%d\n", imageName,
+                image->info9Patch.paddingLeft, image->info9Patch.paddingRight,
+                image->info9Patch.paddingTop, image->info9Patch.paddingBottom);
+    }
 
     // Remove frame from image.
     image->rows = (png_bytepp)malloc((H-2) * sizeof(png_bytep));
@@ -664,7 +636,10 @@
             }
             c = get_color(image->rows, left, top, right - 1, bottom - 1);
             image->colors[colorIndex++] = c;
-            NOISY(if (c != Res_png_9patch::NO_COLOR) hasColor = true);
+            if (kIsDebug) {
+                if (c != Res_png_9patch::NO_COLOR)
+                    hasColor = true;
+            }
             left = right;
         }
         top = bottom;
@@ -767,7 +742,7 @@
                 break;
             }
             if (i == (w - 1)) {
-                NOISY(printf("\n"));
+                printf("\n");
             }
         }
     }
@@ -797,8 +772,10 @@
     // 2. Every pixel has A == 255 (opaque)
     // 3. There are no more than 256 distinct RGBA colors
 
-    // NOISY(printf("Initial image data:\n"));
-    // dump_image(w, h, imageInfo.rows, PNG_COLOR_TYPE_RGB_ALPHA);
+    if (kIsDebug) {
+        printf("Initial image data:\n");
+        dump_image(w, h, imageInfo.rows, PNG_COLOR_TYPE_RGB_ALPHA);
+    }
 
     for (j = 0; j < h; j++) {
         png_bytep row = imageInfo.rows[j];
@@ -814,15 +791,19 @@
             maxGrayDeviation = MAX(ABS(gg - bb), maxGrayDeviation);
             maxGrayDeviation = MAX(ABS(bb - rr), maxGrayDeviation);
             if (maxGrayDeviation > odev) {
-                NOISY(printf("New max dev. = %d at pixel (%d, %d) = (%d %d %d %d)\n",
-                             maxGrayDeviation, i, j, rr, gg, bb, aa));
+                if (kIsDebug) {
+                    printf("New max dev. = %d at pixel (%d, %d) = (%d %d %d %d)\n",
+                            maxGrayDeviation, i, j, rr, gg, bb, aa);
+                }
             }
 
             // Check if image is really grayscale
             if (isGrayscale) {
                 if (rr != gg || rr != bb) {
-                     NOISY(printf("Found a non-gray pixel at %d, %d = (%d %d %d %d)\n",
-                                  i, j, rr, gg, bb, aa));
+                    if (kIsDebug) {
+                        printf("Found a non-gray pixel at %d, %d = (%d %d %d %d)\n",
+                                i, j, rr, gg, bb, aa);
+                    }
                     isGrayscale = false;
                 }
             }
@@ -830,8 +811,10 @@
             // Check if image is really opaque
             if (isOpaque) {
                 if (aa != 0xff) {
-                    NOISY(printf("Found a non-opaque pixel at %d, %d = (%d %d %d %d)\n",
-                                 i, j, rr, gg, bb, aa));
+                    if (kIsDebug) {
+                        printf("Found a non-opaque pixel at %d, %d = (%d %d %d %d)\n",
+                                i, j, rr, gg, bb, aa);
+                    }
                     isOpaque = false;
                 }
             }
@@ -853,7 +836,9 @@
                 *out++ = idx;
                 if (!match) {
                     if (num_colors == 256) {
-                        NOISY(printf("Found 257th color at %d, %d\n", i, j));
+                        if (kIsDebug) {
+                            printf("Found 257th color at %d, %d\n", i, j);
+                        }
                         isPalette = false;
                     } else {
                         colors[num_colors++] = col;
@@ -868,12 +853,14 @@
     int bpp = isOpaque ? 3 : 4;
     int paletteSize = w * h + bpp * num_colors;
 
-    NOISY(printf("isGrayscale = %s\n", isGrayscale ? "true" : "false"));
-    NOISY(printf("isOpaque = %s\n", isOpaque ? "true" : "false"));
-    NOISY(printf("isPalette = %s\n", isPalette ? "true" : "false"));
-    NOISY(printf("Size w/ palette = %d, gray+alpha = %d, rgb(a) = %d\n",
-                 paletteSize, 2 * w * h, bpp * w * h));
-    NOISY(printf("Max gray deviation = %d, tolerance = %d\n", maxGrayDeviation, grayscaleTolerance));
+    if (kIsDebug) {
+        printf("isGrayscale = %s\n", isGrayscale ? "true" : "false");
+        printf("isOpaque = %s\n", isOpaque ? "true" : "false");
+        printf("isPalette = %s\n", isPalette ? "true" : "false");
+        printf("Size w/ palette = %d, gray+alpha = %d, rgb(a) = %d\n",
+                paletteSize, 2 * w * h, bpp * w * h);
+        printf("Max gray deviation = %d, tolerance = %d\n", maxGrayDeviation, grayscaleTolerance);
+    }
 
     // Choose the best color type for the image.
     // 1. Opaque gray - use COLOR_TYPE_GRAY at 1 byte/pixel
@@ -950,7 +937,6 @@
                       png_structp write_ptr, png_infop write_info,
                       image_info& imageInfo, int grayscaleTolerance)
 {
-    bool optimize = true;
     png_uint_32 width, height;
     int color_type;
     int bit_depth, interlace_type, compression_type;
@@ -975,8 +961,10 @@
 
     png_set_compression_level(write_ptr, Z_BEST_COMPRESSION);
 
-    NOISY(printf("Writing image %s: w = %d, h = %d\n", imageName,
-          (int) imageInfo.width, (int) imageInfo.height));
+    if (kIsDebug) {
+        printf("Writing image %s: w = %d, h = %d\n", imageName,
+                (int) imageInfo.width, (int) imageInfo.height);
+    }
 
     png_color rgbPalette[256];
     png_byte alphaPalette[256];
@@ -993,24 +981,26 @@
         color_type = PNG_COLOR_TYPE_RGB_ALPHA;
     }
 
-    switch (color_type) {
-    case PNG_COLOR_TYPE_PALETTE:
-        NOISY(printf("Image %s has %d colors%s, using PNG_COLOR_TYPE_PALETTE\n",
-                     imageName, paletteEntries,
-                     hasTransparency ? " (with alpha)" : ""));
-        break;
-    case PNG_COLOR_TYPE_GRAY:
-        NOISY(printf("Image %s is opaque gray, using PNG_COLOR_TYPE_GRAY\n", imageName));
-        break;
-    case PNG_COLOR_TYPE_GRAY_ALPHA:
-        NOISY(printf("Image %s is gray + alpha, using PNG_COLOR_TYPE_GRAY_ALPHA\n", imageName));
-        break;
-    case PNG_COLOR_TYPE_RGB:
-        NOISY(printf("Image %s is opaque RGB, using PNG_COLOR_TYPE_RGB\n", imageName));
-        break;
-    case PNG_COLOR_TYPE_RGB_ALPHA:
-        NOISY(printf("Image %s is RGB + alpha, using PNG_COLOR_TYPE_RGB_ALPHA\n", imageName));
-        break;
+    if (kIsDebug) {
+        switch (color_type) {
+        case PNG_COLOR_TYPE_PALETTE:
+            printf("Image %s has %d colors%s, using PNG_COLOR_TYPE_PALETTE\n",
+                    imageName, paletteEntries,
+                    hasTransparency ? " (with alpha)" : "");
+            break;
+        case PNG_COLOR_TYPE_GRAY:
+            printf("Image %s is opaque gray, using PNG_COLOR_TYPE_GRAY\n", imageName);
+            break;
+        case PNG_COLOR_TYPE_GRAY_ALPHA:
+            printf("Image %s is gray + alpha, using PNG_COLOR_TYPE_GRAY_ALPHA\n", imageName);
+            break;
+        case PNG_COLOR_TYPE_RGB:
+            printf("Image %s is opaque RGB, using PNG_COLOR_TYPE_RGB\n", imageName);
+            break;
+        case PNG_COLOR_TYPE_RGB_ALPHA:
+            printf("Image %s is RGB + alpha, using PNG_COLOR_TYPE_RGB_ALPHA\n", imageName);
+            break;
+        }
     }
 
     png_set_IHDR(write_ptr, write_info, imageInfo.width, imageInfo.height,
@@ -1034,7 +1024,9 @@
         png_byte *chunk_names = imageInfo.haveLayoutBounds
                 ? (png_byte*)"npLb\0npTc\0"
                 : (png_byte*)"npTc";
-        NOISY(printf("Adding 9-patch info...\n"));
+        if (kIsDebug) {
+            printf("Adding 9-patch info...\n");
+        }
         strcpy((char*)unknowns[p_index].name, "npTc");
         unknowns[p_index].data = (png_byte*)imageInfo.serialize9patch();
         unknowns[p_index].size = imageInfo.info9Patch.serializedSize();
@@ -1078,8 +1070,10 @@
     }
     png_write_image(write_ptr, rows);
 
-//     NOISY(printf("Final image data:\n"));
-//     dump_image(imageInfo.width, imageInfo.height, rows, color_type);
+    if (kIsDebug) {
+        printf("Final image data:\n");
+        dump_image(imageInfo.width, imageInfo.height, rows, color_type);
+    }
 
     png_write_end(write_ptr, write_info);
 
@@ -1094,13 +1088,50 @@
        &bit_depth, &color_type, &interlace_type,
        &compression_type, NULL);
 
-    NOISY(printf("Image written: w=%d, h=%d, d=%d, colors=%d, inter=%d, comp=%d\n",
-                 (int)width, (int)height, bit_depth, color_type, interlace_type,
-                 compression_type));
+    if (kIsDebug) {
+        printf("Image written: w=%d, h=%d, d=%d, colors=%d, inter=%d, comp=%d\n",
+                (int)width, (int)height, bit_depth, color_type, interlace_type,
+                compression_type);
+    }
 }
 
-status_t preProcessImage(const Bundle* bundle, const sp<AaptAssets>& assets,
-                         const sp<AaptFile>& file, String8* outNewLeafName)
+static bool read_png_protected(png_structp read_ptr, String8& printableName, png_infop read_info,
+                               const sp<AaptFile>& file, FILE* fp, image_info* imageInfo) {
+    if (setjmp(png_jmpbuf(read_ptr))) {
+        return false;
+    }
+
+    png_init_io(read_ptr, fp);
+
+    read_png(printableName.string(), read_ptr, read_info, imageInfo);
+
+    const size_t nameLen = file->getPath().length();
+    if (nameLen > 6) {
+        const char* name = file->getPath().string();
+        if (name[nameLen-5] == '9' && name[nameLen-6] == '.') {
+            if (do_9patch(printableName.string(), imageInfo) != NO_ERROR) {
+                return false;
+            }
+        }
+    }
+
+    return true;
+}
+
+static bool write_png_protected(png_structp write_ptr, String8& printableName, png_infop write_info,
+                                image_info* imageInfo, const Bundle* bundle) {
+    if (setjmp(png_jmpbuf(write_ptr))) {
+        return false;
+    }
+
+    write_png(printableName.string(), write_ptr, write_info, *imageInfo,
+              bundle->getGrayscaleTolerance());
+
+    return true;
+}
+
+status_t preProcessImage(const Bundle* bundle, const sp<AaptAssets>& /* assets */,
+                         const sp<AaptFile>& file, String8* /* outNewLeafName */)
 {
     String8 ext(file->getPath().getPathExtension());
 
@@ -1130,8 +1161,6 @@
 
     status_t error = UNKNOWN_ERROR;
 
-    const size_t nameLen = file->getPath().length();
-
     fp = fopen(file->getSourceFile().string(), "rb");
     if (fp == NULL) {
         fprintf(stderr, "%s: ERROR: Unable to open PNG file\n", printableName.string());
@@ -1149,23 +1178,10 @@
         goto bail;
     }
 
-    if (setjmp(png_jmpbuf(read_ptr))) {
+    if (!read_png_protected(read_ptr, printableName, read_info, file, fp, &imageInfo)) {
         goto bail;
     }
 
-    png_init_io(read_ptr, fp);
-
-    read_png(printableName.string(), read_ptr, read_info, &imageInfo);
-
-    if (nameLen > 6) {
-        const char* name = file->getPath().string();
-        if (name[nameLen-5] == '9' && name[nameLen-6] == '.') {
-            if (do_9patch(printableName.string(), &imageInfo) != NO_ERROR) {
-                goto bail;
-            }
-        }
-    }
-
     write_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, 0, (png_error_ptr)NULL,
                                         (png_error_ptr)NULL);
     if (!write_ptr)
@@ -1182,14 +1198,10 @@
     png_set_write_fn(write_ptr, (void*)file.get(),
                      png_write_aapt_file, png_flush_aapt_file);
 
-    if (setjmp(png_jmpbuf(write_ptr)))
-    {
+    if (!write_png_protected(write_ptr, printableName, write_info, &imageInfo, bundle)) {
         goto bail;
     }
 
-    write_png(printableName.string(), write_ptr, write_info, imageInfo,
-              bundle->getGrayscaleTolerance());
-
     error = NO_ERROR;
 
     if (bundle->getVerbose()) {
diff --git a/tools/aapt/Package.cpp b/tools/aapt/Package.cpp
index 872d95c..26cc3c1 100644
--- a/tools/aapt/Package.cpp
+++ b/tools/aapt/Package.cpp
@@ -455,7 +455,6 @@
 
 ssize_t processJarFile(ZipFile* jar, ZipFile* out)
 {
-    status_t err;
     size_t N = jar->getNumEntries();
     size_t count = 0;
     for (size_t i=0; i<N; i++) {
diff --git a/tools/aapt/Resource.cpp b/tools/aapt/Resource.cpp
index f842bee..6ebf41f1 100644
--- a/tools/aapt/Resource.cpp
+++ b/tools/aapt/Resource.cpp
@@ -16,15 +16,19 @@
 
 #include "WorkQueue.h"
 
+// STATUST: mingw does seem to redefine UNKNOWN_ERROR from our enum value, so a cast is necessary.
 #if HAVE_PRINTF_ZD
 #  define ZD "%zd"
 #  define ZD_TYPE ssize_t
+#  define STATUST(x) x
 #else
 #  define ZD "%ld"
 #  define ZD_TYPE long
+#  define STATUST(x) (status_t)x
 #endif
 
-#define NOISY(x) // x
+// Set to true for noisy debug output.
+static const bool kIsDebug = false;
 
 // Number of threads to use for preprocessing images.
 static const size_t MAX_THREADS = 4;
@@ -125,15 +129,17 @@
             String8 leaf(group->getLeaf());
             mLeafName = String8(leaf);
             mParams = file->getGroupEntry().toParams();
-            NOISY(printf("Dir %s: mcc=%d mnc=%d lang=%c%c cnt=%c%c orient=%d ui=%d density=%d touch=%d key=%d inp=%d nav=%d\n",
-                   group->getPath().string(), mParams.mcc, mParams.mnc,
-                   mParams.language[0] ? mParams.language[0] : '-',
-                   mParams.language[1] ? mParams.language[1] : '-',
-                   mParams.country[0] ? mParams.country[0] : '-',
-                   mParams.country[1] ? mParams.country[1] : '-',
-                   mParams.orientation, mParams.uiMode,
-                   mParams.density, mParams.touchscreen, mParams.keyboard,
-                   mParams.inputFlags, mParams.navigation));
+            if (kIsDebug) {
+                printf("Dir %s: mcc=%d mnc=%d lang=%c%c cnt=%c%c orient=%d ui=%d density=%d touch=%d key=%d inp=%d nav=%d\n",
+                        group->getPath().string(), mParams.mcc, mParams.mnc,
+                        mParams.language[0] ? mParams.language[0] : '-',
+                        mParams.language[1] ? mParams.language[1] : '-',
+                        mParams.country[0] ? mParams.country[0] : '-',
+                        mParams.country[1] ? mParams.country[1] : '-',
+                        mParams.orientation, mParams.uiMode,
+                        mParams.density, mParams.touchscreen, mParams.keyboard,
+                        mParams.inputFlags, mParams.navigation);
+            }
             mPath = "res";
             mPath.appendPath(file->getGroupEntry().toDirName(mResType));
             mPath.appendPath(leaf);
@@ -144,7 +150,9 @@
                 return UNKNOWN_ERROR;
             }
 
-            NOISY(printf("file name=%s\n", mBaseName.string()));
+            if (kIsDebug) {
+                printf("file name=%s\n", mBaseName.string());
+            }
 
             return NO_ERROR;
         }
@@ -306,7 +314,7 @@
         assets->addResource(it.getLeafName(), resPath, it.getFile(), type8);
     }
 
-    return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
+    return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
 }
 
 class PreProcessImageWorkUnit : public WorkQueue::WorkUnit {
@@ -356,7 +364,7 @@
             hasErrors = true;
         }
     }
-    return (hasErrors || (res < NO_ERROR)) ? UNKNOWN_ERROR : NO_ERROR;
+    return (hasErrors || (res < NO_ERROR)) ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
 }
 
 status_t postProcessImages(const sp<AaptAssets>& assets,
@@ -373,7 +381,7 @@
         }
     }
 
-    return (hasErrors || (res < NO_ERROR)) ? UNKNOWN_ERROR : NO_ERROR;
+    return (hasErrors || (res < NO_ERROR)) ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
 }
 
 static void collect_files(const sp<AaptDir>& dir,
@@ -398,27 +406,35 @@
 
         if (index < 0) {
             sp<ResourceTypeSet> set = new ResourceTypeSet();
-            NOISY(printf("Creating new resource type set for leaf %s with group %s (%p)\n",
-                    leafName.string(), group->getPath().string(), group.get()));
+            if (kIsDebug) {
+                printf("Creating new resource type set for leaf %s with group %s (%p)\n",
+                        leafName.string(), group->getPath().string(), group.get());
+            }
             set->add(leafName, group);
             resources->add(resType, set);
         } else {
             sp<ResourceTypeSet> set = resources->valueAt(index);
             index = set->indexOfKey(leafName);
             if (index < 0) {
-                NOISY(printf("Adding to resource type set for leaf %s group %s (%p)\n",
-                        leafName.string(), group->getPath().string(), group.get()));
+                if (kIsDebug) {
+                    printf("Adding to resource type set for leaf %s group %s (%p)\n",
+                            leafName.string(), group->getPath().string(), group.get());
+                }
                 set->add(leafName, group);
             } else {
                 sp<AaptGroup> existingGroup = set->valueAt(index);
-                NOISY(printf("Extending to resource type set for leaf %s group %s (%p)\n",
-                        leafName.string(), group->getPath().string(), group.get()));
+                if (kIsDebug) {
+                    printf("Extending to resource type set for leaf %s group %s (%p)\n",
+                            leafName.string(), group->getPath().string(), group.get());
+                }
                 for (size_t j=0; j<files.size(); j++) {
-                    NOISY(printf("Adding file %s in group %s resType %s\n",
-                        files.valueAt(j)->getSourceFile().string(),
-                        files.keyAt(j).toDirName(String8()).string(),
-                        resType.string()));
-                    status_t err = existingGroup->addFile(files.valueAt(j));
+                    if (kIsDebug) {
+                        printf("Adding file %s in group %s resType %s\n",
+                                files.valueAt(j)->getSourceFile().string(),
+                                files.keyAt(j).toDirName(String8()).string(),
+                                resType.string());
+                    }
+                    existingGroup->addFile(files.valueAt(j));
                 }
             }
         }
@@ -433,12 +449,16 @@
 
     for (int i=0; i<N; i++) {
         sp<AaptDir> d = dirs.itemAt(i);
-        NOISY(printf("Collecting dir #%d %p: %s, leaf %s\n", i, d.get(), d->getPath().string(),
-                d->getLeaf().string()));
+        if (kIsDebug) {
+            printf("Collecting dir #%d %p: %s, leaf %s\n", i, d.get(), d->getPath().string(),
+                    d->getLeaf().string());
+        }
         collect_files(d, resources);
 
         // don't try to include the res dir
-        NOISY(printf("Removing dir leaf %s\n", d->getLeaf().string()));
+        if (kIsDebug) {
+            printf("Removing dir leaf %s\n", d->getLeaf().string());
+        }
         ass->removeDir(d->getLeaf());
     }
 }
@@ -595,11 +615,11 @@
                 if (bundle->getVerbose()) {
                     printf("trying overlaySet Key=%s\n",overlaySet->keyAt(overlayIndex).string());
                 }
-                size_t baseIndex = UNKNOWN_ERROR;
+                ssize_t baseIndex = UNKNOWN_ERROR;
                 if (baseSet->get() != NULL) {
                     baseIndex = (*baseSet)->indexOfKey(overlaySet->keyAt(overlayIndex));
                 }
-                if (baseIndex < UNKNOWN_ERROR) {
+                if (baseIndex >= 0) {
                     // look for same flavor.  For a given file (strings.xml, for example)
                     // there may be a locale specific or other flavors - we want to match
                     // the same flavor.
@@ -625,10 +645,10 @@
                     for (size_t overlayGroupIndex = 0;
                             overlayGroupIndex<overlayGroupSize;
                             overlayGroupIndex++) {
-                        size_t baseFileIndex =
+                        ssize_t baseFileIndex =
                                 baseGroup->getFiles().indexOfKey(overlayFiles.
                                 keyAt(overlayGroupIndex));
-                        if (baseFileIndex < UNKNOWN_ERROR) {
+                        if (baseFileIndex >= 0) {
                             if (bundle->getVerbose()) {
                                 printf("found a match (" ZD ") for overlay file %s, for flavor %s\n",
                                         (ZD_TYPE) baseFileIndex,
@@ -734,7 +754,9 @@
         } else {
             className += name;
         }
-        NOISY(printf("Qualifying class '%s' to '%s'", name.string(), className.string()));
+        if (kIsDebug) {
+            printf("Qualifying class '%s' to '%s'", name.string(), className.string());
+        }
         attr->string.setTo(String16(className));
     }
 }
@@ -802,7 +824,10 @@
         }
         String8 origPackage(attr->string);
         attr->string.setTo(String16(manifestPackageNameOverride));
-        NOISY(printf("Overriding package '%s' to be '%s'\n", origPackage.string(), manifestPackageNameOverride));
+        if (kIsDebug) {
+            printf("Overriding package '%s' to be '%s'\n", origPackage.string(),
+                    manifestPackageNameOverride);
+        }
 
         // Make class names fully qualified
         sp<XMLNode> application = root->getChildElement(String16(), String16("application"));
@@ -898,8 +923,9 @@
         return err;
     }
 
-    NOISY(printf("Creating resources for package %s\n",
-                 assets->getPackage().string()));
+    if (kIsDebug) {
+        printf("Creating resources for package %s\n", assets->getPackage().string());
+    }
 
     ResourceTable table(bundle, String16(assets->getPackage()));
     err = table.addIncludedResources(bundle, assets);
@@ -907,7 +933,9 @@
         return err;
     }
 
-    NOISY(printf("Found %d included resource packages\n", (int)table.size()));
+    if (kIsDebug) {
+        printf("Found %d included resource packages\n", (int)table.size());
+    }
 
     // Standard flags for compiled XML and optional UTF-8 encoding
     int xmlFlags = XML_COMPILE_STANDARD_RESOURCE;
@@ -1322,12 +1350,6 @@
 
         // Read resources back in,
         finalResTable.add(resFile->getData(), resFile->getSize());
-#if 0
-        NOISY(
-              printf("Generated resources:\n");
-              finalResTable.print();
-        )
-#endif
     }
 
     // Perform a basic validation of the manifest file.  This time we
@@ -1889,7 +1911,7 @@
 
     indent--;
     fprintf(fp, "%s};\n", getIndentSpace(indent));
-    return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
+    return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
 }
 
 static status_t writeTextLayoutClasses(
@@ -1975,7 +1997,7 @@
                     package16.string(), package16.size(), &typeSpecFlags);
                 //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
                 //    String8(attr16).string(), String8(name16).string(), typeSpecFlags);
-                const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
+                //const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
 
                 fprintf(fp,
                         "int styleable %s_%s %d\n",
@@ -1985,7 +2007,7 @@
         }
     }
 
-    return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
+    return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
 }
 
 static status_t writeSymbolClass(
@@ -2318,7 +2340,7 @@
 
 void
 addProguardKeepMethodRule(ProguardKeepSet* keep, const String8& memberName,
-        const char* pkg, const String8& srcName, int line)
+        const char* /* pkg */, const String8& srcName, int line)
 {
     String8 rule("-keepclassmembers class * { *** ");
     rule += memberName;
@@ -2640,7 +2662,7 @@
 }
 
 status_t
-writeDependencyPreReqs(Bundle* bundle, const sp<AaptAssets>& assets, FILE* fp, bool includeRaw)
+writeDependencyPreReqs(Bundle* /* bundle */, const sp<AaptAssets>& assets, FILE* fp, bool includeRaw)
 {
     status_t deps = -1;
     deps += writePathsToFile(assets->getFullResPaths(), fp);
diff --git a/tools/aapt/ResourceIdCache.cpp b/tools/aapt/ResourceIdCache.cpp
index 359443d..6e30938 100644
--- a/tools/aapt/ResourceIdCache.cpp
+++ b/tools/aapt/ResourceIdCache.cpp
@@ -97,10 +97,10 @@
 
 void ResourceIdCache::dump() {
     printf("ResourceIdCache dump:\n");
-    printf("Size: %ld\n", mIdMap.size());
-    printf("Hits:   %ld\n", mHits);
-    printf("Misses: %ld\n", mMisses);
-    printf("(Collisions: %ld)\n", mCollisions);
+    printf("Size: %zu\n", mIdMap.size());
+    printf("Hits:   %zu\n", mHits);
+    printf("Misses: %zu\n", mMisses);
+    printf("(Collisions: %zu)\n", mCollisions);
 }
 
 }
diff --git a/tools/aapt/ResourceTable.cpp b/tools/aapt/ResourceTable.cpp
index 6632809..6e7f3fb 100644
--- a/tools/aapt/ResourceTable.cpp
+++ b/tools/aapt/ResourceTable.cpp
@@ -14,7 +14,24 @@
 #include <utils/ByteOrder.h>
 #include <stdarg.h>
 
-#define NOISY(x) //x
+// SSIZE: mingw does not have signed size_t == ssize_t.
+// STATUST: mingw does seem to redefine UNKNOWN_ERROR from our enum value, so a cast is necessary.
+#if HAVE_PRINTF_ZD
+#  define SSIZE(x) x
+#  define STATUST(x) x
+#else
+#  define SSIZE(x) (signed size_t)x
+#  define STATUST(x) (status_t)x
+#endif
+
+// Set to true for noisy debug output.
+static const bool kIsDebug = false;
+
+#if PRINT_STRING_METRICS
+static const bool kPrintStringMetrics = true;
+#else
+static const bool kPrintStringMetrics = false;
+#endif
 
 status_t compileXmlFile(const sp<AaptAssets>& assets,
                         const sp<AaptFile>& target,
@@ -76,9 +93,11 @@
     if (hasErrors) {
         return UNKNOWN_ERROR;
     }
-    
-    NOISY(printf("Input XML Resource:\n"));
-    NOISY(root->print());
+
+    if (kIsDebug) {
+        printf("Input XML Resource:\n");
+        root->print();
+    }
     err = root->flatten(target,
             (options&XML_COMPILE_STRIP_COMMENTS) != 0,
             (options&XML_COMPILE_STRIP_RAW_VALUES) != 0);
@@ -86,19 +105,18 @@
         return err;
     }
 
-    NOISY(printf("Output XML Resource:\n"));
-    NOISY(ResXMLTree tree;
+    if (kIsDebug) {
+        printf("Output XML Resource:\n");
+        ResXMLTree tree;
         tree.setTo(target->getData(), target->getSize());
-        printXMLBlock(&tree));
+        printXMLBlock(&tree);
+    }
 
     target->setCompressionMethod(ZipEntry::kCompressDeflated);
     
     return err;
 }
 
-#undef NOISY
-#define NOISY(x) //x
-
 struct flag_entry
 {
     const char16_t* name;
@@ -576,7 +594,7 @@
                         const String16& itemIdent,
                         int32_t curFormat,
                         bool isFormatted,
-                        const String16& product,
+                        const String16& /* product */,
                         PseudolocalizationMethod pseudolocalize,
                         const bool overwrite,
                         ResourceTable* outTable)
@@ -592,16 +610,18 @@
     if (err != NO_ERROR) {
         return err;
     }
-    
-    NOISY(printf("Adding resource bag entry l=%c%c c=%c%c orien=%d d=%d "
-                 " pid=%s, bag=%s, id=%s: %s\n",
-                 config.language[0], config.language[1],
-                 config.country[0], config.country[1],
-                 config.orientation, config.density,
-                 String8(parentIdent).string(),
-                 String8(ident).string(),
-                 String8(itemIdent).string(),
-                 String8(str).string()));
+
+    if (kIsDebug) {
+        printf("Adding resource bag entry l=%c%c c=%c%c orien=%d d=%d "
+                " pid=%s, bag=%s, id=%s: %s\n",
+                config.language[0], config.language[1],
+                config.country[0], config.country[1],
+                config.orientation, config.density,
+                String8(parentIdent).string(),
+                String8(ident).string(),
+                String8(itemIdent).string(),
+                String8(str).string());
+    }
 
     err = outTable->addBag(SourcePos(in->getPrintableSource(), block->getLineNumber()),
                            myPackage, curType, ident, parentIdent, itemIdent, str,
@@ -737,11 +757,13 @@
         }
     }
 
-    NOISY(printf("Adding resource entry l=%c%c c=%c%c orien=%d d=%d id=%s: %s\n",
-                 config.language[0], config.language[1],
-                 config.country[0], config.country[1],
-                 config.orientation, config.density,
-                 String8(ident).string(), String8(str).string()));
+    if (kIsDebug) {
+        printf("Adding resource entry l=%c%c c=%c%c orien=%d d=%d id=%s: %s\n",
+                config.language[0], config.language[1],
+                config.country[0], config.country[1],
+                config.orientation, config.density,
+                String8(ident).string(), String8(str).string());
+    }
 
     err = outTable->addEntry(SourcePos(in->getPrintableSource(), block->getLineNumber()),
                              myPackage, curType, ident, str, &spans, &config,
@@ -1710,7 +1732,7 @@
         }
     }
 
-    return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
+    return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
 }
 
 ResourceTable::ResourceTable(Bundle* bundle, const String16& assetsPackage)
@@ -1764,8 +1786,9 @@
                 }
             }
             if (id != 0) {
-                NOISY(printf("Including package %s with ID=%d\n",
-                             String8(name).string(), id));
+                if (kIsDebug) {
+                    printf("Including package %s with ID=%d\n", String8(name).string(), id);
+                }
                 sp<Package> p = new Package(name, id);
                 mPackages.add(name, p);
                 mOrderedPackages.add(p);
@@ -1856,7 +1879,7 @@
                                  const String16& bagParent,
                                  const ResTable_config* params,
                                  bool overlay,
-                                 bool replace, bool isId)
+                                 bool replace, bool /* isId */)
 {
     status_t result = NO_ERROR;
 
@@ -2163,22 +2186,25 @@
         ref.string(), ref.size(), &package, &type, &name,
         defType, defPackage ? defPackage:&mAssetsPackage,
         outErrorMsg, &refOnlyPublic)) {
-        NOISY(printf("Expanding resource: ref=%s\n",
-                     String8(ref).string()));
-        NOISY(printf("Expanding resource: defType=%s\n",
-                     defType ? String8(*defType).string() : "NULL"));
-        NOISY(printf("Expanding resource: defPackage=%s\n",
-                     defPackage ? String8(*defPackage).string() : "NULL"));
-        NOISY(printf("Expanding resource: ref=%s\n", String8(ref).string()));
-        NOISY(printf("Expanded resource: p=%s, t=%s, n=%s, res=0\n",
-                     String8(package).string(), String8(type).string(),
-                     String8(name).string()));
+        if (kIsDebug) {
+            printf("Expanding resource: ref=%s\n", String8(ref).string());
+            printf("Expanding resource: defType=%s\n",
+                    defType ? String8(*defType).string() : "NULL");
+            printf("Expanding resource: defPackage=%s\n",
+                    defPackage ? String8(*defPackage).string() : "NULL");
+            printf("Expanding resource: ref=%s\n", String8(ref).string());
+            printf("Expanded resource: p=%s, t=%s, n=%s, res=0\n",
+                    String8(package).string(), String8(type).string(),
+                    String8(name).string());
+        }
         return 0;
     }
     uint32_t res = getResId(package, type, name, onlyPublic && refOnlyPublic);
-    NOISY(printf("Expanded resource: p=%s, t=%s, n=%s, res=%d\n",
-                 String8(package).string(), String8(type).string(),
-                 String8(name).string(), res));
+    if (kIsDebug) {
+        printf("Expanded resource: p=%s, t=%s, n=%s, res=%d\n",
+                String8(package).string(), String8(type).string(),
+                String8(name).string(), res);
+    }
     if (res == 0) {
         if (outErrorMsg)
             *outErrorMsg = "No resource found that matches the given name";
@@ -2245,9 +2271,11 @@
             } else {
                 configStr = "(null)";
             }
-            NOISY(printf("Adding to pool string style #%d config %s: %s\n",
-                    style != NULL ? style->size() : 0,
-                    configStr.string(), String8(finalStr).string()));
+            if (kIsDebug) {
+                printf("Adding to pool string style #%zu config %s: %s\n",
+                        style != NULL ? style->size() : 0U,
+                        configStr.string(), String8(finalStr).string());
+            }
             if (style != NULL && style->size() > 0) {
                 outValue->data = pool->add(finalStr, *style, configTypeName, config);
             } else {
@@ -2851,9 +2879,9 @@
         const size_t typeStringsStart = data->getSize();
         sp<AaptFile> strFile = p->getTypeStringsData();
         ssize_t amt = data->writeData(strFile->getData(), strFile->getSize());
-        #if PRINT_STRING_METRICS
-        fprintf(stderr, "**** type strings: %d\n", amt);
-        #endif
+        if (kPrintStringMetrics) {
+            fprintf(stderr, "**** type strings: %zd\n", SSIZE(amt));
+        }
         strAmt += amt;
         if (amt < 0) {
             return amt;
@@ -2861,9 +2889,9 @@
         const size_t keyStringsStart = data->getSize();
         strFile = p->getKeyStringsData();
         amt = data->writeData(strFile->getData(), strFile->getSize());
-        #if PRINT_STRING_METRICS
-        fprintf(stderr, "**** key strings: %d\n", amt);
-        #endif
+        if (kPrintStringMetrics) {
+            fprintf(stderr, "**** key strings: %zd\n", SSIZE(amt));
+        }
         strAmt += amt;
         if (amt < 0) {
             return amt;
@@ -2942,29 +2970,31 @@
             for (size_t ci=0; ci<NC; ci++) {
                 ConfigDescription config = t->getUniqueConfigs().itemAt(ci);
 
-                NOISY(printf("Writing config %d config: imsi:%d/%d lang:%c%c cnt:%c%c "
-                     "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
-                     "sw%ddp w%ddp h%ddp dir:%d\n",
-                      ti+1,
-                      config.mcc, config.mnc,
-                      config.language[0] ? config.language[0] : '-',
-                      config.language[1] ? config.language[1] : '-',
-                      config.country[0] ? config.country[0] : '-',
-                      config.country[1] ? config.country[1] : '-',
-                      config.orientation,
-                      config.uiMode,
-                      config.touchscreen,
-                      config.density,
-                      config.keyboard,
-                      config.inputFlags,
-                      config.navigation,
-                      config.screenWidth,
-                      config.screenHeight,
-                      config.smallestScreenWidthDp,
-                      config.screenWidthDp,
-                      config.screenHeightDp,
-                      config.layoutDirection));
-                      
+                if (kIsDebug) {
+                    printf("Writing config %zu config: imsi:%d/%d lang:%c%c cnt:%c%c "
+                        "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
+                        "sw%ddp w%ddp h%ddp layout:%d\n",
+                        ti + 1,
+                        config.mcc, config.mnc,
+                        config.language[0] ? config.language[0] : '-',
+                        config.language[1] ? config.language[1] : '-',
+                        config.country[0] ? config.country[0] : '-',
+                        config.country[1] ? config.country[1] : '-',
+                        config.orientation,
+                        config.uiMode,
+                        config.touchscreen,
+                        config.density,
+                        config.keyboard,
+                        config.inputFlags,
+                        config.navigation,
+                        config.screenWidth,
+                        config.screenHeight,
+                        config.smallestScreenWidthDp,
+                        config.screenWidthDp,
+                        config.screenHeightDp,
+                        config.screenLayout);
+                }
+
                 if (filterable && !filter.match(config)) {
                     continue;
                 }
@@ -2985,28 +3015,30 @@
                 tHeader->entryCount = htodl(N);
                 tHeader->entriesStart = htodl(typeSize);
                 tHeader->config = config;
-                NOISY(printf("Writing type %d config: imsi:%d/%d lang:%c%c cnt:%c%c "
-                     "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
-                     "sw%ddp w%ddp h%ddp dir:%d\n",
-                      ti+1,
-                      tHeader->config.mcc, tHeader->config.mnc,
-                      tHeader->config.language[0] ? tHeader->config.language[0] : '-',
-                      tHeader->config.language[1] ? tHeader->config.language[1] : '-',
-                      tHeader->config.country[0] ? tHeader->config.country[0] : '-',
-                      tHeader->config.country[1] ? tHeader->config.country[1] : '-',
-                      tHeader->config.orientation,
-                      tHeader->config.uiMode,
-                      tHeader->config.touchscreen,
-                      tHeader->config.density,
-                      tHeader->config.keyboard,
-                      tHeader->config.inputFlags,
-                      tHeader->config.navigation,
-                      tHeader->config.screenWidth,
-                      tHeader->config.screenHeight,
-                      tHeader->config.smallestScreenWidthDp,
-                      tHeader->config.screenWidthDp,
-                      tHeader->config.screenHeightDp,
-                      tHeader->config.layoutDirection));
+                if (kIsDebug) {
+                    printf("Writing type %zu config: imsi:%d/%d lang:%c%c cnt:%c%c "
+                        "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
+                        "sw%ddp w%ddp h%ddp layout:%d\n",
+                        ti + 1,
+                        tHeader->config.mcc, tHeader->config.mnc,
+                        tHeader->config.language[0] ? tHeader->config.language[0] : '-',
+                        tHeader->config.language[1] ? tHeader->config.language[1] : '-',
+                        tHeader->config.country[0] ? tHeader->config.country[0] : '-',
+                        tHeader->config.country[1] ? tHeader->config.country[1] : '-',
+                        tHeader->config.orientation,
+                        tHeader->config.uiMode,
+                        tHeader->config.touchscreen,
+                        tHeader->config.density,
+                        tHeader->config.keyboard,
+                        tHeader->config.inputFlags,
+                        tHeader->config.navigation,
+                        tHeader->config.screenWidth,
+                        tHeader->config.screenHeight,
+                        tHeader->config.smallestScreenWidthDp,
+                        tHeader->config.screenWidthDp,
+                        tHeader->config.screenHeightDp,
+                        tHeader->config.screenLayout);
+                }
                 tHeader->config.swapHtoD();
 
                 // Build the entries inside of this type.
@@ -3083,10 +3115,10 @@
 
     ssize_t amt = (dest->getSize()-strStart);
     strAmt += amt;
-    #if PRINT_STRING_METRICS
-    fprintf(stderr, "**** value strings: %d\n", amt);
-    fprintf(stderr, "**** total strings: %d\n", strAmt);
-    #endif
+    if (kPrintStringMetrics) {
+        fprintf(stderr, "**** value strings: %zd\n", SSIZE(amt));
+        fprintf(stderr, "**** total strings: %zd\n", SSIZE(strAmt));
+    }
     
     for (pi=0; pi<flatPackages.size(); pi++) {
         err = dest->writeData(flatPackages[pi]->getData(),
@@ -3101,13 +3133,10 @@
         (((uint8_t*)dest->getData()) + dataStart);
     header->header.size = htodl(dest->getSize() - dataStart);
 
-    NOISY(aout << "Resource table:"
-          << HexDump(dest->getData(), dest->getSize()) << endl);
-
-    #if PRINT_STRING_METRICS
-    fprintf(stderr, "**** total resource table size: %d / %d%% strings\n",
-        dest->getSize(), (strAmt*100)/dest->getSize());
-    #endif
+    if (kPrintStringMetrics) {
+        fprintf(stderr, "**** total resource table size: %zu / %zu%% strings\n",
+                dest->getSize(), (size_t)(strAmt*100)/dest->getSize());
+    }
     
     return NO_ERROR;
 }
@@ -3339,7 +3368,7 @@
 }
 
 status_t ResourceTable::Entry::assignResourceIds(ResourceTable* table,
-                                                 const String16& package)
+                                                 const String16& /* package */)
 {
     bool hasErrors = false;
     
@@ -3372,7 +3401,7 @@
             }
         }
     }
-    return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
+    return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
 }
 
 status_t ResourceTable::Entry::prepareFlatten(StringPool* strings, ResourceTable* table,
@@ -3431,22 +3460,20 @@
     return NO_ERROR;
 }
 
-ssize_t ResourceTable::Entry::flatten(Bundle* bundle, const sp<AaptFile>& data, bool isPublic)
+ssize_t ResourceTable::Entry::flatten(Bundle* /* bundle */, const sp<AaptFile>& data, bool isPublic)
 {
     size_t amt = 0;
     ResTable_entry header;
     memset(&header, 0, sizeof(header));
     header.size = htods(sizeof(header));
-    const type ty = this != NULL ? mType : TYPE_ITEM;
-    if (this != NULL) {
-        if (ty == TYPE_BAG) {
-            header.flags |= htods(header.FLAG_COMPLEX);
-        }
-        if (isPublic) {
-            header.flags |= htods(header.FLAG_PUBLIC);
-        }
-        header.key.index = htodl(mNameIndex);
+    const type ty = mType;
+    if (ty == TYPE_BAG) {
+        header.flags |= htods(header.FLAG_COMPLEX);
     }
+    if (isPublic) {
+        header.flags |= htods(header.FLAG_PUBLIC);
+    }
+    header.key.index = htodl(mNameIndex);
     if (ty != TYPE_BAG) {
         status_t err = data->writeData(&header, sizeof(header));
         if (err != NO_ERROR) {
@@ -3621,10 +3648,11 @@
     
     sp<Entry> e = c->getEntries().valueFor(cdesc);
     if (e == NULL) {
-        if (config != NULL) {
-            NOISY(printf("New entry at %s:%d: imsi:%d/%d lang:%c%c cnt:%c%c "
+        if (kIsDebug) {
+            if (config != NULL) {
+                printf("New entry at %s:%d: imsi:%d/%d lang:%c%c cnt:%c%c "
                     "orien:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
-                    "sw%ddp w%ddp h%ddp dir:%d\n",
+                    "sw%ddp w%ddp h%ddp layout:%d\n",
                       sourcePos.file.string(), sourcePos.line,
                       config->mcc, config->mnc,
                       config->language[0] ? config->language[0] : '-',
@@ -3642,10 +3670,11 @@
                       config->smallestScreenWidthDp,
                       config->screenWidthDp,
                       config->screenHeightDp,
-                      config->layoutDirection));
-        } else {
-            NOISY(printf("New entry at %s:%d: NULL config\n",
-                      sourcePos.file.string(), sourcePos.line));
+                      config->screenLayout);
+            } else {
+                printf("New entry at %s:%d: NULL config\n",
+                        sourcePos.file.string(), sourcePos.line);
+            }
         }
         e = new Entry(entry, sourcePos);
         c->addEntry(cdesc, e);
@@ -3751,7 +3780,7 @@
         j++;
     }
 
-    return hasError ? UNKNOWN_ERROR : NO_ERROR;
+    return hasError ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
 }
 
 ResourceTable::Package::Package(const String16& name, ssize_t includedId)
@@ -3807,9 +3836,6 @@
         return UNKNOWN_ERROR;
     }
 
-    NOISY(aout << "Setting restable string pool: "
-          << HexDump(data->getData(), data->getSize()) << endl);
-
     status_t err = strings->setTo(data->getData(), data->getSize());
     if (err == NO_ERROR) {
         const size_t N = strings->size();
@@ -4017,7 +4043,7 @@
         }
         item->evaluating = true;
         res = stringToValue(outValue, NULL, item->value, false, false, item->bagKeyId);
-        NOISY(
+        if (kIsDebug) {
             if (res) {
                 printf("getItemValue of #%08x[#%08x] (%s): type=#%08x, data=#%08x\n",
                        resID, attrID, String8(getEntry(resID)->getName()).string(),
@@ -4026,7 +4052,7 @@
                 printf("getItemValue of #%08x[#%08x]: failed\n",
                        resID, attrID);
             }
-        );
+        }
         item->evaluating = false;
     }
     return res;
diff --git a/tools/aapt/StringPool.cpp b/tools/aapt/StringPool.cpp
index c7fd040..eec23aa 100644
--- a/tools/aapt/StringPool.cpp
+++ b/tools/aapt/StringPool.cpp
@@ -3,23 +3,28 @@
 //
 // Build resource files from raw assets.
 //
-
 #include "StringPool.h"
-#include "ResourceTable.h"
 
 #include <utils/ByteOrder.h>
 #include <utils/SortedVector.h>
-#include "qsort_r_compat.h"
 
+#include <algorithm>
+
+#include "ResourceTable.h"
+
+// SSIZE: mingw does not have signed size_t == ssize_t.
 #if HAVE_PRINTF_ZD
 #  define ZD "%zd"
 #  define ZD_TYPE ssize_t
+#  define SSIZE(x) x
 #else
 #  define ZD "%ld"
 #  define ZD_TYPE long
+#  define SSIZE(x) (signed size_t)x
 #endif
 
-#define NOISY(x) //x
+// Set to true for noisy debug output.
+static const bool kIsDebug = false;
 
 void strcpy16_htod(char16_t* dst, const char16_t* src)
 {
@@ -132,8 +137,10 @@
 
     if (configTypeName != NULL) {
         entry& ent = mEntries.editItemAt(eidx);
-        NOISY(printf("*** adding config type name %s, was %s\n",
-                configTypeName->string(), ent.configTypeName.string()));
+        if (kIsDebug) {
+            printf("*** adding config type name %s, was %s\n",
+                    configTypeName->string(), ent.configTypeName.string());
+        }
         if (ent.configTypeName.size() <= 0) {
             ent.configTypeName = *configTypeName;
         } else if (ent.configTypeName != *configTypeName) {
@@ -149,14 +156,18 @@
             int cmp = ent.configs.itemAt(addPos).compareLogical(*config);
             if (cmp >= 0) {
                 if (cmp > 0) {
-                    NOISY(printf("*** inserting config: %s\n", config->toString().string()));
+                    if (kIsDebug) {
+                        printf("*** inserting config: %s\n", config->toString().string());
+                    }
                     ent.configs.insertAt(*config, addPos);
                 }
                 break;
             }
         }
         if (addPos >= ent.configs.size()) {
-            NOISY(printf("*** adding config: %s\n", config->toString().string()));
+            if (kIsDebug) {
+                printf("*** adding config: %s\n", config->toString().string());
+            }
             ent.configs.add(*config);
         }
     }
@@ -173,9 +184,11 @@
         ent.indices.add(pos);
     }
 
-    NOISY(printf("Adding string %s to pool: pos=%d eidx=%d vidx=%d\n",
-            String8(value).string(), pos, eidx, vidx));
-    
+    if (kIsDebug) {
+        printf("Adding string %s to pool: pos=%zd eidx=%zd vidx=%zd\n",
+                String8(value).string(), SSIZE(pos), SSIZE(eidx), SSIZE(vidx));
+    }
+
     return pos;
 }
 
@@ -214,12 +227,15 @@
     return NO_ERROR;
 }
 
-int StringPool::config_sort(void* state, const void* lhs, const void* rhs)
+StringPool::ConfigSorter::ConfigSorter(const StringPool& pool) : pool(pool)
 {
-    StringPool* pool = (StringPool*)state;
-    const entry& lhe = pool->mEntries[pool->mEntryArray[*static_cast<const size_t*>(lhs)]];
-    const entry& rhe = pool->mEntries[pool->mEntryArray[*static_cast<const size_t*>(rhs)]];
-    return lhe.compare(rhe);
+}
+
+bool StringPool::ConfigSorter::operator()(size_t l, size_t r)
+{
+    const StringPool::entry& lhe = pool.mEntries[pool.mEntryArray[l]];
+    const StringPool::entry& rhe = pool.mEntries[pool.mEntryArray[r]];
+    return lhe.compare(rhe) < 0;
 }
 
 void StringPool::sortByConfig()
@@ -239,12 +255,14 @@
     }
 
     // Sort the array.
-    NOISY(printf("SORTING STRINGS BY CONFIGURATION...\n"));
-    // Vector::sort uses insertion sort, which is very slow for this data set.
-    // Use quicksort instead because we don't need a stable sort here.
-    qsort_r_compat(newPosToOriginalPos.editArray(), N, sizeof(size_t), this, config_sort);
-    //newPosToOriginalPos.sort(config_sort, this);
-    NOISY(printf("DONE SORTING STRINGS BY CONFIGURATION.\n"));
+    if (kIsDebug) {
+        printf("SORTING STRINGS BY CONFIGURATION...\n");
+    }
+    ConfigSorter sorter(*this);
+    std::sort(newPosToOriginalPos.begin(), newPosToOriginalPos.end(), sorter);
+    if (kIsDebug) {
+        printf("DONE SORTING STRINGS BY CONFIGURATION.\n");
+    }
 
     // Create the reverse mapping from the original position in the array
     // to the new position where it appears in the sorted array.  This is
@@ -541,9 +559,13 @@
     for (i=0; i<ENTRIES; i++) {
         entry& ent = mEntries.editItemAt(mEntryArray[i]);
         *index++ = htodl(ent.offset);
-        NOISY(printf("Writing entry #%d: \"%s\" ent=%d off=%d\n", i,
-                String8(ent.value).string(),
-                mEntryArray[i], ent.offset));
+        if (kIsDebug) {
+            printf("Writing entry #%zu: \"%s\" ent=%zu off=%zu\n",
+                    i,
+                    String8(ent.value).string(),
+                    mEntryArray[i],
+                    ent.offset);
+        }
     }
 
     // Write style index array.
@@ -559,8 +581,10 @@
 {
     const Vector<size_t>* indices = offsetsForString(val);
     ssize_t res = indices != NULL && indices->size() > 0 ? indices->itemAt(0) : -1;
-    NOISY(printf("Offset for string %s: %d (%s)\n", String8(val).string(), res,
-            res >= 0 ? String8(mEntries[mEntryArray[res]].value).string() : String8()));
+    if (kIsDebug) {
+        printf("Offset for string %s: %zd (%s)\n", String8(val).string(), SSIZE(res),
+                res >= 0 ? String8(mEntries[mEntryArray[res]].value).string() : String8());
+    }
     return res;
 }
 
diff --git a/tools/aapt/StringPool.h b/tools/aapt/StringPool.h
index 1b5a7ba..0b26538 100644
--- a/tools/aapt/StringPool.h
+++ b/tools/aapt/StringPool.h
@@ -138,7 +138,14 @@
     const Vector<size_t>* offsetsForString(const String16& val) const;
 
 private:
-    static int config_sort(void* state, const void* lhs, const void* rhs);
+    class ConfigSorter
+    {
+    public:
+        explicit ConfigSorter(const StringPool&);
+        bool operator()(size_t l, size_t r);
+    private:
+        const StringPool& pool;
+    };
 
     const bool                              mUTF8;
 
diff --git a/tools/aapt/XMLNode.cpp b/tools/aapt/XMLNode.cpp
index 03c66c1..cda24eb 100644
--- a/tools/aapt/XMLNode.cpp
+++ b/tools/aapt/XMLNode.cpp
@@ -16,8 +16,26 @@
 #define O_BINARY 0
 #endif
 
-#define NOISY(x) //x
-#define NOISY_PARSE(x) //x
+// SSIZE: mingw does not have signed size_t == ssize_t.
+// STATUST: mingw does seem to redefine UNKNOWN_ERROR from our enum value, so a cast is necessary.
+#if HAVE_PRINTF_ZD
+#  define SSIZE(x) x
+#  define STATUST(x) x
+#else
+#  define SSIZE(x) (signed size_t)x
+#  define STATUST(x) (status_t)x
+#endif
+
+// Set to true for noisy debug output.
+static const bool kIsDebug = false;
+// Set to true for noisy debug output of parsing.
+static const bool kIsDebugParse = false;
+
+#if PRINT_STRING_METRICS
+static const bool kPrintStringMetrics = true;
+#else
+static const bool kPrintStringMetrics = false;
+#endif
 
 const char* const RESOURCES_ROOT_NAMESPACE = "http://schemas.android.com/apk/res/";
 const char* const RESOURCES_ANDROID_NAMESPACE = "http://schemas.android.com/apk/res/android";
@@ -56,7 +74,10 @@
     size_t prefixSize;
     bool isPublic = true;
     if(namespaceUri.startsWith(RESOURCES_PREFIX_AUTO_PACKAGE)) {
-        NOISY(printf("Using default application package: %s -> %s\n", String8(namespaceUri).string(), String8(appPackage).string()));
+        if (kIsDebug) {
+            printf("Using default application package: %s -> %s\n", String8(namespaceUri).string(),
+                   String8(appPackage).string());
+        }
         isPublic = true;
         return appPackage;
     } else if (namespaceUri.startsWith(RESOURCES_PREFIX)) {
@@ -180,7 +201,7 @@
     return NO_ERROR;
 }
 
-status_t parseStyledString(Bundle* bundle,
+status_t parseStyledString(Bundle* /* bundle */,
                            const char* fileName,
                            ResXMLTree* inXml,
                            const String16& endTag,
@@ -557,8 +578,10 @@
     }
     root->removeWhitespace(stripAll, cDataTags);
 
-    NOISY(printf("Input XML from %s:\n", (const char*)file->getPrintableSource()));
-    NOISY(root->print());
+    if (kIsDebug) {
+        printf("Input XML from %s:\n", (const char*)file->getPrintableSource());
+        root->print();
+    }
     sp<AaptFile> rsc = new AaptFile(String8(), AaptGroupEntry(), String8());
     status_t err = root->flatten(rsc, !keepComments, false);
     if (err != NO_ERROR) {
@@ -569,8 +592,10 @@
         return err;
     }
 
-    NOISY(printf("Output XML:\n"));
-    NOISY(printXMLBlock(outTree));
+    if (kIsDebug) {
+        printf("Output XML:\n");
+        printXMLBlock(outTree);
+    }
 
     return NO_ERROR;
 }
@@ -818,11 +843,13 @@
     } else {
         mAttributeOrder.removeItem(e.index);
     }
-    NOISY(printf("Elem %s %s=\"%s\": set res id = 0x%08x\n",
-            String8(getElementName()).string(),
-            String8(mAttributes.itemAt(attrIdx).name).string(),
-            String8(mAttributes.itemAt(attrIdx).string).string(),
-            resId));
+    if (kIsDebug) {
+        printf("Elem %s %s=\"%s\": set res id = 0x%08x\n",
+                String8(getElementName()).string(),
+                String8(mAttributes.itemAt(attrIdx).name).string(),
+                String8(mAttributes.itemAt(attrIdx).string).string(),
+                resId);
+    }
     mAttributes.editItemAt(attrIdx).nameResId = resId;
     mAttributeOrder.add(resId, attrIdx);
 }
@@ -933,9 +960,11 @@
                                   e.nameResId, NULL, &defPackage, table, &ac)) {
                 hasErrors = true;
             }
-            NOISY(printf("Attr %s: type=0x%x, str=%s\n",
-                   String8(e.name).string(), e.value.dataType,
-                   String8(e.string).string()));
+            if (kIsDebug) {
+                printf("Attr %s: type=0x%x, str=%s\n",
+                        String8(e.name).string(), e.value.dataType,
+                        String8(e.string).string());
+            }
         }
     }
     const size_t N = mChildren.size();
@@ -945,7 +974,7 @@
             hasErrors = true;
         }
     }
-    return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
+    return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
 }
 
 status_t XMLNode::assignResourceIds(const sp<AaptAssets>& assets,
@@ -960,15 +989,17 @@
         for (size_t i=0; i<N; i++) {
             const attribute_entry& e = mAttributes.itemAt(i);
             if (e.ns.size() <= 0) continue;
-            bool nsIsPublic;
+            bool nsIsPublic = true;
             String16 pkg(getNamespaceResourcePackage(String16(assets->getPackage()), e.ns, &nsIsPublic));
-            NOISY(printf("Elem %s %s=\"%s\": namespace(%s) %s ===> %s\n",
-                    String8(getElementName()).string(),
-                    String8(e.name).string(),
-                    String8(e.string).string(),
-                    String8(e.ns).string(),
-                    (nsIsPublic) ? "public" : "private",
-                    String8(pkg).string()));
+            if (kIsDebug) {
+                printf("Elem %s %s=\"%s\": namespace(%s) %s ===> %s\n",
+                        String8(getElementName()).string(),
+                        String8(e.name).string(),
+                        String8(e.string).string(),
+                        String8(e.ns).string(),
+                        (nsIsPublic) ? "public" : "private",
+                        String8(pkg).string());
+            }
             if (pkg.size() <= 0) continue;
             uint32_t res = table != NULL
                 ? table->getResId(e.name, &attr, &pkg, &errorMsg, nsIsPublic)
@@ -977,8 +1008,10 @@
                                       attr.string(), attr.size(),
                                       pkg.string(), pkg.size());
             if (res != 0) {
-                NOISY(printf("XML attribute name %s: resid=0x%08x\n",
-                             String8(e.name).string(), res));
+                if (kIsDebug) {
+                    printf("XML attribute name %s: resid=0x%08x\n",
+                            String8(e.name).string(), res);
+                }
                 setAttributeResID(i, res);
             } else {
                 SourcePos(mFilename, getStartLineNumber()).error(
@@ -996,7 +1029,7 @@
         }
     }
 
-    return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
+    return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
 }
 
 status_t XMLNode::flatten(const sp<AaptFile>& dest,
@@ -1014,18 +1047,7 @@
     // Next collect all remainibng strings.
     collect_strings(&strings, &resids, stripComments, stripRawValues);
 
-#if 0  // No longer compiles
-    NOISY(printf("Found strings:\n");
-        const size_t N = strings.size();
-        for (size_t i=0; i<N; i++) {
-            printf("%s\n", String8(strings.entryAt(i).string).string());
-        }
-    );
-#endif    
-
     sp<AaptFile> stringPool = strings.createStringBlock();
-    NOISY(aout << "String pool:"
-          << HexDump(stringPool->getData(), stringPool->getSize()) << endl);
 
     ResXMLTree_header header;
     memset(&header, 0, sizeof(header));
@@ -1056,17 +1078,13 @@
 
     void* data = dest->editData();
     ResXMLTree_header* hd = (ResXMLTree_header*)(((uint8_t*)data)+basePos);
-    size_t size = dest->getSize()-basePos;
     hd->header.size = htodl(dest->getSize()-basePos);
 
-    NOISY(aout << "XML resource:"
-          << HexDump(dest->getData(), dest->getSize()) << endl);
-
-    #if PRINT_STRING_METRICS
-    fprintf(stderr, "**** total xml size: %d / %d%% strings (in %s)\n",
-        dest->getSize(), (stringPool->getSize()*100)/dest->getSize(),
-        dest->getPath().string());
-    #endif
+    if (kPrintStringMetrics) {
+        fprintf(stderr, "**** total xml size: %zu / %zu%% strings (in %s)\n",
+                dest->getSize(), (stringPool->getSize()*100)/dest->getSize(),
+                dest->getPath().string());
+    }
         
     return NO_ERROR;
 }
@@ -1139,7 +1157,9 @@
 void XMLCALL
 XMLNode::startNamespace(void *userData, const char *prefix, const char *uri)
 {
-    NOISY_PARSE(printf("Start Namespace: %s %s\n", prefix, uri));
+    if (kIsDebugParse) {
+        printf("Start Namespace: %s %s\n", prefix, uri);
+    }
     ParseState* st = (ParseState*)userData;
     sp<XMLNode> node = XMLNode::newNamespace(st->filename, 
             String16(prefix != NULL ? prefix : ""), String16(uri));
@@ -1155,7 +1175,9 @@
 void XMLCALL
 XMLNode::startElement(void *userData, const char *name, const char **atts)
 {
-    NOISY_PARSE(printf("Start Element: %s\n", name));
+    if (kIsDebugParse) {
+        printf("Start Element: %s\n", name);
+    }
     ParseState* st = (ParseState*)userData;
     String16 ns16, name16;
     splitName(name, &ns16, &name16);
@@ -1181,7 +1203,9 @@
 void XMLCALL
 XMLNode::characterData(void *userData, const XML_Char *s, int len)
 {
-    NOISY_PARSE(printf("CDATA: \"%s\"\n", String8(s, len).string()));
+    if (kIsDebugParse) {
+        printf("CDATA: \"%s\"\n", String8(s, len).string());
+    }
     ParseState* st = (ParseState*)userData;
     sp<XMLNode> node = NULL;
     if (st->stack.size() == 0) {
@@ -1208,7 +1232,9 @@
 void XMLCALL
 XMLNode::endElement(void *userData, const char *name)
 {
-    NOISY_PARSE(printf("End Element: %s\n", name));
+    if (kIsDebugParse) {
+        printf("End Element: %s\n", name);
+    }
     ParseState* st = (ParseState*)userData;
     sp<XMLNode> node = st->stack.itemAt(st->stack.size()-1);
     node->setEndLineNumber(XML_GetCurrentLineNumber(st->parser));
@@ -1228,7 +1254,9 @@
 XMLNode::endNamespace(void *userData, const char *prefix)
 {
     const char* nonNullPrefix = prefix != NULL ? prefix : "";
-    NOISY_PARSE(printf("End Namespace: %s\n", prefix));
+    if (kIsDebugParse) {
+        printf("End Namespace: %s\n", prefix);
+    }
     ParseState* st = (ParseState*)userData;
     sp<XMLNode> node = st->stack.itemAt(st->stack.size()-1);
     node->setEndLineNumber(XML_GetCurrentLineNumber(st->parser));
@@ -1240,7 +1268,9 @@
 void XMLCALL
 XMLNode::commentData(void *userData, const char *comment)
 {
-    NOISY_PARSE(printf("Comment: %s\n", comment));
+    if (kIsDebugParse) {
+        printf("Comment: %s\n", comment);
+    }
     ParseState* st = (ParseState*)userData;
     if (st->pendingComment.size() > 0) {
         st->pendingComment.append(String16("\n"));
@@ -1337,8 +1367,10 @@
             }
             if (idx < 0) {
                 idx = outPool->add(attr.name);
-                NOISY(printf("Adding attr %s (resid 0x%08x) to pool: idx=%d\n",
-                        String8(attr.name).string(), id, idx));
+                if (kIsDebug) {
+                    printf("Adding attr %s (resid 0x%08x) to pool: idx=%zd\n",
+                            String8(attr.name).string(), id, SSIZE(idx));
+                }
                 if (id != 0) {
                     while ((ssize_t)outResIds->size() <= idx) {
                         outResIds->add(0);
@@ -1347,8 +1379,9 @@
                 }
             }
             attr.namePoolIdx = idx;
-            NOISY(printf("String %s offset=0x%08x\n",
-                         String8(attr.name).string(), idx));
+            if (kIsDebug) {
+                printf("String %s offset=0x%08zd\n", String8(attr.name).string(), SSIZE(idx));
+            }
         }
     }
 
diff --git a/tools/aapt/ZipEntry.cpp b/tools/aapt/ZipEntry.cpp
index b575988..f97f604 100644
--- a/tools/aapt/ZipEntry.cpp
+++ b/tools/aapt/ZipEntry.cpp
@@ -141,33 +141,15 @@
  *
  * Initializes the CDE and the LFH.
  */
-status_t ZipEntry::initFromExternal(const ZipFile* pZipFile,
+status_t ZipEntry::initFromExternal(const ZipFile* /* pZipFile */,
     const ZipEntry* pEntry)
 {
-    /*
-     * Copy everything in the CDE over, then fix up the hairy bits.
-     */
-    memcpy(&mCDE, &pEntry->mCDE, sizeof(mCDE));
-
-    if (mCDE.mFileNameLength > 0) {
-        mCDE.mFileName = new unsigned char[mCDE.mFileNameLength+1];
-        if (mCDE.mFileName == NULL)
-            return NO_MEMORY;
-        strcpy((char*) mCDE.mFileName, (char*)pEntry->mCDE.mFileName);
-    }
-    if (mCDE.mFileCommentLength > 0) {
-        mCDE.mFileComment = new unsigned char[mCDE.mFileCommentLength+1];
-        if (mCDE.mFileComment == NULL)
-            return NO_MEMORY;
-        strcpy((char*) mCDE.mFileComment, (char*)pEntry->mCDE.mFileComment);
-    }
-    if (mCDE.mExtraFieldLength > 0) {
-        /* we null-terminate this, though it may not be a string */
-        mCDE.mExtraField = new unsigned char[mCDE.mExtraFieldLength+1];
-        if (mCDE.mExtraField == NULL)
-            return NO_MEMORY;
-        memcpy(mCDE.mExtraField, pEntry->mCDE.mExtraField,
-            mCDE.mExtraFieldLength+1);
+    mCDE = pEntry->mCDE;
+    // Check whether we got all the memory needed.
+    if ((mCDE.mFileNameLength > 0 && mCDE.mFileName == NULL) ||
+            (mCDE.mFileCommentLength > 0 && mCDE.mFileComment == NULL) ||
+            (mCDE.mExtraFieldLength > 0 && mCDE.mExtraField == NULL)) {
+        return NO_MEMORY;
     }
 
     /* construct the LFH from the CDE */
@@ -694,3 +676,60 @@
         ALOGD("  comment: '%s'\n", mFileComment);
 }
 
+/*
+ * Copy-assignment operator for CentralDirEntry.
+ */
+ZipEntry::CentralDirEntry& ZipEntry::CentralDirEntry::operator=(const ZipEntry::CentralDirEntry& src) {
+    if (this == &src) {
+        return *this;
+    }
+
+    // Free up old data.
+    delete[] mFileName;
+    delete[] mExtraField;
+    delete[] mFileComment;
+
+    // Copy scalars.
+    mVersionMadeBy = src.mVersionMadeBy;
+    mVersionToExtract = src.mVersionToExtract;
+    mGPBitFlag = src.mGPBitFlag;
+    mCompressionMethod = src.mCompressionMethod;
+    mLastModFileTime = src.mLastModFileTime;
+    mLastModFileDate = src.mLastModFileDate;
+    mCRC32 = src.mCRC32;
+    mCompressedSize = src.mCompressedSize;
+    mUncompressedSize = src.mUncompressedSize;
+    mFileNameLength = src.mFileNameLength;
+    mExtraFieldLength = src.mExtraFieldLength;
+    mFileCommentLength = src.mFileCommentLength;
+    mDiskNumberStart = src.mDiskNumberStart;
+    mInternalAttrs = src.mInternalAttrs;
+    mExternalAttrs = src.mExternalAttrs;
+    mLocalHeaderRelOffset = src.mLocalHeaderRelOffset;
+
+    // Copy strings, if necessary.
+    if (mFileNameLength > 0) {
+        mFileName = new unsigned char[mFileNameLength + 1];
+        if (mFileName != NULL)
+            strcpy((char*)mFileName, (char*)src.mFileName);
+    } else {
+        mFileName = NULL;
+    }
+    if (mFileCommentLength > 0) {
+        mFileComment = new unsigned char[mFileCommentLength + 1];
+        if (mFileComment != NULL)
+            strcpy((char*)mFileComment, (char*)src.mFileComment);
+    } else {
+        mFileComment = NULL;
+    }
+    if (mExtraFieldLength > 0) {
+        /* we null-terminate this, though it may not be a string */
+        mExtraField = new unsigned char[mExtraFieldLength + 1];
+        if (mExtraField != NULL)
+            memcpy(mExtraField, src.mExtraField, mExtraFieldLength + 1);
+    } else {
+        mExtraField = NULL;
+    }
+
+    return *this;
+}
diff --git a/tools/aapt/ZipEntry.h b/tools/aapt/ZipEntry.h
index c2f3227..287a540 100644
--- a/tools/aapt/ZipEntry.h
+++ b/tools/aapt/ZipEntry.h
@@ -298,6 +298,8 @@
         status_t read(FILE* fp);
         status_t write(FILE* fp);
 
+        CentralDirEntry& operator=(const CentralDirEntry& src);
+
         // unsigned long mSignature;
         unsigned short  mVersionMadeBy;
         unsigned short  mVersionToExtract;
diff --git a/tools/aapt/ZipFile.cpp b/tools/aapt/ZipFile.cpp
index 8057068..36f4e73 100644
--- a/tools/aapt/ZipFile.cpp
+++ b/tools/aapt/ZipFile.cpp
@@ -676,8 +676,6 @@
 status_t ZipFile::copyDataToFp(FILE* dstFp,
     const void* data, size_t size, unsigned long* pCRC32)
 {
-    size_t count;
-
     *pCRC32 = crc32(0L, Z_NULL, 0);
     if (size > 0) {
         *pCRC32 = crc32(*pCRC32, (const unsigned char*)data, size);
diff --git a/tools/aapt/qsort_r_compat.c b/tools/aapt/qsort_r_compat.c
deleted file mode 100644
index 2a8dbe8..0000000
--- a/tools/aapt/qsort_r_compat.c
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Copyright (C) 2012 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 <stdlib.h>
-#include "qsort_r_compat.h"
-
-/*
- * Note: This code is only used on the host, and is primarily here for
- * Mac OS compatibility. Apparently, glibc and Apple's libc disagree on
- * the parameter order for qsort_r.
- */
-
-#if HAVE_BSD_QSORT_R
-
-/*
- * BSD qsort_r parameter order is as we have defined here.
- */
-
-void qsort_r_compat(void* base, size_t nel, size_t width, void* thunk,
-        int (*compar)(void*, const void* , const void*)) {
-    qsort_r(base, nel, width, thunk, compar);
-}
-
-#elif HAVE_GNU_QSORT_R
-
-/*
- * GNU qsort_r parameter order places the thunk parameter last.
- */
-
-struct compar_data {
-    void* thunk;
-    int (*compar)(void*, const void* , const void*);
-};
-
-static int compar_wrapper(const void* a, const void* b, void* data) {
-    struct compar_data* compar_data = (struct compar_data*)data;
-    return compar_data->compar(compar_data->thunk, a, b);
-}
-
-void qsort_r_compat(void* base, size_t nel, size_t width, void* thunk,
-        int (*compar)(void*, const void* , const void*)) {
-    struct compar_data compar_data;
-    compar_data.thunk = thunk;
-    compar_data.compar = compar;
-    qsort_r(base, nel, width, compar_wrapper, &compar_data);
-}
-
-#else
-
-/*
- * Emulate qsort_r using thread local storage to access the thunk data.
- */
-
-#include <cutils/threads.h>
-
-static thread_store_t compar_data_key = THREAD_STORE_INITIALIZER;
-
-struct compar_data {
-    void* thunk;
-    int (*compar)(void*, const void* , const void*);
-};
-
-static int compar_wrapper(const void* a, const void* b) {
-    struct compar_data* compar_data = (struct compar_data*)thread_store_get(&compar_data_key);
-    return compar_data->compar(compar_data->thunk, a, b);
-}
-
-void qsort_r_compat(void* base, size_t nel, size_t width, void* thunk,
-        int (*compar)(void*, const void* , const void*)) {
-    struct compar_data compar_data;
-    compar_data.thunk = thunk;
-    compar_data.compar = compar;
-    thread_store_set(&compar_data_key, &compar_data, NULL);
-    qsort(base, nel, width, compar_wrapper);
-}
-
-#endif
diff --git a/tools/aapt/qsort_r_compat.h b/tools/aapt/qsort_r_compat.h
deleted file mode 100644
index e14f999..0000000
--- a/tools/aapt/qsort_r_compat.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2012 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.
- */
-
-/*
- * Provides a portable version of qsort_r, called qsort_r_compat, which is a
- * reentrant variant of qsort that passes a user data pointer to its comparator.
- * This implementation follows the BSD parameter convention.
- */
-
-#ifndef ___QSORT_R_COMPAT_H
-#define ___QSORT_R_COMPAT_H
-
-#include <stdlib.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-void qsort_r_compat(void* base, size_t nel, size_t width, void* thunk,
-        int (*compar)(void*, const void* , const void* ));
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // ___QSORT_R_COMPAT_H
diff --git a/tools/layoutlib/bridge/src/android/graphics/Matrix_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Matrix_Delegate.java
index ebfe9bc..e9b5211 100644
--- a/tools/layoutlib/bridge/src/android/graphics/Matrix_Delegate.java
+++ b/tools/layoutlib/bridge/src/android/graphics/Matrix_Delegate.java
@@ -716,9 +716,8 @@
         float[] src = new float[] { radius, 0.f, 0.f, radius };
         d.mapVectors(src, 0, src, 0, 2);
 
-        float l1 = getPointLength(src, 0);
-        float l2 = getPointLength(src, 2);
-
+        float l1 = (float) Math.hypot(src[0], src[1]);
+        float l2 = (float) Math.hypot(src[2], src[3]);
         return (float) Math.sqrt(l1 * l2);
     }
 
@@ -973,10 +972,6 @@
          }
      }
 
-     private static float getPointLength(float[] src, int index) {
-         return (float) Math.sqrt(src[index] * src[index] + src[index + 1] * src[index + 1]);
-     }
-
     /**
      * multiply two matrices and store them in a 3rd.
      * <p/>This in effect does dest = a*b
diff --git a/tools/layoutlib/bridge/src/android/graphics/RadialGradient_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/RadialGradient_Delegate.java
index 4f16dcf..b640ece 100644
--- a/tools/layoutlib/bridge/src/android/graphics/RadialGradient_Delegate.java
+++ b/tools/layoutlib/bridge/src/android/graphics/RadialGradient_Delegate.java
@@ -198,7 +198,7 @@
 
                         float _x = pt2[0];
                         float _y = pt2[1];
-                        float distance = (float) Math.sqrt(_x * _x + _y * _y);
+                        float distance = (float) Math.hypot(_x, _y);
 
                         data[index++] = getGradientColor(distance / mRadius);
                     }
diff --git a/tools/layoutlib/bridge/src/android/util/FloatMath_Delegate.java b/tools/layoutlib/bridge/src/android/util/FloatMath_Delegate.java
deleted file mode 100644
index 8b4c60b..0000000
--- a/tools/layoutlib/bridge/src/android/util/FloatMath_Delegate.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Copyright (C) 2007 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.util;
-
-import com.android.layoutlib.bridge.impl.DelegateManager;
-import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
-
-/**
- * Delegate implementing the native methods of android.util.FloatMath
- *
- * Through the layoutlib_create tool, the original native methods of FloatMath have been replaced
- * by calls to methods of the same name in this delegate class.
- *
- * Because it's a stateless class to start with, there's no need to keep a {@link DelegateManager}
- * around to map int to instance of the delegate.
- *
- */
-/*package*/ final class FloatMath_Delegate {
-
-    /** Prevents instantiation. */
-    private FloatMath_Delegate() {}
-
-    /**
-     * Returns the float conversion of the most positive (i.e. closest to
-     * positive infinity) integer value which is less than the argument.
-     *
-     * @param value to be converted
-     * @return the floor of value
-     */
-    @LayoutlibDelegate
-    /*package*/ static float floor(float value) {
-        return (float)Math.floor(value);
-    }
-
-    /**
-     * Returns the float conversion of the most negative (i.e. closest to
-     * negative infinity) integer value which is greater than the argument.
-     *
-     * @param value to be converted
-     * @return the ceiling of value
-     */
-    @LayoutlibDelegate
-    /*package*/ static float ceil(float value) {
-        return (float)Math.ceil(value);
-    }
-
-    /**
-     * Returns the closest float approximation of the sine of the argument.
-     *
-     * @param angle to compute the cosine of, in radians
-     * @return the sine of angle
-     */
-    @LayoutlibDelegate
-    /*package*/ static  float sin(float angle) {
-        return (float)Math.sin(angle);
-    }
-
-    /**
-     * Returns the closest float approximation of the cosine of the argument.
-     *
-     * @param angle to compute the cosine of, in radians
-     * @return the cosine of angle
-     */
-    @LayoutlibDelegate
-    /*package*/ static float cos(float angle) {
-        return (float)Math.cos(angle);
-    }
-
-    /**
-     * Returns the closest float approximation of the square root of the
-     * argument.
-     *
-     * @param value to compute sqrt of
-     * @return the square root of value
-     */
-    @LayoutlibDelegate
-    /*package*/ static float sqrt(float value) {
-        return (float)Math.sqrt(value);
-    }
-
-    /**
-     * Returns the closest float approximation of the raising "e" to the power
-     * of the argument.
-     *
-     * @param value to compute the exponential of
-     * @return the exponential of value
-     */
-    @LayoutlibDelegate
-    /*package*/ static float exp(float value) {
-        return (float)Math.exp(value);
-    }
-
-    /**
-     * Returns the closest float approximation of the result of raising {@code
-     * x} to the power of {@code y}.
-     *
-     * @param x the base of the operation.
-     * @param y the exponent of the operation.
-     * @return {@code x} to the power of {@code y}.
-     */
-    @LayoutlibDelegate
-    /*package*/ static float pow(float x, float y) {
-        return (float)Math.pow(x, y);
-    }
-
-    /**
-     * Returns {@code sqrt(}<i>{@code x}</i><sup>{@code 2}</sup>{@code +} <i>
-     * {@code y}</i><sup>{@code 2}</sup>{@code )}.
-     *
-     * @param x a float number
-     * @param y a float number
-     * @return the hypotenuse
-     */
-    @LayoutlibDelegate
-    /*package*/ static float hypot(float x, float y) {
-        return (float)Math.sqrt(x*x + y*y);
-    }
-}
diff --git a/tools/layoutlib/create/src/com/android/tools/layoutlib/create/CreateInfo.java b/tools/layoutlib/create/src/com/android/tools/layoutlib/create/CreateInfo.java
index 79aa642..29a5706 100644
--- a/tools/layoutlib/create/src/com/android/tools/layoutlib/create/CreateInfo.java
+++ b/tools/layoutlib/create/src/com/android/tools/layoutlib/create/CreateInfo.java
@@ -188,7 +188,6 @@
         "android.os.SystemClock",
         "android.text.AndroidBidi",
         "android.text.format.Time",
-        "android.util.FloatMath",
         "android.view.Display",
         "libcore.icu.DateIntervalFormat",
         "libcore.icu.ICU",