Merge "Reduce warning verbosity in aapt"
diff --git a/cmds/app_process/Android.mk b/cmds/app_process/Android.mk
index cb7e1a0..7c25354 100644
--- a/cmds/app_process/Android.mk
+++ b/cmds/app_process/Android.mk
@@ -14,30 +14,11 @@
 	libandroid_runtime
 
 LOCAL_MODULE:= app_process
-LOCAL_32_BIT_ONLY := true
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := app_process
+LOCAL_MODULE_STEM_64 := app_process64
 include $(BUILD_EXECUTABLE)
 
-ifeq ($(TARGET_IS_64_BIT),true)
-
-# 64-bit app_process64
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES:= \
-	app_main.cpp
-
-LOCAL_SHARED_LIBRARIES := \
-	libcutils \
-	libutils \
-	liblog \
-	libbinder \
-	libandroid_runtime
-
-LOCAL_MODULE:= app_process64
-LOCAL_NO_2ND_ARCH := true
-include $(BUILD_EXECUTABLE)
-
-endif # TARGET_IS_64_BIT
-
 # Build a variant of app_process binary linked with ASan runtime.
 # ARM-only at the moment.
 ifeq ($(TARGET_ARCH),arm)
diff --git a/core/java/android/net/http/CertificateChainValidator.java b/core/java/android/net/http/CertificateChainValidator.java
index 1e476fc..d06355d 100644
--- a/core/java/android/net/http/CertificateChainValidator.java
+++ b/core/java/android/net/http/CertificateChainValidator.java
@@ -16,22 +16,28 @@
 
 package android.net.http;
 
-import com.android.org.conscrypt.SSLParametersImpl;
-import com.android.org.conscrypt.TrustManagerImpl;
+import android.util.Slog;
 
 import java.io.ByteArrayInputStream;
 import java.io.IOException;
+import java.lang.reflect.Method;
 import java.security.GeneralSecurityException;
-import java.security.KeyManagementException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
 import java.security.cert.Certificate;
 import java.security.cert.CertificateException;
 import java.security.cert.CertificateFactory;
 import java.security.cert.X509Certificate;
-import javax.net.ssl.DefaultHostnameVerifier;
+
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.HttpsURLConnection;
 import javax.net.ssl.SSLHandshakeException;
 import javax.net.ssl.SSLSession;
 import javax.net.ssl.SSLSocket;
