Merge "Add Third Party Cookie API" into lmp-dev
diff --git a/chromium/Android.mk b/chromium/Android.mk
index d715221..8823abe 100644
--- a/chromium/Android.mk
+++ b/chromium/Android.mk
@@ -35,6 +35,7 @@
 # TODO: filter webviewchromium_webkit_strings based on PRODUCT_LOCALES.
 LOCAL_REQUIRED_MODULES := \
         libwebviewchromium \
+        libwebviewchromium_loader \
         libwebviewchromium_plat_support \
         webviewchromium_pak \
         webviewchromium_webkit_strings_am.pak \
@@ -148,4 +149,27 @@
 LOCAL_CFLAGS := -Wno-unused-parameter
 
 include $(BUILD_SHARED_LIBRARY)
+
+
+# Loader library which handles address space reservation and relro sharing.
+# Does NOT link any native chromium code.
+include $(CLEAR_VARS)
+
+LOCAL_MODULE:= libwebviewchromium_loader
+
+LOCAL_SRC_FILES := \
+        loader/loader.cpp \
+
+LOCAL_CFLAGS := \
+        -Werror \
+
+LOCAL_SHARED_LIBRARIES += \
+        libdl \
+        liblog \
+
+LOCAL_MODULE_TAGS := optional
+
+include $(BUILD_SHARED_LIBRARY)
+
+
 include $(call first-makefiles-under,$(LOCAL_PATH))
diff --git a/chromium/java/com/android/webview/chromium/WebViewChromium.java b/chromium/java/com/android/webview/chromium/WebViewChromium.java
index 7915588..38f28eb 100644
--- a/chromium/java/com/android/webview/chromium/WebViewChromium.java
+++ b/chromium/java/com/android/webview/chromium/WebViewChromium.java
@@ -2044,8 +2044,10 @@
         return new AwPrintDocumentAdapter(mAwContents.getPdfExporter(), documentName);
     }
 
+    @Override
     public void preauthorizePermission(Uri origin, long resources) {
-        // TODO: implement preauthorizePermission.
+        checkThread();
+        mAwContents.preauthorizePermission(origin, resources);
     }
 
     // AwContents.NativeGLDelegate implementation --------------------------------------