-import javax.net.ssl.X509TrustManager;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+import javax.net.ssl.X509ExtendedTrustManager;
 
 /**
  * Class responsible for all server certificate validation functionality
@@ -39,28 +45,54 @@
  * {@hide}
  */
 public class CertificateChainValidator {
+    private static final String TAG = "CertificateChainValidator";
 
-    /**
-     * The singleton instance of the certificate chain validator
-     */
-    private static final CertificateChainValidator sInstance
-            = new CertificateChainValidator();
+    private static class NoPreloadHolder {
+        /**
+         * The singleton instance of the certificate chain validator.
+         */
+        private static final CertificateChainValidator sInstance = new CertificateChainValidator();
 
-    private static final DefaultHostnameVerifier sVerifier
-            = new DefaultHostnameVerifier();
+        /**
+         * The singleton instance of the hostname verifier.
+         */
+        private static final HostnameVerifier sVerifier = HttpsURLConnection
+                .getDefaultHostnameVerifier();
+    }
+
+    private X509ExtendedTrustManager mTrustManager;
 
     /**
      * @return The singleton instance of the certificates chain validator
      */
     public static CertificateChainValidator getInstance() {
-        return sInstance;
+        return NoPreloadHolder.sInstance;
     }
 
     /**
      * Creates a new certificate chain validator. This is a private constructor.
      * If you need a Certificate chain validator, call getInstance().
      */
-    private CertificateChainValidator() {}
+    private CertificateChainValidator() {
+        try {
+            TrustManagerFactory tmf = TrustManagerFactory.getInstance("X.509");
+            tmf.init((KeyStore) null);
+            for (TrustManager tm : tmf.getTrustManagers()) {
+                if (tm instanceof X509ExtendedTrustManager) {
+                    mTrustManager = (X509ExtendedTrustManager) tm;
+                }
+            }
+        } catch (NoSuchAlgorithmException e) {
+            throw new RuntimeException("X.509 TrustManagerFactory must be available", e);
+        } catch (KeyStoreException e) {
+            throw new RuntimeException("X.509 TrustManagerFactory cannot be initialized", e);
+        }
+
+        if (mTrustManager == null) {
+            throw new RuntimeException(
+                    "None of the X.509 TrustManagers are X509ExtendedTrustManager");
+        }
+    }
 
     /**
      * Performs the handshake and server certificates validation
@@ -136,14 +168,31 @@
      * Handles updates to credential storage.
      */
     public static void handleTrustStorageUpdate() {
-
+        TrustManagerFactory tmf;
         try {
-            X509TrustManager x509TrustManager = SSLParametersImpl.getDefaultX509TrustManager();
-            if( x509TrustManager instanceof TrustManagerImpl ) {
-                TrustManagerImpl trustManager = (TrustManagerImpl) x509TrustManager;
-                trustManager.handleTrustStorageUpdate();
+            tmf = TrustManagerFactory.getInstance("X.509");
+            tmf.init((KeyStore) null);
+        } catch (NoSuchAlgorithmException e) {
+            Slog.w(TAG, "Couldn't find default X.509 TrustManagerFactory");
+            return;
+        } catch (KeyStoreException e) {
+            Slog.w(TAG, "Couldn't initialize default X.509 TrustManagerFactory", e);
+            return;
+        }
+
+        TrustManager[] tms = tmf.getTrustManagers();
+        boolean sentUpdate = false;
+        for (TrustManager tm : tms) {
+            try {
+                Method updateMethod = tm.getClass().getDeclaredMethod("handleTrustStorageUpdate");
+                updateMethod.setAccessible(true);
+                updateMethod.invoke(tm);
+                sentUpdate = true;
+            } catch (Exception e) {
             }
-        } catch (KeyManagementException ignored) {
+        }
+        if (!sentUpdate) {
+            Slog.w(TAG, "Didn't find a TrustManager to handle CA list update");
         }
     }
 
@@ -166,7 +215,8 @@
 
         boolean valid = domain != null
                 && !domain.isEmpty()
-                && sVerifier.verify(domain, currCertificate);
+                && NoPreloadHolder.sVerifier.verify(domain,
+                        new DelegatingSSLSession.CertificateWrap(currCertificate));
         if (!valid) {
             if (HttpLog.LOGV) {
                 HttpLog.v("certificate not for this host: " + domain);
@@ -175,13 +225,8 @@
         }
 
         try {
-            X509TrustManager x509TrustManager = SSLParametersImpl.getDefaultX509TrustManager();
-            if (x509TrustManager instanceof TrustManagerImpl) {
-                TrustManagerImpl trustManager = (TrustManagerImpl) x509TrustManager;
-                trustManager.checkServerTrusted(chain, authType, domain);
-            } else {
-                x509TrustManager.checkServerTrusted(chain, authType);
-            }
+            getInstance().getTrustManager().checkServerTrusted(chain, authType,
+                    new DelegatingSocketWrapper(domain));
             return null;  // No errors.
         } catch (GeneralSecurityException e) {
             if (HttpLog.LOGV) {
@@ -192,6 +237,12 @@
         }
     }
 
+    /**
+     * Returns the platform default {@link X509ExtendedTrustManager}.
+     */
+    private X509ExtendedTrustManager getTrustManager() {
+        return mTrustManager;
+    }
 
     private void closeSocketThrowException(
             SSLSocket socket, String errorMessage, String defaultErrorMessage)
@@ -217,4 +268,4 @@
 
         throw new SSLHandshakeException(errorMessage);
     }
-}
+}
\ No newline at end of file
diff --git a/core/java/android/net/http/DelegatingSSLSession.java b/core/java/android/net/http/DelegatingSSLSession.java
new file mode 100644
index 0000000..ff75b24
--- /dev/null
+++ b/core/java/android/net/http/DelegatingSSLSession.java
@@ -0,0 +1,172 @@
+/*
+ * Copyright 2014 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.net.http;
+
+import java.security.Principal;
+import java.security.cert.Certificate;
+import java.security.cert.X509Certificate;
+
+import javax.net.ssl.SSLPeerUnverifiedException;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.SSLSessionContext;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.X509ExtendedTrustManager;
+
+/**
+ * This is used when only a {@code hostname} is available but usage of the new API
+ * {@link X509ExtendedTrustManager#checkServerTrusted(X509Certificate[], String, Socket)}
+ * requires a {@link SSLSocket}.
+ *
+ * @hide
+ */
+public class DelegatingSSLSession implements SSLSession {
+    protected DelegatingSSLSession() {
+    }
+
+    public static class HostnameWrap extends DelegatingSSLSession {
+        private final String mHostname;
+
+        public HostnameWrap(String hostname) {
+            mHostname = hostname;
+        }
+
+        @Override
+        public String getPeerHost() {
+            return mHostname;
+        }
+    }
+
+    public static class CertificateWrap extends DelegatingSSLSession {
+        private final Certificate mCertificate;
+
+        public CertificateWrap(Certificate certificate) {
+            mCertificate = certificate;
+        }
+
+        @Override
+        public Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException {
+            return new Certificate[] { mCertificate };
+        }
+    }
+
+
+    @Override
+    public int getApplicationBufferSize() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public String getCipherSuite() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public long getCreationTime() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public byte[] getId() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public long getLastAccessedTime() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public Certificate[] getLocalCertificates() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public Principal getLocalPrincipal() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public int getPacketBufferSize() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public javax.security.cert.X509Certificate[] getPeerCertificateChain()
+            throws SSLPeerUnverifiedException {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public String getPeerHost() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public int getPeerPort() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public String getProtocol() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public SSLSessionContext getSessionContext() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public Object getValue(String name) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public String[] getValueNames() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public void invalidate() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public boolean isValid() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public void putValue(String name, Object value) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public void removeValue(String name) {
+        throw new UnsupportedOperationException();
+    }
+}
\ No newline at end of file
diff --git a/core/java/android/net/http/DelegatingSocketWrapper.java b/core/java/android/net/http/DelegatingSocketWrapper.java
new file mode 100644
index 0000000..230d017
--- /dev/null
+++ b/core/java/android/net/http/DelegatingSocketWrapper.java
@@ -0,0 +1,127 @@
+/*
+ * Copyright 2014 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.net.http;
+
+import java.io.IOException;
+
+import javax.net.ssl.HandshakeCompletedListener;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.X509ExtendedTrustManager;
+
+/**
+ * This is used when only a {@code hostname} is available for
+ * {@link X509ExtendedTrustManager#checkServerTrusted(java.security.cert.X509Certificate[], String, Socket)}
+ * but we want to use the new API that requires a {@link SSLSocket}.
+ */
+class DelegatingSocketWrapper extends SSLSocket {
+    private String hostname;
+
+    public DelegatingSocketWrapper(String hostname) {
+        this.hostname = hostname;
+    }
+
+    @Override
+    public String[] getSupportedCipherSuites() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public String[] getEnabledCipherSuites() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public void setEnabledCipherSuites(String[] suites) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public String[] getSupportedProtocols() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public String[] getEnabledProtocols() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public void setEnabledProtocols(String[] protocols) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public SSLSession getSession() {
+        return new DelegatingSSLSession.HostnameWrap(hostname);
+    }
+
+    @Override
+    public void addHandshakeCompletedListener(HandshakeCompletedListener listener) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public void removeHandshakeCompletedListener(HandshakeCompletedListener listener) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public void startHandshake() throws IOException {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public void setUseClientMode(boolean mode) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public boolean getUseClientMode() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public void setNeedClientAuth(boolean need) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public void setWantClientAuth(boolean want) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public boolean getNeedClientAuth() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public boolean getWantClientAuth() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public void setEnableSessionCreation(boolean flag) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public boolean getEnableSessionCreation() {
+        throw new UnsupportedOperationException();
+    }
+}
\ No newline at end of file
diff --git a/core/java/android/net/http/X509TrustManagerExtensions.java b/core/java/android/net/http/X509TrustManagerExtensions.java
index cfe5f27..666832a 100644
--- a/core/java/android/net/http/X509TrustManagerExtensions.java
+++ b/core/java/android/net/http/X509TrustManagerExtensions.java
@@ -22,14 +22,25 @@
 import java.security.cert.X509Certificate;
 import java.util.List;
 
+import javax.net.ssl.SSLParameters;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.X509ExtendedTrustManager;
 import javax.net.ssl.X509TrustManager;
 
 /**
  * X509TrustManager wrapper exposing Android-added features.
- *
- * <p> The checkServerTrusted method allows callers to perform additional
- * verification of certificate chains after they have been successfully
- * verified by the platform.</p>
+ * <p>
+ * The checkServerTrusted method allows callers to perform additional
+ * verification of certificate chains after they have been successfully verified
+ * by the platform.
+ * </p>
+ * <p>
+ * If the returned certificate list is not needed, see also
+ * {@code X509ExtendedTrustManager#checkServerTrusted(X509Certificate[], String, java.net.Socket)}
+ * where an {@link SSLSocket} can be used to verify the given hostname during
+ * handshake using
+ * {@code SSLParameters#setEndpointIdentificationAlgorithm(String)}.
+ * </p>
  */
 public class X509TrustManagerExtensions {
 
@@ -61,6 +72,7 @@
      */
     public List<X509Certificate> checkServerTrusted(X509Certificate[] chain, String authType,
                                                     String host) throws CertificateException {
-        return mDelegate.checkServerTrusted(chain, authType, host);
+        return mDelegate.checkServerTrusted(chain, authType,
+                new DelegatingSSLSession.HostnameWrap(host));
     }
 }
diff --git a/core/jni/android/graphics/BitmapFactory.cpp b/core/jni/android/graphics/BitmapFactory.cpp
index 13c1fc8..44bf7f8 100644
--- a/core/jni/android/graphics/BitmapFactory.cpp
+++ b/core/jni/android/graphics/BitmapFactory.cpp
@@ -114,7 +114,7 @@
         }
     }
 
-    int32_t* yDivs = chunk->getXDivs();
+    int32_t* yDivs = chunk->getYDivs();
     for (int i = 0; i < chunk->numYDivs; i++) {
         yDivs[i] = int32_t(yDivs[i] * scale + 0.5f);
         if (i > 0 && yDivs[i] == yDivs[i - 1]) {
diff --git a/core/jni/android/graphics/TextLayoutCache.cpp b/core/jni/android/graphics/TextLayoutCache.cpp
index 92d253f..e2c78b1 100644
--- a/core/jni/android/graphics/TextLayoutCache.cpp
+++ b/core/jni/android/graphics/TextLayoutCache.cpp
@@ -69,7 +69,7 @@
     size_t totalSizeToDelete = text.getSize() + desc->getSize();
     mSize -= totalSizeToDelete;
     if (mDebugEnabled) {
-        ALOGD("Cache value %p deleted, size = %d", desc.get(), totalSizeToDelete);
+        ALOGD("Cache value %p deleted, size = %zu", desc.get(), totalSizeToDelete);
     }
 }
 
@@ -129,7 +129,7 @@
                     bool removedOne = mCache.removeOldest();
                     LOG_ALWAYS_FATAL_IF(!removedOne, "The cache is non-empty but we "
                             "failed to remove the oldest entry.  "
-                            "mSize = %u, size = %u, mMaxSize = %u, mCache.size() = %u",
+                            "mSize = %u, size = %zu, mMaxSize = %u, mCache.size() = %zu",
                             mSize, size, mMaxSize, mCache.size());
                 }
             }
@@ -148,7 +148,7 @@
                 nsecs_t totalTime = systemTime(SYSTEM_TIME_MONOTONIC) - startTime;
                 ALOGD("CACHE MISS: Added entry %p "
                         "with start = %d, count = %d, contextCount = %d, "
-                        "entry size %d bytes, remaining space %d bytes"
+                        "entry size %zu bytes, remaining space %d bytes"
                         " - Compute time %0.6f ms - Put time %0.6f ms - Text = '%s'",
                         value.get(), start, count, contextCount, size, mMaxSize - mSize,
                         value->getElapsedTime() * 0.000001f,
@@ -159,7 +159,7 @@
             if (mDebugEnabled) {
                 ALOGD("CACHE MISS: Calculated but not storing entry because it is too big "
                         "with start = %d, count = %d, contextCount = %d, "
-                        "entry size %d bytes, remaining space %d bytes"
+                        "entry size %zu bytes, remaining space %d bytes"
                         " - Compute time %0.6f ms - Text = '%s'",
                         start, count, contextCount, size, mMaxSize - mSize,
                         value->getElapsedTime() * 0.000001f,
@@ -204,7 +204,7 @@
     ALOGD("------------------------------------------------");
     ALOGD("pid       : %d", getpid());
     ALOGD("running   : %.0f seconds", timeRunningInSec);
-    ALOGD("entries   : %d", cacheSize);
+    ALOGD("entries   : %zu", cacheSize);
     ALOGD("max size  : %d bytes", mMaxSize);
     ALOGD("used      : %d bytes according to mSize", mSize);
     ALOGD("remaining : %d bytes or %2.2f percent", mMaxSize - mSize, remainingPercent);
diff --git a/core/jni/android_net_LocalSocketImpl.cpp b/core/jni/android_net_LocalSocketImpl.cpp
index 9f79f74..98f4bed 100644
--- a/core/jni/android_net_LocalSocketImpl.cpp
+++ b/core/jni/android_net_LocalSocketImpl.cpp
@@ -111,7 +111,7 @@
 
 /* private native void listen_native(int fd, int backlog) throws IOException; */
 static void
-socket_listen (JNIEnv *env, jobject object, jobject fileDescriptor, int backlog)
+socket_listen (JNIEnv *env, jobject object, jobject fileDescriptor, jint backlog)
 {
     int ret;
     int fd;
@@ -231,7 +231,7 @@
 }
 
 static jint
-socket_getOption(JNIEnv *env, jobject object, jobject fileDescriptor, int optID)
+socket_getOption(JNIEnv *env, jobject object, jobject fileDescriptor, jint optID)
 {
     int ret, value;
     int opt, level;
@@ -279,7 +279,7 @@
 }
 
 static void socket_setOption(
-        JNIEnv *env, jobject object, jobject fileDescriptor, int optID,
+        JNIEnv *env, jobject object, jobject fileDescriptor, jint optID,
         jint boolValue, jint intValue) {
     int ret;
     int optname;
diff --git a/core/jni/android_nio_utils.cpp b/core/jni/android_nio_utils.cpp
index 7cbbe12..59d6e41 100644
--- a/core/jni/android_nio_utils.cpp
+++ b/core/jni/android_nio_utils.cpp
@@ -37,7 +37,7 @@
                                          gNioJNI.getBasePointerID, buffer);
     if (pointer != 0L) {
         *array = NULL;
-        return (void *) (jint) pointer;
+        return reinterpret_cast<void *>(pointer);
     }
 
     *array = (jarray) _env->CallStaticObjectMethod(gNioJNI.nioAccessClass,
diff --git a/core/jni/android_os_Debug.cpp b/core/jni/android_os_Debug.cpp
index a041693..d4873d6 100644
--- a/core/jni/android_os_Debug.cpp
+++ b/core/jni/android_os_Debug.cpp
@@ -800,7 +800,7 @@
     fprintf(fp, "Total memory: %zu\n", totalMemory);
     fprintf(fp, "Allocation records: %zd\n", recordCount);
     if (backtraceSize != BACKTRACE_SIZE) {
-        fprintf(fp, "WARNING: mismatched backtrace sizes (%d vs. %d)\n",
+        fprintf(fp, "WARNING: mismatched backtrace sizes (%zu vs. %d)\n",
             backtraceSize, BACKTRACE_SIZE);
     }
     fprintf(fp, "\n");
@@ -823,7 +823,11 @@
             if (backtrace[bt] == 0) {
                 break;
             } else {
+#ifdef __LP64__
+                fprintf(fp, " %016x", backtrace[bt]);
+#else
                 fprintf(fp, " %08x", backtrace[bt]);
+#endif
             }
         }
         fprintf(fp, "\n");
diff --git a/core/jni/android_server_NetworkManagementSocketTagger.cpp b/core/jni/android_server_NetworkManagementSocketTagger.cpp
index 12beff7..7e12b1e 100644
--- a/core/jni/android_server_NetworkManagementSocketTagger.cpp
+++ b/core/jni/android_server_NetworkManagementSocketTagger.cpp
@@ -47,8 +47,8 @@
   return (jint)res;
 }
 
-static int QTagUid_untagSocketFd(JNIEnv* env, jclass,
-                                 jobject fileDescriptor) {
+static jint QTagUid_untagSocketFd(JNIEnv* env, jclass,
+                                  jobject fileDescriptor) {
   int userFd = jniGetFDFromFileDescriptor(env, fileDescriptor);
 
   if (env->ExceptionOccurred() != NULL) {
diff --git a/core/jni/android_text_AndroidBidi.cpp b/core/jni/android_text_AndroidBidi.cpp
index d50a69f..6f7ee49 100644
--- a/core/jni/android_text_AndroidBidi.cpp
+++ b/core/jni/android_text_AndroidBidi.cpp
@@ -26,7 +26,7 @@
 namespace android {
 
 static jint runBidi(JNIEnv* env, jobject obj, jint dir, jcharArray chsArray,
-                    jbyteArray infoArray, int n, jboolean haveInfo)
+                    jbyteArray infoArray, jint n, jboolean haveInfo)
 {
     // Parameters are checked on java side
     // Failures from GetXXXArrayElements indicate a serious out-of-memory condition
diff --git a/core/jni/android_text_AndroidCharacter.cpp b/core/jni/android_text_AndroidCharacter.cpp
index 8b85a7b7..94bd40f 100644
--- a/core/jni/android_text_AndroidCharacter.cpp
+++ b/core/jni/android_text_AndroidCharacter.cpp
@@ -51,7 +51,8 @@
 
 namespace android {
 
-static void getDirectionalities(JNIEnv* env, jobject obj, jcharArray srcArray, jbyteArray destArray, int count)
+static void getDirectionalities(JNIEnv* env, jobject obj, jcharArray srcArray,
+                                jbyteArray destArray, jint count)
 {
     ScopedCharArrayRO src(env, srcArray);
     if (src.get() == NULL) {
@@ -102,7 +103,7 @@
 }
 
 static void getEastAsianWidths(JNIEnv* env, jobject obj, jcharArray srcArray,
-                               int start, int count, jbyteArray destArray)
+                               jint start, jint count, jbyteArray destArray)
 {
     ScopedCharArrayRO src(env, srcArray);
     if (src.get() == NULL) {
@@ -144,20 +145,20 @@
     }
 }
 
-static jboolean mirror(JNIEnv* env, jobject obj, jcharArray charArray, int start, int count)
+static jboolean mirror(JNIEnv* env, jobject obj, jcharArray charArray, jint start, jint count)
 {
     ScopedCharArrayRW data(env, charArray);
     if (data.get() == NULL) {
-        return false;
+        return JNI_FALSE;
     }
 
     if (start < 0 || start > start + count
             || env->GetArrayLength(charArray) < start + count) {
         jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", NULL);
-        return false;
+        return JNI_FALSE;
     }
 
-    bool ret = false;
+    jboolean ret = JNI_FALSE;
     for (int i = start; i < start + count; i++) {
         // XXX this thinks it knows that surrogates are never mirrored
 
@@ -166,7 +167,7 @@
 
         if (c1 != c2) {
             data[i] = c2;
-            ret = true;
+            ret = JNI_TRUE;
         }
     }
     return ret;
diff --git a/core/jni/android_text_format_Time.cpp b/core/jni/android_text_format_Time.cpp
index aa2c5f39..28a8a5d 100644
--- a/core/jni/android_text_format_Time.cpp
+++ b/core/jni/android_text_format_Time.cpp
@@ -117,7 +117,7 @@
     time2java(env, This, t);
     RELEASE_TIMEZONE(This, t)
 
-    return result;
+    return static_cast<jlong>(result);
 }
 
 static void android_text_format_Time_switchTimezone(JNIEnv* env, jobject This,
@@ -155,7 +155,7 @@
     RELEASE_TIMEZONE(aObject, a)
     RELEASE_TIMEZONE(bObject, b)
 
-    return result;
+    return static_cast<jint>(result);
 }
 
 static jstring android_text_format_Time_format2445(JNIEnv* env, jobject This)
@@ -346,7 +346,7 @@
 
     RELEASE_TIMEZONE(This, t)
 
-    return result;
+    return static_cast<jlong>(result);
 }
 
 static void android_text_format_Time_set(JNIEnv* env, jobject This, jlong millis)
@@ -400,10 +400,10 @@
     if (len < 8) {
         jniThrowException(env, "android/util/TimeFormatException",
                           "String too short -- expected at least 8 characters.");
-        return false;
+        return JNI_FALSE;
     }
 
-    jboolean inUtc = false;
+    jboolean inUtc = JNI_FALSE;
 
     ScopedStringChars s(env, strObj);
 
@@ -414,49 +414,49 @@
     n += get_char(env, s, 1, 100, &thrown);
     n += get_char(env, s, 2, 10, &thrown);
     n += get_char(env, s, 3, 1, &thrown);
-    if (thrown) return false;
+    if (thrown) return JNI_FALSE;
     env->SetIntField(This, g_yearField, n);
 
     // month
     n = get_char(env, s, 4, 10, &thrown);
     n += get_char(env, s, 5, 1, &thrown);
     n--;
-    if (thrown) return false;
+    if (thrown) return JNI_FALSE;
     env->SetIntField(This, g_monField, n);
 
     // day of month
     n = get_char(env, s, 6, 10, &thrown);
     n += get_char(env, s, 7, 1, &thrown);
-    if (thrown) return false;
+    if (thrown) return JNI_FALSE;
     env->SetIntField(This, g_mdayField, n);
 
     if (len > 8) {
         // T
-        if (!check_char(env, s, 8, 'T')) return false;
+        if (!check_char(env, s, 8, 'T')) return JNI_FALSE;
         env->SetBooleanField(This, g_allDayField, JNI_FALSE);
 
         // hour
         n = get_char(env, s, 9, 10, &thrown);
         n += get_char(env, s, 10, 1, &thrown);
-        if (thrown) return false;
+        if (thrown) return JNI_FALSE;
         env->SetIntField(This, g_hourField, n);
 
         // min
         n = get_char(env, s, 11, 10, &thrown);
         n += get_char(env, s, 12, 1, &thrown);
-        if (thrown) return false;
+        if (thrown) return JNI_FALSE;
         env->SetIntField(This, g_minField, n);
 
         // sec
         n = get_char(env, s, 13, 10, &thrown);
         n += get_char(env, s, 14, 1, &thrown);
-        if (thrown) return false;
+        if (thrown) return JNI_FALSE;
         env->SetIntField(This, g_secField, n);
 
         if (len > 15) {
             // Z
-            if (!check_char(env, s, 15, 'Z')) return false;
-            inUtc = true;
+            if (!check_char(env, s, 15, 'Z')) return JNI_FALSE;
+            inUtc = JNI_TRUE;
         }
     } else {
         env->SetBooleanField(This, g_allDayField, JNI_TRUE);
@@ -481,10 +481,10 @@
     if (len < 10) {
         jniThrowException(env, "android/util/TimeFormatException",
                           "String too short --- expected at least 10 characters.");
-        return false;
+        return JNI_FALSE;
     }
 
-    jboolean inUtc = false;
+    jboolean inUtc = JNI_FALSE;
 
     ScopedStringChars s(env, strObj);
 
@@ -495,57 +495,57 @@
     n += get_char(env, s, 1, 100, &thrown);
     n += get_char(env, s, 2, 10, &thrown);
     n += get_char(env, s, 3, 1, &thrown);
-    if (thrown) return false;
+    if (thrown) return JNI_FALSE;
     env->SetIntField(This, g_yearField, n);
     
     // -
-    if (!check_char(env, s, 4, '-')) return false;
+    if (!check_char(env, s, 4, '-')) return JNI_FALSE;
     
     // month
     n = get_char(env, s, 5, 10, &thrown);
     n += get_char(env, s, 6, 1, &thrown);
     --n;
-    if (thrown) return false;
+    if (thrown) return JNI_FALSE;
     env->SetIntField(This, g_monField, n);
 
     // -
-    if (!check_char(env, s, 7, '-')) return false;
+    if (!check_char(env, s, 7, '-')) return JNI_FALSE;
 
     // day
     n = get_char(env, s, 8, 10, &thrown);
     n += get_char(env, s, 9, 1, &thrown);
-    if (thrown) return false;
+    if (thrown) return JNI_FALSE;
     env->SetIntField(This, g_mdayField, n);
 
     if (len >= 19) {
         // T
-        if (!check_char(env, s, 10, 'T')) return false;
+        if (!check_char(env, s, 10, 'T')) return JNI_FALSE;
 
         env->SetBooleanField(This, g_allDayField, JNI_FALSE);
         // hour
         n = get_char(env, s, 11, 10, &thrown);
         n += get_char(env, s, 12, 1, &thrown);
-        if (thrown) return false;
+        if (thrown) return JNI_FALSE;
         int hour = n;
         // env->SetIntField(This, g_hourField, n);
 
         // :
-        if (!check_char(env, s, 13, ':')) return false;
+        if (!check_char(env, s, 13, ':')) return JNI_FALSE;
 
         // minute
         n = get_char(env, s, 14, 10, &thrown);
         n += get_char(env, s, 15, 1, &thrown);
-        if (thrown) return false;
+        if (thrown) return JNI_FALSE;
         int minute = n;
         // env->SetIntField(This, g_minField, n);
 
         // :
-        if (!check_char(env, s, 16, ':')) return false;
+        if (!check_char(env, s, 16, ':')) return JNI_FALSE;
 
         // second
         n = get_char(env, s, 17, 10, &thrown);
         n += get_char(env, s, 18, 1, &thrown);
-        if (thrown) return false;
+        if (thrown) return JNI_FALSE;
         env->SetIntField(This, g_secField, n);
 
         // skip the '.XYZ' -- we don't care about subsecond precision.
@@ -579,32 +579,32 @@
                 jniThrowExceptionFmt(env, "android/util/TimeFormatException",
                                      "Unexpected character 0x%02x at position %d.  Expected + or -",
                                      c, tz_index);
-                return false;
+                return JNI_FALSE;
             }
-            inUtc = true;
+            inUtc = JNI_TRUE;
 
             if (offset != 0) {
                 if (len < tz_index + 6) {
                     jniThrowExceptionFmt(env, "android/util/TimeFormatException",
                                          "Unexpected length; should be %d characters",
                                          tz_index + 6);
-                    return false;
+                    return JNI_FALSE;
                 }
 
                 // hour
                 n = get_char(env, s, tz_index + 1, 10, &thrown);
                 n += get_char(env, s, tz_index + 2, 1, &thrown);
-                if (thrown) return false;
+                if (thrown) return JNI_FALSE;
                 n *= offset;
                 hour += n;
 
                 // :
-                if (!check_char(env, s, tz_index + 3, ':')) return false;
+                if (!check_char(env, s, tz_index + 3, ':')) return JNI_FALSE;
             
                 // minute
                 n = get_char(env, s, tz_index + 4, 10, &thrown);
                 n += get_char(env, s, tz_index + 5, 1, &thrown);
-                if (thrown) return false;
+                if (thrown) return JNI_FALSE;
                 n *= offset;
                 minute += n;
             }
diff --git a/core/jni/android_util_Log.cpp b/core/jni/android_util_Log.cpp
index 536a582..93dcbef 100644
--- a/core/jni/android_util_Log.cpp
+++ b/core/jni/android_util_Log.cpp
@@ -85,7 +85,7 @@
     jboolean result = false;
     if ((strlen(chars)+sizeof(LOG_NAMESPACE)) > PROPERTY_KEY_MAX) {
         char buf2[200];
-        snprintf(buf2, sizeof(buf2), "Log tag \"%s\" exceeds limit of %d characters\n",
+        snprintf(buf2, sizeof(buf2), "Log tag \"%s\" exceeds limit of %zu characters\n",
                 chars, PROPERTY_KEY_MAX - sizeof(LOG_NAMESPACE));
 
         jniThrowException(env, "java/lang/IllegalArgumentException", buf2);
diff --git a/libs/androidfw/BackupData.cpp b/libs/androidfw/BackupData.cpp
index 2d0f755..bd9dc76 100644
--- a/libs/androidfw/BackupData.cpp
+++ b/libs/androidfw/BackupData.cpp
@@ -78,7 +78,7 @@
     paddingSize = padding_extra(n);
     if (paddingSize > 0) {
         uint32_t padding = 0xbcbcbcbc;
-        if (DEBUG) ALOGI("writing %d padding bytes for %d", paddingSize, n);
+        if (DEBUG) ALOGI("writing %zd padding bytes for %d", paddingSize, n);
         amt = write(m_fd, &padding, paddingSize);
         if (amt != paddingSize) {
             m_status = errno;
@@ -112,7 +112,7 @@
         k = key;
     }
     if (DEBUG) {
-        ALOGD("Writing header: prefix='%s' key='%s' dataSize=%d", m_keyPrefix.string(),
+        ALOGD("Writing header: prefix='%s' key='%s' dataSize=%zu", m_keyPrefix.string(),
                 key.string(), dataSize);
     }
 
@@ -125,7 +125,7 @@
     header.keyLen = tolel(keyLen);
     header.dataSize = tolel(dataSize);
 
-    if (DEBUG) ALOGI("writing entity header, %d bytes", sizeof(entity_header_v1));
+    if (DEBUG) ALOGI("writing entity header, %zu bytes", sizeof(entity_header_v1));
     amt = write(m_fd, &header, sizeof(entity_header_v1));
     if (amt != sizeof(entity_header_v1)) {
         m_status = errno;
@@ -133,7 +133,7 @@
     }
     m_pos += amt;
 
-    if (DEBUG) ALOGI("writing entity header key, %d bytes", keyLen+1);
+    if (DEBUG) ALOGI("writing entity header key, %zd bytes", keyLen+1);
     amt = write(m_fd, k.string(), keyLen+1);
     if (amt != keyLen+1) {
         m_status = errno;
diff --git a/libs/androidfw/BackupHelpers.cpp b/libs/androidfw/BackupHelpers.cpp
index ab837ad..52dce9f 100644
--- a/libs/androidfw/BackupHelpers.cpp
+++ b/libs/androidfw/BackupHelpers.cpp
@@ -639,7 +639,7 @@
 
         // size header -- calc len in digits by actually rendering the number
         // to a string - brute force but simple
-        snprintf(sizeStr, sizeof(sizeStr), "%lld", s.st_size);
+        snprintf(sizeStr, sizeof(sizeStr), "%lld", (long long)s.st_size);
         p += write_pax_header_entry(p, "size", sizeStr);
 
         // fullname was generated above with the ustar paths
@@ -661,7 +661,7 @@
 
         // [ 124 :  12 ] size of pax extended header data
         memset(paxHeader + 124, 0, 12);
-        snprintf(paxHeader + 124, 12, "%011o", p - paxData);
+        snprintf(paxHeader + 124, 12, "%011o", (unsigned int)(p - paxData));
 
         // Checksum and write the pax block header
         calc_tar_checksum(paxHeader);
@@ -681,7 +681,10 @@
     if (!isdir) {
         off64_t toWrite = s.st_size;
         while (toWrite > 0) {
-            size_t toRead = (toWrite < BUFSIZE) ? toWrite : BUFSIZE;
+            size_t toRead = toWrite;
+            if (toRead > BUFSIZE) {
+                toRead = BUFSIZE;
+            }
             ssize_t nRead = read(fd, buf, toRead);
             if (nRead < 0) {
                 err = errno;
@@ -1095,8 +1098,8 @@
         if (name != filenames[i] || states[i].modTime_sec != state.modTime_sec
                 || states[i].modTime_nsec != state.modTime_nsec || states[i].mode != state.mode
                 || states[i].size != state.size || states[i].crc32 != states[i].crc32) {
-            fprintf(stderr, "state %zu expected={%d/%d, 0x%08x, %04o, 0x%08x, %3d} '%s'\n"
-                            "          actual={%d/%d, 0x%08x, %04o, 0x%08x, %3zu} '%s'\n", i,
+            fprintf(stderr, "state %zu expected={%d/%d, %04o, 0x%08x, 0x%08x, %3zu} '%s'\n"
+                            "          actual={%d/%d, %04o, 0x%08x, 0x%08x, %3d} '%s'\n", i,
                     states[i].modTime_sec, states[i].modTime_nsec, states[i].mode, states[i].size,
                     states[i].crc32, name.length(), filenames[i].string(),
                     state.modTime_sec, state.modTime_nsec, state.mode, state.size, state.crc32,
@@ -1194,7 +1197,7 @@
 test_read_header_and_entity(BackupDataReader& reader, const char* str)
 {
     int err;
-    int bufSize = strlen(str)+1;
+    size_t bufSize = strlen(str)+1;
     char* buf = (char*)malloc(bufSize);
     String8 string;
     int cookie = 0x11111111;
@@ -1229,9 +1232,9 @@
         err = EINVAL;
         goto finished;
     }
-    if ((int)actualSize != bufSize) {
-        fprintf(stderr, "ReadEntityHeader expected dataSize 0x%08x got 0x%08zx\n", bufSize,
-                actualSize);
+    if (actualSize != bufSize) {
+        fprintf(stderr, "ReadEntityHeader expected dataSize %zu got %zu\n",
+                bufSize, actualSize);
         err = EINVAL;
         goto finished;
     }
diff --git a/libs/androidfw/CursorWindow.cpp b/libs/androidfw/CursorWindow.cpp
index 2b74a33..166863c 100644
--- a/libs/androidfw/CursorWindow.cpp
+++ b/libs/androidfw/CursorWindow.cpp
@@ -210,8 +210,8 @@
     uint32_t offset = mHeader->freeOffset + padding;
     uint32_t nextFreeOffset = offset + size;
     if (nextFreeOffset > mSize) {
-        ALOGW("Window is full: requested allocation %d bytes, "
-                "free space %d bytes, window size %d bytes",
+        ALOGW("Window is full: requested allocation %zu bytes, "
+                "free space %zu bytes, window size %zu bytes",
                 size, freeSpace(), mSize);
         return 0;
     }
diff --git a/libs/androidfw/ResourceTypes.cpp b/libs/androidfw/ResourceTypes.cpp
index 652cd4a..1ffe665 100644
--- a/libs/androidfw/ResourceTypes.cpp
+++ b/libs/androidfw/ResourceTypes.cpp
@@ -5996,12 +5996,12 @@
 
                         uintptr_t esize = dtohs(ent->size);
                         if ((esize&0x3) != 0) {
-                            printf("NON-INTEGER ResTable_entry SIZE: 0x%x\n", esize);
+                            printf("NON-INTEGER ResTable_entry SIZE: %p\n", (void *)esize);
                             continue;
                         }
                         if ((thisOffset+esize) > typeSize) {
-                            printf("ResTable_entry OUT OF BOUNDS: 0x%x+0x%x+0x%x (size is 0x%x)\n",
-                                   entriesStart, thisOffset, esize, typeSize);
+                            printf("ResTable_entry OUT OF BOUNDS: 0x%x+0x%x+%p (size is 0x%x)\n",
+                                   entriesStart, thisOffset, (void *)esize, typeSize);
                             continue;
                         }
 
diff --git a/libs/hwui/Patch.cpp b/libs/hwui/Patch.cpp
index b2148b0..442e9ba 100644
--- a/libs/hwui/Patch.cpp
+++ b/libs/hwui/Patch.cpp
@@ -36,6 +36,7 @@
 }
 
 Patch::~Patch() {
+    delete[] vertices;
 }
 
 ///////////////////////////////////////////////////////////////////////////////
diff --git a/libs/hwui/PatchCache.cpp b/libs/hwui/PatchCache.cpp
index 8a44604..2f2debc 100644
--- a/libs/hwui/PatchCache.cpp
+++ b/libs/hwui/PatchCache.cpp
@@ -119,6 +119,17 @@
 
 void PatchCache::removeDeferred(Res_png_9patch* patch) {
     Mutex::Autolock _l(mLock);
+
+    // Assert that patch is not already garbage
+    size_t count = mGarbage.size();
+    for (size_t i = 0; i < count; i++) {
+        if (patch == mGarbage[i]) {
+            patch = NULL;
+            break;
+        }
+    }
+    LOG_ALWAYS_FATAL_IF(patch == NULL);
+
     mGarbage.push(patch);
 }
 
@@ -143,8 +154,8 @@
     for (size_t i = 0; i < patchesToRemove.size(); i++) {
         const patch_pair_t& pair = patchesToRemove[i];
 
-        // Add a new free block to the list
-        const Patch* patch = pair.getSecond();
+        // Release the patch and mark the space in the free list
+        Patch* patch = pair.getSecond();
         BufferBlock* block = new BufferBlock(patch->offset, patch->getSize());
         block->next = mFreeBlocks;
         mFreeBlocks = block;
@@ -152,6 +163,7 @@
         mSize -= patch->getSize();
 
         mCache.remove(*pair.getFirst());
+        delete patch;
     }
 
 #if DEBUG_PATCHES
@@ -216,6 +228,7 @@
         } else {
             mFreeBlocks = block->next;
         }
+        delete block;
     } else {
         // Resize the block now that it's occupied
         block->offset += size;
diff --git a/libs/hwui/ResourceCache.cpp b/libs/hwui/ResourceCache.cpp
index d276a29..77292bf 100644
--- a/libs/hwui/ResourceCache.cpp
+++ b/libs/hwui/ResourceCache.cpp
@@ -31,9 +31,9 @@
     ALOGD("ResourceCache: cacheReport:");
     for (size_t i = 0; i < mCache->size(); ++i) {
         ResourceReference* ref = mCache->valueAt(i);
-        ALOGD("  ResourceCache: mCache(%d): resource, ref = 0x%p, 0x%p",
+        ALOGD("  ResourceCache: mCache(%zu): resource, ref = 0x%p, 0x%p",
                 i, mCache->keyAt(i), mCache->valueAt(i));
-        ALOGD("  ResourceCache: mCache(%d): refCount, recycled, destroyed, type = %d, %d, %d, %d",
+        ALOGD("  ResourceCache: mCache(%zu): refCount, recycled, destroyed, type = %d, %d, %d, %d",
                 i, ref->refCount, ref->recycled, ref->destroyed, ref->resourceType);
     }
 }
diff --git a/libs/usb/tests/AccessoryChat/accessorychat/accessorychat.c b/libs/usb/tests/AccessoryChat/accessorychat/accessorychat.c
index 06b477f..57c0320 100644
--- a/libs/usb/tests/AccessoryChat/accessorychat/accessorychat.c
+++ b/libs/usb/tests/AccessoryChat/accessorychat/accessorychat.c
@@ -32,7 +32,7 @@
 struct usb_device *sDevice = NULL;
 
 static void* read_thread(void* arg) {
-    int endpoint = (int)arg;
+    int endpoint = (int)(uintptr_t)arg;
     int ret = 0;
 
     while (sDevice && ret >= 0) {
@@ -52,7 +52,7 @@
 }
 
 static void* write_thread(void* arg) {
-    int endpoint = (int)arg;
+    int endpoint = (int)(uintptr_t)arg;
     int ret = 0;
 
     while (ret >= 0) {
@@ -136,11 +136,11 @@
             }
 
             if ((ep1->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_IN) {
-                pthread_create(&th, NULL, read_thread, (void *)ep1->bEndpointAddress);
-                pthread_create(&th, NULL, write_thread, (void *)ep2->bEndpointAddress);
+                pthread_create(&th, NULL, read_thread, (void *)(uintptr_t)ep1->bEndpointAddress);
+                pthread_create(&th, NULL, write_thread, (void *)(uintptr_t)ep2->bEndpointAddress);
             } else {
-                pthread_create(&th, NULL, read_thread, (void *)ep2->bEndpointAddress);
-                pthread_create(&th, NULL, write_thread, (void *)ep1->bEndpointAddress);
+                pthread_create(&th, NULL, read_thread, (void *)(uintptr_t)ep2->bEndpointAddress);
+                pthread_create(&th, NULL, write_thread, (void *)(uintptr_t)ep1->bEndpointAddress);
             }
         } else {
             printf("Found possible android device - attempting to switch to accessory mode\n");
diff --git a/media/jni/android_mtp_MtpDatabase.cpp b/media/jni/android_mtp_MtpDatabase.cpp
index 72ce3cc..8129c0d 100644
--- a/media/jni/android_mtp_MtpDatabase.cpp
+++ b/media/jni/android_mtp_MtpDatabase.cpp
@@ -17,11 +17,12 @@
 #define LOG_TAG "MtpDatabaseJNI"
 #include "utils/Log.h"
 
-#include <stdio.h>
 #include <assert.h>
-#include <limits.h>
-#include <unistd.h>
 #include <fcntl.h>
+#include <inttypes.h>
+#include <limits.h>
+#include <stdio.h>
+#include <unistd.h>
 
 #include "jni.h"
 #include "JNIHelp.h"
@@ -388,7 +389,7 @@
         // release date is stored internally as just the year
         if (property == MTP_PROPERTY_ORIGINAL_RELEASE_DATE) {
             char    date[20];
-            snprintf(date, sizeof(date), "%04lld0101T000000", longValue);
+            snprintf(date, sizeof(date), "%04" PRId64 "0101T000000", longValue);
             packet.putString(date);
             goto out;
         }
@@ -645,7 +646,7 @@
     return result;
 }
 
-MtpResponseCode MyMtpDatabase::resetDeviceProperty(MtpDeviceProperty property) {
+MtpResponseCode MyMtpDatabase::resetDeviceProperty(MtpDeviceProperty /*property*/) {
     return -1;
 }
 
@@ -1090,7 +1091,7 @@
 }
 
 static jstring
-android_mtp_MtpPropertyGroup_format_date_time(JNIEnv *env, jobject thiz, jlong seconds)
+android_mtp_MtpPropertyGroup_format_date_time(JNIEnv *env, jobject /*thiz*/, jlong seconds)
 {
     char    date[20];
     formatDateTime(seconds, date, sizeof(date));
diff --git a/services/common_time/common_time_server.cpp b/services/common_time/common_time_server.cpp
index 21e706f..3e11987 100644
--- a/services/common_time/common_time_server.cpp
+++ b/services/common_time/common_time_server.cpp
@@ -590,7 +590,7 @@
     for (i = 0; (i < src_len) && (offset < dst_len); ++i) {
         int res;
         if (0 == (i % 16)) {
-            res = snprintf(dst + offset, dst_len - offset, "\n%04x :", i);
+            res = snprintf(dst + offset, dst_len - offset, "\n%04zx :", i);
             if (res < 0)
                 break;
             offset += res;
diff --git a/services/common_time/utils.cpp b/services/common_time/utils.cpp
index ed2c77d..ddcdfe7 100644
--- a/services/common_time/utils.cpp
+++ b/services/common_time/utils.cpp
@@ -56,7 +56,7 @@
     , mHeader(header) {
     mRingBuffer = new Entry[mSize];
     if (NULL == mRingBuffer)
-        ALOGE("Failed to allocate log ring with %u entries.", mSize);
+        ALOGE("Failed to allocate log ring with %zu entries.", mSize);
 }
 
 LogRing::~LogRing() {
@@ -150,7 +150,7 @@
 
         localtime_r(&mRingBuffer[ndx].first_ts.tv_sec, &t);
         strftime(timebuf, sizeof(timebuf), kTimeFmt, &t);
-        res = snprintf(buf, sizeof(buf), "[%2d] %s.%03ld :: %s%s\n", 
+        res = snprintf(buf, sizeof(buf), "[%2zu] %s.%03ld :: %s%s\n",
                        i, timebuf,
                        mRingBuffer[ndx].first_ts.tv_usec / 1000,
                        mRingBuffer[ndx].s.string(),
diff --git a/services/input/EventHub.cpp b/services/input/EventHub.cpp
index fc64656..e3a3e17 100644
--- a/services/input/EventHub.cpp
+++ b/services/input/EventHub.cpp
@@ -759,7 +759,7 @@
                 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
                     // Device was removed before INotify noticed.
                     ALOGW("could not get event, removed? (fd: %d size: %d bufferSize: %d "
-                            "capacity: %d errno: %d)\n",
+                            "capacity: %zu errno: %d)\n",
                             device->fd, readSize, bufferSize, capacity, errno);
                     deviceChanged = true;
                     closeDeviceLocked(device);
diff --git a/services/input/InputDispatcher.cpp b/services/input/InputDispatcher.cpp
index 10a639e..06a57d5 100644
--- a/services/input/InputDispatcher.cpp
+++ b/services/input/InputDispatcher.cpp
@@ -147,7 +147,7 @@
         return false;
     }
     if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
-        ALOGE("Motion event has invalid pointer count %d; value must be between 1 and %d.",
+        ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
                 pointerCount, MAX_POINTERS);
         return false;
     }
@@ -3107,7 +3107,7 @@
         dump.append(INDENT "TouchedWindows:\n");
         for (size_t i = 0; i < mTouchState.windows.size(); i++) {
             const TouchedWindow& touchedWindow = mTouchState.windows[i];
-            dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
+            dump.appendFormat(INDENT2 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
                     i, touchedWindow.windowHandle->getName().string(),
                     touchedWindow.pointerIds.value,
                     touchedWindow.targetFlags);
@@ -3122,7 +3122,7 @@
             const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
             const InputWindowInfo* windowInfo = windowHandle->getInfo();
 
-            dump.appendFormat(INDENT2 "%d: name='%s', displayId=%d, "
+            dump.appendFormat(INDENT2 "%zu: name='%s', displayId=%d, "
                     "paused=%s, hasFocus=%s, hasWallpaper=%s, "
                     "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
                     "frame=[%d,%d][%d,%d], scale=%f, "
@@ -3152,7 +3152,7 @@
         dump.append(INDENT "MonitoringChannels:\n");
         for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
             const sp<InputChannel>& channel = mMonitoringChannels[i];
-            dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
+            dump.appendFormat(INDENT2 "%zu: '%s'\n", i, channel->getName().string());
         }
     } else {
         dump.append(INDENT "MonitoringChannels: <none>\n");
@@ -3201,7 +3201,7 @@
         dump.append(INDENT "Connections:\n");
         for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
             const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
-            dump.appendFormat(INDENT2 "%d: channelName='%s', windowName='%s', "
+            dump.appendFormat(INDENT2 "%zu: channelName='%s', windowName='%s', "
                     "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
                     i, connection->getInputChannelName(), connection->getWindowName(),
                     connection->getStatusLabel(), toString(connection->monitor),
diff --git a/services/input/InputReader.cpp b/services/input/InputReader.cpp
index 03852a5..d86fa4f 100644
--- a/services/input/InputReader.cpp
+++ b/services/input/InputReader.cpp
@@ -1992,7 +1992,7 @@
     dumpParameters(dump);
     dump.appendFormat(INDENT3 "KeyboardType: %d\n", mKeyboardType);
     dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
-    dump.appendFormat(INDENT3 "KeyDowns: %d keys currently down\n", mKeyDowns.size());
+    dump.appendFormat(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
     dump.appendFormat(INDENT3 "MetaState: 0x%0x\n", mMetaState);
     dump.appendFormat(INDENT3 "DownTime: %lld\n", mDownTime);
 }
@@ -3372,7 +3372,7 @@
 
         for (size_t i = 0; i < mVirtualKeys.size(); i++) {
             const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
-            dump.appendFormat(INDENT4 "%d: scanCode=%d, keyCode=%d, "
+            dump.appendFormat(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
                     "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
                     i, virtualKey.scanCode, virtualKey.keyCode,
                     virtualKey.hitLeft, virtualKey.hitRight,
@@ -6119,8 +6119,8 @@
             && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
         size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
         if (slotCount > MAX_SLOTS) {
-            ALOGW("MultiTouch Device %s reported %d slots but the framework "
-                    "only supports a maximum of %d slots at this time.",
+            ALOGW("MultiTouch Device %s reported %zu slots but the framework "
+                    "only supports a maximum of %zu slots at this time.",
                     getDeviceName().string(), slotCount, MAX_SLOTS);
             slotCount = MAX_SLOTS;
         }
@@ -6292,7 +6292,7 @@
         // If there are too many axes, start dropping them.
         // Prefer to keep explicitly mapped axes.
         if (mAxes.size() > PointerCoords::MAX_AXES) {
-            ALOGI("Joystick '%s' has %d axes but the framework only supports a maximum of %d.",
+            ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
                     getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
             pruneAxes(true);
             pruneAxes(false);
diff --git a/services/java/com/android/server/am/ActivityStack.java b/services/java/com/android/server/am/ActivityStack.java
index d651a62..b42bce2 100755
--- a/services/java/com/android/server/am/ActivityStack.java
+++ b/services/java/com/android/server/am/ActivityStack.java
@@ -1142,6 +1142,7 @@
                         // At this point, nothing else needs to be shown
                         if (DEBUG_VISBILITY) Slog.v(TAG, "Fullscreen: at " + r);
                         behindFullscreen = true;
+                        showHomeBehindStack = false;
                     } else if (isActivityOverHome(r)) {
                         if (DEBUG_VISBILITY) Slog.v(TAG, "Showing home: at " + r);
                         showHomeBehindStack = true;
diff --git a/services/java/com/android/server/pm/Settings.java b/services/java/com/android/server/pm/Settings.java
index e599409..ed025e1 100644
--- a/services/java/com/android/server/pm/Settings.java
+++ b/services/java/com/android/server/pm/Settings.java
@@ -1427,6 +1427,7 @@
                     // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
                     //   system/core/run-as/run-as.c
                     //   system/core/sdcard/sdcard.c
+                    //   external/libselinux/src/android.c:package_info_init()
                     //
                     sb.setLength(0);
                     sb.append(ai.packageName);
diff --git a/services/java/com/android/server/wm/ScreenRotationAnimation.java b/services/java/com/android/server/wm/ScreenRotationAnimation.java
index e630737..f79896b 100644
--- a/services/java/com/android/server/wm/ScreenRotationAnimation.java
+++ b/services/java/com/android/server/wm/ScreenRotationAnimation.java
@@ -199,7 +199,8 @@
     }
 
     public ScreenRotationAnimation(Context context, DisplayContent displayContent,
-            SurfaceSession session, boolean inTransaction, boolean forceDefaultOrientation) {
+            SurfaceSession session, boolean inTransaction, boolean forceDefaultOrientation,
+            boolean isSecure) {
         mContext = context;
         mDisplayContent = displayContent;
         displayContent.getLogicalDisplayRect(mOriginalDisplayRect);
@@ -241,16 +242,21 @@
 
         try {
             try {
+                int flags = SurfaceControl.HIDDEN;
+                if (isSecure) {
+                    flags |= SurfaceControl.SECURE;
+                }
+
                 if (WindowManagerService.DEBUG_SURFACE_TRACE) {
                     mSurfaceControl = new SurfaceTrace(session, "ScreenshotSurface",
                             mWidth, mHeight,
-                            PixelFormat.OPAQUE, SurfaceControl.HIDDEN);
+                            PixelFormat.OPAQUE, flags);
                     Slog.w(TAG, "ScreenRotationAnimation ctor: displayOffset="
                             + mOriginalDisplayRect.toShortString());
                 } else {
                     mSurfaceControl = new SurfaceControl(session, "ScreenshotSurface",
                             mWidth, mHeight,
-                            PixelFormat.OPAQUE, SurfaceControl.HIDDEN);
+                            PixelFormat.OPAQUE, flags);
                 }
                 // capture a screenshot into the surface we just created
                 Surface sur = new Surface();
diff --git a/services/java/com/android/server/wm/WindowManagerService.java b/services/java/com/android/server/wm/WindowManagerService.java
index 5da3e3e..b6c6770 100644
--- a/services/java/com/android/server/wm/WindowManagerService.java
+++ b/services/java/com/android/server/wm/WindowManagerService.java
@@ -2373,6 +2373,11 @@
     }
 
     public void removeWindowLocked(Session session, WindowState win) {
+        removeWindowLocked(session, win, false);
+    }
+
+    private void removeWindowLocked(Session session, WindowState win,
+            boolean forceRemove) {
         if (win.mAttrs.type == TYPE_APPLICATION_STARTING) {
             if (DEBUG_STARTING_WINDOW) Slog.d(TAG, "Starting window removed " + win);
             removeStartingWindowTimeout(win.mAppToken);
@@ -2423,7 +2428,7 @@
                     mDisplayMagnifier.onWindowTransitionLocked(win, transit);
                 }
             }
-            if (win.mExiting || win.mWinAnimator.isAnimating()) {
+            if (!forceRemove && (win.mExiting || win.mWinAnimator.isAnimating())) {
                 // The exit animation is running... wait for it!
                 //Slog.i(TAG, "*** Running exit animation...");
                 win.mExiting = true;
@@ -9921,9 +9926,21 @@
                 screenRotationAnimation.kill();
             }
 
+            // Check whether the current screen contains any secure content.
+            boolean isSecure = false;
+            final WindowList windows = getDefaultWindowListLocked();
+            final int N = windows.size();
+            for (int i = 0; i < N; i++) {
+                WindowState ws = windows.get(i);
+                if (ws.isOnScreen() && (ws.mAttrs.flags & FLAG_SECURE) != 0) {
+                    isSecure = true;
+                    break;
+                }
+            }
+
             // TODO(multidisplay): rotation on main screen only.
             screenRotationAnimation = new ScreenRotationAnimation(mContext, displayContent,
-                    mFxSession, inTransaction, mPolicy.isDefaultOrientationForced());
+                    mFxSession, inTransaction, mPolicy.isDefaultOrientationForced(), isSecure);
             mAnimator.setScreenRotationAnimationLocked(displayId, screenRotationAnimation);
         }
     }
@@ -10840,7 +10857,7 @@
             WindowList windows = displayContent.getWindowList();
             while (!windows.isEmpty()) {
                 final WindowState win = windows.get(windows.size() - 1);
-                removeWindowLocked(win.mSession, win);
+                removeWindowLocked(win.mSession, win, true);
             }
         }
         mAnimator.removeDisplayLocked(displayId);
diff --git a/services/jni/com_android_server_AlarmManagerService.cpp b/services/jni/com_android_server_AlarmManagerService.cpp
index c26a516..a58b00bce 100644
--- a/services/jni/com_android_server_AlarmManagerService.cpp
+++ b/services/jni/com_android_server_AlarmManagerService.cpp
@@ -365,7 +365,9 @@
     int result = impl->set(type, &ts);
     if (result < 0)
     {
-        ALOGE("Unable to set alarm to %lld.%09lld: %s\n", seconds, nanoseconds, strerror(errno));
+        ALOGE("Unable to set alarm to %lld.%09lld: %s\n",
+              static_cast<long long>(seconds),
+              static_cast<long long>(nanoseconds), strerror(errno));
     }
 }