diff --git a/chromium/loader/loader.cpp b/chromium/loader/loader.cpp
new file mode 100644
index 0000000..a5e4e7f
--- /dev/null
+++ b/chromium/loader/loader.cpp
@@ -0,0 +1,250 @@
+/*
+ * Copyright (C) 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.
+ */
+
+// Uncomment for verbose logging.
+// #define LOG_NDEBUG 0
+#define LOG_TAG "webviewchromiumloader"
+
+#include <dlfcn.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+
+#include <jni.h>
+#include <android/dlext.h>
+#include <utils/Log.h>
+
+#define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
+
+namespace android {
+namespace {
+
+void* gReservedAddress = NULL;
+size_t gReservedSize = 0;
+
+jboolean DoReserveAddressSpace(const char* lib) {
+  size_t vsize = 0;
+
+  // First check for a file which explicitly specifies the virtual size needed.
+  // The file has a .so suffix so that the package manager will extract it
+  // alongside the real library.
+  static const char vsize_suffix[] = ".vsize.so";
+  char vsize_name[strlen(lib) + sizeof(vsize_suffix)];
+  strlcpy(vsize_name, lib, sizeof(vsize_name));
+  strlcat(vsize_name, vsize_suffix, sizeof(vsize_name));
+  FILE* vsize_file = fopen(vsize_name, "r");
+  if (vsize_file != NULL) {
+    fscanf(vsize_file, "%zd", &vsize);
+    fclose(vsize_file);
+  }
+
+  // If the file didn't exist or was unparseable, just stat() the library to see
+  // how big it is.
+  if (vsize == 0) {
+    struct stat libstat;
+    if (stat(lib, &libstat) != 0) {
+      ALOGE("Failed to stat %s: %s", lib, strerror(errno));
+      return JNI_FALSE;
+    }
+    // The required memory can be larger than the file on disk due to the .bss
+    // section, and an upgraded version of the library installed later may also
+    // be larger, so we need to allocate more than the size of the file.
+    vsize = libstat.st_size * 2;
+  }
+
+  void* addr = mmap(NULL, vsize, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+  if (addr == MAP_FAILED) {
+    ALOGE("Failed to reserve %zd bytes of address space for future load of %s: %s",
+          vsize, lib, strerror(errno));
+    return JNI_FALSE;
+  }
+  gReservedAddress = addr;
+  gReservedSize = vsize;
+  ALOGV("Reserved %zd bytes at %p", vsize, addr);
+  return JNI_TRUE;
+}
+
+jboolean DoCreateRelroFile(const char* lib, const char* relro) {
+  // Try to unlink the old file, since if this is being called, the old one is
+  // obsolete.
+  if (unlink(relro) != 0 && errno != ENOENT) {
+    // If something went wrong other than the file not existing, log a warning
+    // but continue anyway in the hope that we can successfully overwrite the
+    // existing file with rename() later.
+    ALOGW("Failed to unlink old file %s: %s", relro, strerror(errno));
+  }
+  static const char tmpsuffix[] = ".XXXXXX";
+  char relro_tmp[strlen(relro) + sizeof(tmpsuffix)];
+  strlcpy(relro_tmp, relro, sizeof(relro_tmp));
+  strlcat(relro_tmp, tmpsuffix, sizeof(relro_tmp));
+  int tmp_fd = TEMP_FAILURE_RETRY(mkstemp(relro_tmp));
+  if (tmp_fd == -1) {
+    ALOGE("Failed to create temporary file %s: %s", relro_tmp, strerror(errno));
+    return JNI_FALSE;
+  }
+  android_dlextinfo extinfo;
+  extinfo.flags = ANDROID_DLEXT_RESERVED_ADDRESS | ANDROID_DLEXT_WRITE_RELRO;
+  extinfo.reserved_addr = gReservedAddress;
+  extinfo.reserved_size = gReservedSize;
+  extinfo.relro_fd = tmp_fd;
+  void* handle = android_dlopen_ext(lib, RTLD_NOW, &extinfo);
+  int close_result = close(tmp_fd);
+  if (handle == NULL) {
+    ALOGE("Failed to load library %s: %s", lib, dlerror());
+    unlink(relro_tmp);
+    return JNI_FALSE;
+  }
+  if (close_result != 0 ||
+      chmod(relro_tmp, S_IRUSR | S_IRGRP | S_IROTH) != 0 ||
+      rename(relro_tmp, relro) != 0) {
+    ALOGE("Failed to update relro file %s: %s", relro, strerror(errno));
+    unlink(relro_tmp);
+    return JNI_FALSE;
+  }
+  ALOGV("Created relro file %s for library %s", relro, lib);
+  return JNI_TRUE;
+}
+
+jboolean DoLoadWithRelroFile(const char* lib, const char* relro) {
+  int relro_fd = TEMP_FAILURE_RETRY(open(relro, O_RDONLY));
+  if (relro_fd == -1) {
+    ALOGE("Failed to open relro file %s: %s", relro, strerror(errno));
+    return JNI_FALSE;
+  }
+  android_dlextinfo extinfo;
+  extinfo.flags = ANDROID_DLEXT_RESERVED_ADDRESS | ANDROID_DLEXT_USE_RELRO;
+  extinfo.reserved_addr = gReservedAddress;
+  extinfo.reserved_size = gReservedSize;
+  extinfo.relro_fd = relro_fd;
+  void* handle = android_dlopen_ext(lib, RTLD_NOW, &extinfo);
+  close(relro_fd);
+  if (handle == NULL) {
+    ALOGE("Failed to load library %s: %s", lib, dlerror());
+    return JNI_FALSE;
+  }
+  ALOGV("Loaded library %s with relro file %s", lib, relro);
+  return JNI_TRUE;
+}
+
+/******************************************************************************/
+/* JNI wrappers - handle string lifetimes and 32/64 ABI choice                */
+/******************************************************************************/
+
+jboolean ReserveAddressSpace(JNIEnv* env, jclass, jstring lib32, jstring lib64) {
+#ifdef __LP64__
+  jstring lib = lib64;
+  (void)lib32;
+#else
+  jstring lib = lib32;
+  (void)lib64;
+#endif
+  jboolean ret = JNI_FALSE;
+  const char* lib_utf8 = env->GetStringUTFChars(lib, NULL);
+  if (lib_utf8 != NULL) {
+    ret = DoReserveAddressSpace(lib_utf8);
+    env->ReleaseStringUTFChars(lib, lib_utf8);
+  }
+  return ret;
+}
+
+jboolean CreateRelroFile(JNIEnv* env, jclass, jstring lib32, jstring lib64,
+                         jstring relro32, jstring relro64) {
+#ifdef __LP64__
+  jstring lib = lib64;
+  jstring relro = relro64;
+  (void)lib32; (void)relro32;
+#else
+  jstring lib = lib32;
+  jstring relro = relro32;
+  (void)lib64; (void)relro64;
+#endif
+  jboolean ret = JNI_FALSE;
+  const char* lib_utf8 = env->GetStringUTFChars(lib, NULL);
+  if (lib_utf8 != NULL) {
+    const char* relro_utf8 = env->GetStringUTFChars(relro, NULL);
+    if (relro_utf8 != NULL) {
+      ret = DoCreateRelroFile(lib_utf8, relro_utf8);
+      env->ReleaseStringUTFChars(relro, relro_utf8);
+    }
+    env->ReleaseStringUTFChars(lib, lib_utf8);
+  }
+  return ret;
+}
+
+jboolean LoadWithRelroFile(JNIEnv* env, jclass, jstring lib32, jstring lib64,
+                           jstring relro32, jstring relro64) {
+#ifdef __LP64__
+  jstring lib = lib64;
+  jstring relro = relro64;
+  (void)lib32; (void)relro32;
+#else
+  jstring lib = lib32;
+  jstring relro = relro32;
+  (void)lib64; (void)relro64;
+#endif
+  jboolean ret = JNI_FALSE;
+  const char* lib_utf8 = env->GetStringUTFChars(lib, NULL);
+  if (lib_utf8 != NULL) {
+    const char* relro_utf8 = env->GetStringUTFChars(relro, NULL);
+    if (relro_utf8 != NULL) {
+      ret = DoLoadWithRelroFile(lib_utf8, relro_utf8);
+      env->ReleaseStringUTFChars(relro, relro_utf8);
+    }
+    env->ReleaseStringUTFChars(lib, lib_utf8);
+  }
+  return ret;
+}
+
+const char kClassName[] = "android/webkit/WebViewFactory";
+const JNINativeMethod kJniMethods[] = {
+  { "nativeReserveAddressSpace", "(Ljava/lang/String;Ljava/lang/String;)Z",
+      reinterpret_cast<void*>(ReserveAddressSpace) },
+  { "nativeCreateRelroFile",
+      "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Z",
+      reinterpret_cast<void*>(CreateRelroFile) },
+  { "nativeLoadWithRelroFile",
+      "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Z",
+      reinterpret_cast<void*>(LoadWithRelroFile) },
+};
+
+}  // namespace
+
+void RegisterWebViewFactory(JNIEnv* env) {
+  // If either of these fail, it will set an exception that will be thrown on
+  // return, so no need to handle errors here.
+  jclass clazz = env->FindClass(kClassName);
+  if (clazz) {
+    env->RegisterNatives(clazz, kJniMethods, NELEM(kJniMethods));
+  }
+}
+
+}  // namespace android
+
+JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void*) {
+  JNIEnv* env = NULL;
+  if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
+    ALOGE("GetEnv failed");
+    return JNI_ERR;
+  }
+  android::RegisterWebViewFactory(env);
+  return JNI_VERSION_1_6;
+}
diff --git a/chromium/tests/UbWebViewJankTests/Android.mk b/chromium/tests/UbWebViewJankTests/Android.mk
new file mode 100644
index 0000000..0c2d128
--- /dev/null
+++ b/chromium/tests/UbWebViewJankTests/Android.mk
@@ -0,0 +1,26 @@
+# Copyright 2014 Google Inc. All Rights Reserved.
+#
+# 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.
+
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_PACKAGE_NAME := UbWebViewJankTests
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+LOCAL_MODULE_TAGS := tests
+
+LOCAL_STATIC_JAVA_LIBRARIES := ub-uiautomator ub-janktesthelper
+
+LOCAK_SDK_VERSION := current
+
+include $(BUILD_PACKAGE)
diff --git a/chromium/tests/UbWebViewJankTests/AndroidManifest.xml b/chromium/tests/UbWebViewJankTests/AndroidManifest.xml
new file mode 100644
index 0000000..cf1adb6
--- /dev/null
+++ b/chromium/tests/UbWebViewJankTests/AndroidManifest.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.android.webview.chromium.tests.jank">
+
+    <application>
+        <uses-library android:name="android.test.runner" />
+    </application>
+
+    <instrumentation
+            android:name="android.test.InstrumentationTestRunner"
+            android:targetPackage="com.android.webview.chromium.tests.jank"
+            android:label="Chromium Jank Tests" />
+
+</manifest>
diff --git a/chromium/tests/UbWebViewJankTests/src/com/android/webview/chromium/tests/jank/WebViewFlingTest.java b/chromium/tests/UbWebViewJankTests/src/com/android/webview/chromium/tests/jank/WebViewFlingTest.java
new file mode 100644
index 0000000..efd9f27
--- /dev/null
+++ b/chromium/tests/UbWebViewJankTests/src/com/android/webview/chromium/tests/jank/WebViewFlingTest.java
@@ -0,0 +1,116 @@
+/*
+ * Copyright (C) 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 com.android.webview.chromium.tests.jank;
+
+import android.content.Intent;
+import android.net.Uri;
+import android.os.SystemClock;
+import android.support.test.jank.JankTest;
+import android.support.test.jank.JankTestBase;
+import android.support.test.jank.JankType;
+import android.support.test.uiautomator.UiDevice;
+import android.support.test.uiautomator.UiObjectNotFoundException;
+import android.support.test.uiautomator.UiScrollable;
+import android.support.test.uiautomator.UiSelector;
+
+import java.io.File;
+import java.io.IOException;
+
+/**
+ * Jank test for Android Webview.
+ *
+ * To run
+ * 1) Install the test application (com.android.webview.chromium.shell)
+ * 2) Place a directories containing the test pages on the test device in
+ *    $EXTERNAL_STORAGE/AwJankPages. Each directory should contain an index.html
+ *    file as the main file of the test page.
+ * 3) Build this test and install the resulting apk file
+ * 4) Run the test using the command:
+ *    adb shell am instrument -e Url URL -w \
+ *            com.android.webview.chromium.tests.jank/android.test.InstrumentationTestRunner
+ *
+ */
+public class WebViewFlingTest extends JankTestBase {
+
+    private static final long TEST_DELAY_TIME_MS = 2 * 1000; // 2 seconds
+    private static final long PAGE_LOAD_DELAY_TIMEOUT_MS = 10 * 1000; // 10 seconds
+    private static final long PAGE_LOAD_DELAY_TIME_MS = 20 * 1000; // 20 seconds
+    private static final int MIN_DATA_SIZE = 50;
+    private static final long DEFAULT_ANIMATION_TIME = 2 * 1000;
+    private static final String CHROMIUM_SHELL_APP = "com.android.webview.chromium.shell";
+    private static final String CHROMIUM_SHELL_ACTIVITY = CHROMIUM_SHELL_APP + ".JankActivity";
+    private static final String AW_CONTAINER = "com.android.webview.chromium.shell:id/container";
+
+    private UiDevice mDevice;
+    private UiScrollable mWebPageDisplay = null;
+
+
+    /**
+    * {@inheritDoc}
+    */
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+
+        mDevice = UiDevice.getInstance(getInstrumentation());
+        mDevice.setOrientationNatural();
+
+        // Get the URL argument
+        String url = getArguments().getString("Url");
+        File webpage = new File(url);
+        assertNotNull("No test pages", webpage);
+
+        // Launch the chromium shell
+        Intent intent = new Intent(Intent.ACTION_DEFAULT,
+                Uri.parse("file://" + webpage.getAbsolutePath()));
+        intent.setClassName(CHROMIUM_SHELL_APP, CHROMIUM_SHELL_ACTIVITY);
+        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        getInstrumentation().getContext().startActivity(intent);
+        SystemClock.sleep(PAGE_LOAD_DELAY_TIME_MS);
+    }
+
+    @Override
+    public void beforeLoop() throws UiObjectNotFoundException {
+        getContainer().flingToBeginning(20);
+        SystemClock.sleep(TEST_DELAY_TIME_MS);
+    }
+
+    @JankTest(type=JankType.CONTENT_FRAMES, expectedFrames=MIN_DATA_SIZE)
+    public void testBrowserPageFling() throws UiObjectNotFoundException, IOException {
+        getContainer().flingForward();
+        SystemClock.sleep(DEFAULT_ANIMATION_TIME);
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    protected void tearDown() throws Exception {
+        mDevice.unfreezeRotation();
+        super.tearDown();
+    }
+
+    private UiScrollable getContainer() {
+        if (mWebPageDisplay == null) {
+            mWebPageDisplay =
+                    new UiScrollable(new UiSelector().resourceId(AW_CONTAINER).instance(0));
+            assertTrue("Failed to get web container",
+                mWebPageDisplay.waitForExists(PAGE_LOAD_DELAY_TIMEOUT_MS));
+        }
+        return mWebPageDisplay;
+    }
+}